You are on page 1of 1251

Develop Rich Web Applications

with ADF 12c Essentials


Study Guide
Author: Deepak Bhagat
Fusion Functional Consultant,
Solution Architect & ADF Corporate Trainer

Free Downloadable Course material: GDrive Link


Deepak Bhagat’s Oracle ADF Blogs
Develop Rich Web Application with ADF 12c Essentials – Study Guide

Table of Contents

PART – I: Introduction and Overview

1. Overview of Fusion Middleware and ADF …………………………..….. 2


1.1. Fusion Middleware (FMW) Architecture 4
1.1.1. IT System Runtime Architecture
1.1.2. Fusion Middleware (FMW) Architecture
1.2. Model View Controller (MVC) Architecture 7
1.2.1. Client-Server Architecture
1.2.2. Model View Controller (MVC) Architecture
1.2.3. How does ADF fall in MVC architecture?
1.3. ADF MVC and Application Architecture 8
1.4. Tech-Stack of Application Development Framework (ADF) 8
1.5. Functionalities of ADF 10
1.6. Challenges Faced when Building J2EE Applications 14
1.7. Overview, Features and Key Benefits of ADF 15
1.8. Advantages of ADF over J2EE 21
1.9. Business Benefits of ADF Over Other Frameworks 25

2. Understanding Development Tool: JDeveloper …………………….. 27


2.1. Overview of Development Tool: JDeveloper 29
2.1.1. Overview of JDeveloper
2.1.2. Starting JDeveloper
2.1.3. Selecting Developer Role
2.2. Configuring Development Environment (IDE) Preferences 35
2.3. Exploring and Working with Windows of JDeveloper 36
2.4. Building an ADF Application, Project and Database Connection 48
2.5. Refactoring JDeveloper Artifacts 54
2.6. Advantages of JDeveloper 55

3. Modeling Database Schema ……………………………………………… 60


3.1. Discussing HR System ER Diagram 62
3.2. Examining Training Hands-on Lab Application – Lab Solution 22 63
3.3. ADF Business Rules in PL/SQL 78
3.4. Controlling Entity Posting Order 80

i
ADF training by Deepak Bhagat
Develop Rich Web Application with ADF 12c Essentials – Study Guide

PART – II: ADF Business Components


4. Building Business Service with ADF Business Components ……... 82
4.1. Tech-stack of ADF Business Components (BC) 85
4.2. Types of Objects of ADF Business Components 86
4.2.1. Understanding Entity Objects
4.2.2. Understanding View Objects
4.2.3. Understanding Application Module
4.3. Functionality of ADF Business Components 88
4.4. Creating and Examining ADF Business Components 89
4.5. Examining Configuration Files of ADF Business Components 92
4.6. Testing with ADF Model Tester 96
4.7. Exposing ADF Business Components as Business Service 108

5. Persisting Data using Entity Objects ………………………………… 110


5.1. Tech-stack of Entity Objects (EO) 112
5.2. Persisting Data using Entity Objects 113
5.3. Entity Objects Attribute Mapping 114
5.4. Creating Entity Objects from Tables, Views or Synonyms 118
5.5. Examining Entity Objects and their Attributes 119
5.6. Synchronizing an EO with Table Structure Changes 128
5.7. Entity Association Types 130

6. Querying Data using View Objects …………………………………… 134


6.1. Tech-stack of View Objects (VO) 136
6.2. Types of View Objects 139
6.3. Read Only View Objects based on SQL Query 140
6.4. Updatable View Objects based on Single Entity Objects 145
6.5. Join View Objects based on Multiple Entity Objects 150
6.5.1. Join View Objects based on Referenced Entity Objects
6.5.2. Join View Objects based on Updatable Entity Objects
6.6. Internationalization of Business Services 182
6.7. Read Only View Objects based on Static List 183
6.8. Features of View Objects 186
6.9. Examining Attribute Settings 187
6.10. Master-Detail relationships using View Links 195
6.11. Compare Join View Objects and View Links 200
6.12. Testing View Objects with ADF Model Tester 201
ii
ADF training by Deepak Bhagat
Develop Rich Web Application with ADF 12c Essentials – Study Guide

7. Exposing Business Service through Application Module ……….. 203


7.1. Tech-stack of Application Module (AM) 205
7.2. Ingredients of an AM 206
7.3. Features of AM 208
7.4. Simple and Complex Application Module Data Model 210
7.5. Managing ADF Business Components Transaction by AM 214
7.6. Nested Application Module 215
7.7. Shared Application Module 218
7.8. Application Module Pooling 219
7.9. Handling Application State 221
7.10. Exposing Business Services with ADF Model 224
7.11. Estimating the Size of an Application Module 225
7.12. Creating and Examining an Application Module and Nested AM 226

8. Declaratively Customizing Business Services ………..……………. 228


8.1. Introducing and Using Groovy in ADF 230
8.1.1. Introducing Groovy
8.1.2. Groovy Syntax in ADF
8.1.3. References for Groovy
8.2. Customizing Entity Object’s Default Behavior 237
8.2.1. Customize Attribute Control Hints
8.2.2. Alternate Key Entity Constraints
8.2.3. Synchronize Columns with DBSequence
8.3. Customizing View Object’s Default Behavior 245
8.3.1. Customizing Attribute Control Hints
8.3.2. Performing Calculations: Add Transient Attribute
8.3.3. Projection: Restricting the Columns Retrieved by a Query
8.3.4. Sorting: Reordering Using ORDER BY Clause
8.3.5. Selection: Using WHERE Clause to Restrict the Rows
8.3.6. Selection: Using Parameterized WHERE Clause
8.3.7. Selection: Using Structured Where Clause: View Criteria
8.3.8. Selection: Role of View Criteria in Search
8.3.9. Defining View Accessors (LOV)
8.3.10. Using a List of Values (LOV)
8.3.11. Retaining and Reusing a View Link Accessor Row Set
8.4. Customizing Application Module’s Default Behavior 256
8.4.1. Modifying the Locking Behavior of an Application Module

iii
ADF training by Deepak Bhagat
Develop Rich Web Application with ADF 12c Essentials – Study Guide

9. Validating Business Services …………………………………............ 260


9.1. Validation Options for ADF Business Component Applications 262
9.2. Categories of Validations in ADF Business Components 263
9.3. Declarative Validation: Built-in Rules 266
9.3.1. Collection Validator
9.3.2. Unique Key Validator
9.3.3. Compare Validator
9.3.4. Key Exists Validator
9.3.5. Length Validator
9.3.6. List Validator
9.3.7. Range Validator
9.3.8. Regular Expression Validator
9.3.9. Script Expression Validator
9.4. Declarative Validation: Custom Rules: Method Validator 283
9.5. Programmatic Validation: Global Rules 285
9.6. Global Validation Rule: Creating, Examining and Modifying 287
9.7. Domains: Pre-validated Custom Datatypes 290
9.8. Triggering Validation Execution 294
9.9. Failure Handling with Error Message 296
9.10. Supporting Groovy Expressions for Validations 300
9.11. Key Guidelines for using Validation 301

PART – III: ADF Faces

10. Introducing User Interface Technologies ………………………….. 303


10.1. Evolution of J2EE Web UIs 305
10.2. JSF vs. Traditional JSP 312
10.3. Tech-Stack of JSF 315
10.4. Functionalities/ Concepts of JSF 319
10.5. JSF Functionality: JSF Components 321
10.5.1. Components: Tag Libraries
10.5.2. Components: Renderer Kits
10.5.3. Components: Renderers
10.6. JSF Functionality: Navigation using JSF Controller 330
10.7. JSF Functionality: Managed Beans 334
10.8. JSF Functionality: JSF Life Cycle 336
10.9. Features of JSF 340

iv
ADF training by Deepak Bhagat
Develop Rich Web Application with ADF 12c Essentials – Study Guide
10.10. Key Characteristics of Rich Web UIs 344
10.11. Tech-Stack of ADF Faces 346
10.12. Functionalities of ADF Faces 351
10.13. ADF Faces Functionality: ADF Faces Components 353
10.14. ADF Faces Functionality: Navigation using ADF Controller 360
10.15. ADF Faces Functionality: ADF Faces Life Cycle 362
10.16. Features of ADF Faces 366

11. Getting Started with Rich User Interface …………………............ 371


11.1. Internationalization of an Application using Resource Bundles 374
11.2. Customizing look and feel using ADF Faces Skins 381
11.3. Adding User Interface (UI) Components to the Page 383
11.4. Using of Component Facets 384
11.5. Default Configuration Files 386

12. Planning Pages using Layout Components ………………………… 391


12.1. Overview of Layout Components 396
12.2. Geometry Management, Stretching, Functionalities and Guidelines 422
12.3. Adding and Customizing Layout Components 440
12.4. Performance Impacts 479
12.5. Dynamic Layouts 480

13. Designing User Interfaces and Page Flows ………………………… 482


13.1. Features and Functionalities of ADF Task Flows 486
13.1.1. Features of ADF Task Flows
13.1.2. Additional Functionalities of ADF Task Flows
13.1.3. Features of Unbounded Task Flows
13.1.4. Implementing Unbounded Task Flows
13.1.5. Features of Bounded Task Flows
13.2. Comparing Unbounded and Bounded Task Flows 492
13.3. Types of Task Flow Activities and Components 493
13.4. Using Task Flow Activities 497
13.4.1. Using View Activities as Fragments
13.4.2. Using Method Call Activities
13.4.3. Using Task Flow Call Activities
13.4.4. Using Task Flow Return Activities
13.4.5. Using Router Activities
13.4.6. Using Wildcard Control Flow Activities

v
ADF training by Deepak Bhagat
Develop Rich Web Application with ADF 12c Essentials – Study Guide
13.4.7. Using Control Flow Case Activities
13.4.8. Using URL View Activities
13.4.9. Using Parent Action Activities
13.4.10. Using Save Point Restore Activities
13.5. Exception Handling in Task Flows 507
13.6. ADF Regions: Static and Dynamic 508
13.7. Creating and Using Bounded Task Flow and Fragments 509
13.8. Extracting and Converting Task Flow 518
13.8.1. Extracting a Task Flow
13.8.2. Converting Task Flow to use Page Fragment
13.8.3. Converting to Unbound Task Flow

14. Interactively Controlling with Navigation Components ………… 515


14.1. Overview of Navigation Components 519
14.2. Using Buttons and Links 520
14.3. Using BreadCrumbs and Navigation Panes 522
14.3.1. Using Explicitly Defined Breadcrumbs
14.3.2. Using Navigation Pane
14.4. Using Train Component 526
14.4.1. Defining Sequence of Steps
14.4.2. Skipping Train Stop
14.5. Menu and Toolbar Explorer-type Containers for Navigation 528
14.5.1. Using Menus for Navigation
14.5.2. Printable Page Behavior
14.5.3. Using Toolbar, Toolbar Buttons and Toolboxes
14.6. Creating and Using Secondary Window Layout (Popup) 536
14.6.1. Creating Pop-up Menus
14.6.2. Creating Context Menus
14.7. Performing Navigation 541
14.7.1. JSF Navigation Rules in JDeveloper
14.7.2. JSF Navigation
14.7.3. How Navigation Targets are Determined
14.7.4. Programmatic Navigation
14.7.5. Conditional Navigation
14.7.6. Performing Navigation in ADF
14.8. Accessibility, Access Key and Tool Tip 549
14.8.1. Accessibility
14.8.2. Using Access Key

vi
ADF training by Deepak Bhagat
Develop Rich Web Application with ADF 12c Essentials – Study Guide
15. Ensuring Reusability in Web Applications ………………………… 552
15.1. Benefits of Reusability 555
15.2. Designing for Reuse 556
15.3. Types of Reusable Components 557
15.4. Using Resource Catalog and ADF Library 559
15.4.1. Using a Resource Catalog
15.4.2. Creating a Catalog and Adding Resource to a Catalog
15.4.3. Reusing Components through ADF Library
15.4.4. Removing an ADF Library from Project
15.4.5. Restricting BC Visibility in Libraries
15.5. Using Task Flow as Regions 565
15.6. Creating and Using Page Fragments 574
15.6.1. Features of Page Fragment
15.6.2. Using a Page Fragment on a Page
15.7. Creating and Using Page Template 577
15.7.1. Contents in Page Template
15.7.2. Page Template Codes
15.7.3. Page Templates and Databinding
15.7.4. Example: Page Template
15.8. Creating and Using Task Flow Templates 586
15.9. Creating and Using Declarative Components 588
15.10. Deciding Which Reusable Component to Use 593

16. Working with Scopes, Parameters and Partial Page Refresh …. 595
16.1. Using Memory Scopes 600
16.1.1. Using Memory Scope Attributes
16.1.2. Memory Scope Duration with a Called Task Flow
16.1.3. Memory Scope Duration with a Region
16.1.4. Accessing Memory Scoped Attribute Values
16.2. Defining Page, Task Flow and Region Parameters 606
16.2.1. Overview of Parameters
16.2.2. Task Flow– Using Parameters, Passing & Returning Value
16.2.3. Passing a Value to a Region
16.2.4. Deciding the Usage of Parameter
16.3. Partial Page Rendering 619
16.3.1. Partial Page Rendering Attributes
16.3.2. Conditional Rendering
16.3.3. Enabling Automatic PPR
vii
ADF training by Deepak Bhagat
Develop Rich Web Application with ADF 12c Essentials – Study Guide
17. Responding to Managed Beans, Events and Listeners ………….. 630
17.1. Using Managed Beans 633
17.1.1. Adding UI Code
17.1.2. Registering Existing Java Classes as Managed Beans
17.1.3. Configuring Managed Beans
17.1.4. Referencing Managed Beans
17.1.5. Holding Values in Managed Beans
17.1.6. Using Managed Bean Properties
17.1.7. About Managed Properties
17.1.8. About Backing Bean
17.1.9. Creating Managed Beans
17.2. Describing Types of Events and Listeners 647
17.2.1. Demonstrating Events and Listeners
17.2.2. Describing Types of Events
17.2.3. Other ADF Faces Server Events
17.2.4. Describing Types of Event Listeners
17.2.5. Responding to Action Events
17.2.6. Action Listeners in Code
17.2.7. Creating Action Methods
17.2.8. Action Listeners Vs Action Methods
17.2.9. Responding to Value Change Events
17.2.10. Creating Value Change Listeners
17.2.11. Using Value Change Listeners
17.2.12. Event and Listener Execution Order
17.3. Enabling PPR Programmatically 665
17.4. Overview of Contextual Events 666
17.5. Understanding Life Cycle 669
17.5.1. JSF Life Cycle Phases
17.5.2. ADF Life Cycle Phases
17.5.3. JSF and ADF Life Cycle Phases Events
17.5.4. Phase Identifiers
17.5.5. Phase Listener
17.6. Creating ADF Faces Validation 692
17.6.1. Validation
17.6.2. Validation Approaches
17.6.3. Manual Validation
17.6.4. Implicit Automatic Validation
17.6.5. Explicit Automatic Validation
viii
ADF training by Deepak Bhagat
Develop Rich Web Application with ADF 12c Essentials – Study Guide
17.6.6. Example of Explicit Validation
17.6.7. Creating Custom Validation Method
17.6.8. Custom Validation Components
17.6.9. UI Validation
17.6.10. Input Validation
17.6.11. Additional ADF Faces Validators
17.6.12. Backing Bean Validation
17.7. Creating ADF Faces Convertors 705
17.7.1. JSF Conversion
17.7.2. About Convertors
17.7.3. ADF Faces Convertors
17.7.4. Custom Convertors

18. Binding Model Layer with Business Services ………………………. 712


18.1. Dragging and Dropping Data Bindings 714
18.2. Text and Selection Components 718
18.3. Data Views Components 749
18.4. Data Visualization Components 762
18.5. AJAX with PPR 768

19. Querying Data with Search Components …………………………… 773


19.1. Query Search Component 777
19.2. Quick Query Component 780

20. Implementing Transactions ……………………………………………. 784


20.1. Handling Transactions with ADF Business Components 787
20.1.1. Default ADF Model Transactions
20.1.2. Operations
20.2. Sharing Data Controls 790
20.3. Designating an Exception Handler Activity 793
20.4. Saving for Later 795
20.4.1. Transaction Support Features of Bounded Task Flows
20.4.2. Enabling Explicit Save for Later
20.4.3. Enabling Implicit Save for Later
20.4.4. Restoring Save Points
20.4.5. Setting Global Save for Later Properties
20.5. Implement CRUD Operations 801
20.6. Defining Response to the Back Button 802

ix
ADF training by Deepak Bhagat
Develop Rich Web Application with ADF 12c Essentials – Study Guide
21. Understanding Data Controls and Bindings ……………………….. 804
21.1. Describing the ADF Model Layer 812
21.1.1. ADF Binding Layer
21.1.2. Types of Data Controls
21.1.3. Types of Bindings
21.1.4. Types of Bindings: Source View
21.2. ADF Configuration and Metadata Files 820
21.2.1. ADF Binding Control: Run Time
21.2.2. ADF Binding Control: File Hierarchy
21.3. ADF Region Architecture 825
21.4. ADF Binding Validation 828
21.5. ADF Binding Using Expression Language (EL) 830
21.5.1. Expression Language and Bindings
21.5.2. Using Expression Language
21.6. Programmatic Expression Language 835
21.6.1. Class Files in Programmatic Approach
21.6.2. ADF Binding Class Hierarchy
21.6.3. Programmatic Approach of Binding
21.6.4. JUCtrlActionBinding
21.6.5. Specify When to Refresh Binding Executables
21.6.6. Specify Whether to Refresh Binding Executables

PART – IV: Advance ADF

22. Programmatically Customizing Business Services ……………….. 851


22.1. Types of programmatic customization of ADF Business Component 853
22.2. Using ADF Business Component APIs 854
22.2.1. Class Diagram of ADF Business Components
22.2.2. File Structure of ADF Business Components
22.3. Programmatically Customizing Entity Object (EO) 861
22.3.1. Default Metadata
22.3.2. Generating Entity Java Classes
22.3.3. Customizing Default Behavior: Business Rule
22.3.4. Business Rule: Method Validation
22.3.5. Customizing Default Behavior: Override Methods
22.3.6. Assigning Primary Key using a Database Sequence
22.3.7. Updating Deleted Flag Instead of Deleting Rows

x
ADF training by Deepak Bhagat
Develop Rich Web Application with ADF 12c Essentials – Study Guide

22.3.8. Programmatic Operations on EO: Placements


22.3.9. Programmatic Operations on EO: CRUD Operations
22.3.10. Reading EO: Find by Primary Key
22.3.11. Traverse Association: Iterate Master to Detail Hierarchy
22.3.12. Traverse Association: Iterate Detail to Master Hierarchy
22.3.13. Reading EO: Find EO through View Object
22.3.14. Updating an Existing EO Row
22.3.15. Deleting an Existing EO Row
22.3.16. Creating a New EO Row
22.4. Programmatically Customizing View Object (VO) 890
22.4.1. Default Metadata
22.4.2. Generating View Object Java Classes
22.4.3. Customizing Default Behavior: Business Rule
22.4.4. Customizing Default Behavior: Override Methods
22.4.5. Customizing Default Behavior: Examine VO Methods
22.4.6. Programmatic Operations on VO: Placements
22.4.7. Programmatic Operations on VO: CRUD Operations
22.4.8. Reading VO: Find by Key and Update
22.4.9. Reading VO: Traverse Links
22.4.10. Traverse Links: Iterate Master-Detail Hierarchy
22.4.11. Retain and Reuse a View Link Accessor Row Set
22.4.12. Creating a New VO Row
22.4.13. Programmatic Customization of Sorting and Selection
22.4.14. Change WHERE or ORDER BY Clause at Run Time
22.5. Programmatically Customizing Application Module (AM) 930
22.5.1. Default Metadata
22.5.2. Generating Application Module Java Classes
22.5.3. Adding Service Methods to an Application Module
22.5.4. Implement the Service Method
22.5.5. Publishing the Service Method
22.5.6. Testing Services using ADF Model Tester
22.5.7. Accessing Transaction
22.5.8. Committing Transactions
22.5.9. Customizing the Post Phase
22.5.10. Customizing the Commit Phase
22.6. Implementing Java Client for Testing 956
22.6.1. Creating a Test Client

xi
ADF training by Deepak Bhagat
Develop Rich Web Application with ADF 12c Essentials – Study Guide

23. Deploying ADF Applications ……………………………………………. 964


23.1. Building Source Code 968
23.2. Pre Build: Deployment Profiles 972
23.3. Build Tools and Options 984
23.4. Dependency Management 992
23.5. Building and Deploying 995
23.6. Continuous Integration 997

24. Securing ADF Applications ……………………………………………. 1003


24.1. Authentication and Authorization 1005
24.2. Understanding ADF Security Framework 1006
24.3. ADF Security Architecture 1007
24.4. Oracle Platform Security Service (OPSS) 1008
24.5. OPSS Files 1009

25. Debugging and Troubleshooting ADF Applications …………….. 1011


25.1. Troubleshooting the Business Service 1013
25.1.1. ADF Model Tester
25.1.2. Java Test Clients
25.1.3. Unit Test with JUnit
25.2. Troubleshooting the User Interface 1016
25.3. Using Design-Time Code Validation 1017
25.4. Using Diagnostics and Logging using Java and ADF Logger 1019
25.5. Running in Debug Mode 1027
25.6. Using Tools and Utilities 1045
25.7. Obtaining Help 1049

26. ADF Best Practices ……………………………………………………… 1053


26.1. Tuning Tips for Entity Objects 1055
26.2. Tuning Tips for View Objects 1056
26.3. Tuning Tips for Associations and View Links 1057
26.4. Tuning Tips for Application Modules 1058
26.5. Tuning Tips for ADF Model 1059
26.6. Tuning Tips for Pages 1060
26.7. Tuning Tips for Layouts 1061
26.8. Tuning Tips for Task Flows and Memory Scopes 1063
26.9. Designing for Reuse 1064

xii
ADF training by Deepak Bhagat
Develop Rich Web Application with ADF 12c Essentials – Study Guide

27. Miscellaneous Topics …………………………………………………... 1070


27.1. ADF 12c New Features 1072
27.2. Sample Projects 1099

28. Advance ADF Topics ……………………………………………………. 1101


28.1. Adding Custom View Criteria 1104
28.2. Publishing and Subscribing Contextual Events 1105
28.2.1. Characteristics
28.2.2. Overview
28.2.3. Coordinate Page Regions
28.3. Active Data Service Framework 1120

PART – V: Integrating ADF

29. Integrating ADF with Web Service ………………………………… 1122


29.1. Types of ADF Integrations with Web Service 1126
29.2. What is Web Service 1129
29.3. Types of Web Service 1130
29.4. REST Vs SOAP 1131
29.5. Creating SOAP Web Service with ADF Business Service 1144
29.6. Build REST Web Service with ADF Business Service 1146
29.7. ADF Mobile REST Data Control 1162

30. Integrating ADF with EJB …………………………………………….. 1164

31. Integrating ADF with SOA ……………………………………………. 1168

32. Integrating ADF with MAF ……………………………………………. 1176

33. Integrating ADF with Oracle Cloud Service ……………………… 1200

34. Integrating ADF with WebCenter …………………………………… 1210

xiii
ADF training by Deepak Bhagat
1
2
Lesson Agenda
This lesson gives you an overview of Fusion Middleware architecture and components. It
introduces you to the essential concepts and structure of ADF and explain how it fits into the
Fusion architecture.

Here, you would setup training hands-on lab practices environment. These consists of:
1. System Requirements for ADF Training
2. Oracle Technology Resource Account Login
3. Downloading and Installing Oracle XE Database
4. Downloading and Installing JDeveloper
5. Unlocking HR Schema
6. Entity Relation Diagram of HR System
7. Working with JDev IDE Configuration Files
8. Java for Beginners
9. References
10. Grouping of Hands-on Lab Practices
11. Important Abbreviation and Information
12. Downloading Training Materials

3
Components of Oracle Fusion Architecture
Oracle Fusion Middleware is a standards-based family of products that are often deployed and used in
conjunction with one another to develop Java Platform, Enterprise Edition (Java EE) applications,
providing the benefits of common security, management, deployment architecture, and development
tools.
Oracle Fusion Middleware’s architecture enables you to leverage your investments in any existing
application, system, or technology.
Oracle Fusion Middleware includes the following best-of-breed technologies:
• Oracle BPEL Process Manager: A native Business Process Execution Language (BPEL) engine
for Web service orchestration, enabling you to design, define, and execute business processes
• Oracle Web Services Manager: A console to secure and manage your Web services
• Oracle Business Rules Engine: A product to enable agile management of business rules
• Oracle Enterprise Service Bus: A standards-based product that connects existing IT systems and
business partners as a set of services, and supports event-driven architectures
• Oracle Business Activity Monitoring: A product to report insight into business operations
• Oracle Services Registry: A Universal Description, Discovery and Integration (UDDI) v3–
compliant registry
• Oracle JDeveloper: An integrated development environment for creating and composing
applications in a unified toolset for all Oracle Fusion Middleware tools. Not only can you use
Oracle JDeveloper to build applications, but Oracle developers use JDeveloper to build the other
tools.

4
Components of Oracle Fusion Architecture
Oracle Fusion Middleware is a standards-based family of products that are often deployed and used in
conjunction with one another to develop Java Platform, Enterprise Edition (Java EE) applications,
providing the benefits of common security, management, deployment architecture, and development
tools.
Oracle Fusion Middleware’s architecture enables you to leverage your investments in any existing
application, system, or technology.
Oracle Fusion Middleware includes the following best-of-breed technologies:
• Oracle BPEL Process Manager: A native Business Process Execution Language (BPEL) engine
for Web service orchestration, enabling you to design, define, and execute business processes
• Oracle Web Services Manager: A console to secure and manage your Web services
• Oracle Business Rules Engine: A product to enable agile management of business rules
• Oracle Enterprise Service Bus: A standards-based product that connects existing IT systems and
business partners as a set of services, and supports event-driven architectures
• Oracle Business Activity Monitoring: A product to report insight into business operations
• Oracle Services Registry: A Universal Description, Discovery and Integration (UDDI) v3–
compliant registry
• Oracle JDeveloper: An integrated development environment for creating and composing
applications in a unified toolset for all Oracle Fusion Middleware tools. Not only can you use
Oracle JDeveloper to build applications, but Oracle developers use JDeveloper to build the other
tools.

5
.
6
.
Model-View-Controller Design Pattern
A good practice when developing applications is to employ design patterns. Design patterns are
a convenient way of reusing object-oriented concepts between applications and developers.
The idea behind design patterns is simple: document and catalogue common behaviour
patterns between objects. Developers can then make use of these patterns rather than re-
create them. One of the frequently used design patterns is the Model-View-Controller (MVC)
pattern.
In the MVC pattern, the user input, the business logic, and the visual feedback to the user are
explicitly separated and handled by three types of objects. Each of these objects is specialised
for a particular role in the application:
• The model manages the data of the application domain, responds to requests for
information about its state (usually from the view), and responds to instructions to change
state (usually from the controller).
• The view manages the presentation of the application output to the user.
• The controller interprets the mouse and keyboard inputs from the user, commanding the
model and/or the view to change as appropriate.

7
.
Technology Choices for ADF BC Applications
In this course, you employ the MVC architecture through the use of Oracle ADF and JavaServer
Faces:
• Business Services: ADF Business Components (ADF BC) provides the business services
that are responsible for representing database tables and persisting user input values to the
database.
• Model: ADF data binding is accomplished in compliance with JSR-227, a standard data
binding and data access facility for Java EE that provides a standard for interactions
between UI components and methods available on the business services. With this standard
data binding, any Java UI–rendering technology can declaratively bind to any business
service.
• Controller: The ADF Controller is used to manage page flow and UI input processing.
• View: JavaServer Faces and ADF Faces provide render kits that enable the UI components
defined by JavaServer Faces or ADF Faces to be rendered differently on different devices.
For example, the UI can be rendered on a computer’s browser or on a mobile device such
as a cell phone or PDA.
• Metadata Service: ADF BC applications can also use Metadata Service (MDS) for
customization and personalisation. This is outside the scope of this course.

8
.
9
.
10
.
11
.
12
.
13
.
14
.
Overview of Application Development Framework (ADF)
Oracle ADF is an end-to-end application framework that builds on Java EE standards and open-
source technologies to simplify and accelerate implementing Java EE applications. It is fully
extensible and customizable by adding or modifying libraries.
ADF simplifies the tasks of:
• Creating business services
• Designing user interfaces to access those services
Oracle ADF simplifies Java EE development by minimizing the need to write code that
implements design patterns and the application infrastructure. These implementations are
provided as part of the framework. Oracle ADF also provides a visual and declarative
development experience that minimizes the need to write code and reduces the learning curve
for 4GL developers.
Business services are implemented as metadata, enabling them to be bound to user interfaces
in the same manner regardless of the technology employed in the underlying data model. The
use of metadata also enables business rules for databound fields to be specified at the model
layer, along with labels, validation, and tool tip properties

15
.
How the Oracle ADF Framework Implements MVC
In addition to design patterns, developers often use architectural frameworks to build
applications that perform in a standard way. ADF is such a framework, and it implements the
MVC design pattern as follows:
• Business Services: Business services provide the back-end data model that interacts with
the data source. It may be a set of Java classes or Web services, or can be Enterprise
JavaBeans (EJBs), TopLink, or ADF Business Components.
• Model: ADF data binding is accomplished in compliance with JSR-227, a data binding
and data access facility for Java EE that provides a standard for interactions between UI
components and methods available on the business services. With this standard data
binding, any Java UI–rendering technology can declaratively bind to any business service.
• Controller: Page flow and UI input processing can be implemented in Struts,
JavaServer Faces (JSF), or ADF Controller. The ADF Controller enables you to define task
flows, encompassing more than just page flow. The ADF Controller is explained in detail
in the lesson titled “Planning the User Interface.”
• View: The user interface can be a rich client with ADF Swing components, or can use Java
ServerFaces and ADF Faces components.

16
.
17
.
18
.
19
.
20
.
21
.
22
.
23
.
24
.
25
.
26
.
27
.
Lesson Agenda
This lesson introduces you to the JDeveloper IDE. You learn about the features and benefits of
JDeveloper and how to use its components in application development. You set preferences for
the tool, create an application and project, and create a database connection.

In Hands-on lab you would practice:


1 Creating a New Fusion Application and Project
2 Creating a New Database Connection and Initialize the Project
3 Adding ADF Business Components and ADF Faces
4 Exploring JDeveloper and New Application
5 Exploring Windows of JDeveloper
6 Working with Windows
7 Taking Help using F1 key
8 Refactoring JDeveloper Artifacts
9 Setting IDE Preferences
10 Setting Package Levels

28
.
Overview of Development Tool: JDeveloper
Oracle JDeveloper 12c is a comprehensive development tool that provides facilities to build
Web applications using a common development tool set. This tool has evolved to provide an
integrated environment that enables a developer to design, develop, troubleshoot, optimize,
and deploy Java EE applications. JDeveloper is the integrated development environment (IDE)
that utilizes the Application Development Framework

29
.
30
.
31
.
32
.
Launch JDeveloper
You can launch JDeveloper in one of the following ways:
• Selecting Start > All Programs > Oracle > Oracle Home > Oracle JDeveloper Studio > Oracle
JDeveloper Studio (or a different location as specified in the Installer)
• By double-clicking the JDeveloper executable in the home directory of the JDeveloper
installation
• From the command line or a shortcut with the following command:
<JDev Home>\jdev\bin\jdev.exe
By default, JDeveloper’s user directory is the \system subdirectory of the <JDev_Home>
directory, such as C:\Oracle\Middleware\jdeveloper\system—that is, where it
stores user preferences, such as information about the appearance of the IDE. If you want to
use a different directory, start JDeveloper with the –J-Dide.user.dir flag. The following
example sets the user directory to a directory where the user customarily stores data:
c:\JDev\jdev\bin\jdev.exe –J-Dide.user.dir=c:\Data\JDev.
Note: As an alternative to using this flag, you can set the JDEV_USER_DIR environment
variable in your operating system.
Another flag that you can use when launching JDeveloper is –noreopen, which prevents
JDeveloper from opening all the editor windows that were open the last time you closed
JDeveloper. This can improve JDeveloper’s startup time.

33
.
Select a Developer Role
To begin working in JDeveloper, you need to select a role to use. You then define an application
with one or more projects. If your application requires data from a database, you also need to
create a reusable database connection.
Roles and Shaping: When you start JDeveloper for the first time, you are asked to choose the
role that you as a developer want to use. You can change that role later, if desired, by selecting
Tools > Preferences from the JDeveloper menu.
The JDeveloper environment customizes itself based on the role of the user by removing items
that are not needed from the menus, preferences, new gallery, and even individual fields in
dialog boxes. This is called shaping, and it can even control the default values for fields in dialog
boxes within the tool.

34
.
Set Development Environment (IDE) Preferences
There are many preferences that you can set to affect the display and functionality of the IDE.
You access the Preferences window by selecting Tools > Preferences.
For example, to change the default naming scheme for ADF Business Components objects, you
expand the Business Components node in the Preferences window and select Object Naming.
You can specify a suffix for each type of object.

35
.
Features of JDeveloper
The next few slides provide an overview of using the features that are listed in this slide.

36
.
37
.
Application Window
The Application Navigator presents you with a hierarchical view of all the elements in your
application. At the top of the Application Navigator is a drop-down list of applications that also
enables you to open an application or create a new one. To the right of the drop-down list is an
arrow that displays the application menu, enabling you to select actions pertaining to the current
application.
The Application Navigator contains four panels:
• Projects: Shows all the projects that are part of the current application, along with a
hierarchical view of the project elements. The project panel contains a toolbar that enables
you to display project properties, refresh, filter, or rearrange the display.
• Application Resources: Shows application-level resources such as descriptors and
connections
• Data Controls: Provides a hierarchical view of all the data elements, such as view objects
and methods, that are available to access in the user interface. It enables you to use the
drag-and-drop functionality to create UI components on a page. It also contains a toolbar
that allows you to refresh and filter the display.
• Recently Opened Files: Provides quick access to files in the current application that have
recently been used
You can expand, collapse, minimise, and restore each of these four panels in the Application
Navigator:
• To expand or collapse, click the arrow to the left of the panel name.
• To minimise, select Minimise from the drop-down menu at the right of the panel’s title
bar.
• To restore, click the ellipsis at the bottom right of the Application Navigator and select the
minimised panel that you want to restore.

38
.
Database Window
The Database Navigator provides you with a complete editing environment for online
databases.
You can use it to create, update, and delete database objects. Much of the functionality
available standalone in SQL Developer is also available in JDeveloper. Highlights include:
• SQL Worksheet: Script execution, explain plan, autotrace, code snippets (drag and drop),
DBMS, and OWA output
• Creation of external, index organized, temporary, partitioned (range, hash, and list) tables
and materialized views
• Extensive context menu options to modify objects (for example, table rename, column
additions, compilation, index rebuilds, and database link testing)
• Browse, query, update, delete, sort, and filter data including CLOB and BLOB and
tracking of changes through message log
• Export data in multiple formats, export DDL, import data
• Database reports

39
.
Structure Window
The Structure window is displayed by default below the Application Navigator. If it is not visible,
select View > Structure to display it.
When you select anything in a navigator, editor, or the Property Inspector, the Structure
window displays the elements of the selected document in a tree format. For example, when
you select a availavle source file, the classes, interfaces, methods, and variables are displayed,
and you can sort and view them in a variety of ways. You can use the Structure window to
quickly locate and navigate to specific areas of code in your Java source files and to browse the
class hierarchy. When you are designing a user interface with the visual editor, the Structure
window displays the components of the UI and their associated event-handling methods in a
hierarchical tree format. The Structure window enables you to create new components in
precisely the desired location, whereas such precise placement is often difficult in the visual
editor. You can open as many new instances of the Structure window as you would like. New
instances will automatically track the active selection in the active view unless frozen. You can
freeze and unfreeze the selection in the window by clicking Freeze View. You can click the New
View icon to open a new instance of the Structure window that appears docked with the
existing window or windows.

40
.
Using the Editors
JDeveloper provides a variety of editors with which you can:
• Edit code: To edit source code, double-click the file in the Application Navigator to display the contents in the appropriate
editor. Highlights of the code editor include the following:
- Toolbar: Enables quick access to functions such as generate accessors, surround with, override method/implementation
interface, reformat, and so on
- Auto Code Highlight: Automatically highlights instances of a selected item
- Syntax color options: Makes code easily readable
- Quick Javadoc
- Code folding: Enables you to expand and contract sections of code
- Show Whitespace Characters: Renders spaces, new lines, carriage returns, nonbreaking spaces, and tab characters as
alternate visible characters
- Overview Popup: Enables you to view the source at an overview mark by simply
hovering the cursor over the mark
- Structure Window Popup: View the source for a method by pressing Ctrl while the cursor is over the desired method in the
Structure window.
Quick Outline: Provides a new method to quickly navigate to methods and fields of a class and its superclasses. The “ghost”
window floats just above the code and contains a tree of the available methods and fields of the current class and its
superclasses. Start typing in a filter field to reduce the visible items, allowing quick and easy selection for navigation to the
desired place.
- Code Peek: Provides the ability to view code in different files without navigating or opening new editors
- Last Change Indicator: Provides a marker in the left gutter of code editors provides a quick visual indicator of changes to a file
since the last save
• Edit properties: Many editors for components are modeless editors that appear in the editor area along with the other
editors. They can remain open to enable easy access to component editors while you work on other parts of the application.
• Edit Visually
- Page Flows: Toolbar enables quick access for modifying the display and marking default activities and exception handlers.
- Diagrammers: The internal diagramming framework used to build the UML tools in JDeveloper, the Page Flow diagrams, and
other visual editors has been re-architected to be more flexible for internal consumers. The result for end users is more
consistent behavior between the different diagrams.
- Pages: The breadcrumb bar in the page editor shows the hierarchy of nodes from the current caret position up to the top of
the file. Placing the cursor over a node displays some information about the node and clicking the node navigates the caret to
the node location.

41
.
Log Window
The Log window in JDeveloper enables you to view output from JDeveloper operations such as
running, debugging, and profiling. The Log window consists of a Messages tab and optionally,
additional tabs for displaying results.
The context menu of a log window enables you to select, copy, or save text, clear the text, wrap
the entries, find a specified string in the text, or close a tab. There are other context menu
options depending on the type of log window displayed on a tab. You can also close individual
tabs by clicking the X that appears on the tab when you move the cursor over it, and you can
close all log windows by clicking the X on the top tab. If you close all log windows, you can
reopen them by selecting View > Log from the main menu.

42
.
Components Window
When you are using any type of visual editor, the Component Palette displays the components
that are available to drag to the editor.
The Component Palette features are as follows:
•A drop-down list at the top of the palette enables you to select the component
category to display.
•Collapsible panels and divider sections can be used to organize related components.
•A quick search field helps you to locate components.
You can add commonly used components to your Favorites list for easier access later, and
another panel keeps track of your recently used components.

43
.
Resources Window
The Resource Palette provides a federated view of the contents of one or more otherwise
unrelated repositories in a unified search-and-browse user interface. This enables users to find
the resources needed for the task at hand easily. Users can locate resources from a wide variety
of repositories, search for resources and save searches, preview a resource before using it, and
reuse resources by sharing catalog definitions.
The Resource Palette contains two expandable and resizable panels:
• My Catalogs: Resources are created and published in their source repository. Related
resources are grouped into catalogs and are then exposed to the user in the Resource
Palette.
• Connections: Many types of connections, such as to databases, file systems, or application
servers, can be created and displayed in the Resource Palette for use in any application.
By using the Resource Palette’s toolbar icon, you can create new or import existing catalogs and
connections. You are able to search through all resources. By default, the Resource Palette is
displayed on the right of the JDeveloper IDE. If it does not appear, you can display it by
selecting View > Resource Palette.

44
.
Properties Window
The Property Inspector presents a collection of all settable properties for a selected element.
Features of the Property Inspector include the following:
1. When you select an element in the Structure window or Visual Editor, the Property Inspector
title bar shows the name of the selected element.
2. A toolbar enables you to perform component-level actions, such as rebinding to a different
control, freezing/unfreezing, or creating a new view. You can also toggle auto-extend, which
enlarges the Inspector when the cursor moves over it.
3. A search function enables you to quickly locate a property on any panel.
4. A Component Help button invokes context-sensitive Help.
5. Expanding a category group on the left displays a panel containing a subset of properties.
6. Drop-down lists of values are available for many properties.
7. If an editor is available for a property, an arrow to the right of the property invokes it.
8. Icons indicate whether property values are databound or whether they are changed from the
default.
9. When a property is selected, a brief description of the property is displayed at the bottom of
the Inspector.
When you change a property, the value is automatically validated and applied when you
navigate out of that field.

45
.
46
.
Work with Windows in JDeveloper
By now you can see that JDeveloper has many types of windows that display aspects of the IDE.
Most JDeveloper windows can be maximized or restored by using the context menu that
appears when you right-click its tab. Alternatively, you can double-click the tab to maximize or
restore the windows.
Other options available from the context menu are splitting or unsplitting the window or
closing the window. Another way to close the window is by clicking the X on its tab. To reopen,
either double-click the corresponding node in the Application Navigator, or select the window
to open from the View menu.
You can reposition the window by dragging its tab to a different part of the IDE. You can also
undock and redock floating windows by dragging the tab.
You can use the mouse to resize all JDeveloper windows.
You restore the default arrangement of the IDE windows by selecting Window > Reset Windows
to Factory Settings.

47
.
Requirement to Build an Application
The following slides explain how to create an application, a project, and a database connection.

48
.
Create a New ADF Application
Oracle JDeveloper uses a well-defined structure to manage Java programming applications. The
structure is hierarchical and supports applications, projects, images, .html files, and so on. The
application is the highest level in the control structure. It is a view of all the objects you currently need
while you are working. An application keeps track of the projects you use and the environment settings
while you are developing your Java program.
You create an application by invoking the Create Application dialog box in one of the following ways:
• If there is an application already open in JDeveloper, invoke the application drop-down list and select
New Application. If there is no open application, click New Application.
• Select File > New, and in the New Gallery dialog box, select General > Applications. Then select either
Generic Application, or a specific type of application from the list. Click OK.
Enter values for the following properties in the Create Application Wizard:
• Application Name: Enter a name for the application. This name is used to categorize all the files in
your application.
• Directory Name: Enter a top-level directory for the application or click Browse to locate one. This is
where all your application files are stored during development.
• Application Package Prefix: Enter a prefix for all packages associated with this application. The prefix
you assign defines the root package for every project in the application.
• Application Template: Select a template for the application. Click Manage Templates to edit an
existing template or to create a new one. An application template provides a way to apply best practices
to create the project structure for standard applications with the appropriate combination of
technologies already specified. The new application that is created from a template appears in the
navigator already partitioned into projects, with technology scopes set.
Saving Applications
Whenever you save an application, you are prompted to save all the current open files. To save the
open and modified files, select the Save option (or the Save All option) from the File menu. Italic style is
used in the Application Navigator to indicate files that have not yet been saved. Applications are stored
in files with the extension .jws. You do not edit an application file directly, but you can view the content
of an application file by using any text editor. When you open JDeveloper, the last application used is
opened by default so that you can resume your work.

49
.
Use the Application Overview Page
When you first create an application, the Application Overview page appears in the editor area
of the IDE. This page provides a listing of all the sources for your application, grouped into
helpful categories that are displayed in resizable panels.
The Application Overview page gives you a sense of the overall status of your application, such
as which sources are incomplete, which have errors, and so on. When you select one of the
panels, you have access to a context menu that enables you to create objects. For example, in
the Java Files panel, the New menu enables you to create a Java class or interface. You can also
edit and delete objects here.
In the Application Navigator, select Show Overview from the application menu to display the
Application Overview page.

50
.
The Application Overview Checklist
The Application Overview Checklist is designed to help users (especially new users) by providing
step-by-step instructions describing how to build the type of application they have chosen,
according to Oracle best practice recommendations.
Initially, (in JDeveloper), there is a checklist only for new applications based on the “Fusion Web
Application” application template.

51
.
Create a New Project
JDeveloper projects organize the file elements that are used to create your program. In the Applications
Navigator, projects are displayed as the second level in the hierarchy under the application.
Projects manage environment variables, such as the source and output paths used for compiling and running your
program. Projects also maintain compiler, run-time, and debugging options so that you can customize the
behavior of those tools for each project.
A project file has the file extension .jpr and keeps track of the source files, packages, classes, images, and other
elements that may be needed for your program. You can add multiple projects to your application to easily access,
modify, and reuse your source code. You can view the content of a project file by using any text editor.
There are two ways to create a project in JDeveloper. The first way is when you create an application. Depending
on the application template that you select, one or more projects are created automatically. Sometimes you are
presented with a wizard page enabling you to name the project and set its technologies.
The second method of creating a project is to create a new one. You must first select an existing application to
contain the project. Then you can create a new project from the New Gallery in one of the following ways:
• Invoke the application menu that appears to the right of the application name in the Applications Navigator, or
click the down arrow at the far right of the application name, and select New Project to invoke the New Gallery.
• Select File > New from the menu.
• Click New on the Toolbar.
In the New Gallery, select the type of project to create, and then click OK.
When you are presented with the Create Project Wizard, you can name the project and specify where you want to
store the project files. Depending on the type of project, you may also need to select the technologies to use, set
Java or EJB settings, or define other types of project properties.
Note: You can automatically save and compile a project before running it. This preference is set in project
properties. You can set default properties for new projects as follows:
1. Select Application > Default Project Properties from the JDeveloper menu.
2. In the tree at the left of the Default Project Properties dialog box, select Run/Debug/Profile.
3. With the Default run configuration selected, click Edit.
4. In the tree at the left of the Edit Run Configuration dialog box, select Tool Settings.
5. In the Before Running section, select the options that you want to perform before running, such as Make
Project and Save All.
6. Click OK twice to close both dialog boxes and save your preferences.
You can edit preferences for existing projects by right-clicking the project in the Application Navigator and
selecting Project Properties.

52
.
Create Database Connections
JDeveloper enables you to define several types of connections, including connections to external data sources. Database
connections are visible in the Database Navigator, and are organized by the application that owns them. They can also be
added to a Resource Catalog, enabling other developers to share them.
All IDE connections are stored in the connections.xml file in the system12.x.x.x.xx.xx.xx\o.jdevimpl.rescat2\connections
subdirectory of the JDeveloper user directory (see “Launching JDeveloper” earlier in this lesson for the location of the user
directory).
The file system location for an application’s connection descriptor definition information is the connections.xml file in the
.adf\META-INF subdirectory of the application itself. By default, applications are stored in the \mywork\<Application Name>
directory under the root directory in which JDeveloper is installed, although you can choose to save them elsewhere.

In JDeveloper’s Database Navigator, you can set up and manage database connections to enable your projects to communicate
with external data sources, including the Oracle database. All defined connections are accessible to any application or project.
To define a new database connection, perform the following steps:
1. In the Database Navigator, click the New Connection icon at the top left of the navigator to invoke the Create
Database Connection Wizard, or right-click an application and select New Connection from the context menu.
2. In the Create Connection In field, select IDE Connections if you want a connection that can be added to any
application, or select an application to add the connection for that application only.
3. Provide a name and connection type, and enter a username, a password, and, optionally, a role. If you want to
save the password, select the Save Password check box. This option is selected by default.
4. In the Settings section (determined by your Connection Type choice), enter the connection details as requested
5. Click Test Connection. JDeveloper checks the connection by using the information you provided. If the test succeeds,
a success message appears in the status text area. If the test does not succeed, an error appears. Click Back and
change any previously entered information as needed to correct the error, or check the error content to determine
other possible sources of the error. When the test succeeds, click Finish. The new connection name appears under
the owning application node (or the IDE Connections node) in the Database Navigator.

53
.
Refactoring in JDeveloper
You can use refactoring to rename or move an object:
Renaming: When you use a wizard to create entity objects and view objects,
associations and view links are created automatically. They are by default given names
that are based on the name of the foreign key in the database. It is often desirable to
use a more meaningful phrase to rename them. To do so, you right-click the association
or view link in the Application Navigator and from the context menu, select Refactor >
Rename. A refactoring dialog box appears to enable you to rename the association or
view link.
Moving: When you create an object, you are given the opportunity to specify which
package to place it in. If you later want to change the package where an object resides,
you can right-click the object and select Refactor > Move. A dialog box opens to enable
you to specify a different package; this package gets created if it does not already exist.
When you use refactoring, all references to the object are modified throughout the application.

54
.
Advantages of JDeveloper
Oracle JDeveloper is an integrated development environment (IDE) for building
service-oriented applications by using the latest industry standards for Java, XML, Web services, and SQL. It
supports the complete development life cycle with features for modeling, coding, debugging, testing, profiling,
tuning, and deploying applications.
The goal of JDeveloper is to make enterprise Java development simpler and more accessible, so it focuses on
visual and declarative development. Oracle ADF provides JDeveloper with a Java EE framework that implements
design patterns and eliminates infrastructure coding.
JDeveloper enables you to use the latest standards to develop applications that can operate across multiple
hardware and software platforms. It embraces popular open source frameworks and tools, providing built-in
features for Struts, Ant, JUnit, XDoclets, and Concurrent Versions System (CVS), so that you can use these open
source tools to streamline the development process. JDeveloper also offers an Extension SDK so that you can add
capabilities and customize your development environment.
JDeveloper’s productive IDE enables developers to choose:
• Technology stack: The same productive experience is used for various technology stacks. For example, you can
implement a persistence layer by using Java classes, Enterprise JavaBeans (EJB), ADF Business Components, or
Web services. JDeveloper provides a declarative way to implement the chosen technology, as well as drag-and-
drop mechanisms to bind UI components to any of these implementations.
• Development approach: JDeveloper provides a choice of development approaches that includes Model Driven
Architecture (MDA), declarative development, and hand-coding. With MDA, you start by building a model of
the application, which can then be implemented in different technologies. Declarative development enables
you to specify requirements of the application declaratively, thus minimizing the coding that may be required.
However, hand-coding is still preferred by some. Developers can choose the approach that best suits their skill
levels and preferences. Various developers can work on the same files using any of these approaches.
• Development platform: JDeveloper is a 100% Java-based tool. Because of this, it is a cross-platform IDE that
runs on Windows, Linux, Mac, and various UNIX-based systems.
• Data source: JDeveloper can access any JDBC-compliant database.
• Application server: Applications built with JDeveloper can be deployed to any Java EE–compliant application
server.

55
.
Oracle JDeveloper is a complete IDE that addresses the full development life cycle for Java Web
services and PL/SQL applications.
JDeveloper supports the latest standards and provide a platform for extending the IDE.
The major focus area of Oracle JDeveloper 10g is ease of use and productivity.
JDeveloper is also the development tool for both project fusion (the combined E-business, JD
Edwards, Peoplesoft) and the preferred development tool for components of the Oracle Fusion
Middleware (BPEL, Portal, BI etc.).

56
.
57
.
Oracle JDeveloper 10G is a comprehensive development tool that provides facilities to build
Service-Oriented and Event-Driven Applications using a common development tool set. This
tool has been evolved to provide what Gartner Group refers to as an ISSE – an Integrated
environment that allows a developer to model and generate SOA; to write SOA in an IDE; or to
use wizards to generate SOA.

58
.
Lesson Summary

59
.
60
.
In Hands-on lab one would practice:
1. Exploring HR System ER Diagram
2. Examining Training Lab Application – Lab Solution 22

Optionally you may also practice:


1. Creating an Offline Database Diagram with Existing Schema Objects
2. Adding New Offline Database Schema Objects
3. Generating the SQL Scripts
4. Running the SQL Scripts on Database
5. Invoking PLSQL

61
.
62
.
63
.
64
.
65
.
66
.
67
.
68
.
69
.
70
.
71
.
72
.
73
.
74
.
75
.
76
.
77
.
ADF Business Rules in PL/SQL
You can write code in the custom Java classes for your business components to invoke database
stored procedures and functions. In this lesson, you see some simple examples based on
procedures and functions in a PL/SQL package; however, using the same techniques, you also
can invoke procedures and functions that are not part of a package. When you build the ADF
components, it is better to move the business process logic up into the ADF layer and map the
entities to the table level PL/SQL APIs.

78
.
Typical Environment
For the type of situation you see here, a PL/SQL API has previously been constructed around
the tables to protect them from unauthorized write access. In most legacy situations such as
this, you do not have any choice but to work with the existing PL/SQL.
If you have a PL/SQL package that encapsulates insert, update, and delete access to an
underlying table, you can override the default DML processing event for the entity object that
represents the table so that you invoke the procedures in your PL/SQL API instead.
Often, such PL/SQL packages are used in combination with a companion database view. Client
programs read data from the underlying table using the database view and update the table
using the procedures in the PL/SQL package. This section considers the code necessary to
create a Product entity object based on such a combination of a database view and a PL/SQL
package.

79
.
Controlling Entity Posting Order to Avoid Constraint Violations
Due to database constraints, when you perform DML operations to save changes to a number
of related entity objects in the same transaction, the order in which the operations are
performed can be significant. If you try to insert a new row that contains foreign key references
before you insert the row being referenced, the database can complain with a constraint
violation.
By default, when you commit the transaction, the entity objects in the pending changes list are
processed in chronological order, in other words, the order in which the entities were added to
the list. This means that, for example, if you create a new Employee and then a new
Department related to the employee, the new Department is inserted first, followed by the
new Employee.

80
.
81
.
82
.
Lesson Agenda
This lesson provides students with an overview of ADF Business Components and how they are
used as business services to support a Web application. The lesson introduces many topics for
which additional details are provided in later lessons. Students create a simple master-detail
data model.

In Hands-on lab one would practice:


1. Creating another New Application and Projects
2. Creating Default ADF Business Components
3. Examining Generated ADF Business Components Artifacts
4. Testing the Business Service (using Oracle ADF Model Tester)

83
.
84
.
85
.
86
.
Types of ADF Business Components
There are two types of Oracle ADF Business Components objects that represent features of
your data source. If you have a well-designed data source, the structure of these objects should
reflect the structure of the data source. Data sources are represented by the following types of
components:
• Entity objects, which represent objects in the data source (usually tables, views, and
synonyms in a database)
• Associations, which represent relationships between these objects (such as foreign key
relationships)
Other types of ADF BC objects collect data and present it to the client model. They should be
designed on the client’s specific data needs. For this reason, they are not as reusable as entity
objects and associations. There are three such components:
• View objects, which collect data from the data source, usually by a SQL query
• View links, which represent relationships (such as master-detail relationships) between
view object result sets
• Application modules, which provide a single point of access to the view objects and view
Links

87
.
88
.
Create Business Components from Tables Wizard: Application Module
On the Application Module page of the wizard, you designate whether to add the business
components that you are creating to an application module. Application modules enable you to
test business components and also to expose them to a user interface.
If you choose to use an application module, you can create a default one or specify an existing
one to contain instances of all the view objects, joined in a master-detail hierarchy in every
possible way by the view link instances that the wizard is creating.
If you are creating a new application module, you specify the name of a package to contain it,
and you give the application module a name.

89
.
bc4j.xcfg: The bc4j.xcfg file contains metadata information about the application module and runtime
parameters that have been configured to manage the runtime behavior of each application module
instance. When you generate an application module, this file will be automatically generated in
common subfolders relative to the folder where you create the application module definition. If you
edit an application module configuration by using the editor, the modified values are set in the
corresponding bc4j.xcfg file.
<ModelProjectName>.jpx: The <ModelProjectName>.jpx file is used by both design-time editors and
runtime framework components. JDeveloper uses the <ModelProjectName>.jpx file as a registry to
track the contents of the model packages. It also contains metadata for shared application modules
present in the project, which is used by both design-time and runtime components.
• adf-config.xml: The adf-config.xml file contains application-level settings for various framework
components scattered across different layers of the application. These configuration entries are usually
determined at deployment time and will be configured in the adf-config.xml file. However, there are
cases where an application administrator may want to modify certain parameters at runtime without
bringing down the entire application. You can use the Oracle Enterprise Manager (OEM) control to
modify the specific settings for business components at runtime without bringing down the application.
• adfm.xml: The adfm.xml file contains path information for other registry files used in the model
project. You may not see this file in a model project source during development. IDE generates this file
with appropriate entries when you build a model project. The adfm.xml records path information for
the following files, if they are present in the project:
o bc4j.xcfg
o <ModelProjectName>.jpx
o DataControls.dcx
o DataBindings.cpx

90
.
Create Default ADF Business Components
To create components, right-click the project that you want to contain the components and select New from the context menu. The New
Gallery enables you to create several components in a variety of ways by invoking either a modeler or a wizard.
You can create business components by creating a business components diagram. Dragging database tables from the Database Navigator to
the diagram creates entity objects for those tables. You can then use the Component Palette to create other types of objects. This enables you
to visualize the relationships between the business components as well as to create and modify them visually. This course does not use the
business components diagram, but you may want to experiment with it on your own.
Another way to create business components is by using wizards. You can use individual wizards, such as the Create Entity Object Wizard, to
create one type of object at a time. Alternatively, you can use the Create Business Components from Tables Wizard to create several types of
components at once, which is probably the quickest way to get a data model up and running. The next few slides show the pages in the
“Create Business Components from Tables” Wizard. Subsequent lessons show you some of the other wizards.
Note: JDeveloper automatically invokes the “Create Business Components from Tables” Wizard when you create a new Business Components
project.
On the Entity Objects page of the “Create Business Components from Tables” Wizard, you can create default entity object definitions for the
specified database objects. The wizard also creates associations based on all relevant foreign key relationships, and domains for all needed
Oracle object types. This page enables you to create a large number of simple business components quickly and easily. Later you can edit any
default business components that you create, and you can add new business components that may be needed.
On this page, you specify the name of a package to contain the entities. It is recommended that you keep the business domain components
(entities and associations) in a separate package from the data model components.
Select the database schema that you want to use, and then click Query to display the Tables, Views, and Synonyms in that schema, or enter a
name filter to display only certain ones. Then you can shuttle from the Available list to the Selected list the tables for which you want to create
entity objects. You also can change the entity name if desired.
On the Updatable View Objects page of the wizard, you can create default view object definitions that are updatable because they are based
on the specified entity objects. The wizard also creates view links for all relevant association definitions. The view object definitions that you
create on this page expose all attributes in the entity object.
On this page, you specify the name of a package to contain the view objects. Then you can shuttle from the Available list to the Selected list
the entities for which you want to create view objects. You also can change the view object name if desired
On the Read-Only View Objects page of the wizard, you can create read-only view objects and view links for the specified database objects.
Note that these are table names, not entity objects as was the case when you were creating updatable view objects.
On this page, you specify the name of a package to contain the view objects. Then as with entity objects, you select the database schema that
you want to use and click Query to display the Tables, Views, and Synonyms in that schema, or enter a name filter to display only certain ones.
Then you can shuttle from the Available list to the Selected list the tables for which you want to create read-only view objects. You also can
change the view name if desired

91
.
Examine Generated Artifacts
The business components and the diagram that were created are shown in the Application
Navigator, and if a diagram was created, it opens in the editor.
Note that the Application Navigator shows the packages that were specified in the wizard. In
addition, each component that was created has an associated XML file to contain the metadata
pertaining to that component.
By default, no Java files are created. You can create Java files, if desired, for those components
to which you want to add code. This is discussed in the lesson titled “Programmatically
Customizing Data Services.”

92
.
93
.
Business Component Diagram
On the Diagram page of the wizard, you can choose to create diagram elements on a new or
existing business components diagram. Diagramming is optional.
If you choose to create a diagram, on this page, you specify the diagram’s package and name.
You also can select which types of objects to depict on the diagram. Note that you cannot
create diagram elements for objects that do not exist in the package. For example, you cannot
create an application module on the diagram unless there is an application module in your
business components package.
The next page of the wizard displays a Lesson Summary of what you have specified for the
wizard to create. Click Finish to create the business components.
The individual wizards are similar to this one, except that each creates only a specific type of
component. They enable you to more specifically define each component to customize them to
the needs of your application.

94
.
Examining Created Objects
The business components and the diagram that were created are shown in the Application
Navigator, and if a diagram was created, it opens in the editor.
Note that the Application Navigator shows the packages that were specified in the wizard. In
addition, each component that was created has an associated XML file to contain the metadata
pertaining to that component.
By default, no Java files are created. You can create Java files, if desired, for those components
to which you want to add code. This is discussed in the lesson titled “Programmatically
Customizing Business Services.”

95
.
ADF Model Tester
JDeveloper provides a way to test the data model without creating a client application. You can perform
this testing by using the Business Components Browser, sometimes also referred to as the Business
Components Tester or the BC Tester.
To use the Business Components Browser to test the data model, right-click the application module in
the Application Navigator and select Run from the context menu.
A Connect dialog box appears, where you select your database connection and click Connect. After the
connection is established, the Business Components Browser displays a tree with the application
module and all of its view object and view link instances. You can double-click a top-level view object
instance to view it alone, or double-click a view link instance to view both master and detail in a
hierarchy, with the master row displayed in form style and the detail rows displayed in tabular style.
You learn more about ADF Business Components and how to test them in subsequent lessons.

As explained previously, a view object must be contained in an application module before you can
test it. To test a view object, perform the following steps:
1. Right-click its application module in the Applications Navigator and select Run from the
context menu.
2. In the Business Component Browser Connect dialog box, select the connection to use, and then
click Connect.
3. In Business Component Browser, double-click the view object to execute it. You can then use
the toolbar buttons to navigate between records, to set values for bind variables, or to specify
view criteria.

96
.
Overview of ADF Business Components
Oracle ADF Business Components (ADF BC) provides building blocks that help you to create
the business services part of your application. That is, it governs interaction between the rest of
the application and the data stored in the data source, providing validation, specific services,
and other business logic.
With ADF BC, you can:
• Write and enforce business application logic in a centralized way
• Author and test business logic in components that automatically integrate with databases
• Reuse business logic in multiple applications and application tasks
• Access updatable views of business data that are customized to specific tasks
• Access and update the views from browser, desktop, mobile, and Web service clients
• Maintain and modify the business functionality in layers, without requiring modification of
the delivered application
ADF Business Components are implemented in metadata that you write by using wizards and
that you edit declaratively. You can optionally expose framework code to add functionality if
needed.

97
.
98
.
99
.
Implementation Architecture of ADF BC
Before entering into a detailed discussion on each of the key components in subsequent
lessons, it is helpful to understand a few guiding principles that have gone into the design and
implementation of this layer of Oracle ADF:
• It is based on standard Java and XML. Each component’s run-time behavior is configured
in an XML file, whereas the Java source code for the framework is extensible.
• It is database and application server agnostic. You can use any environment with a JVM.
• It implements all the popular Java EE design patterns, such as Model-View-Controller,
Interface/Implementation Separation, and Session Facade.
• It organizes components into packages. To ensure that your code does not clash with
reusable code from other organizations, you should choose package names that begin with
your organization’s name or Web domain name.
• Most of the classes and interfaces comprising the ADF BC prebuilt code are in the
oracle.jbo or the oracle.jbo.server package.
• Components are metadata driven, but you can optionally generate a Java class where you
can add code.

100
.
Expose Business Service
Oracle ADF Model abstracts the UI data binding from the technology that is used to implement
the back-end business services.
ADF Model implements the JSR-227 service abstraction called the data control, and provides
data control implementations for the most common business service technologies—EJB, Web
services, TopLink, Java classes, and ADF Business Components. Whichever implementation you
choose, JDeveloper and ADF work together to provide you a declarative, drag-and-drop data
binding experience as you build the user interface for your application.
When you create an ADF BC application module, it is automatically exposed as a data control,
including all the view object and view link instances that it contains.
The JDeveloper Data Control Palette exposes an application’s data controls in the IDE, and
enables you to use the drag-and-drop functionality to create UI components on a page. The UI
components created by the Data Control Palette use declarative data binding, which means
that the data binding expressions are automatically configured and that, in most cases, you do
not have to write any additional code. The data bindings use Expression Language (EL).
It does not matter which technology you have used to build your business services—EJB, Web
services or business components—the Data Control Palette looks the same and works in
exactly the same way.

101
.
102
.
103
.
104
.
105
.
106
.
107
.
Exposing the Application Module to the User Interface
Oracle ADF Model abstracts the UI data binding from the technology that is used to implement
the back-end business services.
ADF Model implements the JSR-227 service abstraction called the data control, and provides
data control implementations for the most common business service technologies—EJB, Web
services, TopLink, Java classes, and ADF Business Components. Whichever implementation
you choose, JDeveloper and ADF work together to provide you a declarative, drag-and-drop
data binding experience as you build the user interface for your application.
When you create an ADF BC application module, it is automatically exposed as a data control,
including all the view object and view link instances that it contains.
The JDeveloper Data Control Palette exposes an application’s data controls in the IDE, and
enables you to use the drag-and-drop functionality to create UI components on a page. The UI
components created by the Data Control Palette use declarative data binding, which means
that the data binding expressions are automatically configured and that, in most cases, you do
not have to write any additional code. The data bindings use Expression Language (EL).
It does not matter which technology you have used to build your business services—EJB, Web
services or business components—the Data Control Palette looks the same and works in
exactly the same way.

108
.
109
.
110
.
Lesson Agenda
This lesson teaches you how to enable Web applications to query, insert, update, or delete data
in the database. You learn how to use ADF BC read-only view objects to provide a reusable
mechanism for defining database queries. The entity object is the ADF BC mechanism for
persisting data. You create entity objects from selected tables in the database schema, and
then create updatable view objects based on them.

In Hands-on lab you would practice


1. Creating Multiple Entity Objects at Once
2. Creating an Association
3. Examining Attribute Settings

Optionally you may also practice:


1. Creating Entity Object based on Database View
2. Synchronizing an Entity Object with Table Structure Changes

111
.
112
.
Using Entity Objects to Persist Data
Entity objects contain attributes, business rules, and persistence information that apply to a
specific part of your business model. Entities are used to define a logical structure of your
business, such as product lines, departments, divisions, and so on. They can also define physical
items, such as warehouses, employees, and equipment. For example, CustomerEO is an entity
object.
• An entity object is based on a data source; the example in the slide is based on the Customers
table.
• An entity’s attributes map to the columns of the data source; the CustomerEO entity has
attributes called ID, Name, Status, and Email that map to the corresponding columns of the
CUSTOMERS table.
• You can attach validation rules to an entity object; the Status attribute has a validation rule
that restricts status values to a list of valid values.
You retrieve and modify entity rows in the context of an application module that provides the
database transaction. When your application module creates, modifies, or removes entity
object rows and commits the transaction, changes are saved automatically.

113
.
114
.
Entity object definition XML metadata file: This file is an entity descriptor, which holds metadata
definition for the entity. This file stores the following configurations for an entity object: This file stores
the database object on which the entity is built upon. An entity object can be built from a database
table, view, synonyms, or materialized view.
This file also stores the attribute definition for each column present in the entity object. This includes
the datatype, length, precision, validation rules, and updatability of the attribute. Attribute definition
also includes UI hints such as label, tool tip, format type, and control type.
°°View accessors and entity accessor attributes' definitions are also stored in this file. View accessors
and entity accessor attributes' definitions are used for accessing view objects and associated entity
objects, respectively.
°°Business event definitions that are used for launching business processes in a service oriented
environment.

Entity definition: This class acts as a runtime Java class representation for the entity object definition
XML metadata file. The default entity definition class used by the ADF Business Components' runtime is
oracle.jbo. server.EntityDefImpl, which can be extended to provide custom functionalities, if needed.
• Entity object: This class represents individual entity instance created from the entity definition at
runtime. The default entity object class used by the ADF business components' runtime is
oracle.jbo.server.EntityImpl, which can be extended to provide custom functionalities, if needed. In
simple words, an entity object instance represents a row in the datasource. For example, when you
query an Employee table in the database by using a view object backed up by the EmployeeEO entity
object, the framework creates EmployeeEO entity object instances for storing employee records
returned by the SQL query.
• Entity collection: This class represents the cache of the entity object class held in memory for a
transaction. The default entity collection (entity cache) class used by the ADF Business Components'
runtime is oracle.jbo.server. EntityCache, which can be extended to provide custom functionalities, if
needed.

115
.
Lesson Agenda
This lesson teaches you how to enable Web applications to query, insert, update, or delete data
in the database. You learn how to use ADF BC read-only view objects to provide a reusable
mechanism for defining database queries. The entity object is the ADF BC mechanism for
persisting data. You create entity objects from selected tables in the database schema, and
then create updatable view objects based on them.

116
.
Features of an Entity Object (EO)
An entity object is the ADF BC component that represents a row in a database table and
simplifies modifying its data. It enables you to encapsulate domain business logic for those
rows to ensure that your business policies and rules are consistently validated.
Each entity object maps to a data source, usually a database table or database view. Entity
objects handle database caching, so that changes to data are cached in the entity object before
being committed to the database.
Entity objects are the foundation of the Business Components technology. Each entity object
represents a business object, or business entity, in your application. Entity objects handle
business rules and validation and can contain custom business methods.

117
.
Creating Entity Objects from Tables, View, or Synonyms
When you create an entity object from an existing table, first JDeveloper uses the online
database connection to interrogate the data dictionary to infer the following information:
• The Java-friendly entity attribute names from the names of the table’s columns (for example,
DEPT_ID becomes DeptId)
• The SQL and Java data types of each attribute based on those of the underlying column
• The length and precision of each attribute
• The primary and unique key attributes (If the table has no primary key, it uses RowID.)
• The mandatory flag on attributes, based on NOT NULL constraints
• The relationships between the new entity object and other entities based on foreign key
constraints
JDeveloper then creates the XML component definition file that represents its declarative
settings and saves it in the directory that corresponds to the name of its package.
If you create an entity object from a view, or from a table without a primary key, by default
RowID is used as a primary key. If you create an entity object from a synonym, that entity object
behaves as if it is created on the underlying table or view.

118
.
You can create entity objects with the Create Entity Object Wizard that you invoke from the New Gallery (File > New > Business Tier > ADF Business Components >
Entity Object). This wizard contains the following pages:
• Name: Specify the name and package for the entity object; select the database schema to use; select one or more check boxes for the types of schema objects
to display; select the schema object on which to base the entity object.
• Attributes: Add or delete attributes from the entity object.
• 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 NULL constraints.
- 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.)
- 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 KEY constraints.
- Unique: Specify that the corresponding table column is to be generated with a UNIQUE constraint.
- Queryable: Specify that this attribute can occur in the WHERE clause 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 Date or Timestamp attribute, created by or modified by for a Char, Character, or String attribute, or version number for a Number attribute).
- 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.
• Java: Specify whether to create Java files to implement custom logic for validation and default values in the entity class or to override base class methods. You
can opt to create Java files for any or all of the entity collection class, the entity object class, or the entity definition class. Otherwise, only XML files are generated.
• Generate: It enables you to create a default view object and application module from this entity object.
• Summary: It presents a summary of the selected options.

119
.
120
.
121
.
122
.
123
.
124
.
125
.
126
.
127
.
Synchronizing an Entity Object with Changes to Its Database Table
If you alter a table for which you have already created an entity object, the existing entity is not
disturbed by the presence of additional attributes in its underlying table. However, if you want
to access the new table column in your application, you first need to synchronize the entity
object with the database table. To perform this synchronization from JDeveloper, right-click the
entity object in question and select “Synchronize with Database” from the context menu.
For example, suppose you had issued the following SQL*Plus command to add a new
SECURITY_QUESTION column to the USERS table:
ALTER TABLE USERS ADD (security_question VARCHAR2(60));
When you use the synchronize feature on the existing User entity, the “Synchronize with
Database” dialog box proposes the changes that it can perform for you automatically. By
clicking the desired button, you can carry out the synchronization.

128
.
Generating DB Tables from Eos
You can create database tables from entity objects. Right-click the package that contains the
entity objects and select Create Database Objects from the context menu. Then in the Create
Database Objects dialog box, select the object to create. Another dialog box confirms whether
you want to do this before proceeding.
Use caution when performing this generation, especially on entities that are based on existing
tables. The feature does not generate a script to run later, but performs its operations directly
against the database and drops existing tables.

129
.
Entity Association Types
Association: An association is a relationship between two entities that are not completely
dependent on each other. Each end of the association may exist without the other, and either
may be deleted without deleting the other. In Unified Modeling Language (UML), an association
is represented as a line.
Composition: A composition relationship means that the source entity owns the destination
entity object. The destination entity object cannot exist without the owning entity object
existing first. The source entity object is a container for the destination entity object. For
example, an order owns the order lines associated with it. In a composition, the source cannot
be deleted until all the destination items are deleted. In UML, a composition is represented as a
line with a solid diamond shape at the source end.
Compositions and Validation
When a change is made to the destination entity, a validate message is sent to the source. The
source entity’s validate() method is called when the transaction is committed.
The composition relationship also dictates the sequence of various operations at run time. For
example, child validation is forced before parent. Parent posting is forced before child posting.
You can control many additional composition-related features through settings on the
Association Properties page of the Create Association Wizard, or via the Association Editor.

130
.
Features of Entity Associations
As stated earlier, the “Create Business Components from Tables” Wizard in JDeveloper
automatically creates associations between entities that represent tables that are joined by a
foreign key constraint. Associations are like master-detail relationships in a relational database.
However, you can also create an association manually, as follows:
• Right-click the package name.
• Select New Association from the Context menu. This displays the Create Association Wizard.
Viewing the Components of an Association
When you select an association in the Application Navigator, the Structure window displays the
source (master) entity and the destination (detail) entity. In this example, the PersonEO entity is
the source in the association and the OrderEO entity is the destination. That means that each
person can have multiple orders, and that every order must belong to one person.
The Usefulness of Associations
Associations can be useful in helping you to create a more comprehensive representation of
the business. For example, they allow you to “walk” between entity objects, using the
find-by-primary-key query. When you traverse entity associations in your model, if the entities
are not already in the cache, the ADF Business Components framework performs the query to
bring the entity (or entities) into the cache.
They can also perform autolookups of reference information when foreign key values change.
In addition, when working in declarative SQL mode, the view object’s metadata can cause the
ADF Business Components run time to generate table joins for you.
Generated Files
JDeveloper generates only one file for each association: <Association>.xml (for example,
OrdersPersonsFkAS.xml), which contains all the metadata for the association.

131
.
The properties available under the Behavior tab are as follows:
Use Database Key Constraints: This property does not have any ADF runtime implementation. It is used to create
the foreign key constraints in the database when you generate the database table from entity objects, which
participate in association.
Implement Cascade Delete: This option will allow you to unconditionally delete the composed entities together
with composing entities. If this is deselected, runtime will not allow the deletion of a parent entity if it has any
child entities. Use this feature if you do not want child entities to exist on removal of parent entity.
Optimize for Database Cascade Delete: This option will act as hints for the runtime to optimize the deletion of
detailed entities participating in the association. If this option is selected, when you delete the parent, detailed
entities will not trigger an individual DELETE command. Your database should have the ON DELETE CASCADE
constraint specified to take care of the deletion of entries from the child tale. This feature is useful when you do
not want to replicate the database constraints in the middle tier. This approach makes sense, if there is less
chance for the application to migrate to a different database (or to a different datasource) in future.
Cascade Update Key Attributes: This option will automatically update foreign keys in the child entities when the
primary key in the parent tale is changed. Enable this option if the application allows the user to edit the foreign
key in the parent row.
Update Top-level History Columns: This option will trigger the history column (Modified On or Modified By)
update on the parent when the child is removed, modified, or added. This feature is useful if you are working on
transaction-sensitive applications where you may need to update the history columns in the parent row when any
changes in the child rows are posted to the database. This history column update for the parent row is triggered
with this setting even if there is no change in the parent row attributes.
Lock Level: This option will issue a lock on the composing parent entity whenever the composed child entity is
locked during the data update. The following are the various lock levels that you can choose from: None: No
locking is issued on the parent when the framework acquires a lock on the child entity (destination).
Lock Container: This option locks the immediate parent entity (source entity in the association definition) when
the framework acquires a lock on the child entity (destination entity in the association definition).
Lock Top-level Container: Framework locks the topmost entity object in the composition association hierarchy
when the framework acquires a lock on the child (destination) entity object. The logic to lock the top level
container walks up the association hierarchy and stops either at the top level or when a composition association
that has the Lock Top-level Container flag turned off is found.

132
.
133
.
134
.
In Hands-on lab you would practice
1. Creating Read-Only View Object based on SQL Query
2. Creating Updatable Join View Object
3. Adding View Object to Existing Application Module
4. Testing View Objects

Optionally you may also practice:


1. Internationalizing through Resource Bundle
2. Creating Read-Only View Object based on Static List
3. Creating Multiple Read-Only View Objects at Once
4. Creating View Link
5. Adding Child VO to Master VO Through Link in Existing AM
6. Testing View Objects and Link

135
.
136
.
Overview of View Objects
View objects provide the ability to query data in ADF BC applications. There are two types of
view objects that you can use to retrieve data from the database:
• Updatable View through Entity Objects: Using entity object references enables view object
instances to update data, use validation and other business rules from the entity object
definition, and immediately synchronize data with other view object instances.
• Read-only Access View: SQL-only view objects bypass entity cache population and are faster
for many applications. Note that view objects of this type save changes in memory only, and
are not persisted in the database.
You can also populate the rows of a view object programmatically or by using a static list, but
these types of view objects are not covered in this course.

137
.
An ADF view object is composed of the following components:
• View definition XML file: This is the view object descriptor XML file, which holds metadata definitions. The metadata includes the following:
o The SQL SELECT statement used in the view object
o Bind parameter definitions used in the SQL SELECT statement
o Attribute definition describing each column returned by the query—this includes UI-related metadata, such as UI Hints and UI
Categories for attributes
o Entity usage information (if there is entity backup for the view object)
o Metadata definition for list of values (LOV) and view criteria (query)
o View accessor definition for accessing other view objects
o Business rules
• View definition: This is the runtime Java class representation for the view definition XML file. The default view definition class used by the
ADF Business Components' runtime is oracle.jbo.server.ViewDefImpl, which can be extended to provide custom functionalities, if needed.
• View object: This class represents a view object instance. The view object instance manages the query execution at runtime. The default
view object class used by the ADF Business Components' runtime is oracle.jbo. server.ViewObjectImpl. Developers can extend this class to add
custom functionalities, if needed.
• View criteria: View criteria will let you define filter conditions for attributes in a view object, which will be used at runtime to filter the query
result. This implementation takes the form of a query-by-example approach, which allows the end user to supply values for attributes of the
target view object in order to form the desired search condition.
• Bind variables: These are placeholder variables in a SQL statement used in a view object. These variables will be replaced with the valid ones
before executing the query.
• View accessor: This acts as a gateway for a view object to access another view object. This is used in validation and LOV definitions.
A view object uses the following framework components to set up the infrastructure for query execution and managing the result set:
• Row: A row represents an element in the collection that is a result from a query on a view object.
• Row set: View object uses row sets to manage the collection of rows from a query. The framework will create a different row set when the
same view object is used as a mechanism to query the datasource in different contexts. Some of these areas act as query for list of values
implementation and query for child collection in master-child tree structure. Parameterized conditions used for finding the row sets are
maintained at each row set level.
• Row set iterator: This enables the client to traverse the row set and work with individual items. A client can create one or more row set
iterators to enumerate through the rows.
• Query collection: A query collection contains the rows used in a view object. A view object instance may maintain multiple query
collection, depending on the row filter (a data structure holding bind variable values) used by different row sets to execute query. Note
that a row or row set does not store any data within it, rather they use query collection object for storing rows.
• View link: View link connects two view objects, typically used for implementing master-child relationships.

138
.
Types of VOs

139
.
Types of VOs

140
.
Create Business Components from Tables Wizard: Read-Only View Objects
On the Read-Only View Objects page of the wizard, you can create read-only view objects and
view links for the specified database objects. Note that these are table names, not entity
objects as was the case when you were creating updatable view objects.
On this page, you specify the name of a package to contain the view objects. Then as with
entity objects, you select the database schema that you want to use and click Query to display
the Tables, Views, and Synonyms in that schema, or enter a name filter to display only certain
ones.
Then you can shuttle from the Available list to the Selected list the tables for which you want to
create read-only view objects. You also can change the view name if desired.

141
.
Overview of View Objects
View objects provide the ability to query data in ADF BC applications. There are two types of
view objects that you can use to retrieve data from the database:
Updatable View through Entity Objects: Using entity object references enables view object
instances to update data, use validation and other business rules from the entity object
definition, and immediately synchronize data with other view object instances.
Read-only Access View: SQL-only view objects bypass entity cache population and are faster
for many applications. Note that view objects of this type save changes in memory only, and
are not persisted in the database.
You can also populate the rows of a view object programmatically or by using a static list, but
these types of view objects are not covered in this course.

142
.
143
.
Creating Read-Only VOs
To create a view object, use the Create View Object Wizard. The wizard is available from the New Gallery in the Business Tier > ADF Business Components category. If it is the first component
that you are creating in the project, the Initialize Business Components Project dialog box appears. In this dialog box, you can select a database connection and specify the SQL flavor and type
map for your application.
The SQL Flavor setting controls the syntax of the SQL statements that your view objects will use and the syntax of the DML statements that your entity objects will use. If JDeveloper detects
that you are using an Oracle database driver, it defaults this setting to the Oracle SQL flavor. The supported SQL flavors include:
• Oracle– The default, for working with Oracle
• Olite– For the Oracle Lite database
• SQLServer– For working with a Microsoft SQL Server database
• DB2– For working with an IBM DB2 database
• SQL92– For working with any other supported SQL92- compliant database
The Type Map setting controls whether you want this project to use the optimized set of Oracle data types, or use only the basic Java data types. If JDeveloper detects that you are using an
Oracle database driver, it defaults this setting to the Oracletype map. The supported type maps are:
• Oracle – Use optimized types in the oracle.jbo.domainpackage
• Java– Use basic Java types only
Note: You can change the database connection information later by editing project properties, but the SQL flavor and type map cannot be changed after the initialization of the project.
Therefore, if you plan to have your application run against both Oracle and non-Oracle databases, you should select the SQL92SQL flavor when you begin building your application, not later.
Although this makes the application portable to both Oracle and non-Oracle databases, it sacrifices using some of the Oracle- specific optimizations that are inherent in using the Oracle SQL
flavor.
The Name page of the Create View Object Wizard enables you to supply the view object name and the package to contain it, as well as the kind of data you need the view object to manage.
For the read-only view object, select “Read-only access through SQL query.”
The SQL Statement page of the wizard enables you to enter a custom SQL statement and to check its syntax. You also can specify an ORDERBYclause. There are buttons to invoke a query
builder, to perform an explain plan, and to test the syntax of the query.
You can type in the query if desired, but clicking the Query Builder button enables you to build the query and helps to avoid typing mistakes. In the SQL Statement dialog box of the Query
Builder, you can select Quick-pick objects in the tree at the left. Then select the schema and click Query to show the available tables or views, which you can expand to show the attributes. You
select the objects from the Available list and shuttle them to the Selected list to populate the query with the desired attributes and FROMclause. Selecting attributes under a foreign key
ensures that tables are joined based on the foreign key. You can also define aliases on the Quick-pick objects page.
Selecting other elements from the tree at the left displays other pages that enable you to define various clauses or bind variables for the query.
After you have written the query, click Test for a syntax check.
On the next few pages of the Create View Object Wizard, you can define:
• Bind variables
• Attribute mappings
• Attributes
• Attribute settings
These pages enable you to create bind variables and set properties on attributes. Bind variables are discussed in a later lesson. If you create the view object without setting values for these
pages, you can edit the view object later to set them.
Business components by default are defined in .xmlfiles. However, the Java page of the wizard enables you to optionally create .Javafiles where you can add custom code if desired. If you
create the view object without creating the Java files, you can create them at a later time.
Application modules are discussed in a later lesson, but for now you should understand that application modules provide a way to expose business components to applications. To be able to
test your view object, it must be contained in an application module. The last step of the Create View Object Wizard enables you to optionally put the view object into an application
module. If you choose not to do so now, you may add the view object to an application module later.

144
.
Characteristics of Updatable View Objects
So far you have learned to create view objects that are based on a SQL query. Such view objects
can be used by client applications to present data in read-only mode.
You have also learned that the entity object is the ADF BC mechanism to interact with the
database, enabling inserts, updates, and deletes. However, entity objects are not visible to
client applications.
To retrieve and present to the client application the records to be updated, you need a different
type of view object, one that is based on an entity object rather than on a SQL query. This is
called an updatable view object.
The slide shows an example of a view object, called CustomerStatusVO. An updatable view
object is bound to an entity object; this one is based on the CustomerEO entity object. A view
object’s attributes map to the attributes of the underlying entity object; the CustomerStatusVO
view object has attributes that map to the Name and Status attributes of the underlying entity
object.
Even though an updatable view object is based on an entity object, it still uses a SQL query
(select) to sort and filter data, so you can specify ORDER BY and WHERE clauses for it.

145
.
Create Business Components from Tables Wizard: Updatable View Objects
On the Updatable View Objects page of the wizard, you can create default view object
definitions that are updatable because they are based on the specified entity objects. The
wizard also creates view links for all relevant association definitions. The view object definitions
that you create on this page expose all attributes in the entity object.
On this page, you specify the name of a package to contain the view objects. Then you can
shuttle from the Available list to the Selected list the entities for which you want to create view
objects. You also can change the view object name if desired.

146
.
Overview of View Objects
View objects provide the ability to query data in ADF BC applications. There are two types of
view objects that you can use to retrieve data from the database:
Updatable View through Entity Objects: Using entity object references enables view object
instances to update data, use validation and other business rules from the entity object
definition, and immediately synchronize data with other view object instances.
Read-only Access View: SQL-only view objects bypass entity cache population and are faster
for many applications. Note that view objects of this type save changes in memory only, and
are not persisted in the database.
You can also populate the rows of a view object programmatically or by using a static list, but
these types of view objects are not covered in this course.

147
.
EO and VO Interaction: Retrieving Data
A view object typically gets its data by using a SQL query, and a view object is usually bound to
an entity object. This slide should help to explain these two apparently conflicting pieces of
information. View objects and entity objects work together when a view object retrieves data:
• The view object queries the database, ensuring that its data is current.
• Data retrieved by the query is saved to the entity object’s cache.
Calculated Attributes
A calculated attribute is based only on a database query, not on an entity object’s attribute.
Calculated attributes get their data directly from a column expression in the SQL query; the
data is stored in the view object’s cache.
Entity Objects
The data is passed to the entity object to validate business rules stored in the object. The view
object determines what data is retrieved. The entity object guarantees that the data follows the
defined business rules.
Synchronization
Values in view object rows and entity object rows remain coordinated.

148
.
EO and VO Interaction: Updating Data
When you update data in the database, the process described in the previous slide is not quite
reversed:
• The view updates the entity object’s cache.
• When the transaction is committed, the entity object updates the database.
As stated on the preceding page, the entity object guarantees the validity of the data that is
being committed to the database.

149
.
Types of VOs

150
.
151
.
Creating a Join View Object
A join view object is one that is based upon multiple entity objects that are related by one or
more associations. When you create a join view object, you can select from the following join
types:
• Inner join (default): Rows that meet query criteria are returned only if related rows exist in
both entities. For example, only Person rows with at least one order and only Orders rows that
are associated with a person are returned.
• Left outer join: All rows that meet the criteria from the first entity object are returned by the
query, regardless of whether there are rows in the second entity. For example, all Person rows
that meet query criteria are returned, regardless of whether they have an associated order.
• Right outer join: All rows that meet the criteria from the second entity object are returned by
the query, regardless of whether there are rows in the first entity. For example, all Order rows
that meet query criteria are returned, regardless of whether they have an associated person.
Shaping the Data
It is important to realize that the type of join view object selected will determine how the data
will be shaped, specifically as to how it will be used in either the business services or the UI.
Therefore, different types of view objects can be used to represent different facets of the data.

152
.
Overview of View Objects
View objects provide the ability to query data in ADF BC applications. There are two types of
view objects that you can use to retrieve data from the database:
Updatable View through Entity Objects: Using entity object references enables view object
instances to update data, use validation and other business rules from the entity object
definition, and immediately synchronize data with other view object instances.
Read-only Access View: SQL-only view objects bypass entity cache population and are faster
for many applications. Note that view objects of this type save changes in memory only, and
are not persisted in the database.
You can also populate the rows of a view object programmatically or by using a static list, but
these types of view objects are not covered in this course.

153
.
Including Reference Entities in Join View Objects
It is extremely common in business applications to supplement information from a primary business
domain object with secondary reference information to help the end user understand what foreign
key attributes represent. For example, when displaying employees, rather than displaying the
department number, it may be more meaningful for users if the department name is displayed. The
department name is in a separate entity from the employees’ entity.
When you create a join view object, the additional entity is most commonly used as a nonupdatable
reference entity. To include a reference entity, when you create the view object (or when editing it
later), perform the following steps:
1. Add the secondary entity to the view object as a Reference entity, choosing the association and
join type to use.
2. Add the referenced attributes to the selected attributes for the view object.
3. When the application module is run, the referenced attributes are displayed in read-only mode.
You can include multiple referenced entities in the same view object. In fact, in most cases all but
one of the entities in a view object are reference entities.
The example in the slide shows the Orders entity as the primary entity for the view object. The
FirstName, LastName, and PersonId attributes are added from the reference entity, Persons,
to be displayed as read-only attributes.

154
.
Including Reference Entities in Join VO
It is extremely common in business applications to supplement information from a primary
business domain object with secondary reference information to help the end user understand
what foreign key attributes represent. For example, when displaying employees, rather than
displaying the department number, it may be more meaningful for users if the department
name is displayed. The department name is in a separate entity from the employees’ entity.
When you create a join view object, the additional entity is most commonly used as a
nonupdatable reference entity. To include a reference entity, when you create the view object
(or when editing it later), perform the following steps:
Add the secondary entity to the view object as a Reference entity, choosing the association and
join type to use.
Add the referenced attributes to the selected attributes for the view object.
When the application module is run, the referenced attributes are displayed in read-only mode.
You can include multiple referenced entities in the same view object. In fact, in most cases all
but one of the entities in a view object are reference entities.
The example in the slide shows the Orders entity as the primary entity for the view object. The
FirstName, LastName, and PersonId attributes are added from the reference entity, Persons, to
be displayed as read-only attributes.

155
.
Types of VOs

156
.
Overview of View Objects
View objects provide the ability to query data in ADF BC applications. There are two types of
view objects that you can use to retrieve data from the database:
Updatable View through Entity Objects: Using entity object references enables view object
instances to update data, use validation and other business rules from the entity object
definition, and immediately synchronize data with other view object instances.
Read-only Access View: SQL-only view objects bypass entity cache population and are faster
for many applications. Note that view objects of this type save changes in memory only, and
are not persisted in the database.
You can also populate the rows of a view object programmatically or by using a static list, but
these types of view objects are not covered in this course.

157
.
158
.
159
.
160
.
161
.
162
.
163
.
164
.
165
.
166
.
167
.
168
.
169
.
170
.
171
.
172
.
173
.
174
.
175
.
176
.
177
.
178
.
179
.
180
.
181
.
Internationalization of Business Services
Many of the declarative modifications that you make to the data model involve text, such as
labels or messages. ADF makes it easy to translate such text by offering the option to store it in
resource bundles. You can use one resource bundle for the entire project or a separate one for
each file.
Resource bundles are properties files containing translatable strings stored with key values and
optionally with descriptions that are stored as comments. For example, the label for the
OrderDate field of the Orders entity object is stored as:
#Used for the label of Orders.OrderDate ORDER_DATE=Order Date
where ORDER_DATE is the key, Order Date is the translatable string, and the first line is the
description. Although the description suggests the usage, the string can be used anywhere.
To provide multiple languages, a translator needs only to copy the properties file and append
_<locale> to the name. For example, the properties file depicted in the slide may have a
German translation; the name of that file would be Project1Bundle_de.properties.
All the translations should be stored in the same directory.
When you configure the user interface to support multiple translations as explained in the
lesson titled “Planning the User Interface,” which translation is used depends on the client’s
browser settings.

182
.
Types of VOs

183
.
184
.
185
.
Features of View Objects
A view object is a reusable Oracle ADF business component that encapsulates a SQL query and
simplifies working with its results. View objects have the following characteristics:
• They are defined by providing a SQL query or underlying entity object.
• They simplify the job of executing a query and working with the results.
• They can be linked to one or more other view objects to create master-detail hierarchies.
• They execute the query at run time to produce a row set of rows through which you can
iterate by using a row set iterator.
• You can filter the row set a view object produces by applying a set of query-by-example
criteria.
• You can create a view of data that is specific to your application or to a part of your
application.
• You use view object instances in the context of an application module that provides the
database transaction for the view object queries.

186
.
Creating Updatable View Objects
The process of creating an updatable view object begins with selecting the view object from the New
Gallery to invoke the Create View Object Wizard, just as you did with read-only view objects.
However, on the Name page of the wizard, you specify that you want the view object to have
updatable access through entity objects, instead of read-only access as you do to create a read-only
view object.
After you have selected to base the view object on entity objects, the next page of the wizard, the
Entity Objects page, enables you to select from existing entity objects. If you select more than one,
you can specify the join type and whether the second entity object is updatable or only for reference.
These choices are discussed in more detail later.
The Attributes page presents all the attributes of the entities that you selected and enables you to
select the ones that you want in the view object, thus restricting the columns returned by the query.
You can use the arrows at the right to rearrange the order of the attributes, and you can use the New
button to create calculated or transient attributes that are not part of the entity (more about these in
the lesson titled “Declaratively Customizing Data Services”).
The Attribute Settings page of the wizard is similar to the one in the Create Entity Object Wizard.
However, these settings apply to this view object only, and if different, override the attribute settings
in the entity object. Different views may present data differently.

187
.
188
.
189
.
190
.
191
.
192
.
193
.
194
.
Creating Master-Detail Relationships with View Objects
You can use view links to create master to multiple detail and cascading master-detail
relationships between view objects. To create view objects with these characteristics, you need
to create view links.

195
.
Linking View Objects
You have learned to use associations to define a relationship between entity objects. You have
also learned how to join multiple tables in a view object query, producing a single view object
that contains attributes from multiple tables. View links enable you to join multiple view
objects in a master-detail hierarchy. When your needs call for showing the user a set of master
rows, and for each master row a set of coordinated detail rows, then you can create view links
to define how you want the master and detail view objects to relate. Note, however, that a
query of the detail view object via the master only occurs as long as the view link is included as
part of the application module.
To define a view link, you can first create a view object that queries the master table and
another that queries the detail table. Then you can create a new view link, selecting the
attributes of the source (master) and destination (detail) view objects to link on and clicking
Add to create the source/destination pair. If multiple attribute pairs are required to define the
link between master and detail, you can repeat these steps to add additional
source/destination attribute pairs.

196
.
197
.
198
.
Linking VOs (View Link)
You have learned to use associations to define a relationship between entity objects. You have
also learned how to join multiple tables in a view object query, producing a single view object
that contains attributes from multiple tables. View links enable you to join multiple view
objects in a master-detail hierarchy. When your needs call for showing the user a set of master
rows, and for each master row a set of coordinated detail rows, then you can create view links
to define how you want the master and detail view objects to relate. Note, however, that a
query of the detail view object via the master only occurs as long as the view link is included as
part of the application module.
To define a view link, you can first create a view object that queries the master table and
another that queries the detail table. Then you can create a new view link, selecting the
attributes of the source (master) and destination (detail) view objects to link on and clicking
Add to create the source/destination pair. If multiple attribute pairs are required to define the
link between master and detail, you can repeat these steps to add additional
source/destination attribute pairs.

199
.
Compare Join VOs with View Links
A join view query for the example in the previous slide may be as follows:
SELECT Orders.ORDER_ID,
Orders.ORDER_DATE,
Persons.PERSON_ID,
Persons.FIRST_NAME,
Persons.LAST_NAME
FROM PERSONS Persons, ORDERS Orders
WHERE Persons.PERSON_ID = Orders.CUSTOMER_ID
A query for a view link uses a bind variable in a WHERE clause that is appended to the base
query for the source or destination view object. In the example in the previous slide, the
WHERE clause that is appended would be something like the following:
:Bind_PersonId = Orders.CUSTOMER_ID
This would query all the orders for the current customer, displaying orders and customers in a
master-detail fashion.

200
.
Testing VOs with ADF Model Tester
As explained previously, a view object must be contained in an application module before you
can test it. To test a view object, perform the following steps:
1. Right-click its application module in the Applications Navigator and select Run from the
context menu.
2. In the Business Component Browser Connect dialog box, select the connection to use, and
then click Connect.
3. In Business Component Browser, double-click the view object to execute it. You can then use
the toolbar buttons to navigate between records, to set values for bind variables, or to specify
view criteria.

201
.
202
.
203
.
Lesson Agenda
In this lesson, you learn how to expose ADF BC data services to an application. You learn that
the application module enables the data services to be used on a Web page, and you learn
about how ADF Model abstracts the data for binding to user interface components. You create
application modules and test them with the Business Components Tester.

In Hands-on lab, optionally you may also practice:


Creating New Nested Application Module

204
.
205
.
Ingredients of an application module
An application module comprises of the following components:
• Application module XML metadata file: This is the application module descriptor file
holding metadata definitions. The metadata includes exposed business methods and data
models for use, by clients, such as view objects and associated view criteria, master-child
view, objects connected through view links, and nested application modules.
• Application module definition: This is the runtime Java class representation of the
application module XML metadata file. The default base class for storing the application
module definition is oracle.jbo.server. ApplicationModuleDefImpl which can be extended to
add custom functionalities if needed. This class stores the runtime metadata for application
modules read from the corresponding XML file.
• Application module implementation: This class represents an application module instance
generated by runtime to serve a request from the client. The default base class used for
representing an application module instance is oracle.jbo.server.ApplicationModuleImpl. You
will subclass this class to define the custom business logic that must execute in the
application's middle tier.
• bc4j.xcfg: This file contains metadata for all the application modules present in the
same Java package for a project. This file is located in the Common subdirectory relative to
the path where the application module's XML component definition is located. An
application module's runtime behaviour is controlled by the configuration properties present
in this file. The properties stored in this file include the JDBC data source name, application
module pooling configurations, database specific configurations, locking mode, and so on.

206
.
What is Application Module (AM)
Oracle ADF application modules are business components that represent particular
application tasks. The application module provides a data model for the application
task by acting as a sort of “wrapper” for the view object and view link instances
required for the task. Although conceptually an application module is a wrapper for
the entities, views, associations, and view links in an application task, its data model
contains only views and view links. The underlying entities and associations are
included by implication. The application module also contains services that help the
client accomplish the task. For example, an application module can represent and
assist with tasks such as:
• Updating customer information
• Creating a new order
• Processing salary increases
Restricted and Unrestricted Views
In the application module shown in the slide, PersonsVO1 is an unrestricted view
and OrdersVO1 is a restricted view. When you run the application module,
PersonsVO1 can display all rows of person data, but OrdersVO1 can display only
the order data associated with the current person. When you add a view to your
application module’s data model, you can add it as an unrestricted view or as a
restricted view.

207
.
Features of an AM
The application module acts as a wrapper for the views and entities in your business model. It
also handles all database transactions and performs tasks that are specific to the application.
An application module performs a specific application task—for example, logging service
requests or processing user information. An application module has the following main
characteristics:
• It represents the data model that your client uses and has one connection to the database.
• It enables you to gather data customized to a client interface (such as a form), so that data
can be retrieved in one network round-trip instead of multiple trips.
• It can contain other application modules, called nested application modules, enabling you
to separately develop, test, and then reuse the application module functionality.
• It keeps track of all changes that affect data in the database and defines the transactional
model.
• It provides remotely accessible methods, which implement the application module
behavior.
• You can deploy the same application module in multiple configurations.
• As discrete units, application modules are easily reused in the business logic tiers of other
applications.

208
.
209
.
Defining the Data Model for the Application Module
The application module contains an active data model of the view objects and view link
instances required for the task that the application module performs. When you create the
application module, you need to define all the view objects that are part of the application
module. All view objects contained within the current package are available to be included.
Select the view objects required and click the right arrow to include them in the data model. To
remove a view object from the data model, select it in the Data Model section and click the left
arrow.
By default, the wizard creates instance names for the data model components based on their
corresponding view object names. You might want to change the instance name based on its
function or hierarchical placement. In the example in the slide, you might rename the nested
instance to “AddressesPerPerson,” because the wizard generates a less clear instance name,
“AddressesVO1 via PersonAddressVL1” by default.

210
.
211
.
212
.
Using Master-Detail View Objects (Data Model) in Application Modules
When you run an application module in the Business Components Browser, or when you use an
application module’s data control in a user interface, you need to be aware of the levels of VO
instances that are shown in the BC Browser or the Data Controls panel:
• The first level, displayed just under the application module in the hierarchy, shows
independent instances of view objects.
• Any subordinate levels show instances of view objects that are accessed via a view link.
These are child VO instances of the independent VO instance on the first level, and
therefore contain only rows related to the current row of the master VO. There may be
multiple detail levels, each showing related records of its direct master VO.
In the example in the slide, OrderVO1 contains only the orders belonging to the current row in
CustomerVO1. OrderVO2 contains all orders, unless restricted by a WHERE clause or view
criteria.

213
.
Transactions in ADF BC
An application module is a transactional container for a logical unit of work, so any updates, inserts, or
deletes for all view objects in the application module are committed or rolled back at once. The
outermost, or root, application module provides the transaction context for all nested application
modules.
At run time, the application module delegates transaction management to a companion Transaction
object, which provides an entity cache as a work area to hold entity rows involved in the current user’s
transaction. Each entity cache contains rows of a single entity type, so a transaction involving two or
more entity objects holds the working copies of those entity rows in separate caches. The entity cache is
also the place where new entity rows wait to be saved.
When an entity row is created, modified, or removed, it is automatically enrolled in the transaction’s list
of pending changes. When you call commit() on the Transaction object, it processes its pending changes
list, validating new or modified entity rows that might still be invalid. When the entity rows in the
pending list are all valid, Transaction issues a database SAVEPOINT and coordinates saving the entity
rows to the database. If all goes successfully, it issues the final database COMMIT statement. If anything
fails, Transaction performs a ROLLBACK TO SAVEPOINT to allow the user to fix the error and try again.
When a root application module contains other nested application modules, they all participate in the
root application module’s transaction and share the same database connection and a single set of entity
caches. This sharing is handled for you automatically by the root application module and its Transaction
object. You should keep this transaction context in mind when designing the application. If you want
separate transactions, do not nest the application modules.
For example, you may have an InventoryManagerAM application module that has methods to add or
subtract from inventory. It would make sense to nest this application module inside a customer-facing
ShoppingAM. When the customer submits an order, you could subtract the ordered items from the
inventory as a part of the same transaction. If the commit fails, the order does not get submitted, and
inventory changes are rolled back as well. It would not make sense, however, for you to nest the
inventory management application module inside one that manages human resources. HR transactions,
such as hiring or salary changes, should be completely separate transactions from inventory
management.

214
.
Nested Application Module
Application modules support the ability to create software components that mimic the
modularity of your use cases, for which your higher-level functions might reuse a subfunction
that is common to several business workflows. You can implement this modularity by defining
composite application modules that you assemble using instances of other application
modules. This task is referred to as application module nesting. That is, an application module
can logically contain one or more other application modules, as well as view objects. The
outermost containing application module is referred to as the root application module.
Any application module can be used as a root application module, but it would usually be one
that maps to a more complex use case. When a root application module contains other nested
application modules, they all participate in the root application module’s transaction and share
the same database connection and a single set of entity caches. This sharing is handled for you
automatically by the root application module and its Transaction object.
When you nest an instance of one application module inside another, you aggregate not only
the view objects in its data model, but also any service methods it defines. This feature of
nesting, or reusing, an instance of one application module inside of another is one of the most
powerful design aspects for implementing larger-scale, real-world application systems.
The example in the slide shows that the InventoryAM application module contains nested
application module instances of StockAM and ProcureAM, in addition to view object instances.

215
.
216
.
217
.
Shared Application Module
Web applications often utilize data that is required across sessions and does not change much.
An example of this type of static data might be displayed in a lookup list. Accessing static data
can incur an unnecessary overhead when static data caches are repopulated from the database for
each application session on each request. In order to optimize performance, a common practice
when working with ADF Business Components is to cache the static data for reuse across
sessions and requests.
Shared application modules allow requests from multiple sessions to share a single application
module instance which is managed by the application pool for the lifetime of the Web server
virtual machine. In the case of application-level sharing, any user session will be able to access
the same view instances contained in the shared application module. In contrast, the life cycle of
the session-level shared application module extends to a user session. In this case, view instances
of the application module will be accessible by other components in the same user session.
You specify that an application module is to be shared in the Project Properties dialog box:
1. Double-click the name of the project that contains the application module, to invoke the
Project Properties dialog box.
2. In the panel on the left, expand the Business Components node and select Application
Module Instances.
3. Click the Application or Session tab to define whether the instance is to be application
scoped or session scoped.
4. Select the AM to be shared in the Available tree on the left and use the arrow to shuttle it
to the Application Module Instances pane on the right.
5. You can change the name of the instance if required. Click OK to create the instance.

218
.
Application Module Pooling
An application module pool is a collection of application module instances of the same type,
such as an Orders application module or a Human Resources application module. This pool of
application module instances is shared by multiple browser clients. The amount of time
between submitting Web pages enables a smaller number of application module components
to serve a larger number of active users. This reduces memory usage and improves
performance.
At any one time, the pool may contain application module instances that are partitioned into
three groups, based on their state. When the processing of a current HTTP request completes,
the application module instance is checked back into the pool. If the AM instance has managed
state, the pool keeps track that the AM is referenced by that particular session.
An application module instance in the pool may be:
• Unconditionally available for use
• Available, but referenced for preferred reuse by a certain active session because that would
be more efficient due to the managed state of the application module
• Unavailable because it is being used at that very moment by a Web container thread.
You can configure application module pool behavior, sizing, and cleanup behavior. For more
information about this, refer to the Fusion Developer’s Guide for ADF in online Help.
Note: Pools are created only for root application modules, not for nested ones that users
access indirectly through a root application module.

219
.
220
.
221
.
State Management in Application
HTTP is a stateless protocol. ADF model supports both stateless applications as well as those
involving a unit of work that may span multiple pages.
An application module supports passivating its pending transaction state to an XML document,
which is stored in the database in a single, generic table, keyed by a unique passivation
snapshot ID. It also supports the reverse operation of activating pending transaction state from
one of these saved XML “snapshots.”
You can demonstrate passivation in the Business Components Browser by making changes
without saving them, and then selecting File > Save Transaction State. A dialog box displays the
transaction key ID. Then close and reopen the BC Browser; it displays the original data without
your changes. Select File > Restore Transaction State to restore the pending changes, which you
can then commit to the database if desired.
Passivation and activation are performed automatically in an ADF BC application by the
application module pool. This automatic state management provides the simplicity of a stateful
programming model that is nearly as scalable as a completely stateless application.

222
.
Application module state management
Since an application module is responsible for the transaction management of an application, it
includes some of the settings and configurations for high availability and to maintain the state
of the application. High availability is a concept in which the state of an application is
maintained even when the handshake between servers occurs in a clustered environment. In
this context, a handshake means that when a server goes down, the clustered server gets
another server up and running to maintain the state of the application.

For example, a user connects to a website that is hosted on a clustered server and gets
connected to Server1 of that cluster. The user starts creating a new record at the same time
that Server1 goes down for maintenance. At such a time, the user data should not be lost, and
the user should be allowed to continue with the creation of the record. For this to happen, the
state of the application has to be maintained so that the state of the application is transferred
from Server1 to Server2, and the user will not see the change in the state of the application.

Passivation is done in the server to store the state of the application, and the passivation state
can be stored in a flat file or a database. Activation reloads the state of the application at the
point where it was left. The two APIs that are helpful in the application module for high
availability are assivateState() and activateState().The failover feature is enabled by setting the
value of jbo.dofailover to true in the application module. With this setting, the passivation state
will occur at the end of every request.

223
.
ADF Model
Developers need a standard way to bind services to Java UIs and to simplify the use of different
service implementations in the model. As a developer, you need to know and understand the
specifics of the technology that is used to persist data in your application. It is time consuming
to write boilerplate code to create interactions between UI components and services.
ADF Model provides a generalized approach. ADF Model offers a layer of abstraction,
describing the middle-tier business services to the view, so that the developer is insulated from
the specifics of the underlying service implementation. Instead of binding the view to the
business services, you bind the view to the model, and the model is bound to the business
service by a data control and exposed to the developer through a binding. In short, ADF Model
provides a common API to bind data from a business service to a UI. Out-of-the-box, ADF
Model supports data controls for services based on Java classes, EJB session beans, Web
services, and ADF Business Components.
Data controls are an ADF Model layer that represents the back-end business services. Each time
you create an ADF BC application module, a data control is automatically created that contains
all the view object instances and client methods that are exposed in the application module.
Data control is what enables you to bind UI components to the back-end data.

224
.
Estimate the Size of an AM
An application module represents the logical data model to accomplish a specific user task.
In the early analysis phases of application development, architects and designers often use
UML use-case techniques to iteratively refine a high-level description of the different kinds of
business functions that the system needs to support. Each high-level, end-user use case
identified during the design phase should generate the following considerations:
The domain business objects involved: What core business data is relevant to the use case?
The user-oriented view of business data required: What subset of columns, what filtered set
of rows, sorted in what way, grouped in what way is needed to support the use case?

225
.
Creating an Application Module
When you create an application module, JDeveloper creates the XML component definition file
that represents its declarative settings and saves it in the directory that corresponds to the
name of its package. For example, given an application module named PersonAM in the
oracle.model package, the XML file created is ./oracle/model/PersonAM.xml under the
project’s source path. This XML file contains the information needed at run time to re-create
the view object instances in the application module’s data model. You can view the contents of
this XML file by selecting the view object in the Application Navigator and looking in the
corresponding Sources folder in the Structure Window. Double-clicking the name of the XML
file opens it in an editor so that you can inspect it.
After you have created your application module, you can edit any of its settings by using the
Application Module Editor. To launch the editor, select Edit from the context menu in the
Application Navigator, or double-click the application module.

226
.
227
.
228
.
Lesson Agenda
This lesson teaches you to customize business components to change the data behavior for the
application. You learn to make various declarative modifications to the data model. You then
test the modified functionality with the Business Components Tester.

In Hands-on lab one would practice:


1. Customizing Entity Objects by Defining Control Hints
2. Customizing View Object by Adding Transient Attribute
3. Defining List of Values and Accessors
4. Creating View Object with Parameterized Where Clause

Optionally you may also practice:


1. Creating and Using Parameterized View Criteria
2. Creating Alternate Key Entity Constraints
3. Declaratively Populating Primary Key with a Database Sequence

229
.
Introduce Groovy
Groovy is an agile, dynamic language for the Java platform, defined as JSR 241. It has many
features that were inspired by languages such as Python, Ruby, and Smalltalk, making them
available to Java developers with a Java-like syntax. It interoperates seamlessly with any Java
class, and can be compiled and interpreted without disturbing normal operations.
The latest release of JDeveloper provides integrated support for Groovy. You can use Groovy
expressions for all sorts of declarative values, such as bind variables and attribute default
values. You can use a Groovy script that returns true or false for declarative validation. You can
also use Groovy expressions in error messages. You see examples of using Groovy expressions
when these different topics are presented in this lesson and later lessons.
Groovy can simplify expressions and make them more concise in that it supports object access
via dot-separated notation, so it supports syntax such as Empno instead of
getAttribute(EMPNO).
You can find out more about Groovy at http://groovy.codehaus.org/ and
http://radio.weblogs.com/0118231/2007/05/22.html#a829.
Note: Groovy is still a fairly new technology and is missing features such as code completion
and debugging capabilities. This makes it difficult to use for large segments of code

230
.
231
.
232
.
Groovy Syntax in ADF
The current object is passed into the script as the “this” object. So, to reference any attributes inside the current object, simply use the
attribute name. For example, in an attribute-level or entity-level Script Expression validator, to refer to an attribute named “Salary,” the script
may say simply reference Salary. There is one top-level reserved name, adf, to get to objects that the framework makes available to the Groovy
script. These objects include:
• adf.context: To reference the ADFContext object
• adf.object: To reference the object on which the expression is being applied
• adf.error: In validation rules, to access the error handler that allows the validation expression to generate exceptions (adf.error.raise) or
warnings (adf.error.warn)
• adf.currentDate: To reference the current date with time truncated
• adf.currentDateTime: To reference the current date and time
All the other accessible member names come from the context in which the script is applied:
• Bind Variable: The context is the variable object itself. You can reference the structureDef property to access other information as well as the
viewObject property to access the view object in which the bind variables participate.
• Transient Attribute: The context is the current entity or view row. You can reference all attributes by name in the entity or view row in which
it appears, as well as any public method on that entity or view row. To access methods on the current object, you must use the adf.object
keyword to reference the current object like this: adf.object.yourMethodName(). The adf.object keyword is equivalent to the this keyword in
Java. Without it, in transient expressions, the method is assumed to exist on the dynamically compiled Groovy script object itself.
• Expression Validation Rule: The context is the validator object (JboValidatorContext) merged with the entity on which the validator is
applied.
You can reference keywords such as:
- newValue, in an attribute-level validator, to access the attribute value being set
- oldValue, in an attribute-level validator, to access the current value of the attribute being set
- source, to access the entity on which the validator is applied in order to invoke methods on it (accessing simply by using attribute values in
the entity does not require using the source keyword).
All Java methods, language constructs, and Groovy language constructs are available in the script. Some additional tips to keep in mind:
• You can use built-in aggregate functions on ADF RowSet objects by referencing the functions sum(), count(), avg(), min(), and max(). They
accept a string argument, which is interpreted as a Groovy expression that gets evaluated in the context of each row in the set as the
aggregate is being computed:
rowSetAttr.sum("GroovyExpr") such as employeesInDept.sum("Sal") or employeesInDept.sum("Sal!=0?Sal:0 + Comm!=0?Comm:0")
rowSetAttr.count("GroovyExpr"), rowSetAttr.avg("GroovyExpr"), rowSetAttr.min("GroovyExpr"), rowSetAttr.max("GroovyExpr")
• Use the return keyword just like in Java to return a value, unless it is a one-line expression in which case the return is assumed to be the
result of the expression itself (such as Sal + Comm or Sal > 0).
• Use the ternary operator to implement functionality that is similar to SQL’s NVL() function—for example, Sal + (Comm != null ? Comm : 0).
• Do not use { } to surround the entire script. Groovy treats { as a beginning of a Closure object. (See Groovy documentation for more
information about Closures.)
• Any object that implements oracle.jbo.Row, oracle.jbo.RowSet, or oracle.jbo.ExprValueSupplier is automatically wrapped at run time into a
Groovy “Expando” object to extend the properties available for those objects beyond the bean properties. This enables easy reference to ADF
row properties (even if no Java class is generated) and avoids introspection for most used names.

233
.
References for Groovy

234
.
Internationalization of Business Services
Many of the declarative modifications that you make to the data model involve text, such as
labels or messages. ADF makes it easy to translate such text by offering the option to store it in
resource bundles. You can use one resource bundle for the entire project or a separate one for
each file.
Resource bundles are properties files containing translatable strings stored with key values and
optionally with descriptions that are stored as comments. For example, the label for the
OrderDate field of the Orders entity object is stored as:
#Used for the label of Orders.OrderDate ORDER_DATE=Order Date
where ORDER_DATE is the key, Order Date is the translatable string, and the first line is the
description. Although the description suggests the usage, the string can be used anywhere.
To provide multiple languages, a translator needs only to copy the properties file and append
_<locale> to the name. For example, the properties file depicted in the slide may have a
German translation; the name of that file would be Project1Bundle_de.properties.
All the translations should be stored in the same directory.
When you configure the user interface to support multiple translations as explained in the
lesson titled “Planning the User Interface,” which translation is used depends on the client’s
browser settings.

235
.
Editing Entity Objects
You can access all the properties of entity objects, associations, view objects, view links, and
application modules by using the object editors and the property inspectors.
You can open the flat editor for an object by double-clicking the component in the Application
Navigator, or by right-clicking it and selecting Open from the context menu. The flat editor is
nonmodal, with collapsible headers.
The editor enables you to edit the .xml file for the entity object. You can edit it declaratively on
the Overview tab, although in rare instances you may need to edit it directly by clicking the
Source tab at the bottom of the editor. The History tab enables you to see changes that have
been made and to reverse those changes if desired.
In addition to the editors, the Property Inspector enables you to edit business components. If
the Property Inspector is not visible, you can display it by selecting View > Property Inspector.
The Property Inspector also has tabs to access panels that display various categories of
properties for the selected object. If the property is also displayed in the editor, its value is
synchronized so that a value change is reflected in both places. The Property Inspector may also
display some properties of objects that are not accessible in the editor for that object.
The Property Inspector features a search bar and a toolbar; these are described thoroughly in
the lesson titled “Getting Started with JDeveloper.”

236
.
Customize EO’s Default Behavior
JDeveloper 12c has the ability to define more behaviors declaratively than did earlier
JDeveloper versions. This reduces the learning curve and the amount of time it takes to develop
applications.
The subsequent slides provide some examples of ways to declaratively modify the default
behavior of entity objects.

237
.
238
.
Customize Attribute Control Hints
One of the many powerful, built-in features of ADF Business Components is the ability to define control
hints on attributes. Control hints are additional attribute settings that the view layer can use to
automatically display the queried information to the user in a consistent, locale-sensitive way. Control
hints set on view objects override those set at the entity object level.
To add control hints for an entity object or a view object attribute, perform the following steps:
Open the object editor, select the Attributes node in the tree at the left, select the attribute, and click
Edit.
In the attribute editor, click Control Hints, and set the desired properties. To add text to a resource
bundle, click the ellipsis (…) next to the text.
Add the displayed value, accept the generated key or change it, and then click “Save and Select” to use
the new text resource.
You can set the following control hints:
Display Hint: Determines whether the attribute should be displayed
Label Text: Changes the default label for the attribute. Labels are prompts or table headers that
precede the value of a field.
Tooltip Text: Sets text to appear in tooltip or the <ALT> attribute of HTML
Format Type: Sets the formatter to use, such as currency or number for a number attribute
Format: Sets the format to use. Select a format from a list or enter any Java format that is valid for that
type.
Control Type: Specifies the type of control that the UI displays
Display Width: Sets the character width to be used by the control that displays this attribute
Display Height: Sets the number of character rows to be used by the control that displays this attribute
Form Type: Specifies whether the attribute is displayed in detail or Lesson Summary style layout (not
valid for Web applications)
Auto Submit: When enabled (true) , Auto Submit triggers a partial submit on value
changes in the user interface. The default is false.

239
.
Customize EO’s Default Behavior
JDeveloper 12c has the ability to define more behaviors declaratively than did earlier
JDeveloper versions. This reduces the learning curve and the amount of time it takes to develop
applications.
The subsequent slides provide some examples of ways to declaratively modify the default
behavior of entity objects.

240
.
Alternate Key Entity Constraints
Alternate keys are first class key citizens in ADF BC, and are stored in a hashmap for fast
access. They are useful for:
• Efficient uniqueness checks in the middle tier via the Unique Key validator
• Direct row lookups via the findByKey() class of methods
They differ from:
• Primary keys in that it is possible to define any number of multipart alternate keys
• Unique keys in that those are used primarily for forward generation of UNIQUE constraints
in the database
For example, if you want to be able to locate a Department entity instance based either on the
unique DepartmentId (primary key) or the DepartmentName, you can define an alternate
key for the DepartmentName attribute. You can then use this named alternate key in the new
findByAltKey() entity object API, or you can reference it in a Unique Key validator to
automatically enforce that two departments cannot have the same DepartmentName value.

To create an alternate key entity constraint, perform the following steps:


1. Select an entity object and run the New Entity Constraint Wizard.
2. Name the constraint.
3. Select the columns to use.
4. Select the Alternate Key constraint type. You may elect to make the Alternate Key
attributes mandatory, which will be automatically validated at run time by the implicit
entity-level MandatoryAttributesValidator, which loops through all mandatory
constraints on the row.
If you want to check the uniqueness of the key, you must explicitly add an entity-level Unique
Key validator on the Alternate Key attributes. Adding a validator is explained in the lesson titled
“Validating User Input.”

241
.
Customize EO’s Default Behavior
JDeveloper 12c has the ability to define more behaviors declaratively than did earlier
JDeveloper versions. This reduces the learning curve and the amount of time it takes to develop
applications.
The subsequent slides provide some examples of ways to declaratively modify the default
behavior of entity objects.

242
.
Synchronize Columns 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 check
boxes 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 built-in data type
DBSequence. Setting this data type automatically enables the Refresh After Insert property.
When you create a new entity row whose primary key is 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.
Note: The sequence name shown on the Sequence tab applies only at design time when you
create a database table from an entity object. The sequence indicated on this tab is created
along with the table on which the entity object is based.

243
.
Editing View Objects
You can invoke the view object editor by double-clicking the view object in the Application
Navigator, or by right-clicking it and selecting Edit <VO Name> from the context menu.
The editor enables you to edit the .xml file for the view object. You can edit it declaratively on
the Overview tab, although in rare instances you may need to edit it directly by clicking the
Source tab at the bottom of the editor. The History tab enables you to see changes that have
been
made and to reverse those changes if desired.
When you click the Overview tab, you are presented with navigation tabs that contain the
following categories:
• General: Set custom properties, tuning, or alternate keys for the view object.
• Entity Objects: Modify or add entity objects on which to base the view object.
• Attributes: Modify or add attributes or define custom properties or lists of values.
• Query: Modify the SQL query and set bind variables or view criteria.
• Java: Generate Java files or expose custom methods to client applications.
• View Accessors: Define a set of possible values for a given foreign key; used mainly for
validation and for lists of values.
• List UI Hints: Specify default display settings for the view object when used as a list in
the UI.

244
.
Customizing VO’s Default Behavior
The next few slides present several examples of the ways in which you can declaratively modify
the default behavior of view objects.

245
Defining View Object Control Hints
View objects use the control hints from their associated entity objects, so you would not
normally need to define them at the view object level. It is better to define them for the entity
object so that displays are consistent throughout the application.
However, you can define the same control hints for view objects as you can for entity objects. If
there is a control hint defined for a view object, it overrides the one defined at the entity object
level.
There may be cases where you would want to override the entity object control hints for a
specific view, such as the following:
• You may need to display the data differently in different views. For example, in an
application’s entity objects, you may define the label for all of the primary key items as ID,
such as for ProductId, SupplierId, WarehouseId, and so on. But if you have a particular
view that displays the IDs of multiple referenced entity objects, for that view object you
may want to override the entity-level label for those IDs, as described in the slide.
• You may display the same attribute twice in a view. For example, imagine defining the
Label UI hint for the Ename attribute of the Emp EO to be the string “Employee’s Name.”
If there is an association that relates the Emp EO to itself via the relationship (Emp.Mgr =
Emp.Empno), you may create a View Object that includes the Emp EO usage twice, once
to include employee information and again to display information about that employee’s
manager. In the context of this VO, you might have the Ename attribute from the base
Emp EO as well as the Ename attribute to show the name of the employee’s manager. If
you allow the inherited EO-level UI hints to be used, both the employee’s name and the
manager’s name in this view object will use the inherited UI control hint label of
“Employee’s Name.” You can define the VO-attribute-level UI hint for the
ManagerEname view object attribute to have the hint “Manager’s Name” to clarify the
situation, which will override the inherited “Employee’s Name” hint for that attribute.
In addition to the attributes that are based on entity objects, you may have some transient
attributes that are defined only at the view object level, so you may want to define control hints
for those.

246
.
Performing Calculations
You can calculate the value of an attribute by entering an expression.
For example, a view object based on OrderItemEO may have a transient attribute called
LineTotal. To implement a calculation for that attribute, perform the following steps:
1. Invoke the attribute editor for LineTotal.
2. In the View Attribute panel:
a. Select the Expression option for Value Type. Expressions can use the Groovy
expression language and can reference attributes from the view object definition.
b. Enter the calculation for Value: UnitPrice*Quantity.
c. In the Dependencies panel, shuttle Quantity and UnitPrice to the Selected list. This
ensures that the value for LineTotal is recalculated whenever the value for either
Quantity or UnitPrice changes.

247
.
Projecting (Restricting) and Reordering the Columns Retrieved by a Query
The Attributes tab of the view object editor enables you to restrict the columns retrieved by the
query by deleting attributes. You can also add attributes, either new ones or, for entity-based
views, attributes based on columns that exist in the entity object. You can also change the
order
in which the attributes appear in the query statement.
The example in the slide shows an existing query that selects PRINCIPAL_NAME, TITLE,
FIRST_NAME, LAST_NAME, and some other columns. After deleting and reordering attributes,
the query is changed and no longer selects the deleted PRINCIPAL_NAME and TITLE
columns, and the order in which LAST_NAME and FIRST_NAME are selected is reversed.

248
.
Changing the Order of Queried Rows
You can set an ORDER BY clause on the query by clicking the Query tab of the view object
editor. To invoke the Edit Query dialog box, click Edit (pencil icon) in the Query section of the
panel. Enter an ORDER BY clause (without the ORDER_BY keyword). If you click Edit to the
right of the Order By field, you invoke a dialog box that enables you to select the columns and
construct the ORDER BY clause.

249
.
Use of View Criteria
Instead of changing WHERE clauses by using string manipulation, you may find it more efficient to use view criteria
to assemble complex WHERE clauses. View criteria are named expressions that you can use to assemble a WHERE
clause.
A view criteria row specifies query-by-example requirements for one or more view object attributes. For example,
suppose the view object definition CustOrdVO includes the following attributes: LastName, OrderTotal, and
DiscountId. Then a view criteria row for an instance of CustOrdView could specify requirements for each of these
attributes, such as: LastName STARTSWITH “S”, OrderTotal > 500, and DiscountId <> NULL.
Another view criteria row for this instance could specify different requirements for a different set of attributes,
such as: OrderTotal > 1000, and CreditLimit > 5000.
For a view criteria row to be satisfied, all of its attribute requirements must be met.
View criteria are made up of collections of view criteria rows. For the view criteria to be met, at least one of the
rows must be satisfied. For example, if vc1 has the requirements: OrderTotal > 500, CreditLimit > 2500, and
DiscountId <> NULL, and vc2 has the requirements: OrderTotal > 1000 and CreditLimit > 5000, then the complete
view criteria are equivalent to the following WHERE clause condition:
(OrderTotal > 500 AND CreditLimit > 2500 AND DiscountId <> NULL) OR
(OrderTotal > 1000 AND CreditLimit > 5000)
You can define view criteria at design time and apply them in the Business Components Browser to test them.
Also, you can use bind variables for view criteria values.
The Query Execution Mode sets the source from which the view object retrieves rows. You can set it to:
Database (default): Limits the results of the filtered view object to the database table specified by the query
In Memory:
Limits the results to the in-memory results of the view object query
Uses rows already in the row set
Can be used to progressively refine the row set contents through in-memory filtering
Prevents unnecessary database access
Both: Is useful when you have newly created, but not yet committed, results in the row set that you want to filter
and combine with filtered results from the database table

250
.
251
.
Role of View Criteria in Search
The view criteria that you define in the model facilitate the production of search forms required
in the UI. The view criteria object is a row set of one or more view criteria rows, whose
attributes mirror those in the view object. The view criteria definition comprises query
conditions that augment the WHERE clause of the target view object. Query conditions that
you specify apply to the individual attributes of the target view object.
The Edit View Criteria dialog box lets you create view criteria and save them as part of the view
object’s definition, where they appear as named view criteria. You use the Query page of the
overview editor to define view criteria for specific view objects.
The example in the slide shows the definition of a view criteria, SearchByName, on the
BrowseProductVO view object.
When the view objects are created and specified as instances in an application module,
JDeveloper automatically creates a data control to encapsulate the collections (view instances)
that the application module contains. JDeveloper then populates the Data Controls panel with
these collections and any view criteria that you have defined, as shown on the right in the
example in the slide. The SearchByName named criteria, part of the BrowseProduct collection
in the FODProductAMDataControl, is available to be dropped onto the page for the creation of
a Search form (as you learn in the lesson titled “Adding Functionality to Pages” in this course).

252
.
Creating View Accessors
View accessors facilitate traversing from a detail record to all the associated master records. For
example, a view accessor could enable you to traverse from an employee to all the
departments the employee is allowed to join, rather than just to the department the employee
is currently in. View accessors are commonly used both in validation, which is discussed in the
lesson titled “Validating User Input,” and in lists of values, which is discussed next.
You can define view accessors for entity or view objects, but defining them at the entity level is
usually preferable because it enables access by any view object that is based on that entity. You
can define a view accessor to any view object in the same workspace. Simply click “Create new
view accessors” on the View Accessors tab of the EO or VO editor, and then in the View
Accessors dialog box, select the view object or objects to access. You can create multiple view
accessors at once.
If the view accessor retrieves a view object on which view criteria or bind variables are defined,
you can optionally use those for the view accessor to restrict the rows that are retrieved, and
you can also add an ORDER BY clause. To choose these options, with the view accessor selected
in the View Accessors dialog box, click Edit. You can also set these options after creating the
view accessor by editing it.

253
.
Using a List of Values (LOV)
You can define LOVs on view object attributes. LOVs use view accessors as a data source:
For an attribute that is mapped to an entity object, you normally use the same underlying
entity object view accessor that is used by the Key Exists validator for the underlying EO
attribute. The entity object view accessor can be extended at the view object level to either
change the UI Hints or change bind expressions.
You can define view object view accessors to be used for transient attributes that are not
mapped to entity object attributes.

254
.
255
.
Customizing AMs
The application module editor contains several tabs that enable you to declaratively modify
aspects of the application module, as listed in the slide. You learn more about modifying
application modules as you complete the course application.

256
.
Application Module Parameters
The application module pool manager is controlled by parameters that you set in the
application module configuration. You find the parameters by editing the application module
configuration. To edit the configuration, right-click the application module and select
Configurations. Then click the Edit button. This opens the Business Component Configuration
Wizard. Click the Properties tab to see and edit the configuration properties.
The parameters are listed in alphabetical order by default. The properties that control the
application module pool manager begin with jbo.ampool.

Removing Instances
Application module instances are removed from the pool as follows: The pool manager
compares the number of inactive, available instances in the pool against the minimum available
instance size. If the number of inactive, available instances is greater than the minimum
available instance size, then the pool will attempt to remove any inactive, available instances.
An inactive instance is defined as an instance that has been unused for a period longer than the
pool’s maximum inactive age. The pool will continue to remove inactive, available application
module instances until the minimum available instance size has been reached or there are no
more inactive, available instances.

257
.
Modifying the Locking Behavior of an Application Module
By default, the application module uses pessimistic locking, which means that a lock is issued
on a database row when an application changes data in that row.
Oracle recommends using optimistic locking for Web applications. A lock is acquired only just
before posting changes to the database, and the application module instance can be
immediately released when a Web page terminates. This provides the best level of
performance for Web applications that expect many users to access the application
simultaneously.
To change your configuration to use optimistic locking, perform the following steps:
Click the Configurations tab of the Application Module editor.
Select a configuration and click Edit.
On the Properties tab of the Configuration Editor, set the value of the
jbo.locking.mode property (default value is pessimistic) to one of the following:
optimistic: Issues a SELECT FOR UPDATE statement to lock the row for both
updates and deletes, then detects whether the row has been changed by another user by
comparing the change indicator attribute if there is one, or the values of all the persistent
attributes of the current entity as they existed when fetched into the cache
optupdate: Optimistic locking only for updates; the UPDATE statement
determines whether the row was updated by another user by including a WHERE
clause that matches the existing row; an update occurs if attributes remain unchanged since
fetch

258
.
259
.
260
.
Lesson Agenda
This lesson covers data validation options for ADF BC applications. You learn when each option
is most suitable. You create and use validation methods and declarative validation, and you
create and use a domain for validation.

In Hands-on lab one would practice:


1. Adding Declarative Validation: Range Validator
2. Generating Java Files for Entity Objects
3. Adding Method Validator

Optionally you may also practice:


Adding Declarative Validation: Unique Key Validator

261
.
Validation Options for ADF BC Applications
There are various options for handling validation in ADF BC applications:
Business services: You should build in as much validation as you can when creating the business services in order to protect the integrity of the
data in the database and to prevent malicious attacks. There are a multitude of opportunities to add validation at the business services level:
- Oracle ADF Business Components provides a number of predefined validation rule classes that enable you to add business logic without
writing a single line of code, or you can also add programmatic validation.
Database (PL/SQL): You can implement validation in the database; however, such validation cannot be exposed in the UI. For example, you
cannot use database validation to expose a list of valid values in the UI.
User interface: The ADF Faces input components that you use to build the pages of your application also have built-in validation capabilities.
You use these prebuilt ADF Faces validators to ensure that when a user edits or enters data in a field and submits the form, the data is
validated against the rules and conditions you have specified. However, UI validation should always have equivalent validation at the business
services layer, so that the same validation is applied when the model is exposed in other ways.
There are various opportunities for adding validation in ADF BC applications (as shown in the
slide), but be aware that they can create an overhead in terms of managing them; keeping them in synch with each other is a manual process.
Take the example of a data structure, Person, which represents the concept of a Person entity known to the business. This Person must have a
gender and that gender’s value can be either Male or Female. You define a simple business rule with a name, optionality, and domain. This
rule can easily end up being implemented in different places (as described below).
You create a relational table in the database and create a column called gender and make it a mandatory column. The table’s DDL is one
implementation of the part of the rule. If you add a SQL check constraint (gender = male or gender = female), you have completely
implemented the rule in the table and have a single location to maintain.
However, in most object-oriented (OO) systems today, you need a software object to represent this rule through Object-Relational Mapping
(ORM). So now you need a class named Person and an attribute named gender. You could code this in Java and use JEE/JPA or ADF BC to
provide the support for ORM. This is not the problem. The problem is that you want to implement that rule closer to the client. You can thus
implement the rule in the class itself and have the class test the gender value before it gets back to the database. So, the rule is now
implemented in two languages in two places.
But if this is a Web application, you might want to have the rule enforced in the client, before getting back to the Java class in the server. So,
now you implement the rule in JavaScript. The rule is now implemented in three languages and platforms.
And it does not stop there. If you wanted to expose the Person functionality via a Web server, you might code the rule there also, or in
different languages for different applications. It would not be unusual, over time to see this same gender rule implemented in DDL, SQL,
PL/SQL, Java, JavaScript, an EJB, a Web Service , C++, .Net, BPEL, a rules engine for SOA systems, and so on.
Eventually the rule may need to be changed, or extended. How do you know all the places to change it? How do you know if you have found
and changed them all? And, how do you know it was changed or implemented correctly and consistently in all the different places?
Thus, you see that adding validation in the necessary places to protect your data is only part of the task; managing the maintenance of it is
equally important.

262
.
263
.
Validation Options for ADF BC Applications
There are various options for handling validation in ADF BC applications:
Business services: You should build in as much validation as you can when creating the business services in order to protect the integrity of the
data in the database and to prevent malicious attacks. There are a multitude of opportunities to add validation at the business services level:
- Oracle ADF Business Components provides a number of predefined validation rule classes that enable you to add
business logic without writing a single line of code, or you can also add programmatic validation.
Database (PL/SQL): You can implement validation in the database; however, such validation cannot be exposed in the UI. For example, you
cannot use database validation to expose a list of valid values in the UI.
User interface: The ADF Faces input components that you use to build the pages of your application also have built-in validation capabilities.
You use these prebuilt ADF Faces validators to ensure that when a user edits or enters data in a field and submits the form, the data is
validated against the rules and conditions you have specified. However, UI validation should always have equivalent validation at the business
services layer, so that the same validation is applied when the model is exposed in other ways.
There are various opportunities for adding validation in ADF BC applications (as shown in the
slide), but be aware that they can create an overhead in terms of managing them; keeping them in synch with each other is a manual process.
Take the example of a data structure, Person, which represents the concept of a Person entity known to the business. This Person must have a
gender and that gender’s value can be either Male or Female. You define a simple business rule with a name, optionality, and domain. This
rule can easily end up being implemented in different places (as described below).
You create a relational table in the database and create a column called gender and make it a mandatory column. The table’s DDL is one
implementation of the part of the rule. If you add a SQL check constraint (gender = male or gender = female), you have completely
implemented the rule in the table and have a single location to maintain.
However, in most object-oriented (OO) systems today, you need a software object to represent this rule through Object-Relational Mapping
(ORM). So now you need a class named Person and an attribute named gender. You could code this in Java and use JEE/JPA or ADF BC to
provide the support for ORM. This is not the problem. The problem is that you want to implement that rule closer to the client. You can thus
implement the rule in the class itself and have the class test the gender value before it gets back to the database. So, the rule is now
implemented in two languages in two places.
But if this is a Web application, you might want to have the rule enforced in the client, before getting back to the Java class in the server. So,
now you implement the rule in JavaScript. The rule is now implemented in three languages and platforms.
And it does not stop there. If you wanted to expose the Person functionality via a Web server, you might code the rule there also, or in
different languages for different applications. It would not be unusual, over time to see this same gender rule implemented in DDL, SQL,
PL/SQL, Java, JavaScript, an EJB, a Web Service , C++, .Net, BPEL, a rules engine for SOA systems, and so on.
Eventually the rule may need to be changed, or extended. How do you know all the places to change it? How do you know if you have found
and changed them all? And, how do you know it was changed or implemented correctly and consistently in all the different places?
Thus, you see that adding validation in the necessary places to protect your data is only part of the task; managing the maintenance of it is
equally important.

264
.
Use Declarative Validation: Built-in Rules
The easiest way to create and manage validation rules is through the declarative validation
framework. Oracle ADF is shipped with a number of built-in declarative validation rules that will
satisfy many of your business needs. You implement these rules through the entity object
editor and they are stored in the entity object’s XML file.
You can implement these rules either on the entity object itself, or on its attributes. The next
few slides show how to use the built-in declarative validation rules.

265
.
Use Declarative Validation: Built-in Rules
The easiest way to create and manage validation rules is through the declarative validation
framework. Oracle ADF is shipped with a number of built-in declarative validation rules that will
satisfy many of your business needs. You implement these rules through the entity object
editor and they are stored in the entity object’s XML file.
You can implement these rules either on the entity object itself, or on its attributes. The next
few slides show how to use the built-in declarative validation rules.

266
.
267
.
Use Declarative Validation: Built-in Rules
The easiest way to create and manage validation rules is through the declarative validation
framework. Oracle ADF is shipped with a number of built-in declarative validation rules that will
satisfy many of your business needs. You implement these rules through the entity object
editor and they are stored in the entity object’s XML file.
You can implement these rules either on the entity object itself, or on its attributes. The next
few slides show how to use the built-in declarative validation rules.

268
.
Collection Validator
You can use collection validation to:
Compute the average, count, sum, min, or max of an attribute in a child of the current entity object
Compare the computed value with a literal, a view object attribute, an entity attribute, or the value
returned by a SQL query, a view accessor, or an expression
For example, you could verify that the total value of an order (the sum of its line items) does not exceed
Rs 1,00,000, as depicted in the example in the slide.
When you use a Collection validator, a <CollectionValidationBean> tag is added to the XML file.
You set the following options to define a Collection validator:
Operation: Select sum, average, count, min, or max.
Accessor: Select an association that has been defined for the entity.
Attribute: Select the child attribute on which the operation is to be performed.
Operator: Select equals, not equals, less than, greater than, less than or equal to, or greater than or
equal to.
Compare With: Select literal value, query result, view object attribute, view accessor attribute,
expression, or entity attribute.
Enter Literal Value: Select or define the value with which to compare the calculation.

269
.
Unique Key Validator
like an attribute-level validator; users see the validation error when they attempt to tab out of
the key attribute that the validator is validating.
When you create a Unique Key validator, a <UniqueKeyValidationBean> tag is added to the
entity object’s XML file.

270
.
Use Declarative Validation: Built-in Rules
The easiest way to create and manage validation rules is through the declarative validation
framework. Oracle ADF is shipped with a number of built-in declarative validation rules that will
satisfy many of your business needs. You implement these rules through the entity object
editor and they are stored in the entity object’s XML file.
You can implement these rules either on the entity object itself, or on its attributes. The next
few slides show how to use the built-in declarative validation rules.

271
.
Compare Validator
The Compare validator performs a logical comparison between an entity attribute and another
value. You specify the operator and the value to compare.

272
.
Key Exists Validator
The Key Exists validator checks whether a key exists based on a primary, an alternate, or a
foreign key. It first checks the cache, thus finding rows not yet committed to the database, and
then checks the database if the key is not found in the cache.
When you define a Key Exists validator, after you have selected the rule type in the Add
Validation Rule dialog box, you also specify the following:
Validation Target Type: You can select Entity Object, View Object, or View Accessor. If
you want the Key Exists validator to be used for all view objects that use this entity attribute,
select Entity Object.
If you have chosen the Entity Object target type, you select the Association Name from a
drop-down list. If you have chosen either View Object or View Accessor, you select an entity
attribute and the attribute of the target whose key you are searching, and then click Add to add
the attribute/target pair.
When you use a Key Exists validator, an <ExistsValidationBean> tag is added to the XML file.

273
.
274
.
Length Validator
The Length validator compares the number of characters or bytes in the attribute value against
the specified length. You select the operator and comparison type, and then you set the length
value.
When you use a Length validator, a <LengthValidationBean> tag is added to the XML file.

275
.
List Validator
The List validator compares an attribute against a list that is of one of the following types:
Literal value: Ensures that the value is in, or not in, the list of literal values that you define
Query result: Ensures that the value is in, or not in, the first column of the query’s result set
View attribute: Ensures that the value is in, or not in, the attribute of the specified view object;
all rows are retrieved
View accessor: Ensures that the value is in, or not in, the specified attribute in all rows of
the view object retrieved by the view accessor. This is similar to a view attribute, except that a
view accessor is required to be defined when you want to use an LOV in the user interface.
The example in the slide shows a List validator that ensures that a valid customer ID is entered
for an order. It is based on a view accessor, defined on the OrderEO, that accesses a view object
that queries customers.
When you use a List validator, a <ListValidationBean> tag is added to the XML file.
Note: List validators based on SQL queries or VO attributes retrieve all rows of a query each
time validation is performed. It is recommended that you use these types of List validators only
for a relatively small set of values.

276
.
277
.
278
.
Range Validator
You can use a Range validator to ensure that an attribute falls within, or outside of, specified
minimum and maximum values. This validator performs an inclusive range comparison.
When you use a Range validator, a <RangeValidationBean> tag is added to the XML file.

279
.
Regular Expression Validator
Regular expressions provide a powerful syntax that enables matching strings with particular
characters, words, or patterns of characters. This syntax can be quite complex and is outside
the scope of this course. To learn about regular expressions, you can visit
http://www.regular-expressions.info, or explore the Java tutorial at
http://java.sun.com/docs/books/tutorial/essential/regex/index.html.
The Regular Expression validator compares attribute values against a mask specified by a Java
regular expression. This type of validator enables you to provide a dynamic script for more
complex validation rules.
Instead of defining an expression in this validator, you can select from a list of predefined
expressions. The built-in predefined expressions include telephone number and email address.
You can add your own expressions to this list by modifying the PredefinedRegExp.properties
file. This file is located in the o.BC4J subdirectory of the JDeveloper system directory
(system12.2.1.0.xx.xx.xx), which is a subdirectory of JDeveloper’s user directory.
When you use a Regular Expression validator, a <RegExpValidationBean> tag is added to the
XML file.

280
.
Use Declarative Validation: Built-in Rules
The easiest way to create and manage validation rules is through the declarative validation
framework. Oracle ADF is shipped with a number of built-in declarative validation rules that will
satisfy many of your business needs. You implement these rules through the entity object
editor and they are stored in the entity object’s XML file.
You can implement these rules either on the entity object itself, or on its attributes. The next
few slides show how to use the built-in declarative validation rules.

281
.
Script Expression Validator
A Script Expression validator enables you to use a Groovy expression that returns either true or
false for validation, or to use an entire Groovy script. When you define a Script Expression
validator, an <ExpressionValidationBean> tag is added to the XML file.
The following are some usage notes about the Script Expression validator:
All Java methods, language constructs, and Groovy constructs are available in the script.
Do not use { } to surround the entire script.
Use newValue to refer to the new value of the attribute being validated.
Use the return keyword just like in Java to return true or false, unless it is a
one-line expression, in which case the return is assumed to be the result of the expression
itself—for example, Sal > 0.
You must either return true or false, or call adf.error.raise or
adf.error.warn to display a message that is defined in your message bundle.
You can use built-in aggregate functions on RowSet objects by referencing the functions:
sum(String attrName)—for example: sum(”Salary”),
count(String attrName), avg(String attrName)
Use the ternary operator to implement functionality that is similar to SQL’s NVL()
function—for example, Sal + (Comm != null ? Comm : 0).

282
.
Use Declarative Validation: Built-in Rules
The easiest way to create and manage validation rules is through the declarative validation
framework. Oracle ADF is shipped with a number of built-in declarative validation rules that will
satisfy many of your business needs. You implement these rules through the entity object
editor and they are stored in the entity object’s XML file.
You can implement these rules either on the entity object itself, or on its attributes. The next
few slides show how to use the built-in declarative validation rules.

283
.
Entity-Specific Rules (Method Validator)
You can implement more complex validation rules for your business domain layer by using your
own Java code in Method validators. You code the rule in Java, and it is triggered by the
Method validator at the appropriate point in the entity object validation cycle.
You can create entity-level or attribute-level Method validators. You can add any number of
attribute-level or entity-level Method validators, provided they each trigger a distinct method
name in your code. There are many types of validation you can code with a Method validator,
either on an attribute or on an entity.
The method must be defined as public and return a Boolean value. The name of the method
must begin with the keyword validate. The code can be as complex or simple as the validation
rules require.

284
.
Use Declarative Validation: Built-in Rules
The easiest way to create and manage validation rules is through the declarative validation
framework. Oracle ADF is shipped with a number of built-in declarative validation rules that will
satisfy many of your business needs. You implement these rules through the entity object
editor and they are stored in the entity object’s XML file.
You can implement these rules either on the entity object itself, or on its attributes. The next
few slides show how to use the built-in declarative validation rules.

285
.
Using Declarative Global Validation Rules
As you saw in the preceding slides, ADF Business Components comes with a base set of built-in
declarative validation rules. However, one of the most powerful features of the validator
architecture is that you can create your own programmatic validation rules. When you realize
that you are writing the same kind of validation code over and over again, you can build a
validation rule class that captures this validation “pattern.” After you have defined a validation
rule class, it is as simple to use as any of the built-in rules.
For easier reuse of your custom validation rules, you can package them into a Java Archive (JAR)
file for reference by applications that make use of the rules.
The slides that follow describe each of the steps involved in the process of creating and using
your own declarative validation rules.

286
.
Create the Java Class for a Global Rule
The Java class needs to implement the JboValidatorInterface interface in the oracle.jbo.rules
package. To create the class, invoke the New Gallery and in the Categories list, select Business
Tier > ADF Business Components. Select Validation Rule in the Items list to create a class where
you can add the validation rule code.
In the Create Validation Rule Class dialog box, enter a name and package for the rule, along
with a display name and description. The display name should be the name you want to appear
in the list of validators to choose from when adding validation to an attribute, whereas the
description becomes a comment in the code to describe the validation that is implemented.
When you click OK, the Java class is created.
The example in the slide shows creating a validation rule that compares two dates, validating
that one date is not later than another. The intention is that this rule can be used to compare
any two date attributes in any entity object.

287
.
Examining the Generated Skeleton Code
The slide shows the skeleton code for the example (without the package name, import
statements, or comments). The Java class that is created implements the
JboValidatorInterface interface with its three methods:
•get Description(): Gets the text description of this validator

•setDescription(java.lang.String description ): Sets the text

description of this validator


•validate(JboValidatorContext ctx): Tests the validity of the object or value

as described in the validator context; this is the method that is executed when the validation
occurs
The newly created class also sets the description that you entered when you defined the rule,
and adds its own validateValue() method where you can add the validation code. You
can replace the return statement with your own code.
After you have created a rule in this way, it is automatically registered in the project and is
available for use in your business components.

288
.
Modifying the Code for the Global Rule
To achieve the goal of comparing any two date attributes in an entity, you modify the skeleton code as follows:
1. You want to use this validation rule to compare any two dates in any entity object, so you first add some properties that will specify which
entity attributes should be compared. Add
two more private strings and initialize them to null:
private String earlierDateAttrName = "";
private String laterDateAttrName = "";
You also generate public accessors for these new properties by right-clicking the editor and selecting Generate Accessors. Accessors are not
shown in the example in the slide.
2. Because you intend this to be an entity-level validation rule, you add a method that returns
true if the rule is applied at the entity level:
private boolean validatorAttachedAtEntityLevel(JboValidatorContext ctx) {
return ctx.getOldValue() instanceof EntityImpl;
}
3. Next you perform the comparison in the validate() method. You first call the method that you just defined to ensure that the validator is
defined at the entity level, and then you call validateValue() to compare the dates, raising an exception if the validation fails:
public void validate(JboValidatorContext ctx) {
if (validatorAttachedAtEntityLevel(ctx)){ EntityImpl eo = (EntityImpl)ctx.getSource();
Date earlierDate = (Date)eo.getAttribute(getEarlierDateAttrName());
Date laterDate = (Date)eo.getAttribute(getLaterDateAttrName());
if (!validateValue(earlierDate,laterDate)) {
throw new ValidationException("model.CompareDates validation failed");
}
}
else {
throw new RuntimeException("Rule must be at entity level");
}
}
4. Finally, you modify validateValue() to perform the comparison:
private boolean validateValue(Date earlierDate, Date laterDate) {
return (earlierDate == null) || (laterDate == null) || (earlierDate.compareTo(laterDate) <= 0);
}

289
.
Use Declarative Validation: Built-in Rules
The easiest way to create and manage validation rules is through the declarative validation
framework. Oracle ADF is shipped with a number of built-in declarative validation rules that will
satisfy many of your business needs. You implement these rules through the entity object
editor and they are stored in the entity object’s XML file.
You can implement these rules either on the entity object itself, or on its attributes. The next
few slides show how to use the built-in declarative validation rules.

290
.
Using a Domain to Create Custom-Validated Data Types
When you find yourself repeating the same sanity-checking validations on the values of similar
attributes across multiple entity objects, you can save yourself time and effort by creating your
own data types that encapsulate this validation.
For example, in your application, you may have numerous entity object attributes that store
strings that represent URLs. One technique you could use to ensure that end users always enter a
valid URL is to create your own data type (for example, URLDomain) that represents the
structure and format of a URL. You can then use URLDomain as the data type of every
attribute in your application that represents a URL.
When you create a new domain object, JDeveloper generates code in the domain’s constructor
to call the validate() method of the domain class. When you add your validation code to
this method, it is automatically executed when the domain object is instantiated.
The clear benefit of using a domain is that a domain can be used by multiple attributes, whereas
a validation rule (other than a global rule) applies to one attribute or entity object only.
Note: Domain validation code is executed whenever you query existing data. If existing data
fails the check, you need to either correct the existing data or code the check so that existing
data is determined to be valid.

291
.
Create and Use a Domain
The slide shows the steps to create and use a domain.
You create the domain by right-clicking in the Application Navigator and selecting New Domain,
or by invoking the New Gallery (Business Tier > ADF Business Components > Domain).
When you create a new domain object, JDeveloper generates code in the domain’s constructor
to call the validate() method, as shown in the next slide. Therefore, if you add your validation
code to the validate() method, it is automatically executed when the domain object is
instantiated.
In the final step, you change the type of an entity’s attribute to the domain, such as
URLDomain, as shown in the example in the slide. This causes the validation code to be called
when the entity object is instantiated

292
.
When you create a domain object, you are essentially creating a new data type; the example
creates the type called URLDomain. You can then change an entity attribute’s type to your new
type; in this example, you can change the type of an entity’s attribute to URLDomain. When the
entity is instantiated, or when the entity’s attribute is populated or changed, the URLDomain()
constructor is called. The constructor executes the validation code that you have written to
verify that this attribute is valid.
Because String is a base JDK type, a domain based on a String variable aggregates a
private mData String member field to hold the value that the domain represents.
Note: Domain validation code is executed whenever you query existing data. If existing data
fails the check, you need to either correct the existing data or code the check so that existing
data is determined to be valid.

293
.
Trigger Validation Execution
Each entity row tracks whether or not its data is valid. When a user modifies a persistent
attribute of an existing entity row or creates a new entity row, the entity is marked as invalid,
and any validation that you have implemented is evaluated again before the entity is again
considered valid. In validation rules, you can specify when this validation is executed as follows:
Validation Level: In an entity validation rule, you can specify whether validation should be
performed at the entity-level (the default) or at the transaction level. If you specify that it
should be performed at the transaction level, it will be carried out after all entity-level
validation. For this reason, you should use this option where you want to ensure that a specific
piece of validation is performed at the end of the process.
Conditional Execution: You can enter a Boolean condition using a Groovy expression to define
conditional validation execution. When the condition evaluates to true, the rule is executed.
You have the option to test your expression to see if it is valid.
Triggering Attributes:
By default, a validator fires on an attribute whenever the entity as a whole is dirty. However, in
an entity validation rule, you can choose to trigger validation only when certain attributes
change (when one of the triggering attributes is dirty).
Validation always occurs before changes are posted to the database. If you must code
validation that depends on seeing posted changes, override the beforeCommit() method in the
object’s Java file.

294
.
Specify Validation Order
Attribute validation occurs when focus moves from the attribute, whereas entity validation
occurs when the record is committed. With compositions, changing a child entity causes the
parent entity to be validated as well, with child entities being validated before parent entities.
You can specify the validation order of rules within a certain group (entity or an attribute) by
using the up and down arrows to rearrange the validation rules on the Validators page of the
editor. For example, although you cannot control the order in which attributes are validated
(they are validated in the order in which they appear in the entity definition), you can order
validations for a given attribute.
If you want to ensure that a Key Exists or an entity-level Method validator is performed at the
end of the validation process, you can set it to perform at the transaction level, rather than at
the entity level. It is then fired after all entity-level validation is performed. You set the level of
validation on the Validation execution tab of a validation rule editor.

295
.
Handle Validation Errors
When a validation rule throws exceptions, the exceptions are bundled and returned to the
client, and any database changes pertaining to the transaction are rolled back.
The Failure Handling tab on the Validation page of the Validation Rule page of the entity object
editor (or the attribute editor) is where you specify the error message that you want to display
to the end user when the validation fails.
You use the Validation Failure Severity option buttons to specify whether the message is an
Error message (default) or Informational Warning.
You can enter Groovy expressions to populate variables in error message text to make the
message more meaningful. And you can store messages in a resource bundle or property file to
make them translatable.

296
.
Specifying the Severity of an Error Message
If you define the message as an Error message, the end user is not able to navigate out of the
current field or record and must revisit the field where the data has failed the validation test. If
the message is classified as Informational Warning, the user can continue after the message has
been acknowledged.

297
.
Storing Messages as Translatable Strings
Typically you store error messages in a resource bundle or other property file to facilitate
translation and reuse of messages. A resource bundle contains key-value pairs for any
messages and data strings in your application that you want to translate or reuse.
To use an existing message or create a new stored message, perform the following steps:
1. Click the Select Text Resource button to open the Select Text Resource dialog box.
2. In the Select Text Resource dialog box:
- To use an existing message, select it and click Select
- To create a new message, enter the message in the Value field. This automatically
populates the Key field, but you can change the key to a more meaningful name if
desired. You also enter a description, which can assist the translator in knowing how the
message is to be used.
- Click “Save and Select” to store and use the message

298
.
Use Groovy Variables in Error Messages
Using Groovy variables in error messages enables you to display dynamic labels and values in
your messages. This also makes your messages more reusable when adding to a resource, as
described in the next slide.
When you create the message, use any variable name, surrounded by braces. JDeveloper
automatically adds the variable as a message token in the lower part of the Failure Handling
page.
You must supply the values for the message tokens. You can use expressions such as
source.hints.OrderDate.label to reference the value of the user-friendly display label of the
OrderDate attribute of the source entity object being evaluated. To reference the value, simply
use the name of the attribute.
At run time, the error message is displayed with the specified labels and values.

299
.
Groovy Expressions for Validation
You can use a Groovy expression to return a true/false statement. The Script Expression
validator requires that the expression return either true or false. A common use of this
feature would be to validate an attribute value, for example, to make sure that an account
number is valid or check that one date is later than another, as in the example in the slide.
To use Groovy to validate a true/false expression:
1. In the Application Navigator, double-click the desired entity object.
2. On the Business Rules page of the overview editor, select where you want to add the
validator.
- To add an entity-level validator, select the Entity folder.
- To add an attribute-level validator, expand the Attributes folder and select the
appropriate attribute.
3. Click the green plus sign to create a new validator.
4. In the Add Validation Rule dialog box, in the Rule Type drop-down list, select Script
Expression.
5. Enter a validation expression in the field provided.
6. You can optionally click the Validation Execution tab and enter criteria for the execution
of the rule, such as dependent attributes and a precondition expression.
7. Click the Failure Handling tab and enter or select the error message that will be shown to
the user if the validation rule fails.
8. Click OK.

300
.
301
.
302
.
303
.
Lesson Agenda
ADF Faces, used in this course, is built on top of the JavaServer Faces technology. This lesson
describes UI technologies, especially JSF, and explains how ADF enhances the ability to build
rich user interfaces.

304
.
305
.
The Web (WWW)
HyperText Markup Language (HTML) is a markup language for defining Web pages. It consists of
tags that describe the elements of a document, such as links, text, paragraphs, lists, and forms.
The ability to define hyperlinks to other Web pages was instrumental in the development of the
World Wide Web.
HTML documents are transmitted to a Web browser from a Web server via the HyperText
Transfer Protocol (HTTP), which can also serve images, sound, and other types of content. HTTP
is simply a set of rules and standards for exchanging files on the Web.
HTTP is a request/response protocol. It sends a request from the client browser to the Web
server and returns the response in the form of the requested HTML document or other
content. It is a stateless protocol; each request-and-response set has no knowledge of previous
requests. With HTTP it is difficult to implement Web sites that react intelligently to user input.
One of the technologies intended to overcome this difficulty is Java.

306
.
Web Development
You can design Java programs as server-based components that form scalable Internet applications.
The currently accepted model for Java Internet computing divides the end-to-end application process
into several logical tiers. To make use of this model, JavaSoft defined Java Platform, Enterprise Edition
(Java EE), which has four logical tiers:
Client Tier
When Java executes on client machines, it is typically implemented as a browser-based application. But
a thin client can be simply Web pages that are delivered from a server as HTML.
Web (Presentation) Tier
This is executed on a Web server. Code in this tier handles the application’s presentation to the client.
Common Java features for this function are servlets, JSP pages (JSPs), and JavaServer Faces (JSF).
Servlets and JSPs can each generate dynamic HTML for display as Web pages to clients.
Application (Business Logic) Tier
You can use Java on an application server to implement shareable, reusable business logic as application
components. A common way to implement this is to use component models, such as Enterprise
JavaBeans (EJB) and Common Object Request Broker Architecture (CORBA) objects. These two
components are also to be considered during design time, when a distributed environment is required.
Data Tier
The data server not only stores data but also stores and executes Java code, particularly where this code
is data intensive or enforces validation rules pertaining to the data. You can also use Business
Components, from the Oracle Application Development Framework (ADF), to support your application’s
data access.

307
.
Servlets
The servlet technology is the foundation of Web application programming in Java. A servlet is a
server-side Java program that gives Java-enabled servers additional functionality via a request-
response programming model. Although servlets can respond to any type of request, they are
commonly used to extend the applications hosted by Web servers. Servlets can perform back-
end functionality or can dynamically construct user interfaces.
The life cycle of a servlet is controlled by the container in which the servlet is deployed. When a
request is mapped to a servlet, the container performs the following steps:
It loads the servlet class if there is no instance of it, creates an instance of the servlet class, and
initializes the servlet instance by calling the init method.
It invokes the service method, passing a request and response object.
If the container needs to remove the servlet, it finalizes the servlet by calling the servlet’s
destroy method.
When the browser request is for a servlet, the Web server forwards the request to the servlet
container. The servlet dynamically constructs the HTML file, using any parameters that are sent
in the URL request, and then the Web server returns the HTML file to the client browser

308
.
Java Server Pages (JSP)
Although servlets are powerful, they have some disadvantages. They can be cumbersome to
program, and every change requires the intervention of the servlet programmer.
Sun understood this problem and developed JavaServer Pages (JSP) as the solution. JSP
combines HTML with JSP tags in a file that has a .jsp extension. When the HTTP request
contains this extension, the Web server runs the JSP in the servlet container, which converts it
into a servlet. After it is compiled, further requests for the .jsp file run the servlet without the
compilation process, unless the .jsp file is changed on the server.
Division of labor between a programmer and a page designer is much easier in JSP, and
compilation takes place automatically when a JSP page is modified. Note that though JSP is an
extension of the servlet technology, it does not make servlets obsolete. In real-world
applications, servlets and JSP pages are used together.

309
.
310
.
311
.
Make sure to emphasize that JSF here is compared to “traditional” JSP before JSF
arrived. Remember JSF works just fine with JSP today.

312
.
16
313
.
314
.
315
.
316
.
WML: Wireless Markup Language
SVG: Scalar Vector Graphics
L&F: Look and Feel

317
.
WML: Wireless Markup Language
SVG: Scalar Vector Graphics
L&F: Look and Feel

JSF Architecture
One of the key advantages of JSF is that it is both a Java Web UI standard as well as a
framework that firmly follows the Model-View-Controller (MVC) design pattern. This makes
JSF applications much more manageable because the UI code (View) is cleanly separated from
the application data and logic (Model). To prepare the JSF context, which provides application
data access to the pages, and to guard against unauthorized or improper access of the pages,
all user interactions with the application are handled by a front-end “Faces” servlet (Controller).

318
.
319
.
Summary of Key Elements
This diagram shows all the key components in the JSF Architecture discussed earlier. In
everyday operation, the programmer is concerned only with the red boxes. These are the
primary areas where code can be entered. Everything in the blue boxes is generally handled by
the framework, although (as in all the aspects of JSF) it can be extended or customized.
The view here is the page definition itself and the model represents the back-end integration
usually handled by Managed Beans.

320
.
Standard Component Model for Web Development
The JSF component model is similar to the Abstract Window Toolkit (AWT) GUI component
model. It has events and properties that are similar to the Swing component model. It also has
containers that contain components, which are in turn components that can be contained by
other containers. In theory, the JSF component model is divorced from HTML and JSP. The
standard set of components that ships with JSF has JSP bindings and generates HTML
renderings.
Examples of JSF components include calendar input components and rich HTML input
components. You may never have time to write such components, but what if they already
existed? The component model lowers the entry barrier to add more functionality to Web
applications by making a commodity of common functionality.

321
.
322
.
JSF Model
As discussed previously, components are used to build JSF views, rather than mark-up
documents. The coding paradigm for UI components is based on the JavaBeans model. You set
property values or attributes to define the state and attach listeners to respond to value
changes or other events, thereby defining behavior.
Some components can be nested. In most cases, the purpose of nesting components is to
provide a layout for other components, such as a table, within a view. UI components are
standardized within JSF, so you can mix and match components from different vendors.
However, if you do so, you may not be able to achieve a standard look and feel or be able to
support internationalization.
JavaServer Faces includes:
UI components: Server-side objects that are independent of the target client and render back
to the client using external renderer classes. UI components consist of attributes, behaviors,
and renderers.
Renderers: Classes that reside on the server and are responsible for displaying the UI
component in a graphical representation that is understood by the client
Render kits: Renderer classes packaged into libraries that enable you to develop a JSF
application for different client devices (such as browsers or mobile devices) without altering
application code. A render kit for an HTML client is part of standard JSF.

323
.
324
.
325
.
326
.
327
.
328
.
329
.
330
.
Traditional Navigation
This type of navigation is also referred to as the Model 1 type. In both cases, if the physical
location of the page is changed, you have to modify all the links and forms using it. How can
you avoid this maintenance nightmare?
JSF controls the pages using a separate XML file, faces-config.xml, that contains all the
navigation mechanisms.

331
.
JSF Navigation

In JavaServer Faces, navigation between application pages is not hard coded in the file, but is
defined by a set of rules that are centrally defined in the faces-config.xml file. Navigation rules
determine the next page to display when a user clicks a navigation component, such as a
button or a hyperlink.
A navigation rule defines the navigation from one page to one or more other pages. Each
navigation rule can have one or more cases, which define where a user can go from that page.
For example, if a page has links to several other pages in the application, you can create a single
navigation rule for that page and one navigation case for each link to the different pages. The
rule itself can define the navigation from:
A specific JSF page
All pages whose paths match a specified pattern, such as all the pages in one directory, which is
called a pattern-based rule
All pages in a Java EE Web application, which is called a global navigation rule

332
.
JSF Expression Language
To display data from the data model, Web page UI components are bound to binding objects
using JSF EL. These expressions reference a specific binding object in a binding container. At
run time, the JSF run time evaluates an EL expression and pulls the value from the binding
object to populate the component with data when the page is displayed. If the user updates
data in the UI component, the JSF run time pushes the value back into the corresponding
binding object based on the same EL expression.

333
.
334
.
JSF Managed Bean
JSF components are a type of JavaBean, and they are also designed to work with another type
of JavaBean called a managed bean. Often managed beans handle events or some
manipulation of data that is best handled at the front end rather than placing the logic in a
business component. However, all application data and processing should be handled by logic
in the business layer of the application.
Some typical uses for managed beans are:
To hold values that can be used by multiple pages
To execute a method in response to user interaction, such as a button click
To execute a method when a UI event, such as a value change, takes place Backing beans are a
specialized type of managed bean that exposes some or all of the UI
components on the page by defining accessors for them. When you create a JSF page, the Page
Implementation section of the Create JSF Page dialog box enables you to choose whether to
expose the UI components, which you would need to do only if the page requires special code
to manipulate its components programmatically. For example, you may set a condition to
determine whether to render the component. If you choose to expose components in a
managed bean, JDeveloper automatically adds stubs for accessors as you add components to
the page. Backing beans are directly related to pages, whereas other types of managed beans
can be made available to multiple pages.

335
.
336
.
337
.
JSF Life Cycle Phases
The life cycle handles both initial requests and postbacks.
When a user makes an initial request for a page, the life cycle executes only the Restore View and Render Response phases because there is no
user input or actions to process. The life cycle builds the UI tree from the view, and then renders the view, returning a response to the user and
saving the view tree for future requests in the FacesContext object. All the component tags, event handlers, converters, and validators on the
page have access to the FacesContext instance.
When a user executes a postback, a form is submitted that is contained on a page that was previously loaded into the browser as a result of
executing an initial request. When the life cycle handles a postback, it restores the view based on the data saved on the server, and then
executes the following additional phases:
Apply Request Values: Values provided in components that hold a value (such as input fields) have their values applied to their counterparts in
the view tree. All events such as ValueChangeEvents (VCE) or ActionEvents (AE) are queued. A VCE means that a value has changed for a
specific UI component. An AE means that a button (or any UI component that is a source of an action) was clicked. If a component has its
immediate attribute set to true, then validation, conversion, and events associated with the component are processed during this phase.
Process Validation: Conversion and validation logic is executed for each component. This means both built-in validation/data conversion and
custom validation/conversion are added onto the components. If a validation error is reported, an exception is thrown. The life cycle halts and
the response is rendered with validation error messages. 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.
Update Model: The component’s validated local values are moved to the model and the
local copies are discarded. If you are using a backing bean for a JSF page to manage your UI components, any managed bean properties that
are value-bound to the UI component using the value attribute are updated with the value of the component.
Invoke Application: Any action bindings for command components or events are invoked. Navigation is handled here depending on the
outcome of action method (if any).
Setting the immediate Attribute
You can use the immediate attribute to allow components on the page to be validated in the Apply Request Values phase of the life cycle as
opposed to the Process Validations phase:
Using immediate on an input component means that that component’s value is validated
before any input components that do not have the immediate attribute set to true.
Therefore, if a validation error occurs on an immediate input component, the life cycle
moves from the Apply Request Values phase (where the immediate attribute is
evaluated) to the render phase, and validation does not run on any “nonimmediate” input components. Additionally, if the new value of an
immediate input component is different from the existing value, then a ValueChangeEvent is raised. However, instead of the event being
processed during the Process Validations phase, the event is processed at the end of the Apply Request Values phase. Therefore, any
ValueChangeListener associated with the immediate input component executes before any command component’s ActionListener (assuming
the command component occurs later on the page). You learn about event listeners in the lesson titled “Responding to Application Events.”
For command components, if set to immediate and the component has an action that
returns a value for navigation, the life cycle proceeds directly to the Render Response phase. The validation and model update phases are
skipped. A Cancel button is an example of when this would be used.

338
.
JSF Life Cycle Overview
The life cycle of a JavaServer Faces page is similar to that of a JSP: The client makes an HTTP
request for the page, and the server responds with the page translated to HTML. However,
because of the extra features that the JavaServer Faces technology offers, the life cycle
provides some additional services to process a page.
A JavaServer Faces page is represented by a tree of UI components called a view. This tree is a
run-time representation of a JSF page. Each UI component tag on a page corresponds to a UI
component instance in the tree.
The FacesServlet object manages the request processing life cycle in JSF applications.
FacesServlet creates an object called FacesContext, which contains the information necessary
for request processing, and invokes an object that executes the life cycle.
When a client makes a request for the page, the life cycle starts. During the life cycle, the JSF
implementation must build the view while considering the state saved from the previous
postback. When the client performs a postback of the page, the JavaServer Faces
implementation performs several tasks, such as validating the data input of components in the
view and converting input data to types specified on the server side. The JSF implementation
performs all these tasks as a series of steps in the life cycle.

339
.
340
.
Java Server Faces (JSF)
JavaServer Faces (JSF) is a component-based architecture, which means that instead of working with markup, the developer
works with UI components, similar to Swing. Thus JSF simplifies Web development. The developer need not be concerned with
UI implementations, and is able to use declarative definition, making it more robust and extensible.
JSF is a server-side UI technology, as opposed to a client-side UI technology such as ADF Swing. Requests are sent from the
Web browser or other client to the server, where JSF translates the request into an event that the application logic can
process. JSF also ensures that every widget that is defined on the server is correctly displayed on the client.
JSF technology establishes the standard for building server-side user interfaces, managing their state, handling events and
input validation, defining page navigation, and supporting internationalization and accessibility. JSF hides the complexities of
UI management, simplifying the process of building Web Uis.
For example, consider what is required to develop a simple order form using traditional Web technologies: HTML for your
presentation, state management over HTTP, JavaScript for input validation and behavior, and a servlet on the server side to
process the order. In JSF, the developer is not concerned with these underlying technologies, but considers a field or a button
on a form as a component in terms of a traditional UI. A button is as you think of it in the physical world: It is not an
HTML or a JSP tag, but an object that when pressed has an associated behavior.
Developers can attach listeners to interpret user interactions with components into business logic, and the JSF infrastructure
manages the rest for you. Thus, developing JSF applications is more about user interface design and assigning business logic to
components rather than programming against low-level APIs.
JSF can automatically synchronize UI components with backing beans, which are Java objects that collect user input and
respond to events. It can be used with a variety of clients.
The JSF specification was written with tool support facilities built in. The standard JSR-276 (Design Time Metadata for JSF
Components, http://www.jcp.org/en/jsr/detail?id=276) aims to ensure that components from different vendors render
correctly in IDEs that support JSF.
Because JSF is a UI component framework that works with tools and runs inside containers, it appeals to many types of
programmers and has wide industry support.
There are many Web sites where you can get further information about JSF, such as
http://myfaces.apache.org and http://java.sun.com/javaee/javaserverfaces

341
.
342
.
25
343
.
Features of Rich Web Uis
Increased Responsiveness: Traditional Web applications interact with data on the server,
resulting in elongated round-trips even for simple activities, such as sorting and filtering. Rich
UIs typically cache data sets on the client side, making activities such as sorting and filtering
much more responsive because no round-trip to the server is necessary.
Asynchronous communication with the server: Traditional Web applications typically render
pages in a top-down fashion, so that the length of time that a page takes to load will be no less
than the longest operation on the page. Utilizing asynchronous communication with the server
eliminates the traditional top-down rendering of a page and can, therefore, give the perception
of improved performance. Long operations can be performed asynchronously, with a callback
mechanism triggering the rendering of a particular section of the page when the operation is
complete. This leads to a natural tendency to create fragments of markup (something both
portlets and JSF make very easy) to take advantage of parallelization.
Behaviors not available in HTML alone: Rich UIs clearly differ from traditional Web application
in their look and feel and in how the end user interacts with and navigates the application; that
look and feel cannot be produced through HTML alone. For example, HTML alone cannot open
new windows or change color on mouse over. However, such dynamic features, coupled with
asynchronous behavior and parallelization, create a highly decorated window into an
application.

344
.
345
.
346
.
347
.
WML: Wireless Markup Language
SVG: Scalar Vector Graphics
L&F: Look and Feel

348
.
WML: Wireless Markup Language
SVG: Scalar Vector Graphics
L&F: Look and Feel

349
.
WML: Wireless Markup Language
SVG: Scalar Vector Graphics
L&F: Look and Feel

350
.
351
.
352
.
353
.
354
.
355
.
356
.
357
.
358
.
359
.
360
.
ADF Controller
ADF Controller is an enhanced navigation and state management model on top of JavaServer
Faces. It enables you to describe page flows declaratively. Page flows can be encapsulated in a
task flow, which promotes reuse. Task flows represent activities and the control flow rules that
define the transitions between the activities. JSF navigation alone does not provide this task
flow concept.
In addition to navigation, the ADF Controller provides the ability to call methods, either on
managed beans or on Java objects that are not managed beans. It provides support for
application tasks such as validation, state management, security, and declarative transaction
control.
The ADF Controller also enables you to control behavior when navigation is the result of the
user clicking the Back button.
Subsequent lessons elaborate on the functionality of the ADF Controller.

361
.
362
.
JSF Life Cycle Phases
The life cycle handles both initial requests and postbacks.
When a user makes an initial request for a page, the life cycle executes only the Restore View and Render Response phases because there is no
user input or actions to process. The life cycle builds the UI tree from the view, and then renders the view, returning a response to the user and
saving the view tree for future requests in the FacesContext object. All the component tags, event handlers, converters, and validators on the
page have access to the FacesContext instance.
When a user executes a postback, a form is submitted that is contained on a page that was previously loaded into the browser as a result of
executing an initial request. When the life cycle handles a postback, it restores the view based on the data saved on the server, and then
executes the following additional phases:
Apply Request Values: Values provided in components that hold a value (such as input fields) have their values applied to their counterparts in
the view tree. All events such as ValueChangeEvents (VCE) or ActionEvents (AE) are queued. A VCE means that a value has changed for a
specific UI component. An AE means that a button (or any UI component that is a source of an action) was clicked. If a component has its
immediate attribute set to true, then validation, conversion, and events associated with the component are processed during this phase.
Process Validation: Conversion and validation logic is executed for each component. This means both built-in validation/data conversion and
custom validation/conversion are added onto the components. If a validation error is reported, an exception is thrown. The life cycle halts and
the response is rendered with validation error messages. 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.
Update Model: The component’s validated local values are moved to the model and the
local copies are discarded. If you are using a backing bean for a JSF page to manage your UI components, any managed bean properties that
are value-bound to the UI component using the value attribute are updated with the value of the component.
Invoke Application: Any action bindings for command components or events are invoked. Navigation is handled here depending on the
outcome of action method (if any).
Setting the immediate Attribute
You can use the immediate attribute to allow components on the page to be validated in the Apply Request Values phase of the life cycle as
opposed to the Process Validations phase:
Using immediate on an input component means that that component’s value is validated
before any input components that do not have the immediate attribute set to true.
Therefore, if a validation error occurs on an immediate input component, the life cycle
moves from the Apply Request Values phase (where the immediate attribute is
evaluated) to the render phase, and validation does not run on any “nonimmediate” input components. Additionally, if the new value of an
immediate input component is different from the existing value, then a ValueChangeEvent is raised. However, instead of the event being
processed during the Process Validations phase, the event is processed at the end of the Apply Request Values phase. Therefore, any
ValueChangeListener associated with the immediate input component executes before any command component’s ActionListener (assuming
the command component occurs later on the page). You learn about event listeners in the lesson titled “Responding to Application Events.”
For command components, if set to immediate and the component has an action that
returns a value for navigation, the life cycle proceeds directly to the Render Response phase. The validation and model update phases are
skipped. A Cancel button is an example of when this would be used.

363
.
364
.
365
.
366
.
367
.
368
.
369
.
370
.
371
.
Lesson Agenda
This lesson describes how to use ADF Faces to create a simple page

In Hands-on lab one would practice:


1. Creating New Application with only ViewController Project
2. Setting Up the UI Project for Internationalization
3. Setting Up the Skin Preference

372
.
373
.
Internationalization of an Application
If you want your application to be viewed by users in more than one country, you can configure
it to different locales so that it displays the correct language for the language setting of a user’s
browser. For example, if you know that your application will be viewed in Germany, you can
localize your application so that when a user’s browser is set to use the German language, the
text strings in the application will appear in German.
ADF Faces components provide automatic translation. The resource bundles used for the
components’ skin (which determines the look and feel as well as the text within it) are
translated into 28 languages. If a user sets the browser to use the German language, any text
contained within the components is automatically displayed in German.

374
.
375
.
To internationalize your application, you need to do the following:
1. Create a base resource bundle that contains all the text strings that are not part of the components
themselves. This is a text file with a .properties extension that contains
key/value pairs: the key is the name of the text resource and the value is the translation— for example,
CANCEL=Cancel.
This bundle should be in the default language of the application.
2. Create a localized version of the bundle for each locale supported by the application. You can copy the
resource bundle file to another file and append the file name with an underscore and the language code, such as
_de for German. For example, if the resource bundle file name is StorefrontUIBundle.properties,
you would name the German resource bundle StorefrontUIBundle_de.properties. Then translate the
values in the file—for example, CANCEL=Annullieren.
3. Register the locales with the application. You do this on the Application page of faces- config.xml.
(Click the Overview tab at the foot of the faces-config.xml file, and
then select Application from the list at the top left. You can specify a default locale and add supported locales
in the Locale Config area.)
4. Use the bundle on your page.
a) Note that you need to set your page encoding to be a superset of all supported languages. By
default, JDeveloper sets the page encoding to windows-1252. To set the default to a different
page encoding, perform the following steps:
1. Select Tools > Preferences.
2. Select Environment from the list at the left, if it is not already selected.
3. Set Encoding to the preferred default.
b) Bind all attributes that represent strings of static text on the page to the appropriate key in the
resource bundle, using the variable defined in the faces-config.xml file for the
<resource-bundle> element.

376
.
Automatically Create Resource Bundles
Resource bundles contain the actual text that you have added to the application. You need to
create a version of the resource bundle for each locale where your application will be used, and
add a <locale-config> element to define the default and support locales in the application’s
faces-config.xml file. You also need to add a <resource-bundle> element to your application’s
faces-config.xml file to make the resource bundles available to all the pages in your application
without using an <f:loadBundle> tag on every page. (With JSF1.2, you do not need to load the
base resource bundle on each page of your application with the <f:loadBundle> tag.)
After you have configured and registered a resource bundle, the Expression Language editor
will display the key from the bundle, making it easier to reference the bundle on application
pages.
The first example in the slide shows part of the UIResources.properties file, which displays
some of the English-language entries for static text in the StoreFront application. The second
example shows the same file named UIResources_de.properties, but with the browser set to
use the German language.

377
.
Automatically Create a Text Resource
You do not need to manually edit the resource bundle file to create a text resource (name–
value pair). The JDeveloper IDE provides a simpler way to do this.
1. In the Property Inspector, click the arrow to the right of the text attribute for which you want
to enter a text resource and select Select Text Resource. The first time you do this, the
appropriate resource bundle file is created if it does not already exist.
2. In the Select Text Resource dialog box, you can either select an existing text resource or
create a new one.
a. Enter a Display Value (the text that should be displayed in the UI and that is
translatable).
b. Enter a key (defaults based on the Display Value, but you can change it).
c. Enter a Description (how the text resource is to be used).
d. Click “Save and Select” (or Select when choosing an existing text resource).
3. The UI reflects the string, whereas the property shows the EL expression that refers to the
text resource.
4. The text resource is added to the resource bundle.

378
.
379
.
To internationalize your application, you need to do the following:
1. Create a base resource bundle that contains all the text strings that are not part of the components
themselves. This is a text file with a .properties extension that contains
key/value pairs: the key is the name of the text resource and the value is the translation— for example,
CANCEL=Cancel.
This bundle should be in the default language of the application.
2. Create a localized version of the bundle for each locale supported by the application. You can copy the
resource bundle file to another file and append the file name with an underscore and the language code, such as
_de for German. For example, if the resource bundle file name is StorefrontUIBundle.properties,
you would name the German resource bundle StorefrontUIBundle_de.properties. Then translate the
values in the file—for example, CANCEL=Annullieren.
3. Register the locales with the application. You do this on the Application page of faces- config.xml.
(Click the Overview tab at the foot of the faces-config.xml file, and
then select Application from the list at the top left. You can specify a default locale and add supported locales
in the Locale Config area.)
4. Use the bundle on your page.
a) Note that you need to set your page encoding to be a superset of all supported languages. By
default, JDeveloper sets the page encoding to windows-1252. To set the default to a different
page encoding, perform the following steps:
1. Select Tools > Preferences.
2. Select Environment from the list at the left, if it is not already selected.
3. Set Encoding to the preferred default.
b) Bind all attributes that represent strings of static text on the page to the appropriate key in the
resource bundle, using the variable defined in the faces-config.xml file for the
<resource-bundle> element.

380
.
ADF Faces Skins
You can change the appearance or look and feel of an application without having to rewrite the
user interface. A skin in ADF Faces is a global style sheet that needs to be set only in one place
for the entire application. Every component automatically uses the styles as described by the
skin. Any changes to the skin are picked up at run time, so no change to code is needed. Skins
are based on the Cascading Style Sheet specification, using CSS 3.0 syntax.
In addition to using a CSS file to determine the styles, skins also use a resource bundle to
determine the text. For example, the words “Previous” and “Next” in the navigation bar of the
ADF Faces table component are determined by using the skin’s resource bundle. All the
included skins use the same resource bundle.
You set an element in the trinidad-config.xml file that determines which skin to use, and if
necessary, under what conditions. In the trinidad-config.xml file, replace the
<skin-family> value with the family name for the skin you want to use. For example:
<trinidad-config xmlns="http://myfaces.apache.org/trinidad/config">
<skin-family>fusion</skin-family>
</trinidad-config>

381
.
ADF Faces Skins Usage
ADF Faces provides the following skins for you to use in your applications:
blafplus-medium: This skin provides a modest amount of styling. This style extends the simple
skin.
blafplus-rich: This skin extends the blafplus-medium skin. It provides more styling than the
blafplus-medium skin. For example, graphics in the blafplus- rich skin have rounded corners.
fusion: This defines the default styles for ADF Faces components. This skin provides a
significant amount of styling.
fusion-projector: This defines the styles for an application that you want to
demonstrate to an audience using a projector. This skin modifies a number of elements in the
fusion skin so that an application renders appropriately when displayed using table- top
projectors (particularly older models of projector). This skin is useful if the audience is present
at the same location as the projector. This skin may not be appropriate for an audience that
views an application online through a Web conference.
simple: This skin contains only minimal formatting.
You can learn more about skinning in the course.

382
.
Add UI Components to the Page
You can add databound components to a page by using either the Component Palette or the
Data Controls panel. You also can right-click in the Structure window or in the Design view in
the editor and select from the context menu to insert a component. You can also add
components through the Code Editor, using XML. Click the Source tab to display the Code
Editor.

383
.
Use of Component Facets
When you begin to use components, you see in the Structure window that many of them
contain facets. A facet is a placeholder where a developer can add content.
For example, the af:showDetailItem component has a facet called toolbar. As the name
suggests, the facet is intended as a placeholder for a toolbar, although you could place any
content there.
In the example in the slide, the application developer has added a toolbar component with a
toolbarButton to the toolbar facet of showDetailItem and set the button’s text property value
to “I’m a button on the toolbar facet!” At run time, that text is displayed at the place
designated for the toolbar facet on the showDetailItem component.
It is important to note that a facet can have only one direct child. If the developer adds more
buttons to the toolbar facet, they must be added to the direct child of the facet, which is the
toolbar component.

384
.
385
.
1. Deploy and run the Web Service
• adf-settings.xml: The adf-settings.xml file keeps the UI project configurations. This file is present in the <
project-root >/src/META-INF folder.
• faces-config.xml: The faces-config.xml file contains the configurations for a web application built using JSF. This
file allows us to configure managed beans, data convertors, and validators used in the UI, navigation cases,
global resource bundles, view handlers, page lifecycle phase listeners, and custom lifecycle factory
implementation for the application.
• adfc-config.xml: ADF Faces is built on top of the JSF with a lot of extra features, which are not covered by the
core JSF. ADF Faces uses adfc-config.xml to keep its configurations. As a Fusion developer, you should use adfc-
config.xml to configure the navigation cases and managed bean definitions. To run your Fusion web
application, you may need both faces-config.xml and adfc-config.xml files—which is true even if you have not
added any custom configuration entries in faces-config.xml.
• trinidad-config.xml: Apache MyFaces Trinidad forms the base for the ADF Faces component set. In fact,
Trinidad components earlier were ADF Faces components, which were donated to Apache Software
Foundation later in the journey. By default, the generated trinidad-config.xml file contains only the skin family
name. However, trinidad-config.xml can be used to override the default configurations for accessibility
settings, locale settings, state management, and so on.
• web.xml: The web.xml file acts as deployment descriptor for a Java-based web application. When you generate
a Fusion web application by using JDeveloper, a default web.xml file with default settings will be created for
you. The default entries include context parameters for configuring the runtime state of the system, security
filters, data binding filters for web pages, and resource look up filters. The web.xml file also includes servlet
context listeners for initializing the management and monitoring services for view and model layers.
• adf-config.xml: The adf-config.xml file contains application-level settings, which manage the runtime
infrastructure—such as failover behavior for the application modules, global fetch limit for all the view objects,
caching of resource bundles, automated refresh of page bindings, and so on—for your application.
• weblogic-application.xml: This file is the WebLogic Server-specific deployment descriptor.
The adf-faces-config.xml file contains configuration elements that can be set to override ADF
Faces specific functionality such client-side validation, usage of custom skins, control output to
the client for debugging purposes.

The adf-faces-skins.xml file contains a list of available skins that can be used by the application
at runtime.

The adf-faces-impl.jar and the adf-faces.api.jar contains the ADF Faces runtime libraries

The adfshare.jar (optional) contains common runtime used in context with the rest of Oracle
ADF (in particular the ADF binding layer).

The af.tld and afh.tld are the JSP tag libraries containing the ADF Faces tags representing the
ADF Faces UI components to be used by application developers.

387
.
1. Deploy and run the Web Service

.
1. <context-param>
2. <param-name>javax.faces.CONFIG_FILES</param-name>
3. <param-value>/WEB-INF/faces-config1.xml,/WEB-INF/faces-config2.xml</param-value>
4. </context-param>

.
390
.
391
.
Lesson Agenda
One of the goals in Web development is to design attractive and usable pages. This lesson
describes how to use complex layout components and styles to achieve a desired appearance.
Students also learn to use dynamic page layout techniques.

In Hands-on lab one would practice:


1. Creating New JSF Page
2. Adding Default Layout Components
3. Customizing Layout Components

392
.
393
.
394
.
395
.
396
.
397
.
398
.
399
.
400
.
401
.
402
.
403
.
404
.
405
.
406
.
407
.
408
.
409
.
410
.
411
.
Create Resizable Panes: Panel Splitter
When you have groups of unique content to present to users, consider using multiple panes
separated by adjustable splitters. When viewing the page in a client browser, users can change
the size of panes by dragging a splitter, and also choose to collapse or restore panes. When a
pane is collapsed, its contents are hidden; when a pane is restored, the contents are displayed.
The af:panelSplitter component enables you to organize contents into two panes separated by
an adjustable splitter. Clicking the arrow button on a splitter collapses a pane (and its contents)
in the direction of the arrow. The value of the orientation attribute determines whether the
panes are horizontal (default) or vertical. The pane contents are specified in the facets first and
second. The slide shows a page divided into two horizontal panes (placed left to right), and
another page divided into two vertical panes (placed top to bottom). It also shows a nested
panelSplitter, created by a horizontal panelSplitter into the first facet of a vertical panelSplitter.
The af:panelSplitter component uses geometry management to stretch its child components at
run time. This means when the user collapses one pane, the contents in the other pane are
explicitly resized to fill up available space. If af:panelSplitter is the root component for your
page contents, stretching occurs automatically.

412
.
Another feature of the panel splitter component is that users can collapse or
restore its panes. When a pane is collapsed, the pane contents are hidden; when a
pane is restored, the contents are displayed. The collapsed attribute on
af:panelSplitter determines whether the splitter is in a collapsed (hidden)
state. By default, the collapsed attribute is false, which means both panes
are displayed. When the user clicks the arrow button on the splitter, collapsed
is set to true and one of the panes is hidden.
ADF Faces uses the collapsed and positionedFromEnd attributes to
determine which pane (that is, the first or second pane) to hide (collapse) when the
user clicks the arrow button on the splitter. When collapsed is true and
positionedFromEnd is false, the first pane is hidden and the second pane
stretches to fill up the available space. When collapsed is true and
positionedFromEnd is true, the second pane is hidden instead. Visually, the
user can know which pane will be collapsed by looking at the direction of the
arrow on the button. When the user clicks the arrow button on the splitter, the pane
collapses in the direction of the arrow. The splitterPosition and
collapsed attributes are persistable; that is, when the user moves the splitter or
collapses a pane, ADF Faces can implicitly persist the attribute value changes for

413
.
the component.

413
414
.
415
.
416
.
417
.
418
.
419
.
420
.
421
.
422
.
423
.
Panel Collection Component
ADF Faces provides a number of layout components that can be used to arrange other
components on a page. Usually, you begin building your page with these components. You then
add components that provide other functionality (for example, rendering data or rendering
buttons) either inside facets or as child components to these layout components.
The panelCollection component is a layout component that is very useful for displaying
collection components, such as table, tree, and treeTable, because it adds more functionality to
the components placed inside it. You can add a toolbar and a status bar to tables, trees, and
tree tables by surrounding them with the panelCollection component. The top panel contains a
standard menu bar as well as a toolbar that holds menu-type components such as menus and
menu options, toolbars and toolbar buttons, and status bars. Some buttons and menus are
added by default. For example, when you surround a table, tree, or tree table with a
panelCollection component, a toolbar that contains the View menu is added. This menu
contains menu items that are specific to the table, tree, or tree table component.

424
.
Panel Collection
You can use the af:panelCollection component to add menus, toolbars, and status bars to data aggregation components such as tables, trees, and tree tables. You
would create the af:panelCollection component, and then add the table, tree, or tree table component as a direct child of panelCollection.
The af:panelCollection tag contains a menu facet for af:menu, a toolbar facet for af:toolbar, a secondaryToolbar facet for another af:toolbar, and a statusbar facet.
The table, tree, or tree table is added after the last facet.
The default top-level menu and toolbar items depends on the child component being used:
Tables and trees: The default top-level menu is View.
Tables and tree table: The default toolbar menu is Detach.
Tree and tree table (when the pathStamp is used): The toolbar buttons Go Up, Go To
Top, and Show as Top also appear.
The example shown in the slide has the following source code:
<af:panelCollection binding="#{editor.component}">
<f:facet name="menus">
<af:menu text="Actions">
<af:commandMenuItem text="Add..." />
<af:commandMenuItem text="Create.." />
<af:commandMenuItem text="Update..." disabled="true"/>
<af:commandMenuItem text="Copy"/>
<af:commandMenuItem text="Delete"/>
<af:commandMenuItem text="Remove" accelerator="control A"/>
<af:commandMenuItem text="Preferences"/>
</af:menu>
</f:facet>
<f:facet name="toolbar">
<af:toolbar>
<af:commandToolbarButton shortDesc="Create" icon="/new_ena.png">
</af:commandToolbarButton>
<af:commandToolbarButton shortDesc="Update" icon="/update_ena.png">
</af:commandToolbarButton>
<af:commandToolbarButton shortDesc="Delete" icon="/delete_ena.png">
</af:commandToolbarButton>
</af:toolbar>
</f:facet>
<f:facet name="secondaryToolbar"> </f:facet>
<f:facet name="statusbar">
<af:toolbar>
<af:outputText id="statusText" ... value="Custom Statusbar Message"/>
</af:toolbar>
</f:facet>
<af:table rowSelection="multiple" columnSelection="multiple" ...
<af:column ...
</af:column>
The panelCollectioncomponent is a naming container. If you want to add its contained component, such as a table, as partialTriggers(described
later in this lesson), you must use its fully qualified name. For example, if you have a panelCollectioncomponent with id=entriesCollectionand a
contained table with id=deptTable, and you want to update a panelFormon the selection change of the table, you would declare the panelForm's
partialTriggersas:
<panelForm partialTriggers="entriesCollection:deptTable">

425
.
426
.
427
.
428
.
429
.
430
.
431
.
432
.
433
.
434
.
435
.
436
.
437
.
438
.
439
.
440
.
441
.
442
.
443
.
444
.
445
.
446
.
447
.
448
.
449
.
450
.
451
.
452
.
453
.
454
.
455
.
456
.
457
.
458
.
459
.
460
.
461
.
462
.
463
.
464
.
465
.
466
.
467
.
468
.
469
.
470
.
471
.
472
.
473
.
474
.
475
.
476
.
477
.
478
.
479
.
Dynamic Layouts

480
.
Lesson Summary

481
.
482
.
Lesson Agenda
The user interface of a Web application usually comprises multiple pages. In this lesson, you
learn how to use the ADF Controller to manage page navigation and task flows.

In Hands-on lab one would practice:


1. Creating Bounded Task Flows and Add View Activities
2. Creating New Page Fragments
3. Adding Task Flow Call Activities
4. Adding Return Activities
5. Using Bounded Task Flows as a Region on a page

Optionally you may also practice:


1. Using Unbounded Task Flow with View and Control Flow Activities
2. Extracting Part of Task Flow
3. Creating Bounded Task Flow without Fragments
4. Converting Bounded Task Flows to Use Page Fragments

483
.
484
.
485
.
Features of Task Flows
In the lesson titled “Understanding UI Technologies,” you learned that the ADF Controller
enhances the JSF navigation model by providing the concept of task flows.
ADF task flows provide a modular approach for defining control flow in an application. Instead
of representing an application as a single large JSF page flow, you can break it up into a
collection of reusable task flows. In each task flow, you identify application activities, the work
units that must be performed in order for the application to complete. An activity represents a
piece of work that can be performed when running the task flow.
The ADF task flow offers the following advantages over standard JSF page flows:
The application can be broken into a series of tasks, instead of having to represent the
application in a single page flow.
You can use activities other than pages in a task flow.
You can navigate between activities, not just pages.
Task flows are modular and reusable within an application or in different applications.
Shared memory scope enables data to be passed between activities within the task flow. The
ADF controller supports two types of task flows:
1. Unbounded task flows
2. Bounded task flows

486
.
487
.
488
.
Features of Unbounded Task Flows
Although there can be many bounded task flows in an application, there can be only one
unbounded task flow, which is assembled at run time by combining one or more adfc-
config.xml files. The set of files that is combined to produce the ADF unbounded task flow is
referred to as the application’s bootstrap configuration files.
The ADF unbounded task flow represents the outermost task flow of an ADF application. The
application’s entry point can be a view within the ADF unbounded task flow.
As a user navigates within an application, a task flow stack is maintained to keep track of the
calls from task flow to task flow. An ADF unbounded task flow always logically exists as the first
entry on the task flow stack, but would simply be empty if no unbounded task flow is defined.
An unbounded task flow does not contain the well-defined boundary or single entry point of a
bounded task flow. You should use an unbounded task flow if your application has multiple
points of entry. For example, an end user might enter an application through two different
home pages.

489
.
Implement Unbounded Task Flows
By default, adfc-config.xml is the XML configuration file for an ADF unbounded task flow. You
can double-click this file in the Application Navigator to open it in the editor.
There are four tabs at the bottom of the editor that enable you to see different views of the
source file for the task flow, all of which remain coordinated as you edit them:
Diagram: Provides a visual view that enables you to drag source elements, components, or
diagram notations from the Component Palette to define the task flow
Overview: Contains different panels that enable you to configure the task flow
Source: Displays the XML source code, which you can edit directly
History: Shows a history of changes
A common way of working is to initially create pages and navigation in the unbounded task
flow, because that enables you to easily test them in one location. When they are functioning
correctly, you can convert portions of the unbounded task flow to a bounded task flow if
needed.
A typical application is a combination of an unbounded and one or more bounded task flows.
Every Fusion Web application contains an unbounded task flow, even if the unbounded task
flow is empty. The application can call bounded task flows from activities in the unbounded
one.

490
.
Features of Bounded Task Flows
Although there can be only one unbounded task flow in an application, there can be many bounded task flows.
You can think of a bounded task flow as a process because it defines a modular block of task flow functionality for
reuse. It is the only type of task flow that can be used as a region on a page.
Bounded task flows have the following characteristics:
• Single entry point and zero or more well-defined exit points
• Well-defined boundary with a transaction beginning and end. It consists of its own set of private control flow
rules, activities, and managed beans.
• Memory scope (pageFlow scope)variables for passing data between activities within the ADF bounded task flow,
with a lifespan that is longer than request, but shorter than the session scope
• Declarative support for transaction management
- Ability to begin a new transaction upon ADF bounded task flow entry
- Ability to commit or roll back upon ADF bounded task flow exit
• Declarative support for Back button navigation
• Ability to pass input parameters from the ADF bounded task flow caller to store within the pageFlow scope
• Ability to return values back to ADF bounded task flow caller upon exit
• Metadata only loaded on demand
• ADF bounded task flow fragment reuse through task flow templates
• Addressable, in that when you invoke an ADF bounded task flow, you must specify an identifier and the name of
the XML document that contains the identifier Bounded task flows consist of a group of activities and control flows
between the activities that enable a user to complete a task.
There are different types of task flow activities, including the following:
• View activity: Displays a page or page fragment
• Router activity: Evaluates a declarative expression to produce a control flow outcome
• Method call activity: Invokes application logic (Java method) from within the task flow
• Task flow call activity: Calls an ADF bounded task flow
• Task flow return activity: Defines an exit point of the task flow
• Save point restore activity: Restores an application that supports save for later functionality. This is explained in
the lesson titled “Implementing Transactional Capabilities.”
• URL view activity: Redirects the view port to any URL addressable resource

491
.
492
.
493
.
494
.
495
.
496
.
497
.
Define Task Flow Return Activity
When you define a task flow return activity, you need to specify the outcome that is returned
to the calling task flow. You can have only one outcome per task flow return. The calling flow
should have a control flow rule that corresponds to the outcome that you name in the task flow
return activity. If a bounded task flow has its own transaction scope, then the return activity
will also control whether a commit or rollback will happen when the task flow returns to its
caller.
The example in the slide shows the task flow that calls the shopping cart flow. The shopping
cart flow has a return activity, depicted on the right of the slide, whose outcome is defined as
checkout. The calling task flow has a control flow rule named checkout, so when the called
shopping cart flow is exited via the Checkout task flow return activity, navigation in the calling
task flow proceeds to the CheckoutFlow.

498
.
499
.
500
.
Define ADF Control Flow Rules
The overall navigation through a JSF application uses a set of rules for choosing the next page
to display when, for example, the user clicks a button or link. To define the navigation for your
application, you need to define the control flow rules themselves, and then include on the
pages the controls that a user can interact with to navigate to another place in the application
at run time.
ADF Faces components that can be used to implement navigation features on pages include:
• Buttons and links, which users click to navigate to another place in the application
• Components such as tabs and breadcrumbs
• Train components for walking users through sequential steps of a process
Control flow rule definitions are stored in configuration files (adfc-config.xml or a similar
ml file). You can define the rules directly in the .xml configuration file, or you can use the
Navigation Modeler and the Configuration Editor, which offer the following advantages:
• Provide a GUI environment for modeling and editing the navigation between pages
• Enable you to map out your application navigation using a visual diagram
• Update the configuration file for you automatically
Use the Navigation Modeler to initially create control flow rules; use the Configuration Editor to
create global or pattern-based rules for multiple pages, create default navigation cases, and
edit control flow rules. These tools, along with the Structure window, are explained further in
subsequent slides.

501
.
Example of ADF Control Flow Rules
An example of an ADF unbounded task flow showing simple navigation:
<control-flow-rule>
<from-activity-id>browseOrders</from-activity-id>
<control-flow-case>
<from-outcome>showDetail</from-outcome>
<to-activity-id>orderDetail</to-activity-id>
</control-flow-case>
</control-flow-rule>
<control-flow-rule>
<from-activity-id>orderDetail</from-activity-id>
<control-flow-case>
<from-outcome>showOrders</from-outcome>
<to-activity-id>browseOrders</to-activity-id>
</control-flow-case>
</control-flow-rule>
A button on each page fragment invokes the appropriate action. For example, the Show Items
button on the browseOrders page fragment is defined as follows:
<af:commandButton text="Show Items" action="showDetail"/>

502
.
Use Wild Cards
Most control flow rules specify navigation from one activity to another. However, you can also define global rules that affect all
pages by setting the <from-activity-id> element to an asterisk, so that the rule can be called from any page. You can create a
global rule by dragging a wildcard control flow rule element from the Component Palette, and then define the flow outcomes
for the wildcard rule.
The example in the slide shows a wildcard control flow rule that has from-outcome elements to navigate to every page in the
task flow. Because of this wildcard rule, any page in the task flow can navigate to any other page. The source XML looks like
this:
<control-flow-rule>
<from-activity-id>*</from-activity-id>
<control-flow-case>
<from-outcome>shop</from-outcome>
<to-activity-id>ProductCatalog</to-activity-id>
</control-flow-case>
<control-flow-case>
<from-outcome>search</from-outcome>
<to-activity-id>ProductSearch</to-activity-id>
</control-flow-case>
<control-flow-case>
<from-outcome>details</from-outcome>
<to-activity-id>ProductDetails</to-activity-id>
</control-flow-case>
<control-flow-case>
<from-outcome>cart</from-outcome>
<to-activity-id>DisplayShoppingCart</to-activity-id>
</control-flow-case>
<control-flow-case>
<from-outcome>add</from-outcome>
<to-activity-id>AddShoppingCart</to-activity-id>
</control-flow-case>
<control-flow-case>
<from-outcome>checkout</from-outcome>
<to-activity-id>CheckoutFlow</to-activity-id>
</control-flow-case>
</control-flow-rule>

503
.
504
.
Make View Activities Bookmarkable
You can enable users to easily return to a view activity in an unbounded task flow by
designating the activity as bookmarkable. On the Bookmark tab of the Property Inspector, you
can set the bookmark property to true. You can optionally add parameters in the URL
Parameters section and add an optional method binding in the converter field for a parameter’s
value. You can also optionally specify a method in the method field that the ADF Controller
should invoke before rendering the view. You can use this method to retrieve additional
information based on the parameter values.
Instead of making the view activity bookmarkable, you can choose to use the redirect option to
create a new browser URL for the view activity. You do this by setting the redirect property to
true on the Common panel of the Property Inspector for the view activity.

505
.
Check for Dirty Data
SomeDC::isTransactionDirty() works well with those DataControls which have implemented
oracle.adf.model.TransactionalDataControl. Apparently it works with ADF BC. However this may
not work (as of now) with Bean DC as it lacks the specific transactional context
implementation. DCDataControl::isTransactionModified() does not consult underlying model
for checking the modified status, rather it keeps track of 'TxnModified' flag and marks it as dirty
whenever UI pushes updated data to the binding layer.

506
.
507
.
508
.
Create Bounded Task Flow
To create a new task flow that is bounded, you can invoke the New Gallery and select
Web Tier > JSF > ADF Task Flow. In the Create ADF Task Flow dialog box, you perform the
following:
• Give the task flow a name, location, and unique ID.
• Select the “Create as Bounded Task Flow” check box.
• Indicate whether to create it with page fragments. If you want to use page
fragments (discussed in the lesson titled “Ensuring Reusability”), you need to be aware that you
cannot run a page fragment by itself. You may initially create the bounded task flow with pages
and convert it to page fragments after the testing of the task flow is complete.
• Indicate whether to create the task flow as a train, which is a progression of
related pages guiding the end user through a series of steps. Each step in a train contains a UI
component showing the user’s progress and enabling the user to return to earlier steps.
• Indicate whether to use a template and whether to update the task flow when
the template changes.
Another way to create a bounded task flow is to extract part of an existing task flow into its
own bounded task flow. To do this, click the task flow diagram and drag out an area to surround
the activities that you want to include in the separate task flow. Then right-click one of the
activities and select Extract Task Flow from the context menu.

509
.
Page Fragments

510
.
To create a new task flow that is bounded, you can invoke the New Gallery and select
Web Tier > JSF > ADF Task Flow. In the Create ADF Task Flow dialog box, you perform
the following:
• Give the task flow a name, location, and unique ID.
• Select the “Create as Bounded Task Flow” check box.
• Indicate whether to create it with page fragments. If you want to use page fragments
(discussed in the lesson titled “Ensuring Reusability”), you need to be aware that you
cannot run a page fragment by itself. You may initially create the bounded task flow
with pages and convert it to page fragments after the testing of the task flow is
complete.
• Indicate whether to create the task flow as a train, which is a progression of related
pages guiding the end user through a series of steps. Each step in a train contains a UI
component showing the user’s progress and enabling the user to return to earlier steps.
• Indicate whether to use a template and whether to update the task flow when the
template changes.
Another way to create a bounded task flow is to extract part of an existing task flow into its
own bounded task flow. To do this, click the task flow diagram and drag out an area to
surround the activities that you want to include in the separate task flow. Then right-click one
of the activities and select Extract Task Flow from the context menu.

511
.
Convert a Bounded Task Flow to Use Page Fragments
When you are initially developing a bounded task flow, you may use view activities that
correspond to pages (.jspx). However, to use a task flow as a region, the view activities cannot
be full pages, so you can convert the task flow to one that uses page fragments. You have to
only right-click a blank space on the task flow diagram and select Convert To Task Flow With
Page Fragments.
This converts all pages associated with view activities in the bounded task flow to page
fragments. You can optionally save old pages by selecting the Keep Page? check box. New page
fragment names default to the names of the old pages. For example, MyPage.jspx becomes
MyPage.jsff.
Note: It is best practice to use page fragments on other pages only through bounded task
flows, even if you have a page flow with only that page fragment.

512
.
513
.
514
.
515
.
Lesson Agenda
ADF Faces contains several components to enhance and implement navigation on pages. This
lesson teaches you how to implement such navigation by using ADF Faces navigate on
components

In Hands-on lab one would practice:


1. Creating Links and Buttons for Navigation
2. Using Menu and Menu Items

Optionally you may also practice:


1. Assigning Internationalization and Accessibility
2. Using BreadCrumbs
3. Using Popup Dialog
4. Defining Sequence of Steps (Train) and Use Wild Card Activity

516
.
517
.
518
.
Overview of Navigation Components
Navigation components in ADF Faces include:
• Button and link components for navigating to another location with or without server-side
actions
• Components that render items such as tabs and breadcrumbs for navigating hierarchical
pages
• Train components for navigating a multistep process

519
.
520
.
521
.
Use Breadcrumbs
The af:breadCrumbs component enables you to display a path of links for navigation. You can
explicitly define the links by using one af:commandNavigationItem component for each.
Alternatively, you can define the links dynamically by using the XML Menu Model.
You need to add the breadcrumbs to each page that should display them, or use a page
fragment or page template, discussed in the lesson titled “Ensuring Reusability.”

522
.
Use Explicitly Defined Breadcrumbs
To provide a simple navigation hierarchy where you define the navigation items for the
breadcrumbs, you can add the af:breadCrumbs component to each page, with one or more
af:commandNavigationItem components that you explicitly set. The value of the
af:commandNavigationItem component’s attributes may be set to a page or to an EL
expression.
For example, in a shopping application, you may want to enable the user to follow the
breadcrumbs to display categories and subcategories of products, rather than pages, as shown
in the example in the slide. Instead of static values, you can use parameters and action listeners
to make these breadcrumbs dynamic, displaying the names of the categories and subcategories
by using EL expressions that evaluate to changing parameter values.

523
.
524
.
Overview of XML Menu Model
For a very simple page hierarchy, you can manually create navigational components, such as
breadcrumbs or navigation panes, and add navigation items for each. However, this becomes
very cumbersome when a navigational hierarchy encompasses several pages. An ADF menu
model enables you to create complex navigational hierarchies without all the tedious manual
coding.
You can organize related JSF pages in a tree-like hierarchy that users can navigate to drill down
or up to another level of the hierarchy by using navigation items in navigation panes or
breadcrumbs. The XML Menu Model represents navigation for a page hierarchy in XML format.
The hierarchy is described within the menu element. The hierarchy is composed of nodes, each
of which can correspond to a page. The menu element can contain the following types of
nodes:
groupNode: Contains one or more child nodes to navigate to indirectly, and must
reference the ID of at least one of its child nodes, which can be an item node or another group
node
itemNode: A node that performs navigation upon selection
sharedNode: References another XML menu, and is used to link or include various
menus
For more information and examples of creating an XML Menu hierarchy, see the Web User
Interface Developer’s Guide for ADF and the Fusion Developer’s Guide for ADF.

525
.
Define Sequence of Steps
If you have a set of pages that users should visit in a particular order, consider using the af:train component on each page to
display a series of navigation items to guide users through the multistep process. Not only does a train display the number of
steps in a multistep process, it also indicates the location of the current step in relation to the entire process.
Suppose you have eight steps in a multistep process, such as creating a new item in an inventory system. When configured
properly, the af:train component would render all eight steps on a page, with each step represented as a train stop, and with
all the stops connected by lines. Each train stop has an image (for example, a square block) with a label underneath the image.
The slide shows an example of how this train could look on a page.
Each train stop corresponds to one step or one page in your multistep process. Users navigate the train stops by clicking an
image or label, which causes a new page to display. Typically train stops must be visited in sequence, that is, a user cannot
jump to step 3 if the user has not visited step 2.
As shown in the slide, a train is actually a specialized type of task flow with linear steps.
Note: Internationalization of the text displayed for a train stop is currently not supported.
As shown in the slide, the train component provides at least four styles for train stops:
The current stop is indicated by a bold font style in the label, and a different image for the stop.
Stops visited before the current stop are indicated by a different label font color and image
color.
The next stop immediately after the current stop appears enabled.
Any other stops that have not been visited are disabled.
A train stop can include a subprocess train. That is, you can launch a child multistep process from a parent stop, and then
return to the correct parent stop after completing the subprocess. Suppose stop #4 has a subprocess train containing three
stops. When the user navigates to the first stop in the subprocess train, ADF Faces displays an icon representing the parent
train before and after the subprocess train.
Adding Navigation Buttons
The af:trainButtonBar component may be used in conjunction with the af:train component to provide additional navigation
items for the train, in the form of Back and Next buttons. The third example in the slide shows what a rendered
af:trainButtonBar component could look like. The Back and Next buttons provided by af:trainButtonBar enable users to
navigate only to the next or previous train stop from the current stop. You can also use the af:trainButtonBar component
without af:train.
The train and train button bar work by having the value attribute bound to a train model of type
org.apache.myfaces.trinidad.model.MenuModel. The train menu model contains the information needed to:
Control a specific train behavior (that is, how the train advances users through the train stops to complete the multistep
process)
Dynamically generate the train stops, including the train stop labels, and the status of each stop (that is, whether a stop is
currently selected, visited, unvisited, or disabled)

526
Skip Train Stop
You can set a train stop to be skipped by setting the skip property to true. You would typically
set this property to an EL expression that evaluates to true or false to conditionally skip the
train stop.
The example in the slide shows the Property Inspector for a view in the task flow of the train.
The skip property is set to a managed bean method that is coded to perform some evaluation
and conditionally return either true or false.
At run time, the user cannot navigate to a skipped train stop.

527
.
Use Menus for Navigation
ADF Faces provides menu bars and toolbars that you can add to a page. Menu items and
toolbar buttons enable users to perform some change on a selected object or to navigate
somewhere else in the application. A toolbox can be used to group menus and multiple
toolbars together. The example in the slide contains both a menu bar and a toolbar.
Both menu items and toolbar buttons have the capability to display differently when selected.
Additionally, they can both navigate to other pages in the application, and perform any logic
needed for navigation in the same way that other command components do.
You use the menuBar component to render a bar that contains the menu bar items, such as File
in the example. Each item on a menu bar item is rendered by a menu component, which holds
a vertical menu. Each vertical menu consists of a list of commandMenuItem components that
can invoke some operation on the application. You can nest menu components inside menu
components to create submenus.

528
.
529
.
530
.
Printable Page Behavior
The af:showPrintablePageBehavior operation creates a printable page that the user can print by
using the browser’s Print button. To allow printing, place the af:showPrintablePageBehavior
component (an Operations component) within the page. The showPrintablePageBehavior tag is
an operation, so you can drag it from the Operations components section of the Component
Palette to a button or any other component that executes an operation.
If the page contains a layout component with panes, such as a panel splitter, place the button
that contains the af:showPrintablePageBehavior component in the facet whose pane contents
you want users to be able to print. For example, in a panel splitter, if the second facet is the
main content area of the af:panelSplitter component, then insert the button that contains the
af:showPrintablePageBehavior component into that facet. If you insert
af:showPrintablePageBehavior anywhere outside of af:panelSplitter, the printed result may not
contain all of the main content area.
Therefore, it is important to place the print operation within the af:panelSplitter facet whose
pane contents users would normally want to print. If both facets need printing support, insert
one af:showPrintablePageBehavior component into each facet. To print contents of both panes,
the user then has to execute the print command one pane at a time.

531
.
Use Toolbar, Toolbar Buttons and Toolboxes
Along with menus, you can create toolbars in your application that contain toolbar buttons
used to initiate some operation in the application. The buttons can display text, an icon, or a
combination of both. You can use the group component to group related toolbar buttons.
Toolbars can also contain other UI components, such as drop-down lists, command buttons,
and command links. However, toolbar buttons provide additional functionality:
The af:commandToolbarButton component has a popup facet that enables you to
provide pop-up menus from a toolbar button.
The flex property of a component can be set to an integer that indicates the ratio of this
component to other flexible components within the same container.
You can use more than one toolbar component by enclosing them in a toolbox component (in
the Layout group of the Component Palette). Doing so stacks the toolbars so that the first
toolbar on the page displays on the top, and the last toolbar displays at the bottom. When you
use more than one toolbar, you can set the flex attribute on the toolbars to determine which
toolbar should be the longest. If you want toolbars to be displayed next to each other (rather
than stacked), you can enclose them in a group component.
Within a toolbar, you can set one component to stretch so that the toolbar will always equal
that of its parent container. When a window is resized such that all the components within the
toolbar can no longer be displayed, the toolbar displays an overflow icon.

532
.
533
.
534
.
535
.
536
.
Create Pop-up Menus
You can also have the menu launch in a pop-up window that displays vertically. To create a pop-
up menu, perform the following steps:
Drag the ToolbarButton component to a toolbar on the JSF page and set the text attribute to
display the name of the button. Use the icon attribute to set the image to use on the button.
In the Structure window, expand the ToolbarButton facets and drag a Menu component to the
popup facet.
Drag to the Menu component as many Menu Item components as needed to define the items
in the vertical menu. Set properties on the Menu Items as needed.

537
.
538
.
539
.
Creating Context Menus
ADF Faces client behavior tags provide declarative solutions to common client operations that
you would otherwise have to write yourself using JavaScript, and register on components as
client listeners. In this release, ADF Faces supports the client behavior af:showPopupBehavior
to use in place of a client listener. You perform the following steps to use
af:showPopupBehavior to create a context menu for a component:
1. Create a pop-up menu with af:popup, af:menu, and af:commandMenuItem components.
2. Give the pop-up menu an ID.
3. Create a component to use the context menu.
4. Drag the af:showPopupBehavior operation to the component and set properties:
• popupId: Specify the ID of the af:popup component whose contents you want to display in
a pop-up.
• alignId: Specify the ID of the component to align the pop-up contents with.
• align: Specify an alignment position that is relative to the component identified by alignId.
• triggerType: Specify the event type to use to trigger the pop-up. Default is action, because
typically you would associate af:showPopupBehavior with a command component. When
the command component is clicked, an action event is fired, which triggers the pop-up to
display. If you associate af:showPopupBehavior with some other noncommand
component, such as af:outputText, set triggerType on af:showPopupBehavior to
contextMenu, which displays a pop-up context menu. The slide shows a sample code that
displays a pop-up menu when users right-click the text rendered by af:outputText. The
slide also shows the sample context menu generated at run time.
Note: You can use the same general steps to display a pop-up window that contains any
components, not just one that contains a menu.

540
.
541
.
542
.
Navigation cases are defined in the faces-config.xml file and are defined from a page source to
a page target based on the outcome of an action. Alternatively the navigation can be from a
method source.

543
.
Definition of the navigation case in the faces-config.xml:

<!ELEMENT navigation-rule (description*, display-name*, icon*, from-view-id?, navigation-


case*)>

The from-view-id element is the identifier of the page of origin. To describe the navigation rule
for a JSP page called index.jsp, the following is the value of the from-view-id subelement:

<from-view-id>/index.jsp</from-view-id>

<!ELEMENT navigation-rule (description*, display-name*, icon*, from-view-id?, navigation-


case*)>

The navigation-case element represents a possible target. A navigation-rule element can have
zero or several navigation-case subelements.

Each navigation-case element specifies the target page for a particular outcome of the from-
view-id processing. An outcome can come from the action attribute of the UICommand
component in the from-view-id element.

544
.
Wildcard = *

<navigation-rule>
<from-view-id>/app/*</from-view-id>
<navigation-case> . . . </navigation-case>
</navigation-rule>

Applies to all pages that are stored within /app/ directory and thus have this string as a
viewId prefix

Default match looks for “*” only

545
.
To programmatically set a new navigation target, we need to get a hold onto the ViewHandler
to create the new UIViewRoot. Note that you could also restore an existing view if it is still
available. However this requires some more complex tracking than what we want to show in
this training.

Once we have a handle to the ViewHandler, we call its create() method and add the access path
to the JSF page we want tp navigate to. The access path is the path that starts in public-html,
the directory that JSP pages are based in by default. The SRMain page is located in public-
html\app\SRMain.jsp

Setting the view root immediately navigates to the new page. To avoid conflicts e.g. if using this
in an action event in the backing bean, make sure that this method then returns null.

546
.
547
.
Perform Navigation
Like any JSF application, an application that uses ADF Faces components contains a set of rules
for choosing the next page to display when, for example, a button or link is clicked. You define
the rules in an ADF Faces application by adding control flow rules and cases to task flows.
JSF uses an outcome String to select the control flow rule to use to perform a page navigation.
ADF Faces navigation components generate an action event when users activate the
component. The JSF navigation handler and default ActionListener mechanism use the logical
outcome String on the activated component to find a match in the set of control flow rules.
When JSF locates a match, the corresponding page is selected and rendered.
The example in the slide shows two pages in an ADF task flow:
The BrowseOrders page has a control-flow-case whose control flow from-outcome is
named showItems, which defines that navigation should go to the OrderItems page.
The OrderItems page has a control-flow-case whose control flow from-outcome is
named goOrders, which defines that navigation should return to the BrowseOrders page. There
are two command buttons on the pages:
The BrowseOrders page has a command button whose action is set to showItems.
The OrderItems page has a command button whose action is set to goOrders.

548
.
549
.
Use Access Key
You can define access keys (also known as mnemonics or shortcut keys) in the Property Inspector for the
component by entering the mnemonic character in the AccessKey property.
Use one of the following attributes to specify a keyboard character for an ADF Faces input, command, or go
component:
accessKey: Use to set the mnemonic character used to gain quick access to the
component. For command buttons, command links, go buttons, and go links, the character specified by this
attribute must exist in the text attribute of the component; otherwise, ADF Faces does not display the visual
indication that the component has an access key.
textAndAccessKey: Use to simultaneously set the text and the mnemonic character for a component using the
ampersand (&) character. In .jspx files, use &amp; for an
ampersand. In JSP files and in the Property Inspector, you need to use only the &. The ampersand should precede
the character to be used as an access key.
labelAndAccessKey: Use to simultaneously set the label attribute and the accesskey on an input component using
conventional ampersand notation
valueAndAccessKey: Use to simultaneously set the value attribute and the access
key using conventional ampersand notation. The example in the slide specifies the label as
Select Date and sets the access key to e, the letter immediately after the ampersand.
Reusing Access Keys
You can bind the same access key to several components. If the same access key appears in multiple locations on
the same page, the rendering agent cycles among the components accessed by the same key. That is, each time
the access key is pressed, focus moves from component to component. When the last component is reached,
focus returns to the first component.
Depending on the browser, if the same access key is assigned to two or more Go components on a page, the
browser may activate the first component instead of cycling through the components that are accessed by the
same key.
Note: If you assign an access key that is already defined as a shortcut menu in the browser, the ADF Faces
component access key takes precedence

550
.
551
.
552
.
Lesson Agenda
This lesson teaches you to create and use components that are reusable: page templates, page
fragments, declarative components, and bounded task flows in regions. It also introduces the
concepts of the Resource Catalog and ADF libraries to package components and make them
available for reuse.

In Hands-on lab one would practice:


Creating and Using Reusable Component

Optionally you may also practice:


1. Creating Page Templates
2. Applying Template to Existing Page Fragments
3. Creating a New Header Template
4. Applying Template to Existing Page
5. Creating a New Page with Template
6. Adding Panel Springboard Component
7. Converting JSPX to Facelets

553
.
554
.
Benefits of Reusability
Duplicating code or content is one of the worst practices. It can be an easy solution sometimes,
but changing the application becomes a lot more difficult, which means that in the long term,
you cannot adapt to new user requirements or fix problems quickly. Ideally, an application
should not contain multiple versions of the same code and the Web content should not be
copied and pasted.
Code reuse can increase developer productivity and application maintainability. Instead of
reinventing the wheel, you should always look for well-designed frameworks and customizable
components. Application-specific code can also be reused across modules and even across
related projects. This latter type of reusability allows you to make rapid changes, exploit new
features globally, and spend less time testing and debugging.
These things might sound like good advice for programmers, but Web developers should pay
attention to them too. Oracle ADF Faces provides built-in components along with support for
creating additional reusable components. Very often, however, the bits of HTML and JSP
markup are copied from one Web page and pasted into other pages, which means that
multiplied markup has to be modified everywhere when the Web content changes. In addition,
the look of an application becomes inconsistent if some of the pages are not updated. This
does not happen if the UI parts are reused across pages so that any change requires editing in
exactly one place.

555
.
Design for Reuse
Creating and consuming reusable components should be included in the early design and
architectural phases of software projects. You and your development team should consider
which components are candidates for reuse, not only in the current applications but also for
future applications and for applications being developed in other departments.
When you create reusable components, you should try to create unique and relevant names for
the application, project, application module, task flow, or any other relevant file or component.
Do not accept the JDeveloper Wizard’s default names, but try to have unique names to avoid
name conflicts with other projects or components in the application. You should also consider
creating standardized naming conventions so both creators and consumers of ADF Library JARs
can readily identify the component functionality.
You and your team should decide on the type of repository needed to store the library JARs,
where to store them, and how to access them. You should consider how to organize and group
the library JARs in a structure that fits your organizational needs.

556
.
Types of Reusable Components
The following reusable components are supported by ADF:
Data Control: Any data control can be packaged into an ADF Library JAR.
Application Module: When you package an application module data control, you also package
the business components associated with that application module.
Business Components: Business components are the entity objects, view objects, and
associations used in the business layer; you can package them by themselves or together with
an application module.
Task Flows and Task Flow templates: Task flows can be packaged into an ADF Library
JAR for reuse. ADF bounded task flows built using pages can be dropped onto pages, creating a
link to call the bounded task flow. If an ADF task flow template was created in the same project
as the task flow, the ADF task flow template is included in the ADF Library JAR and is reusable.
Page Templates: You can package a page template and its artifacts into an ADF Library JAR. If
the template uses image files and they are included in a directory within your project, these
files are also available for the template during reuse.
Declarative Components: You can create declarative components and package them for reuse.
The tag libraries associated with the component are included and loaded into the consuming
project.

557
Types of Reusable Components
The following reusable components are supported by ADF:
Data Control: Any data control can be packaged into an ADF Library JAR.
Application Module: When you package an application module data control, you also package
the business components associated with that application module.
Business Components: Business components are the entity objects, view objects, and
associations used in the business layer; you can package them by themselves or together with
an application module.
Task Flows and Task Flow templates: Task flows can be packaged into an ADF Library
JAR for reuse. ADF bounded task flows built using pages can be dropped onto pages, creating a
link to call the bounded task flow. If an ADF task flow template was created in the same project
as the task flow, the ADF task flow template is included in the ADF Library JAR and is reusable.
Page Templates: You can package a page template and its artifacts into an ADF Library JAR. If
the template uses image files and they are included in a directory within your project, these
files are also available for the template during reuse.
Declarative Components: You can create declarative components and package them for reuse.
The tag libraries associated with the component are included and loaded into the consuming
project.

558
Use a Resource Catalog
The Resource Catalog is your window into the many disparate resources that your application
may need to consume. It enables you to define connections to the resource providers, and to
drag those resources into your application as needed. The resource catalog provides a search
tool to search all the defined repositories in a single action. Connections can be created for the
following types of resource repositories:
Application server
Database
File system
UDDI Registry
URL adapter
WebDAV
BAM/Fabric
BI Presentation server
BPEL
MDS connection
Portlet producers
Virtual Content Repository (VCR)
WSDL adapter

559
.
560
.
Types of Reusable Components
The following reusable components are supported by ADF:
Data Control: Any data control can be packaged into an ADF Library JAR.
Application Module: When you package an application module data control, you also package
the business components associated with that application module.
Business Components: Business components are the entity objects, view objects, and
associations used in the business layer; you can package them by themselves or together with
an application module.
Task Flows and Task Flow templates: Task flows can be packaged into an ADF Library
JAR for reuse. ADF bounded task flows built using pages can be dropped onto pages, creating a
link to call the bounded task flow. If an ADF task flow template was created in the same project
as the task flow, the ADF task flow template is included in the ADF Library JAR and is reusable.
Page Templates: You can package a page template and its artifacts into an ADF Library JAR. If
the template uses image files and they are included in a directory within your project, these
files are also available for the template during reuse.
Declarative Components: You can create declarative components and package them for reuse.
The tag libraries associated with the component are included and loaded into the consuming
project.

561
Reuse Components
In the course of application development, certain components are often used more than once.
Whether the reuse happens within the same application, or across different applications, it is
often advantageous to package these reusable components into a library that can be shared
between different developers, across different teams, and even across departments within an
organization.
ADF Library provides a convenient and practical way to create, deploy, and reuse high-level
components. You should design your application with component reusability in mind. If you
created components that can be reused, you can package them into JAR files and add them to a
resource catalog. If you need a component, you may look into the resource catalog for that
component, and then add the library into your project or application.
For example, you can create an application module for a domain and package it up to be used
as the model project in several different applications. Or, if your application consumes
components, you may be able to load a page template component from a repository of ADF
Library JARs to create common look-and-feel pages. Then you can put your page flow together
by stringing several task flow components pulled from the library.

562
.
Remove an ADF Library from Project
You can remove an ADF Library JAR only if there are no dependencies from any components to
the ADF Library components. When you remove a JAR, it is no longer in the project class path
and all its components are no longer available for use.
There are two ways to remove an ADF Library from a project:
By using the Resource Palette: Right-click the JAR in the Resource Palette and select “Remove
from Active Project.”
Manually remove the JAR using the Project Properties window:
In the Application Navigator, double-click the project.
In the Project Properties dialog box, select “Libraries and Classpath” in the left pane.
In the “Libraries and Classpath” list, select ADF Library. Click Edit.
In the Edit Library Definition window, select the ADF Library JAR that you want to remove under
the Class Path node. Click Remove.
Click OK to accept the deletion, and click OK again to exit the Project Properties window.
After you have deleted all ADF Library JAR files from the project, an ADF Library placeholder
icon may still be present in the Project Properties Libraries window, as shown in the slide. You
do not need to remove this icon.

563
.
Restrict BC Visibility in Libraries
When deploying a library for reuse, there may be some business components that are not
intended for reuse, but must be included in the library because other components depend
upon them. For example:
The library developer wants consuming projects to access components in the library only
through services exposed on the application module. All components in the library are private
and may not be reused.
The library developer wants consuming projects to access an entity object only by using or
extending view objects in the library, and the entity object contains attributes that should not
be exposed in any view object. In this case, the entity object is private and the view objects are
public.
You can mark an ADF BC object as public (the default) or private. Setting Library Private to
true keeps the object from appearing to the consumer who is browsing the library JAR.
To mark a BC object as private, perform the following steps:
Open the object in the editor.
In the Property Inspector, click the Type tab and set Library Private to true.
When an object is marked as private, it is not visible in the Resource Catalog or in the
Application Navigator of the consuming project

564
.
Types of Reusable Components
The following reusable components are supported by ADF:
Data Control: Any data control can be packaged into an ADF Library JAR.
Application Module: When you package an application module data control, you also package
the business components associated with that application module.
Business Components: Business components are the entity objects, view objects, and
associations used in the business layer; you can package them by themselves or together with
an application module.
Task Flows and Task Flow templates: Task flows can be packaged into an ADF Library
JAR for reuse. ADF bounded task flows built using pages can be dropped onto pages, creating a
link to call the bounded task flow. If an ADF task flow template was created in the same project
as the task flow, the ADF task flow template is included in the ADF Library JAR and is reusable.
Page Templates: You can package a page template and its artifacts into an ADF Library JAR. If
the template uses image files and they are included in a directory within your project, these
files are also available for the template during reuse.
Declarative Components: You can create declarative components and package them for reuse.
The tag libraries associated with the component are included and loaded into the consuming
project.

565
566
.
Wrap a Task Flow as a Region
You can drag to your page a bounded task flow that includes page fragments and create it as a
region on the page. The default activity of the task flow appears in the editor and on the page
when it is first run.
At run time, you can use page navigation (described in the lesson titled “Implementing
Navigation on Pages”) to navigate through the task flow. As you do this, the region refreshes
without redrawing the entire page (partial page refresh).

567
.
.
569
.
570
.
571
.
572
.
573
.
Types of Reusable Components
The following reusable components are supported by ADF:
Data Control: Any data control can be packaged into an ADF Library JAR.
Application Module: When you package an application module data control, you also package
the business components associated with that application module.
Business Components: Business components are the entity objects, view objects, and
associations used in the business layer; you can package them by themselves or together with
an application module.
Task Flows and Task Flow templates: Task flows can be packaged into an ADF Library
JAR for reuse. ADF bounded task flows built using pages can be dropped onto pages, creating a
link to call the bounded task flow. If an ADF task flow template was created in the same project
as the task flow, the ADF task flow template is included in the ADF Library JAR and is reusable.
Page Templates: You can package a page template and its artifacts into an ADF Library JAR. If
the template uses image files and they are included in a directory within your project, these
files are also available for the template during reuse.
Declarative Components: You can create declarative components and package them for reuse.
The tag libraries associated with the component are included and loaded into the consuming
project.

574
Characteristics of Page Fragments
As you build Web pages for an application, some pages may quickly become large and
unmanageable. One possible way to simplify the process of building and maintaining complex
pages is to use page fragments.
Large, complex pages broken down into several smaller page fragments are easier to maintain.
Depending on how you design a page, the page fragments created for an entire page may also
be reused on other pages. For example, suppose different parts of several pages use the same
components, then you might find it beneficial to create page fragments containing those
components, and reuse those page fragments on several pages or in several places on the same
page. Deciding on how many page fragments to create for one or more complex pages depends
on your application, the degree to which you want to reuse portions of a page between
multiple pages, and the need to simplify complex pages.
Page fragments are created and used much like pages, except that page fragments are not
defined as a full Web page. This enables page fragments to be used as a smaller part of a larger
page. To utilize the capability of page fragments to be used as part of a page, it is likely that
most pages for Fusion applications will be built as page fragments.
A page fragment does not contain f:view or af:document; its contents are simply enclosed
within jsp:root. You cannot run page fragments like you can run complete JSF pages.

575
.
Use a Page Fragment on a Page
When you build a JSF page using page fragments, the page can use one or more page fragments
that define different portions of the page. The same page fragment can be used more than
once on a page, and on multiple pages.
To consume a page fragment on a JSF page, at the part of the page that will use the page
fragment contents, insert the jsp:include tag to include the desired page fragment file, as in the
following example:
<jsp:include page="/fragment_page.jsff"/>
Another way to use a page fragment is as part of a bounded task flow that you add to a page as
a region; this is described shortly.
When you modify a page fragment, the pages that consume the page fragment automatically
display the modifications. With pages built from page fragments, when you make layout
changes, you should check that the overall layout of pages that consume the page fragments
still meet requirements.
If the consuming page uses Oracle ADF Model data binding, a page fragment used with
jsp:include uses the binding container of the consuming page, so its page definition file is not
loaded. Only page fragments created as part of ADF bounded task flows can have their own
binding context.

576
.
Types of Reusable Components
The following reusable components are supported by ADF:
Data Control: Any data control can be packaged into an ADF Library JAR.
Application Module: When you package an application module data control, you also package
the business components associated with that application module.
Business Components: Business components are the entity objects, view objects, and
associations used in the business layer; you can package them by themselves or together with
an application module.
Task Flows and Task Flow templates: Task flows can be packaged into an ADF Library
JAR for reuse. ADF bounded task flows built using pages can be dropped onto pages, creating a
link to call the bounded task flow. If an ADF task flow template was created in the same project
as the task flow, the ADF task flow template is included in the ADF Library JAR and is reusable.
Page Templates: You can package a page template and its artifacts into an ADF Library JAR. If
the template uses image files and they are included in a directory within your project, these
files are also available for the template during reuse.
Declarative Components: You can create declarative components and package them for reuse.
The tag libraries associated with the component are included and loaded into the consuming
project.

577
Characteristics of Page Template
A page template provides a reusable page definition that enforces consistent branding and
page layout across the application. It enables developers to change the branding and page
layout for all the pages or page fragments that use the page template by changing only the
page template definition. Templates can contain attributes and ADF bindings.
Page templates use standard ADF components; therefore, all skins are automatically applied.
They cannot be nested, or based on another page template. Pages that use the same page
template take advantage of partial page refresh—just the content that is specific to a page
changes without the need to refresh the template.
There are two sets of page template definition files:
For each page template there is:
A JSP XML file (.jspx), which defines the rendered UI in terms of other JSF
components, facet references, and EL expressions resolved against the page template’s UI
attributes and model
An optional model-specific file—for example, an ADF page definition (.pdm) file
Across all page templates there is:
A pagetemplate-metadata.xml file, which contains the paths of all the page template
definitions in the project, located in the META-INF directory of the project
An application or library .cpx file, which contains any application and library-wide
model information

578
.
.
580
.
581
.
582
.
583
.
584
.
585
.
Types of Reusable Components
The following reusable components are supported by ADF:
Data Control: Any data control can be packaged into an ADF Library JAR.
Application Module: When you package an application module data control, you also package
the business components associated with that application module.
Business Components: Business components are the entity objects, view objects, and
associations used in the business layer; you can package them by themselves or together with
an application module.
Task Flows and Task Flow templates: Task flows can be packaged into an ADF Library
JAR for reuse. ADF bounded task flows built using pages can be dropped onto pages, creating a
link to call the bounded task flow. If an ADF task flow template was created in the same project
as the task flow, the ADF task flow template is included in the ADF Library JAR and is reusable.
Page Templates: You can package a page template and its artifacts into an ADF Library JAR. If
the template uses image files and they are included in a directory within your project, these
files are also available for the template during reuse.
Declarative Components: You can create declarative components and package them for reuse.
The tag libraries associated with the component are included and loaded into the consuming
project.

586
587
.
Types of Reusable Components
The following reusable components are supported by ADF:
Data Control: Any data control can be packaged into an ADF Library JAR.
Application Module: When you package an application module data control, you also package
the business components associated with that application module.
Business Components: Business components are the entity objects, view objects, and
associations used in the business layer; you can package them by themselves or together with
an application module.
Task Flows and Task Flow templates: Task flows can be packaged into an ADF Library
JAR for reuse. ADF bounded task flows built using pages can be dropped onto pages, creating a
link to call the bounded task flow. If an ADF task flow template was created in the same project
as the task flow, the ADF task flow template is included in the ADF Library JAR and is reusable.
Page Templates: You can package a page template and its artifacts into an ADF Library JAR. If
the template uses image files and they are included in a directory within your project, these
files are also available for the template during reuse.
Declarative Components: You can create declarative components and package them for reuse.
The tag libraries associated with the component are included and loaded into the consuming
project.

588
.
Characteristics of Declarative Components
Declarative components are reusable, composite UI components that are made up of other existing ADF Faces
components. Suppose you are reusing the same components consistently in multiple circumstances. Instead of
copying and pasting the commonly used UI elements repeatedly, consider defining a declarative component that
contains those components, and then reusing that composite declarative component in multiple places or pages.
Any changes to the declarative component affect all pages that use the declarative component. Declarative
components do not support ADF Model parameters. They are not databound and contain no business logic. This
means that you cannot drag an item from the Data Controls panel when defining the component layout section of
a declarative component. However, when consuming a declarative component on a page, you can drop databound
content into the facets defined on the declarative component, and the declarative component’s attributes can
have data binding. For example, if you want to reuse a databound address object that comprises four input fields
on a JSF page, you could create a declarative component with four input components and four parameters, and
assign the parameters to the value attributes of the input components. At design time, the page author can bind
the input component values (via the declarative component’s attributes in the Property Inspector) to different
data sources, including ADF Model data binding.
Declarative components are composed of other components. For example, you could design a declarative
component to include a facet (placeholder) for the product image component and facets for two text
components to display a product description and product cost. You can also hide attributes, such as labels, of a
declarative component, so that they cannot be changed by other developers who use the component.
A declarative component cannot be changed or customized at run time. It must be defined at design time,
and uses the following definition files:
• A JSP xml file (.jspx) that defines the rendered UI in terms of other JSF components, Facet references, and EL
expressions resolved against the declarative component’s UI attributes. There is one such file for each declarative
component
• A declarativecomp-metadata.xmlfile that contains the declarative components’ file paths in the project. This file,
located in the META-INFdirectory of the project, is shared across all declarative component definitions in an
application or library

590
.
Create a Declarative Component
When you invoke the Create JSF Declarative Component dialog box, you can specify the name
of the component, its file name and path, and the package in which to place it. You must add a
tag library, and you can define facets, attributes, and methods for the component. When you
click OK, the .jspx file opens in the editor. You can drag components to the editor to create the
component.
JDeveloper creates an <af:componentDef> tag in the declarative component definition JSPX
fragment. This tag acts as the root of the tag hierarchy. This tag describes the entire declarative
component in two sections:
af:xmlContent section: Defines the declarative component metadata in facet and
attribute elements
Component layout section (anything outside of af:xmlContent):
Defines the actual UI components that make up the composite declarative component
Requires that only one child is defined for the layout, so you can use one of the panel layouts to
contain multiple elements
Uses af:facetRef tags to reference named facets, and EL expressions containing
named attributes to enable page authors to set their own property values for the declarative
component

591
.
Use a Declarative Component on a Page
To use a declarative component on a page, you first have to ensure that the component
appears in the Component Palette. You then can drag the component to a page just as you
would any other component.
To use a declarative component in another project, you first must deploy the components’
project as an ADF library JAR file, and then add it to your current project as described
previously—but add it as a JSP tag library. After it is added to your project, the library appears
in the drop-down list in the Component Palette, and you can use any declarative components
defined in that library by dragging them to a JSF JSP.
You can use the Property Palette to provide values for the attributes that you defined. If you
marked any of the attributes as required, when you drag the component to the page, a dialog
box appears to enable you to enter attribute values.

592
.
Decide Which to Use
At first you may be confused about the differences between page templates, declarative
components, and bounded task flows and when you would want to use each.
You could use a page template when multiple pages have similar layout. For example, you may
want to display several data elements with a master at top and detail at the bottom in a panel
splitter. You may also want several pages to have a similar look and feel, such as branding,
header, footer, or toolbars.
A declarative component is a composite of existing components that you define and reuse from
the Component Palette. If you often find yourself constructing groupings of components that
are the same, you can define a declarative component, so that all you need to do is drag it from
the Component Palette to reuse it in multiple pages or applications. For example, you could
define an address component that could be used whenever you display an address of any type
in any application. That declarative component can be bound to different data, just like any
component.
Bounded task flows are useful any time you have a set of activities and control flows that needs
to be reused, such as a shopping cart or checkout in a shopping application, or creating an
account in a banking application. You can call the bounded task flow. When constructed with
page fragments, a bounded task flow can be used in a region on a page, so that the activities
are displayed in the region without refreshing the entire page. You can create a portlet from a
task flow as well.

593
.
594
.
595
.
Lesson Agenda
This lesson explains how to pass parameters and values between UI elements such as pages,
regions, and bounded task flows.

In Hands-on lab, optionally you may also practice:


1. Implementing Set Action Listener, Scopes and Partial Page Refresh
2. Setting Conditional Display
3. Defining Task Flow Parameters
4. Defining Regions Parameters
5. Using Refresh Property in PageDef

596
.
597
.
BAT = Bhagat ADF Training.
PSP = Parameters, Scopes and Partial Page Refresh (PPR).

598
.
599
.
Memory scopes:
• Application Scope: The object will be stored for the duration of the current application and
it is across user sessions.
• Session Scope: The object is available for the current user session and will not be available if
the user exits out of the session. We will use the SessionScope API to store the object in the
session. In an EL expression we used it as #{sessionScope.param}. You should not reference
or use the standard servlet scopes such as session, application, or request to refer to the
managed bean. Referring to the managed bean with a standard prefix will fail to instantiate
the bean.
• Page Flow Scope: The object is available for the duration of the bonded task flow. We use
#{pageFlowScope.param} to access the object stored in pageFlowScope.
• Request Scope: The object is available only from the HTTP request and the response time is
sent back to the client.
• Backing Bean Scope: The object is available from the time an HTTP request is made until a
response is sent back to the client. The scope is just like Request Scope and is only used for a
managed bean and for developing custom components. Each page can have more than one
page fragment or a declarative component and we would want to separate the scope
instances from each other. The scope is used as #{backingBeanScope.param}.
• View Scope: The object is available only for the time the view ID is available and it is
unavailable if the ID changes. If we want to store information that needs to be available only
for a single page, we will use the View Scope. It is used as #{viewScope.param}.

600
.
601
.
Memory Scope Duration with a Called Task Flow
As stated previously, you should store values in the scope with the shortest duration that fits
your needs, so it is important to know the duration of memory scopes in an application.
The parent task flow depicted in the slide contains three view activities, a router, a method call,
and a task flow call. The called bounded task flow has two view activities: a method call and a
task flow return.
The request scope line shows that the duration of a request scope is from the time a request is
issued in a view activity until another view activity creates a request. Routers and method calls
do not have a request scope of their own, so values set in RS1 above are available to the router
and the method call. If the called task flow had no view activities, RS1 would span the task flow
also. However, each of the called task flow’s two view activities creates a request, ending the
previous request scope and starting a new one. View scope is similar, except that it begins
when a view is rendered and ends when a new view is rendered.
As mentioned earlier, the page flow scope attributes are accessible anywhere within a task
flow. The called task flow has its own page flow scope, PFS2, that is separate from the parent’s
PFS1, and the called task flow cannot access PFS1, so parameters, which are discussed in this
lesson, are needed to pass information from the parent to the called task flow.
Session scope lasts throughout the user session, while application scope lasts beyond the user
session and can share values among all instances of an application.

602
.
Memory Scope Duration with a Region
This example is similar to the previous one, except that the bounded task flow is contained in a
region on the page that is represented as a view activity within the main task flow. It shows the
following differences from the previous slide:
The backing bean scope is available for the declarative components, and lasts as long as the
component is in focus. Each component notifies the controller when it starts and ends being in
focus. There is a separate backing bean scope for each declarative component.
The page flow scope works differently in this example, because the second task flow is in a
region on a view within the main task flow. So the duration of the page flow scope of the main
task flow is throughout its entire flow, including the region that contains the other task flow.
The bounded task flow represented as a region has its own page flow scope as well. Each task
flow’s scope is independent of and cannot access objects in the other task flow’s scope.
The view scope for the page fragments in the bounded task flow (in the region on the page
represented by the view activity B) is separate from the view scope for the containing page. The
views in the region cannot access the view scope of the containing page, and the containing
page cannot access the view scopes of the page fragments in the region.

603
.
Access Memory Scoped Attribute Values
You can access memory-scoped attributes in one of the following ways:
By using EL: You can access objects stored in memory scopes through EL expressions.
The object names must use the name of the scope as a prefix, because EL expressions do not
automatically look into any memory scopes.
The first example in the slide shows how to have a button’s label provided by a
pageFlowScope managed bean, and to have a method on the bean called when the
button is selected. (This example is just for illustrative purposes; in practice, you would use
resource bundles for the text of labels.)
By using Java: pageFlowScope is a java.util.Map that can be accessed from Java
code. To get a reference to pageFlowScope, use the getPageFlowScope() method
provided by Trinidad in org.apache.myfaces.trinidad.context.RequestContext. The second
example in the slide retrieves an object from pageFlowScope.

604
.
605
.
Overview of Parameters
There are several types of parameters that you can use to pass information to different parts of
the application. Subsequent slides discuss page parameters, region parameters, task flow
parameters, view activity parameters, and task flow call activity parameters.
The examples discussed in the next few slides show how to use the first four types of
parameters to pass a value from a containing page to a task flow represented as a region on
that page. You actually can accomplish this task without using all four types of parameters.
However, using more types of parameters enables you to make your pages and task flows more
reusable, as shown in the examples.
After presenting this example, the remainder of the lesson discusses how to pass values to a
called task flow and return values to the calling task flow.

606
Use Task Flow Parameters
Building well-defined, parameterized task flows that can be used as regions on pages is a good
way to provide reusable and highly maintainable segments of functionality across your
application.
Parameters and page events are how different regions and portlets on a single page can
communicate with each other and pass context to each other without being hard-wired
together, or even knowing if the other one is present on the page. For example, a region that
shows a graph of types of goods sold for a particular country could take a parameter into the
region that specifies the country. That same region could also take in a parameter that specifies
whether or not it should display the results as a graph or as a pie chart. Using parameters
enables that same region to be reused in a variety of different situations.
You define task flow parameters in the task flow’s .xml file. You can define a task flow
parameter declaratively, as shown in the slide. The slide shows an example of an input
parameter with the name pname, and value #{pageFlowScope.pname}. The parameter works
as follows:
When the parameter pname is passed into the task flow, its value is stored in the page flow-
scoped attribute pname.
Inside the task flow, activities and pages can get the value of the page flow-scoped attribute by
using the EL expression #{pageFlowScope.pname}.
In the lesson titled “Responding to Application Events,” you learn how to set up contextual
events to communicate between regions. You can use page parameters and task flow
parameters in conjunction with events to coordinate regions.

607
.
Job of the Task Flow Parameter
As previously stated and as depicted in the table in the slide, the bounded task flow parameter
receives an input value and stores it in a memory-scoped attribute. The example shows storing
it in pageFlowScope, so that the value of that attribute can then be used anywhere in the task
flow, such as on a page fragment within the task flow.
But where does that input value come from? A task flow is independent of the page that
contains it. It cannot receive a value directly from a page parameter of the containing page, so
another mechanism is needed. In the example, there needs to be a way to pass the value in the
nameToPass page output parameter into the pname task flow input parameter.

608
.
Pass a Value to a Task Flow
Another situation where you would need to pass values to a task flow is when you call one task flow from another.
A called ADF bounded task flow can accept input parameters from another ADF unbounded or bounded task flow
and can pass return values to the caller upon exit. To pass an input parameter to a bounded task flow, you must
specify:
Input parameter on the task flow call activity. This specifies where the calling task flow stores parameter values.
Input parameter definition on the called bounded task flow. This specifies where the called bounded task flow can
retrieve parameter values.
The input parameter name specified for each of the above options should be the same in order to map input
parameter values back into the called bounded task flow. The value for each corresponds to the mapping between
where the value will be retrieved within the caller and the called task flow.
In the input parameter definition for the called bounded task flow, you can specify whether an input parameter is
required. If a required input parameter is not received, a run-time error occurs. An input parameter definition that
is identified as not required can be ignored during the task flow call activity creation.
By default, input parameters are passed by reference, although you can select the pass-by-value check box in the
Property Inspector for the task flow call activity to pass by value. Mixing the two, however, can lead to unexpected
behavior in cases where parameters reference each other.
Task flow call activity input parameters can be passed by reference only if managed bean objects are passed, not
individual values, so the pass-by-value check box applies only to managed bean objects and is used to override the
default setting of passing by reference. Individual values are only passed by value.
If you call a bounded task flow using a URL rather than a task flow call activity, you pass parameters and values on
the URL itself.
To specify input parameters on the task flow call activity, perform the following steps:
Select the task flow call activity in the task flow diagram.
In the Property Inspector, click Parameters and expand the Input Parameters section:
Click Add and enter a name for the parameter.
Enter a parameter value—for example,
#{pageFlowScope.callingTaskflowParm}. The value specifies where the parameter value will be taken from within
the calling task flow.
Optionally, select the pass-by-value check box. (By default, parameters are passed by reference to the
called bounded task flow.)
After you have specified an input parameter for the task flow call activity, you can specify an input parameter
definition for the called ADF bounded task flow as explained previously.

609
.
Return Values to a Calling Task Flow
A task flow return activity causes the ADF bounded task flow to return to the task flow that called it. The called
bounded task flow can pass return values back to the calling task flow.
To return a value, you must specify:
Return value definitions on the called bounded task flow. These specify where the return value is to be taken from
upon exit of the called bounded task flow.
Return values on the task flow call activity in the calling task flow. These specify where
the calling task flow can find return values.
The caller of the bounded task flow can choose to ignore the return value definition values by not identifying any
task flow call activity return values back to the caller.
Return values on the task flow call activity are passed back by reference. Nothing inside the ADF bounded task
flow still references them, so there is no need to pass by value and make a copy.
To specify a return value for a called ADF bounded task flow, perform the following steps:
In the task flow editor, open the called ADF bounded task flow.
On the Overview tab, select the Parameters panel and click Add in the Return Value Definitions section to add the
return value:
In the name field, enter a name to identify the return value—for example, Return1.
In the value field, enter an EL expression that specifies where the return value is to be taken from upon
exit of the called bounded task flow—for example,
#{pageFlowScope.ReturnValueDefinition}.
To specify a return value for the calling task flow, perform the following steps:
In the task flow editor, open the calling ADF task flow and in the task flow diagram, select the task flow call
activity.
In the Property Inspector, select the Parameters panel and click Add in the Return Values section.
In the name field, enter a name to identify the return value—for example, Return1.
The name of the return value must match the name of the return value definition on the called task flow
definition.
In the value field, enter an EL expression that specifies where the calling task flow can find return
values—for example, #{pageFlowScope.ReturnValue}.
Tip: If you drop the bounded task flow that you intend to call on the task flow call activity, the name field is
already specified. Therefore, the name field for the return value automatically matches the name of the return
value definition on the called task flow definition.

610
.
Use Region Parameters
To pass a parameter from a containing page to a task flow, you need a region parameter, which
you define as follows:
Define a page parameter and a task flow parameter as shown in the previous slides.
Pass the page parameter’s value to the input parameter of the task flow. You do this by defining
a region parameter in the page definition file of the containing page, either in the Structure
window or, with the region selected in the Executables section, in the Property Inspector.
Then set the parameter’s value to the EL value of the page parameter.
A simpler way to define a region parameter is when you create the region. If the task flow has
input parameters defined on it, then when you drag a task flow to a page to create a region,
you must define region parameters for the task flow parameters.
After you have defined the region parameters, you can access the value within a page on the
contained region by using the expression #{pageFlowScope.<input parameter name>}, such as
in the following example on the task flow’s default page:
<af:outputLabel value="Hello, "/>

<af:outputText value="#{pageFlowScope.pname}"/>

611
.
Job of Region Parameter
The region parameter acts as a bridge from the page parameter to the task flow. It takes the
value stored in the page parameter and stores it in an output parameter, which should have the
same name as the input parameter of the task flow. Now the task flow is able to receive that
value and store it in the page flow-scoped attribute that can be used anywhere within that task
flow.

612
.
Job the View Activity Parameter
The view activity parameter simply takes the value that is stored in one memory-scoped
attribute for the task flow and stores it in another—the memory-scoped attribute that is used
by the page. In this way, you can integrate independently developed pages into multiple task
flows without changing either the task flow or the page.

613
.
Use Page Parameters
You define page parameters in the page definition of the page. The example in the slide shows
setting a page parameter to a String value by using Expression Language, because the value of
the parameter must be an expression.
You could also set the page parameter to a value contained in a managed bean, in the binding
container, or in a memory-scoped attribute. For example:
<parameters>
<parameter id="myDeptId" value="#{DepartmentBean.deptId}"/>
<parameter id= "fname" value="#{bindings.FirstName.InputValue}"/>
<parameter id= "lname" value="#{pageFlowScope.lastName}"/>
</parameters>
You can access the parameter value in EL as #{bindings.<param name>}.
You can use page parameters to, for example, pass values into a page template, enabling the
use of the same template for a variety of different pages. Another example of using a page
parameter is to set a value in a containing page to pass to a region (task flow) on the page.

614
.
Job of the Page Parameter
It is often necessary to pass values between pages. In this example, there is a bounded task
flow that is represented as a region on a page. The task flow contains a view activity that
represents a page fragment, and the requirement is to pass a value from the containing page to
that page fragment.
As depicted in the table in the slide, the parameter of a containing page takes a value that is
assigned to it and stores it in a parameter in the binding container. Subsequent slides build this
table to show the functions of different types of parameters.

615
.
Develop a Page Independently of a Task Flow
To make a page (or page fragment) reusable in different task flows, it should be independent of
the task flow. The page flow-scoped attributes that are referenced on the page may not be
named the same as the task flow’s page flow-scoped attributes. So pages that are developed
independently and used in different task flows need another mechanism to be able to use the
values that are stored in page flow-scoped attributes for a particular task flow.

616
.
Pass a Value to a Region
The more types of parameters you use, the more reusable your components are. The page
fragment in this diagram is represented as a view activity in a task flow used as a region on a
containing page, like the example that was just discussed. Because parameters are used at each
level, the page can be developed independently of all other components without regard to the
names of memory-scoped attributes that are used on the page:
The containing page uses a page parameter to pass its value to the region.
The region uses a region parameter to pass the value on to the task flow, so the task flow can
be developed independently of the page and reused on multiple pages.
The task flow uses a task flow parameter to pass the value to its view activity.
The view activity uses a view activity parameter to store the value in the memory-scoped
attribute that is used by the page fragment.
All of these parameters could be named differently, as long as the output parameter of one
level has the same name as the input parameter of the next level. For example, the region’s
output parameter would have the same name as the task flow’s input parameter.
Page and region parameters are stored in the page’s binding container, so you define them in
the page definition file for the page. Task flow and view activity parameters are defined in the
.xml file for the bounded task flow.

617
Decide the Usage of Parameter
As you have seen in this lesson, the use of one type of parameter does not preclude the use of
another, because they all have different functions. Defining parameters is all about providing
reusability. Defining parameters on a task flow improves reusability of that task flow. Defining
parameters on a page or page fragment improves its reusability. Parameters also make an
object much more encapsulated (self-contained).
For example, if you have a bounded task flow that updates customers, you could have it take in
CustomerId as a parameter. The task flow can then make sure that the correct customer is
queried to edit—and there is no reliance on the consumer of that bounded task flow setting
the current row in a view object in some application module that this bounded task flow uses.
This ensures that the interface between consumer and producer is much better documented
and separated from the internal implementation.
If you want to make the page a more reusable component, you may provide a parameter on
the page for exactly the same reasons.

618
.
Features of Partial Page Rendering
Unlike standard JSF events, ADF Faces events support AJAX-style partial postbacks to enable
partial page rendering, which enables refreshing portions of page content that have minimal
processing without the need to redraw the entire page. In ADF Faces components, this is
implemented by a hidden IFrame, which is automatically added to a Web page when one of the
following ADF Faces elements is used: af:document, afh:body, or af:panelPartialRoot.
Two main AJAX patterns are implemented with PPR:
Single component refresh: Implemented natively. For example, the ADF Faces table component
comes with a built-in functionality that enables you to scroll through the table, sort the table by
clicking a column header, mark a line or several lines for selection, and expand specific rows in
the table—all through declarative property settings with no coding needed
Cross-component refresh: Implemented declaratively or programmatically by the application
developer by defining ADF Faces UI components to act either as a trigger for a partial update or
as a partial listener to be updated

619
.
AJAX – very trendy – Asynchronous JavaScript with XML basically the ability to send requests to
the server down a different pipe within the browser. The whole page is not submitted, rather a
separate communication takes place behind the scenes which can send packets of Info to the
server to process and then parse the results and update the screen with new data

620
.
621
.
622
.
A good example of PPR in action is the Status list box in the SREdit screen. Changing the status
to Closed automatically disables some other input fields

623
.
624
.
625
.
Use EL to Conditionally Display Components
In JSF, you use a simple Expression Language (EL) to work with the information you want to
present. At run time, a generic expression evaluator returns the value of expressions,
automating access to the individual objects and their properties without requiring code.
Because any attribute of a component can be assigned a value by using an EL expression, it is
easy to build dynamic, data-driven user interfaces.
Following are some examples of how to use EL:
For the component’s value: At run time, the value of a JSF UI component is determined by its
value attribute. Although a component can have static text as its value, typically the value
attribute contains an EL expression that the run-time infrastructure evaluates to determine
what data to display.
To hide a component when a set of objects you need to display is empty: Use a Boolean- valued
expression such as #{not empty ProductList.selectedProducts} in the UI component’s rendered
attribute. If the list of selected products in the object named ProductsList is empty, the
rendered attribute evaluates to false and the component disappears from the page.
For more information about Expression Language, see:
http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSPIntro7.html
http://www.oracle.com/technology/sample_code/tutorials/jsp20/simpleel.html

626
.
Rendered property references a managed bean and calls the method isStaff which returns true
or false, based on the internal Java evaluation

627
.
Enable Automatic PPR
Configuring PPR manually can be tedious and error-prone, especially when back-end business
logic is added to the mix. The complexity rises further when page developers use back-end
components that are developed by another team because they may not be aware of how the
back- end logic changes values.
To resolve this difficulty, you can enable automatic partial page refresh on the bindings of any
page. This causes components whose values change as a result of back-end business logic to be
automatically repainted. At run time, the binding layer is notified of value changes, and
appropriate components are added to the PPR targets list.
This feature enables you to avoid much of the manual PPR configuration, so that you can focus
on building the UI or business logic.

628
.
Lesson Summary

629
.
630
.
In Hands-on lab one would practice:
1. Creating Managed Bean
2. Creating Action Listener and Adding Method Binding
3. Creating Value Change Listener

Optionally you may also practice:


1. Adding Phase Listener
2. Adding Validator
3. Adding Converter

631
.
632
.
Adding UI Code
You can add UI code to the task flow by using managed beans.
Managed beans are Java classes with a no-argument constructor that you register with the
application in the task flow .xml files. When the JSF application starts up, it parses these files
and makes the beans available to be referenced in EL expressions (you learn about these in the
lesson titled “Implementing Transactional Capabilities”) or Java code, enabling access to the
beans’ properties and methods.
Whenever a managed bean is referenced for the first time and it does not already exist, the
Managed Bean Creation Facility instantiates the bean by calling the default constructor method
on the bean. If any properties are also declared, they are populated with the declared default
values.

633
.
Register Existing Java Classes as Managed Beans
To register an existing class as a managed bean, open the task flow in the editor, click the
Overview tab, select the Managed Beans panel, and click Create. Enter values for the managed
bean attributes in the Property Inspector, browsing to locate the existing class

634
.
Configure Managed Beans
Managed beans can be defined only in ADF Controller source files (adfc-config.xml or bootstrap
source files, and task flow definition files). They are not allowed in the faces- config.xml file.
Managed beans are defined in the .xml files by using the <managed- bean> tag. Attributes of
the managed bean, as shown in the example in the slide, are as follows:
<managed-bean-name>: Specifies the name that is used to refer to the managed bean
throughout the application
<managed-bean-class>: Contains the fully qualified class name for the JavaBean
<managed-bean-scope>: Defines the scope of the JavaBean. The possible values for
this element are application, session, request, pageFlow, view,
backingBean, or none. (These are described in the lesson titled “Passing Values
Between UI Elements.”) If the value of the managed-bean-scope element is
something other than none, the JavaBean created is stored in the corresponding object.
For example, if the value is request, the JavaBean is stored in the request object of a
given user.
If you have created a new Java class for your bean, JDeveloper creates the skeleton code to
which you need to add your own code.

635
.
Context Objects
FacesContext can be accessed across JSF as a static class. It provides access to the JSF APIs
and functions, such as the message stack, which is compiled throughout the Faces request life
cycle.
ExternalContext allows developers to work with the servlet API, as they are used to
working with JSP and Struts. However, it is recommended that you use FacesContext for as
long as possible.
FacesContext and ADFFacesContext are static classes.

636
.
Reference Managed Beans
You can reference managed beans by using either Expression Language (EL) or Java, as shown in
the examples in the slide. Expression language is described in the lesson titled “Implementing
Transactional Capabilities.”
What the Java code in the slide does is to assign the value of a managed bean (whose name is
expressed in EL) to a User object. It uses the following classes and methods:
FacesContext is a class that contains all of the per-request state information related to
the processing of a single JSF request, and the rendering of the corresponding response. It is
passed to, and potentially modified by, each phase of the request processing life cycle. (You
learn about life-cycle phases in the next few slides.)
ELContext is a class that is used to evaluate an expression.
ExpressionFactory is a class that parses a String into a value expression (as in the
code in the slide) or a method expression for later evaluation.
The createValueExpression() method parses expressions that evaluate to values.
The expression must be first parsed, and then evaluated.
The ValueExpression class encapsulates a parsed expression, and its getValue()
method evaluates the expression relative to the provided context, and returns the resulting
value.

637
.
Hold Values in Managed Beans
Managed beans enable you to hold values, either in the properties of the managed bean or in
the scoped managed bean attributes. You learn more about configuring and coding managed
beans in the lesson titled “Responding to Application Events.”
You can pass values between pages by using managed beans to hold the values. The JSF run
time manages instantiating these beans on demand when any EL expression references them
for the first time. When displaying a value, the JSF run time evaluates the EL expression and
pulls the value from the managed bean to populate the component with data when the page is
displayed. If the user updates data in the UI component, the JSF run time pushes the value back
into the corresponding managed bean based on the same EL expression.

638
.
Use Managed Bean Properties
Managed properties are bean attributes that are exposed through the setter and getter
methods for write and read access. All attributes that are not explicitly set as managed
properties retain the default values upon bean instantiation.
The <managed-property> element represents an individual property of a managed bean. A
managed property calls the equivalent setter method of the bean on bean initialization.
The <managed-property> element is nested within the <managed-bean> element. Managed
properties must have a name and a value. Optionally, they can have a property class, a
description, a display name, and an icon. The last three elements are for tools to display the
property and have no meaning for the JSF application at run time.
The property class does not need to be mentioned for simple types because JSF will figure this
out.
Although null is among the possible values for a managed property, it is allowed only if the
property is an object. This means that null cannot be used for types of int, boolean, and so on.

639
.
640
.
641
.
Example using an ArrayList

<managed-bean>
<managed-bean-name>MyBookmarksMap</managed-bean-name>
<managed-bean-class>java.util.ArrayList</managed-bean-class>
<managed-bean-scope>application</managed-bean-scope>
<list-entries>
<value> http://otn.oracle.com/products/ias</value>
<value>http://otn.oracle.com/products/jdev</value>
</list-entries>
</managed-bean>

642
.
In the example above the value bar should be set on the property foo, which is an instance of
FooBean. Using nested managed properties is not an option on JavaServer Faces because all
managed properties must be properties of the owning class and not a class referenced by this
class.

Configuring the two managed beans as in our example will populate the myBean property foo
with an instance of FooBean that has a property “bar” set via the managed properties. This way
the property value “Hello World” is accessible” from myBean.

643
.
Backing beans are created and stored with the application using the managed bean creation
facility, which is configured in the application configuration resource file.

To bind UI component values and instances to backing bean properties or to reference backing
bean methods from UI component tags, page authors use the JavaServer Faces expression
language (EL) syntax. This syntax uses the delimiters #{}. A JavaServer Faces expression can be
a value-binding expression (for binding UI components or their values to external data sources)
or a method-binding expression (for referencing backing bean methods).

644
.
Managed beans can be created as Java classes in a project before configuring them as a
managed bean, or created on the fly when binding a command button. Double click on the
command button to launch the binding editor. Choose to create a new class as a managed bean
or to reuse an existing class. To reuse an existing class, choose a backing bean or search the
classpath. If searching the classpath, select the Java class you want to become a managed bean
and press okay. The class will be configured as a managed bean in the faces-config.xml file. The
new method then can be created and the command button bound to it.

645
.
Auto binding is a feature that can be convenient when developing JavaServer Faces, but at the
same time it produces a lot of unwanted overhead. When creating a page with auto-binding
enabled, then JDeveloper created a bean representation of the JSF page that contains
instance variables for all UI components added to the page. Instance variables will also be
created for frames and panels.
Having the instance variables and the associated getter and setter methods created is quite
useful for programmatic component modification. However, the generated backing bean
classes become very big soon and are not easy to read for this reason. If you decide to have
backing beans auto generated, then the recommendation is to
a) Manually clean up the backing bean. Remove all the instance variables and getter and
setter methods that you don’t want to perform any programmatically operation on. Make
sure that you don’t leave any reference to the removed instance variables behind in the UI
component properties.
b) Check the “Binding” property of the UI component. The error message that JSF presents at
runtime when a value binding exists for a non-existing instance variable is not very
meaningful and doesn’t point to the problem. So be careful.

646
.
Use Event Listeners
Components can generate events, which are occurrences that take place as users interact with
an application, such as when they click a button or change a value. There are also events, such
as gaining or losing focus, that are not the result of user interactions.
If there is a listener for the event, the event communicates some information about what
happened, so that the listener can respond. An event, then, is a component’s way of letting a
listener know that something happened.
An event listener is a class that implements one of the listener interfaces and contains code to
respond to the event. A component has mechanisms to register and deregister event listeners
for the types of events that are generated by the component.

647
.
648
.
649
.
Describe Types of Events
In traditional JSF applications, event handling typically takes place on the server. JSF event
handling is based on the JavaBeans event model, where event classes and event listener
interfaces are used by the JSF application to handle events generated by components. For a JSF
application to be able to respond to user events, you typically register event listeners on the
components that would generate events. The following types of events are supported:
A phase event or listener is executed as part of the standard JSF life cycle. You can add to the
standard behavior by implementing your own phase listener.
An action event occurs when a command component is activated. For example, when a
user clicks a button or a link, the form containing the component is submitted, and the
component creates an event object that stores information about the event and identifies the
component that generated the event. The event is also added to an event queue. At the
appropriate time in the JSF life cycle, JSF tells the component to broadcast the event to the
appropriate registered listener, which invokes the listener method that processes the event.
Events may trigger a change in the user interface or invoke the back-end application code, or
both. The return value of an action event is usually used for navigation.
A value change event occurs when the local value of an input component changes; it fires
only after component value validation and form submission.

650
.
In addition to server-side action and value change events, ADF Faces components also fire other kinds of server events. ADF Faces server events, and the
components that generate them, include the following:
• ActionEvent: All command components
• DialogEvent: dialog
• DisclosureEvent: showDetail, showDetailHeader, showDetailItem
• FocusEvent(generated when focusing in on a specific subtree, which is not the same as a client-side keyboard focus event ): tree, treeTable
• LaunchEvent: All command components
• LaunchPopupEvent: inputListOfValues, inputComboboxListOfValues
• PollEvent: poll
• QueryEvent: query, quickQuery, table
• QueryOperationEvent: query, queryCriteria, quickQuery
• RangeChangeEvent: table
• RegionNavigationEvent: region
• ReturnEvent: All command components
• ReturnPopupDataEvent: inputListOfValues, inputComboboxListOfValues
• ReturnPopupEvent: inputListOfValues, inputComboboxListOfValues
• RowDisclosureEvent: tree, treeTable
• SelectionEvent: tree, treeTable, table
• SortEvent: treeTable, table
• ValueChangeEvent: All input and select components (components that implement EditableValueHolder)

All server events have associated event listeners. For example, to process a LaunchEvent event, you would create a LaunchListener event listener
implementation. All server event listener implementations must override a processEvent() method, where Event is the event type. For example,
LaunchListener accepts an instance of LaunchEvent as the single argument; in your implementation, you must override the event processing method, as
shown in the method signature here:
public void processLaunch (LaunchEvent evt) {
// your code here
}
Instead of creating an event listener implementation, you can create an event listener method in a backing bean. Any event listener method must be a public method
that accepts the event as the only parameter and returns void.
As you can see by the examples in the slide, the Property Inspector in JDeveloper exposes the proper listeners for the type of ADF Faces component being used.

651
.
652
.
653
.
Respond to Action Events
Action events are events that are associated with command components (such as
commandButton, commandLink, or commandMenuItem).
An action event enables you to define an action method that returns an outcome to be used for
navigation. Instead of entering a control flow outcome directly in the action property of a
command component, you refer to a bean method that returns a string that corresponds to the
control flow outcome. An example is shown in the next slide.
Action method code can be either in the page-backing bean or in a separate class. The benefit
of having the code in the backing bean is that the code that is associated with a specific page is
all local to the page (single source). However, the benefit of a separate class is reusability. For
example, if you have standard code that should be executed regardless of the page, the
separate class approach makes more sense. If you use the backing bean approach, JDeveloper
creates a method stub for you; all you have to do is add your custom code. JDeveloper also
registers the action in the page source.
When the page is submitted, the action method is added to the queue of application events to
be executed. Action methods are the last to fire in the application phase of the life cycle. For
this reason, they are generally used to determine navigation.

654
.
655
.
Create Action Methods
You can create an action in JDeveloper by performing the following steps:
Invoke the action-binding editor by either double-clicking the component in the editor or by
right-clicking it in the Structure window and select “Create Method Binding for Action.”
In the action-binding editor, you can accept the proposed method name or change it to a
name of your choice. You can select to create a new bean and method if desired.
You then add whatever code you need to the action method. Remember that action methods
can be used for controlling the UI, modifying values, or navigation; however, action methods
return a String outcome.
For example, the myBean.selectWhere method depicted in the slide could have code similar to
the following:
public String selectWhere() { if <some condition> {
return (“cart”); /* navigate to shopping cart */
}
else {
return(“prod”); /* navigate to Product page */
}}

656
.
Use Action Listeners
Command components, such as buttons and links, generate actions when clicked. Action
listeners are event listeners that define code to execute in response to that action. Action
listeners contain code that processes the action event object passed to it by the command
component.

657
.
Value Change Events
Value change events are attached to input and select components. When there is a change to
the value of a component, a value change event is added to the queue of application events to
be executed. Just like action events, the code can be either in the backing bean or in a separate
class. JDeveloper creates the method stub in the backing bean and registers the listener in the
page source by using the valueChangeListener property of the component tag.
The registered value change listener is added to the queue of listeners to be processed before
any action events. Action events, which are linked to navigation, are executed last.

658
.
659
.
Listen for Value Change Events
You create value change events by entering the name of the method in the
valueChangeListener property of the component. If you are creating a new method, JDeveloper
adds the method stub to the Java class. You then add your custom code.

660
.
The following implementation of processValueChange() method writes the name of the
component that raises the value change event to the the message list. To display the message,
drop a message element to the page

public class MyValueChangeListener implements ValueChangeListener {


public MyValueChangeListener() {
}
public void processValueChange(ValueChangeEvent ValueChangeEvent) throws AbortProcessingException {
// print out the source name
FacesContext ctx = FacesContext.getCurrentInstance();
String eventSource;
if (ValueChangeEvent.getSource() instanceof HtmlInputText){
eventSource = ((HtmlInputText) ValueChangeEvent.getSource()).getId();
}
else{
eventSource = "Instance of "+ValueChangeEvent.getSource().getClass().toString();
}
FacesMessage fm = new
FacesMessage(FacesMessage.SEVERITY_INFO,ValueChangeEvent.getSource()+eventSource+" said hello", null);
ctx.addMessage("MyValueChangeListener",fm);
}
}

Note that you can use one ValueChangeListener with different UI component. To obtain the
component value, you need to perform proper type casting

661
.
662
.
Event and Listener Execution Order
There is a specific order in which the events and listeners are executed. The validators are fired
first within the Process Validation phase of the JSF life cycle. The next phase is the Invoke
Application phase that handles all the events and listeners.
The value change listeners are executed first, followed by the action listeners. The action
method is executed last because that is what determines navigation. Any of these listeners can
raise an AbortProcessingException to abort the process.
If an action listener raises an exception, it does not prevent navigation. In most cases, however,
you would not want to navigate, but rather redisplay the page with an error message. To
implement that behavior, in the action property, you can call a method that returns null if there
is an exception, but otherwise returns the String outcome to use for navigation.
For example, the selectWhere() method referenced in the Action property of the Update Order
button shown in the slide may contain code to navigate to a manager task flow call if the value
of the order is over a certain amount, or to a commit method for an order below that amount.
The navigation is dependent on the String outcome returned by the selectWhere() method.

663
.
ADF Faces Enhanced Event Handling
Like standard JSF components, ADF Faces command components deliver ActionEvent events
when the components are activated, and ADF Faces input and select components deliver
ValueChangeEvent events when the component local values change. Though ADF Faces adheres
to standard JSF event handling techniques, it also enhances event handling. Unlike standard JSF
events, ADF Faces events support AJAX-style partial postbacks to enable partial page rendering
(PPR). Instead of full page rendering, ADF Faces events and components can trigger partial page
rendering, that is, only portions of a page refresh upon request.

664
.
Enable PPR Programmatically
If you need to execute some logic to determine whether a component should be refreshed, you
cannot handle the refresh using partial triggers, but need to use a different technique.
Also, if you need to refresh a component only when a certain event occurs (such as when the
selection changes), and not when other events are triggered, using partial triggers may not be
the most efficient method to use because when you use partial triggers, the component is
refreshed for all events that are fired by those trigger components. For example, a table
supports multiple events, such as sorting and selecting events. Similarly, for components that
display the results of complicated queries, if you want to refresh the component only when the
selection changes, a more efficient way than using partial triggers is to use a selection listener.
The addPartialTarget() method enables you to add a component as a partial target for an event,
so that when that event is triggered, the partial target component is refreshed. With this
technique, you can associate the component you want to have refreshed with the event that is
to trigger the refresh.
The following example, part of a managed bean, adds a UI component as a partial target:
public void doPartialRefresh(UIComponent uc){
AdfFacesContext adfctx = AdfFacesContext.getCurrentInstance(); adfctx.addPartialTarget(uc);}

665
.
Contextual Events: Example
As an example of using the Contextual Event Framework, consider a containing page that
contains two regions representing two task flows. The task flows in the separate regions have
no knowledge of one another, as if there is a wall between them. Only the containing page has
knowledge of both regions, so it is the containing page that must coordinate the interaction
between them.
The goal of creating a contextual event in this example is to accomplish the following:
• Pass information from the first region to the second region.
• React in the second region based on the information that is passed.
When an action, such as a button click, occurs in the first region, the event is initiated. There is
a method defined that constructs the payload for the event, that is, the information that is
being passed to the other region. There is another method on the target, or consumer region,
that specifies how that region should respond. The job of the containing page is to map the
event: specify which is the payload method, which is the handler method, and so on.

666
.
There are several aspects that define a contextual event:
1. A container page that contains the regions to be coordinated
2. A producer that invokes a method to raise the event and provide a payload (information
needed by the event)
3. A consumer that is the target of the event
4. A handler method that is bound either to the consumer page fragment or to the page
containing the regions
5. An event mapping on the container page definition that specifies:
- The producer region and payload method
- The event name
- The consumer and event handler
- The parameter (payload) to pass to the event

667
.
Characteristics of the Contextual Event Framework
When a page contains multiple regions that need to work together to display relevant
information to the user, the need to communicate between regions becomes very important.
This communication can be handled through an event framework called the Contextual Event
Framework. This framework provides the page with the ability to map events to be produced
and consumed by the page’s various regions, along with the information to be passed to the
consumer regions.
In a typical scenario, a consumer would need to register with the producer to get event
notification. However, the Contextual Event Framework in ADF enables the producer and
consumer to be tied through an event routing mechanism. The producer publishes the
contextual event it is going to raise. The page listens for the event and then routes it to the
consumer.
The Contextual Event Framework includes the following characteristics:
A contextual event can go across data controls.
A contextual event can be raised or consumed only with a method action binding that must be
only data control methods, not managed bean methods.
Event payload can either be primitive or any serializable object.

668
.
JSF Life Cycle Phases
The life cycle handles both initial requests and postbacks.
When a user makes an initial request for a page, the life cycle executes only the Restore View and Render Response phases because there is no
user input or actions to process. The life cycle builds the UI tree from the view, and then renders the view, returning a response to the user and
saving the view tree for future requests in the FacesContext object. All the component tags, event handlers, converters, and validators on the
page have access to the FacesContext instance.
When a user executes a postback, a form is submitted that is contained on a page that was previously loaded into the browser as a result of
executing an initial request. When the life cycle handles a postback, it restores the view based on the data saved on the server, and then
executes the following additional phases:
Apply Request Values: Values provided in components that hold a value (such as input fields) have their values applied to their counterparts in
the view tree. All events such as ValueChangeEvents (VCE) or ActionEvents (AE) are queued. A VCE means that a value has changed for a
specific UI component. An AE means that a button (or any UI component that is a source of an action) was clicked. If a component has its
immediate attribute set to true, then validation, conversion, and events associated with the component are processed during this phase.
Process Validation: Conversion and validation logic is executed for each component. This means both built-in validation/data conversion and
custom validation/conversion are added onto the components. If a validation error is reported, an exception is thrown. The life cycle halts and
the response is rendered with validation error messages. 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.
Update Model: The component’s validated local values are moved to the model and the
local copies are discarded. If you are using a backing bean for a JSF page to manage your UI components, any managed bean properties that
are value-bound to the UI component using the value attribute are updated with the value of the component.
Invoke Application: Any action bindings for command components or events are invoked. Navigation is handled here depending on the
outcome of action method (if any).
Setting the immediate Attribute
You can use the immediate attribute to allow components on the page to be validated in the Apply Request Values phase of the life cycle as
opposed to the Process Validations phase:
Using immediate on an input component means that that component’s value is validated
before any input components that do not have the immediate attribute set to true.
Therefore, if a validation error occurs on an immediate input component, the life cycle
moves from the Apply Request Values phase (where the immediate attribute is
evaluated) to the render phase, and validation does not run on any “nonimmediate” input components. Additionally, if the new value of an
immediate input component is different from the existing value, then a ValueChangeEvent is raised. However, instead of the event being
processed during the Process Validations phase, the event is processed at the end of the Apply Request Values phase. Therefore, any
ValueChangeListener associated with the immediate input component executes before any command component’s ActionListener (assuming
the command component occurs later on the page). You learn about event listeners in the lesson titled “Responding to Application Events.”
For command components, if set to immediate and the component has an action that
returns a value for navigation, the life cycle proceeds directly to the Render Response phase. The validation and model update phases are
skipped. A Cancel button is an example of when this would be used.

669
.
JSF Request Life Cycle: Restore View
In the Restore View phase of the JSF life cycle, a request comes through the FacesServlet
controller. The controller examines the request and extracts the view ID, which is determined
by the name of the JSP page.
The JSF framework controller uses the view ID to look up the components for the current view.
If the view does not already exist, the JSF controller creates it. If the view already exists, the JSF
controller uses it. The view contains all the graphical user interface (GUI) components.
This phase of the life cycle presents three view instances: new view, initial view, and postback,
with each one handled differently. In the case of a new view, JSF builds the view of the Faces
page in the form of a component tree, and it wires the event handlers and validators to the
components. The view is saved in a FacesContext object, which holds all the information
needed to process a single request. The FacesContext object can be accessed by all the
components of the application, event handlers, converters, and validators.

670
.
JSF Request Life Cycle: Apply Request Values
The purpose of the Apply Request Values phase is for each component to retrieve its current
state. The components must first be retrieved or created from the FacesContext object,
followed by their values. Component values are typically retrieved from the request
parameters, although they can also be retrieved from cookies or headers.
If a component’s immediate event handling property is set to true, the component’s value is
validated during this phase. If the validation fails, an error message is generated and queued in
FacesContext, where it is displayed during the Render Response phase along with any other
validation errors.
Setting the component’s immediate property to true does not cause any of the life cycle
phases to be skipped unless validation fails, in which case, the processing jumps to the Render
Response phase to display the current view with the validation errors. If you want to jump to
the Render Response phase in other cases, you can use a value change listener. This is
described in a later slide in this lesson.

671
.
JSF Request Life Cycle: Process Validations
The first event handling of the life cycle takes place after the Apply Request Values phase. At
this stage, each component’s values are validated against the application’s validation rules. The
validation rules can be predefined (shipped with JSF) or defined by the developer. Values
entered by the user are compared with the validation rules. If an entered value is invalid, an
error message is added to FacesContext, and the component is marked invalid. If a component
is marked invalid, JSF advances to the Render Response phase, which displays the current view
with the validation error messages. If there are no validation errors, JSF advances to the Update
Model Values phase.
Conversion also occurs during the Process Validations phase. For example, if the field is bound
to an Integer property, the value is converted to an Integer. If the value conversion fails, an
error message is generated and queued in FacesContext, where it is displayed during the
Render Response phase, along with any validation errors. The converted value is then stored in
the component.
At the end of the Process Validations phase, new component values are set, any validation or
conversion error messages and events are queued in FacesContext, and any value change
events are delivered.

672
.
JSF Request Life Cycle: Update Model Values
The Update Model Values phase updates the actual values of the server-side model by
updating the properties of your backing beans or ADF Business Components. Only those bean
properties that are bound to a component’s value are updated. Note that this phase happens
after validation, so you can be sure that the values copied to your bean’s properties are valid (at
least at the formfield level; they may still be invalid at the business-rule level).

673
.
JSF Request Life Cycle: Invoke Application
In the Invoke Application phase, the JSF controller invokes the application to handle Form
submissions. The component values have been converted, validated, and applied to the model
objects, so you can now use them to execute the application’s business logic.
In this phase, you also get to specify the next logical view for a given sequence or number of
possible sequences. For this, you define a specific outcome for a successful Form submission
and return the outcome. For example, if the outcome is successful, move the user to the next
page. For this navigation to work, you must create a mapping to the successful outcome as a
navigation rule in the faces-config.xml file. After the navigation occurs, you move to
the final phase of the life cycle.

674
.
JSF Request Life Cycle: Render Response
In the Render Response phase, you display the view with its components in their current state.
If the request is a postback and errors were encountered during the Apply Request Values
phase, Process Validations phase, or Update Model Values phase, the original page is rendered
during the Render Response phase.
After the content of the view is rendered, the state of the response is saved so that subsequent
requests can access it and it is available to the Restore View phase.

675
.
Using the immediate Attribute
In the Apply Request Values phase, each component in the tree extracts new values from the
request parameters (using its decode method) and stores it locally. Most associated events are
queued for later processing. If you set a component’s immediate attribute to true, the
validation, conversion, and events associated with the component are processed during this
phase and the life cycle skips the Process Validations, Update Model Values, and Invoke
Application phases. Additionally, any associated iterators are invoked.

676
.
The Big Picture
All life cycle classes use a life cycle context to provide the parameters needed by the life cycle
methods. You can customize the behavior of these ADF life cycle classes by overriding the life
cycle methods, but you cannot change the order in which the methods are called.

677
.
678
.
Describing JSF and ADF Life-Cycle Roles
When a page is submitted and a new page requested, the application invokes both the JSF
request life cycle and the ADF page life cycle.
The JSF life cycle handles the submission of values on the page, validation for components,
navigation, and displaying the components on the resulting page and saving and restoring state.
The JSF life-cycle phases use a UI component tree to manage the display of the faces
components. This tree is a run-time representation of a JSF page: each UI component tag on a
page corresponds to a UI component instance in the tree. The FacesServlet object manages the
request processing life cycle in JSF applications. FacesServlet creates an object called
FacesContext, which contains the information necessary for request processing, and invokes an
object that executes the life cycle.
The ADF life cycle handles preparing and updating the data model, validating the data at the
model layer, and executing methods on the business layer. The ADF life cycle uses the binding
container to make data available for easy referencing by the page during the current page
request.

679
.
680
.
681
.
682
.
683
.
684
.
685
.
.
.
.
.
.
.
Validation
ADF Faces provides the following types of validation:
UI component attributes: ADF Faces input components have attributes that can be used
to validate data. For example, you can set the required attribute on a component to
specify whether a value must be entered. When set to true, the component must have a
value.
Default ADF Faces validators: The standard validators supplied by ADF Faces and the JSF
reference implementation provide common validation checks, such as validating date
ranges and validating the length of entered data.
Custom ADF Faces validators: You can create your own validators, and then select them
to be used in conjunction with UI components.
You can use UI validation to provide immediate feedback and meaningful error messages to
users. However, UI validation should always have equivalent validation at the business services
layer, so that the same validation is applied when the model is exposed in other ways.

692
.
693
.
694
.
695
.
696
.
697
.
698
.
699
.
UI Validation
You can add UI code to the task flow by using managed beans. You learn how to code and
register managed beans in the lesson titled “Responding to Application Events.” However, a
brief mention of managed beans is included in this lesson on task flows because managed
beans are specific to task flows and are configured in the task flow’s XML file.
Managed beans are Java classes with a no-argument constructor that you register with the
application in task flow .xml files. When the JSF application starts up, it parses these files and
makes the beans available to be referenced in EL expressions or Java code, enabling access to
the beans’ properties and methods.
Whenever a managed bean is referenced for the first time and it does not already exist, the
Managed Bean Creation Facility instantiates the bean by calling the default constructor method
on the bean. If any properties are also declared, they are populated with the declared default
values.

700
.
701
.
The regular expression in the example allows characters only and no digits. The input length is
limited to 1 – 10 characters, which also means it cannot be null
Presenters should point out the power of the RegEx validator – this is incredibly powerful for
any kind of format related validation

702
.
To create a backing bean validator, select a component in the UI, open the Property Inspector
and type a name for the method, e.g “validateDepartment”. JDeveloper automatically creates
the backing binding code for it.

Arguments passed to the method


===============================

-Faces context instance


-The UI component that has the validator assigned so you can have access to it e.g. to disable
it. Don’t forget to perform proper type casting if needed for the operation.
-The object, which is actually the value contained added or contained in the field

703
.
704
.
705
.
706
.
ColorConverter
============================
Color Format Syntax:
To specify the color format use a color pattern string. In this pattern, all ASCII letters are
reserved as pattern letters, which are defined as the following:
Symbol Meaning Presentation Example ------ ------- ------------ ------- r red
component (Number) 242 g green component (Number) 242 b blue component (Number) 242
a alpha component (Number) 255 R red component (Hex) F2 G green component (Hex) F2 B
blue component (Hex) F2 A alpha component (Hex) FF ' escape for text (Delimiter) '' single
quote (Literal) ' Examples:
Format Pattern Result -------------- ------- "#RRGGBB" ->> #6609CC "rrr,ggg,bbb" -
>> 102,009,204 "t" ->> Transparent (when alpha is zero)

707
.
708
.
709
.
710
.
711
.
712
.
Lesson Agenda
In this lesson we are learn to using data control panel, how to bind data to ui pages and binding
programmatically

In Hands-on lab one would practice:


Creating a Read Only ADF Tables with Row Selection

Optionally you may also practice:


1. Customizing Data and UI Components
2. Creating a Detail Forms
3. Making a Table Non-Selectable
4. Using setCurrentRowWithKey
5. Using setCurrentRowWithKeyValue
6. Creating a Graph Component
7. Creating a Read Only Tree

713
.
714
.
715
.
716
.
717
.
Output Components
ADF Faces provides components for displaying text, icons, and images, and for playing audio
and video clips on application pages.
You can output error or warning messages with the af:message or af:messages
component.
Read-only text, either specified explicitly or from a resource bundle or bean, is displayed using
the af:outputText and af:outputFormatted components. As implied by the names of the
components, you can specify a certain amount of formatting for text displayed using the
af:outputFormatted component. For styling output text, setting the whole of the text to some
style, you use the styling features available with both components.
Each skin used for the presentation of an application provides icons representing standard
functions, such as an error or a warning, which you can display using the af:icon component
with the name of the type of icon (required, warning, info, error, or logo).
Many other ADF Faces components can have icons associated with them, such as a menu
where each of the menu items can have an associated icon. You identify the image to use for
each one as the value of an icon attribute for the component itself.
To play back an audio clip or a video clip, you use the af:media component. These components
have attributes for you to define how the item is presented on the page.

718
.
719
.
720
.
721
.
722
.
723
.
724
.
725
.
726
.
727
.
728
.
729
.
730
.
731
.
732
.
733
.
Selection components
The selection components allow end users to select single or multiple values from a list or group of items. ADF Faces provides a
number of different selection components that range from simple Boolean checkboxes and radio buttons to order shuttle
boxes that allow the user to select multiple items and order them.
Almost all of the selection components present items as either multiple tags of af:selectItem orf:selectItem or one tag
of f:selectItems. This rule applies to all select components except for
the selectBooleanCheckbox and selectBooleanRadio components. The following list explains different select components:
selectBooleanCheckbox – This is a component that is used to create an HTML checkbox as shown in the following screenshot;
its value must always be a boolean or java.lang.Booleanand not an object as with other select components. It toggles between
selected (true) or unselected (false) states.
selectBooleanRadio – This component is exactly like the selectBooleanCheckboxcomponent but in a radio button format (as
shown in the following screenshot). It also allows grouping multiple selectBooleanRadio components together using the
same group attribute.
selectOneRadio – This is a component that is used to create a list of radio buttons through which the user can select a single
value from a list. It returns a single object. The following screenshot shows the list of radio buttons created
using selectOneRadio:
selectManyCheckbox – This is a component that is used to create a list of checkboxes from which the user can select one or
more values. It returns a list of objects. The following screenshot shows one such list of checkboxes:
selectOneListbox – This is a component that allows the user to select a single value from a list of items displayed in a listbox, as
shown in the following screenshot. It returns a single object.
selectManyListbox – Like selectOneListbox, this component shows a list that allows the user to select one or more items from
the list; it also provides the All option that selects all items of the list and returns a list of objects. The following screenshot
shows an example of such a list:
selectOneChoice – This is a component that allows the end user to select items from a drop-down list (also known as
combobox) and returns a single object. The following screenshot shows an example of this list:
selectManyChoice – This is a component that allows the user to select multiple values from a list of items displayed in a
combobox and returns a list of objects, as shown in the following screenshot. This component can be configured to include
the All option, just like selectManyListbox.
selectManyShuttle – This is a component that presents end users with two different list boxes, namely, Available
Values and Selected Values, as shown in the following screenshot. The end users can shuttle from one list to the other using
different arrows provided between the lists. This component returns a list of objects (the items of the Selected Values list).
selectOrderShuttle – This is similar to the selectManyShuttle component, but additionally, it includes the up and down arrow
buttons that the users can use to reorder values in the Selected Values list box as shown in the following screenshot:
In this recipe, we will add the DepartmentId attribute as selectOneChoice inside the Employeesform we created in the first
recipe.

734
.
Single-Selection Components
In order to add the selectOneChoice component, follow the ensuing steps:
Open the inputComponets.jsf page.
Drag the DepartmentId attribute
under EmployeesView1 inChapter4AppModuleDataControl from the Data Control pane and
drop it inside the panel form layout.
Select Single Selection and choose ADF Select One Choice.
Save everything.
Run the inputComponents.jsf page. You should now see the following output page:

735
.
736
.
Multiple Selection

737
.
738
.
739
.
740
.
741
.
742
.
743
.
744
.
745
.
746
.
Define a List
You can define a list in one of two ways:
At the model layer: You can define lists of values (LOVs) on view object attributes declaratively,
including the ability to:
Configure the display style (including both inline drop-down lists for shorter lists and
pop-up windows for longer lists)
Filter the choices in the list based on user input
Autofill the attribute value if user input identifies a unique match
Automatically use other attribute values in the current row to parameterize “cascading”
lists
In the UI, by binding a selection component to model data
When you define lists at the model layer, they appear in a consistent manner regardless of the
type of UI that you use. In addition, you can test them with the Business Components Browser.
Because defining lists at the model layer is a best practice, that is the method discussed in this
lesson.

747
.
Select a Date
As with other components, you can create a calendar component by dragging from the Component Palette or the Data
Controls panel. However, when a default component is created for a date attribute, it is automatically created as an
af:inputDate component. This component presents a text input field for entering dates and a button for picking dates from a
calendar. The default date format is the short date format appropriate for the current locale. For example, in U.S. English, the
format is mm/dd/yy. However, you can override the format using af:convertDateTime. The same component can also include
the selection of time if the column is of the timeStamp type.
When you use the af:inputDate component, an af:convertDateTime subcomponent is included. This subcomponent converts a
String into java.util.Date, and vice versa, based on the pattern and style set.
You can set the following attributes on the af:inputDate component, either programmatically or by using the Property
Inspector:
label: Specify a label for the component.
chooseId: Specify the ID of the af:chooseDate component, which can be used to pick the Date value for this af:inputDate.
value: Specify the initial value of the component.
minValue: Specify the minimum value allowed for the date value. When set to a fixed value on a tag, this is parsed as an ISO
8601 date. ISO 8601 dates are of the format yyyy-MM-dd (for example, 2002-02-15). All other uses require java.util.Date
objects.
•maxValue: Specify the maximum value allowed for the date value. When set to a fixed value on a tag, this is parsed as an ISO
8601 date. ISO 8601 dates are of the format yyyy-MM-dd (for example, 2002-02-15). All other uses require java.util.Date
objects.
•disableDays Specify a binding to an implementation of the org.apache.myfaces.trinidad.model.DateListProvider interface. The
getDateList method should generate a List of individual java.util.Date objects, which should be rendered as disabled. The dates
must be in the context of the given base calendar. Note: This binding requires periodic round-trips. If you just want to disable
certain weekdays (for example, Saturday and Sunday), use the disabledDaysOfWeek attribute.
•disableDaysOfWeek: Specify a space-delimited list of weekdays that should be rendered as disabled in every week. The list
should consist of one or more of the following abbreviations: sun, mon, tue, wed, thu, fri, sat. By default, all days are enabled.
•disableMonths: Specify a space-delimited list of months that should be rendered as disabled in every year. The list should
consist of one or more of the following abbreviations: jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec. By default, all
months are enabled.
Note: ADF Faces pop-up components, such as dialog boxes, pop-up windows (af:popup), LOVs, and calendar components, are
not normal browser windows, but rather DHTML overlays that current pop-up blocker technology does not detect. They are,
therefore, not affected by pop-up blockers.

748
.
749
.
750
.
Use Tables
The ADF Faces table component af:table is similar to the standard JSF component but provides
additional features, including the ability to sort columns by clicking the column header, filtering
data, reordering columns, and selecting a single row or multiple rows.
Table attributes enable you to specify the look and feel of the table, whether users will be able
to select rows, or reorder columns, as well as identifying the data to be displayed.
The immediate children of a table component must all be column components, af:column. Each
visible column component is displayed as a separate column in the table. For sets of columns
that are related in some way, you can group them into column groups, with one heading
spanning several columns.
Attributes of each column specify details of the column, such as the alignment of values,
whether values are allowed to wrap within cells, and whether the column can be sorted, and if
so, on which property it is to be sorted. To specify the headers and footers for columns, header
and footer facets are available.
Within a column, both ADF Faces and standard JSF tags can be used for displaying the data.

751
.
752
.
753
.
Use Tree Tables
The ADF Faces tree table component af:treeTable displays hierarchical data in the form of a table. The
display is more elaborate than the display of an af:tree component. The af:treeTable component can
display columns of data for each tree node in the hierarchy. The component includes mechanisms for
focusing in on subtrees within the main tree, as well as expanding and collapsing elements in the
hierarchy.
The immediate children of an af:treeTable component must be af:column components, in the same way
as for af:table components. The af:treeTable component has a nodeStamp facet, which renders the
object name column. This is the column that contains the primary identifier of an element in the
hierarchy. For example, in a hierarchy of products, the object name column might be the category name
or the product name.
The af:treeTable component supports the same vertical and horizontal grid lines and banding as the
table component.
Both the af:tree and af:treeTable components render icons that the user can click to expand or collapse
a subtree. When the user clicks one of these icons, the component generates a RowDisclosureEvent.
(You learn more about events in the lesson titled “Responding to Application Events.”) The event has
two RowKeySet objects: RemovedSet for all the collapsed nodes and AddedSet for all the expanded
nodes. The component expands the subtrees under all nodes in the added set and collapses the
subtrees under all nodes in the removed set.
You can register custom RowDisclosureListener instances, which can do post processing, on the tree
component.
The af:tree and af:treeTable components use an instance of the oracle.adf.view.rich.model.RowKeySet
class to keep track of which elements are expanded. This instance is stored as the disclosedRowKeys
attribute on the component. You can use this instance to control the expand or collapse state of an
element in the hierarchy programmatically. Any element contained by the RowKeySet instance is
expanded, and all other elements are collapsed. The addAll() method adds all elements to the set, and
the removeAll() method removes all elements from the set.

754
.
Use Table Model Methods in a Selection Listener
The ADF Faces table components use a model to access the data in the underlying list. The
specific model class is oracle.adf.view.rich.model.CollectionModel. You may also use other
model instances, such as java.util.List, java.util.Array, and javax.faces.model.DataModel. If you
use one of these other classes, the table component automatically converts the instance into a
CollectionModel.
You can use table model methods, for example, in a method called by a selection listener on
the table. You can programmatically manipulate the table in the following ways:
To make a row current, call setRowIndex() with the appropriate index into the list or
with the appropriate rowKey.
To access a particular row in the list, first make that row current, and then call the
getRowData() method on the table.
To obtain the total number of rows in the list, call getRowCount(); if the model does
not yet know the total number of rows that are available, getRowCount() returns -1.
The table has an isRowAvailable() method that returns true if the current row is available. This
method is especially useful when the total number of rows is unknown.
You cannot use af:forEach to iterate over data within a table component; you can use
af:iterator instead.

755
.
Use Tree Model Methods in a Selection Listener
The ADF Faces tree components use a model to access the data in the underlying hierarchy. The
specific model class is oracle.adf.view.rich.model.TreeModel, which extends CollectionModel.
You can use code from this class in a managed bean method and call it from a tree’s selection
listener.
The TreeModel is a collection of rows. It has an isContainer() method that returns true if the
current row contains child rows. To access the children of the current row, call the
enterContainer() method. Calling this method results in the TreeModel instance changing to
become a collection of the child rows. To revert to the parent collection, call the exitContainer()
method.
The oracle.adf.view.faces.model.ChildPropertyTreeModel class can be useful when constructing
a TreeModel.

756
.
757
.
758
.
759
.
760
.
761
.
762
.
Use Data Visualization Components (DVT)
ADF Data Visualization components are a set of rich interactive ADF Faces components that
provide significant graphical and tabular capabilities for analyzing data. ADF Data Visualization
components have the following characteristics in common:
You create them at design time by using the Data Controls panel, the visual editor, the
Property Inspector, and the Component Palette.
Design time provides a live data preview.
You can bind data to standard rowset data controls, as well as hierarchical, BAM, and BI
data controls.
To see a demo of these components, go to
http://www.oracle.com/technology/products/jdev/viewlets/11/index.html and select Data
Visualization and Graphs for JSF.

763
.
The following list identifies the data visualization components:
•Graph: Supports more than 50 types of graphs, including bar, pie, line, scatter, and stock graphs, enabling you to evaluate data points on multiple axes in a
variety of ways. Part of JDeveloper since 10g, Graph is now a JSF component with many new features added:
-There are several new graph types, including funnel, floating bar, and fit to curve.
-Graphs can render in Flash or in Portable Network Graphics (PNG), an XML-based language for drawing two-dimensional graphics.
-Interactivity features include zooming and scrolling, time selector window, line and legend highlighting and fading, and dynamic reference lines and areas.
-The JSF graph tag is improved, with simplified tags for 17 commonly used graph types.
•Hierarchy Viewer: The hierarchy viewer component displays hierarchical data as a set of linked nodes in a diagram. The nodes and links correspond to the
elements and relationships to the data. The component supports pan and zoom operations, expanding and collapsing of the nodes, rendering of simple ADF
Faces components within the nodes, and search of the hierarchy viewer data. A common use of the hierarchy viewer is to display an organization chart, as
shown in the slide.
•Gauge: A new data visualization component in JDeveloper 11g that focuses on identification of problems in data. Supported gauge types are:
-Dial: Standard and Threshold
-Status Meter: Standard and Threshold
-LED
•Geographic map: A new data visualization component in JDeveloper 11g that provides functionality of Oracle Spatial within the ADF framework. It enables
you to represent business data on a geographic map, and supports superimposing multiple layers of information on a single map. Available map types are:
-Thematic
-Pie
-Bar
-Point
•Pivot table: A new data visualization component in JDeveloper 11g that supports multiple layers of data labels on a row or a column edge and automatic
calculation of subtotals and totals. It enables you to switch data labels from one edge to another to obtain different views of your data. Supported features
include:
-Horizontal and vertical scrolling
-Header and cell formatting
-Drag and drop pivoting
-Automatic totals and subtotals against ADF BC Data Control
-Drilling against BI Data Control
•Gantt chart: A new data visualization component in JDeveloper 11g that provides the ability to track tasks and resources on a time axis. Its purpose is to
assist in project planning. The following Gantt Chart types are supported:
-Project Gantt: Focuses on project management
-Scheduling Gantt: Focuses on resource management

764
.
765
.
766
.
767
.
Asynchronous JavaScript and XML (AJAX) combined with the component-based approach of
JavaServer Faces (JSF) is the technology behind ADF Faces’ highly interactive components.
ADF Rich Client components automatically provide various AJAX-like interactions, such as
sorting on table components

768
.
Freeze Columns

769
.
Delete and Insert Rows

770
.
Run and Test the Page
To test the page, run it either from the task flow diagram or from the page itself. To run the
page, right-click it in the editor and select Run. To run as part of the task flow, right-click the
view in the task flow and select Run.
To make testing quicker, you can retest the page without rerunning it if the page definition
(data binding information) has not changed. To do so, remove the parameters (everything from
? to the end) from the URL in the browser and reload the page. You can also retest it by clicking
the link that displays in the Log window. Make sure to recompile and save any changes before
retesting.
Then test the functionality. The example in the slide depicts a default ADF Search Form. To test
the functionality, you must enter one or more query criteria, and then click Search to retrieve
the queried data.

771
.
772
.
773
.
Lesson Agenda
In this lesson you can learn how to use different types of tree and table components and DVT
components

In Hands-on lab one would practice:


Adding Query Search and Result

Optionally you may also practice:


1. Customizing Query Search and Result
2. Adding Quick Search

774
.
775
.
776
.
The af:query component is used for transactional searches, providing a comprehensive set of search criteria and controls. The query component is a full-featured
component that can support multiple search criteria, dynamically adding and deleting criteria, selectable search operators, match all/any selections, seeded or
saved searches, basic and advanced modes, and personalization of searches.
It has the following two modes that the user can toggle by clicking a button that appears if the ModeChangeVisibleproperty of the query component is set to true:
•Basic mode query form features include:
-Drop-down list of selectable search criteria operators
-Custom list of operators
-Custom operators
-Selectable whereclause conjunction of either andor or(match all or match any)
-Saved searches and seeded searches
-Personalizing saved searches
•Advanced mode query form features include the ability for a user to dynamically add search criteria by selecting from a list of searchable attributes. The user
can subsequently delete any criteria that were added.
When you drop an af:querycomponent onto a JSF page, the component provides a search panel that includes one or more input fields for entering search criteria
values. The user can select from the drop-down list of operators to create a SQL Query WHEREclause for the search. You can configure an input field to be a list of
values (LOV), a number spinner, a date picker, or other control.
A Match All/Match Any radio group further modifies the query. A Match All selection is essentially an ANDfunction. The query returns only rows that match all of
the selected criteria. A Match Any selection is an ORfunction, where the query returns all rows that match any one of the criteria.
After users enter all the search criteria values (including null values) and select the Match All/Any option button, they can click the Search button to initiate
the query. The query results can be displayed in any output component. Typically the output component is a table or tree table, but you can associate other
display components such as af:form, af:outputText, and graphics to display the results component.
If you enable the Basic/Advanced button, the user can toggle between the two modes. Each mode displays only the search criteria that were defined for that
mode. You can define a search criteria field to appear only for basic, only for advanced, or for both modes.
In advanced mode, the control panel also includes an Add More button that displays a pop-up list of searchable attributes. When the user selects any of these
attributes, a dynamically generated search criteria input field and drop-down operator appears. All search criteria input fields are positioned in the order in which
the attributes are defined in the data source. Any newly created search criteria fields will also follow this rule. For example, if the attributes in the underlying
data source are ordered A, B, C, D, and E, and the default search fields are A, C, and If the user adds D, the search fields appear in the order A, C, D, E.
This newly created search criteria field also has a delete icon next to it. The user can subsequently click this icon to delete the added field. The originally defined
search criteria fields do not have a delete icon and, therefore, the user cannot delete them.
Search criteria can be saved and reaccessed using a given search name, but only if the application is configured to use persistence.
Note: Certain properties set on the view criteria in the ADF BC layer affect the run-time behavior of the query, such as the following:
•Requiredproperty of view criteria row: Determines whether a view criteria item is a required or optional part of the attribute value comparison in the generated
WHEREclause. The default is optional, which means that no exception is generated for nullvalues. If set to required, an exception is thrown when no value is
supplied. If set to Selectively Required, the view criteria item is ignored at run time if no value is supplied and another criteria item at the same level has a value;
otherwise, an exception is thrown.
•modeproperty of view criteria: Determines the initial mode, Basicor Advanced

777
.
Create Query Search Form
You create a query search form by dropping a named view criteria item from the Data Control
panel onto a page. The named criteria represent the view criteria that have been defined for
the data collection in the model. When you drop a named view criteria onto a page, that view
criteria is the basis for the initial search form. All other view criteria defined against that data
collection appear in the Saved Search drop-down list. Users can then select any of the view
criteria search forms, and also any saved searches.
You have a choice of dropping only a search panel, dropping a search with a results table, or
dropping a search with a tree table. If you choose to drop the search panel with a table, you
can select the filtering option to create a filtered table.
Normally, you would drop a query search panel with the results table or tree. JDeveloper
automatically wires up the results table or tree with the query panel. If you drop the query
search panel without the results table or tree, you can designate a component that is based on
the query’s data collection as a results component. In the Property Inspector for the query
panel, copy the value of the ResultsComponentId field, and then paste that value into the Id
field for the component that you want to designate as a results component.

778
.
Modify Query Behavior
When you define the view criteria in a view object, you specify the attributes and conjunctions
that form the query statement and serve as a basis for the query search form. You can also
specify some of the default properties of the search form after it has been dropped onto the
page. These properties include setting the basic/advanced mode, automatic query execution,
and search criteria field rendering.
After the query search form is created, you can set other properties such as setting the ID of
the results table or component. For example, to hide the Basic/Advanced toggle button, you
can set the ModeChangeVisible field to false.
Additionally, you can add a Cancel button to the footer facet of the query search form and use
it to call code in the business or model layer that would cancel a long-running query.

779
.
Quick Query Component
The quick query component has a single search criteria input field. The user can select which attribute to search by selecting from a drop-down list. The available
searchable attributes are drawn from the model or from a managed bean. The user can search against the selected attribute or against all attributes. The search
criteria field type will automatically match the attribute type. For example, if the selected search field is of type VARCHAR, an Input Text component is rendered.
Quick query components may be used as the starting point of a more complex transactional search that uses a query component. For example, the user may
perform a quick query search on one attribute, and if successful, may want to continue to a more complex search. The quick query component supports this by
having a built-in advanced link that is an af:commandLink component. You can create a managed bean to enable the user to switch from a quick query to a query
component.
Under the af:quickQuery tag are several attributes that define the quick query properties. The attributes of interest include:
The id attribute, which uniquely identifies the quick query. This value should be set to match the results table or the component’s partialTriggers value.
The Layout attribute, which specifies the quick query layout to be either horizontal or vertical
The Label attribute, which specifies the name to be displayed at the top of the search panel. It is usually an af:outputText component.
The af:quickQuery tag supports the following three facets:
The criteriaItems facet specifies the component that displays the search attributes of the search object. This component is usually an af:selectOneChoice, but
other components can be specified. You are responsible for connecting the quick query component with the model and implementing the queryListener in the
model.
The criterionValue facet specifies the component that displays or accepts the value of the search attribute of the search object. This component is usually an input
component, such as af:inputText, but other components can be specified. You are responsible for connecting the quick query component with the model and
implementing queryListener in the model.
The end facet, where you can add a command component to enable users to change from a quick query to a query (advanced mode)
The example shown in the slide has the following source code:
<af:quickQuery id="personsViewCriteriaOneQueryId" label="Search" value="#{bindings.PersonsViewCriteriaOneQuery.queryDescriptor}"
queryListener="#{bindings.PersonsViewCriteriaOneQuery.quickSearch}" layout="vertical">
<f:facet name="criteriaItems">
<af:selectOneChoice label="criteriaItems" simple="true" shortDesc="value" value="#{bindings.PersonsViewCriteriaOneQuery.selectedItem.value}">
<f:selectItems value="#{bindings.PersonsViewCriteriaOneQuery.searchableItems}"/>
</af:selectOneChoice>
</f:facet>
<f:facet name="criterionValue">
<af:inputText label="criterionValue" simple="true" shortDesc="value" value="#{bindings.PersonsViewCriteriaOneQuery.selectedItem.criterionValue}"/>
</f:facet>
<f:facet name="end">
<af:commandLink text="Advanced" rendered=“true"/>
</f:facet>
</af:quickQuery>

780
.
781
.
Schematic Representation of a Query Process
The sequential process of how a page sends a value to be used to return records to the page is
as follows:
1. You enter a wildcard in the Department field. This is a parameter for an executable binding
(ExecuteDepartmentsWithParams).
2. Click Find to execute the find_action method using the ExecuteDepartmentsWithParams
method.
3. The parameter value is passed into the deptNameVar1 variable for execution.
4. The ExecuteWithParams method is passed into the find_action method.
5. The source of the binding is the Data Control, which is part of the (6) Department View
Object, which is represented in the page definition file as an iterator (7).
6. In the page definition, DepartmentsView1 contains all the attributes that are used to display
on the page (9).

782
.
783
.
784
.
Lesson Agenda
This lesson describes how to build pages to support a multipage transaction. You add
transaction capability to the checkout flow and also define pages to insert, update, and delete
suppliers.
In Hands-on lab one would practice:
Implementing Create Operation

Optionally you may also practice:


1. Implementing Delete Operation and Creating Helper Method
2. Implementing Update Operation

785
.
786
.
Handle Transactions with ADF BC
A transaction is a persisted collection of work that can be committed or rolled back together as
a group.
The Business Components framework handles all transactions at the application module level.
The application module provides a transaction context, with a single database connection.
When you commit a change, the commit applies to all view objects in the application module.
For nested application modules, the outermost or root application module provides the
transaction context for all nested application modules.

787
.
Default ADF Model Transactions
The default behavior when an ADF model change is committed is to issue the commit directly
to the Transaction object of the current associated ADF BC application module instance to
handle the transaction.

788
.
Operations:
Operations are the actions bounded within the application module or the view object collection. The exposed
operations are mapped to an action component to invoke the action and execute the operation.
For the application module, we have the default operations defined. They are the Commit and Rollback
operations.
The operations available for the view object collection are as follows:
• Create: This operation is available to create a new record for the table component. The newly created record
will not be inserted and is not displayed in the UI for a table component. For a form-based component, this
method will create a new record and will display the information.
• CreateInsert: This operation will create a new record and will also insert a blank record if there is no default
value assigned for the attributes of the record. The newly created row is displayed in the UI for the table
component.
• Create with parameters: This method will allow the user to create a new record with some parameters, and
the values passed as parameters will be predefined for the created row.
• Delete: This operation is used to delete the current row from the view object collection.
• Execute: This operation will execute and refresh the current collection.
• Find: To find a specific record in the collection object.
• First: This method sets the current row so that the first row is shown to the user.
• Last: This operation is used to set the last row of the view object collection as the current row.
• Next: This operation is used to refer to the next row in the collection as the current row.
• Next Set: This operation is used to move to the next set in the collection.
• Previous: This method is used to set the previous record as the current row.
• Previous Set: This method is used to move to the previous set in the view object collection.
• removeRowWithKey: The key value is provided for this operation to remove the row matching the
corresponding key.
• setCurrentRowWithKey: The current row in the collection is set to the row matching the corresponding key
passed using this operation.
• setCurrentRowWithKeyValue: This operation will set the row to the matching key value.

789
.
Share Data Controls
The ADF Model layer provides a scoping mechanism for data controls called a DataControlFrame. At any given time there is
one current DataControlFrame. Whenever a data control is referenced, for example, by the EL expression #{bindings.foo}, the
ADF Model layer goes to the current DataControlFrame to find the data control.
By default, the called task flow shares all data control instances with its caller (shared data control scope). You can change that
by deselecting the “Share data controls with calling task flow” check box. With this setting, a DataControlFrame is created for
each task flow that is entered, with the result that each task flow has its own unique instance of any data controls it uses—it is
isolated from its caller and does not share any data control instances.
The model layer uses the DataControlFrame to manage the transaction that the data controls within the frame participate in.
The behavior of various task flow transactional settings is dependent on the data control scope, as shown in the following
table:
Synchronizing with the Model
By default, a transaction is not committed until the task flow is exited, because that is when the DataControlFrameis
committed. If you attempt to commit in the middle of the task flow, the state of the UI gets out of synchronization with the state
of the model. However, you can enable a midtask flow commit by manually committing the DataControlFrame, as in the
following example:
static public void saveAndContinue() {
Map sessionMap =
FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
BindingContext context = (BindingContext)sessionMap.get(BindingContext.CONTEXT_ID);
String currentFrameName = context.getCurrentDataControlFrame();
DataControlFrame dcFrame = context.findDataControlFrame(currentFrameName); dcFrame.commit();
dcFrame.beginTransaction(null);}
FacesContextcontains the information necessary for request processing, and invokes an object that executes the life cycle.
BindingContextis a container object that defines a hierarchy of data controls and data binding objects derived from the
Oracle ADF Model Layer. It is the handle through which the client accesses the data binding layer, and is represented by the
bindingsvariable in EL data binding expressions.

790
.
791
.
792
.
Handle Transaction Exceptions
During the execution of an ADF task flow, exceptions can occur that may require some kind of
exception handling, such as when a method call activity throws an exception or when a user is
not authorized to execute the activity.
To handle exceptions thrown from an activity or caused by some other type of ADF controller
error, you can create an exception handler for an ADF bounded or unbounded task flow. When
an exception is raised within the task flow, the control flow passes to the designated exception
handling activity. The exception handler activity can be any supported activity type, for
example, a view that displays an error message, or a router activity that passes the control flow
to a method, based on an expression that evaluates the type of exception.
As a best practice, any ADF bounded task flow representing a managed transaction should
designate an exception handling activity. When running an ADF bounded task flow managed
transaction, the ADF controller attempts to commit the transaction when it reaches a task flow
return activity identified in metadata for a commit. If the commit throws an exception, the
control is passed to the ADF bounded task flow’s exception handling activity. This provides the
end user a chance to correct any data and then reattempt to commit it. You can use the
exception handling activity to display a warning message on a page that tells the user to correct
the data and attempt to commit it again.

793
.
Designate an Exception Handler Activity
To designate an activity as an exception handler for a task flow, perform the following steps:
Right-click the activity in the task flow diagram, and then select Mark Activity > Exception
Handler. A red exclamation mark is superimposed on the activity in the task flow to indicate
that it is an exception handler.
To unmark the activity, right-click the activity in the task flow diagram, and then select
Unmark Activity > Exception Handler. If you mark an activity as an exception handler in a task
flow that already has a designated exception handler, the old handler is unmarked.
After you designate that an activity is the exception handling activity for a task flow, the task
flow metadata updates with an <exception-handler> element that specifies the ID of the
activity, as shown in the slide.

794
.
Transaction Support Features of Bounded Task Flows
Transaction options on the called task flow definition specify whether a called ADF bounded
task flow should join an existing transaction, create a new one, or create a new one only if
there is no existing transaction.
Savepoints: ADF creates a savepoint when a task flow is entered with an existing transaction.
The savepoint is a snapshot of the model state at the time the task flow was entered. The
savepoint enables the model state to be restored to what it was at the time the task flow was
entered.
If the called ADF bounded task flow is able to start a new transaction (based on the
transaction option that you select), you can specify whether the transaction is committed or
rolled back when the task flow returns to its caller.
In a called task flow definition, you can specify two different return task flow activities
that result in either committing or rolling back a transaction in the called ADF bounded task
flow.
You can enable users to save the state of the UI and model at any point and come back to it
later.
You can specify how a page should behave when users navigate to it by using the Back button.

795
.
Save for Later
In some applications, an end user may need to stop without completing a task, for example, when additional
information is needed to answer questions. As the developer of the application, you may want to retain the
current state of the task if a user leaves a page without finalizing it. You can also enable the user to complete the
rest of the task at a future point, with former unsaved values restored to the page. The ability to save the current
application state is called save for later.
There are two general categories of saving for later:
Explicit: For example, a page contains a button that the user can click to save all the data entered so far on the
page. Explicit save for later is available for both ADF unbounded and bounded task flows. For example, a user may
click a button to save, but not submit, a partial expense report, and then may cancel out of the application. Later
the user can invoke a list of saved expense reports and select the one to continue working on.
Implicit: For example, a user accidentally closes a browser window without saving data entered on a page, a user
logs out without saving the data, or the session times out. Implicit save for later can originate only from a bounded
task flow.
Save for later saves the data without enforcing validation rules or submitting it. The end user can resume working
on the application later with the same data that was saved at the point when save for later was performed.
Save for later is implemented by using a save-point-id that captures a snapshot of the ADF application at a specific
point in time. This includes everything from the time the savepoint is created in the originating task flow up the
call stack. Application state information is also saved, including:
UI state, including table sort order and selected tabs, check boxes, table rows, and so on
Managed beans: Saves the state information that is saved in memory scopes, except for request scope and
application scope
Navigation state: Task flow call stack, which tracks where the user is in the application and the navigational path
for getting there, and also the starting point of any data transactions
Model state: Any data model updates made since beginning the current bounded task flow, subject to limits
imposed by the model layer on the saved state lifetime
The same save-point-id can be used when the same user repeatedly performs a save for later on the same
instance of a task flow within the same browser window within the same session. If a user performs a save for
later following every page of a task flow, only one save- point-id is created and is overlaid each time.
An example of when you might use an explicit save for later is an expense report application. A user may click a
button to save, but not submit, the partial expense report, and then may cancel out of the application. Later the
user can invoke a list of saved expense reports and select the one to continue working on.

796
.
Enable Explicit Save for Later
To enable explicit save for later, you must incorporate a call to the createSavePoint() API to create a savepoint. The
save-point-idsaves data and state information about a region, view port, or portlet. Later, you use the Save Point Restore
activity to restore application state and data associated with a save-point-id.
A save-point-idis stored in a database table or Java object cache, depending on the value that you have specified for the
savepoint-managerconfiguration option (discussed later in this lesson). When save-point-idis restored, it is deleted
from the database or Java object cache.
To add the save for later capability to a task flow, perform the following steps:
1. Drag a method call activity from the ADF Task Flow page of the Component Palette to the diagram for the ADF bounded
task flow.
2. In the diagram, select the Method Call activity.
3. On the Common page of the Property Inspector, enter an ID for the method—for example,
callCreateSavePoint.
4. In the method field, enter an EL expression for the savepoint method, for example,
#{controllerContext.currentViewPort.createSavePoint}.
If you created your own method to call createSavePoint, enter that method name
instead (see the example that follows this list of steps).
5. After adding the method call activity to the diagram, connect it to the other existing activities in the diagram
using control flows.
6. You can optionally set properties in the adfc-config.xmlfile, such as the savepoint
default expiration time and where savepoints are stored. This is described later in this lesson.
You can access the createSavePoint()method under the currentViewPortnode under ADF Controller Objects.
Instead of calling this method directly, you may want to create your own method that calls createSavePoint(), as shown
in the following example: (If you do this, you can update save-point-idwith any attributes you create on your method.)
package viewcontroller;
You can override the global settings for individual savepoints for the amount of time that a savepoint remains in effect by
calling the setSavePointTimeToLive()method. You can include this in the same method that you use to create the
savepoint. The method signature is:
void setSavePointTimeToLive(long timeInSeconds)

797
.
Enable Implicit Save for Later
Implicit save points are generated only if a critical task flow is present in any of the page flow
stacks for any view port under the current root view port. An implicit savepoint is not
generated if the request is a request for an ADF Controller resource, such as:
The task flow call activity
The task flow return activity
A Save Point Restore activity
A dialog
Implicit savepoints are deleted when the task flow at the bottom of the stack completes or a
new implicit savepoint is generated, whichever comes earlier.
If you want an implicit save for later to occur when the session times out, the user logs out
without saving the data, or the user closes the only browser window, then you can select the
Critical check box on the Behavior panel of the Overview tab for the task flow definition, or set
Critical to true on the Behavior panel of the Property Inspector. You must also set an attribute
in the adfc-config.xml file, as described later in this lesson.
If multiple windows are open when the implicit savepoint is created, a different save-point- id is
created for each browser window. This includes everything from the root view port of the
browser window and down. To return a list of implicitly saved savepoints, you can use
controllerContext.savePointManager.listSavePointIds.

798
.
Restore Save Points
Restoring a save-point-idreturns the end user back to the part of the application where the ID was created and restores the
application state. Use the Save Point Restore activity to restore a previously persistent savepoint for an application.
When a savepoint is restored, the ADF controller terminates the saved application and restarts the application that was
executing when the end user performed a save. The end user’s original location in the application is displayed. After the
save-point-idis restored, it is deleted from its method of persistence (database or Java object cache).
A Save Point Restore activity is not required within every individual application supporting save for later capabilities. It is only
required within the applications responsible for restoring the previously persistent save-point-id. For example, a Save
Point Restore activity would not be required within a Create Expense Report application, but would be within the application
used to select previously saved Expense Reports for further updates.

Save Point Restore Finalizers


When used in conjunction with a Save Point Restore activity, a Save Point Restore Finalizer contains application-specific logic
that may need to be performed to restore the application’s state. The Save Point Restore Finalizer is a method that is invoked
after the ADF bounded task flow’s state has been restored. This method performs any necessary application logic to ensure that
the application's state is correct before proceeding with the restore. For example, you might use a Save Point Restore Finalizer
to restore logic for time validations.
During the restore process, each bounded task flow on the call stack being restored gets a chance to verify that its restored state
is valid and to perform any restore-specific logic it might need.
To add a Save Point Restore Finalizer method to an ADF bounded task flow, perform the following steps:
1. In the editor, open the ADF bounded task flow on which you want to execute a Save Point Restore Finalizer method. This
is the ADF bounded task flow being restored, not the task flow executing the Save Point Restore activity.
2. In the editor, click the Overview tab and click Common.
3. Click the button next to the Finalizer.
4. In the dialog box, specify a custom Save Point Restore Finalizer method on a managed bean—for example:
#{pageFlowScope.taskflowBean.finalizerMethod}

799
.
Set Global Save for Later Properties
In the adfc-config.xml file, you can set the following properties that govern the save for later
behavior:
savepoint-expiration: Number of seconds that, by default, savepoints in an
application are retained. The default is 86400 (24 hours). You can override for individual
savepoints by setting time-to-live on the savepoint.
savepoint-manager: Type of savepoint persistence. The default is DATABASE, but
can alternatively be set to JOC (Java object cache).
savepoint-datasource: The JNDI name of the data source, such as
jdbc/MyConnectionDS (Typically, this is the name of the database connection
appended with DS.)
enable-implicit-savepoints: Set to true to enable implicit save for later.

800
.
801
.
Define Response to the Back Button
To deal with cases in which the end user clicks the Back button to navigate back into an ADF bounded
task flow that was already exited, you can specify the following task-flow- reentry options for the task
flow definition that specify whether a page in the ADF bounded task flow can be reentered:
reentry-allowed: Reentry is allowed on any view activity within the ADF bounded task flow.
reentry-not-allowed: Reentry of the ADF bounded task flow is not allowed. An end user can still click
the browser’s Back button and return to a page within the bounded task flow. However, if the user does
anything on the page such as clicking a button, an exception (for example, InvalidTaskFlowReentry) is
thrown indicating that the bounded task flow was reentered improperly. The actual reentry condition is
identified upon the submit of the reentered page.
reentry-outcome-dependent: Reentry of an ADF bounded task flow using the browser’s Back button is
dependent on the outcome that was received when the same ADF bounded task flow was previously
exited via task flow return activities. For example, a task flow representing a shopping cart can be
reentered if the user exited by canceling an order, but not if the user exited by completing the order.
Upon reentry, ADF bounded task flow input parameters are evaluated using the current state of the
application, not the application state existing at the time of the original ADF bounded task flow entry.
If the Task Flow Reentry property of the task flow is set to reentry-outcome- dependent, a property of
the task flow return activity determines whether the user can use the Back button to navigate back to
the called task flow. On the Behavior tab of the task flow return’s Property Inspector, you can set the
Reentry property to reentry-allowed or reentry-not-allowed. This enables you to specify a different
response to the Back button depending on the outcome that is returned to the calling task flow.
When an end user reenters an ADF bounded task flow by using the browser’s Back button and reentry is
allowed, the value of a managed bean on the reentered task flow is set back to its original value—the
same value that it was before the end user left the original task flow.
This results in the managed bean value resetting back to its original value before a view activity in the
reentered task flow is rendered. Any changes that occurred before reentry are lost. To change this
behavior, specify the <redirect> element on the view activity in the reentered bounded task flow. When
the end user reenters the bounded task flow using the Back button, the managed bean has the new
value from the parent task flow, not the original value from the child task flow that is reentered.

802
.
803
.
804
.
In Hands-on lab one would practice:
Examining the Page’s Data Bindings

805
.
806
.
807
.
808
.
809
.
What Is Data Binding?
Having an easy and declarative way to bind Business Services to UI components is critical to simplifying the development of Java EE
applications that can be accessed from different interfaces. In the Model layer, Oracle ADF Model implements the JSR-227 service abstraction,
which is called the data control, and provides out-of-box data control implementations for the most common business service technologies.
ADF Model: Overview
In the Model layer, Oracle ADF Model implements the JSR-227 service abstraction called the data control. Data controls abstract the
implementation technology of a business service by using standard metadata interfaces to describe the service’s operations and data
collections, including information about the properties, methods, and types involved. Using JDeveloper, you can view the information as icons
that you can then drag onto a page. JDeveloper then automatically creates the bindings from the page to the services. At run time, the ADF
Model layer reads the information that describes your data controls and data bindings from appropriate XML files and implements the two-
way connection between your UI and your business service.
Oracle ADF provides out-of-the-box data control implementations for the most common business service technologies. Using JDeveloper and
Oracle ADF together provides you with a declarative, drag-and-drop data binding experience as you build your user interfaces. Along with
support for ADF application modules, the ADF Model also provides support for the following service technologies:
• Enterprise JavaBeans (EJB) session beans and JPA entities
• JavaBeans
• Web services
• XML
• CSV files
The Heart of ADF: ADFm
The key aspect of the ADF Model is the implementation of the JSR-227 specification, which provides the interface between the Business
Services layer and the UI layer.
The ADF Model, also known as ADF data binding, was introduced in JDeveloper 9.0.5. Previously, you defined the binding between your client
and your Business Services. For example, you used ADF BC JavaServer Pages (JSP) tags to bind a text field in a JSP to a View Object (VO)
attribute. The ADF Model introduces another layer of abstraction; instead of binding the client to the Business Services, you bind the client to
the model and bind the model to the Business Services.
The ADF Model describes the middle tier data model to the client. This description has the same metadata format for any business service
type.
JDeveloper helps to create data-bound user interfaces with the ADF Model by using:
• Drag-and-drop data binding
• Data control wizards
• Binding editors
• Page-definition editing
ADF Model Bindings
In JavaServer Faces (JSF), you use a simple EL to bind to the information that you want to present and/or modify. For example, you use
expressions such as #{UserList.selectedUsers} to reference a set of selected users, #{user.name} to reference a particular user’s name, and
#{user.role == 'manager'} to evaluate whether a user is a manager or not. At run time, a generic expression evaluator returns the List, String,
and Boolean values of these respective expressions, automating access to the individual objects and their properties without requiring code.

810
.
811
.
ADF Model Data Control Concepts
The Oracle ADF Model layer uses Extensible Markup Language (XML) configuration files to
direct generic data-binding features. Data controls abstract the implementation technology of a
business service by using standard metadata interfaces to describe the service’s operations and
data collections, including information about the properties, methods, and types involved.
At design time, visual tools such as JDeveloper can leverage the standard service metadata to
simplify binding UI components to any data control operation or data collection.
At run time, the generic Oracle ADF Model layer reads the information describing your data
controls and bindings from appropriate XML files and implements the two-way “wiring” that
connects your UI to your business service. This combination enables three key benefits:
• You write less code, so there are fewer lines to test and debug.
• You work the same way with any UI and business service technology.
• You gain useful run-time features because you do not have to code them yourself.

ADFm: Data Controls and Data Bindings


The ADF Model implements two concepts in JSR-227 that enable decoupling the UI technology
from the business service implementation. This technology has two parts:
• Declarative bindings describe and manage the characteristic interactions between specific
kinds of UI components (View and Controller layers) and the methods provided by a
Business Service (Model layer).
• Data controls provide supplemental metadata about the Business Service’s capabilities and
constraints, as well as a simple interface to normalize typical transactional interactions with
the service.

812
.
ADF Data Controls:
• They exposes Business Services to Bindings Layer.
• UI Layer interacts with Bindings and Bindings interact with data Controls.
• Each user gets its own instance of Data Controls
• By default there is a data control for each Root Application Module in Business Components
• All the instances in AM Datamodel and methods are exposed in data Controls

813
.
Different types of data controls support different functionality out of the box; the table shows
which types of data controls support transactions, sorting and updates. Support for
transactions, sorting and updates are defined by attributes in the .dcx file:
SupportsTransactions, SupportsSortCollection, and SupportsUpdates. If you want to change this
support you need to change the setting in the dcx file and extend your data control to
implement the appropriate methods. For example, if you want to support transactions for a
JavaBean data control you must change SupportsTransactions to true and implement
commitTransaction() and rollbackTransaction() in your data control.

814
.
815
.
Page Definition Files
The page definition file is created automatically the first time you create a binding on a page. Alternatively, if you select “Go to Page Definition” for a page that does not currently have a page definition, you are prompted to create
the page definition file. Page definition files are named <pagename>PageDef.xml. If you rename a page definition file, you must also change the name of the file in DataBindings.cpx. A page definition file includes the following
elements:
• <parameters>: Defines page-level parameters that are EL accessible. These parameters store information that is local to the page request.
• <executables>: Defines the list of items (methods and iterators) to execute during the prepareModel phase of the ADF page life cycle. The execution is performed in the sequence listed in the <executables> section, depending
on the item’s refresh and refreshCondition attribute values.
• <bindings>: Refers to an entry in <executables> to get the collection from which bindings extract or submit attribute-level data
ADF Data Bindings Concepts
Data bindings abstract the details of accessing data from data collections in a data control and of invoking its operations. There are three basic kinds of data binding objects that automate the key aspects of data binding that all
enterprise applications require:
• “Iterator bindings” to bind to an iterator that tracks the current row in a data collection
• “Value bindings” to connect the UI components to the attributes in a data collection
• “Action bindings” to invoke custom or built-in operations on a data control or its data Collections
Iterator binding: Keeps track of the current row in a data collection
• Iterator
• Method iterator
• Accessor iterator
• Variable iterator
Value binding: Connects UI components to attributes in a data collection—for example, attribute binding, tree binding, list binding, and table binding
Action binding: Invokes a method or operation
Binding Objects in the Executables Section
The following types of binding objects are available in the executables section:
• iterator: Is the basic link from data to binding
• methodIterator: Links the results of a method call to a binding
• accessorIterator: Links to detail collections for nested objects (not used with ADF BC)
• variableIterator: Accesses local data defined in the page definition file
- Most often used for method arguments
- Not linked to a data control
• invokeAction: Allows the invocation of a method binding automatically within the life cycle (an alternative to invocation using a user action—for example, clicking a button). This type of binding was used in earlier versions of
JDeveloper to invoke a method, but in the current version, it is better to use a method call in a task flow, which gives you better control over when the method is executed.
Controlling the Execution of Executables
Refreshing an invoke action binding invokes the action.
Determining When to Refresh
You can use the Refresh property on iterator bindings and invoke action executables in your page definition file to control when each is evaluated during the ADF page life cycle. Valid values for the Refresh property are:
• deferred (the default): Enforces execution whenever it is demanded for the first time, such as when a binding value is referenced in an EL expression. When it is called, it does not re-execute unless the binding itself or any
parameter values for the binding have changed.
• prepareModel: Refreshes during the Prepare Model phase
• renderModel: Refreshes during the Prepare Render phase
Note: The key distinction between the Prepare Model phase and the Prepare Render phase is that one comes before JSF’s Invoke Application phase and the other after it. Because action listeners fire in JSF’s Invoke Application
phase, if you need your iterator to refresh after these action listeners have performed their processing, you may want to set the Refresh property to renderModel.
• ifNeeded: Refreshes the iterator only if it has not been refreshed, based on the refresh condition or if no condition is specified, during the Prepare Model phase
• prepareModelIfNeeded: Same as ifNeeded, during the Prepare Model phase Refreshing an invoke action binding invokes the action.
Determining When to Refresh (continued)
• renderModelIfNeeded: Is the same as ifNeeded, during the Render Model phase
• RefreshAfter: Specifies that one executable refreshes after another (you also need to set the RefreshAfter property in addition to the Refresh property); used to handle dependencies between executables
• never (valid for iterator bindings only): Refreshes only when your own code calls getRowSetIterator() on the iterator binding
• always (valid for iterator bindings only): Iterator is always refreshed during both the Prepare Model and Prepare Render phases
Determining Whether to Refresh
Before refreshing any bindings, the ADF run time evaluates the refreshCondition attribute of the executables, which specifies the conditions under which the executable should be refreshed. You can specify the refreshCondition
value using a Boolean EL expression (default is true.) If an iterator binding is not refreshed during the life cycle, it does not point to any row set iterator for that request. This results in the value bindings related to that iterator
binding not having any data to display. This can be a desirable result when, for example, you want a page such as a search page to initially show no data. To achieve this, you can use the refreshCondition of:
#{adfFacesContext.initialRender}, which evaluates to true when a page is first rendered. You should set the Refresh property of an executable to renderModel when refreshCondition is dependent on the model. So if you want to
use the #{adfFacesContext.initialRender} expression in refreshCondition of an executable, you must set the Refresh property to either renderModel or renderModelIfNeeded, which causes the method to be executed during the
prepareRender phase. Another attribute, which determines whether to refresh the executable is refreshAfter. It specifies the condition after which the page should be refreshed. Refresh the iterator when the cart already has an
ID or if the order status is OPEN.

816
.
Attribute Values:
• Is used to access single value from collection/ Iterator executable
• They are accessed using #{bindings.<bindingName>.inputValue>
Page Definition File:
• Each page/fragment has a page definition file
• It’s a XML file that stores bindings of the corresponding page
• They are created by default when any UI component is created on the page associated to DC
for the first time. E.g. drag and drop VO as Table
• Gets created in Application Sources in ViewController Project
• One can go to page definition through bindings tab of the page
Executables:
• Bindings must refer executables
• Executables are Iterators/collection models from data controls
• Iterators sync the current row accessed in the UI to the row in collection model and
remembers it
• VO Iterators are created whenever any VO is dragged to the page to create a component
• Variable iterator are used to save values between the requests

817
.
• IDE adds ADF Faces Components to the JSF page. Common attributes of the UI components
are defaulted by using the attribute definitions present in the model, referred through
Expression Language (EL).
• It creates DataBindings.cpx if it is not found in the default view package under the ADFm
source directory. The default location of the ADF model source is the adfmsrc folder located
under the view project.
• It creates adfm.xml if it is not found in the META-INF folder under the adfmsrc directory. This
is considered as a registry of all metadata registries used by the view project. When IDE
creates a data binding cpx file (DataBindings.cpx), an entry is made in adfm.xml to keep track
of all the cpx files present in a web application.
• It creates the page definition XML (<PageName>PageDef.xml) file if it is not already present
for the page. This is located in the pageDefs folder under the view project package, which is
found under the adfmsrc directory. This file contains the binding metadata for each data
bound UI element present on the page. When IDE creates a page definition file for the JSF
page, it also adds a mapping entry between the JSF and page definition file in the
DataBindings.cpx file.
• It adds the required library dependencies to the view project.
• It updates web.xml to add runtime configurations such as ADFBindingFilter, which is required
by the ADF Faces Components runtime.

818
.
819
.
adf-config.xml: The adf-config.xml file specifies application-level settings that are usually determined at deployment and
are often changed at runtime. You can use a deployment profile to specify settings that are used at application deploy time.
You can change some of the settings at runtime using Oracle Enterprise Manager. JDeveloper generates the adf-config.xml file
when you create an application using the Fusion Web Application (ADF) template. It stores the file in the following
directory:application_root\.adf\META-INF
faces-config.xml: Used to register JSF application resources, like default renderer kit and resource bundle.
adfc-config.xml: Is the source file for the ADF unbounded task flow that JDeveloper creates by default when you create
an application. By default, JDeveloper stores the adfc-config.xml file in the following directory:
application_root\ViewController\Web Content\WEB-INF
web.xml: Sets up the ADFBindingFilter. When you create a project in JDeveloper that uses JSF technology, a starter
web.xml file with default settings is created for you in the /WEB-INF folder. To edit the file, double-click web.xml in the
Application Navigator to open it in the XML editor. Contains the configuration parameters needed to run an ADF Faces
application, such as: where to save the application view state, servlets and filters, registered mime types and session time-out
period.
trinidad-config.xml: This file defines custom look and feel of JDeveloper i.e., skins.
adfm.xml: The file registry is used extensively by the ADF Library resource catalog browsing implementations, by the ADF
model layer design time, and at runtime during merge and discovery. When a developer creates a binding on a page,
JDeveloper adds metadata files (for example, page definitions) in the project source tree. The adfm.xml file then notes the
location of each. In short, it defines the location of .cpx, .jpx, .xcfg files.
DataControls.dcx: Is the registry for the data controls in the application. It contains information about the type of data
control needed to work with a particular service (e.g. EJB, JavaBean, XML, Webservice, etc..) and how to construct the data
control at runtime.
DataBindings.cpx: Contains mapping of pages, page definitions references and data control reference. The
DataBindings.cpx file defines the Oracle ADF binding context for the entire application, hence also known as Binding Context. It
also has Default Exception Handler which can be modified using ErrorHandlerClass attribute.
<pagename>PageDef.xml: Is the page definition XML file. This file is created each time you design a new web page. It
binds iterators to VO and iterator bindings to iterators . It is also know as Binding Container.
Model.jpx: The.jpx file contains configuration information that JDeveloper uses in the design time to allow you to create the
data model project with ADF Business Components.
bc4j.xcfg: The bc4j.xcfg file contains metadata information about application module names, the database connection used
by the application module, and the runtime parameters the user has configured for the application module.
task-flow-definition.xml: The default file name that JDeveloper proposes for the source file of the first ADF bounded task
flow that you create is task-flow-definition.xml. This file stores the metadata for a bounded task flow. It contains entries for
each view activity, method call activity, task flow call, and so on that you add to the bounded task flow.
<page>.jspx or .jsff: References bindings defined in the page definition file.
<AM>.xml: Defines VO names and locations.

820
.
At run time, the objects created from these files interact in the following sequence:
1. When you first request for an ADF data-bound Web page, the servlet registers the
ADFBindingFilter Oracle ADF servlet filter named in the web.xml file.
2. The binding filter creates an empty binding context.
3. When a page is rendered, the binding filter asks the binding context to load a corresponding
<page>PageDef.xml file for the page.
4. The binding context creates the binding container by loading the <pagename> file as
referenced by the <pagemap> element from the DataBindings.cpx file.
5. adfm.xml loads the .cpx contents and finds the right PageDef.xml based on the
<pagemap> element.
6. The binding container’s prepareModel phase prepares or refreshes all relevant executables.
(By default, most are marked deferred.)
7. An iterator binding is executed by referencing the named method on the data control found
via the data control factory named in the bc4j.xcfg file.
8. The binding container also creates the bindings defined in the <bindings> section of the
<pagename>PageDef.xml file for the mapped Web page.
9. The Web page references ADF bindings through EL using the expression #{bindings},
which get resolved when you access the binding container of the page.
10. The page pulls the available data from the bindings on the binding container.

821
.
1. When the first request for an ADF databound web page occurs, the servlet registers the
Oracle ADF servlet filter (Binding Filter) ADFBindingFilter named in the web.xml file.
2. ADF Binding filter asks the adfm.xml file to load the Binding Context DataBindings.cpx.
3. Binding Context loads two things. First it finds or creates Application Module configuration
(bc4j.xcfg) and data controls (if any).
4. Then binding context creates the binding container by loading the <page> file as referenced
by the <pagemap> element in the DataBindings.cpx file.
5. When a page is rendered, the binding container creates the bindings defined in
the <bindings> section of the pagenamePageDef.xml file for the mapped web page.
6. The binding container's prepareModel phase prepares and refreshes all relevant
executables (most are marked deferred by default).
7. An iterator binding gets executed by referencing the named method on the data control
found through the data control factory named in the case of ADF Business Components in
the bc4j.xcfg file
------------------------------------------------------------------------------------------

822
.
823
.
What just happened?
Using the action performed in the previous section, we learned how to create the bindings in the page definition file. The Commit action binding will be displayed in the binding container of
the page definition file. In the Create Action Binding dialog, the operation is populated automatically because Commit and Rollback are the options available by default in
EmpDirectoryModuleDataControl.
Adding executables:
Just like creating the bindings for the component, we can add the executable for the page definition by clicking on the Add buttn in the Executables section of the page definition file.
Some of the items in the Executables section are as follows:
accessorIterator:
acessorIterator is used to iterate the Accessor hierarchy from the data control layer. The CacheResults property will manage the collection between requests. ChangeEventPolicy will control
the behavior of the refresh action. The options available are as follows:
• none: The iterator is refreshed based on the refresh condition provided.
• push: Asynchronous data changes will automatically be refreshed.
• ppr: ppr is a partial page rendering, which will refresh only some part of the page. The setting will help the iterator to be refreshed if the current row of the iterator is changed and the
ppr action occurs.
invokeAction:
We create this executable to invoke an action on a specific condition. For example, if we want to invoke the Commit action on a condition and on a page load, we will map the invokeAction
item to the Commit operation binding and then move the invokeAction item to the top as the first executable in the list of executables in the page definition. The invokeAction item provides a
Refresh property, which will allow the accessor method based on the option provided. The options available are as follows:
• always: This option refreshes the executable always.
• deferred: If the refresh is based on another executable, this option refreshes the executable accordingly.
• ifNeeded: The refresh is taken care of whenever needed by the framework. This is the default for executables.
• never: Never refreshes the executable.
• prepareModel: Refreshes every time the binding is prepared.
• prepareModelIfNeeded: Only refreshes if needed and/or if the page binding container is prepared.
• refreshAfter: Sets the dependent executable to execute the current executable after the one mentioned.
• renderModel: Refreshes the executable when the page is rendered.
• renderModeIfNeeded: Refreshes the executable only if it is needed by the framework when the page is rendered.
The RefreshCondition item will hold the condition on which the refresh is to happen. RefreshAfter will hold the condition after which the executable is refreshed.
iterator
The iterator item simply references a collection to traverse the records. We can have the refresh condition and parameters set to change the behavior of the iterator item. Iterator also has
properties such as Refresh, RefreshCondition, and cacheResults. The RangeSize property for the Iterator item will represent the number of rows displayed in the Iterator collection.
Page:
We can have a nested page definition specified within another page definition as a container using this executable. This is primarily used to ensure that bindings of a template are referenced
at runtime.
searchRegion:
The searchRegion item is an executable for querying the data using view criteria. The query component will make use of the searchRegion executable to query information from the database
through the view criteria from the model layer.
shuttleRegion:
The shuttleRegion executable is useful for the shuttle component to display the shuttle elements. The available and the selected list of elements is maintained within the shuttleRegion
executable.

824
.
825
.
826
.
827
.
ADF validation is added like JSF validation as an additional element to the attribute binding.
This is very similar to the way that validators are added to JavaServer Faces. Since client side
validation can be fooled it may be considered as best practices to use the two validations in
combination. In future developments ADF may provide a central definition for validation rules
that then is automatically read on the different layers.

828
.
ADF business components has always had declarative validation and control hints; now these
features are available for data controls (all types except ADF BC) and bindings.

10.1.3 onwards also supports binding-level authorization (ADF BC only)

829
.
Access Bindings from Page:
• Bindings are accessed in page/fragment using EL
• Bindings variable (#{bindings}) contain all the bindings from the page definition of current
page in which it is accessed

830
.
The example on the page shows an ADF Faces inputText component (a text field with label) that
will display the employee name. The text field’s attributes are all set using EL expressions; the
dot-separated expressions in the example all start with bindings, the binding variable that
represents the binding context of the current page.

The attributes are evaluated as follows:


•value=“#{bindings.Ename.inputValue}”: The value of the inputText component is set to the
value of the Ename attribute
•label=“#{bindings.Ename.label}”: The label is set to the label property of the Ename attribute.
If you have assigned a custom label to Ename, then the label property is your custom label,
otherwise the label property is the same as the attribute name.
•required=“#{bindings.Ename.mandatory}”: required is a boolean attribute that determines
whether a value must be entered in the field. In this case required evaluates to the mandatory
property of the Ename attribute: if Ename is a mandatory attribute, then the inputText requires
a value and will be displayed with a required indicator (*) next to the field.

831
.
Use Expression Language (EL)
You can use a simple Expression Language (EL) to work with information. EL is part of JSP
Standard Tag Library (JSTL), and it defines a standard syntax for accessing dynamic values
without using Java scriptlets in JSPs. The standard syntax is #{object.attribute} for a JSF
expression or ${expression} for a standard JSTL expression. Binding expressions can use either a
$ or #prefix, but EL expressions in JSF pages can use only the # prefix.
At run time, a generic expression evaluator returns the value of expressions, automating access
to the individual objects and their properties without requiring code. You use EL expressions
throughout an ADF Faces application to bind attributes to object values determined at run
time.
The value of certain UI components (such as an input text component) is determined at run
time by the value attribute. Though a component can have static text as its value, typically the
value attribute contains an EL expression that the run-time infrastructure evaluates to
determine what data to display. Because any attribute of a component (and not just the value
attribute) can be assigned a value by using an EL expression, it is easy to build dynamic,
data-driven user interfaces.
You can create EL expressions declaratively by using the JDeveloper Expression Builder. You can
access the builder from the Property Inspector by selecting Expression Builder from the drop-
down list of an attribute.

832
.
Immediate EL Syntax: ${}
Occasionally, you may notice an expression that begins with $ rather than #. This indicates a
read-only expression that is evaluated immediately when a page is rendered.

833
.
Deferred EL Syntax: #{}
An expression, which begins with “#” uses deferred evaluation. This means that the expression
is evaluated at an appropriate time in the page life cycle, depending on how the expression I
used on the page.

834
.
835
.
836
.
837
.
838
.
839
.
840
.
841
.
842
.
843
.
844
.
845
.
Specify When to Refresh Binding Executables
Refreshing Iterator Bindings
For scalability reasons, at run time the iterator bindings in the binding container release any reference they have to a row set
iterator at the end of each request. During the next request, the iterator bindings are refreshed to again point at a “live” row
set iterator that is tracking the current row of some data collection. The act of refreshing an ADF iterator binding during the
ADF page life cycle is the operation of accessing the row set iterator to reunite the binding to the row set iterator to which it is
bound.
Refreshing Invoke Action Bindings
Refreshing an invoke action binding invokes the action.
Determining When to Refresh
You can use the Refresh property on iterator bindings and invoke action executables in your page definition file to control
when each is evaluated during the ADF page life cycle. The valid values for the Refresh property are as follows:
deferred (the default): Enforces execution whenever demanded the first time, such as when a binding value is referenced in an
EL expression. After it is called, it does not reexecute unless the binding itself or any parameter values for the binding have
changed.
prepareModel: Refreshes just during the Prepare Model phase
renderModel: Refreshes just during the Prepare Render phase
Note: The key distinction between the Prepare Model phase and the Prepare Render phase is that one comes before JSF’s
Invoke Application phase, and the other after. Because JSF’s Invoke Application phase is when action listeners fire, if you need
your iterator to refresh after these action listeners have performed their processing, you will want to set the Refresh property
to renderModel.
ifNeeded: Refreshes the iterator only if it has not been refreshed, based on the refresh condition or if no condition is specified,
during the Prepare Model phase
prepareModelIfNeeded: Same as ifNeeded, during the Prepare Model phase
renderModelIfNeeded: Same as ifNeeded, during the Render Model phase
RefreshAfter: Specifies that one executable refreshes after another (you also then need to set the RefreshAfter property in
addition to the Refresh property). RefreshAfter is used to handle dependencies between executables.
never (valid for iterator bindings only): Refreshes only when your own code calls getRowSetIterator() on the iterator binding
always (valid for iterator bindings only): Iterator always refreshed during both the Prepare Model and Prepare Render phases
Note: Refreshing an iterator binding does not forcibly reexecute its query each time. The first time the view object instance’s
row set iterator is accessed during a particular user’s unit of work, this implicitly executes the view object’s query if it was not
already executed. Subsequent refreshing of the iterator binding related to that view object instance on page requests that are
part of the same logical unit of work only accesses the row set iterator again, but does not forcibly reexecute the query. When
you want to reexecute the query to refresh its data, use the Execute or ExecuteWithParams built-in operation, or
programmatically call the executeQuery() method on the iterator binding.

846
.
Specify Whether to Refresh Binding Executables
The Refresh property determines the phase in which to invoke the executable, whereas the
RefreshCondition property determines whether to refresh the binding. Before refreshing any
bindings, the ADF run-time evaluates the RefreshCondition attribute of the executables, which
specifies the conditions under which the executable should be refreshed. You can specify the
RefreshCondition value using a Boolean EL expression (default is true).
If an iterator binding is not refreshed during the life cycle, it is not pointing to any row set
iterator for that request. This results in the value bindings related to that iterator binding not
having any data to display. This can be a desirable result when, for example, you want a page,
such as a search page, to initially show no data. To achieve this, you can use the expression
#{adfFacesContext.isInitialRender}, which evaluates to true when a page is
first rendered. So that data does not display when the page is first rendered, use a
RefreshCondition of: #{!adfFacesContext.isInitialRender}.
You should set the Refresh attribute of an executable to renderModel when the
RefreshCondition is dependent on the model. So if you want to use the
#{adfFacesContext.isInitialRender} expression in a RefreshCondition of
an executable, you must set the Refresh property to either renderModel or
renderModelIfNeeded, so that the executable refreshes during the Prepare Render phase.

847
.
Task Flow and ADF Life Cycle
Task flows associated with ADF regions are initially refreshed when their parent page is first
displayed. The task flow’s bindings are refreshed based on the Refresh and
RefreshCondition attributes. Regions, like pop-ups, that are not initially displayed are also
initialized at page startup. You can use a task-flow router activity to defer region initialization.
An ADF region initially refreshes when the parent JSF page on which the region is located first
displays. To execute the ADF task flow at the same time that the region renders, you must
trigger a task flow binding refresh at the same time that the region renders.
During initial refresh, any binding parameter values for the ADF region task flow are passed in
from the parent page. The parameter values are used to display the initial page fragment within
the ADF region. If the ADF-bounded task flow relies on input parameter values that are not
available when the page is first created, ensure that your task flow behaves correctly if the
input
parameter values are null. An ADF region task flow binding can be refreshed again based on
one
of the following task flow binding attributes:
• Neither Refresh nor RefreshCondition attributes specified (default)
• RefreshCondition="#{EL.expression}"
• Refresh="ifNeeded"
If the ADF region task flow binding does not have parameters, Refresh="ifNeeded" is
equivalent to not specifying the Refresh attribute. If you set Refresh to ifNeeded, the
RefreshCondition attribute should not be specified.

848
.
Declarative Control over Individual Page Life Cycle
Refresh="ifNeeded": Any change to a task flow binding parameter value causes the ADF
region to refresh. There are no values other than ifNeeded for the Refresh attribute.
RefreshCondition="#{EL.expression}": The ADF region is refreshed a single time
when its RefreshCondition evaluates to true. RefreshCondition must evaluate to a
Boolean value. At the time RefreshCondition is evaluated, if the bindings variable is
used within the EL expression, the context refers to the binding container of the parent page,
not the page fragment displayed within the ADF Region. RefreshCondition is independent of
the change of value of the binding parameters. If the task flow binding parameters do not
change, nothing within the ADF region changes.

849
.
850
.
851
.
Lesson Agenda
This lesson teaches you to implement business logic programmatically. You add business logic
to entity and view object classes and add service methods to an application module. You learn
to use ADF BC client APIs to change the behavior of business components, and then test the
modified functionality by creating and running a test client.

852
.
853
.
854
.
Using Client APIs
The Java interfaces of the oracle.jbo package provide a client-accessible API for your business
service. This package intentionally does not contain an Entity interface, or any methods that
would allow clients to directly work with entity objects. Instead, client code works with
interfaces such as:
ApplicationModule: To work with the application module
ViewObject: To work with the view object
Row: To work with the view rows
For a list of the most commonly used methods in the oracle.jbo interfaces, see Appendix E in
the Fusion Developer’s Guide for ADF.

855
.
856
.
857
.
858
.
859
.
860
.
861
.
Entity object definition XML metadata file: This file is an entity descriptor, which holds metadata
definition for the entity. This file stores the following configurations for an entity object: This file stores
the database object on which the entity is built upon. An entity object can be built from a database
table, view, synonyms, or materialized view.
This file also stores the attribute definition for each column present in the entity object. This includes
the datatype, length, precision, validation rules, and updatability of the attribute. Attribute definition
also includes UI hints such as label, tool tip, format type, and control type.
°°View accessors and entity accessor attributes' definitions are also stored in this file. View accessors
and entity accessor attributes' definitions are used for accessing view objects and associated entity
objects, respectively.
°°Business event definitions that are used for launching business processes in a service oriented
environment.

Entity definition: This class acts as a runtime Java class representation for the entity object definition
XML metadata file. The default entity definition class used by the ADF Business Components' runtime is
oracle.jbo. server.EntityDefImpl, which can be extended to provide custom functionalities, if needed.
• Entity object: This class represents individual entity instance created from the entity definition at
runtime. The default entity object class used by the ADF business components' runtime is
oracle.jbo.server.EntityImpl, which can be extended to provide custom functionalities, if needed. In
simple words, an entity object instance represents a row in the datasource. For example, when you
query an Employee table in the database by using a view object backed up by the EmployeeEO entity
object, the framework creates EmployeeEO entity object instances for storing employee records
returned by the SQL query.
• Entity collection: This class represents the cache of the entity object class held in memory for a
transaction. The default entity collection (entity cache) class used by the ADF Business Components'
runtime is oracle.jbo.server. EntityCache, which can be extended to provide custom functionalities, if
needed.

862
.
863
.
864
.
865
.
Generate Java Classes for Adding Code
ADF enables you to customize the behavior of your business components to the requirements
of your application. Although an increasing number of modifications can be accomplished
declaratively, there are cases where you must add code to meet the requirements.
By default, the only files generated for business components are the metadata files in XML. If
you need to add Java code, you can optionally generate Java classes on the Java tab of the
component’s editor as follows:
Click Edit (the pencil icon).
In the Select Java Options dialog box, select the check boxes for the class and methods that you
want to generate.
Click OK to generate the class. Then add to the class the methods that you want to code. Just as
with the XML definition file, JDeveloper keeps the generated code in your Java classes
up to date with any changes you make in the editor.
To delete a Java class that has already been generated, follow the same process, but deselect
those classes that you want to delete. Any code that you may have added to those classes is
lost when you delete the class.

866
.
Supporting Entity Java Classes
There are three base Java classes that implement entity objects:
EntityImpl: This is the entity object class. At run time, one entity object is instantiated
for each row of data. This class contains methods to get and set entity attribute values. All entity object
classes extend this class. The EntityImpl.java class provides methods to insert, update, delete, and lock
rows. The ADF Business Components technology uses this class to manage instances of each entity.
When you generate the entity object class, you can also generate:
Accessors: Generate typesafe accessors for the entity object’s attributes.
Data Manipulation Methods: Generate methods to override DML methods, such as
lock() and doDML().
Create Method: Select to override the create() method to modify or add
initialization features to the create logic.
Remove Method: Select to override the remove() method to modify or add clean-
up code to the remove logic.
EntityDefImpl: This is the entity definition class. At run time, one entity definition is
instantiated for each entity. You can add methods to this class that are used by all entity object
instances. For example, you could override a method to globally change the default format mask for
number attributes.
EntityCollImpl: This class represents the set of rows from the entity that is stored in the internal ADF
Business Component cache. You do not usually need to generate or modify this class, but if you do, you
may also choose to generate bind variable accessors and typesafe getters and setters for named bind
variables. An example of when you might want to generate this class is if you need to programmatically
retain and reuse an association accessor row set.
When you choose to generate Java classes for entity objects, the classes that are generated extend the
base classes. The classes that you generate use the entity name, followed by Impl, DefImpl, or CollImpl
(such as PersonEOImpl.java). These classes provide methods to manipulate either row-level data or the
definition of the entity itself. You can use the generated classes to add custom validation or business
logic.
You learn later in this lesson about the base classes for view objects and application modules.

867
.
868
.
869
.
870
.
871
.
872
.
873
.
Eagerly Assign Values from a Database Sequence
As you learned in the lesson titled “Declaratively Customizing Data Services,” you can
declaratively assign the DBSequence type for primary key attributes whose values are
populated by a database trigger at commit time. However, you can also eagerly allocate a
sequence number to use as a default value for an attribute so that:
The user can see its value
The value does not change when the data is saved
To accomplish this, use the SequenceImpl helper class in the oracle.jbo.server
package:
You override the initDefaults() method, as shown in the example in the slide. It shows code
from the Java class of a ProductEO entity object.
Call the initDefaults()method of the parent class.
Create a new instance of the SequenceImpl object to get a handle to the database
sequence.
Obtain the next number from the database sequence.
Assign the next sequence number to the ProdId.
The disadvantage of using a database sequence in this manner is that it results in more gaps in
the numbers assigned to primary keys, because if the user does not commit the record, the
sequence number is wasted.

874
.
Update Deleted Flag Instead of Deleting Rows
Your requirements may demand that rows are never physically deleted from a table, but rather
only have the value of a DELETED column changed from N to Y to mark it as deleted. There are
two method overrides required to alter an entity object’s default behavior to achieve this
effect:
Update a DELETED flag when a row is removed: Generate a Java class for your entity object and
override the remove() method to set the deleted flag before calling the super.remove()
method. The row will still be removed from the row set, but it will have the value of its
DELETED flag modified to Y in the entity cache. It is important to set the attribute before calling
super.remove(), because an attempt to set the attribute of a deleted row causes
DeadEntityAccessException.
Force an update instead of a delete: Override the doDML() method and write code that
conditionally changes the operation flag. When the operation flag equals DML_DELETE, your
code will change it to DML_UPDATE instead.
With this overridden doDML() method in place to complement the overridden remove()
method, any attempt to remove an entity row through any view object based on that entity will
update the DELETED column instead of physically deleting the row. However, to prevent rows
that are marked deleted from appearing in view object query results, you need to include
DELETED = 'N' as part of the WHERE clause of each view object.

875
.
876
.
877
.
878
.
879
.
880
.
881
.
Traverse Associations
By default, JDeveloper generates accessor methods for each association: a getter and a setter
in the destination to retrieve the source, and a getter in the source to get the destination.
These accessor methods are generated in the entity object classes on either end of the
association. The client code does not access the entity object code directly, so you could use
these methods in application module service methods or in programmatic view object or entity
object code.
Example of Accessor Methods: The PersonEO and OrderEO entities are linked by the
PersonEOToOrderEO association. JDeveloper generates two methods in OrderEOImpl.java (the
destination entity object) for traversing the association from destination to source:
public PersonEOImpl getPersonEO(): Get the department to which this
employee belongs.
public void setPersonEO(PersonEOImpl value): Set the value of the
department to which this employee belongs.
To retrieve an attribute’s value from the source entity while in the destination entity, use the
get<Source>() method plus the get() method for the attribute that you want to retrieve, as
shown in the above example for retrieving the email address from the PersonEO entity. The
PersonEO entity has only the getOrderEO accessor, with no setter.

882
.
Traverse Associations
By default, JDeveloper generates accessor methods for each association: a getter and a setter
in the destination to retrieve the source, and a getter in the source to get the destination.
These accessor methods are generated in the entity object classes on either end of the
association. The client code does not access the entity object code directly, so you could use
these methods in application module service methods or in programmatic view object or entity
object code.
Example of Accessor Methods: The PersonEO and OrderEO entities are linked by the
PersonEOToOrderEO association. JDeveloper generates two methods in OrderEOImpl.java (the
destination entity object) for traversing the association from destination to source:
public PersonEOImpl getPersonEO(): Get the department to which this
employee belongs.
public void setPersonEO(PersonEOImpl value): Set the value of the
department to which this employee belongs.
To retrieve an attribute’s value from the source entity while in the destination entity, use the
get<Source>() method plus the get() method for the attribute that you want to retrieve, as
shown in the above example for retrieving the email address from the PersonEO entity. The
PersonEO entity has only the getOrderEO accessor, with no setter.

883
.
884
.
Update or Remove an Existing Entity Row
You can add a method to update or remove a row. For example, you can add an application
module method to update an employee row by performing the following steps:
Find the Employee by ID: This example assumes that you have defined a helper method named
retrieveEmployeeById() that retrieves the EmployeeEO entity object by its primary key.
Set one or more attributes to new values: Use the setAttribute() method of the
EntityImpl class to update the value of the Email attribute to the new value passed in.
Commit the transaction: Use the application module’s getDBTransaction() method
to access the current transaction object and call its commit() method to commit the
transaction.
The example for removing an entity row would be the same as this, except that after finding
the existing entity, you would use the following line instead to remove the entity before
committing the transaction:
emp.remove();

885
.
Update or Remove an Existing Entity Row
You can add a method to update or remove a row. For example, you can add an application
module method to update an employee row by performing the following steps:
Find the Employee by ID: This example assumes that you have defined a helper method named
retrieveEmployeeById() that retrieves the EmployeeEO entity object by its primary key.
Set one or more attributes to new values: Use the setAttribute() method of the
EntityImpl class to update the value of the Email attribute to the new value passed in.
Commit the transaction: Use the application module’s getDBTransaction() method
to access the current transaction object and call its commit() method to commit the
transaction.
The example for removing an entity row would be the same as this, except that after finding
the existing entity, you would use the following line instead to remove the entity before
committing the transaction:
emp.remove();

886
.
Create a New Entity Row
In addition to using the entity definition for finding existing entity rows, you can also use it to create
new ones. For example, you could write a createProduct() method to accept the name and description
of a new product, and return the new product ID assigned to it. Assume that the ProdId attribute of the
Product entity object has been updated to have the DBSequence type, so that its value is automatically
refreshed to reflect the value that the ASSIGN_PRODUCT_ID trigger on the PRODUCTS table assigns to it
from the PRODUCTS_SEQ sequence in the database schema.
The example follows these steps:
Find the entity definition: Use EntityDefImpl.findDefObject() to find the entity definition for the
ProductEO entity.
Create a new instance: Use the createInstance2() method on the entity definition to create a new
instance of the entity object. (The method name really has a 2 at the end. The regular createInstance()
method has protected access and is designed to be customized by developers. The second argument of
AttributeList type is used to
supply attribute values that must be supplied at create time; it is not used to initialize the values of all
attributes found in the list. For example, when creating a new instance of acomposed child entity row
using this API, you must supply the value of a composing parent entity’s foreign key attribute in the
AttributeList object passed as the second argument. Failure to do so results in an
InvalidOwnerException.
Set attribute values: Use the setAttribute() method on the entity object to assign
values for the Name and Description attributes in the new entity row.
Commit the transaction: Call commit() on the current transaction object to commit the
transaction.
Return the trigger-assigned product ID to the caller: Use getAttribute() to retrieve the ProdId attribute
as a DBSequence, and then call getSequenceNumber().longValue() to return the sequence number as a
long value to the caller.

887
.
888
.
889
.
890
.
An ADF view object is composed of the following components:
• View definition XML file: This is the view object descriptor XML file, which holds metadata definitions. The metadata includes the following:
o The SQL SELECT statement used in the view object
o Bind parameter definitions used in the SQL SELECT statement
o Attribute definition describing each column returned by the query—this includes UI-related metadata, such as UI Hints and UI
Categories for attributes
o Entity usage information (if there is entity backup for the view object)
o Metadata definition for list of values (LOV) and view criteria (query)
o View accessor definition for accessing other view objects
o Business rules
• View definition: This is the runtime Java class representation for the view definition XML file. The default view definition class used by the
ADF Business Components' runtime is oracle.jbo.server.ViewDefImpl, which can be extended to provide custom functionalities, if needed.
• View object: This class represents a view object instance. The view object instance manages the query execution at runtime. The default
view object class used by the ADF Business Components' runtime is oracle.jbo. server.ViewObjectImpl. Developers can extend this class to add
custom functionalities, if needed.
• View criteria: View criteria will let you define filter conditions for attributes in a view object, which will be used at runtime to filter the query
result. This implementation takes the form of a query-by-example approach, which allows the end user to supply values for attributes of the
target view object in order to form the desired search condition.
• Bind variables: These are placeholder variables in a SQL statement used in a view object. These variables will be replaced with the valid ones
before executing the query.
• View accessor: This acts as a gateway for a view object to access another view object. This is used in validation and LOV definitions.
A view object uses the following framework components to set up the infrastructure for query execution and managing the result set:
• Row: A row represents an element in the collection that is a result from a query on a view object.
• Row set: View object uses row sets to manage the collection of rows from a query. The framework will create a different row set when the
same view object is used as a mechanism to query the datasource in different contexts. Some of these areas act as query for list of values
implementation and query for child collection in master-child tree structure. Parameterized conditions used for finding the row sets are
maintained at each row set level.
• Row set iterator: This enables the client to traverse the row set and work with individual items. A client can create one or more row set
iterators to enumerate through the rows.
• Query collection: A query collection contains the rows used in a view object. A view object instance may maintain multiple query
collection, depending on the row filter (a data structure holding bind variable values) used by different row sets to execute query. Note
that a row or row set does not store any data within it, rather they use query collection object for storing rows.
• View link: View link connects two view objects, typically used for implementing master-child relationships.

891
.
892
.
893
.
To generate Java classes for a view object, double-click on the view object to display the
overview editor. In the overview editor, go to the Java tab and click on Edit Java Options icon.
In the Select Java Options dialog, select the types of Java classes that you want to generate.
• View object class: This class is customized to add business methods and to override the
default lifecycle of view object instances. For example, to build programmatic a view object,
you must generate a view object class for the desired view object and override the lifecycle
call back methods to hook the custom logic.
• View row class: This class represents a row in the result collection in a view object. If you
want to modify the default read and write operations for specific attributes, this is the class
you need to extend. For example, if you have any transient attributes defined in the view
object whose value is derived from other attributes in the row, you can override the
get<AttributeName> method and add the logic over there.
• View object definition class: This class manages the view definition implementation and
controls view row creations. You may rarely customize this class to override the properties at
runtime. For example, if you want to modify the properties or attributes of a view object at
runtime, you can override the resolveDefObject() method in the oracle.jbo.server.
ViewDefImpl class and add custom logic for altering the definition before returning to the
caller.
• Service data object (SDO) class: This is useful if you want to expose the view object as a web
service abstracting the data of the view object. This is typically used in service-oriented
architecture when you need to expose functionalities of a view object as web service. The
SDO standardizes the way that data structures are passed between Java and XML.

894
.
Generate Java Classes for Adding Code
ADF enables you to customize the behavior of your business components to the requirements
of your application. Although an increasing number of modifications can be accomplished
declaratively, there are cases where you must add code to meet the requirements.
By default, the only files generated for business components are the metadata files in XML. If
you need to add Java code, you can optionally generate Java classes on the Java tab of the
component’s editor as follows:
Click Edit (the pencil icon).
In the Select Java Options dialog box, select the check boxes for the class and methods that you
want to generate.
Click OK to generate the class. Then add to the class the methods that you want to code. Just as
with the XML definition file, JDeveloper keeps the generated code in your Java classes
up to date with any changes you make in the editor.
To delete a Java class that has already been generated, follow the same process, but deselect
those classes that you want to delete. Any code that you may have added to those classes is
lost when you delete the class.

895
.
Support View Object Java Classes
There are three base Java classes that implement view objects:
ViewObjectImpl.java: This is the view object class. All view object classes extend
this class. The ADF Business Components technology uses this class to manage instances of
each view. When you generate the view object class, you can also generate bind variable
accessors (typesafe accessors for the view object’s named bind variables) or custom Java data
source methods.
ViewDefImpl: This is the view definition class. At run time, one view definition is
instantiated for each view. You can add methods to this class that are used by all view object
instances.
ViewRowImpl.java: This is the view row class. When you generate the view row
class, you can also generate:
Accessors: Typesafe accessors for the view row’s attributes
Expose Accessors to the Client: Turns all accessors into client methods
When you choose to generate Java classes for view objects, the classes that are generated
extend the base classes. The classes that you generate use the entity name, followed by
ViewImpl, ViewRowImpl, or ViewDefImpl (such as OrdersViewImpl.java).

896
.
897
.
898
.
899
.
900
.
What happens when a client invokes executeQuery() on a view object instance?
When a client invokes executeQuery() on the view object the following methods defined on the view object are engaged at various stages of
query execution:
• ViewObjectImpl::executeQuery(): This method is invoked when a client calls executeQuery() on the view object. This method
in turn engages the default row set for the view object in the query execution cycle, and delegates the call for further processing.
• ViewObjectImpl::prepareRowSetForQuery(ViewRowSetImpl vrs): This method prepares the row set for query
execution. If you need to assign bind variable values or modify the WHERE clause conditionally, just before executing the query for a
specific row set, then this is the method where you can hook your custom code. This method also gets executed before the count query
methods such as getQueryHitCount()and getCappedQueryHitCount(). The count queries are typically used by UI components such as
tables or tree tables to size their scroll bar.
• ViewObjectImpl::prepareVOForQuery(): This method prepares the view object for build queries. If you need to assign bind
variable values or modify the WHERE clause conditionally, just before executing the query for a view object, then this is the method where
you can hook your custom code. This method is called from prepareRowSetForQuery(). Logically, you will override this method if you want
to alter the query or to set bind variable values at the view object level, which needs to be reflected in all containing row sets.
• ViewObjectImpl::executeQueryForCollection(Object qc, Object[] params, int noUserParams): This
method is invoked right before the row set starts executing the query. If this method is overridden, the custom logic will be applied to all
row sets owned by this view object. In contrast, if the user overrides the view object's executeQuery(), then the custom logic in it applies
only when the user calls executeQuery() on the view object. In other words, if a client calls executeQuery() on secondary row sets, then the
framework will not engage the executeQuery() method during query executions.
• ViewObjectImpl::buildQuery (int noUserParams, boolean forRowCount): This method builds the native SQL
statement. A view object's query statement is normally built from various clauses, such as SELECT, FROM, WHERE, and ORDER BY that you
set for a view object. However, an application can bypass this mechanism either by supplying a user defined query at design time and
selecting an expert mode for the view object or by calling setQuery() on a view object instance at runtime. While generating the query, the
framework also provides database specific interpretation for range paging, view criteria, and effective dated attributes.
• ViewObjectImpl::bindParametersForCollection(QueryCollection qc, Object[] params,
PreparedStatement stm): This method binds parameter values for the SQL statement at runtime. This includes bind parameters
appearing in the query statement as well as the range paging parameters supplied by the framework.
• ViewObjectImpl::setResultSetForCollection(Object qc, ResultSet rs): This method is responsible for storing
results of query execution for further processing. By default, the result set is stored in the corresponding query collection object.
• ViewObjectImpl::hasNextForCollection(Object qc): This method is invoked when a client starts to iterate over the rows
set by calling hasNext() on the row set iterator. This method returns true if there are more rows in the query result.
• ViewObjectImpl::createRowFromResultSet(Object iqc, ResultSet resultSet): This method creates a view row
instance from the query result. The new view rows are created when the client traverses through the result set.
• ViewObjectImpl::releaseUserDataForCollection (Object qc, Object data): This is a callback method which
can be overridden to add some resource cleanup. Runtime invokes this method when the query collection object for the row set is garbage
collected.

901
.
902
.
Examine View Object Methods
Because you can access view objects directly in client code, it may be useful to review the methods that are available for view objects. When you generate the
view object class for a view object, it extends ViewObjectImpl, which indirectly (through the ViewObject interface) implements the RowSet interface. Rowset is an
interface representing a scrollable range of rows, of which one may be designated as the current row. Some of its methods include the following:
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
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

903
.
904
.
905
.
906
.
907
.
908
.
909
.
910
.
911
.
912
.
913
.
Find a Row and Update a Foreign Key Value
This sample code looks up an employee and reassigns the employee to a different department.
It uses the following steps:
Finds the employees view object
Constructs a key to find employee number 101
Finds the row that matches this key
Prints the employee’s name
Prints the current value of the employee’s department
Assigns the employee to a different department
Prints the new value of the employee’s department
Rolls back the transaction Here is the output of this code:
Employee Name: Kochhar
Employee is in department 90 Employee reassigned to department 60 Transaction cancelled

914
.
Traverse Links
Traversing a view link is similar to traversing an association. You use the accessor method in the source
(master) view object to get the RowIterator object that contains all the associated rows in the
destination (detail) view object. You can also traverse a view link from destination (detail) to source
(master).
Similar to the example in the slide, the OrdersViewRowImpl class contains a method to return a single
row containing OrdersView. Using this method, you can determine and manipulate detail information
about the Order to which the current OrderItem belongs.
By default, a view link is a one-way relationship that enables the current row of the source (master) to
access a set of related rows in the destination (detail) view object. This is accomplished because, by
default, an accessor is generated only in the master view object. On the View Link Properties page of
the Create View Link Wizard, you can change the default behavior by generating an accessor in the
detail view object.
At run time, the getAttribute() method on a Row enables you to access by name the value of any
attribute of a row in the view object’s result set. The view link accessor behaves like an additional
attribute in the current row of the source view object, so you can use the same getAttribute() method
to retrieve its value. The only practical difference between a regular view attribute and a view link
accessor attribute is its data type. Whereas a regular view attribute typically has a scalar data type with
a value such as 303 or ahunold, the value of a view link accessor attribute is a row set of zero or more
correlated detail rows. Assuming that curOrder is a Row from some instance of the Orders view object,
you can write a line of code to retrieve the detail row set of order items:
RowSet lineItems = (RowSet)curOrder.getAttribute(“LineItems");
The RowSet is closed when you iterate and retrieve the last row from it. If you stop the iteration before
retrieving the last row, you can programmatically close the RowSet if you want to release all the rows it
contains. You can do this using the closeRowSet() API.
Note: If you generate the custom Java class for your view row, the type of the view link accessor will be
RowIterator. At run time, the return value will always be a RowSet, so it is safe to cast the view link
attribute value to a RowSet.

915
.
Iterate Master-Detail Hierarchy
The sample code, placed in a test client, iterates over all departments and their associated
employees in a master-detail hierarchy. The beginning of the code sets up standard test client
code, which you learn to do shortly. The remaining code performs the following actions:
Finds the DepartmentsView1 view object
Executes the view object query
Iterates over the resulting rows
Prints out the department name
Gets the related RowSet of employees by using the view link accessor
Iterates over the employees rows
Prints out the last name of each employee
The beginning of the resulting output looks like this:
Department 10
Employee Name: Whalen Department 20
Employee Name: Hartstein
Employee Name: Fay

916
.
Programmatically Retain and Reuse a View Link Accessor Row Set
In the lesson titled “Declaratively Customizing Data Services,” you learned how to declaratively
retain and reuse a view link accessor row set and why it may be advisable to do so. It is also
possible to perform this caching of the row set programmatically.
To use the view link accessor retention feature, perform the following steps:
Generate a Java class for your view object.
In that Java class, override the create() method. (The optional @Override annotation
tells the compiler that a superclass method is being overridden; if not done correctly, a compile
error occurs.)
Add a line after super.create() that calls the
setViewLinkAccessorRetained() method , passing true as the parameter
Because this is a method of the view definition class ViewDefImpl, this affects all view link
accessor attributes for that view object. When this feature is enabled for a view object,
because the view link accessor row set is not re-created each time, the current row of its
default row set iterator is also retained as a side effect.
Because of this, before calling code that iterates through the row set, your code needs to
explicitly call the reset() method on the row set that you retrieve from the view link accessor.
This resets the current row in its default row set iterator back to just before the first row.

917
.
Creating a New Row
To create a new employee, you perform the following steps:
Find the employees view object.
Create a new row and insert it into the row set.
Set the value of some required attributes in the row.
Commit the transaction.
Display a message. The output is:
Added employee 999 to Department 60
You can view the table by browsing it from the Navigator to see that the record was added.

918
.
919
.
920
.
921
.
922
.
923
.
924
.
Architecture of view criteria
A view criteria can include multiple view criteria or view criteria rows linked by various criteria
conjunction types such as AND, OR, and UNION. Each view criteria row can optionally include
multiple view criteria items.

The query execution mode that you set for the view criteria decides the source to read rows:
• Database: In this mode view criteria is used for database query. This is the default mode. You
can use the ViewCriteria.CRITERIA_MODE_QUERY constant to refer this mode
programmatically.
• In-memory: In this mode, view criteria is used for in-memory filtering. You can use the
ViewCriteria.CRITERIA_MODE_CACHE constant to refer this mode programmatically.
• Both (database and in-memory): In this mode, view criteria is used for a database query
first and then for in-memory row filtering. You can combine the
ViewCriteria.CRITERIA_MODE_QUERY and ViewCriteria.CRITERIA_ MODE_CACHE constants
in order to refer this mode programmatically:
ViewCriteria.CRITERIA_MODE_QUERY | ViewCriteria.CRITERIA_MODE_ CACHE

View criteria with in-memory execution mode supports all the SQL operators discussed under
RowMatch.

925
.
926
.
927
.
928
.
Change View Object WHERE or ORDER BY Clause at Run Time
You can change the WHERE and ORDER BY clauses of a query at run time by calling setWhereClause() or
setOrderByClause() on the view object. Although setWhereClause() is the easiest way to change a view
object’s query, it often is not the most efficient. If you can, you should use parameterized WHERE
clauses or structured WHERE clauses.
To change the WHERE clause of a query at run time, perform the following steps:
Create a String containing the new WHERE clause. Do not include the word WHERE. If
you want to remove the WHERE clause entirely, use null. For example, either of the
following could be appropriate definitions:
String whereClause = "ORDER_TOTAL > 500";
String whereClause = null;
Pass this string into setWhereClause(). For example, if OrdVO is a variable
containing the view object instance to be changed, you would call:
ordVO.setWhereClause(whereClause);
If there is an existing design-time WHERE clause, using setWhereClause() adds to it,
further restricting the query results.
To change the ORDER BY clause of a query at run time, perform the following steps:
Create a String containing the new ORDER BY clause. Do not include the words ORDER
BY. If you want to remove the ORDER BY clause entirely, use null. For example, either
of the following could be appropriate definitions:
String orderByClause = "ORDER_TOTAL";
String orderByClause = null;
Pass this string into setOrderByClause(). For example, if OrdVO is a variable
containing the view object instance to be changed, you would call:
ordVO.setOrderByClause(orderByClause);

929
.
930
.
Ingredients of an application module
An application module comprises of the following components:
• Application module XML metadata file: This is the application module descriptor file
holding metadata definitions. The metadata includes exposed business methods and data
models for use, by clients, such as view objects and associated view criteria, master-child
view, objects connected through view links, and nested application modules.
• Application module definition: This is the runtime Java class representation of the
application module XML metadata file. The default base class for storing the application
module definition is oracle.jbo.server. ApplicationModuleDefImpl which can be extended to
add custom functionalities if needed. This class stores the runtime metadata for application
modules read from the corresponding XML file.
• Application module implementation: This class represents an application module instance
generated by runtime to serve a request from the client. The default base class used for
representing an application module instance is oracle.jbo.server.ApplicationModuleImpl. You
will subclass this class to define the custom business logic that must execute in the
application's middle tier.
• bc4j.xcfg: This file contains metadata for all the application modules present in the
same Java package for a project. This file is located in the Common subdirectory relative to
the path where the application module's XML component definition is located. An
application module's runtime behaviour is controlled by the configuration properties present
in this file. The properties stored in this file include the JDBC data source name, application
module pooling configurations, database specific configurations, locking mode, and so on.

931
.
932
.
933
.
934
.
935
.
936
.
Generate Java Classes for Adding Code
ADF enables you to customize the behavior of your business components to the requirements
of your application. Although an increasing number of modifications can be accomplished
declaratively, there are cases where you must add code to meet the requirements.
By default, the only files generated for business components are the metadata files in XML. If
you need to add Java code, you can optionally generate Java classes on the Java tab of the
component’s editor as follows:
Click Edit (the pencil icon).
In the Select Java Options dialog box, select the check boxes for the class and methods that you
want to generate.
Click OK to generate the class. Then add to the class the methods that you want to code. Just as
with the XML definition file, JDeveloper keeps the generated code in your Java classes
up to date with any changes you make in the editor.
To delete a Java class that has already been generated, follow the same process, but deselect
those classes that you want to delete. Any code that you may have added to those classes is
lost when you delete the class.

937
.
Application Module Files
Four main files control the behavior of the application module.
<AppMod>.xml: The metadata file that contains all the definitions for every object
included in the module. It includes all the attribute definitions needed during design time for all
the view objects and view links in the module. This is the file that you edit declaratively when
editing the application module.
bc4j.xcfg: Contains all the configuration information including the JDeveloper
connection details. This file is used by the BC Tester while running the module. You edit this file
declaratively by using project properties (Business Components) to edit connection details, and
by right-clicking the application module and selecting Configurations to edit configuration
details.
<AppMod>Impl.java: Contains all the methods and behaviors for the application
module for which you have defined code. You need to generate this file only if you have to
programmatically modify the behavior of the application module.
<AppMod>Def.java: The application module definition class. At run time, one
application module definition is instantiated for each application module. You can add methods
to this class that are used by all instances, but this file is not used as often as
<AppMod>Impl.java.

938
.
939
.
Add Service Methods to an Application Module
Service methods are methods that are specific to an application module. These methods may
be independent of any view in the application. For example, you may need a method that
determines the number of current orders for a specific item in inventory. That method can be
used from any client without needing to instantiate an inventory or order view.
You can also add code that affects the behavior of a particular view object in the application
module; for example, you can change the WHERE or ORDER BY clause of a view object. You
would do this if you were reusing a view object in multiple application modules and wanted the
view object to behave differently in different application modules.

940
.
Code the Service Method
Add the Java code for the custom method to the <name>AMImpl.java file. The example in the
slide shows a retrievePersonById() method in the
PersonAMImpl.java class for the PersonAM application module. It uses the
getDefinitionObject() method of the PersonEOImpl entity object class to access its
related entity definition, uses the createPrimaryKey() method on the entity object class to
create an appropriate Key object to look up the person, and then uses the findByPrimaryKey()
method on the entity definition to find the entity row in the entity cache. It returns the
LastName attribute of the PersonEOImpl object.

941
.
Publish the Service Method
When you add a public custom method to your application module class, if you want clients to
be able to invoke it, you need to include the method on the application module’s client
interface. To do this, perform the following steps:
Click the Java finger tab in the Application Module Editor.
Click the Edit application module client interface icon (the Pencil icon).
Shuttle the method you want to publish from the Available pane to the Selected pane, and then
click OK.
JDeveloper creates a Java interface with the same name as the application module in the
common subpackage of the package where your application module resides. The interface
extends the base ApplicationModule interface in the oracle.jbo package, reflecting that a client
can access all the functionality that your application module inherits from the
ApplicationModuleImpl class. The interface created by the example in the slide includes the
retrievePersonById() method that was added to the client interface of the application module.
Each time a method is added to or removed from the Selected list in the Edit Client Interface
dialog box, the corresponding service interface page is updated automatically
JDeveloper also generates a client proxy class that is used when you deploy your application
module for access by a remote client. All the generated files are displayed in the Navigator
under the application module’s node.
Note: If your method does not appear in the Available list in the Edit Client Interface dialog box,
it may be that it contravenes one or more of the rules for inclusion. Only public methods with
parameter and return types that are primitives or that implement the Serializable interface are
included in the list.

942
.
Test Service Methods in the Business Components Browser
You can use the Business Components Browser to test service methods. Double-click the
application module in the tree at the left to show it. Select the method to test from the
Method drop-down list, and supply values for any required parameters. When you click
Execute, the results, including a return value if any, are displayed in the lower part of the
window.

943
.
944
.
945
.
946
.
Access Transaction
You access an application module’s transaction context through the Transaction and
DBTransaction interfaces. You can access the methods in these interfaces through the
getTransaction() and getDBTransaction() methods in the ApplicationModuleImpl class.
Some useful methods of the Transaction interface with regard to application modules are:
commit: Commits the transaction, and saves all the changes to the database. If the
database connection is established, the transaction is implicitly started.
connect: Attempts to establish a connection to the given database URL
disconnect: Disconnects the server from the database
getLockingMode: Gets the preferred locking mode for this transaction. In ADF BC, the
locking mode defaults to LOCK_PESSIMISTIC; however, Oracle Fusion applications use
optimistic locking by default.
rollback: Rolls back the transaction, and discards all the changes
setLockingMode: Sets the preferred locking mode for this transaction. Changing the
locking mode affects only the subsequent locks that are placed.
The Transaction interface contains a standard set of methods that include commit(),
setLockingMode(), and getLockingMode(). The DBTransaction interface extends Transaction. It
contains some more specialized methods that deal with entity objects. Some of the methods
are findByPrimaryKey(), getSession(), and getEnvironment(). For the most part, the Transaction
interface provides the methods you will use most often.
JDeveloper’s online Help contains the Javadoc for oracle.jbo.Transaction and
oracle.jbo.server.DBTransaction. Refer to the Javadoc for a complete list of available methods.

947
.
948
.
949
.
950
.
Customize the Post Phase
You can customize the behavior of the post operation by overriding EntityImpl.postChanges(),
which is the method that is used, by default, to perform the post operation. The slide shows an
example of this, with code that intercepts a delete action and only marks the deleted rows as
deleted, without actually removing them from the table. You could use this technique if you
want to preserve history of deleted rows.
The code in the example calls getPostState() to determine the entity’s post state. The post state
is the state of the entity object’s data relative to the transaction’s corresponding database data.
The Entity interface contains a number of constants that define the possible values for an
entity’s post state. The post state is set to STATUS_UNMODIFIED when the data is posted to the
database.

951
.
Customize the Commit Phase
The TransactionListener interface defines beforeCommit() and afterCommit() methods. You can
implement a transaction listener and add it to the transactions list of event listeners by calling
the transaction’s addTransactionListener() method. For example, in an entity object’s code, call:
getTransaction().addTransactionListener(myTransListener);
Your entity objects are also transaction listeners, and are already on your transaction’s list of
event listeners. Because of this, you can also override an entity object’s beforeCommit() and
afterCommit() methods. The simple example in the slide shows adding a printed notification
that a record has been committed; however, you could perform any action, such as notifying an
employee’s manager by email that information about an employee has been updated.
Customize Rollback
The procedure for Customize rollback behavior is similar to the procedure for customizing
commit behavior. The TransactionListener interface also defines beforeRollback() and
afterRollback() methods that are called before and after a rollback operation.

952
.
953
.
954
.
955
.
956
.
957
.
If you want to test custom code, you can create a test client program. Create a Java class by
using the Create Java Class Wizard that you invoke from the New Gallery under the General
category.
Enter a class name and a package.
In Optional Attributes, deselect the “Constructors from Superclass” and Implement Abstract
Methods check boxes.
Select the Main Method check box.
Click OK to create the class.
The file opens in the editor to show you the skeleton code:
Place the cursor on a blank line inside the body of the main() method and use the bc4jclient
code template to create the few lines of necessary code. To use this predefined code template,
enter the characters bc4jclient, and then press Ctrl + Enter to expand the code template.
Adjust the values of the amDef and config variables to reflect the names of the
application module definition and the configuration that you want to use, respectively, such as
module.FODCategoryAM and FODCategoryAMLocal.
Finally, change the view object instance name in the call to findViewObject() to be the one you
want to work with. Specify the name exactly as it appears in the Data Model tree on the Data
Model panel of the Application Module editor, such as CategoryVO1.

958
.
959
.
960
.
961
.
962
.
963
.
964
.
In Hands-on lab one would practice:
1. Creating a Business Service Deployment Profile
2. Creating a Web Module Deployment Profile
3. Creating an Application Deployment Profile
4. Starting Integrated Weblogic Server
5. Deploying the Application from Jdeveloper
6. Running the Application
7. Undeploying the Application

965
.
966
.
967
.
968
.
969
.
970
.
971
.
972
.
973
.
974
.
975
.
976
.
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 the 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 the user customization.

977
.
978
.
979
.
980
.
981
.
982
.
983
.
984
.
985
.
986
.
987
.
988
.
989
.
990
.
991
.
992
.
993
.
994
.
995
.
996
.
997
.
998
.
999
.
1000
.
1001
.
1002
.
1003
.
In Hands-on lab, optionally you may practice:
1. Configuring the Application to use ADF Security
2. Defining Users in the Identity Store
3. Defining Application Roles
4. Implementing Security on Task Flows and Pages
5. Testing Application Authentication and Authorization

1004
.
1005
.
1006
.
web.xml
This file can be found in the public_html/WEB-INF folder. web.xml is the deployment descriptor for the entire application. The changes that
are made as part of enabling security are:
• The initialization parameter remove.anonymous.role is set to false for the JpsFilter filter as this filter is the first filter defined in the
file.
• Filter mapping for adfBindings along with adfAuthentication is added. This is added for the authentication servlet.
• The servlet and the servlet mapping are added for adfAuthentication.
• The security constraint is added for the authentication servlet so that when the framework invokes it, authentication gets triggered.
weblogic.xml
This file is used as the deployment descriptor for the web application deployed in the WebLogic server. The security role is assigned in the
weblogic.xml file, which is located in the same folder as that of the web.xml file, using the following code:
<security-role-assignment>
<role-name>valid-users</role-name>
<principal-name>users</principal-name>
</security-role-assignment>
adf-config.xml
The runtime configurations for the ADF web application are added to this file. The metadata for the UI page is configured using adf-config.xml.
The JaasSecurityContext element is added for the file located in the .adf/META-INF folder. The authorizationEnforce and
authenticationRequire options will be set to true for the property using the following code:
<sec:JaasSecurityContext
initialContextFactoryClass="oracle.adf.share.security.JAASInitialContextFactory“
jaasProviderClass="oracle.adf.share.security.providers.jps.JpsSecurity
Context"authorizationEnforce="true" authenticationRequire="true"/>
jps-config.xml
This file is located in the src/META-INF folder. The security service is provided and the service instances are defined in this file. Oracle Platform
Security Services (OPSS) are defined for different security stores. Credential Store Service Provider, Login Module
Service Provider, XML-based IdStore Provider, XML-based PolicyStore Provider, and Anonymous Service
Provider are the service providers added to the file. Different login modules are added. The equivalent file in the WebLogic server is used
for security.
jazn-data.xml
This file is primarily a policy store. The default security realm is added to this file in the same folder. The security realm is determined by the
file in the WebLogic server domain using the following code:
<jazn-realm default="jazn.com">
<realm>
<name>jazn.com</name>
</realm>
</jazn-realm>

1007
.
1008
.
1009
.
1010
.
1011
.
Lesson Agenda
As an application is being built, it is advisable to test it whenever a functionality is added, so
that errors are caught as early as possible. This makes problems easier to diagnose and correct.
This lesson discusses ways to track down application problems and create test cases to improve
software quality. It discusses tools to help you troubleshoot Fusion applications, including
FileMon, JUnit, ADF Logger, ADF Diagnostics, and the JDeveloper Debugger. You also learn how
to obtain assistance with JDeveloper and application problems.

In Hands-on lab one would practice:


1. Copying Solution
2. Discovering Application Problems
3. Setting Breakpoints in the Debugger
4. Running Application Module in Debug Mode

1012
.
Troubleshoot the Business Service
You have already learned about two ways to test business services without the need to define a user interface:
Business Components Browser (see the lessons titled “Building a Business Model with ADF Business Components” and
“Querying and Persisting Data”). If you want to troubleshoot problems with Java code in your model, you can set breakpoints
in the code, and then run the BC Browser in debug mode as follows: In the Structure window, right- click the application
module’s <AppModuleName>Impl.java file (for example, EmpModuleImpl.java), and select Debug from the context menu.
Java test client (see the lesson titled “Programmatically Customizing Data Services”) This lesson discusses various other
methods that you can use to diagnose problems with the
business service model.
Test Java Code with JUnit
JUnit is an open source regression-testing framework for Java (see http://www.junit.org). JUnit is more of a testing tool than a
troubleshooting tool, but if you are developing an application of any complexity, it could be useful to create a suite of JUnit
tests to quickly verify your Java code. For example, you could write a JUnit test for each ADF BC view object to instantiate the
view object and execute its query.
JDeveloper provides two JUnit extensions: JUnit integration and JUnit integration for business components. You can install
these extensions by selecting Tools > Preferences > Extensions > “Check for Updates.”
Unit Test with JUnit
Testing code as it is being developed, before it goes to QA, can improve code quality and drastically reduce maintenance and
debug time.
A unit test:
Is highly localized
Is designed to test code only within a single package
Does not test interactions between packages (functional testing does that)
JUnit is the most popular framework for unit testing, enabling developers to write and run repeatable tests. Its features
include:
Assertions to test expected results
Fixtures for sharing test data
Test suites that organize and run tests
Graphical and textual test runners
JUnit works by performing many small tests, reporting success or failure of each; it is not intended to report multiple failures
per test. Improving the testability of code usually results in better design.
JUnit enables you to automate tests for repeatability and to collect tests into suites for regression testing.

1013
.
Test Java Code with JUnit
JUnit is an open source regression-testing framework for Java (see http://www.junit.org). JUnit
is more of a testing tool than a troubleshooting tool, but if you are developing an application of
any complexity, it could be useful to create a suite of JUnit tests to quickly verify your Java
code. For example, you could write a JUnit test for each ADF BC view object to instantiate the
view object and execute its query.
JDeveloper provides two JUnit extensions: JUnit integration and JUnit integration for business
components. You can install these extensions by selecting Tools > Preferences > Extensions >
“Check for Updates.”

1014
.
Unit Test with JUnit
Testing code as it is being developed, before it goes to QA, can improve code quality and
drastically reduce maintenance and debug time.
A unit test:
Is highly localized
Is designed to test code only within a single package
Does not test interactions between packages (functional testing does that)
JUnit is the most popular framework for unit testing, enabling developers to write and run
repeatable tests. Its features include:
Assertions to test expected results
Fixtures for sharing test data
Test suites that organize and run tests
Graphical and textual test runners
JUnit works by performing many small tests, reporting success or failure of each; it is not
intended to report multiple failures per test. Improving the testability of code usually results in
better design.
JUnit enables you to automate tests for repeatability and to collect tests into suites for
regression testing.

1015
.
Troubleshoot the UI
Some of the methods that you learn in this lesson are also useful for troubleshooting problems
with the user interface

1016
.
1017
.
Use Design-Time Code Validation
In addition to providing features such as code insight, JDeveloper’s source editor provides code
validation, error cues, and correction suggestions. The following slides discuss how this works
with Java, XML, and JSPX files.

Design-Time XML Validation


All XML documents that have a schema (XSD) or a document type definition (DTD) registered
with JDeveloper (such as page definition files, .cpx files, page definition files, faces
configuration files, web.xml, and so on) provide validation, as well as code insight, and
adherence to audit rules.
When you create Web pages and work with the ADF data controls to create the ADF binding
definitions in JDeveloper, the Oracle ADF declarative files that you edit must conform to the
XML schema defined by Oracle ADF. When an XML syntax error occurs, the JDeveloper XML
compiler immediately displays the error in the Structure window. You can double-click the error
to open the file in the XML editor.

Design-Time JSPX Validation


JSPX source and design time both flag errors as well as deprecated components, and perform
other validations specific to JSPX and JSF.

1018
.
1019
.
Use Logging and Diagnostics
Java and Oracle provide logging frameworks:
The Java logging framework, introduced in JDK 1.4, provides extensive logging APIs through the
java.util.logging package. You can find an overview of the java.util.logging package at
http://java.sun.com/j2se/1.4.2/docs/api/overview- Lesson Summary.html. For an overview of
the Java logging framework, visit
http://java.sun.com/j2se/1.4.2/docs/guide/util/logging/overview.html.
Oracle’s logging framework complements the standard Java framework to automatically
integrate log data with Oracle log analysis tools. In the ODL framework, log files are formatted
in XML, enabling them to be more easily parsed and reused. The ODL framework provides
support for managing log files, including log file rotation. The maximum log file size and the
maximum size of log directories can also be defined.

1020
.
Use ADF Logging
Oracle Diagnostic Logging (ODL) enables the automatic capture of context information for
meaningful analysis. You have control over which messages are logged, through logging level
and module filter.
By using ODL, ADF Logging messages are handled in the same way as all logging messages in
the application server—they are output in a common format, and loaded into a common
repository where they can be viewed as a single stream or analyzed in different ways.
ADF Faces leverages the Java Logging API (java.util.logging.Logger) to provide logging
functionality.

1021
.
Java Logging
The logging API is part of the Java Platform, Standard Edition (Java SE) in JDK 1.4 and later versions, and
the java.util.logging package is shipped with the JDK. It is designed to enable a Java program to produce
messages of interest to end users, system administrators, and software developers. It is useful in
production environments where you cannot run the debugger, or where running the debugger might
hide the problem. For example, timing-related problems often cannot be reproduced when running in
the debugger.
The primary class in the logging facility is Logger. A Logger represents a sort of channel through which
logging messages can be sent. Usually each class has its own Logger.
A Logger is configured with a Level. This is a class that indicates the severity of the problem being
reported or the level of detail required for that individual class, or both. The predefined levels are as
follows:
SEVERE: Extremely important messages such as fatal errors
WARNING: Warning messages
INFO: Informational run-time messages
CONFIG: Informational messages about configuration settings
FINE: Used for greater detail when diagnosing problems
FINER: Even greater detail
FINEST: Greatest detail
There are two other values: ALL (log all messages) and NONE (no messages).
A LogRecord is an object that represents a message that should be written to a log. It contains a variety
of information, including the message to be printed, the name of the Logger to which it was originally
sent, the Level and creation time and date of the message being sent, and the thread ID of the caller.
In ADF, Java logging is particularly useful for tracing Expression Language (EL) evaluation in Faces,
although the JDeveloper Debugger has been enhanced to enable you to evaluate EL expressions.

1022
.
Configure ADF Logging
Oracle WebLogic Server (WLS) uses logging.xml to configure the ODL loggers globally. You can access
the overview editor for Oracle Diagnostic Logging Configuration from the
Application Server Navigator or from the Log window. The slide shows the Actions menu in the
Log window.
There are several ADF loggers that you can configure in the ODL configuration file.
A logging level is a threshold set by the system administrator to control the logging of messages. The
logging can be set to any one of the following seven severities for each logger individually:
Failure reporting:
SEVERE: Highest level of severity to catch any unexpected errors during normal
execution
WARNING: For internal errors or exceptions for which the user was not notified
Progress reporting:
INFO: Key flow steps
CONFIG: Configuration properties and environment settings
FINE: High-level logging message (This is the level that Oracle recommends.)
FINER: Entry or exit from a routine
FINEST: Low-level logging messages giving maximum detail
After a level is set, only messages that have a severity greater than or equal to the defined level will be
logged. For example, setting the level to WARNING means that logging occurs for WARNING and SEVERE
messages. Setting the level to the lowest severity, FINEST, means that messages of all seven severities
are logged.
A module filter is an optional comma-delimited list of non-case-sensitive strings. You can define a filter,
so only messages that match the filter criteria get logged. Use of a wildcard (%) is supported—for
example, MODULE=store%, jtf%.

1023
.
ODL Configuration Overview Editor
You configure logging levels or view existing log settings in the ODL Configuration Overview
Editor.
To configure log levels, perform the following steps:
In the overview editor, click the Overview tab, and then select ODL Log Levels or Java Log Levels
for the logger types that you want to view.
If you want to see only persistent loggers, select Hide Transient Loggers.
To add a logger:
If the server is running, click the Add icon drop-down menu, and select Add Persistent
Logger or Add Transient Logger. If the server is not running, click Add to add a persistent
logger. You cannot add a transient logger.
In the Add Logger dialog box, enter a logger name.
Select the logging level.
Click OK.
For any logger, including a newly created logger, you can specify its handlers by selecting from a
list of available handlers by clicking the Add icon in the Handler Declarations section.

1024
.
Create Log Configurations in JDeveloper
To create an Oracle ADF Model debugging configuration, perform the following steps:
In the Application Navigator, double-click the user interface project.
In the Project Properties dialog box, click Run/Debug/Profile and create a new run
configuration, for example, named ADF Debugging.
Double-click the new run configuration to edit the properties.
In the Edit Run Configuration dialog box, for Launch Settings, enter the following Java options
for the default virtual machine:
-Djbo.debugoutput=adflogger -Djbo.adflogger.level=FINE
Oracle recommends level=FINE for detailed diagnostic messages.
On the Run menu, select the new configuration as the active run configuration (Run > Choose
Active Run Configuration).

1025
.
View ODL Logs
From the main menu, select Tools > Oracle Diagnostic Log Analyzer.
In the editor for Oracle Diagnostic Log Analyzer, navigate to the log file or enter the path and
name of the log file.
From the drop-down list, select ODL Log Level or Java Log Level.
Select the corresponding check box for each type of log entry you want to view. You must select
at least one type.
The available ODL log level types are Incident Error, Error, Warning, Notification, Trace, and
Unknown.
The available Java log level types are Severe, Warning, Info, Config, Fine, Finer, Finest, and
Unknown.
Specify a time period for the entries you want to view. You can select the most recent period or
a range.
To filter the results, use the query panel to search on a text pattern. For additional query
panels, click Add.
To initiate the filters and display the log messages, click Search.
To order the results by the message ID, select the Group by Id check box.
To group the messages by time period or by request, in the Related column, select either
Related by Time or Related by Request.
To show or hide columns for display, select from the Column drop-down list.

1026
.
1027
.
Use the JDeveloper Debugger
JDeveloper’s integrated debugger is very useful for finding and fixing problems in your code. The following are
some key places to set breakpoints:
Source breakpoint in the doIt() method of the JUCtrlActionBinding class (oracle.jbo.uicli.binding package): This is
the method that executes when any ADF action binding is invoked, and you can step into the logic and look at
parameters if relevant.
Method breakpoints in:
oracle.jbo.server.ViewObjectImpl.executeQueryForCollection method: This is the method that is called when a
view object executes its SQL query.
oracle.jbo.server.ViewRowImpl.setAttributeInternal method: This is the method that is called when any view row
attribute is set.
oracle.jbo.server.EntityImpl.setAttributeInternal method: This is the method that is called when any entity object
attribute is set.
ADF Structure Window and ADF Data Window
The ADF Declarative Debugger provides standard debugging features such as the ability to examine variable and
stack data. When an application pauses at any breakpoint (ADF Declarative or Java code breakpoint), you can
examine the application status using a variety of windows:
You can check where the break occurs in the Breakpoint window.
You can check the call stack for the current thread using the Stack window. When you select a line in the Stack
window, information in the Data window, Watches window, and all Inspector windows is updated to show
relevant data.
You can use the Data window to display information about arguments, local variables, and static fields in your
application.
The ADF Structure window displays the run-time structure of the project. The ADF Data window automatically
changes its display information based on the selection in the ADF Structure window. For example, if a task flow
node is selected, the ADF Data window displays the relevant debugging information for task flows.
Use Quick Javadoc
After you have added the ADF Source library to your project, you instantly have access to the helpful Quick
Javadoc feature that the JDeveloper code editor makes available. You can right-click a class or method, or press
Ctrl + D, to invoke it. This not only helps when writing code, but also when debugging it.

1028
.
Understand Breakpoint Types
There are several different types of breakpoints, each with different uses:
Exception: An exception of this class (or a subclass) is thrown. This is useful when you do not know where the exception
occurs, but you know what kind of exception it is, such as a java.lang.NullPointerException. The check box options enable you
to control whether to break on caught or uncaught exceptions of this class. The Browse button helps you find the fully qualified
class name of the exception. The Exception Class combo box remembers the most recently used exception breakpoint classes.
Note that this is the default breakpoint type when you create a breakpoint in the breakpoints window.
Source: A particular source line in a particular class in a particular package is run. You can create a source breakpoint in the
New Breakpoint window, but it is usually easier to create it by clicking in the breakpoint margin in the editor at the left of the
line you want to break on.
Method: A method in a given class is invoked. This is handy to set breakpoints on a particular method that you might have
seen in the call stack while debugging a problem. Of course, if you have the source, you can set a source breakpoint wherever
you want in that class, but this kind of breakpoint enables you to stop in the debugger even when you do not have a source for
a class.
Class: Any method in a given class is invoked. This can be handy when you might only know the class involved in the problem,
but not the exact method you want to stop on. Again, this kind of breakpoint does not require source. The Browse button
helps you quickly find the fully qualified class name you want to break on.
Watchpoint: A given field is accessed or modified. This can be helpful to find a problem if the code inside a class modifies a
member field directly from several different places (instead of going through setter or getter methods each time). You can stop
the debugger in its tracks when any field is modified. You can create a breakpoint of this type by using the Toggle Watchpoint
menu item on the shortcut menu when pointing at a member field in the source of the class.
To see the Debugger Breakpoints window, use the View > Breakpoints menu choice from the main JDeveloper menu, or
optionally the key accelerator for this: Ctrl + Shift + R. You can create a new breakpoint by selecting Add Breakpoint from the
context menu anywhere in the Breakpoints window or by clicking the plus sign on the Breakpoints toolbar.
ADF Framework Debugging
You use the ADF Declarative Debugger in JDeveloper to set breakpoints on ADF task flow activities, page definition
executables, and method, action, and value bindings. Instead of needing to know all the internal constructs of the ADF code,
such as method names and class names, you can set breakpoints at the highest level of object abstraction.
You can set or remove such breakpoints by right-clicking task flow activities or bindings and selecting Toggle Breakpoint; you
can also set or remove breakpoints on executables or bindings by clicking the margin in the binding editor.
For example, when you set a breakpoint on the Choose Action router activity in the CheckoutFlow, a red dot icon appears on
the activity, as shown in the slide. When the breakpoint is reached, the application pauses and the icon changes, as shown.
After the application pauses at the breakpoint, you can view the run-time structure of the objects as a tree in the ADF Structure
window, as shown in the slide. The ADF Data window displays a list of data for a given object selected in the ADF Structure
window.

1029
.
Use Breakpoints
You can use breakpoints for more than just stopping code execution. JDeveloper supports
advanced breakpoint actions and conditions for fine-tuning when a breakpoint is triggered and
what action happens. Virtually any Boolean expression can be a breakpoint condition, and it
can be applied to all threads, or a specific set of named threads.
The first of the conditional breakpoint examples in the slide breaks only when the variable
value is a Date type. The second breaks only when the status is “shipped.” The third breaks only
when the variable i is greater than 50. The third example (i>50) is particularly useful if you have
a breakpoint inside a loop (with i as the loop variable) but you know your problem occurs only
when the loop has executed a number of times.
For actions, breakpoints typically just break into the code. However, you can beep, log a
message or an expression result to the log console, dump the stack, or enable or disable a
group of breakpoints.

1030
.
Object Preferences
An excellent but often overlooked feature of the JDeveloper Debugger is the ability to filter for
the members that you want to see in the debugger window for any class. In the debugger’s
Data window, pointing at any item and selecting Object Preferences from the context menu
opens a dialog box that enables you to customize which members appear in the debugger and
(more importantly sometimes) which members do not appear. These preferences are set by
class type and can really simplify the amount of scrolling you need to do in the debugger Data
window. This is especially useful while debugging when you might be interested only in a few
members of a class.
Displaying fewer fields narrows your focus when debugging and may make it easier to locate
and isolate potential problems in your program. For example, you can create filters for classes
in the Data windows so that the debugger displays only the fields of interest to you. This
drastically reduces clutter and allows you to find the relevant data more quickly.

1031
.
Use the EL Evaluator
When you debug and reach a breakpoint, you can use the EL Evaluator to examine the value of
an EL expression. The EL Evaluator appears as a tab in the debugger window area; you can
select View > Debugger > EL Evaluator if it is not visible.
Enter an EL expression in the input field. When you enter #{ in the field, a discovery function
helps you to select the correct expression to evaluate, and auto-completion also facilitates
expression entry. You can evaluate several EL expressions at the same time by separating them
with semicolons. After you have entered the expression or expressions, click Evaluate. If the EL
expression no longer applies within the current context, the expression evaluates to null.
The EL Evaluator is different from the Watches window in that EL evaluation occurs only when
stopped at a breakpoint, not when stopped at subsequent debugging steps.

1032
.
Use Oracle ADF Source Code for Debugging
Adding Oracle ADF source code to your application debugging session will:
Provide access to the JDeveloper Quick Javadocs feature in the code editor. Without the source
code, you will have only standard Javadocs.
Enhance the use of breakpoints by showing the Oracle source code that is being executed when
the breakpoint is encountered. You can also set breakpoints more easily by clicking the margin
in the source code line you want to break on. Without the source code, you will have to know
the class, method, or line number in order to set a breakpoint within Oracle code.
Allow you to see the values of all local variables and member fields in the debugger.
If you have valid Oracle ADF support, you can obtain the complete source code for Oracle ADF
by opening a service request with Oracle Worldwide Support. You can request a specific version
of the Oracle ADF source code

1033
.
Set Up Oracle ADF Source Code for Debugging
After you receive or download the source file archive, extract it to a working directory. You
create libraries of the source code Jave Archive (JAR) files in this directory, and then add the
libraries to your JDeveloper projects.
To add the ADF source zip file into the user library, perform the following steps:
Select Tools > Manage Libraries to display the Manage Libraries dialog box.
With the Libraries tab selected, click New.
In the Create Library window, enter a library name for the source that identifies the type of
library and select the Source Path node in the tree structure. Do not enter a value for the Class
Path. Click Add Entry.
In the Select Path Entry window, browse to the source file directory and select the source zip
file. Click Select.
In the Create Library window, verify that the Source Path entry has the correct path to the
source zip file, and deselect the “Deployed by Default” check box. Click OK.
Click OK to close the Manage Libraries dialog box.
After the source library has been added to the list of available libraries, add it to the project you
want to debug, as you would add any library.

1034
.
Set Breakpoints in Source Code
After adding the source code to your project, you can debug any Oracle ADF code for the
current project in the same way as you have been doing for your own Java code. This means
that you can press Ctrl + – (the minus sign) to open a “Go to Java Class” dialog box, in which
you can enter any class name in Oracle ADF. When you select the class and click OK, JDeveloper
opens the source file automatically, so you can set breakpoints as desired.
Hint: In the “Go to Java Class” dialog box, you can enter just the uppercase letters from a class
name. For example, to find JUMethodIteratorDef, you can enter JUMI and the class is located.

1035
.
Use Common Oracle ADF Breakpoints
If you loaded Oracle ADF source code, you can use additional breakpoints to debug your
application. By looking at the stack window when you hit these breakpoints and stepping
through the source, you can get a better idea of what is going on. These breakpoints are useful
for debugging declarative functionality. Commonly used ADF breakpoints include:
oracle.jbo.JboException: Exception breakpoint that is the base class of all ADF BC run-time
exceptions
oracle.jbo.DMLException: Exception breakpoint that is the base class forexceptions originating
from the database
doIt(): Method exception from the class
oracle.jbo.uicli.binding.JUCtrlActionBinding: Executes when any ADF action binding is invoked,
so you can step into the logic and look at parameters if relevant
oracle.jbo.server.ViewObjectImpl.executeQueryForCollection: Method exception; called when a
VO executes its SQL query
oracle.jbo.server.ViewRowImpl.setAttributeInternal: Method exception; called when any view
row attribute is set
oracle.jbo.server.EntityImpl.setAttributeInternal: Method exception; called when any entity
object attribute is set

1036
.
ADF Faces provides optimized markup to the client such as content compression and rendering
optimized markup to the client.
The debug-output flag will force ADF Faces runtime to render nicely formatted and readable
markup to the client, whereas the context parameter will ensure that style class names and ID
are not compressed to 0x and instead render the full name e.g. OraSelectInput

This makes debugging client side much easier, but will also effect performance. Ensure to turn
this off when deploying to production environment.

1037
.
Debug Interactions with the Model Layer
The processing of your JSF page in combination with Oracle ADF Model is controlled by two
classes:
oracle.adf.controller.faces.lifecycle.FacesPageLifecycle:
Provides the default implementation of the phase of the ADF life cycle.
oracle.adf.controller.v2.lifecycle.PageLifecycleImpl: Provides
the starting point for creating the objects of the Oracle ADF binding context
FacesPageLifecycle implements certain methods of PageLifecycleImpl to provide customized
error-handling behavior for ADF Faces applications. A good place to set a breakpoint in the
FacesPageLifecycle class is on the prepareModel() method because it initiates the first phase of
the ADF life cycle. Generally, however, you set breakpoints on PageLifecycleImpl because it is
the starting point.
The successful interaction between the Web page and these objects of the Oracle ADF binding
context ensures that the page’s components are displayed with correct and complete data, that
methods and actions produce the desired result, and that the page renders properly with the
appropriate validation errors.

1038
.
Correct Failures to Display Data
After BindingContainer is created by BindingContext, the ADF life cycle initiates the Prepare
Model and the Render Model phases before data can be displayed on the Web page. Before the
bindings are resolved and data can appear on the Web page, the page parameters must be set
and the Iterator and Method executables must be refreshed by executing the named service
methods and ADF iterator bindings.
The ADF life cycle enters the Prepare Model phase by calling
BindingContainer.refresh(PREPARE_MODEL). During the Prepare Model phase,
BindingContainer page parameters get prepared and then evaluated. Next, BindingContainer
executables get refreshed based on the order of entry in the pagedef.xml file’s <executables>
section and on the evaluation of their Refresh and RefreshCondition properties (if present).
When an executable leads to an iterator binding refresh, the corresponding data control is
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 is thrown and the data is not available to
display.

1039
.
Correct Failures to Invoke Actions and Methods
When the executables are refreshed, actions and custom methods may be invoked on the page. At this stage, the
corresponding action or method binding is refreshed. If an executable or its target binding is not executed, the
action is ignored.
The entry point for action and method execution is the DCDataControl.invokeOperation() method. Debugging on
that method enables you to work with the same method that the data control uses to invoke the method. This is
preferred because some adapter data controls can interpret the method name in a custom way rather than leave
it to ADF to call the method.
To debug the action or method invocation for the binding container, perform the following steps:
In the oracle.adf.model.binding.DCDataControl class, set a breakpoint on invokeOperation() as the entry point to
debug an action or method invocation.
When processing pauses, step into the method to verify that instanceName in the Data window shows that the
method being invoked is the intended method on the desired object.
Verify that args in the Data window shows that the parameter value for each parameter being passed into your
method is as expected.
To debug an invocation of a coded method for the binding container, perform the following steps:
In your class, set a breakpoint on the desired method.
In the oracle.adf.model.generic.DCGenericDataControl class, set a breakpoint on invokeMethod() to halt
processing before looking into the Data window.
When processing pauses, step into the method to verify that instanceName in the Data window shows that the
method being invoked is the intended method on the desired object.
Verify that args in the Data window shows that the parameter value for each parameter being passed into your
method is as expected.
If the debugger does not reach a breakpoint that you set on an action in the binding container, then the error is
most likely a result of the way the executable’s Refresh and RefreshCondition attributes were defined. Examine
the attribute definitions.
Whether the <invokeAction> executable is refreshed during the Prepare Model phase, depends on the value of
Refresh and RefreshCondition (if they exist). If Refresh is set to prepareModel, or if no value is supplied (that is, it
uses the default ifneeded), then the RefreshCondition attribute value is evaluated. If no RefreshCondition value
exists, the executable is invoked. If a value for RefreshCondition exists, then that value is evaluated, and if the
return value of the evaluation is true, then the executable is invoked. If the value evaluates to false, the
executable is not invoked. The default value always enforces execution.

1040
.
Debug Life Cycle Events: Task Flows
This slide describes where to set breakpoints if you want to stop at specific points in a task
flow.

1041
.
Debug Life Cycle Events: Parameters and Methods
The execute() method for each activity type’s implementation logic is always called from
oracle.adfinternal.controller.engine.ControlFlowEngine.doRouting (). If you want to track your
progression through the page flow graph, this is a useful place to set a breakpoint.

1042
.
Debug Life Cycle Events: Switching Between the Main Page and Regions

1043
.
ADF Structure Window and ADF Data Window
The ADF Declarative Debugger provides standard debugging features such as the ability to
examine variable and stack data. When an application pauses at any breakpoint (ADF
Declarative or Java code breakpoint), you can examine the application status using a variety of
windows:
You can check where the break occurs in the Breakpoint window.
You can check the call stack for the current thread using the Stack window. When you select a
line in the Stack window, information in the Data window, Watches window, and all Inspector
windows is updated to show relevant data.
You can use the Data window to display information about arguments, local variables, and
static fields in your application.
The ADF Structure window displays the run-time structure of the project. The ADF Data
window automatically changes its display information based on the selection in the ADF
Structure window. For example, if a task flow node is selected, the ADF Data window displays
the relevant debugging information for task flows.

1044
.
1045
.
Identif Search Paths on Windows with FileMon
FileMon is a free Windows utility that you can download from http://www.sysinternals.com. Its
purpose is to show where a running application searches for the files that it needs, so it is
useful for resolving problems with CLASSPATH settings.
To use FileMon, perform the following steps:
Run filemon.exe.
Set a filter for the file type in which you are interested. FileMon produces a lot of output; you
probably want to set a filter to restrict the output to a more readable size. To set a filter, click
the Filter button on the FileMon toolbar. For example, you can use the filter
*\*.jsp to monitor all .jsp files that your application is trying to open.
If desired, save the output to a log file.
Note: You can also get information about the classes that load by using the JVM option
-verbose:class.

1046
.
Use Audit Profiles
To create an audit profile:
From the main menu, select Tools > Preferences. The Preferences dialog box appears.
Select the Audit > Profiles page.
From the Profile drop-down menu, select a profile to copy.
Select the rules, assists, and metrics to enable in the new profile.
Configure the selected rules, assists, and metrics, if required.
Click Save As. Enter a name for the new profile and click Save. The new profile name is shown
in the Audit Profiles preferences page’s Profile box.
Click OK.

1047
.
Use JDeveloper’s Profiler
JDeveloper includes a profiler that you can use to gather statistics on your program so that you
can more easily diagnose performance issues. With it you can examine and analyze the
performance of your program. You can perform the following types of profiling:
CPU profiling: Tabulates the processing time of specific methods
Memory profiling: Tabulates the allocation and freeing of data objects
You can start a CPU or memory profiling session for a project or any of its runnable files, and
you can have multiple sessions running, depending on the availability of system resources.
Note: For a simple CPU profile report that is sent to standard output, you can use the –Xprof
JVM option. To use this utility, edit the project properties and select Run/Debug/Profile. Edit an
existing configuration or create a new one. In the Launch Settings, add –Xprof to the Java
Options field. You can also easily get garbage collection information by using the
-verbose:gc JVM option.

Run the Profiler


Profilers are invoked from the Run menu, as alternative ways to run a program. First from the
Run menu, you select the active run configuration that corresponds to the profiler options that
you defined. Then you select from the Run menu again to specify which profiler to run.
As you run the program (such as an ADF BC application module in the Business Components
Browser), the profiler information is displayed in the JDeveloper IDE.

1048
.
1049
.
Obtain Help
The information that you are able to obtain from troubleshooting can be used to search various
sources of help. You can search for error numbers, exceptions, and so on.

1050
.
Request Help
If you ask a forum for help, try to include as much relevant information as possible. You are not
expected to include all the information listed for every problem, just what is appropriate. Give
your post a meaningful subject line. For example, “Need help” is less likely to get anyone to
look at your post than “Unable to refresh detail when clicking tree node.”
Including stack trace information in your posting can be extremely useful. JDeveloper’s Stack
window makes communicating this information easy. Whenever the debugger is paused, you
can view the Stack window to see the program flow as a stack of method calls that got you to
the current line, and use the context menu to set some helpful options:
Preferences: You can set the Stack window to include the line number information as well
as the class and method name that are there by default.
Export: Save the current stack information to an external text file.
Provide concrete examples in your request for help rather than abstract descriptions. For
example, you might start a problem description as follows: “My page contains an input form for
editing customer information. Each customer can have one or more phone numbers.” This is
easier to understand than an abstract description, such as: “My page contains an input form for
editing an object, one of whose attributes can have one or more values.”
When you solve your problem, you should post the solution to the forum thread, so that others
can benefit from it.

1051
.
1052
.
1053
.
1054
.
1055
.
In a view object, you will have the custom logic to work on SQL queries and the data that is displayed in the UI layer. The following are some of
the advanced concepts for view objects:
• Tuning: View object tuning plays an important role in the performance of an application. Some of the common tuning concepts are
discussed here in this section.
• MaxFetchSize: MaxFetchSize is the maximum number of rows fetched from a database for the current view object. -1 will retrieve an
unlimited number of rows or all the rows returned from a query. The value 0 will cause no query execution and no rows will be returned.
• FetchSize: This is the number of rows that is returned on a single database round trip. This setting will determine how many rows will be
returned for a particular view object at runtime on a single query.
• FetchMode: This is the mode that controls how the rows are retrieved in a JDBC result set. Some of the modes allowed for this function
are as follows:
o FETCH_ALL: This mode will fetch all the rows at once
o FETCH_AS_NEEDED: This mode will fetch the number of rows defined by FetchSize first, and the rows are again fetched upon
further request
• RowFetchLimit: This option is provided in the adf-config.xml file to limit the number of rows fetched by the view object query, and it is
applied to the entire view object in an application.
• Forward-only mode: This setting is used to manage one row and the next row. The navigation proceeds in a linearly forward manner.
• ListRangeSize: This is the setting for the list of values that are added to the attribute in the view object. The value of this setting will be set
to a lesser value to reduce a large number of rows being returned unnecessarily. The value -1 will retrieve all the rows.
• RangeSize: This is the setting that is added in combination with the ListRangeSize setting in the UI binding iterator. A value of -1 will
include all the rows to be displayed in the iterator range.
• AccessMode: This defines how the row is accessed in a view object. The modes are as follows:
o SCROLLABLE: This mode is used to cache rows in a collection.
o FORWARD_ONLY: This mode is used for sequential access to rows in a collection.
o RANGE_PAGING: The paging is done based on the defined value of RangeSize. If the rows that are requested are not in the
range, the rows are fetched from the database using the ROWNUM query.
o RANGE_PAGING_AUTO_POST: The rowset will post any changes in the transaction for rows out of the current range.
• Query Optimizer: These are hints added to a query to help retrieve the record efficiently. This will influence the execution plan of the
query. The modes are as follows:
o ALL_ROWS: This mode fetches all rows as quickly as possible
o FIRST_ROWS: This mode fetches the first row as quickly as possible
• SQL Mode: Use the view object SQL mode to control the area from which the rows have to be retrieved. You can combine the following
query modes to retrieve records efficiently:
o QUERY_MODE_SCAN_DATABASE_TABLES: This mode is used to scan rows from the database. This is the default mode.
o QUERY_MODE_SCAN_VIEW_ROWS: This mode is used to scan rows from the view cache. This mode uses the existing rows and
will not go back to the database.
o QUERY_MODE_SCAN_ENTITY_ROWS: This mode is used to scan rows from the entity cache. This mode uses the entity object
rows that are valid for entity-based view objects.
• Association Consistent: When using two view objects that have the same entity type, one view object is notified about the changes made
to an entity through the other view object via the flag to view link consistency. The flag to view link consistency is jbo.viewlink.consistent
in the AM configurations, which can be performed programmatically using setAssociationConsistent(true).

1056
.
1057
.
Configuring Locking Mode for an ADF application
The jbo.locking.mode configuration property controls how entities are locked. This property is
configurable from two places:
• Per application module level: Open the application modules in the editor and then select
the desired configuration. Click on the yellow edit icon to open up the Edit configuration
dialog box. Click on the Properties tab and modify jbo.locking.mode to the desired value.
• Application level: Double-click on the adf-config.xml file in the ADF META-INF folder in the
Application Resources under the Descriptors panel view in Application Navigator. Click on
the Business Components tab on the adf-config.xml editor window and set Locking Mode
appropriately.

Supported values for jbo.locking.mode are as follows:


• None: This implies the case where no locking is done when the user updates a row.
• Pessimistic: The pessimistic locking mode will try to lock an entity instance in advance
before allowing any changes by explicitly firing SELECT FOR UPDATE on the underlying
database row, and the row will remain locked till you commit the transactions. This is not
recommended for a web application in optimistic mode, because during recycling of
application modules framework will issue a rollback on JDBC connection and potentially
client may loss all the lock associated with database connection.
• Optimistic: The optimistic locking mode will try to lock the entity before posting modified
data to the database, followed by a check for stale data.
• Optupdate: The optupdate locking mode will not issue lock on the row, it will just see if all
row attributes that are participating in the update have the latest value from the database
table.

1058
.
1059
.
1060
.
1061
.
1062
.
1063
.
Design for Reuse
Creating and consuming reusable components should be included in the early design and
architectural phases of software projects. You and your development team should consider
which components are candidates for reuse, not only in the current applications but also for
future applications and for applications being developed in other departments.
When you create reusable components, you should try to create unique and relevant names for
the application, project, application module, task flow, or any other relevant file or component.
Do not accept the JDeveloper Wizard’s default names, but try to have unique names to avoid
name conflicts with other projects or components in the application. You should also consider
creating standardized naming conventions so both creators and consumers of ADF Library JARs
can readily identify the component functionality.
You and your team should decide on the type of repository needed to store the library JARs,
where to store them, and how to access them. You should consider how to organize and group
the library JARs in a structure that fits your organizational needs.

1064
.
Conform to PPR Guidelines
When PPR is implemented correctly, it improves application performance as follows:
Rendering performance is improved by generating only a subset of the page.
Network traffic is reduced by sending only a subset of the page’s contents to the browser.
User perception of performance is improved because of not spending time looking at a blank
page.
When performance improvement is not possible with PPR, it should not be implemented, thus
avoiding unnecessary code bloat.
PPR should not be invoked in the following contexts:
When navigating to another page, because some page elements, such as page titles, do not
change during PPR
When response times may be long (user is blocked during a partial page submit), such as:
Database queries or database maintenance operations
Processes that demand significant middle-tier processing
When multiple sections of the page need to be redrawn, such as:
Action or choices that affect more than half the content of the page
Inline messaging, which features a message box at the top of the page, and may insert inline
messages below multiple fields

1065
.
1066
.
1067
.
1068
.
1069
.
1070
.
1071
.
1072
.
1073
.
1074
.
1075
.
1076
.
1077
.
1078
.
1079
.
1080
.
1081
.
1082
.
1083
.
1084
.
1085
.
1086
.
1087
.
1088
.
1089
.
1090
.
1091
.
1092
.
1093
.
1094
.
1095
.
1096
.
1097
.
1098
.
1099
.
1100
.
1101
.
Hands-on Lab practices provides sample and steps to learn following advance but common
features:
1. Custom View Criteria
2. Traversing and deleting master-detail
3. Creating an Application Module base class
4. Programmatically calling EL, scopes and conditional display
5. Adding Router Activity
6. Programmatically handling confirm Dialog Yes and No
7. Programmatically invoking Popup
8. Programmatically closing Popup
9. Rendering Dynamic Region
10. Add Context Menu
11. Creating Data Control Method from Backing Bean
12. Contextual Events
13. Programmatically adding PPR
14. Programmatically handling UI CRUD transactions

1102
.
Hands-on lab practice application design.

1103
.
Hands-on lab practice application design.

1104
.
Hands-on lab practice application design.

1105
.
Characteristics of the Contextual Event Framework
When a page contains multiple regions that need to work together to display relevant
information to the user, the need to communicate between regions becomes very important.
This
communication can be handled through an event framework called the Contextual Event
Framework. This framework provides the page with the ability to map events to be produced
and
consumed by the page’s various regions, along with the information to be passed to the
consumer regions.
In a typical scenario, a consumer would need to register with the producer to get event
notification. However, the Contextual Event Framework in ADF enables the producer and
consumer to be tied through an event routing mechanism. The producer publishes the
contextual
event it is going to raise. The page listens for the event and then routes it to the consumer.
The Contextual Event Framework includes the following characteristics:
• A contextual event can go across data controls.
• A contextual event can be raised or consumed only with a method action binding that must
be only data control methods, not managed bean methods.
• Event payload can either be primitive or any serializable object.

1106
.
Contextual Events: Example
As an example of using the Contextual Event Framework, consider a containing page that
contains two regions representing two task flows. The task flows in the separate regions have
no
knowledge of one another, as if there is a wall between them. Only the containing page has
knowledge of both regions, so it is the containing page that must coordinate the interaction
between them.
The goal of creating a contextual event in this example is to accomplish the following:
• Pass information from the first region to the second region.
• React in the second region based on the information that is passed.
When an action, such as a button click, occurs in the first region, the event is initiated. There is
a
method defined that constructs the payload for the event, that is, the information that is being
passed to the other region. There is another method on the target, or consumer region, that
specifies how that region should respond. The job of the containing page is to map the event:
specify which is the payload method, which is the handler method, and so on.

1107
.
Using Contextual Events
There are several aspects that define a contextual event:
1. A container page that contains the regions to be coordinated
2. A producer that invokes a method to raise the event and provide a payload (information
needed by the event)
3. A consumer that is the target of the event
4. A handler method that is bound either to the consumer page fragment or to the page
containing the regions
5. An event mapping on the container page definition that specifies:
- The producer region and payload method
- The event name
- The consumer and event handler
- The parameter (payload) to pass to the event
The steps required to set up a contextual event are described in the next few slides.

1108
.
Using Contextual Events: Step 1
Although they do not need to be performed exactly in order, defining a contextual event
requires
several steps as explained in this and the following slides:
1. Create the container, producer, and consumer:
If you have two regions on a containing page that you want to coordinate by using
contextual events, you first need to decide which is the producer and which is the
consumer. For example, you may want the data in the consumer region to display
differently depending on what is clicked in the producer region, such as displaying
products or categories when the user clicks a subcategory or a root category in a category
tree. (This is the example that is used in the course application.)

1109
.
Using Contextual Events: Step 2
2. Create the method that constructs the payload and expose it as a data control:
After you have designated the producer and the consumer, you can determine what data, or
payload, the consumer of the event requires to refresh its region appropriately. This can be
as simple as passing a foreign key value, but some complex business logic may be required
to produce the data needed by the consumer region. In any case, you need to create a
method to construct the event payload. This can be in a separate Java class, or it can be a
service method in the application module. The method must always return the event
payload.
No matter how you create the method, you must expose it as a data control. If it is in a
separate Java class, you can simply drag it to the Data Control Palette. If it is an
application module method, you must expose it to the client interface.

1110
.
Using Contextual Events: Step 3
3. Invoke the payload method:
You need to call the method that you just created, so you can create a command
component (button or link) on the producer region’s page and drag the method to that
component from the Data Control Palette.

1111
.
Using Contextual Events: Step 4
4. Supply values for the payload method arguments, if any:
The previous step creates a method action binding in the producer page definition. In that
page definition file, you may need to supply a value for any arguments that are passed to
the method. In the Structure window, select the method argument and set its value in the
Property Inspector. You can use EL to pass a value from the data that is on the page.

1112
.
Using Contextual Events: Step 5
5. Raise the event when the payload method is invoked:
You need to specify that an event be raised when the payload method is invoked. In the
Structure window for the page definition for the producer page fragment, insert
<events> inside the method binding, and insert <event> inside <events>. Specify
the event name to be raised as any meaningful name.
Note: One method action can raise one or more events.
You can also use the Contextual Events tab in the page definition file for the producer page
to define an event. (This is explained in the next slide.)

1113
.
Using Contextual Events: Step 5
You can also use the Contextual Events tab in the page definition file itself to define a
contextual event on the producer page.
1. In the overview editor for the producer page definition, click the Contextual Events tab.
2. In the Events section, click the Add icon.
3. In the Publish Contextual Events dialog box, perform the following steps:
a. Select Create New Event.
b. Enter the name of the event.
c. Select Pass Custom Value from if you want to pass payLoad data to the consumer.
d. If you are passing payload data, select the type of data from the drop-down list.
e. You can conditionally raise the event by entering an EL expression on the Raise
Condition tab.
f. Click OK.
The event is created on the page, but it is not ready for publishing until it is associated
with the component binding.

1114
.
Using Contextual Events: Step 6
6. Create an event handler method and expose as a data control:
You also need to create an event handler that specifies what happens in the consumer
region after the event is raised. Does it need to requery, using the payload data, or does it
simply need to refresh the region? Again, this event handler method, which can be defined
in a separate class or as an application module service method, must be exposed as a data
control. The handler method expects event parameters or the event payload itself.

1115
.
Using Contextual Events: Step 7
7. Create a method binding for the event handler method:
Depending on the situation, you need to bind that handler method to either the consumer
page fragment or the containing page (the one that contains the regions). You do this by
opening the page definition for that page and creating method action as a generic binding.
A dialog box enables you to select the data control and operation for the method action.

1116
.
Using Contextual Events: Step 8
8. Map the event:
Event mapping means that you tell the containing page how to route the event. You do this
on the page that contains the regions to be coordinated. In the Structure window for its
page definition, right-click the root node and select Edit Event Map. In the upper portion of
the Event Map editor, you specify the mapping:
- Select the Producer (the method on the producer page fragment that constructs the
payload for the event). This should populate the Event Name for you, because in the
page definition file for the producer page fragment, you have already specified the
event to be raised when the method is invoked.
- Select the consumer, which is the method to be invoked to handle the event.
- Click the ellipsis button beside Parameters to supply the payload for the event. The
Edit Consumer Params dialog box enables you to name the parameter and to use EL
to specify the payload, which must be ${payLoad}. You can click the ellipsis in
the Param Value column to use Expression Builder to choose this value from Payload
Data.
- After you have defined the mapping, click Add New to add it to the Event Entries
Summary.
You can also use the Contextual Events tab in the page definition file to map an event
(explained in the next slide).

1117
.
Using Contextual Events: Step 8
Alternatively, you can use the Contextual Events tab in the page definition file for the parent
page to create a map for the contextual event – defining subscribers to, and consumers of, the
event.
1. In the overview editor of the parent page definition, click the Contextual Events tab.
2. On the right of the page, click the Subscribers tab, and click the Add icon in the Event
Subscribers section.
3. In the Subscribe to Contextual Event dialog box, click the Search icon.
4. In the Select Contextual Event dialog box, select the event you want to subscribe to from
the tree and click OK.
5. Click the Search icon next to the Handler field.
6. In the Select Handler dialog box, select the event handler from the tree and click OK.
7. The Parameters tab enables you to specify consumer parameters for the event. Click Add,
and enter name-value pair as parameters.
8. If you want to conditionally handle the event, click the Handle Condition tab, and enter
an EL Expression that determines the conditions under which the handler will process the event.
9. Click OK.
10. In the Publish Contextual Events dialog:
a. Select Create New Event.
b. Enter the name of the event.
c. Select Pass Custom Value from if you want to pass payLoad data to the consumer.
d. If you are passing payload data, select the type of data from the dropdown list.
e. You can conditionally raise the event by entering an EL expression in the Raise
Condition tab.
f. Click OK.
The event is created on the page, but it is not ready for publishing until it is associated
with the component binding.

1118
.
Using Contextual Events: Step 9
9. Specify region refreshing:
You also need to define how the regions will be refreshed:
- Producer region: Typically you do not want to refresh the producer region, so for the
button that invokes the event, set the PartialSubmit property to true.
- Consumer region: If you are performing an action in the handler method that
refreshes the page (such as requerying), then you do not need to worry about
refreshing the consumer page fragment or region. The event consumer processes the
payload and updates its model accordingly. Otherwise, you need to set refresh
and refreshCondition appropriately for the consumer region on the page
definition for the containing page.
At run time, when the user clicks the button or link in the producer task flow, a PPR action
submit in the event producer region invokes a method action in the event producer task flow.
When the method action in the event producer task flow is invoked, it raises an ADFm
event. The ADFm event is consumed by a method action inside the consumer task flow
according to the event mapping defined in the containing page’s page definition. The event
consumer processes the payload and updates its model accordingly.

1119
.
The Active Data Services framework
The Active Data Service (ADS) framework is a server-side push framework that allows UI
information to be refreshed, with the value as a particular interval of time. The ADF Faces
components that support the Active Data Service framework are activeCommandButton,
activeImage, activeOutputText, table, tree, and treeTable.

The ADS framework consists of the following interfaces:


• ActiveDataModel: This interface is responsible for starting and stopping active data. This will
keep track of the active data's event ID as well.
• Event Manager: This interface listens and raises a push event for the active data. It manages
and retrieves the active data.
• Push Service: This interface transmits the active data to the client for a refresh.
• Active Data Manager: This interface delivers the active data to the client. It handles multiple
client interfaces using a shared channel.
• Active Data Proxy: This interface listens to the data change event and delegates to JSF
models.

1120
.
1121
.
1122
.
1123
.
Hands-on lab practice application provides sample and steps to learn following features:
1. Create REST Web Service with ADF Business Service
2. Create SOAP Web Service with ADF Business Service
3. Consume REST Web Service (ADF)
4. Consume REST Web Service (Generic)
5. Consume SOAP Web Service

1124
.
1125
.
1126
.
1127
.
1128
.
1129
.
1130
.
1131
.
1132
.
1133
.
1134
.
1135
.
1136
.
1137
.
1138
.
1139
.
1140
.
1141
.
1142
.
1143
.
1144
.
1145
.
1146
.
1147
.
1148
.
1149
.
1150
.
1151
.
1152
.
1153
.
1154
.
1155
.
1156
.
1157
.
1158
.
1159
.
1160
.
1161
.
1162
.
1163
.
1164
.
In Hands-on lab one would practice:
Consuming EJB Data Control

1165
.
1166
.
1167
.
1168
.
In Hands-on lab one would practice:
Integrating SOA

1169
.
1170
.
Fusion Architecture
The basic Fusion architecture is depicted in the graphic in the slide. The upper part comprises
the core application and the lower part comprises the integration SOA layer. On top, you have
the Model-View-Control (MVC) model for development, which supports better reusability and
easier changes. At the bottom, you see all the business activities and components and how
they fit into the MVC model. You also have integration with manual processes and metrics for
making changes.

1171
.
1172
.
Oracle SOA Platform
You never start SOA from the beginning. You would always want to reuse existing assets,
whether it is legacy services, Commercial Off The Shelf (COTS), or even interaction with your
business partners. The first thing that you need to do is to normalize these heterogeneous
sources via adapters, or in the case of external partners, via a B2B gateway that provides all the
security and framework required to extend your SOA beyond the boundaries of your
enterprise.
After normalization, you need to enable data flows in a reliable and flexible fashion.
Additionally, you want to virtualize all these data sources to ensure loose coupling and
maximum flexibility as you move forward.
Now that you have the necessary foundation, you can start building new value, declaratively,
through orchestration of these assets. For example, you could start building a brand new
employee hiring application that would leverage your existing PeopleSoft HR coupled with BMC
Remedy and additional homegrown systems that used to be disconnected.

1173
.
Orchestrating Services
BPEL is the core part of the overall SOA solution that also includes Enterprise Service Bus (ESB)
for messaging between systems. A rule engine repository is available to dynamically and easily
change the rules governing the process flow.

1174
.
1175
.
1176
.
In Hands-on lab one would practice:
Working with Mobile Application Framework (MAF)

1177
.
1178
.
1179
.
1180
.
1181
.
1182
.
1183
.
1184
.
1185
.
1186
.
1187
.
1188
.
1189
.
1190
.
1191
.
1192
.
1193
.
1194
.
1195
.
1196
.
1197
.
1198
.
1199
.
1200
.
1201
.
1202
.
1203
.
1204
.
1205
.
1206
.
1207
.
1208
.
1209
.
1210
.
1211
.
What Is WebCenter?
WebCenter implements the (run-time) customization and personalization requirements, allows
consumption of third party, external portlets (that also bridge technologies), provides many
Web 2.0/E2.0 Services (Blog, Wiki, Content Integration, Tagging, Linking, Email/VOIP/IM
integration, and so on) and Community Workspaces and Search and Recent Activities.

1212
.
Key Benefits of Oracle WebCenter
As a developer, Oracle WebCenter enables you to:
• Develop applications using industry standards that are supported in Java EE, portals, content
integration, SOA, and presence servers
• Easily integrate your application into an existing infrastructure, such as content
management, Web 2.0 services, security, application server and database infrastructure,
search, and collaboration
• Use a single paradigm to build all your UIs. You use the same development model for all UI
components: composite applications, portals, and business intelligence.
• Extend your Java EE and SOA applications. Oracle WebCenter injects new capabilities into
the standard JavaServer Faces development environment to allow you to create context-rich
applications that satisfy your business needs. Oracle WebCenter also provides natural user
interaction environment for your SOA applications and allows you to leverage all types of
services to create a more effective user experience.
• Reduce your development time by leveraging the Web 2.0 services that ship with Oracle
WebCenter

1213
.
1214
.
1215
.
1216
.
1217
.
1218
.
Oracle WebCenter Portal Components
How did Oracle WebCenter come to be?
It started with Java Server Faces (JSF). JSF is the development platform for the user interface of WebCenter
applications. JSF offers component-based development that provides benefits such as drag-and drop support and
easy editing of component properties. JSF frees the developer from writing HTML code as is necessary when
developing applications by using servlet and JSP technologies.
Oracle’s Application Development Framework (ADF) provides another level of productivity that you need as an
enterprise application developer. ADF simplifies Java EE development by providing out-of-the-box implementation
design patterns and infrastructure code. ADF provides a choice of development approach, technologies used, and
deployment platform. In combination with the visual development environment of Oracle JDeveloper, ADF
increases the productivity of the Java developer.
Functionality typically found in portals, such as consuming portlets and content integration, has proven to be
useful in enterprise applications. WebCenter Framework is created to address these requirements.
Similarly, Web 2.0 capabilities that support collaboration and communication among information workers are
beneficial in enterprise applications. WebCenter Services provides a number of these capabilities.
Run-time editing and customizing applications is a much-requested feature of modern enterprise applications.
Oracle Composer provides a collection of components, processes, and an API to accomplish this.
Recognizing the advantages that these capabilities—portal-like features, Web 2.0 services, runtime editing and
customization—bring to the enterprise, Oracle integrated them with the functionality of JSF and ADF, and
developed a new platform for user interaction: Oracle WebCenter.
Using these capabilities, application developers can create custom WebCenter applications, such as composite
applications that focus on the use of Web 2.0 services or enterprise portals, by utilizing more of the run-time
editing capabilities.
Using all these components and features, Oracle created an out-of-the-box application, WebCenter Spaces, which
provides you with the latest technology for social networking, communication, collaboration, and personal
productivity.
Oracle JDeveloper is the tool of choice to develop WebCenter applications. JDeveloper contains extensions to
support declarative development of applications using WebCenter features, and supports drag-and-drop to add
Web 2.0 services to the application.
Oracle’s strategy is to build the next versions of its business applications with the same open, standards-based UI
technology stack that is offered to its customers. Therefore, WebCenter is key to the development of Oracle
Fusion Applications, the next generation of Oracle E-Business, JD Edwards, PeopleSoft, and Siebel applications.

1219
.
WebCenter Framework
Oracle WebCenter Framework augments the JSF declarative development environment with
additional components, integration, and run-time options by integrating capabilities that are
historically included only in portal products. These capabilities enable you to:
• Integrate content from many different content stores through standard interfaces
• Build and consume rich standards-based portlets
• Make the application customizable at run time, which empowers end users to edit
application pages according to their requirements using Oracle Composer
WebCenter supports portlets that are written using two different APIs, the industry standard
JSR 168 and Oracle’s propriety PDK-Java API. JSF (ADF) pages and task flows can be portletized
using the JSF Portlet Bridge, that is, other applications can consume JSF pages or task flows as
portlets. WebCenter also comes with a set of useful, predeployed portlets.

1220
.
WebCenter Services
Oracle WebCenter Services includes a complete set of Web 2.0 content, search, collaboration,
communication, and social networking services that you can add directly to your applications to
create a dynamic and interactive environment for your users.
These services are delivered as reusable, out-of-the-box components, and are available during
development (JDeveloper) and at run time (Oracle Composer) to create and extend your
application. Each service is designed for the enterprise and adheres to a consistent security
model
across all services, a set of standardized framework extensions, including life cycle, user
provisioning, search, and a standards-based UI for Web 2.0 services.
The WebCenter services add Web 2.0 capabilities such as presence, wiki, blogs, tagging, and so
on, to your ADF application. You integrate them into your application through a set of task
flows.
You can easily integrate Web 2.0 services in your ADF application to get:
• Thin adapter layer to abstract back-end services
- Email Adapter: IMAP, MS Exchange
• Back-end systems represented by unified connection architecture

1221
.
WebCenter Portal Spaces
WebCenter Spaces is an out-of-the-box solution that delivers enterprise-ready line of business
(LOB) portals, communities, and team sites.
It is designed for business users to quickly build a workspace. It is pre-integrated with
Composer, Business Dictionary, and WebCenter Enterprise 2.0 Services.
IT can extend and customize Spaces using WebCenter Framework and extensive Spaces Web
Services APIs (for example, mobile access).

1222
.
There are three key areas of WebCenter Spaces. They are:
Personal Space
• Focuses on personal information
• Provides personalized environment to suit individual needs
• Brings business context to the end user
• Enables targeted interaction with peers
Group Space
• Focuses on team group collaboration and social networking
• Connects users with a common goal or interest
• Integrates relevant applications
Business Role Pages
• Is created for a group, department, organization, or everyone
• Is controlled by the WebCenter Spaces administrator

1223
.
1224
.
1225
.
Oracle Composer
Oracle Composer is a browser-based platform that enables information workers to easily
customize and personalize pages at run time. Pages can be easily modified by rearranging
components on a page and by editing components in place. The layered customization model
of Oracle Composer separates metadata from code. This means that you can build a single
application that individuals, departments, and organizations throughout the company can
customize without changing the core application. Subsequently, the core application can be
patched or upgraded without loss of customizations.
Oracle Composer provides a rich feature set to tailor fit the application to business and
personal requirements. This includes:
• A Resource Catalog containing view components and data available to build the page
• A sandbox to view the page design and commit the changes only when ready
WebCenter also provides a rich API to enable run time creation of pages. Several page
templates are provided out of the box to make the creation process easy and quick. After
creation, these pages can be shared among users, and edited and customized using Oracle
Composer.

1226
.
1227
.
Metadata Services
Metadata Services is a persistent store for application metadata. With customization, this
metadata defines the changes made on application pages. Because the application pages are
defined as XML documents, the changes are represented as XML elements. These changes are
not stored in the original base document, but as separate XML files. Changes describe the
insertion or removal of components, or moving a component to a different place in the
container hierarchy, that is, changing the component’s parent. Component attributes can also
be set or changed.
When the page is rendered, the rendering engine merges the base document with the
modifications stored in MDS. MDS offers layered store for the modifications. For example, the
same page can be modified in three ways: for a particular site, for all application users, or for
individual users. Rendering applies all these layers, depending on the run-time context when
the page is accessed.
MDS provides a persistence store of the modifications. During development or in simple
installations, MDS can use the file system to store the modifications. However, in large, highly
available systems, MDS uses a database schema.

1228
.
The Metadata Services framework
The Oracle Metadata Services framework is used to provide customization features for ADF
users in an ADF web application. Users have the ability to customize the way a web application
is presented to them. The customer can add more custom features at runtime using Metadata
Services (MDS).
For example, in the above screenshot, the base document for the page is displayed with
customization for User1 and without customization for User2, at the same time.

1229
.
1230
.
What Is a Portlet?
A portlet is a reusable and pluggable Web component that runs remotely and provides a dynamic
view of an information source, such as a stock ticker or weather outlook. By placing portlets that
derive data from different data sources on a common page, you can provide users a single-source
experience. Because of their dynamic nature, portlets are often used to display excerpts of other
Web sites, generate summaries of key information, perform searches, and access assembled
collections of information from a variety of data sources.
Portlets are as varied as the interests of users. The content source of the portlet can be a document,
an application, or a commonly requested piece of information, such as a report, an employee list,
or external information from the Internet. The portlet code can run remotely on a different server
than the servers running the applications that consume the portlet. When an application consumes
a portlet, the application – the consumer – will display the portlet’s HTML output embedded in
the application’s page.
Oracle WebCenter offers a set of prebuilt portlets for use in enterprise applications. In addition,
Oracle has created a partner initiative to support a community of independent software vendors
and content providers who create standard portlets for their applications and services.
Portlets typically offer customization and/or personalization, that is, users can change and
configure their behavior at run time. Portlets store customization data so the next time the portlet
is displayed, this data controls its appearance and behavior.

1231
.
Consuming a Portlet: Overview
This slides illustrates the steps to consume portlets.
First, you must register the producer with your WebCenter application. The purpose of
registration is to provide the WebCenter application with the information that it needs to
communicate with the portlet producer and with the portlets through the producer.
After the registration, you can drag any of the producer’s portlets to the page, creating an
instance of that portlet in your application.

1232
.
1233
.
1234
.
1235
.
1236
.

You might also like