Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Oracle Fusion Middleware 11g: Build Applications With ADF I

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

Oracle Fusion Middleware 11g:

Build Applications with ADF I


Electronic Presentation

D53979GC10
Edition 1.0
December 2008

Copyright 2008, Oracle. All rights reserved.

Authors

Disclaimer

Pam Gamer
Gary Williams

This document contains proprietary information and is protected by copyright and other intellectual
property laws. You may copy and print this document solely for your own use in an Oracle training
course. The document may not be modified or altered in any way. Except where your use constitutes
"fair use" under copyright law, you may not use, share, download, upload, copy, print, display,
perform, reproduce, publish, license, post, transmit, or distribute this document in whole or in part
without the express authorization of Oracle.

Technical Contributors
and Reviewers
Glenn Maslen
Ken Cooper
Joe Huang
Taj-ul Islam
Duncan Mills
Kenichi Mizuta
Frank Nimphius
Dan Pillay
Blaise Ribet
Oliver Steinmeier

The information contained in this document is subject to change without notice. If you find any
problems in the document, please report them in writing to: Oracle University, 500 Oracle Parkway,
Redwood Shores, California 94065 USA. This document is not warranted to be error-free.
Restricted Rights Notice
If this documentation is delivered to the United States Government or anyone using the
documentation on behalf of the United States Government, the following notice is applicable:
U.S. GOVERNMENT RIGHTS
The U.S. Governments rights to use, modify, reproduce, release, perform, display, or disclose these
training materials are restricted by the terms of the applicable Oracle license agreement and/or the
applicable U.S. Government contract.
Trademark Notice

Editors
Steve Elwood
Raj Kumar
Aju Kumar

Publishers
Veena Narasimhan
Jothi Lakshmi

Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be
trademarks of their respective owners.

Course Introduction:
Oracle Fusion Middleware 11g:
Build Applications with ADF I

Copyright 2008, Oracle. All rights reserved.

Course Objectives

After completing this course, you should be able to do the


following:
Build and customize a data model by using ADF
Business Components
Expose the data model in a Web application with a rich
ADF Faces user interface
Secure Web applications
Deploy Web applications

I-2

Copyright 2008, Oracle. All rights reserved.

Course Agenda: Day 1

Basic ADF Business Components:


Lesson 1: Introduction to Oracle Fusion and Oracle ADF
Lesson 2: Getting Started with JDeveloper
Lesson 3: Modeling the Database Schema
Lesson 4: Building a Business Model with ADF Business
Components
Lesson 5: Querying and Persisting Data
Lesson 6: Exposing Data

I-3

Copyright 2008, Oracle. All rights reserved.

Course Agenda: Day 2

Customization, Validation, and Troubleshooting:


Lesson 7: Declaratively Customizing Data Services
Lesson 8: Programmatically Customizing Data Services
Lesson 9: Validating User Input
Lesson 10: Troubleshooting ADF BC Applications

I-4

Copyright 2008, Oracle. All rights reserved.

Course Agenda: Day 3

Basic UI Concepts:
Lesson 11: Understanding UI Technologies
Lesson 12: Binding UI Components to Data
Lesson 13: Planning the User Interface
Lesson 14: Adding Functionality to Pages
Lesson 15: Implementing Navigation on Pages

I-5

Copyright 2008, Oracle. All rights reserved.

Course Agenda: Day 4

Basic ADF Faces UI:


Lesson 16: Achieving the Required Layout
Lesson 17: Ensuring Reusability
Lesson 18: Passing Values Between UI Elements

I-6

Copyright 2008, Oracle. All rights reserved.

Course Agenda: Day 5

Advanced ADF Faces:


Lesson 19: Responding to Application Events
Lesson 20: Implementing Transactional Capabilities
Lesson 21: Implementing Security in ADF Applications
Lesson 22: Deploying ADF Applications

I-7

Copyright 2008, Oracle. All rights reserved.

Introduction
to
Oracle Fusion and Oracle ADF

Copyright 2008, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do the


following:
Describe the Fusion architecture
Explain how ADF fits into the Fusion architecture
Describe the ADF technology stack (MVC)
Find more information about ADF

1-2

Copyright 2008, Oracle. All rights reserved.

Examining Oracle Fusion Architecture

1-3

Copyright 2008, Oracle. All rights reserved.

Oracle Application Development


Framework (ADF)

1-4

Is an end-to-end Java EE framework that is extensible


Utilizes and adds value to the Java EE platform
Abstracts Java EE complexity
Provides declarative and visual development
Enables developers to focus on the application, not the
low-level infrastructure
Creates reusable and maintainable code
Uses metadata, simplifying the basic task of wiring user
interfaces to services
Implements Java EE best practices and design patterns,
including MVC
Copyright 2008, Oracle. All rights reserved.

The Model-View-Controller Design Pattern

Web and Mobile

Rich Clients

Controller

1-5

View

Controller

Model

Model
(JSR-227)

Business Services

Business
Services

Copyright 2008, Oracle. All rights reserved.

Implementing MVC with the ADF Framework:


Business and Data Services
Web and Mobile

Rich Clients

View

Controller

Controller

Model
(JSR-227)

Model

Java

EJB

TopLink

BAM

BPEL

ADFbc
Web
Services

BI

Essbase

Portlets

Business
Services

Data
Services
Relational Data

1-6

XML Data

Legacy Data

Copyright 2008, Oracle. All rights reserved.

Packaged Apps

Implementing MVC: ADF Model


Web and Mobile

Rich Clients

View

Controller

Controller

Model
(JSR-227)

ADF Bindings (JSR 227)

Java

EJB

TopLink

BAM

BPEL

ADFbc
Web
Services

BI

Essbase

Portlets

Business
Services

Data
Services
Relational Data

1-7

XML Data

Legacy Data

Copyright 2008, Oracle. All rights reserved.

Packaged Apps

Implementing MVC: Controllers


Web and Mobile

Rich Clients

View

Controller
Struts

JSF/ADF Task Flow


Model

ADF Bindings (JSR 227)

Java

EJB

TopLink

BAM

BPEL

ADFbc
Web
Services

BI

Essbase

Portlets

Business
Services

Data
Services
Relational Data

1-8

XML Data

Legacy Data

Copyright 2008, Oracle. All rights reserved.

Packaged Apps

Implementing MVC: View


Desktop
ADF Swing

Browser-based
JSP

Office

JSF

Struts

ADF Faces / DVT

JSF/ADF Task Flow

EJB

TopLink

BAM

BPEL

ADFbc
Web
Services

BI

Controller

Model

ADF Bindings (JSR 227)

Java

View

Essbase

Portlets

Business
Services

Data
Services
Relational Data

1-9

XML Data

Legacy Data

Copyright 2008, Oracle. All rights reserved.

Packaged Apps

Technology Choices for ADF BC Applications


Desktop
ADF Swing

Browser-based
JSP

Office

JSF

Struts

ADF Faces / DVT

JSF/ADF Task Flow

EJB

TopLink

BAM

BPEL

ADFbc
Web
Services

BI

Controller

Model

ADF Bindings (JSR 227)

Java

View

Essbase

Portlets

Business
Services

Data
Services
Relational Data

1 - 10

XML Data

Legacy Data

Copyright 2008, Oracle. All rights reserved.

Packaged Apps

Introducing JDeveloper: Oracles Java and Web


Development Tool
Design Applications
Develop Java EE Apps
Develop Business
Processes
Develop DBMS Schemas
Profile, Debug, Optimize
Deploy & Manage

1 - 11

Copyright 2008, Oracle. All rights reserved.

Obtaining Additional Information

You can obtain more information about


Oracle Fusion, Oracle ADF, and ADF
Business Components from the following
sources:
Oracle Technology Network (OTN)
Forums
Blogs
Oracle Magazine
Developers Guides
Online Help

1 - 12

Copyright 2008, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


Describe the Fusion architecture
Explain how ADF fits into the Fusion architecture
Describe the ADF technology stack (MVC)
Find more information about ADF

1 - 13

Copyright 2008, Oracle. All rights reserved.

Getting Started with JDeveloper

Copyright 2008, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do the


following:
List the benefits that JDeveloper provides for application
development
Use the features of the JDeveloper IDE
Define IDE preferences
Create applications, projects, and connections in
JDeveloper

2-2

Copyright 2008, Oracle. All rights reserved.

Describing the Benefits of Using JDeveloper

Standard, open, and


extensible
Improved productivity
Visual and declarative
Simpler development of
Java EE applications

Productivity with Choice

2-3

Technology stacks
Development approaches
Development platform
Data sources
Application servers
Copyright 2008, Oracle. All rights reserved.

Launching JDeveloper

You can launch


JDeveloper by:
Double-clicking
jdeveloper.exe in the
<JDev Home> directory
Starting from the command
line or a shortcut pointing to
jdev.exe in the <JDev Home>\jdev\bin directory

You can specify flags:


For the user directory:
-J-Dide.user.dir=<path>
For editor windows:
-noreopen

2-5

Copyright 2008, Oracle. All rights reserved.

Defining JDK and Role

When you install or


launch JDeveloper, you
need to specify:
Path to java.exe

2-6

A developer role

Copyright 2008, Oracle. All rights reserved.

Using JDeveloper Features

JDeveloper features that facilitate ease of application


development include:
Application Navigator
Database Navigator
Editor (code or visual editors)
Component Palette
Resource Palette (IDE and Application)
Data Controls panel
Structure Window
Property Inspector
Log Window
2-7

Copyright 2008, Oracle. All rights reserved.

Using JDevelopers Application Navigator

Has expandable, minimizable panels to


display:
Projects
Application resources
Data controls
Recently opened files

Expandable Panels

Minimizing a Panel
Restoring a Panel
2-8

Copyright 2008, Oracle. All rights reserved.

Using JDevelopers Database Navigator

The Database Navigator:


Shows both IDE and application connections
Enables you to:
View database elements Delete connections
Filter the display
Change connection properties
Create new connections Open SQL Worksheet
Create new
connection

2 - 10

Apply
filter

Copyright 2008, Oracle. All rights reserved.

Using JDevelopers Editors


Edit code:

Visually edit task flows,


diagrams, and pages:

Edit
properties:

2 - 11

Copyright 2008, Oracle. All rights reserved.

Using JDevelopers Component Palette


The Component Palette enables you to:
Display the components available to drag to visual editor
Search for components
Display the favorites and recently used components

2 - 13

Copyright 2008, Oracle. All rights reserved.

Using JDevelopers Resource Palette


Toolbar: Create/Import or Search

The Resource Palette:


Contains two types of
resources:
Catalogs
Connections

2 - 14

Provides single searchable view


of and access to many types of
resources
Facilitates sharing resources
among developers

Copyright 2008, Oracle. All rights reserved.

Using JDevelopers Structure Window

The Structure Window provides:


A tree view of selected document or object
The ability to:
Show Methods, Fields,
Sort Static / Public Members
View in different
New View
ways
Freeze /
Synch
Navigate
Unfreeze

2 - 15

Copyright 2008, Oracle. All rights reserved.

with
Editor

Using JDevelopers Property Inspector


1
2

3
6

2 - 16

Copyright 2008, Oracle. All rights reserved.

Using JDevelopers Log Window

The Log window:


Displays JDeveloper
messages, such as
logging and compilation
messages
Has one or more tabs:
A Messages tab and additional
tabs depending on what is occurring
Displays standard output (such as
System.out.println() messages)

2 - 17

Has context menu for clearing, wrapping, saving output,


searching, and so on
Copyright 2008, Oracle. All rights reserved.

Working with JDeveloper Windows

Many of the windows in JDeveloper can be:


Maximized or restored
Opened or closed
Split or unsplit
Repositioned
Docked or undocked
Resized

2 - 18

Copyright 2008, Oracle. All rights reserved.

Setting IDE Preferences


Select Tools > Preferences to set options:

2 - 19

Copyright 2008, Oracle. All rights reserved.

Getting Started in JDeveloper

To build an application in JDeveloper, you need to define:


An application
One or more projects
A database connection

2 - 20

Copyright 2008, Oracle. All rights reserved.

Creating an Application in JDeveloper

2 - 21

Copyright 2008, Oracle. All rights reserved.

Using the Application Overview

Application Overview shows


details about the applications:
Java files
XML files
Offline databases
Page flows
Web pages
ADF Business Components
ADF binding files
EJB 3.0
Web services

2 - 23

It enables you to:


Access:

Cue cards
Tutorials
Samples
Guided steps
Detailed help

Create new objects

Copyright 2008, Oracle. All rights reserved.

Creating a Project in JDeveloper

2 - 24

Copyright 2008, Oracle. All rights reserved.

Creating Database Connections

Two types:
IDE:
Available to be added to any application
Create in Database Navigator or Resource Palette
To add to an application, drag to Application Resources or to
an application in Database Navigator

Application:
Owned by a specific application
Create in Database Navigator or Application Resources

2 - 26

Copyright 2008, Oracle. All rights reserved.

Creating a Database Connection


in JDeveloper

2 - 27

Copyright 2008, Oracle. All rights reserved.

Describing the Course Application

2 - 29

Copyright 2008, Oracle. All rights reserved.

Presenting the Storefront


User Interface

2 - 30

Copyright 2008, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


List benefits that JDeveloper provides for application
development
Use the features of the JDeveloper IDE
Define IDE preferences
Create applications, projects, and connections in
JDeveloper

2 - 31

Copyright 2008, Oracle. All rights reserved.

Practice 2 Overview:
Using JDeveloper
This practice covers the following topics:
Setting preferences for the IDE
Creating a JDeveloper application, project, and database
connection
Viewing the course application in a browser and identifying
functionality

2 - 32

Copyright 2008, Oracle. All rights reserved.

Modeling the Database Schema


(optional)

Copyright 2008, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do the


following:
Describe JDevelopers tool for database modeling
Create a schema model
Modify the schema model
Reconcile the modifications to the database
Import database object definitions to an offline database
Reconcile offline database objects with the database

3-2

Copyright 2008, Oracle. All rights reserved.

Modeling Database Schemas

With JDevelopers database modeler, you can:


Create a schema model
Modify the schema model
Reconcile changes to the database

3-3

Copyright 2008, Oracle. All rights reserved.

Goals of Database Modeling

Database modeling can help you achieve the following goals:


For existing database objects:
Visualize the schema to help analyze whether it meets
requirements.
Make any necessary modifications.

For new database objects:


Design schema to support business requirements.
Generate DDL to create the required database objects.

3-4

Copyright 2008, Oracle. All rights reserved.

Characteristics of the JDeveloper Database


Modeler
With the JDeveloper Database Modeler you can:

3-5

Model existing objects, such as

Use Property Inspector to set


properties on diagram and its
tables and foreign keys, by
objects
dragging from Database
Navigator

Create new objects by


dragging from
Component Palette

Copyright 2008, Oracle. All rights reserved.

Database Modeling Tools in JDeveloper

You can work with database objects in the following ways:


Online: Create and modify schema objects directly in a
database through a JDeveloper connection.
Offline:
Model metadata for database objects outside the context of a
database schema.
Import objects from online database.
Generate changes to online schemas.

Diagrammer:
Create and modify objects by dragging from Component
Palette and Database Navigator.
Import objects from offline database model.
Generate changes to online schemas.

3-6

Copyright 2008, Oracle. All rights reserved.

Modeling Database Objects Offline

You can create offline database definitions in the following


ways:
Create new offline database objects
Copy from database with filters

3-7

Copyright 2008, Oracle. All rights reserved.

Creating a New Offline Database

To create a definition for an offline database in which you


can model database objects, perform the following steps:
1. In the Application Navigator, right-click a project and choose
New to display the New Gallery.
2. In the New Gallery, expand Database Tier, and select Offline
Database Objects.
3. Select Offline Database to launch the Create Offline
Database Wizard.
4. In the pages of the wizard, enter properties for the database,
such as its name.

3-8

After an offline database is created, you can create various


database object definitions within it.
Copyright 2008, Oracle. All rights reserved.

Creating New Schema


Objects in an Offline Database
Create new schema objects in an offline database by using
wizards to define:
Functions
Materialized views and view logs
Packages
Procedures
Sequences
Synonyms
Tables
Triggers
Types
Views
3-9

Copyright 2008, Oracle. All rights reserved.

Creating a Database Diagram

3 - 10

Copyright 2008, Oracle. All rights reserved.

Importing Tables to the Diagram


from an Offline Database

3 - 11

Copyright 2008, Oracle. All rights reserved.

Editing Objects on the Diagram


In-place editing:
Edit Table dialog box:

3 - 12

Copyright 2008, Oracle. All rights reserved.

Generating Changes from the Diagram


to the Database

Invoke wizard.
In the wizard:

3 - 13

Select objects.
Specify operation.
Set database options.
Set SQL script options.

SQL script opens in


editor;
right-click to run it.

Copyright 2008, Oracle. All rights reserved.

Reconciling Changes to the Database

Choosing ALTER with Manual Reconcile enables you to


choose changes to be generated to the database.

3 - 14

Copyright 2008, Oracle. All rights reserved.

Generating Changes from the Offline Database


Object to the Database
To generate imported offline database objects to the database:
Right-click the object
in the Applications
Navigator
Select Generate To
Select the JDeveloper
connection, or choose
to create a SQL script
or SXML

3 - 15

Copyright 2008, Oracle. All rights reserved.

Importing Database Objects Without a Diagram

You can import database


objects to an offline
database without using a
diagram:

3 - 16

Copyright 2008, Oracle. All rights reserved.

Presenting the Storefront Schema

3 - 17

Copyright 2008, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


Describe JDevelopers tool for database modeling
Create a schema model
Modify the schema model
Reconcile the modifications to the database
Import database object definitions to an offline database
Reconcile offline database objects with the database

3 - 18

Copyright 2008, Oracle. All rights reserved.

Practice 3 Overview:
Modeling the Schema for the Course Application
(optional)
This practice covers the following topics:
Creating a database diagram
Adding existing schema objects to the diagram
Adding a new database object to the diagram
Creating the DDL to add the new object to the database

3 - 19

Copyright 2008, Oracle. All rights reserved.

Building a Business Model


with
ADF Business Components

Copyright 2008, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do the


following:
Describe the role of ADF Business Components in building
a business service
Explain the architecture of ADF BC
Identify the types of components that cooperate to provide
the business service implementation
Use JDeveloper design-time facilities for ADF BC
Explain how ADF BC components are used in a Web
application

4-2

Copyright 2008, Oracle. All rights reserved.

Describing ADF Business Components (ADF BC)

ADF Business Components (ADF BC) characteristics:


Provides data interaction and business logic execution
Maps to a data source, such as an Oracle database
Enables 4GL development
Wizard-based or visual development
Implemented in metadata, not code

Enables business logic development


Predefined Java methods for any event
Declarative business rules

4-3

Copyright 2008, Oracle. All rights reserved.

ADF BC Implementation Architecture

Characteristics of the Business Components layer of ADF:


Based on standard Java and XML
Works with any application server or database
Implements popular design patterns
Components are organized into packages
Prebuilt code in two main packages:
oracle.jbo
oracle.jbo.server

4-4

Components metadata driven with optional Java code

Copyright 2008, Oracle. All rights reserved.

Types of ADF Business Components

StorefrontAM
Customer

CustVO

CustomerOrder

4-5

CustomerEO

OrderEO

AllOrders

OrdVO

Application Module
with View
Object Instances

View
Objects
and
View
Link

LineItemEO
Entity Objects
and
Associations

Copyright 2008, Oracle. All rights reserved.

Creating ADF Business Components

You can create ADF Business


Components by:
Creating a
Business
Components
Diagram
Using the wizards

4-6

Copyright 2008, Oracle. All rights reserved.

The Create Business Components from Tables


Wizard: Entity Objects

Specify
Package.
Restrict
query.

Rename
entity.

4-7

Copyright 2008, Oracle. All rights reserved.

The Create Business Components from Tables


Wizard: Updatable View Objects

Specify
Package.

Rename
view object.

4-8

Copyright 2008, Oracle. All rights reserved.

The Create Business Components from Tables


Wizard: Read-Only View Objects

Specify
Package.

Rename
view object.

4-9

Copyright 2008, Oracle. All rights reserved.

The Create Business Components from Tables


Wizard: Application Module

Create an
application
module?
Name
application
module.

4 - 10

Copyright 2008, Oracle. All rights reserved.

The Create Business Components from Tables


Wizard: Diagram

Create?
Name
diagram
Choose
objects

4 - 11

Copyright 2008, Oracle. All rights reserved.

Examining Created Objects

4 - 12

Copyright 2008, Oracle. All rights reserved.

Testing the Data Model

4 - 13

Copyright 2008, Oracle. All rights reserved.

Exposing the Application Module to the User


Interface
Oracle ADF Model:
Abstracts service implementation from clients
EJB, Web services, TopLink, Java classes, ADF BC
JSP, mobile

Provides declarative data


binding:
Implements JSR 227
Uses EL (expression
language)
Separates view from
business service
Creates data control
from application module

4 - 14

Copyright 2008, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


Describe the role of ADF Business Components in building
a business service
Explain the architecture of ADF BC
Identify the types of components that cooperate to provide
the business service implementation
Use JDeveloper design-time facilities for ADF BC
Explain how ADF BC components are used in a Web
application

4 - 15

Copyright 2008, Oracle. All rights reserved.

Practice 4 Overview:
Building a Business Model
This practice covers the following topics:
Using the Business Components from Tables Wizard to
quickly build part of the data model
Testing the model with the Business Components Browser

4 - 16

Copyright 2008, Oracle. All rights reserved.

Querying and Persisting Data

Copyright 2008, Oracle. All rights reserved.

Objectives
After completing this lesson, you should be able to do the
following:
Describe the characteristics of an ADF BC view object
Create ADF BC view objects that can be used for data
queries in a Web application
Modify SQL statements in view objects
Explain how entity objects relate to database tables
Describe the persistence mechanism of entity objects
Create entity objects from database tables
Create associations between entity objects
Create updatable view objects based on entity objects
Link view objects to one another
Refactor business components
5-2

Copyright 2008, Oracle. All rights reserved.

Using View Objects


Updatable
View Object
CustomerStatus
ID
Name
Status

CustomerStatusRO

5-3

Copyright 2008, Oracle. All rights reserved.

Characteristics of a View Object (VO)


View objects:
Represent a query
Are used for joining, filtering, projecting, and sorting
business data
Enable you to have a view of data that is specific to one
part of your application
Can be constructed from a SQL statement, static values,
or populated programmatically
Can also be based on any number of entity objects
View
objects

Reusable
Query Components

PriorityOrderVO

5-4

ItemListVO

Copyright 2008, Oracle. All rights reserved.

Creating View Objects for Queries

1 Invoke the Create View Object


Wizard.

5-5

Initialize project for


Business Components.

Copyright 2008, Oracle. All rights reserved.

Creating View Objects for Queries

3 Specify package, name, and kind of data.


5-6

Copyright 2008, Oracle. All rights reserved.

Creating View Objects for Queries

5-7

Enter the SQL query,


or use Query Builder.

Copyright 2008, Oracle. All rights reserved.

Creating View Objects for Queries


5

5-8

Create bind variables


and set attribute
properties as needed.

Copyright 2008, Oracle. All rights reserved.

Creating View Objects for Queries


6

5-9

Optionally, create Java


classes (if adding
programmatic business
logic).

Optionally, create a new


application module or
add to an existing one.

Copyright 2008, Oracle. All rights reserved.

Testing View Objects with the Business


Components Browser
1

Run the application module.

5 - 10

Provide
connection
details.

Double-click the
view object
instance.

Copyright 2008, Oracle. All rights reserved.

Characteristics of an Entity Object (EO)

Entity objects:
Represent a row in a database table or other data source
Handle database caching
Contain attributes representing the database columns
Encapsulate attribute-level and entity-level validation logic
Can contain custom business methods

CustomerEO
5 - 11

Copyright 2008, Oracle. All rights reserved.

OrderEO

Using Entity Objects to Persist Data


Entity
object

CustomerEO
Id
Name
Status
Email

Attributes

Status List
(Gold Silver Platinum)

Validation
rule

CUSTOMERS
Database
table

5 - 12

ID

NAME

STATUS

201
202

Steve
Mike

Gold
Silver

Email
msmith@company.com
dgonzales@company.com

Copyright 2008, Oracle. All rights reserved.

Creating Entity Objects


The Create Entity Object Wizard:
Attributes page
Name page

Attribute Settings page

5 - 13

Copyright 2008, Oracle. All rights reserved.

Creating Entity Objects


from Tables, Views, or Synonyms
When you create an entity object, JDeveloper:
Interrogates the data dictionary for information
Infers primary key, or creates one from RowID

Creates implicit validators for database constraints


Creates the XML component definition file
(<EO_name>.xml)

Creates optional Java files if selected, such as entity object


class <EO_name>Impl.java

Generates associations based on foreign keys, if


applicable (<Association_name>FkAS.xml)

5 - 15

Copyright 2008, Oracle. All rights reserved.

Synchronizing an Entity Object


with Changes to Its Database Table

ALTER
ALTER TABLE
TABLE USERS
USERS
ADD
(security_question
ADD (security_question VARCHAR2(60));
VARCHAR2(60));

5 - 16

Copyright 2008, Oracle. All rights reserved.

Generating Database Tables from Entity Objects

Right-click package and


select Create Database
Objects.

In Create Database Objects


dialog box, select objects to
create.

Use with caution!

5 - 17

Copyright 2008, Oracle. All rights reserved.

Characteristics of Associations

5 - 18

Define a relationship between EOs


Facilitate access to data
in related entity objects
May be based on database
constraints
May be independent of database
constraints
Are used in defining
validations and LOV metadata
Consist of a source (master)
and a destination (detail) entity
PersonEO

OrdersPersonsFkAS

OrderEO

Source

Association

Destination

Copyright 2008, Oracle. All rights reserved.

Creating Associations
Use the Create Association Wizard:
Name page

Association Properties page

Entity Object page

Association Query page

5 - 19

Copyright 2008, Oracle. All rights reserved.

Association Types

Association
Entities are related but not
completely dependent.
Either end of the association can
exist without the other.
Customer
Either can be deleted without
deleting the other.

Composition
Destination entity is completely
dependent on source entity.
Source entity owns destination
entity.
No destination entity can be
created without the owning entity
existing first.
Source entity cannot be deleted
without deleting all its associated
destination entities.

5 - 20

Order

Order

Copyright 2008, Oracle. All rights reserved.

Order Item

Characteristics of
Updatable View Objects
Entity Object

View Object

CustomerEO

CustomerStatusVO
select name, status
from customers
order by name
Name

ID
Name
Status
Email

5 - 21

Mike
Steve

ID

NAME

STATUS

EMAIL

201
202

Steve
Mike

Gold
Silver

Steve@abc.com
Mike@abc.com

Copyright 2008, Oracle. All rights reserved.

Status
Silver
Gold

Database
Table

Creating Updatable View Objects


Use the Create View Object Wizard:

Name page
Entity Objects page
5 - 22

Copyright 2008, Oracle. All rights reserved.

Creating Updatable View Objects:


Attributes and Settings

Attributes page

Attribute Settings page

5 - 23

Copyright 2008, Oracle. All rights reserved.

Creating Updatable View Objects:


Query

5 - 25

Copyright 2008, Oracle. All rights reserved.

Creating Updatable View Objects:


Additional Settings

5 - 27

Copyright 2008, Oracle. All rights reserved.

Interaction Between Views and


Entities: Retrieving Data

The view object queries the database directly.


Data retrieved by the query is saved to the entity objects
cache.
EO
VO

Select

Nonpersistent attributes are stored and retrieved from the


view objects cache.
VO
Select
(12*monthly_sal)

5 - 28

Copyright 2008, Oracle. All rights reserved.

Interaction Between Views and


Entities: Updating Data

The view object updates the entity objects cache.


The entity object commits to the database.

Commit

5 - 29

EO

Update

Copyright 2008, Oracle. All rights reserved.

VO

Creating a Join View Object

Join is based on
association
between
entities.

5 - 30

Copyright 2008, Oracle. All rights reserved.

Including Reference Entities


in Join View Objects

5 - 31

Copyright 2008, Oracle. All rights reserved.

Creating MasterDetail Relationships


with View Objects
Different types of masterdetail relationships are
supported.

Master to Single
Detail

5 - 32

Master to Multiple
Details

Cascading Master
Detail to Any Depth

Copyright 2008, Oracle. All rights reserved.

Linking View Objects


Use the Create View Link
Wizard to create a view link
between CustomerVO and
OrderVO view objects.

Joined queries and view links


display information differently.

5 - 33

Copyright 2008, Oracle. All rights reserved.

Comparing Join View Queries with View Links

Join view queries:


Contain all attributes from main and referenced entities in
a single row
WHERE clause relates key from main table with foreign key
in referenced tables
View link queries:
Use a bind variable to relate detail records to key for
selected master record
Append WHERE clause with bind variable to the base SQL
query for the source or destination view object

5 - 34

Copyright 2008, Oracle. All rights reserved.

Refactoring Objects

With refactoring you can:


Rename objects, such as
associations and view links
Move objects or packages
to a different package
Change all references
throughout the application

5 - 35

Copyright 2008, Oracle. All rights reserved.

Summary
In this lesson, you should have learned how to:
Describe the characteristics of an ADF BC view object
Create ADF BC view objects that can be used for data
queries in a Web application
Modify SQL statements in view objects
Explain how entity objects relate to database tables
Describe the persistence mechanism of entity objects
Create entity objects from database tables
Create associations between entity objects
Create updatable view objects based on entity objects
Link view objects to one another
Refactor to move and rename associations and links
5 - 36

Copyright 2008, Oracle. All rights reserved.

Practice 5 Overview:
Creating Entity Objects and View Objects
This practice covers the following topics:
Creating read-only view objects to support LOVs
Creating entity objects for tables that need to be updated
in the application
Creating associations
Creating updatable view objects
Creating view links
Refactoring associations and links

5 - 37

Copyright 2008, Oracle. All rights reserved.

Exposing Data

Copyright 2008, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do the


following:
Explain the role of application modules
Describe the characteristics of application modules
Create an application module
Explain how application modules can manage:
Business components transactions
Application state

6-2

Explain the role of the ADF Model

Copyright 2008, Oracle. All rights reserved.

Oracle ADF Application Module (AM)

An Oracle ADF Business Component that encapsulates:


Active data model
Business service methods
for a logical unit of work, related to an end-user task.
OrderAM
PersonsVO1
OrdersVO1 via PersonOrderVL

6-3

Copyright 2008, Oracle. All rights reserved.

Characteristics of an Application Module

6-4

Represents the data model that the client uses and has
one connection to the database
Provides transactional context for the application
Enables you to gather data customized to a client interface
so that data can be retrieved in one network round-trip
Can contain other application modules, called nested
application modules
Keeps track of all changes that affect data in the database
Provides remotely accessible methods to implement
application module behavior
Is deployable in multiple configurations
Can be easily reused in business logic tiers of other
applications
Copyright 2008, Oracle. All rights reserved.

Creating an Application Module

1. In the New Gallery Business Tier, choose ADF Business


Components > Application Module to invoke the Create
Application Module Wizard.
2. Specify a name for the application module and identify the
package where it should belong.
3. Define the data model for
the application module by
selecting view objects
from a tree of available
view objects.

6-5

Copyright 2008, Oracle. All rights reserved.

Defining the Data Model for the


Application Module

6-6

Copyright 2008, Oracle. All rights reserved.

Using MasterDetail View Objects


in Application Modules
First level: Independent VO instances
OrderAMDataControl
CustomerVO1
OrderVO1 via CustomerToOrder
OrderVO2

Subordinate levels: VO instances accessed via a view link


display both master and detail.

6-7

Copyright 2008, Oracle. All rights reserved.

Determining the Size of an


Application Module
Is it better to have one big application module, or lots of little
ones?
An application module is a logical unit of work.
Let use cases drive application module decisions:
Can be grouped by domain business objects involved
Grouped by the user-oriented view of business data required

6-8

Consider the possibility of reuse of the application module.


Consider service or transaction flow.

Copyright 2008, Oracle. All rights reserved.

Business Components Transactions

Application modules:
Handle transaction and concurrency support
Use a single database connection
Provide transaction context for updates, deletes, and inserts
for all view objects in the application module, so all are
committed or rolled back at once

6-9

For nested application modules, the outermost application


module provides the transaction context for the others.
No coding is required unless you want to modify the
default behavior.

Copyright 2008, Oracle. All rights reserved.

Application Module Pooling

Application module pooling:


Enables users to share application modules
Manages application state
Provides the same instance or one with an identical state
when requested by an application with managed state
Order Application Module Pool
M
rA
e
d
Or

6 - 12

Available

M
rA
e
d
r

Referenced: Id like to be
used by User2

M
rA
e
d
r

Unavailable: Im busy
right now!

Copyright 2008, Oracle. All rights reserved.

Managing Application State

AM passivation saves transaction state in an XML


document stored in database
AM activation retrieves saved transaction state
Performed automatically when needed
51
10

Saved
state

10
51

Passivation

6 - 13

Activation

Copyright 2008, Oracle. All rights reserved.

10
51

The Role of ADF Model


Desktop
ADF Swing

Browser-based
JSP

Office

JSF

Struts

ADF Faces / DVT

JSF/ADF Task Flow

ADF Bindings

Java

EJB

TopLink

BAM

BPEL

ADFbc
Web
Services

View

Controller

Model

BI

Essbase

Portlets

Business
Services

Data
Services
Relational Data

6 - 14

XML Data

Legacy Data

Copyright 2008, Oracle. All rights reserved.

Packaged Apps

Describing the Course Application: Database


Objects

6 - 15

Copyright 2008, Oracle. All rights reserved.

Describing the Course Application: View Objects

View objects exposed in


application modules

6 - 16

View objects used


for LOVs in the UI

Copyright 2008, Oracle. All rights reserved.

Describing the Course Application: Data Controls


1

4
2

6
6 - 18

Copyright 2008, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


Explain the role of application modules
Describe the characteristics of application modules
Create an application module
Explain how application modules can manage:
Business components transactions
Application state

6 - 19

Explain the role of the ADF Model

Copyright 2008, Oracle. All rights reserved.

Practice 6 Overview:
Defining Application Modules
This practice covers the following topics:
Packaging view objects in application modules to provide
the data needs of the application
Testing the business components

6 - 20

Copyright 2008, Oracle. All rights reserved.

Declaratively Customizing Data Services

Copyright 2008, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do the


following:
Describe how to declaratively change data behavior
Declaratively modify view objects, entity objects, and
application modules
Create view accessors
Create LOVs

7-2

Copyright 2008, Oracle. All rights reserved.

Using Groovy
Groovy
Is a Java-like scripting language that is dynamically
compiled and evaluated at run time
Enables you to use declarative expressions, instead of
writing Java code, for the following types of values in the
ADF BC data model:

7-3

Bind variables
Calculated attributes
Attribute default values
View criteria
View accessor bind variables
Validation
Validation message token binding
Copyright 2008, Oracle. All rights reserved.

Using Groovy Syntax in ADF

Java Code

Equivalent
Groovy script

((Number)getAttribute("Sal").multiply(new
Number(0.10))

Sal * 0.10

((Date)getAttribute("PromotionDate")).compareTo PromotionDate
((Date)getAttribute("HireDate")) > 0
> HireDate

Reserved name adf gets objects from framework:


adf.context
adf.object
adf.error
adf.currentDate
adf.currentDateTime
7-4

Copyright 2008, Oracle. All rights reserved.

Internationalizing the Data Model

When an application is internationalized, the UI displays


text based on users
browser settings.
To use resource
bundles for translatable
strings you can:
Create one bundle
per file or project
Translate and
append
_<locale>
to file name
Configure the UI

7-6

Copyright 2008, Oracle. All rights reserved.

Editing Business Components


Editors provide access to business component properties:

Property Inspector
Entity Object Editor
7-7

Copyright 2008, Oracle. All rights reserved.

Modifying the Default Behavior of Entity Objects

With declarative settings, you can:


Define attribute control hints
Synchronize columns with
trigger-assigned values
Use alternate key entity
constraints
Validate user input (presented in the lesson titled
Validating User Input)

7-8

Copyright 2008, Oracle. All rights reserved.

Modifying the Default Behavior of Entity Objects

With declarative settings, you can:


Define attribute control hints
Synchronize columns with
trigger-assigned values
Use alternate key entity
constraints
Validate user input (presented in the lesson titled
Validating User Input)

7-9

Copyright 2008, Oracle. All rights reserved.

Defining Attribute Control Hints


1

7 - 10

Copyright 2008, Oracle. All rights reserved.

Modifying the Default Behavior of Entity Objects

With declarative settings, you can:


Define attribute control hints
Synchronize columns with
trigger-assigned values
Use alternate key entity
constraints
Validate user input (presented in the lesson titled
Validating User Input)

7 - 12

Copyright 2008, Oracle. All rights reserved.

Synchronizing with Trigger-Assigned Values

To synchronize when database trigger updates a column,


use Refresh After Update or Refresh After Insert.
To use a database sequence to generate a primary key:
Set data type of
attribute to
DBSequence
Set Updatable to
Never
Refresh After
Insert is selected
automatically

7 - 13

Copyright 2008, Oracle. All rights reserved.

Modifying the Default Behavior of Entity Objects

With declarative settings, you can:


Define attribute control hints
Synchronize columns with
trigger-assigned values
Use alternate key entity
constraints
Validate user input (presented in the lesson titled
Validating User Input)

7 - 15

Copyright 2008, Oracle. All rights reserved.

Using Alternate Key


Entity Constraints
Alternate keys are:
Used for efficient uniqueness checks
Used for direct row lookups with findByKey() methods

7 - 16

Different from primary keys or unique keys

Copyright 2008, Oracle. All rights reserved.

Creating Alternate Key


Entity Constraints
Use the New Entity Constraint Wizard:
1

7 - 17

Copyright 2008, Oracle. All rights reserved.

Creating Alternate Key


Entity Constraints

7 - 18

Copyright 2008, Oracle. All rights reserved.

Editing View Objects

7 - 19

Copyright 2008, Oracle. All rights reserved.

Modifying the Default Behavior of View Objects

With declarative settings, you can:


Define attribute control hints
Perform calculations
Restrict the columns retrieved by a query
Change the order of queried rows
Restrict the rows retrieved by a query
Retain and reuse a row set
Define a list of values

7 - 20

Copyright 2008, Oracle. All rights reserved.

Modifying the Default Behavior of View Objects

With declarative settings, you can:


Define attribute control hints
Perform calculations
Restrict the columns retrieved by a query
Change the order of queried rows
Restrict the rows retrieved by a query
Retain and reuse a row set
Define a list of values

7 - 21

Copyright 2008, Oracle. All rights reserved.

Defining View Object Control Hints

Same as for entity objects


Overrides EO control hint settings: Use in cases such as:
The same data must be displayed differently in different
views.
OR
The VO uses the same attribute twice as in a recursive
relationship.

Can also be used for transient attributes defined at VO


level

7 - 22

Copyright 2008, Oracle. All rights reserved.

Modifying the Default Behavior of View Objects

With declarative settings, you can:


Define attribute control hints
Perform calculations
Restrict the columns retrieved by a query
Change the order of queried rows
Restrict the rows retrieved by a query
Retain and reuse a row set
Define a list of values

7 - 24

Copyright 2008, Oracle. All rights reserved.

Performing Calculations

Setting recalculation
dependencies

7 - 25

Copyright 2008, Oracle. All rights reserved.

Modifying the Default Behavior of View Objects

With declarative settings, you can:


Define attribute control hints
Perform calculations
Restrict the columns retrieved by a query
Change the order of queried rows
Restrict the rows retrieved by a query
Retain and reuse a row set
Define a list of values

7 - 26

Copyright 2008, Oracle. All rights reserved.

Restricting and Reordering


the Columns Retrieved by a Query

Use the Attributes tab of editor to delete or reorder


attributes.
Query changes to reflect the new SELECT clause.

Original query

Deleting attributes

Modified
query
Reordering attributes
7 - 27

Copyright 2008, Oracle. All rights reserved.

Modifying the Default Behavior of View Objects

With declarative settings, you can:


Define attribute control hints
Perform calculations
Restrict the columns retrieved by a query
Change the order of queried rows
Restrict the rows retrieved by a query
Retain and reuse a row set
Define a list of values

7 - 28

Copyright 2008, Oracle. All rights reserved.

Changing the Order of Queried Rows

To change the order, perform the following steps:


1. Click the Query tab of the view object editor.
2. Click Edit in the Query section of the panel.
3. Click Edit in the Edit Query dialog box.
4. In the Order By dialog box, select the columns for sorting
the rows retrieved by the query.

7 - 29

Copyright 2008, Oracle. All rights reserved.

Modifying the Default Behavior of View Objects

With declarative settings, you can:


Define attribute control hints
Perform calculations
Restrict the columns retrieved by a query
Change the order of queried rows
Restrict the rows retrieved by a query
Retain and reuse a row set
Define a list of values

7 - 30

Copyright 2008, Oracle. All rights reserved.

Restricting the Rows Retrieved by a Query

Add a WHERE
clause:

7 - 31

Copyright 2008, Oracle. All rights reserved.

Using View Criteria


(Structured WHERE Clauses)

7 - 32

You can use the view criteria to define complex query


criteria at design time.
You can specify execution mode.

Copyright 2008, Oracle. All rights reserved.

Using Parameterized WHERE Clauses

Edit the
view object.

7 - 34

Edit the SQL


query.

Copyright 2008, Oracle. All rights reserved.

Add a
parameterized
WHERE clause.

Using Named Bind Variables

7 - 35

Copyright 2008, Oracle. All rights reserved.

Modifying the Default Behavior of View Objects

With declarative settings, you can:


Define attribute control hints
Perform calculations
Restrict the columns retrieved by a query
Change the order of queried rows
Restrict the rows retrieved by a query
Retain and reuse a row set
Define a list of values

7 - 36

Copyright 2008, Oracle. All rights reserved.

Retaining and Reusing a


View Link Accessor Row Set
Retaining a view link accessor row set:
Enables caching of the view link
accessor RowSet object

Avoids overhead of creating new


detail RowSet objects

May be advisable when application


makes numerous calls to the same
view link accessor attributes
Can be implemented declaratively
in the Tuning section of the
General tab for view object that is
the source for the view link

7 - 37

Copyright 2008, Oracle. All rights reserved.

Modifying the Default Behavior of View Objects

With declarative settings, you can:


Define attribute control hints
Perform calculations
Restrict the columns retrieved by a query
Change the order of queried rows
Restrict the rows retrieved by a query
Retain and reuse a row set
Define a list of values

7 - 38

Copyright 2008, Oracle. All rights reserved.

Creating View Accessors

7 - 39

View accessors are used for validation and LOVs.


Create on View Accessors page of EO or VO editor

Copyright 2008, Oracle. All rights reserved.

Using a List of Values (LOV)

LOVs:
Are defined on view object attributes
Use view accessors as a data source:
For attributes mapped to an entity object attribute:

Use the view accessor that is used by the entity object


attributes Key Exists validator.
Extend the view accessor at the view object level for UI hints or
bind expressions if required.

For transient attributes, you can define a new view accessor.

7 - 40

Copyright 2008, Oracle. All rights reserved.

Defining the View Accessor for the List of Values


1

7 - 41

Copyright 2008, Oracle. All rights reserved.

Defining the List of Values

7 - 42

Copyright 2008, Oracle. All rights reserved.

Modifying Application Modules

The Application Module editor has the following tabs:


General: Set tuning parameters, define custom properties.
Data Model: Refine the data model.
Java: Create Java classes, expose methods to the client
interface.
EJB Session Bean: Enable EJB session bean support.
Configurations: Create or modify sets of configuration
parameters.

7 - 43

Copyright 2008, Oracle. All rights reserved.

Changing the Locking Behavior


of an Application Module

7 - 44

Default locking behavior is pessimistic.


Optimistic locking is recommended for Web applications.
Change configuration: Set jbo.locking.mode to
optimistic or optupdate.

Copyright 2008, Oracle. All rights reserved.

Summary

In this lesson, you should have learned to:


Describe how to declaratively change data behavior
Declaratively modify view objects, entity objects, and
application modules
Create view accessors
Create LOVs

7 - 45

Copyright 2008, Oracle. All rights reserved.

Practice 7 Overview:
Declaratively Modifying Business Components
This practice covers the following topics:
Changing data labels and formats
Specifying that an entity object should use a database
sequence to generate the primary key
Designating history columns
Creating bind variables and view criteria
Creating join view objects
Defining an LOV

7 - 46

Copyright 2008, Oracle. All rights reserved.

Programmatically Customizing Data Services

Copyright 2008, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do the


following:
Generate Java classes for business components
Override class methods
Implement programmatic modifications
Add service methods to an application module
Create a test client
Use business component client APIs

8-2

Copyright 2008, Oracle. All rights reserved.

Generating Java Classes for Adding Code

To generate a Java class:


1. On the business component editors Java page, click Edit
2. Select classes to generate

8-3

Copyright 2008, Oracle. All rights reserved.

Programmatically Modifying the Default


Behavior of Entity Objects
Many modifications are possible with coding, such as:
Traversing associations
Overriding base class methods

8-4

Copyright 2008, Oracle. All rights reserved.

The Supporting Entity Java Classes

EntityImpl
The entity class
Represents a row
Provides getter and
setter methods

EntityDefImpl
The entity definition class
Represents the whole entity
Can be used to modify the entity definition

EntityCollImpl
Represents the cached set of rows from the entity
Not usually necessary to modify or override methods in this
class

8-5

Copyright 2008, Oracle. All rights reserved.

Traversing Associations
OrderEO

PersonEOToOrderEO

PersonEO

getPersonEO()
setPersonEO()
getPersonEmail()

getOrderEO()
getEmail()

Accessor in source
to get destination

Accessors in destination
to get and set source

The destination entitys EntityImpl.java file contains


methods to get and set the source entity. For example,
OrderEOImpl.java contains getPersonEO() and
setPersonEO().
You could add a method to OrderEO.java to get the
email address of the associated person (customer):
public String getPersonEmail() {
return getPersonEO().getEmail(); }

8-7

Copyright 2008, Oracle. All rights reserved.

Overriding Base Class Methods

You can override methods in


the base classes for objects.
For example, you can override
methods in EntityImpl.java,
such as:
doDML(): Use it to log
changes in another entity.
beforeCommit(): Use it to
validate multiple instances of the
same entity.
remove(): Use it to log a
deletion in an entity.
8-8

Copyright 2008, Oracle. All rights reserved.

Overriding Base Class Methods Example:


Updating a Deleted Flag
Instead of Deleting Rows
// In <Entity name>Impl.java

public void remove() {


setDeleted("Y");
super.remove();
}

protected void doDML(int operation,


TransactionEvent e) {
if (operation == DML_DELETE) {
operation = DML_UPDATE;
}
super.doDML(operation, e);
}

Overriding the remove() and doDML() methods

8-9

Copyright 2008, Oracle. All rights reserved.

Overriding Base Class Methods Example:


Eagerly Assigning Values
from a Database Sequence

1
2
3
4
5

// In ProductEOImpl.java
import oracle.jbo.server.SequenceImpl;
// Default ProdId value from PRODUCTS_SEQ sequence at
protected void initDefaults() {
super.initDefaults();
SequenceImpl sequence = new
SequenceImpl("PRODUCTS_SEQ",getDBTransaction());
DBSequence dbseq = new
DBSequence(seq.getSequenceNumber());
populateAttributeAsChanged(ProdId, dbseq);
}

Overriding the initDefaults() method

8 - 10

Copyright 2008, Oracle. All rights reserved.

Programmatically Modifying the Default


Behavior of View Objects
For example, you can:
Change the WHERE or ORDER_BY clause programmatically

8 - 11

Retain and reuse a row set


Traverse view links

Copyright 2008, Oracle. All rights reserved.

The Supporting View Object Java Classes

ViewObjectImpl
The view class
Provides methods
to manage the row
set

ViewDefImpl
The view definition class
Represents the whole view
Can be used to modify the view definition

ViewRowImpl
The view object row class
Instantiated for each record returned by the query
Provides attribute accessors

8 - 12

Copyright 2008, Oracle. All rights reserved.

Examining View Object Methods

Javadoc for the


ViewObjectImpl class

8 - 13

Copyright 2008, Oracle. All rights reserved.

Changing View Object


WHERE or ORDER BY Clause at Run Time
Database
Table
CustomerStatusRO
ID

NAME

STATUS

201
202
201

Susan
Mike
Steve

Platinum
Silver
Gold

select name,
status
from customers
order by name

ViewObject vo = am.findViewObject
("CustomerStatusRO");
String whereClause = "NAME < 'Su'";
String orderByClause = "STATUS";
vo.setWhereClause(whereClause);
vo.setOrderBy(orderByClause);

8 - 16

Copyright 2008, Oracle. All rights reserved.

Name

Status

Mike
Steve
Susan

Silver
Gold
Platinum

Name

Status

Steve
Mike

Gold
Silver

Using Named Bind Variables at Run Time

Assigning values to named bind variables at run time:


ViewObject
ViewObject vo
vo == am.findViewObject("PersonView1");
am.findViewObject("PersonView1");
vo.setNamedWhereClauseParam("TheName","alex%");
vo.setNamedWhereClauseParam("TheName","alex%");
vo.executeQuery();
vo.executeQuery();

Adding named bind variables at run time:


vo.setWhereClause("person_type_code
vo.setWhereClause("person_type_code == :PersonType");
:PersonType");
vo.defineNamedWhereClauseParam("PersonType",
vo.defineNamedWhereClauseParam("PersonType", null,
null, null);
null);
vo.setNamedWhereClauseParam("PersonType","STAFF");
vo.setNamedWhereClauseParam("PersonType","STAFF");
//
// execute
execute the
the query,
query, process
process the
the results,
results, and
and then
then later...
later...
vo.setNamedWhereClauseParam("PersonType","CUST");
vo.setNamedWhereClauseParam("PersonType","CUST");
//
// execute
execute the
the query,
query, process
process the
the results
results

8 - 18

Copyright 2008, Oracle. All rights reserved.

Programmatically Retaining
and Reusing a View Link Accessor Row Set
To retain and reuse a view link accessor row set
programmatically:
1. Generate a Java class for the source view object.
2. Override the create() method.
3. Add setViewLinkAccessorRetained(true).
public
public class
class OrderVOImpl
OrderVOImpl extends
extends ViewObjectImpl
ViewObjectImpl {{
public
public OrdersViewImpl()
OrdersViewImpl() {{
}}
@Override
@Override
protected
protected void
void create()
create() {{
super.create();
super.create();
setViewLinkAccessorRetained(true);
setViewLinkAccessorRetained(true);
}}
}}

4. Call reset() each time you reuse the RowSet object.


8 - 19

Copyright 2008, Oracle. All rights reserved.

Traversing Links

Links may be traversed in either direction.


ViewRowImpl.java contains a method to get the
associated row iterator.
For example, OrdersViewRowImpl contains the method:
public
public oracle.jbo.RowIterator
oracle.jbo.RowIterator getOrderItemsView
getOrderItemsView ()
()

8 - 20

Use the methods of RowIterator to move from row to


row and to get individual attribute values.

Copyright 2008, Oracle. All rights reserved.

Application Module Files

Created by default:

Supporting Java classes:

8 - 22

<AppMod>AM.xml: Includes detailed metadata about the


View Objects included
bc4j.xcfg: Contains all the configuration and connection
details
<AppMod>AMImpl.java: Contains all the methods and
behaviors that affect each application module instance
<AppMod>AMDef.java: Contains methods to be used by
all instances of the application module

Copyright 2008, Oracle. All rights reserved.

Centralizing Implementation Details


Best practice is to place code in application module service
methods rather than in multiple clients.

Code to
manipulate
view objects

Client
8 - 23

Application Module
Copyright 2008, Oracle. All rights reserved.

Adding Service Methods


to an Application Module
Service methods:
Are useful for:

Code that is not dependent on a specific view


Performing operations across view object instances
Managing transactions
Dynamically changing the data model

Can be called from the client, requiring very little data


manipulation in the client itself
Are implemented in the application modules class
Are added by:
Adding code to the Java class
Publishing to the client interface

8 - 25

Copyright 2008, Oracle. All rights reserved.

Coding the Service Method

Add the Java code for the method to the


<AM_Name>AMImpl.java file.

8 - 27

Copyright 2008, Oracle. All rights reserved.

Publishing the Service Method

To publish the service method to clients:


1. Open the Application
Module Editor and
select the Java panel
2. Click the Pencil icon
to edit the Client
Interface
3. Shuttle the method
you want to publish
into the Selected list

8 - 28

Copyright 2008, Oracle. All rights reserved.

Testing Service Methods in the Business


Components Browser

Show the AM.


Select the method.
Set parameter values.

Click Execute.
Observe results.

8 - 30

Copyright 2008, Oracle. All rights reserved.

Accessing a Transaction

Transaction and DBTransaction are interfaces that


define database transactions.
Use the methods in these interfaces to access an
application modules transaction. For example:
ApplicationModuleImpl
ApplicationModuleImpl am;
am; ...
...
//
Commit
the
transaction
// Commit the transaction
am.getTransaction().commit();
am.getTransaction().commit();

8 - 31

Copyright 2008, Oracle. All rights reserved.

Committing Transactions
Post phase
1. Validate pending changes.
2. Post updates to the database.

Commit phase
Commit the transaction.

8 - 33

Copyright 2008, Oracle. All rights reserved.

Customizing the Post Phase

Override the entity objects postChanges() method.

Example: For a deleted entity, mark the database row


instead of deleting the data.
public
public void
void postChanges(TransactionEvent
postChanges(TransactionEvent e)
e) {{
if
if (getPostState()
(getPostState() ==
== Entity.STATUS_DELETED)
Entity.STATUS_DELETED) {{
//
// Custom
Custom code
code to
to mark
mark database
database rows,
rows, such
such as
as
//
// by
by updating
updating aa Deleted
Deleted flag
flag in
in the
the record
record
}}
else
else {{
super.postChanges(e);
super.postChanges(e);
}}
}}

8 - 34

Copyright 2008, Oracle. All rights reserved.

Customizing the Commit Phase

Implement a TransactionListener.
Implement beforeCommit() and afterCommit().

Add your listener to the transactions list of


event subscribers.
Alternatively, override the entity objects
beforeCommit() or afterCommit() methods.

Example: In PersonEOImpl, print notification that record is committed:


@Override
@Override
public
public void
void afterCommit(TransactionEvent
afterCommit(TransactionEvent transactionEvent)
transactionEvent) {{
System.out.println("Record
System.out.println("Record committed
committed for
for "" ++
getFirstName()
getFirstName() ++ "" "" ++ getLastName());
getLastName());
super.afterCommit(transactionEvent);
super.afterCommit(transactionEvent);
}}
8 - 35

Copyright 2008, Oracle. All rights reserved.

Using Entity Objects and Associations


Programmatically

Code to manipulate an entity object is typically placed in


an application module class or the class of another entity
object.
Typical tasks that you may need to code:
Finding an entity object by primary key
Updating or removing an existing entity row
Creating a new entity row

8 - 36

Copyright 2008, Oracle. All rights reserved.

Finding an Entity Object


by Primary Key

public
public String
String findOrderID(long
findOrderID(long orderId)
orderId) {{
String
String entityName
entityName == "oracle.fod.storefront.model.entity.OrderEO";
"oracle.fod.storefront.model.entity.OrderEO";
EntityDefImpl
1
EntityDefImpl orderDef
orderDef == EntityDefImpl.findDefObject(entityName);
EntityDefImpl.findDefObject(entityName);

Key
Key orderKey
orderKey == new
new Key(new
Key(new Object[]{orderId});
Object[]{orderId});

EntityImpl
EntityImpl order
order == orderDef.findByPrimaryKey(getDBTransaction(),
orderDef.findByPrimaryKey(getDBTransaction(),
orderKey);
orderKey);
if
if (order
(order !=
!= null)
null) {{
return
}}
return (String)order.getAttribute(ShipToName");
(String)order.getAttribute(ShipToName");
else
return
}} }}
else {{
return null;
null;

8 - 37

Copyright 2008, Oracle. All rights reserved.

Updating or Removing
an Existing Entity Row

public
public void
void updateEmpEmail(long
updateEmpEmail(long empId,
empId, String
String newEmail)
newEmail) {{
EntityImpl
1
EntityImpl emp
emp == retrieveEmployeeById(empId);
retrieveEmployeeById(empId);
if
if (emp
(emp !=
!= null)
null) {{
emp.setAttribute(Email",newEmail);
2
emp.setAttribute(Email",newEmail);
try
try {{
3
getDBTransaction().commit();
}}
getDBTransaction().commit();
catch
catch (JboException
(JboException ex)
ex) {{
getDBTransaction().rollback();
getDBTransaction().rollback();
throw
}}
}} }}
throw ex;
ex;

8 - 38

Copyright 2008, Oracle. All rights reserved.

Creating a New Entity Row

public
public long
long createProduct(String
createProduct(String name,
name, String
String description)
description) {{
String
String entityName
entityName == oracle.
oracle. fod.storefront.
fod.storefront. model.entity.ProductEO";
model.entity.ProductEO";
1 EntityDefImpl
EntityDefImpl productDef
productDef == EntityDefImpl.findDefObject(entityName);
EntityDefImpl.findDefObject(entityName);

2 EntityImpl
EntityImpl newProduct
newProduct ==
productDef.createInstance2(getDBTransaction(),null);
productDef.createInstance2(getDBTransaction(),null);
newProduct.setAttribute("Name",name);
newProduct.setAttribute("Name",name);
3 newProduct.setAttribute("Description",description);
newProduct.setAttribute("Description",description);
try
try {{
getDBTransaction().commit();
}}
4
getDBTransaction().commit();
catch
catch (JboException
(JboException ex)
ex) {{
throw
}}
throw ex;
ex;
5 DBSequence
DBSequence newIdAssigned
newIdAssigned ==
(DBSequence)newProduct.getAttribute("ProdId");
(DBSequence)newProduct.getAttribute("ProdId");
return
return newIdAssigned.getSequenceNumber().longValue();
newIdAssigned.getSequenceNumber().longValue();

8 - 39

Copyright 2008, Oracle. All rights reserved.

Using Client APIs

Client interfaces in the oracle.jbo package include:


ApplicationModule
ViewObject
Row
(But NOT Entity)

8 - 41

Copyright 2008, Oracle. All rights reserved.

Creating a Test Client

[Ctrl]+[Enter]

Need to modify names in


generated skeleton code
to reflect your AM
package and name and
VO instance name.

8 - 42

Copyright 2008, Oracle. All rights reserved.

Using View Objects in Client Code

Examples of using view objects programmatically:


Using query results programmatically
Using view criteria to alter view object queries at run time
Iterating masterdetail hierarchy
Finding a row and updating a foreign key value
Creating a new row

8 - 43

Copyright 2008, Oracle. All rights reserved.

Using Query Results Programmatically

ViewObject
Row
Row
Row
RowSetIterator

8 - 44

RowSet
hasNext
next

setNamedWhereClauseParam
executeQuery

setWhereClause
setNamedWhereClauseParam
executeQuery

hasNext
next

hasNext
next

Copyright 2008, Oracle. All rights reserved.

Using View Criteria Programmatically

ViewCriteria
ViewCriteria vc
vc == custOrdVO.createViewCriteria();
custOrdVO.createViewCriteria();

ViewCriteriaRow
ViewCriteriaRow promotionRow
promotionRow == vc.createViewCriteriaRow();
vc.createViewCriteriaRow(); 2
ViewCriteriaRow
ViewCriteriaRow noPromRow
noPromRow == vc.createViewCriteriaRow();
vc.createViewCriteriaRow();
promotionRow.setAttribute("OrderTotal",
promotionRow.setAttribute("OrderTotal", ">
"> 500");
500");
promotionRow.setAttribute("CreditLimit",
">
promotionRow.setAttribute("CreditLimit", "> 2500");
2500");
3
promotionRow.setAttribute(DiscountId",
<>
NULL");
promotionRow.setAttribute(DiscountId", <> NULL");
noPromRow.setAttribute("OrderTotal",
noPromRow.setAttribute("OrderTotal", ">
"> 1000");
1000");
noPromRow.setAttribute(CreditLimit",
noPromRow.setAttribute(CreditLimit", ">
"> 5000");
5000");
vc.addElement(promotionRow);
vc.addElement(promotionRow);
vc.addElement(noPromRow);
vc.addElement(noPromRow);
custOrdVO.applyViewCriteria(vc);
custOrdVO.applyViewCriteria(vc);
custOrdVO.executeQuery();
custOrdVO.executeQuery();

8 - 45

Copyright 2008, Oracle. All rights reserved.

4
5
6

Iterating MasterDetail Hierarchy


public
public class
class TestClient
TestClient {{
public
public static
static void
void main(String[]
main(String[] args)
args) {{
TestClient
TestClient testClient
testClient == new
new TestClient();
TestClient();
String
amDef
String
amDef == "oracle.hr.test.TestAM";
"oracle.hr.test.TestAM";
String
config
String
config == "TestAMLocal";
"TestAMLocal";
ApplicationModule
ApplicationModule am
am ==
Configuration.createRootApplicationModule(amDef,config);
Configuration.createRootApplicationModule(amDef,config);
ViewObject
ViewObject dept
dept == am.findViewObject("DepartmentsView1");
am.findViewObject("DepartmentsView1");
1
dept.executeQuery();
dept.executeQuery();
2
while
while (dept.hasNext())
(dept.hasNext()) {{
3
Row
Row department
department == dept.next();
dept.next();
System.out.println("Department
System.out.println("Department "" ++
4
department.getAttribute("DepartmentId"));
department.getAttribute("DepartmentId"));
RowSet
RowSet emps
emps == (RowSet)department.getAttribute("EmployeesView");
(RowSet)department.getAttribute("EmployeesView");
5
while
while (emps.hasNext())
(emps.hasNext()) {{
6
Row
Row emp
emp == emps.next();
emps.next();
System.out.println("
System.out.println(" Employee
Employee Name:
Name: "" ++
emp.getAttribute("LastName"));
7
emp.getAttribute("LastName")); }}
}}
Configuration.releaseRootApplicationModule(am,true);}}
Configuration.releaseRootApplicationModule(am,true);}}
8 - 47

Copyright 2008, Oracle. All rights reserved.

Finding a Row and Updating


a Foreign Key Value

1
3
4
5
6
7
8

8 - 48

public
public class
class TestClient
TestClient {{
public
public static
static void
void main(String[]
main(String[] args)
args) {{
TestClient
TestClient testClient
testClient == new
new TestClient();
TestClient();
String
amDef
String
amDef == "oracle.hr.test.TestAM";
"oracle.hr.test.TestAM";
String
config
=
String
config = "TestAMLocal";
"TestAMLocal";
ApplicationModule
am
=
ApplicationModule am =
Configuration.createRootApplicationModule(amDef,config);
Configuration.createRootApplicationModule(amDef,config);
ViewObject
ViewObject vo
vo == am.findViewObject("EmployeesView1");
am.findViewObject("EmployeesView1");
Key
empKey
=
new
2 Key empKey = new Key(new
Key(new Object[]{101});
Object[]{101});
Row[]
Row[] empsFound
empsFound == vo.findByKey(empKey,1);
vo.findByKey(empKey,1);
if
(empsFound
!=
null
if (empsFound != null &&
&& empsFound.length
empsFound.length >> 0)
0) {{
Row
Row emp
emp == empsFound[0];
empsFound[0];
System.out.println("Employee
System.out.println("Employee Name:
Name: "" ++ emp.getAttribute("LastName"));
emp.getAttribute("LastName"));
System.out.println("Employee
System.out.println("Employee is
is in
in department
department ++
emp.getAttribute("DepartmentId"));
emp.getAttribute("DepartmentId"));
emp.setAttribute("DepartmentId",60);
emp.setAttribute("DepartmentId",60);
System.out.println("Employee
System.out.println("Employee reassigned
reassigned to
to department
department "" ++
emp.getAttribute("DepartmentId"));
emp.getAttribute("DepartmentId"));
am.getTransaction().rollback();
am.getTransaction().rollback();
System.out.println("Transaction
System.out.println("Transaction cancelled");}
cancelled");}
Configuration.releaseRootApplicationModule(am,true);
Configuration.releaseRootApplicationModule(am,true); }}
}}

Copyright 2008, Oracle. All rights reserved.

Creating a New Row

1
2
3

4
5

public
public class
class TestClient
TestClient {{
public
static
public static void
void main(String[]
main(String[] args)
args) {{
TestClient
TestClient testClient
testClient == new
new TestClient();
TestClient();
String
amDef
=
"oracle.hr.test.TestAM";
String
amDef = "oracle.hr.test.TestAM";
String
config
String
config == "TestAMLocal";
"TestAMLocal";
ApplicationModule
am
=
ApplicationModule am =
Configuration.createRootApplicationModule(amDef,config);
Configuration.createRootApplicationModule(amDef,config);
ViewObject
ViewObject vo
vo == am.findViewObject("EmployeesView1");
am.findViewObject("EmployeesView1");
Row
newEmp
=
Row newEmp = vo.createRow();
vo.createRow();
vo.insertRow(newEmp);
vo.insertRow(newEmp);
newEmp.setAttribute("EmployeeId",999);
newEmp.setAttribute("EmployeeId",999);
newEmp.setAttribute("FirstName","Pam");
newEmp.setAttribute("FirstName","Pam");
newEmp.setAttribute("LastName","Gamer");
newEmp.setAttribute("LastName","Gamer");
Date
Date now
now == new
new Date();
Date();
newEmp.setAttribute("HireDate",now);
newEmp.setAttribute("HireDate",now);
newEmp.setAttribute("JobId","IT_PROG");
newEmp.setAttribute("JobId","IT_PROG");
newEmp.setAttribute("Email","pgamer@mymail.com");
newEmp.setAttribute("Email","pgamer@mymail.com");
newEmp.setAttribute("DepartmentId",60);
newEmp.setAttribute("DepartmentId",60);
newEmp.setAttribute("ManagerId",103);
newEmp.setAttribute("ManagerId",103);
am.getTransaction().commit();
am.getTransaction().commit();
System.out.println("Added
System.out.println("Added employee
employee "" ++
newEmp.getAttribute("EmployeeId")
newEmp.getAttribute("EmployeeId") ++ "" to
to Department
Department "" ++
newEmp.getAttribute("DepartmentId"));
newEmp.getAttribute("DepartmentId"));
Configuration.releaseRootApplicationModule(am,true);
Configuration.releaseRootApplicationModule(am,true); }}
}}

8 - 49

Copyright 2008, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


Generate Java classes for business components
Override class methods
Implement programmatic modifications
Add service methods to an application module
Create a test client
Use business component client APIs

8 - 50

Copyright 2008, Oracle. All rights reserved.

Practice 8 Overview:
Programmatically Modifying
Business Components
This practice covers the following topics:
Generating Java classes
Overriding base class methods
Using a test client to enable testing code that uses some of
the view object APIs
Extending the application module base class
Adding service methods to an application module

8 - 51

Copyright 2008, Oracle. All rights reserved.

Validating User Input

Copyright 2008, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do the


following:
Describe the types of validation available to ADF BC
applications
Decide which validation options are appropriate for
different validation requirements
Use the declarative validation options provided in
JDeveloper
Create programmatic validation
Use domains in validation

9-2

Copyright 2008, Oracle. All rights reserved.

Validation Options for ADF BC Applications

Validation options:
Business services:
ADF BC

Metadata (declarative validation)


Java (programmatic validation)

Database (PL/SQL)

9-3

User interface

Copyright 2008, Oracle. All rights reserved.

Triggering Validation Execution


The Validation Execution tab
enables you to specify:
When validation should
occur
Conditions governing
validation execution
Which attributes trigger
validation
Attribute
validation rule

9-4

Copyright 2008, Oracle. All rights reserved.

Entity
validation rule

Handling Validation Errors

Use the Failure Handling tab on the Validation Rule


page of the entity object editor or attribute editor to:
Specify message
severity
Insert Groovy
variables into error
messages.
Click Select Text
Resource to store
error messages as
translatable strings

9-5

Copyright 2008, Oracle. All rights reserved.

Specifying the Severity of an Error Message

There are two severity


levels for error messages:
Error
Informational warning

9-6

Copyright 2008, Oracle. All rights reserved.

Using Groovy Variables in Error Messages

In error messages:
You indicate a variable
by surrounding a name
with braces {}

Message tokens are


added automatically
You provide message
token expressions:
source.hints.
<attr>.label for
labels
<attr> for values

9-7

Copyright 2008, Oracle. All rights reserved.

Storing Error Messages as Translatable Strings

9-8

Copyright 2008, Oracle. All rights reserved.

Defining Validation in the Business Services

Implementing validation in entity objects ensures that


validation is:
Consistent
Easily maintained

You can define validation by:


Using declarative validation:

Built-in validation rules


Custom validation rules

Using programmatic validation


Using domains: Prevalidated custom data types

9-9

Copyright 2008, Oracle. All rights reserved.

Using Declarative Validation: Built-in Rules

Built-in rules greatly reduce the need for coding.


Include the following types of rules:
Defined only at entity level:

Collection validator
Unique key validator

Can be defined at entity or attribute level, but pertain to an EO


attribute:

Compare validator
Key exists validator
Length validator
List validator
Range validator
Regular expression validator

Can be defined at entity or attribute level to validate the EO or the


attribute:

9 - 10

Method validator
Script Expression validator
Copyright 2008, Oracle. All rights reserved.

Defining Declarative Validation


Defining an
attribute-level
List validator

9 - 11

Copyright 2008, Oracle. All rights reserved.

Using Declarative Validation: Built-in Rules

Built-in rules greatly reduce the need for coding.


Include the following types of rules:
Defined only at entity level:

Collection validator
Unique key validator

Can be defined at entity or attribute level, but pertain to an EO


attribute:

Compare validator
Key exists validator
Length validator
List validator
Range validator
Regular expression validator

Can be defined at entity or attribute level to validate the EO or the


attribute:

9 - 12

Method validator
Script Expression validator
Copyright 2008, Oracle. All rights reserved.

Using Declarative Built-in Rules:


Collection Validator

Collection validators are defined at the entity level.


To define a Collection
validator, specify:

9 - 13

Operation
Accessor
Attribute
Operator
Compare with
Compare with value

Copyright 2008, Oracle. All rights reserved.

Using Declarative Built-in Rules:


Unique Key Validator
The Unique Key validator:
Is defined at entity level
Ensures that primary key values
are always unique
Can also be used for alternate
keys
Failure throws
TooManyObjectsException

9 - 14

Copyright 2008, Oracle. All rights reserved.

Using Declarative Validation: Built-in Rules

Built-in rules greatly reduce the need for coding.


Include the following types of rules:
Defined only at entity level:

Collection validator
Unique key validator

Can be defined at entity or attribute level, but pertain to an EO


attribute:

Compare validator
Key exists validator
Length validator
List validator
Range validator
Regular expression validator

Can be defined at entity or attribute level to validate the EO or the


attribute:

9 - 15

Method validator
Script Expression validator
Copyright 2008, Oracle. All rights reserved.

Using Declarative Built-in Rules:


Compare Validator
For a Compare validator, you specify:

Attribute-level
Compare validator

1. Attribute (if
entity level)
2. Operator
Entity-level
Compare validator
3. Value to
compare
with

9 - 16

Copyright 2008, Oracle. All rights reserved.

Using Declarative Built-in Rules:


Key Exists Validator
The Key Exists validator:
Checks if key value exists
Checks cache first
1
2

Entity Object target type


View Accessor target type

(for all views based on this EO)

(for single view)


9 - 17

Copyright 2008, Oracle. All rights reserved.

Using Declarative Built-in Rules:


Length Validator
For a length validator, you specify:

Attribute (if defining at EO level)

Operator:

9 - 18

Comparison Type:

Value(s):

Copyright 2008, Oracle. All rights reserved.

Using Declarative Built-in Rules:


List Validator
Ensures that value is in (or not
in) a list defined by:
Literal values
SQL query
VO attribute
View accessor
Although you can define at entity or
attribute level, the List validator
pertains to an entity attribute.

9 - 19

Copyright 2008, Oracle. All rights reserved.

Using Declarative Built-in Rules:


Range Validator
For a range validator, you
specify:
Operator: Between or
Not Between
Range: Minimum and
Maximum values

Although you can define at entity or attribute level, the range


validator pertains to an entity attribute.

9 - 20

Copyright 2008, Oracle. All rights reserved.

Using Declarative Built-in Rules:


Regular Expression Validator

For a regular expression validator, you specify:

9 - 21

Operator:

Regular Expression:

Qualifier(s):

Predefined Expressions:

Copyright 2008, Oracle. All rights reserved.

Using Declarative Validation: Built-in Rules

Built-in rules greatly reduce the need for coding.


Include the following types of rules:
Defined only at entity level:

Collection validator
Unique key validator

Can be defined at entity or attribute level, but pertain to an EO


attribute:

Compare validator
Key exists validator
Length validator
List validator
Range validator
Regular expression validator

Can be defined at entity or attribute level to validate the EO or the


attribute:

9 - 22

Script Expression validator


Method validator
Copyright 2008, Oracle. All rights reserved.

Using Declarative Built-in Rules:


Script Expression Validator
To define a Groovy expression, you:
Omit braces {}
Use newValue for new
value of current attribute
Write code to return true
or false and/or call
adf.error.raise or
adf.error.warn

Can use aggregate


functions on RowSet

Can use ternary operator


Click Test to check syntax

9 - 23

Copyright 2008, Oracle. All rights reserved.

Using Declarative Custom Rules:


Entity-Specific Rules (Method Validators)
Method validators:
Extend declarative rules for entities or attributes
Call Java methods in your entity object (not in a separate
class as a global rule is)
Are called automatically during validation cycle
Must:
Be defined as
public
Return a Boolean
value
Be named like
validateXXX()
9 - 24

public boolean validateOrder(){


if( // add your validation code )
return true;
else
return false;
}

Copyright 2008, Oracle. All rights reserved.

Using Declarative Custom Rules:


Creating an Entity-Specific Method Validator
Create at either the entity or attribute level:

Adds a method to the


<EO>Impl.java file
9 - 25

Add your own code


to the validateXXX() method

Copyright 2008, Oracle. All rights reserved.

Using Declarative Global Validation Rules

Custom global validation rules are available to assign


declaratively to any business components by using the
following steps:
1. Create a Java class that implements the
JboValidatorInterface interface in the
oracle.jbo.rules package.
2. Modify the code for the validation rule.
3. Assign the rule to a business component object.

9 - 26

Copyright 2008, Oracle. All rights reserved.

Creating the Java Class for a Global Rule


Purpose of rule: Compare any two dates in any entity object
and raise an exception if the first date is after the second date.
Name of Java class

Name that displays


in rule type list
9 - 27

Copyright 2008, Oracle. All rights reserved.

Examining the Generated Skeleton Code

public class CompareDates implements JboValidatorInterface {


private String description = "Returns true if date1 is not after date2";
public CompareDates() {
}
public boolean validateValue(Object value) {
return true;
}
public void validate(JboValidatorContext ctx) { This method is executed
if (!validateValue(ctx.getNewValue())) {
when validation occurs.
throw new
ValidationException("model.CompareDates validation failed");
}
}
public String getDescription() {
return description;
}
public void setDescription(String str) {
description = str;
}
}

9 - 28

Copyright 2008, Oracle. All rights reserved.

Modifying the Code for the Global Rule


public class CompareDates implements JboValidatorInterface {
private String description = "Return true if date1 is not after date2";
private String earlierDateAttrName = "";
1
private String laterDateAttrName = "";

4
2

9 - 29

public void validate(JboValidatorContext ctx) {


This method is executed
if (validatorAttachedAtEntityLevel(ctx)){
when validation occurs.
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");
}
}
private boolean validateValue(Date earlierDate, Date laterDate) {
return (earlierDate == null) || (laterDate == null) ||
(earlierDate.compareTo(laterDate) <= 0);
}
private boolean validatorAttachedAtEntityLevel(JboValidatorContext ctx) {
return ctx.getOldValue() instanceof EntityImpl;
}

Copyright 2008, Oracle. All rights reserved.

Assigning the Global Rule to an Object


Generate the entity Java class.

Select the
global rule
from
the Rule
Type list.
Create a new validator for an
attribute or for the entity.
Provide
values for
any
properties.

9 - 31

Copyright 2008, Oracle. All rights reserved.

Testing the Global Validation Rule

When you change the date


to violate the validation rule and
attempt to commit the change,
an error message displays
the run-time exception.
9 - 32

Copyright 2008, Oracle. All rights reserved.

Using Programmatic Validation


Create custom methods in the EntityImpl.java file:
public boolean checkOrderMode(){
if ( ("ONLINE".equals(getOrderMode())) &&
(getCustomerEmail() == null))
{
return false;
}
else {
return true;
}}

Call in overridden validateEntity() method:


protected void validateEntity(){
if (!checkOrderMode()) {
throw new JboException("Online order must have email");
}
super.validateEntity();
}

9 - 33

Copyright 2008, Oracle. All rights reserved.

Debugging Custom Validation Code


with the JDeveloper Debugger

9 - 34

JDeveloper Debugger is
useful for pinpointing
problems in your custom
validation code.
Set source breakpoints to
pinpoint problems.
Set exception breakpoints
to stop when a particular exception
is thrown.
At breakpoints you can execute code one line at a time
and view variable values.
To run a file in debug mode, right-click and select Debug.
Copyright 2008, Oracle. All rights reserved.

Using a Domain to Create


Custom-Validated Data Types

Domains are Java classes that extend the basic data types
(String, Number, Date , and so on).

You can create your own data types that encapsulate


specific validation rules.
Use domains for more complex validation:

Format of a phone number


Validity of a URL
Validity of an email address
Checksum of digits of a credit card number

Validation is done by the domain constructor.


A domain is not bound to a particular entity or attribute.

9 - 35

Copyright 2008, Oracle. All rights reserved.

Creating and Using a Domain

1. Create the domain.


2. Add validation code to the validate() method in the
domains Java file.
3. Edit an entity and change the type of an attribute to the
domain.

URLDomain
appears in the
list of types.

9 - 36

Copyright 2008, Oracle. All rights reserved.

Coding Validation in a Domain

The validate() method is called by the domains constructor


(mdata is a private String variable containing the string to be
validated):
Example: URLDomain verifies that an attribute is a valid URL.
protected void validate()
{
try {
// Make sure the user entered a valid URL
java.net.URL u = new java.net.URL(mData);
}
catch (java.net.MalformedURLException e)
{throw new
oracle.jbo.domain.DomainValidationException
("Invalid URL"); }
}

9 - 37

Copyright 2008, Oracle. All rights reserved.

Specifying Validation Order

General validation order:


Changed attributes are validated
when they lose focus.
Changed entities are validated at
commit time.
In compositions, child entities are
validated before parent entities.
You can control order of validation
within attributes or an entity.
You can specify validation at
transaction level for some
validators.
9 - 38

Copyright 2008, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


Describe the types of validation available to ADF BC
applications
Decide which validation options are appropriate for
different validation requirements
Use the declarative validation options provided in
JDeveloper
Create programmatic validation
Use domains in validation

9 - 39

Copyright 2008, Oracle. All rights reserved.

Practice 9 Overview:
Implementing Validation
This practice covers the following topics:
Using declarative validation
Using programmatic validation
Creating and using a domain
Testing the validation

9 - 40

Copyright 2008, Oracle. All rights reserved.

Troubleshooting ADF BC Applications

Copyright 2008, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do the


following:
Use tools for logging and diagnostics
Utilize design-time code validation
Make use of FileMon and JUnit
Use the JDeveloper profiler
Test Web service calls:
Use a sample client to call a Web service
Use the JDeveloper HTTP Analyzer

10 - 2

Use the JDeveloper debugger


Utilize sources of help
Copyright 2008, Oracle. All rights reserved.

Troubleshooting the Business Service

Test a business service in isolation from views or controllers:


BC Browser
Java test clients

JDeveloper and ADF tools for logging and diagnostics:


Java logging
ADFLogger
ADF Diagnostics

Validate code at design time.


Build unit tests with JUnit.
Diagnose CLASSPATH and other file access problems: FileMon

Diagnose performance problems: JDeveloper Profiler


Diagnose Web service problems: HTTP Analyzer, sample Web
client
Step through code: JDeveloper debugger

10 - 3

Copyright 2008, Oracle. All rights reserved.

Troubleshooting the UI

10 - 4

Java EE Logging (Java Logger, ADF Logger)


Design-time troubleshooting
Using the JDeveloper Debugger
Debugging through the source

Copyright 2008, Oracle. All rights reserved.

Using Logging and Diagnostics

10 - 5

Displaying debug messages to the console


Java logging
ADF logging / Oracle Diagnostic Logging (ODL)

Copyright 2008, Oracle. All rights reserved.

Displaying Debug Messages to the Console

Edit the projects run


configuration:

Set Java options:


-Djbo.debugoutput=console

10 - 6

Copyright 2008, Oracle. All rights reserved.

Java Logging

It is useful in environments where you cant run the


debugger or where running the debugger might hide the
problem.
Many Java programs use the Java logging API to produce
useful messages.
You can configure Java logging to produce different levels
of logging output:

10 - 7

SEVERE
WARNING
INFO
CONFIG
FINE

FINER
FINEST
ALL
NONE

Copyright 2008, Oracle. All rights reserved.

Core Java Logging

Edit <Java_Home>/jre/lib/logging.properties:
Set
java.util.logging.ConsoleHandler.level=FINE
Add the line: com.sun.faces.level=FINE

10 - 9

Now the log contains JSF Reference Implementation


debug messages.

Copyright 2008, Oracle. All rights reserved.

Using ADF Logging

ADF Logging is built on Oracle Diagnostic Logging (ODL),


which provides:
Capture of context information
Control over which messages are logged by setting:

10 - 10

Logging level
Module filter

ODL uses a common format and repository for all


components in the WebLogic Server.

Copyright 2008, Oracle. All rights reserved.

Configuring ADF Logging

The Oracle Diagnostic Logging (ODL) configuration file


(logging.xml) controls the loggers under the oracle tree.
Set the logging threshold for the groups you are debugging
(levels are SEVERE, WARNING, INFO, CONFIG, FINE,
FINER, or FINEST):

ADFm logger settings:


<logger name="oracle.adf" level="FINE"/>
<logger name="oracle.jbo" level="FINE"/>
ADFv logger settings:
<logger name="oracle.adf" level="FINE"/>
<logger name="oracle.adfinternal" level="FINE"/>
ADFc logger settings:
<logger name="oracle.adf.controller" level="FINE"/>
<logger name="oracle.adfinternal.controller"
level="FINE"/>

Optionally set the module filter.

10 - 11

Alternatively, create configuration in JDeveloper.


Copyright 2008, Oracle. All rights reserved.

Creating Logging Configurations in JDeveloper


ADF Model debugging configuration:
Edit the projects run configuration.
Set Java options: -Djbo.debugoutput=adflogger
-Djbo.adflogger.level=FINE

10 - 13

Copyright 2008, Oracle. All rights reserved.

Viewing ODL Logs

10 - 14

Copyright 2008, Oracle. All rights reserved.

Using Design-Time Code Validation

JDevelopers editors provide error cues and correction


suggestions for files such as:
XML
Java
JSPX

10 - 15

Copyright 2008, Oracle. All rights reserved.

Design-Time XML Validation

10 - 16

Copyright 2008, Oracle. All rights reserved.

Design-Time Java Code Validation

10 - 17

Copyright 2008, Oracle. All rights reserved.

Design-Time JSPX Validation

10 - 18

As you edit a page, the XML syntax is checked and errors


and warnings are flagged.
Errors are visible in Design, Source and Bindings editors.

Copyright 2008, Oracle. All rights reserved.

Using Tools and Utilities

10 - 19

JUnit
JDeveloper Profiler
FileMon
Web service sample client
JDeveloper HTTP Analyzer
JDeveloper Debugger

Copyright 2008, Oracle. All rights reserved.

Testing Java Code with JUnit

Open source regression testing framework


Useful for creating tests to verify Java code
JDevelopers JUnit extension provides wizards for creating
test components.
More information and examples:

10 - 20

SRDemo sample application


Toystore sample application
JDeveloper online documentation
http://www.junit.org

Copyright 2008, Oracle. All rights reserved.

Unit Testing with JUnit

JUnit makes it easy for developers to write and run repeatable


tests. Its features include:
Assertions for testing expected results
Test fixtures for sharing common test data
Test suites for organizing and running tests
Graphical and textual test runners

10 - 21

Copyright 2008, Oracle. All rights reserved.

Using JDevelopers Profiler

With the Profiler, you can:


Monitor programs as they run
Find bottlenecks and memory leaks
Two types of profiling:
CPU: Method processing times
Memory: Allocation and freeing of data objects

10 - 22

Copyright 2008, Oracle. All rights reserved.

Running the Profiler

10 - 23

Copyright 2008, Oracle. All rights reserved.

Identifying Search Paths on Windows with


FileMon

Useful for troubleshooting CLASSPATH problems

Shows you the path that your running application is looking


in for classes and files

10 - 24

Copyright 2008, Oracle. All rights reserved.

Troubleshooting Web Services

You can test Web services by:


Defining a sample client
Using the HTTP Analyzer

10 - 25

Copyright 2008, Oracle. All rights reserved.

Troubleshooting Web Services: Sample Client

The sample Java client initializes a proxy to the Web


service.
You add custom code to call the Web service operations.

greetingService_Service=new GreetingService_Service();
GreetingService greetingService =
greetingService_Service.getGreetingServiceSoapHttpPort();
// Add your code to call the desired methods.
System.out.println(greetingService.sayHelloTo("Pam"));

10 - 26

To create a sample client, select Create Client for Web


Service Annotations in the context menu.
It is not automatically synchronized with the Web service.
Copyright 2008, Oracle. All rights reserved.

Troubleshooting Web Services: HTTP Analyzer

10 - 27

Copyright 2008, Oracle. All rights reserved.

Using the JDeveloper Debugger

10 - 28

It is very useful for pinpointing problems in your


application.
Set source breakpoints to pinpoint problems in custom
code.
Set exception breakpoints to stop when a particular
exception is thrown.
When breakpoint is encountered at run time, you can step
through code and view values of variables.
To run an application in debug mode, right-click and select
Debug.

Copyright 2008, Oracle. All rights reserved.

Understanding Breakpoint Types

Type

Breaks when

Exception

An exception of this class (or a subclass) is thrown.

Source

A particular source line in a particular class in a particular package


is run.

Method

A method in a given class is invoked.

Class

Any method in a given class is invoked.

Watchpoint

A given field is accessed or modified.

10 - 29

Copyright 2008, Oracle. All rights reserved.

Using Breakpoints

You can create groups of breakpoints that can be enabled


or disabled all at once.
You can use conditional breakpoints. Examples:

10 - 31

value instanceof oracle.jbo.domain.Date


status.equalsIgnoreCase("shipped")
i > 50

You can use actions other than stop with breakpoints.

Copyright 2008, Oracle. All rights reserved.

Declarative UI Debugging
The Declarative Debugger enables you to set breakpoints on:
Executables
Task flow activities
Bindings
Breakpoint reached:

10 - 32

Copyright 2008, Oracle. All rights reserved.

Using the EL Evaluator

The expression language evaluator enables:


Introspection of the values between the view and model
Watches based on EL

Using the discovery function

An evaluated expression

An evaluated expression on watch list displays changed value.

10 - 33

Copyright 2008, Oracle. All rights reserved.

ADF Structure Pane and ADF Data Window

During debugging:
ADF Structure Pane shows items in current viewport
ADF Data Window shows data within:
Item selected in ADF Structure Pane
ADF context
Scoped variables

10 - 34

Copyright 2008, Oracle. All rights reserved.

Object Preferences

10 - 35

Filter out fields that


are displayed in
debugger.
Change default value
displayed in debugger.
Show expressions as
details instead of fields.
Customize types
throughout the
type hierarchy.

Copyright 2008, Oracle. All rights reserved.

Using Oracle ADF Source Code for Debugging

Adding ADF source code enables you to:


Access Javadocs in the code editor
Set breakpoints on Oracle code as well as your own
Access symbolic names via Debug libraries

10 - 36

Copyright 2008, Oracle. All rights reserved.

Setting Up Oracle ADF Source Code for


Debugging
To use source code for debugging, you can:
Add the source zip into the user library
Add the library to a project

10 - 37

Copyright 2008, Oracle. All rights reserved.

Utilizing Quick Javadoc


Right-click a method and select Quick
Javadoc:

10 - 38

Copyright 2008, Oracle. All rights reserved.

Setting Breakpoints in Source Code

To set a breakpoint in Oracle code, perform the following steps:


1. Press [Ctrl] + [-].
2. Enter an Oracle ADF class name or its uppercase letters.
3. Set breakpoints in the source file that JDeveloper opens.

10 - 39

Copyright 2008, Oracle. All rights reserved.

Using Common Oracle ADF Breakpoints

Useful for debugging declarative functionality


In oracle.jbo package you can set breakpoints on:

JboException
DMLException
uicli.binding.JUCtrlActionBinding.doIt()
server.ViewObjectImpl.
executeQueryForCollection()
server.ViewRowImpl.setAttributeInternal()
server.EntityImpl.setAttributeInternal()

10 - 40

Copyright 2008, Oracle. All rights reserved.

Debugging Interactions with the Model Layer

Controlled by two classes:


oracle.adf.controller.faces.lifecycle.FacesPageLifecycle
oracle.adf.controller.v2.lifecycle.PageLifecycleImpl

Set breakpoints if encountering problems such as:


Components not displaying correctly with complete data
Validation errors not rendering properly

10 - 41

Copyright 2008, Oracle. All rights reserved.

Correcting Failures to Display Data

To debug all executables:


oracle.adf.model.binding.DCBindingContainer
internalRefreshControl(int, boolean)

To debug the method iterator:


oracle.jbo.uicli.binding.JUMethodIteratorDef
initSourceRSI()

To debug an attribute binding:


oracle.jbo.uicli.binding.JUCtrlValueBinding
getInputValue()

10 - 42

Copyright 2008, Oracle. All rights reserved.

Correcting Failures to Invoke Actions and


Methods

10 - 45

Actions are ignored if an executable or its target binding is


not executed.
You can debug action or method invocation by breaking on
DCDataControl.invokeOperation(), which is entry
point for action and method execution.
You can debug invocation of coded methods by breaking
on DCGenericDataControl.invokeOperation().

Copyright 2008, Oracle. All rights reserved.

Debugging Life Cycle Events: Task Flows

Before a task flow is called:


oracle.adfinternal.controller.activity.
TaskFlowCallActivityLogic.execute()

Before a task flows input parameters are resolved:


oracle.adfinternal.controller.activity.
TaskFlowCallActivityLogic.getInputValues()

Before and after a task flow returns:


oracle.adfinternal.controller.activity.
TaskFlowReturnActivityLogic.execute()

10 - 47

Copyright 2008, Oracle. All rights reserved.

Debugging Life Cycle Events:


Parameters and Methods

For debugging the ADF controllers interpretation of the


navigation routing:
oracle.adfinternal.controller.engine.
ControlFlowEngine.doRouting()

For debugging before view activitys input parameters are


evaluated:
oracle.adfinternal.controller.
application.PageParameterPagePhaseListener
.beforePhase()

For calling an ADF controller method action:


oracle.adfinternal.controller.activity.
MethodCallActivityLogic.execute()

10 - 48

Copyright 2008, Oracle. All rights reserved.

Debugging Life Cycle Events:


Switching Between Main Page and Regions

To keep track of the context switching between the main page


and regions, set a breakpoint in:
oracle.adfinternal.controller.state.
RequestState.setCurrentViewPortContext()

10 - 49

Copyright 2008, Oracle. All rights reserved.

Obtaining Help

Sources of help include:


Online Help
Javadoc
Support (MetaLink)
Forums
Blogs
Internet Search

10 - 50

Copyright 2008, Oracle. All rights reserved.

Requesting Help

Post your request to the appropriate forum:


Use meaningful subject line.
Describe exact steps to reproduce the problem.
Include exact error information (error number, exception) if
you receive an error message.
Include a stack trace if appropriate.
Include a test case if possible.
List technologies and product version numbers.
Concrete examples are better than abstract descriptions.
Mention troubleshooting steps you have tried and how they
affected the problem.
10 - 51

Copyright 2008, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


Use tools for logging and diagnostics
Utilize design-time code validation
Make use of FileMon and JUnit
Use the JDeveloper profiler
Test Web service calls:
Use a sample client to call a Web service
Use the JDeveloper HTTP Analyzer

10 - 52

Use the JDeveloper debugger


Utilize sources of help

Copyright 2008, Oracle. All rights reserved.

Practice 10 Overview:
Troubleshooting
This practice covers running the JDeveloper debugger to
diagnose a problem with the ADF BC model.

10 - 53

Copyright 2008, Oracle. All rights reserved.

Understanding UI Technologies

Copyright 2008, Oracle. All rights reserved.

Objectives
After completing this lesson, you should be able to do the following:
Describe the use of Web browsers and HTML
Explain how Java has come into widespread use as a language
for developing Web applications
Describe the function of Servlets and JSPs
Define JavaServer Faces
Explain the JSF component architecture
List some JSF component types included in the standard
implementation
Describe the purpose of backing beans
Explain the use of managed beans
Describe the JSF life cycle
Explain how ADF Faces augments the JSF life cycle
11 - 2

Copyright 2008, Oracle. All rights reserved.

Enabling the World Wide Web


with HTML and HTTP
HTML: A markup language for defining Web pages
HTTP: A stateless request/response protocol for serving Web
pages
HTTP
request
HTTP
response

Browser client
HTML document

11 - 3

Copyright 2008, Oracle. All rights reserved.

Web
server
HTML files

Describing the Java Programming Language

Java:
Is both a platform and an object-oriented language
Was originally designed by Sun Microsystems for
consumer electronics
Contains a class library
Uses a virtual machine for program execution
Provides the following benefits:

11 - 4

Object-oriented
Interpreted and platform independent
Dynamic and distributed
Multithreaded
Robust and secure
Copyright 2008, Oracle. All rights reserved.

Using Java as a Language for Web Development


Client

Web server
Presentation

Application server
Business
logic

Servlets, JavaServer Enterprise


JavaBeans (EJB),
Pages (JSPs),
CORBA
JavaServer Faces
(JSF)

11 - 6

Copyright 2008, Oracle. All rights reserved.

Data

What Are Servlets?

Servlets:
Are written in Java
Extend the Web server
HTTP
request

Back-end functionality
User interface
HTTP
response

Browser client
HTML document

Can be used to provide:

Web
server
HTML files

Request
type?
Other
Servlet

Web
container

11 - 8

Copyright 2008, Oracle. All rights reserved.

What Are JavaServer Pages (JSP)?

JSP:
Combines HTML and JSP tags
Is saved as .jsp

11 - 9

Is compiled to a servlet on the first request


Is recompiled only when changed on the server
Enables servlet functionality with less programming

Copyright 2008, Oracle. All rights reserved.

What Are JavaBeans?

JavaBeans:
Are Java classes that comply with
certain standards
Consist of properties, methods, and events
Can be used by builder tools such as JDeveloper
Can store state based on defined memory scope
Can be used in JSPs

11 - 10

Copyright 2008, Oracle. All rights reserved.

What Is JavaServer Faces (JSF)?

Component-based (not mark-up)


Simplifies Web development
Insulates the developer from UI implementations
Declarative definitionmore robust and extensible

Server-side UI technology
Standard Java EE Web UI framework with a huge base of
vendor support; contributors include Sun, Oracle, IBM

11 - 11

Automatic state and event handling


Diverse client base (not just HTML)
Designed with tooling in mind
Display-agnostic
Applicable to wide spectrum of programmer types
Copyright 2008, Oracle. All rights reserved.

JSF Key Concepts

JSF includes the following concepts:


UI component, including renderers and render kits
Controller: The navigation rules that govern page flow
Managed beans and backing beans to encapsulate
business logic, data, and properties of components (ADF
BC applications define business logic mainly
in the model layer, not the UI layer.)
Life cycle: Creation, validation, data binding and business
service interactions of a page

11 - 13

Copyright 2008, Oracle. All rights reserved.

JSF Component Model

JSF concepts include:


Server-side UI components:
Provide functionality, definition, or behavior
Can be nested

Renderers: Display UI components in a technology


understood by the output device
Render kits:
A render kit is a library of renderers.
The basic HTML Render Kit is part of the reference
implementation.

11 - 14

Copyright 2008, Oracle. All rights reserved.

JSF Multiple Renderers


Option buttons: When an item has focus, its highlighting looks
different depending on the client.

Render kits enable the same component to be


rendered differently depending on the client.
11 - 15

Copyright 2008, Oracle. All rights reserved.

Traditional Navigation

In traditional navigation, a button or hyperlink is hard coded to


navigate to a specific page:
<body>
<form action="myNewPage.html">
<button type="button"/>
</form>
</body>

Hard-coded
hyperlink
navigation

11 - 16

Hard-coded
button
navigation

<body>
<a href="http://myNewPage.html">
Go To My New Page
</a>
</body>

Copyright 2008, Oracle. All rights reserved.

Defining Navigation by Using the JSF Controller

firstPage
Button

firstPage.jsp

myNewPage
success

myNewPage.jsp

JSF Navigation Rules


defined in
faces-config.xml
11 - 17

Copyright 2008, Oracle. All rights reserved.

JSF Navigation Example

A command UI component can be bound to an action:


<h:commandButton action="#{mybean.navAction}"/>

firstPage
Button
firstPage.jsp

mybean: The logical name of a managed bean


(MyBean.java) with an action method, navAction(),
which returns a string
11 - 18

Copyright 2008, Oracle. All rights reserved.

Using JSF Components

JSF components include:


Core
HTML

11 - 19

Copyright 2008, Oracle. All rights reserved.

Using JSF Managed Beans

Managed beans are optional and can be used to:


Hold presentation and controller logic
Store state
Execute Java routines when, for example, a user
clicks a button
Define handler for Event Listeners
Add any code needed by UI
Backing beans:
Are a specialized type of managed beans that contain
accessors for UI components
Have a 1-to-1 relationship with a page
11 - 20

Copyright 2008, Oracle. All rights reserved.

Overview of JSF Page Life Cycle

A JSF page is represented by a tree of UI components, called a


view.
Request processing is managed by FacesServlet , which
creates the FacesContext object.
When a client makes a request for the page, the life cycle starts.
During the life cycle, JSF implementation builds the view while
considering the state saved from the previous postback.
When the client performs a postback of the page, JSF
implementation must perform life-cycle steps:
Conversion
Validation

11 - 21

Copyright 2008, Oracle. All rights reserved.

Formal Phases of the JSF Life Cycle

JSF life cycle


Postback

Restore View

Process
Validations

Validate immediate

Initial
request

Exception

Render
Response

11 - 22

Apply
Request
Values

Invoke
Application

Copyright 2008, Oracle. All rights reserved.

Exception

Update
Model

Key Characteristics of Rich User Interfaces

Rich Web UIs include the following characteristics:


Increased
responsiveness over
traditional Web
applications
Asynchronous
communication with
the server
Behaviors not available
in HTML alone

11 - 24

Copyright 2008, Oracle. All rights reserved.

Adding to JSF with ADF Faces

Built on top of JSF APIs


Much larger component set:
over 100 types
More advanced and
interesting components
Partial-page rendering
Scrollable, sortable table

11 - 25

Rich feature set for customizing


applications
Uses Ajax, SVG, Flash
ADF model support
Runs on any JSF-compliant implementation
Copyright 2008, Oracle. All rights reserved.

Using the ADF Controller

Built on top of JSF navigation model


Handles page flow
Promotes page reuse through
abstraction
Increases flexibility and
manageability

Place for code execution, such as


programmatic interaction with the
model and business service
Application support tasks

11 - 26

Input validation
State management

Security
Declarative transaction control

Declarative Back button control


Copyright 2008, Oracle. All rights reserved.

ADF Life Cycle Phases


JSF Phases

ADF Phases

Events

Restore View

JSF Restore View

before(JSF Restore View)


after(JSF Restore View)

Init Context

before(Init Context)
after(Init Context)

Prepare Model

before, after

Apply Request Values

JSF Apply Request Values

before, after

Process Validations

JSF Process Validations

before, after

Update Model Values

JSF Update Model Values

before, after

Validate Model Updates

before, after

JSF Invoke Application

before, after

Metadata Commit

before, after

JSF Render Response

before, after

Only after navigation


Init Context

before, after

Only after navigation


Prepare Model

before, after

Prepare Render

before, after

Invoke Application

Render Response

11 - 27

Copyright 2008, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


Describe the use of Web browsers and HTML
Explain how Java has come into widespread use as a language
for developing Web applications
Describe the function of Servlets and JSPs
Define JavaServer Faces
Explain the JSF component architecture
List some JSF component types included in the standard
implementation
Describe the purpose of backing beans
Explain the use of managed beans
Describe the JSF life cycle
Explain how ADF Faces augments the JSF life cycle
11 - 28

Copyright 2008, Oracle. All rights reserved.

Binding UI Components to Data

Copyright 2008, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do the


following:
Create a JSF page
Add ADF Faces UI components to a page
Include databound components on a page
Create and edit data bindings

12 - 2

Copyright 2008, Oracle. All rights reserved.

Creating a JSF Page


Use New Gallery
OR task flow
diagram.

<?xml version='1.0' encoding='UTF-8'?>


<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.0"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:af="http://xmlns.oracle.com/adf/faces/rich">
<jsp:directive.page contentType="text/html;charset=UTF8"/>
<f:view>
<af:document>
<af:form/>
</af:document>
</f:view>
</jsp:root>
12 - 3

Copyright 2008, Oracle. All rights reserved.

Adding UI Components to the Page

You can create components on a page by:


Dragging a component from the Component Palette
Using the context menu in editor or Structure window
Dragging a data element from the Data Controls panel

12 - 5

Copyright 2008, Oracle. All rights reserved.

Using the Component Palette

Drag the component from the Component Palette:


Component category
pop-up list

12 - 6

Copyright 2008, Oracle. All rights reserved.

Using the Context Menu


Context menu of
Structure
window

Context menu of
editor

12 - 7

Copyright 2008, Oracle. All rights reserved.

Using the Data Controls Panel


The Data Controls panel:
Is a visual representation of your
business service that contains:
Methods
Parameters and
results
Attributes
Collections
Built-in operations

12 - 8

Provides automatic data binding for


any business service; for example,
there automatically is a data control
for every ADF BC application
module
Copyright 2008, Oracle. All rights reserved.

Describing the ADF Model Layer

Data controls describe


the public interface of a
business service.
Bindings connect UI
components to data or
actions.
Data controls and
bindings are defined
by using XML metadata.

Bindings

Bindings

Data Control
Business service

12 - 9

Copyright 2008, Oracle. All rights reserved.

Types of Data Bindings

Iterator Binding: Keeps track of the current row in a data


collection.
Iterator
Method iterator

12 - 10

Accessor iterator
Variable iterator

Value Binding: Connects UI components to attributes in a


data collection; examples: attribute binding, tree binding,
list binding, table binding
Action Binding: Invokes a method or operation
Copyright 2008, Oracle. All rights reserved.

Using Expression Language (EL)

Use Expression Builder


to declaratively create EL
expressions.

12 - 12

Copyright 2008, Oracle. All rights reserved.

Expression Language and Bindings

Data binding expressions are written using EL.


They are evaluated at run time to determine what data to
display.
ADF EL expressions typically have the form:
#{bindingVariable.BindingObject.propertyName}

Example of an inputText component in a JSF page:


<af:inputText
value="#{bindings.Ename.inputValue}
label="#{bindings.Ename.label}
required="#{bindings.Ename.mandatory}">

12 - 13

Copyright 2008, Oracle. All rights reserved.

Creating and Editing Data Bindings

Data Bindings:
Are created automatically when you drag them from the
Data Controls panel to a page or panel
Can also be created and edited in the editor, the Property
Palette, or the Structure window
Quantity:
Price:

12 - 15

7
$3.49

Copyright 2008, Oracle. All rights reserved.

Rebinding: Example
In the visual editor or its Structure window, perform the
following steps:
1. Right-click the component.
2. Select Rebind to Another ADF Control.
3. Select a different control to bind to.

12 - 16

Copyright 2008, Oracle. All rights reserved.

Opening a Page Definition File

The page definition file <pagename>PageDef.xml (for


example, browseOrdersPageDef.xml):

Is created automatically when you add


a databound component to a page
Contains all the binding definitions
for a page

To open a page definition, perform the


following steps:
1. Right-click the page in the editor or
Application Navigator.
2. Select Go to Page Definition.

12 - 17

Copyright 2008, Oracle. All rights reserved.

Editing Bindings in a Page Definition File

1
2

12 - 18

Copyright 2008, Oracle. All rights reserved.

Editing Bindings from a Page

12 - 19

Copyright 2008, Oracle. All rights reserved.

Tracing Data Binding:


From Database to Databound Components

Database table

ADF BC
Entity Object

Databound components on a JSP

12 - 20

ADF BC
View Object

ADF BC
Application
Module

Binding Container

Copyright 2008, Oracle. All rights reserved.

ADF Model
Data Control

Tracing Data Binding:


From AM to Data Control

JDeveloper creates data


controls for each ADF
BC application module.

12 - 21

Copyright 2008, Oracle. All rights reserved.

Tracing Data Binding:


Creating Databound Components
Data Control
Page

Example: Drag OrderVO1 to a page and


create as an ADF Form with navigation.
12 - 22

Copyright 2008, Oracle. All rights reserved.

Tracing Data Binding:


From Data Control to Databound Components
Page

Binding
container

The OrderId field is bound to the OrderId


attribute, using an attribute (value) binding.
The iterator binding ensures that the current
row is displayed.

12 - 23

Copyright 2008, Oracle. All rights reserved.

Data Control

Tracing Data Binding:


From Data Control to Databound Components
Page

Binding
container

The OrderShippedDate field is bound to the


OrderShippedDate attribute, also using
an attribute binding.
12 - 24

Copyright 2008, Oracle. All rights reserved.

Data Control

Tracing Data Binding:


From Data Control to Databound Components
Data Control
Page

Binding
container

The Next button uses an action binding to


call the Next operation, which increments
the current row in the iterator binding.
12 - 25

Copyright 2008, Oracle. All rights reserved.

Examining Data Binding Objects


and Metadata Files
Page
definition
file

Binding
Container

Data
Control

Structure
definition
file
*.xml

*PageDef.xml
Binding Context

Binding
context
definition file
DataBindings.cpx
12 - 26

Copyright 2008, Oracle. All rights reserved.

Data
Controls
definition
file
DataControls.dcx

Binding Existing Components to Data

You can add data binding to existing components:


1. Right-click the component and select Bind to ADF Control.
2. Select a data control object from the Bind to ADF Control
dialog box.

12 - 28

Copyright 2008, Oracle. All rights reserved.

Accessing Data Controls and Bindings


Programmatically

Use methods in DCBindingContainer.


Example of accessing an ADF BC application module:
DCBindingContainer bc = getBindingContainer();
MyAppModule
myAM = (MyAppModule)bc.findDataControl

("MyAppModuleDataControl").getDataProvider();
//Now use myAM to call app module methods.

Example of getting an attribute from an iterator binding:


DCBindingContainer bc = getBindingContainer();
String empname = (String)bc.findIteratorBinding("empIter")
.getCurrentRow().getAttribute("EmpName");

Access binding container with convenience API:


BindingContainer bc =
BindingContext.getCurrent().getCurrentBindingsEntry();

12 - 29

Copyright 2008, Oracle. All rights reserved.

Running and Testing the Page

1. Run the page.


2. Test the functionality.

12 - 30

Copyright 2008, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


Create a JSF page
Add ADF Faces UI components to a page
Include databound components on a page
Create and edit data bindings

12 - 31

Copyright 2008, Oracle. All rights reserved.

Practice 12 Overview:
Creating Databound Pages
This practice covers the following topics:
Creating simple JSF pages
Creating and editing data bindings
Examining metadata files
Changing the file name of a JSP
Editing metadata files to maintain data binding

12 - 32

Copyright 2008, Oracle. All rights reserved.

Planning the User Interface

Copyright 2008, Oracle. All rights reserved.

Objectives
After completing this lesson, you should be able to do the
following:
Describe the Model-View-Controller design pattern
Explain the role of the ADF Controller
Differentiate between bounded and unbounded task flows
Create task flows
Define control flows
Define global navigation
Create routers for conditional navigation
Call methods and other task flows
Convert task flows
Use validation in the user interface
13 - 2

Copyright 2008, Oracle. All rights reserved.

Describing the Model-View-Controller (MVC)


Design Pattern

Web and Mobile

Rich Clients

Controller

13 - 3

View

Controller

Model

Model

Business Services

Business
Services

Copyright 2008, Oracle. All rights reserved.

Implementing MVC with the ADF Framework


Desktop
ADF Swing

Browser-based
JSP

Office

JSF

ADF Faces / DVT

View

Controller
Struts

JSF/ADF Task Flow


Model

ADF
ADFBindings
Bindings
Java

EJB

TopLink

BAM

BPEL

ADFbc
Web
Services

BI

Essbase

Portlets

Business
Services

Data
Services
Relational Data

13 - 4

XML Data

Legacy Data

Copyright 2008, Oracle. All rights reserved.

Packaged Apps

Technology Choices for Fusion Applications


Desktop
ADF Swing

Browser-based
JSP

Office

JSF

ADF Faces / DVT

View

Controller
Struts

JSF/ADF Task Flow


Model

ADF Bindings

Java

EJB

TopLink

BAM

BPEL

ADFbc
Web
Services

BI

Essbase

Portlets

Business
Services

Data
Services
Relational Data

13 - 5

XML Data

Legacy Data

Copyright 2008, Oracle. All rights reserved.

Packaged Apps

Characteristics of ADF Task Flows

ADF task flows are logical units of page flows that:


Offer advantages over JSF page flows:

13 - 6

Application can be broken into series of tasks


Can contain nodes other than pages
Can navigate between activities other than pages
Reusable
Shared memory scope

Can be either unbounded or bounded

Copyright 2008, Oracle. All rights reserved.

Characteristics of Unbounded ADF Task Flows

Unbounded ADF task flows often serve as the entry point to an


application, and have the following characteristics:
First entry on task flow stackthe outermost task flow
No well-defined boundary or single point of entry: use an
unbounded task flow if your application has multiple points
of entry
Can be used to define the top level flow of an application
Bookmarkable pages

13 - 7

Copyright 2008, Oracle. All rights reserved.

Working with Unbounded Task Flows

Unbounded task flow source file is adfc-config.xml.

Editor contains four tabs to show different views:

13 - 8

Diagram
Source
Overview
History

You can easily test task flow functionality in the unbounded


task flow, and convert to bounded when functioning
correctly.
Copyright 2008, Oracle. All rights reserved.

Characteristics of Bounded Task Flows

Bounded task flows:

Are modular blocks of task flow functionality for reuse, with the following
characteristics:

Single point of entry


Well-defined boundary
pageFlow Memory scope
Declarative transaction
management
Declarative Back button support

Ability to accept input parameters and


to return values
On-demand metadata loading
Fragment reuse through task flow
templates
Addressable

Consist of:

Activities

13 - 9

View
Router

Control flows between activities

Copyright 2008, Oracle. All rights reserved.

Comparing Unbounded
and Bounded Task Flows
Unbounded:

Bounded:

First entry on task flow stack

Added to task flow stack when called

No well-defined boundary or single point of entry Single point of entry, with zero or more exit
points
Cannot be used as a region on a page

Use as region on page with page fragments

Does not accept parameters

Can accept parameters and return values

Not securable on its own; uses page security

Can be secured separately from pages

Cannot manage transactions or save for later

Declarative transaction
management, save for later

Cannot be called

Must be called to be invoked

Can be bookmarked

Not bookmarkable

13 - 11

Copyright 2008, Oracle. All rights reserved.

Example: Bounded and Unbounded


ADF Task Flows
The unbounded task
flow for a shopping
application

The bounded CheckoutFlow


task flow

13 - 12

Copyright 2008, Oracle. All rights reserved.

Creating an Unbounded Task Flow

You can create an unbounded task flow by:


Adding task flow components to adfc-config.xml

13 - 13

Using the New Gallery


Converting a bounded task flow

Copyright 2008, Oracle. All rights reserved.

Creating a Bounded Task Flow


You can create a bounded task flow by doing one of the
following:
1. Using the New Gallery
OR
2
2. Extracting part of an
existing task flow
1

13 - 14

Copyright 2008, Oracle. All rights reserved.

Converting Task Flows


You can convert task flows:
Unbounded to bounded

13 - 15

Bounded to unbounded

Copyright 2008, Oracle. All rights reserved.

Using a Bounded Task Flow

Using a bounded task


flow in a region on a
page

13 - 16

Copyright 2008, Oracle. All rights reserved.

Using ADF Task Flow Components


1

13 - 17

Copyright 2008, Oracle. All rights reserved.

Defining ADF Control Flow Rules

ADF control flow rules:


Define flow through activities, such as views (pages)
Are stored in task flow configuration files
Can be defined by using:

The visual editor (Navigation Modeler)


The .xml console (Configuration Editor)
The .xml file directly
The Structure window

Are invoked by:


Command components (button, link)
Tabs or breadcrumbs
Trains

13 - 20

Copyright 2008, Oracle. All rights reserved.

Example of ADF Control Flow Rules


<af:commandButton
text="Show Items"
action="showDetail"/>

browseOrders Page:

<af:commandButton
text= "Return to Orders"
action="showOrders"/>

orderDetail Page:

13 - 21

Copyright 2008, Oracle. All rights reserved.

Using the Navigation Modeler


to Define Control Flow

13 - 22

Copyright 2008, Oracle. All rights reserved.

Using the Configuration Editor


to Define Control Flow

Use from-action
to define dynamic
control flow.

13 - 23

Copyright 2008, Oracle. All rights reserved.

Editing the.xml File to Define Control Flow


Source code editor shows errors:
...
<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>
...
13 - 24

Copyright 2008, Oracle. All rights reserved.

Using the Structure Window


to Modify a Task Flow
Freeze /
Unfreeze New
View
View

13 - 25

Copyright 2008, Oracle. All rights reserved.

Using Wildcards to Define Global Navigation

To define a global (for all pages) control flow rule, drag a


wildcard control flow rule to the page:

13 - 26

Copyright 2008, Oracle. All rights reserved.

Using Routers for Conditional Navigation

Router activities:
Use expressions
that evaluate to
true or false
Define
from-outcomes
based on the
value of the expression

13 - 28

Copyright 2008, Oracle. All rights reserved.

Defining Router Activities

2
3

13 - 29

Copyright 2008, Oracle. All rights reserved.

Calling Methods and Other Task Flows


Task flow call

Method call

13 - 30

Copyright 2008, Oracle. All rights reserved.

Defining a Task Flow Return Activity

When you return from a called task flow, the task flow return
activity specifies the outcome that is returned to the caller.

Calling task flow

13 - 31

Task flow return activity


of called task flow

Copyright 2008, Oracle. All rights reserved.

Making View Activities Bookmarkable


(or Redirecting)

Saving a view activity as a bookmark is available only in


unbounded task flows.
You can:
Designate in Property Inspector at
design time
Designate at run time with the
ViewBookmarkable() method
Optionally specify:

URL parameters
Method to invoke before view is rendered

Use the redirect option for a view activity


instead of making it bookmarkable
13 - 32

Copyright 2008, Oracle. All rights reserved.

Adding UI Code

Managed beans:
Configured in adfc-config.xml or other task flow .xml
file
Plain Old Java Objects (POJOs), Lists and Maps
Have no-argument constructor
Lazy initialization by JavaServer Faces framework as
needed

13 - 33

Copyright 2008, Oracle. All rights reserved.

Incorporating Validation into the User Interface

ADF Faces provides the following types of validation:


UI component attributes
Default ADF Faces validators
Custom ADF Faces validators

13 - 34

Use ADF Faces validation to provide immediate feedback


to users, instead of waiting for commit.
You should always define equivalent validation at the
business component level.

Copyright 2008, Oracle. All rights reserved.

Describing the Course Application:


UI Functionality

3
4

13 - 35

Copyright 2008, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


Describe the Model-View-Controller design pattern
Explain the role of the ADF Controller
Differentiate between bounded and unbounded task flows
Create task flows
Define control flows
Define global navigation
Create routers for conditional navigation
Call methods and other task flows
Convert task flows
Use validation in the user interface
13 - 36

Copyright 2008, Oracle. All rights reserved.

Practice 13 Overview:
Defining Task Flows
This practice covers the following topics:
Building an unbounded task flow
Creating a bounded task flow
Defining control flow rules
Adding routers, wildcards, and task flow calls
Converting an unbounded task flow to a bounded task flow

13 - 37

Copyright 2008, Oracle. All rights reserved.

Adding Functionality to Pages

Copyright 2008, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do the


following:
Internationalize the user interface
Use component facets
Enable users to:
Select a value from a list
Select a date from a calendar

14 - 2

Display tabular data in tables


Display hierarchical data in trees
Display text or media with icons and images
Define search forms and display results
Display data graphically
Copyright 2008, Oracle. All rights reserved.

Internationalization

14 - 3

Internationalization is the support for multiple locales.


Localization is the process in which support for a specific
locale is added.
ADF Faces components provide automatic translation (into
28 languages).

Copyright 2008, Oracle. All rights reserved.

Resource Bundles

Resource bundles contain locale-specific strings used in


an application.
Translation strings can include parameters.
You do not need to load the base resource bundle on each
page of your application.
UIResources.properties

str.browserTitle=StoreFront Sample Application


str.about=About this sample
str.copyright=\u00a9 Oracle Corp, 2007
str.contact=Contact Us
UIResources_de.properties

str.browserTitle=StoreFront Beispielanwendung
str.about=ber dieses Beispiel
str.copyright=\u00a9 Oracle Corp, 2007
str.contact=Kontakt

14 - 4

Copyright 2008, Oracle. All rights reserved.

Steps to Internationalize an Application

1. Create a base resource bundle containing all text strings


that are not part of the components themselves.
2. Create a localized resource bundle for each locale
supported by the application.
3. Register the locales with the application.
Part of
4. Use the resource bundle on your page.
the
component
CANCEL=Cancel
CANCEL=Annullieren

14 - 5

Copyright 2008, Oracle. All rights reserved.

Automatically Creating a Resource Bundle

Set project to create a resource bundle automatically:

14 - 7

Copyright 2008, Oracle. All rights reserved.

Automatically Creating a Text Resource

14 - 8

Copyright 2008, Oracle. All rights reserved.

Using Component Facets

Facets are:
Placeholders for subcomponents
Similar to detail elements
Used to specify subordinate elements such as toolbars,
headers, or footers
Displayed with the component

14 - 9

Copyright 2008, Oracle. All rights reserved.

Using ADF Faces Rich Client Components

This lesson discusses the following types of components:


Input components
List components
Dates

14 - 10

Table and tree components


Output components
Query components
Data visualization components

Copyright 2008, Oracle. All rights reserved.

Using ADF Faces Input Components

14 - 11

Copyright 2008, Oracle. All rights reserved.

Defining a List

You can define a list:


At the model layer
In the UI

14 - 13

Copyright 2008, Oracle. All rights reserved.

Defining Lists at the Model Layer


1

14 - 14

Copyright 2008, Oracle. All rights reserved.

Selecting a Value from a List

Input select components:


Item: af:selectItem
List of values: af:inputListOfValues,
af:selectOneListBox, af:selectManyListbox
Combo Box: af:inputComboboxListOfValues
Check Box: af:selectBooleanCheckbox,
af:selectManyCheckbox
Menu: af:selectOneChoice, af:selectManyChoice
Radio group: af:selectBooleanRadio
Radio item: af:selectOneRadio
Shuttles: af:selectManyShuttle,
af:selectOrderShuttle
14 - 15

Copyright 2008, Oracle. All rights reserved.

Selecting a Date

Date attributes are automatically created as af:inputDate


components:

<af:inputDate value="#{bindings.OrderDate.inputValue}"
label="#{bindings.OrderDate.label}"
required="#{bindings.OrderDate.mandatory}">
<af:convertDateTime pattern="#{bindings.OrderDate.format}"/>
</af:inputDate>

14 - 16

Copyright 2008, Oracle. All rights reserved.

Using ADF Faces Table and Tree Components

14 - 18

Copyright 2008, Oracle. All rights reserved.

Using Tables

ADF Faces table component adds to JSF table by


providing:
Column sorting
and reordering

Data filtering
Row selection
(single or
multiple rows)

14 - 19

There are many formatting options for ADF tables.

Copyright 2008, Oracle. All rights reserved.

Rendering (Stamping) the Table Data

Each child component of a column is stamped once per row, so


no embedded stamped components:
<af:table var="row" value="#{myBean.allEmployees}">
<af:column>
<af:outputText value="#{row.firstname}"/>
</af:column>
<af:column>
<af:outputText value="#{row.lastname}"/>
</af:column>
<af:table var="row" value="#{myBean.EmployeeManager}">
<af:column>
<af:outputText value="#{row.firstname}"/>
</af:column>
<af:column>
<af:outputText value="#{row.lastname}"/>
</af:column>
</af:table>
</af:table>

14 - 20

Copyright 2008, Oracle. All rights reserved.

Setting Table Attributes


Type

Description

Attribute(s)

Setting(s)

Grid Lines
(table attribute)

Lines separating
cells

verticalGridVisible
horizontalGridVisible

true or false

Banding
(table attribute)

Alternating
background
colors

rowBandingInterval
columnBandingInterval

number of rows or
columns you want to
be in each band

Column or row
headers

Labels for
columns or rows

header facet or headerText

attribute

text to display in
header

rowHeader column attribute

true or false

Column groups

Common label for


group of columns

To group columns, nest af:column tags, using the


outer af:column tag as the group, and the inner tags
as the columns within the group.

Column
formatting

Align, wrap,
width, height

Align

14 - 21

nowrap
width, height

Copyright 2008, Oracle. All rights reserved.

start,end,left,
right, center
true or false

number or %

Using Trees

14 - 23

Copyright 2008, Oracle. All rights reserved.

Using Tree Tables

Tree tables:
Display hierarchical data
in a table
Combine features of
trees and tables

14 - 24

Copyright 2008, Oracle. All rights reserved.

Providing Data for Trees

<af:tree
value="#{bindings.RootCategory1.treeModel}"
var="node">
<f:facet name="nodeStamp">
<af:outputText value="#{node}"/>
</f:facet>
</af:tree>

14 - 26

Copyright 2008, Oracle. All rights reserved.

Providing Data for Trees

A tree binding rule for the root tree node, with an additional
level for the child collection, provides the hierarchical data.

14 - 27

Copyright 2008, Oracle. All rights reserved.

Using ADF Faces Output Components


With output components, you can:
Display messages, text, icons, and
images
Play audio and video files
Source:

Design time:

<af:messages/>
<af:outputText value="Error icon:"/>
<af:icon name="error"
shortDesc="Error Icon"/>
<af:outputText value="Info icon:"/>
<af:icon name="info"/>
<af:outputText value="Media component: "/>
<af:media source="/Brian.wma"
standbyText="One moment please"/>

Run time:
14 - 28

Copyright 2008, Oracle. All rights reserved.

Using ADF Faces Query Components

14 - 29

Copyright 2008, Oracle. All rights reserved.

Using the af:query Component

Advanced mode query with dynamically added search criterion

14 - 30

Copyright 2008, Oracle. All rights reserved.

Using the af:quickQuery Component

A quick query:
Has a selectable list of attributes to search on
Has a single search criterion input field
Can have a link to more advanced search capabilities, with
switching implemented in managed bean

Quick query component in horizontal layout

14 - 32

Copyright 2008, Oracle. All rights reserved.

Creating a Query Search Form

Drag a named criteria from the Data Controls panel:

14 - 34

Copyright 2008, Oracle. All rights reserved.

Modifying Query Behavior


You can set properties that affect query behavior:
On the models view criteria:

14 - 35

On the query in the UI:

Copyright 2008, Oracle. All rights reserved.

Using
ADF Data Visualization Components
Common features:
Design time creation by
using:

14 - 36

Data Controls panel


JSF visual editor
Property Inspector
Component Palette

Live data preview at


design time
Support for data binding

Copyright 2008, Oracle. All rights reserved.

Visualizing Data

The following types of data visualization components are available:

Gauge
Graph

Gantt chart

14 - 37

Pivot table

Copyright 2008, Oracle. All rights reserved.

Geographic
map

Summary

In this lesson, you should have learned how to:


Internationalize the user interface
Use component facets
Enable users to:
Select a value from a list
Select a date from a calendar

14 - 39

Display tabular data in tables


Display hierarchical data in trees
Display text or media with icons and images
Define search forms and display results
Display data graphically
Copyright 2008, Oracle. All rights reserved.

Practice 14 Overview:
Using ADF Faces Components
This practice covers the following topics:
Using a tree component
Creating a search page
Defining LOVs

14 - 40

Copyright 2008, Oracle. All rights reserved.

Implementing Navigation on Pages

Copyright 2008, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do the


following:
Implement command buttons and links
Create menus
Menu bar
Pop-up
Context

15 - 2

Use an ADF menu model


Define navigation panes
Use breadcrumbs
Define trains
Copyright 2008, Oracle. All rights reserved.

Using ADF Faces Navigation Components

15 - 3

Copyright 2008, Oracle. All rights reserved.

Performing Navigation

Control flow rules are defined in the task flow.


A component fires an action event to generate a String
outcome corresponding to the control case
from-outcome.

Event listener responds by executing navigation.

15 - 4

Copyright 2008, Oracle. All rights reserved.

Using Buttons and Links

Command components:
Include af:commandButton and af:commandLink
Submit requests and fire action events when activated
Typically used for internal navigation

Go components:
Include af:goButton and af:goLink
Navigate directly without server-side actions
Are typically used for external navigation
Do not use control flow rules

15 - 5

Command and go components have the


same appearance.
Copyright 2008, Oracle. All rights reserved.

Defining Access Keys

Use for input, command, and go components


Set component attributes:
accessKey (input, command, or go components):
<af:goLink text="Home" accessKey="h">

textAndAccessKey (command or go components):


<af:commandButton textAndAccessKey="&amp;Home"/>

labelAndAccessKey (input components):


<af:inputSelectDate value="Choose date"
labelAndAccessKey="D&amp;ate"/>

valueAndAccessKey (input components):


<af:outputLabel for="someid"
valueAndAccessKey="Select Dat&amp;e"/>
<af:inputText simple="true" id="someid"/>

15 - 6

Can define same access key for multiple components


Copyright 2008, Oracle. All rights reserved.

Defining Tooltips

Use the shortDesc attribute:

<af:commandButton text="commandButton 1"


shortDesc="This is a command button"/>

15 - 8

Can also be defined as a UI Control Hint on EO or VO in


the model
Copyright 2008, Oracle. All rights reserved.

Using Toolbars, Toolbar Buttons, and Toolboxes

Toolbars contain other components.


Toolbar buttons have special properties (if you use toolbar
buttons, always put them on a toolbar).
Toolboxes contain multiple toolbars.
You can stretch one component on a toolbar.
Overflow buttons are automatic.

Toolbox
Toolbar
Stretched component

15 - 9

Copyright 2008, Oracle. All rights reserved.

Overflow icon

Using Menus for Navigation

You can group menu bars and toolbars in a toolbox.


Menu bars contain menus, which provide the top-level
menu.
Menu items:
Provide the vertical (drop-down) selections
Like toolbar buttons, can:

15 - 10

Display differently when selected


Perform navigation

Copyright 2008, Oracle. All rights reserved.

Creating Menus

15 - 11

Copyright 2008, Oracle. All rights reserved.

Creating Pop-Up Menus

15 - 13

Copyright 2008, Oracle. All rights reserved.

Creating Context Menus

To create a context menu, use the af:showPopupBehavior


operation.

15 - 14

Copyright 2008, Oracle. All rights reserved.

Using a Navigation Pane

You can either:


Define navigation levels
explicitly
Or
Bind to XML Menu Model
<af:navigationPane hint="bar" id="barExample">
<af:commandNavigationItem text="Bar Item 1" partialSubmit="true"
actionListener="#{demoCommandNavigationItem.navigationItemAction}"/>
<af:commandNavigationItem text="Bar Item 2" partialSubmit="true" selected="true"
actionListener="#{demoCommandNavigationItem.navigationItemAction}"/>
<af:commandNavigationItem text="Bar Item 3" partialSubmit="true"
actionListener="#{demoCommandNavigationItem.navigationItemAction}"/>
<af:commandNavigationItem text="Disabled Item" partialSubmit="true" disabled="true"
actionListener="#{demoCommandNavigationItem.navigationItemAction}"/>
<af:commandNavigationItem text="Component Guide" immediate="true" action="guide"/>
</af:navigationPane>

15 - 16

Copyright 2008, Oracle. All rights reserved.

Using Breadcrumbs

Breadcrumbs: af:breadCrumbs
Links: af:commandNavigationItem

You can:
Define breadcrumbs explicitly
Bind to XML Menu Model

15 - 17

Copyright 2008, Oracle. All rights reserved.

Using Explicitly Defined Breadcrumbs

Use static values:


<af:breadCrumbs>
<af:commandNavigationItem text=Store/>
<af:commandNavigationItem text=Media/>
<af:commandNavigationItem text=Music/>
</af:breadCrumbs>

15 - 18

Can also use EL for dynamic values


Copyright 2008, Oracle. All rights reserved.

Using XML Menu Model for Dynamic Navigation


Items
XML Menu Model:
Represents navigation for a page hierarchy in XML format
Contains the following elements:

menu
groupNode
itemNode
sharedNode

Home
Benefits
Insurance
Health

15 - 19

Employee Data

Paid
Time Off

Dental

Copyright 2008, Oracle. All rights reserved.

Creating an ADF Menu Model

Create the page hierarchy in one or more unbounded task


flows.
In the Application Navigator, right-click each task flow and
select Create ADF Menu Model.

Level 0 (root_menu)

Home

Level 1 (home_menu)
Benefits

Employee Data

Level 2 (benefits_menu)
Insurance

Level 3
(insurance_menu)

15 - 20

Health

Paid
Time Off

Dental

Copyright 2008, Oracle. All rights reserved.

Examining the ADF Menu Model


<?xml version="1.0" encoding="windows-1252" ?>
<menu xmlns="http://myfaces.apache.org/trinidad/menu">
<groupNode id="groupNode_Insurance" idref="itemNode_Dental"
label="Insurance">
<itemNode id="itemNode_Dental" label="Dental" action="adfMenu_Dental"
focusViewId="/Dental"/>
<itemNode id="itemNode_Health" label="Health" action="adfMenu_Health"
focusViewId="/Health"/>
</groupNode>
</menu>

15 - 22

Copyright 2008, Oracle. All rights reserved.

Binding the Navigation Pane to an


XML Menu Model

Home
Benefits

Paid Time Off

Insurance
Health

15 - 23

Employee Data

Dental

Levels and Hints


0 tabs
1 buttons
2 bar
3 list

Copyright 2008, Oracle. All rights reserved.

Binding Breadcrumbs to an XML Menu Model


To link breadcrumbs to the menu model:
Set Var and Value properties on the breadcrumbs
component
Add a navigation item to the nodeStamp facet and set its
properties just as for navigation panes item
Copy the breadcrumbs component to each page
Home
Benefits
Insurance
Health
15 - 25

Employee Data

Paid
Time Off

Dental
Copyright 2008, Oracle. All rights reserved.

Defining a Sequence of Steps


A train is a specialized type of task flow with linear steps:
Navigation items rendered by af:train

Navigation buttons rendered


by af:trainButtonBar

Creating the task flow for


a train

15 - 26

Copyright 2008, Oracle. All rights reserved.

Creating a Train

<af:train value="#{controllerContext.currentViewPort.taskFlowContext.trainModel}"/>
<af:trainButtonBar
value="#{controllerContext.currentViewPort.taskFlowContext.trainModel}"/>
<af:outputText value="Train Stop 1"/>

15 - 28

Copyright 2008, Oracle. All rights reserved.

Skipping a Train Stop

To skip a train stop, perform the following steps:


Set the skip property of train stop to true.
Typically set to expression that evaluates to true or
false, such as managed bean method or property.
If true, users cannot navigate to that train stop.

15 - 29

Copyright 2008, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


Implement command buttons and links
Create menus
Menu bar
Pop-up
Context

15 - 30

Use an ADF menu model


Define navigation panes
Use breadcrumbs
Define trains

Copyright 2008, Oracle. All rights reserved.

Practice 15 Overview:
Using ADF Faces Navigation Components
This practice covers the following topics:
Creating buttons and links to implement navigation
Adding breadcrumbs
Defining a train

15 - 31

Copyright 2008, Oracle. All rights reserved.

Achieving the Required Layout

Copyright 2008, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do the


following:
Use complex layout components
Explain how to use ADF Faces skins
Use dynamic page layout

16 - 2

Copyright 2008, Oracle. All rights reserved.

Using ADF Faces Layout Components


You can use the following components to achieve the desired
layout:

16 - 3

af:spacer
af:separator
af:panelSplitter
af:panelStretchLayout
af:panelAccordion
af:panelFormLayout
af:panelTabbed
af:showDetail

af:panelGroupLayout
af:panelCollection
af:panelHeader
af:showDetailHeader
af:group
af:panelList
af:panelBox
af:panelBorderLayout

Copyright 2008, Oracle. All rights reserved.

Adding Spaces and Lines


Output text on a page
No spacers

With spacers and separator

<af:form>
<af:spacer width="10"/>
<af:outputText value="outputText1"/>
<af:spacer width="10"/>
<af:outputText value="outputText2"/>
<p><af:spacer height="10"/></p>
<af:separator/>
<p><af:spacer height="10"/></p>
<af:spacer width="10"/>
<af:outputText value="outputText3"/>
<af:spacer width="10"/>
<af:outputText value="outputText4"/>
</af:form>

16 - 4

Copyright 2008, Oracle. All rights reserved.

Stretching Components

Enable stretching so that a component fills the designated area,


such as browser window:

16 - 5

Copyright 2008, Oracle. All rights reserved.

Enabling Automatic Component Stretching:


Panel Splitter or Panel Stretch Layout
Table on page:

Same table within


stretched Panel Stretch
Layout component:

16 - 6

Copyright 2008, Oracle. All rights reserved.

Stretching a Table Column

Table with no stretched columns:

Table with last column stretched :

16 - 7

Copyright 2008, Oracle. All rights reserved.

Creating Resizable Panes


Panel Splitters
af:panelSplitter
Horizontal
orientation:

16 - 8

Nested:

Copyright 2008, Oracle. All rights reserved.

Vertical
orientation:

Printing Layout Panel Content

<af:commandButton text="Printable Page">


<af:showPrintablePageBehavior/>
</af:commandButton>

16 - 9

Copyright 2008, Oracle. All rights reserved.

Creating Collapsible Panes


with the Panel Splitter Component
Attributes:
Behavior

collapsed positionedFromEnd

16 - 10

true

false

First pane hidden; second pane


stretches

true

true

Second pane hidden; first pane


stretches

false

true

Both panes displayed, with


splitterPosition governing size
of 2nd pane and splitter arrow pointed
toward 2nd pane

false

false

Both panes displayed, with


splitterPosition governing size
of 1st pane and splitter arrow pointed
toward 1st pane

Copyright 2008, Oracle. All rights reserved.

Creating Collapsible Panes


with the Panel Accordion
With default settings

Characteristics of Panel
Accordion component:
Does not automatically
stretch it children
Panes cannot be resized
at run time only expand
or contract
Panes defined by
showDetailItem

<af:panelAccordion>
<af:showDetailItem text="This is a pane"/>
<af:showDetailItem text="This is another pane"/>
</af:panelAccordion>
16 - 11

Copyright 2008, Oracle. All rights reserved.

Panel Accordion Overflow


Automatic overflow icons
to display
content out of view

16 - 12

Copyright 2008, Oracle. All rights reserved.

Setting Panel Accordion Properties


<af:showDetailItem
text="Browse Products"
inlineStyle="width:100%;
height:100%;" flex=1">

<af:showDetailItem
text="Selected Product"
inlineStyle="width:100%;
height:100%;" flex="2">

With discloseMany="true"
discloseNone="true"

16 - 13

Copyright 2008, Oracle. All rights reserved.

Arranging Items in Columns or Grids

Use af:panelFormLayout with labels above or below the


text:

Use rows and maxColumns attributes to arrange items in the


form:

16 - 15

Copyright 2008, Oracle. All rights reserved.

Creating Stacked Tabs

Use af:panelTabbed; use af:showDetailItem for each


tab:
<af:panelTabbed position="both">
<af:showDetailItem text=Categories">
<! Root categories table here -->
</af:showDetailItem>
<af:showDetailItem text=Subcategories">
<! Subcategories table here -->
</af:showDetailItem>
<af:showDetailItem text=Products">
<! Products table here -->
</af:showDetailItem>
</af:panelTabbed>

16 - 17

Copyright 2008, Oracle. All rights reserved.

Hiding and Displaying Groups of Content

<af:showDetail>
<af:panelGroupLayout layout="vertical">
<af:outputText value="Indexed Child 1"/>
<af:outputText value="Indexed Child 2"/>
</af:panelGroupLayout>
</af:showDetail>

16 - 18

Copyright 2008, Oracle. All rights reserved.

Arranging Items Horizontally or Vertically, with


Scrollbars
Panel group layout arrangements

16 - 20

Panel group layout inside stretched


panel splitter does not stretch its children

Copyright 2008, Oracle. All rights reserved.

Displaying Table Menus, Toolbars, and Status


Bars
Use panelCollection for table with menus and toolbars:

16 - 22

Copyright 2008, Oracle. All rights reserved.

Creating Titled Sections and Subsections

Panel header
component with
sections and
subsections:
af:panelHeader

Show detail header component with sections that expand or


collapse: af:showDetailHeader

16 - 24

Copyright 2008, Oracle. All rights reserved.

Grouping Related Components


Use af:group to:
Add multiple components to a facet

16 - 25

Group related
child components

<af:panelFormLayout>
<af:inputDate label="Pick a date"/>
<!-- first group -->
<af:group>
<af:selectManyCheckbox label=
"Select all that apply">
<af:selectItem label="Coffee" value="1"/>
//other select items
</af:selectManyCheckbox>
<af:inputText label="Special instructions"
rows="3"/>
</af:group>
<!-- Second group -->
<af:group>
<af:inputFile label="File to upload"/>
<af:inputText label="Enter passcode"/>
</af:group>
<af:inputText label="Comments" rows="3"/>
<af:spacer width="10" height="15"/>
<f:facet name="footer"/>
</af:panelFormLayout>

Copyright 2008, Oracle. All rights reserved.

Displaying a Bulleted List

Use af:panelList to display a bulleted list in one or more


columns.
To create columns, nest inside af:panelFormLayout and set
the rows property:

Create a list hierachy with nested


af:panelList components:

Specify bullet style


by setting
list-style-type to:
disc
square
circle

16 - 26

decimal
lower-alpha
upper-alpha
Copyright 2008, Oracle. All rights reserved.

Displaying Items in a Content Container


Offset by Color
Use af:panelBox to display items in a content container
offset by color.

16 - 27

Copyright 2008, Oracle. All rights reserved.

Arranging Content Around a Central Area:


Panel Border Layout
Panel Border Layout: Predefined named areas around a
central area where direct child content is displayed.

16 - 28

Copyright 2008, Oracle. All rights reserved.

Arranging Content Around a Central Area:


Panel Stretch Layout
The panel stretch layout component:
Can arrange content around a central area
Does not render anything by itself
Has fewer facets than panel border, with no direct children

The panel stretch layout component at design time


16 - 30

Copyright 2008, Oracle. All rights reserved.

Using ADF Faces Skins

ADF Faces skins:


Provide a global style sheet for an application
Use a CSS file to set styles
Use a resource bundle for text

Included skins:
Oracle
Minimal
Simple

16 - 31

Copyright 2008, Oracle. All rights reserved.

Using Dynamic Page Layout

Dynamic page layout is made possible by using:


Expression Language (EL)
Partial Page Rendering (PPR)

16 - 32

Copyright 2008, Oracle. All rights reserved.

Using Expression Language to Conditionally


Display Components

You can use EL for any of a components attributes.


Example of setting attributes with EL:
<af:selectOneChoice
value="#{bindings.CardTypeCode.inputValue}"
label="#{bindings.CardTypeCode.label}"
partialTriggers="PaymentType"
rendered="#{bindings.PaymentTypeCode.inputValue == 'CC'}">
<f:selectItems value="#{bindings.CardTypeCode.items}"/>
</af:selectOneChoice>

16 - 33

Copyright 2008, Oracle. All rights reserved.

Characteristics of Partial Page Rendering (PPR)

PPR:
Is enabled by ADF Faces
Enables redrawing only a portion of a page
Requires server round-trip:
Rerenders only a portion of the server-side component tree
Downloads only the appropriate fragment of HTML

Currently certified on IE 7.0+ and Firefox 2.0.0.2 +


Supported (but not certified) on Firefox 3.0 and Safari 3.1.2
Implements certain ADF Faces patterns
Single component refresh
Cross-component refresh

16 - 34

Can be enabled declaratively or programmatically


Copyright 2008, Oracle. All rights reserved.

Enabling PPR Declaratively


Triggering component:
(must have unique ID and
cause a Submit)

Target component:
(must specify triggering
component)
16 - 35

Copyright 2008, Oracle. All rights reserved.

Native PPR Example

16 - 37

Copyright 2008, Oracle. All rights reserved.

Declarative PPR Example

<af:commandToolbarButton
id="updateToolbarButton"
text="Update Shopping Cart"/>

<af:table
//bindings
partialTriggers="deleteToolbarButton
menuDelete updateToolbarButton">
//list of columns
</af:table>

16 - 38

<af:commandToolbarButton
id="deleteToolbarButton"
text="Delete/>

<af:commandMenuItem
id="menuDelete" partialSubmit="true"
text="Delete"/>

Copyright 2008, Oracle. All rights reserved.

Enabling PPR Programmatically

Why?
Need logic to determine if component should refresh
Refresh should occur on only one of several events that a
triggering component may fire (for example, on row selection
in table, use a selection listener)

16 - 40

How? Use the addPartialTarget method.

Copyright 2008, Oracle. All rights reserved.

Enabling Automatic PPR

To enable automatic PPR:


Select a binding in the
page definition file
Set ChangeEventPolicy
to ppr

16 - 41

Copyright 2008, Oracle. All rights reserved.

Conforming to PPR Guidelines

Purposes of PPR:
Improve application performance
Improve the user experience

Guidelines for using PPR:


http://www.oracle.com/technology/tech/blaf/specs/ppr.html

PPR should not be used:


When navigating to another page
When response times may be long
When multiple sections of the page need to be redrawn

16 - 42

PPR may cause accessibility issues.

Copyright 2008, Oracle. All rights reserved.

Summary

In this lesson, you should have learned to:


Use complex layout components
Explain how to use ADF Faces skins
Use dynamic page layout

16 - 43

Copyright 2008, Oracle. All rights reserved.

Practice 16 Overview:
Using ADF Faces Layout Components
This practice covers the following topics:
Modifying the layout of pages
Defining partial page rendering

16 - 44

Copyright 2008, Oracle. All rights reserved.

Ensuring Reusability

Copyright 2008, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do the


following:
Explain the benefits of reusing components
Create and use a resource catalog
Create and use ADF libraries
Define and use a task flow template
Create and use a page template
Create a declarative component and use it on a page
Create a page fragment and use it in a bounded task flow
Use a bounded task flow as a region

17 - 2

Copyright 2008, Oracle. All rights reserved.

Benefits of Reusability

Designing code to be reused has the following benefits:


Increased developer productivity
Fewer bugsdebug once
Consistency
In functionality
In look and feel

17 - 3

Easier maintainability
Rapid adaptability

Copyright 2008, Oracle. All rights reserved.

Designing for Reuse

Guidelines:
Use naming conventions.

Avoid naming conflicts.


Facilitate identifying component functionality.

Standardize storage by agreeing on:

Type of repository needed


Storage and organization
Access methods

Make components available for reuse by using:


Resource catalog
ADF library

17 - 4

Copyright 2008, Oracle. All rights reserved.

Using a Resource Catalog

A resource catalog:
Enables application developers to find and incorporate
shared resources, such as libraries containing ADF BC
Model Objects, validators, message bundles, and so on,
that were created by other members of the team
Provides a federated view of the resources from one or
more otherwise unrelated repositories in a unified search
and browse UI
Enables you to store libraries comprising a common
repository that can be used by the developers building any
client application
Ensures that all application developers use the same
business model without any discrepancies
17 - 5

Copyright 2008, Oracle. All rights reserved.

Creating a Resource Catalog

Creating a catalog:

Adding resources to
a catalog:
17 - 6

Copyright 2008, Oracle. All rights reserved.

Reusing Components

ADF Library enables you to reuse components:


Package them into ADF Library JAR files.
Add them to a resource catalog.
Add the library to a project to use its
components.

17 - 7

Copyright 2008, Oracle. All rights reserved.

Creating an ADF Library


1

17 - 8

Copyright 2008, Oracle. All rights reserved.

Adding an ADF Library to a Project


by Using the Resource Palette
1

17 - 9

Copyright 2008, Oracle. All rights reserved.

Removing an ADF Library from a Project

Remove by:
Using Resource
Palette

17 - 10

Using Project Properties

Copyright 2008, Oracle. All rights reserved.

Restricting BC Visibility in Libraries

Set Library Private property for a business component to true


if you dont want consumers to see the object in the library JAR.

17 - 11

Copyright 2008, Oracle. All rights reserved.

Types of Reusable Components

ADF supports reusing the following types of components:


Data controls
Application modules
Business components
Task flows
Task flow templates
Page templates
Declarative components

17 - 12

Copyright 2008, Oracle. All rights reserved.

Using Task Flow Templates

17 - 13

Copyright 2008, Oracle. All rights reserved.

Characteristics of Page Templates

Page templates:
Are reusable
Enable consistent look across pages or page fragments
Are built from standard ADF components
Cannot be nested
Use partial page refresh when navigating between pages that
use the same template
Use three types of files:
Page-specific definition file (.jspx)
Definition file for all templates: pagetemplate-metadata.xml
Application or library file (.cpx)

17 - 14

Copyright 2008, Oracle. All rights reserved.

Creating a Page Template

17 - 15

Copyright 2008, Oracle. All rights reserved.

Creating a Page Template

Header (with Title)

Menu Regions

A
Named Facets

B
News Portlet

17 - 16

Copyright 2008, Oracle. All rights reserved.

Editing a Page Template

Header (with Title)

Header (with Title)

A
Must continue
to use the
same named
facets

B
Footer
Modified Template

Original Template

17 - 17

Copyright 2008, Oracle. All rights reserved.

Applying a Page Template to a Page

17 - 18

Copyright 2008, Oracle. All rights reserved.

Characteristics of Declarative Components

Declarative components:
Are component definitions that are reusable across
applications
When changed, affect all pages that use them
Are made up of any number of other components
Do not have data binding in their definition
Can be made available for reuse in the Component Palette
Are defined only at design time in:
One .jspx file for each component
One declarativecomp-metadata.xml file for all
declarative components in a project
17 - 19

Copyright 2008, Oracle. All rights reserved.

Creating a Declarative Component

The JSF Declarative


Component dialog box:
Is invoked with New >
Web Tier > JSF > JSF
Declarative Component
Creates the
<af:componentDef>
tag in .jspx file

17 - 21

Creates metadata

Copyright 2008, Oracle. All rights reserved.

Using a Declarative Component


on a Page
To use a declarative component on a page:
Deploy the components project as an ADF library JAR file
Add the ADF library to your current project.
Select the ADF library from the Component Palette dropdown list.
Select the declarative component and drag it to your page,
providing values for any attributes.

17 - 22

Copyright 2008, Oracle. All rights reserved.

Characteristics of Page Fragments

Page fragments:
Are built like regular pages
Have page definition files like regular pages do
Are not defined as a full Web page
Can be displayed within a page that contains other content
Cannot contain af:document or f:view tags

17 - 23

Cannot be run on their own

Copyright 2008, Oracle. All rights reserved.

Creating a Page Fragment

You can create a page fragment by:


1. Using the New Gallery
OR
2. Double-clicking a view in a bounded task flow that uses
page fragments
1

17 - 24

Copyright 2008, Oracle. All rights reserved.

Using a Page Fragment on a Page

You can use a page fragment on a page by:


Inserting the jsp:include tag:

The included page fragment uses the binding context of the


consuming page.
Page definition file for page fragment is not loaded (doesnt use
bindings).

Inserting a bounded task flow with page fragments as a


region in your page; the page fragment can have its own
binding context

17 - 25

Modifying the page fragment affects all pages that use it


(but check the overall layout of consuming pages).

Copyright 2008, Oracle. All rights reserved.

Characteristics of Regions

An ADF region:
Represents a task flow as part of a page
Is similar to a portlet, but for local functionality
Can share information and transaction boundaries with
other page content

17 - 26

Copyright 2008, Oracle. All rights reserved.

Wrapping a Task Flow as a Region


Drag bounded task flow to page as a region:

Default activity displays


at design and run time:

17 - 27

Copyright 2008, Oracle. All rights reserved.

Converting a Bounded Task Flow to Use Page


Fragments
To use a bounded task flow containing pages as a region,
convert to a task flow with page fragments.

17 - 28

Copyright 2008, Oracle. All rights reserved.

Deciding Which to Use

You can use a page template when you want:


Similar page layout to be used on multiple pages
Similar look on multiple pages

You can use a declarative component when you want to:


Use a similar grouping of components on multiple pages or
applications
Select the component from the Component Palette

You can use a bounded task flow when you want to:
Reuse a set of activities and control flows
Use multiple page fragments in a region on a page
Create a portlet from a set of activities and control flows

17 - 29

Copyright 2008, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


Explain the benefits of reusing components
Create and use a resource catalog
Create and use ADF libraries
Define and use a task flow template
Create and use a page template
Create a declarative component and use it on a page
Create a page fragment and use it in a bounded task flow
Use a bounded task flow as a region

17 - 30

Copyright 2008, Oracle. All rights reserved.

Practice 17 Overview:
Implementing Reusability
This practice covers the following topics:
Converting bounded task flows to use page fragments
Creating a page template for the main page and for the
checkout flow
Using bounded task flows in regions on the main page

17 - 31

Copyright 2008, Oracle. All rights reserved.

Passing Values
Between
UI Elements

Copyright 2008, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do the


following:
Define the data model to reduce the need to pass values
Use a managed bean to hold values
Use page parameters
Use task flow parameters
Pass values from containing pages to regions

18 - 2

Copyright 2008, Oracle. All rights reserved.

Holding Values in the Data Model


(Business Components)

Define transient attributes to hold values.


Row concurrency can coordinate multiple pages without
parameter passing.
Defining view links in the data model:
Coordinates master and detail pages
Re-executes queries as needed
Reduces the need to pass parameters between UI pages
and regions

18 - 3

Copyright 2008, Oracle. All rights reserved.

Holding Values in Managed Beans

Managed beans are optional and can be used to:


Hold values
Store state

How?
Managed properties
Scoped managed bean variables

18 - 4

Copyright 2008, Oracle. All rights reserved.

Using Managed Properties

Managed bean variables that are exposed through getter


and setter methods
Configured in the .xml file of the task flow

Possible values:

18 - 5

null
Literal string
Lists and Maps
Value binding expression (EL)

Copyright 2008, Oracle. All rights reserved.

Managed Properties: Examples


Literal string:
<managed-bean>
<managed-property>
<property-name>label</property-name>
<value>Hello World</value>
</managed-property>

EL (accessing a managed bean):


<managed-bean>
<managed-property>
<property-name>label</property-name>
<value>#{Userbean['firstname']}</value>
</managed-property>

18 - 6

Copyright 2008, Oracle. All rights reserved.

Using Scoped Managed Bean Variables

JSF scopes:
application
session
request
none

Additional ADF Faces scopes:


view (ADF Faces)
pageFlow (ADF Faces)
backingBean (only for page fragments or
declarative components)

Why use scopes?


Save state of model
Enables passing values to other pages or phases

pageFlow scope:
Retains values for current process (page flow) only
Independent of other processes, unless using LaunchEvent
Can be accessed via EL or Java
Can be explicitly cleared

18 - 7

Copyright 2008, Oracle. All rights reserved.

Accessing pageFlowScope from a Page

You can access pageFlowScope variables by using:

EL:
<af:commandButton
text="#{pageFlowScope.buttonBean.label}"
action="#{pageFlowScope.buttonBean.action}"/>

Java:
import java.util.Map;
import
org.apache.myfaces.trinidad.context.RequestContext;
. . .
Map pageFlowScope =
RequestContext.getCurrentInstance().getPageFlowScope()
;
Object myObject = pageFlowScope.get("myObjectName");

18 - 9

Copyright 2008, Oracle. All rights reserved.

Using pageFlowScope Without Writing Java Code

<af:table
The Master page stores an employee
value="#{myManagedBean.allEmployees}"
row in pageFlowScope variable
var="emp" rowSelection="single">
empDetail.
<af:column headerText="Name">
<af:outputText value="#{emp.name}"/>
</af:column>
<af:column
The Detail page retrieves employee
headerText="Department Number">
<af:outputText
data from pageFlowScope variable
value="#{emp.deptno}"/>
empDetail.
</af:column>
<h:panelGrid columns="2">
<af:column headertext="Select">
<af:outputText value="Firstname:"/>
<af:commandButton
<af:inputText
text="Show more details"
value="#{pageFlowScope.empDetail.name}"/>
action="showEmpDetail">
<af:outputText value="Email:"/>
<af:setActionListener
<af:inputText
from="#{emp}"
value="#{pageFlowScope.empDetail.email}"/>
to=
<af:outputText value="Hiredate:"/>
"#{pageFlowScope.empDetail}"/>
<af:inputText
</af:commandButton>
value="#{pageFlowScope.empDetail.hiredate}"/>
</af:column>
<af:outputText
value="Salary:"/>
</af:table>
<af:inputText
value="#{pageFlowScope.empDetail.salary}"/>
</h:panelGrid>

2
3

18 - 10

Copyright 2008, Oracle. All rights reserved.

Using Parameters

You can use:


Page parameters
Task flow parameters
Region parameters
View activity parameters
Task flow call activity parameters

18 - 11

Copyright 2008, Oracle. All rights reserved.

Using Page Parameters

Define page parameters in the Structure window for a page


definition file:

#{bindings.nameToPass}

18 - 12

Copyright 2008, Oracle. All rights reserved.

The Job of the Page Parameter


Receives a value and stores it in a parameter in the binding
container:
Containing
page
parameter

18 - 13

Parameter
type

Parameter name

Parameter value

Parameter function

output

nameToPass

#{'Pam'}

Receive a value and store


it in binding container.

Copyright 2008, Oracle. All rights reserved.

Using Task Flow Parameters

1. The pname parameter is passed into the task flow, and its
value is assigned to the pageFlowScope variable pname.
2.

18 - 14

Inside the task flow, activities and pages can get the value
of the parameter using the EL expression:
#{pageFlowScope.pname}

Copyright 2008, Oracle. All rights reserved.

The Job of the Task Flow Parameter


Stores input value into page flowscoped variable:

Containing
page
parameter

Parameter
type

Parameter name

Parameter value

Parameter function

output

nameToPass

#{'Pam'}

Receive a value and store


it in binding container.

?
Bounded
task flow
parameter

input

Page
fragment in
task flow

#{pageFlowScope.pname}

18 - 16

pname

#{pageFlowScope.
pname}

Copyright 2008, Oracle. All rights reserved.

Store parameter value in


page flowscoped
variable.

Using Region Parameters

1. Define a page parameter and a parameter on the task flow


as in previous slides.
2. In the page definition file for the containing page, define
the same parameter on the region and set its value to the
page parameter:

3. Within the task flow, use pageFlowScope to access the


<af:outputLabel value="Hello, "/>
parameter value:

<af:spacer width="10" height="10"/>


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

18 - 17

Copyright 2008, Oracle. All rights reserved.

The Job of the Region Parameter


Passes the value from the page to its task flow:
Parameter
type

Parameter name

Parameter value

Parameter function

Containing
page
parameter

output

nameToPass

#{'Pam'}

Receive a value and store


it in binding container.

Region
parameter

output

pname

#{bindings.
nameToPass}

Store binding value as


parameter.

Bounded
task flow
parameter

input

pname

#{pageFlowScope.
pname}

Store parameter value in


page flowscoped
variable.

Page
fragment in
task flow

#{pageFlowScope.pname}

18 - 18

Copyright 2008, Oracle. All rights reserved.

Developing a Page Independently of a Task Flow


Page not aware of the task flows page flowscoped variable:
Parameter
type

Parameter name

Parameter value

Parameter function

Containing
page
parameter

output

nameToPass

#{'Pam'}

Receive a value and store


it in binding container.

Region
parameter

output

pname

#{bindings.
nameToPass}

Store binding value as


parameter.

Bounded
task flow
parameter

input

pname

#{pageFlowScope.
pname}

Store parameter value in


page flowscoped
variable.

?
Page
fragment in
task flow

18 - 19

#{pageFlowScope.ename}

Copyright 2008, Oracle. All rights reserved.

Passing Parameters from a Task Flow to One of


Its Pages
Use view activity parameter:

18 - 20

Copyright 2008, Oracle. All rights reserved.

The Job of the View Activity Parameter


Populates the page flowscoped variable expected by the page:
Parameter
type

Parameter name

Parameter value

Parameter function

Containing
page
parameter

output

nameToPass

#{'Pam'}

Receive a value and store


it in binding container.

Region
parameter

output

pname

#{bindings.
nameToPass}

Store binding value as


parameter.

Bounded
task flow
parameter

input

pname

#{pageFlowScope.
pname}

Store parameter value in


page flowscoped
variable.

View activity
parameter

internal

#{pageFlowScope.
ename}

#{pageFlowScope.
pname}

Store page flowscoped


variable into page flow
scoped variable expected
by the reusable page.

Page
fragment in
task flow

#{pageFlowScope.ename}

18 - 21

Copyright 2008, Oracle. All rights reserved.

Summary: Passing a Value from a Page


to a Reusable Page Fragment in a Region
Containing Page

Page parameter
Region
parameter

Region
Task Flow
View Activity

Task flow
parameter

View activity
parameter

Page Fragment

18 - 22

Copyright 2008, Oracle. All rights reserved.

Passing Values to a Task Flow from a Task Flow


Call Activity
1. Define an input parameter on the task flow call activity:

2. Define an input parameter on the called task flow.


18 - 23

Copyright 2008, Oracle. All rights reserved.

Returning Values to a Calling Task Flow

To return a value, you must specify:


Return value definitions on the called task flow
Return values on the task flow call activity in the calling task
flow

18 - 25

Names must match.

Copyright 2008, Oracle. All rights reserved.

Deciding Which Type of Parameter to Use

Parameters are designed to:


Improve reusability
Encapsulate functionality

18 - 27

You can use more than one type of parameter to achieve


these goals.

Copyright 2008, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


Define the data model to reduce the need to pass values
Use a managed bean to hold values
Use page parameters
Use task flow parameters
Pass values from containing pages to regions

18 - 28

Copyright 2008, Oracle. All rights reserved.

Practice 18 Overview:
Passing Values Between Pages
This practice covers the following topics:
Conditionally displaying tables based on parameters
Changing a panel header title based on parameters

18 - 29

Copyright 2008, Oracle. All rights reserved.

Responding to Application Events

Copyright 2008, Oracle. All rights reserved.

Objectives
After completing this lesson, you should be able to do the
following:
Configure and use managed beans to contain code to
respond to events
Describe the different types of events
Use phase listeners
Create event listeners
Define action listeners
Create value change listeners
Describe ADF Faces enhanced event handling
List other types of server events used by ADF Faces
components
Explain how ADF components use AJAX events
Use contextual events to coordinate regions
19 - 2

Copyright 2008, Oracle. All rights reserved.

Adding UI Code

Managed beans:
Configured in adfc-config.xml or other task flow .xml
file
Plain Old Java Objects (POJOs), Lists and Maps
Have no-argument constructor
Lazy initialization by JavaServer Faces framework as
needed

19 - 3

Copyright 2008, Oracle. All rights reserved.

Creating Managed Beans


2. Browse for existing Java
class or create new class.

1. Right-click command button.

3. Search class.

5. Create method.
4. Select class.

6. Bean automatically gets configured


in adfc-config.xml file (see next slide).
19 - 4

Copyright 2008, Oracle. All rights reserved.

Registering Existing Java Classes


as Managed Beans
Use Overview tab of task flow.

19 - 5

Copyright 2008, Oracle. All rights reserved.

Configuring Managed Beans

Entry in adfc-config.xml:
<managed-bean>
<managed-bean-name> DepartmentBean </managed-bean-name>
<managed-bean-class> sample.DepartmentsManagedBean
</managed-bean-class>
<managed-bean-scope> request </managed-bean-scope>
</managed-bean>

Skeleton for new managed


bean (add your own code):

19 - 6

Copyright 2008, Oracle. All rights reserved.

Referencing Managed Beans

Use in Expression Language on JSF Page:

<af:inputText
value="#{DepartmentBean.firstName}"/>

Use in Java code:

FacesContext facesContext =
FacesContext.getCurrentInstance();
ELContext elContext = facesContext.getELContext();
ExpressionFactory expressionFactory =
facesContext.getApplication().getExpressionFactory();
ValueExpression exp =
expressionFactory.createValueExpression(elContext,
"#{DepartmentBean}", DepartmentsManagedBean.class);
DepartmentsManagedBean dept =
(DepartmentsManagedBean)exp.getValue(elContext);

19 - 7

Copyright 2008, Oracle. All rights reserved.

Describing JSF and ADF Life-Cycle Roles

The JSF life cycle handles presentation:

Submission of values on the page


Validation for components
Navigation
Displaying the components on the resulting page
Saving and restoring state

The ADF life cycle handles data:


Preparing and updating the data model
Validating the data at the model layer
Executing methods on the business layer

19 - 8

Copyright 2008, Oracle. All rights reserved.

Coordinating JSF and ADF Life Cycles

19 - 9

Copyright 2008, Oracle. All rights reserved.

Specifying When to Refresh Binding Executables

19 - 11

Refreshing iterator reconnects it with RowSetIterator


object.
Refreshing invoke action binding invokes the action.
You can set the Refresh property to determine when to
refresh.

Copyright 2008, Oracle. All rights reserved.

Specifying Whether to Refresh Binding


Executables

Set RefreshCondition to an EL expression evaluating


to true (default) or false.

Example: A search page that initially shows no data has


iterator binding with settings:
RefreshCondition=
"#{!adfFacesContext.isInitialRender}"
(false when page is first rendered)
Refresh="renderModel"

19 - 13

Copyright 2008, Oracle. All rights reserved.

Describing Types of Events

JSF supports:
Phase events
Execute as part of the JSF and ADF life cycle
Can be used to augment standard behavior

Action events
Occur when a command component is activated, such as
when a user clicks a button or a link
Return a control flow outcome

Value change events


Occur when the local value of a input component changes,
such as when a user selects a check box
Used for managing UI elements

19 - 14

Copyright 2008, Oracle. All rights reserved.

Using Phase Listeners

JSF life cycle


Postback

Restore/Create
Component Tree
(View)

Apply
Request
Values

Process
Events,
Validation

Render
Response

Invoke
Application

Update
Model

Initial
Request

19 - 15

Copyright 2008, Oracle. All rights reserved.

Using Event Listeners

Event Object
Ive been clicked!
Does anyone care?

Yes Im listening!
Now Ill get to work

Event Listener

Event Source

19 - 16

Copyright 2008, Oracle. All rights reserved.

Responding to Action Events

19 - 17

Command components raise action events.


Code to respond to the action event can be in the backing
bean or external class.
Stub code is generated by JDeveloper on demand.
The action is registered in the page source.
Action events are called in the Invoke Application phase of
the life cycle.
Action methods are the last to execute after other listeners,
such as valueChange events.

Copyright 2008, Oracle. All rights reserved.

Creating Action Methods

To create an action method:


1. Invoke the action binding
editor.
2. Choose existing bean and
method, or create new.

JDeveloper:
If the bean does not exist, creates Java class and registers
as a managed bean
If the method does not exist, creates a method stub in the
managed bean class
Adds the method to the action property of component

19 - 18

Add your own code.


Action methods return a String outcome.
Copyright 2008, Oracle. All rights reserved.

Using Action Listeners

Action listeners differ from action methods:


Action listeners:
Contain code to respond
to an action
Do not return a value
Execute after value
change listeners

Action methods:
Are used for navigation

Return a String outcome

Execute last

However, both can be


initiated by the same
action, such as a
button click.

19 - 19

Copyright 2008, Oracle. All rights reserved.

Value Change Events

19 - 20

Input components raise value change events.


Code for the value change listener can be in the backing
bean or external class.
Stub code is generated by JDeveloper.
The value change event is registered in the page source.
Value change events are processed in the Invoke
Application phase of the life cycle.
Value change events fire before action events.

Copyright 2008, Oracle. All rights reserved.

Listening for Value Change Events

Select the input component in the visual editor.


Edit the valueChangeListener property and select a bean
and method, or create a new one.
JDeveloper:
Creates the method in the managed bean if it doesnt already
exist
Adds the method to the valueChangeListener property in
the page source

19 - 21

Add your code.

Copyright 2008, Oracle. All rights reserved.

Event and Listener Execution Order

Following is the order in which the events and listeners fire:


1. Validator (managed bean method that performs validation
on the components value)
2. Value change listener (managed bean method to handle
value-change events)
3. Action listener (managed bean method to handle action
events)
4. Action method
(managed bean
method to return a
logical outcome
String that is used
in navigation)
19 - 22

Copyright 2008, Oracle. All rights reserved.

ADF Faces Enhanced Event Handling

ADF Faces adds to JSF event handling by providing:


Partial page rendering (PPR)
JavaScript

19 - 23

Copyright 2008, Oracle. All rights reserved.

Using JavaScript in ADF Faces Applications

You can use JavaScript:


To create custom components
To respond to events
In individual pages or bundled in a library

19 - 24

Copyright 2008, Oracle. All rights reserved.

Other ADF Faces Server Events

Property Inspector of ADF Faces components displays


appropriate event listeners:

19 - 25

Copyright 2008, Oracle. All rights reserved.

Using Table Model Methods in a Selection


Listener
You can do the
following
programmatically:
Make row current:
setRowIndex()
or setRowKey().

Access data in
the current row:
getRowData().

Obtain number of rows:


getRowCount().

Determine if you are at end


of table: isRowAvailable()

19 - 27

Copyright 2008, Oracle. All rights reserved.

Using Tree Model Methods in a Selection Listener

You can do the


following
programmatically:
Determine if a row
has children:
isContainer()

Access children of
current row:
enterContainer()

Revert to parent
collection:
exitContainer()

19 - 28

Copyright 2008, Oracle. All rights reserved.

Additional AJAX Events

Additional event types include AJAX events:

19 - 29

Copyright 2008, Oracle. All rights reserved.

Characteristics of the Contextual Event


Framework

Contextual events:
Provide a way to coordinate regions
Containing
Page

Can be invoked and consumed only by method action of a


data control

19 - 30

Producer and consumer may be the same or different data


controls.
Copyright 2008, Oracle. All rights reserved.

Contextual Events Overview


Containing page
Event
map
Payload
method

19 - 31

Consumer
method
Producer
region

Consumer
region

Copyright 2008, Oracle. All rights reserved.

Using the Contextual Event Framework to


Coordinate Page Regions
Payload
Method

Handler
Method

1
Producer

2
Producer
PageDef

19 - 32

Containing
Page

3
Consumer

5
Containing
PageDef

Copyright 2008, Oracle. All rights reserved.

Consumer
PageDef

Using the Contextual Event Framework to


Coordinate Page Regions: Step 1

Producer

Containing
Page

Define a page
that contains
two regions.

19 - 33

Copyright 2008, Oracle. All rights reserved.

Consumer

Using the Contextual Event Framework to


Coordinate Page Regions: Step 2
Construct
an event
payload.

Producer

19 - 34

Payload
Method

Containing
Page

Copyright 2008, Oracle. All rights reserved.

Consumer

Using the Contextual Event Framework to


Coordinate Page Regions: Step 3
Payload
Method

Producer

19 - 35

Invoke the
payload method.

Containing
Page

Copyright 2008, Oracle. All rights reserved.

Consumer

Using the Contextual Event Framework to


Coordinate Page Regions: Step 4
Payload
Method

Producer

Producer
PageDef

19 - 36

Containing
Page

Supply a value
for the payload
method argument.

Copyright 2008, Oracle. All rights reserved.

Consumer

Using the Contextual Event Framework to


Coordinate Page Regions: Step 5
Payload
Method

Producer

Producer
PageDef

19 - 37

Containing
Page

Raise an event
when the
payload method
is invoked.

Copyright 2008, Oracle. All rights reserved.

Consumer

Using the Contextual Event Framework to


Coordinate Page Regions: Step 6
Payload
Method

Producer

Handler
Method

Containing
Page

Producer
PageDef

19 - 38

Copyright 2008, Oracle. All rights reserved.

Create an
event handler.

Consumer

Using the Contextual Event Framework to


Coordinate Page Regions: Step 7
Payload
Method

19 - 39

Handler
Method

Producer

Bind the
event
Containing handler.

Consumer

Producer
PageDef

Containing
PageDef

Consumer
PageDef

Page

Copyright 2008, Oracle. All rights reserved.

Using the Contextual Event Framework to


Coordinate Page Regions: Step 8
Payload
Method

Handler
Method

Producer

Containing
Page

Consumer

Producer
PageDef

Containing
PageDef

Consumer
PageDef

Map the event.

19 - 40

Copyright 2008, Oracle. All rights reserved.

Using the Contextual Event Framework to


Coordinate Page Regions: Step 9
Payload
Method

Producer

Handler
Method

Containing
Page

Consumer

Specify producer
region refreshing.
Specify consumer
region refreshing .

Producer
PageDef

19 - 41

Containing
PageDef

Copyright 2008, Oracle. All rights reserved.

Consumer
PageDef

Summary
In this lesson, you should have learned how to:
Configure and use managed beans to contain code to
respond to events
Describe the different types of events
Use phase listeners
Create event listeners
Define action listeners
Create value change listeners
Describe ADF Faces enhanced event handling
List other types of server events used by ADF Faces
components
Explain how ADF components use AJAX events
Use contextual events to coordinate regions
19 - 42

Copyright 2008, Oracle. All rights reserved.

Practice 19 Overview:
Responding to Events
This practice covers the following topics:
Defining task flow parameters
Using a contextual event to coordinate user selection in a
tree in one region with the display in another region
Using phase listeners

19 - 43

Copyright 2008, Oracle. All rights reserved.

Implementing Transactional Capabilities

Copyright 2008, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do the


following:
Explain ADF BC transaction handling
Implement task flow transaction control
Handle transaction exceptions
Define response to the browsers Back button
Enable save for later functionality

20 - 2

Copyright 2008, Oracle. All rights reserved.

Handling Transactions with ADF BC

20 - 3

Application modules handle transaction and concurrency


support.
No coding is required unless you want to customize the
default behavior.
For nested application modules, the outermost application
module provides the transaction context for the others.

Copyright 2008, Oracle. All rights reserved.

Default ADF Model Transactions

Database table

ADF BC
Entity Object

Databound components on a JSP

20 - 4

ADF BC
View Object

Binding Container

Copyright 2008, Oracle. All rights reserved.

ADF BC
Application Module

ADF Model
Data Control

Transactions in Task Flows

20 - 5

Copyright 2008, Oracle. All rights reserved.

Controlling Transactions in Task Flows

20 - 6

Copyright 2008, Oracle. All rights reserved.

Transaction Support Features


of Bounded Task Flows
Transaction:
Inherit with savepoint
or New

Back Button
Support
Save for later

Declarative
Commit
/ Rollback

20 - 7

Copyright 2008, Oracle. All rights reserved.

Specifying Task Flow Transaction Start Options


Defining task flow transaction options:

In Property Inspector

In Structure window

20 - 8

Copyright 2008, Oracle. All rights reserved.

Specifying Task Flow Return Options


Commit or rollback must be specified for
some transactions:

You specify commit or rollback on transaction


return activities:

20 - 9

Copyright 2008, Oracle. All rights reserved.

Enabling Transactions on a Task Flow


1

20 - 11

Copyright 2008, Oracle. All rights reserved.

Sharing Data Controls

Data control scopes:


Shared (default): Called flow shares data control instances
with calling flow
Isolated: Called flow has unique instance of data controls

<data-control-scope>
<shared/>
</data-control-scope>

20 - 13

Copyright 2008, Oracle. All rights reserved.

Handling Transaction Exceptions

You should designate an exception handling activity on


transactional task flows.
Can be any activity type, such as:
View: To display a message
Router: To call a method depending on the type of exception

20 - 15

Copyright 2008, Oracle. All rights reserved.

Designating an Exception Handler Activity

<exception-handler>ShowError</exception-handler>
...
...
<view id="ShowError"></view>

20 - 16

Copyright 2008, Oracle. All rights reserved.

Defining Response to the Back Button

The task-flow-reentry property determines if user


can return to an exited task flow by clicking the
browsers Back button:

reentry-allowed: OK
reentry-not-allowed: Throws exception
reentry-outcome-dependent: Depends on
outcome from exited task flow
Return
to exited
task flow?

20 - 17

Copyright 2008, Oracle. All rights reserved.

Saving for Later

Quitting time
Ill work some
more on this
tomorrow.

20 - 19

Next morning
Greatright
where I
left off!

Copyright 2008, Oracle. All rights reserved.

Enabling Explicit Save for Later

Contains
button that
performs save
for later

Calls
createSavePoint
to add a
save-point-id

Contains field for


user to enter
save-point-id
to pass to restore
activity

Restores
application state
and data to what
was captured in
save-point-id

Save for later task flow

20 - 21

Copyright 2008, Oracle. All rights reserved.

Enabling Implicit Save for Later

To enable implicit save for later:


Change a setting in adfc-config.xml

Mark the task flow as critical

You can use the task flow editor or the Property Inspector to mark the
task flow as critical.

20 - 23

Copyright 2008, Oracle. All rights reserved.

Restoring Savepoints

A Save Point Restore activity:


Restores the state of
the application
Deletes the savepoint
from its persistence store
Optionally performs additional logic with a Save Point
Restore Finalizer
Is required in applications that are responsible for restoring
save-point-id (not necessarily the same application
that was saved for later)

20 - 24

Copyright 2008, Oracle. All rights reserved.

Setting Global Save for Later Properties

Set properties in the adfc-config.xml file:


savepoint-expiration
savepoint-manager
savepoint-datasource
enable-implicit-savepoints

20 - 26

Copyright 2008, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


Explain ADF BC transaction handling
Implement task flow transaction control
Handle transaction exceptions
Define response to the browsers Back button
Enable save for later functionality

20 - 27

Copyright 2008, Oracle. All rights reserved.

Practice 20 Overview:
Controlling Transactions
This practice covers the following topics:
Implementing commit functionality in the shopping cart
Adding transaction control to the checkout flow
Adding the ability to insert, update, and delete suppliers

20 - 28

Copyright 2008, Oracle. All rights reserved.

Implementing Security
in
ADF Applications

Copyright 2008, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to:


Explain the need to secure Web applications
Describe security aspects of a Web application
Implement ADF security:
Authentication
Authorization:

21 - 2

In the data model


In the UI for task flows and pages

Access security information programmatically


Use Expression Language to extend security capabilities

Copyright 2008, Oracle. All rights reserved.

Benefits of Securing Web Applications

Web applications often connect with a single database


user account. Therefore, separate application users
accounts must be utilized.
Identity can be used to:
Ensure that only authenticated users can access the
application
Restrict access to parts of the application
Customize the UI (such as pick lists)
Provide the user name for auditing
Set up a virtual private database (VPD)

21 - 3

Copyright 2008, Oracle. All rights reserved.

Examining Security Aspects


Authentication: Is this user allowed to
access this application?
Application

Resource 1

Resource 2

Resource 3

Authorization: Is this users role


allowed to access this resource?

Resource 4

21 - 4

Copyright 2008, Oracle. All rights reserved.

Resource 5

Resource 6

ADF Security Framework: Overview

The ADF security framework provides:

Standard features required to secure ADF applications


More granular declarative security
Hierarchical roles with permission inheritance
Utility methods for use in EL expressions
Different access defined for different roles at same URL

Uses JAAS enforced by ADF binding servlet filter


Can authenticate users against a resource provider:
LDAP
OID
XML-based

21 - 5

Copyright 2008, Oracle. All rights reserved.

Configure ADF Security Wizard:


Configuring ADF Security Authentication
Tools > Configure ADF Security

21 - 6

Copyright 2008, Oracle. All rights reserved.

Configure ADF Security Wizard:


Choosing the Authentication Type
Most commonly used:
HTTP basic authentication:
It uses browser login dialog box.
Cached credentials prevent logout.

Form-based authentication: Developer-designed login


page

21 - 7

Copyright 2008, Oracle. All rights reserved.

Using Form-Based Authentication

You implement authentication in the UI by:


Configuring the login in web.xml (done by Configure ADF
Security Wizard)

Setting up a login page to accept user credentials with the


following elements:
A form attribute: action="jsecurity_check"
An input text item: name="j_username"
An input password: name="j_password"

21 - 8

Presenting the login page in HTTPS mode

Copyright 2008, Oracle. All rights reserved.

Configure ADF Security Wizard:


Choosing the Identity Store
Choices:
Application XML:
Used for small-scale applications or testing
Uses the Oracle Platform Security for Java's file-based
repository
Configured in JDeveloperuser and role information stored
in jazn-data.xml

LDAP:
Identity store configured outside of JDeveloper
Scalable and secure
Integrates with Oracle Single Sign On

21 - 9

Copyright 2008, Oracle. All rights reserved.

Configure ADF Security Wizard:


Choosing the Welcome Page

21 - 10

Specify page where user should go upon


authentication
Ignored if page specified on URL
If no page specified, user returns to the login page

Copyright 2008, Oracle. All rights reserved.

Configure ADF Security Wizard:


Enabling ADF Authorization

21 - 11

Choose the ADF


Authentication and
Authorization option.
Select an option for testing.
To change existing
authorizations,
use overview
editor for
jazn-data.xml.

Copyright 2008, Oracle. All rights reserved.

Files Modified by Configure ADF Security Wizard:


web.xml
web.xml modifications:

21 - 12

ADF authentication servlet definition


and mapping
Security constraint
Login configuration

Copyright 2008, Oracle. All rights reserved.

Other Files Modified or Created


by Configure ADF Security Wizard
adf-config.xml

jps-config.xml

jazn-data.xml

Modified
Created

21 - 13

<CredentialStoreContext
<CredentialStoreContext credentialStoreClass=
credentialStoreClass=
"oracle.adf.share.security.providers.jazn.JAZNCredentialStore"
"oracle.adf.share.security.providers.jazn.JAZNCredentialStore"
credentialStoreDefaultUser="anonymous"
credentialStoreDefaultUser="anonymous"
credentialStoreLocation="./credential-jazn-data.xml"/>
credentialStoreLocation="./credential-jazn-data.xml"/>
<sec:JaasSecurityContext
<sec:JaasSecurityContext initialContextFactoryClass=
initialContextFactoryClass=
"oracle.adf.share.security.JAASInitialContextFactory"
"oracle.adf.share.security.JAASInitialContextFactory"
jaasProviderClass=
jaasProviderClass=
"oracle.adf.share.security.providers.jps.JpsSecurityContext"
"oracle.adf.share.security.providers.jps.JpsSecurityContext"
authorizationEnforce="true"
authorizationEnforce="true"
<serviceProviders>
authenticationRequire="true"/>
<serviceProviders>
authenticationRequire="true"/>
<serviceProvider
<serviceProvider
class="oracle.security.jps.internal..."
class="oracle.security.jps.internal..."
...
...
</serviceProvider>
</serviceProvider>
Based Authentication
uthentication
...
...
<serviceInstances>
<serviceInstances>
<jazn-realm
<serviceInstance
<jazn-realm default="jazn.com">
default="jazn.com">
<serviceInstance
<realm>
provider="credstore.provider"
<realm>
provider="credstore.provider"
<name>jazn.com</name>
...
<name>jazn.com</name>
...
</realm>
</serviceInstance>
</realm>
</serviceInstance>
</jazn-realm>
...
</jazn-realm>
...
<policy-store>
<jpsContexts
<policy-store>
<jpsContexts default="Storefront-12">
default="Storefront-12">
...
<jpsContext
...
<jpsContext name="anonymous">
name="anonymous">
...
<serviceInstanceRef
...
<serviceInstanceRef ref="credstore"/>
ref="credstore"/>
</policy-store>
...
</policy-store>
...
</jpsContext>
</jpsContext>
</jpsContexts>
</jpsContexts>

Copyright 2008, Oracle. All rights reserved.

Enabling Users to Access Resources

To give users access:


Define a security realm in the identity store:
Create users.
Create roles.
Assign users to roles.

Define an application policy in the policy store


Create application roles.
Map the identity roles to the application roles.
Grant the application roles access to resources.

21 - 14

Copyright 2008, Oracle. All rights reserved.

Defining Users and Roles in the Identity Store


Defining a Realm

Opening the Properties editor

Adding user credentials


to the default realm

Adding a user to
a role in the
identity store

21 - 15

Copyright 2008, Oracle. All rights reserved.

Defining Security Policies

A security policy is a set of grants made to roles.


To define a security policy:
Create application roles
Assign identity store roles to application roles
Grant permissions to roles

21 - 16

Copyright 2008, Oracle. All rights reserved.

Defining Application Roles in the Policy Store

Policy store is in
jazn-data.xml.

21 - 17

Copyright 2008, Oracle. All rights reserved.

Assigning Identity Store Roles


to Application Roles
Users

Roles
clerk

manager

Mapping an identity role


to an application role
app_clerk

21 - 18

app_manager

Copyright 2008, Oracle. All rights reserved.

Granting Permissions to Roles

You can associate roles to grants on resources:


Authorization Point Grants Issued On:

Defined In:

Groups of pages

Bounded task flows

jazn-data.xml editor

Individual pages

Page definitions *

jazn-data.xml editor

Rows

Entity objects or
attributes

EO security and authorization


editors

* To secure page with no


data, create an empty
page definition file.

21 - 19

Copyright 2008, Oracle. All rights reserved.

Securing Groups of Pages


(Bounded Task Flows)

Prevent unauthorized access to secured task flows


Provide developers with ability to:
Secure a bounded task flow as a logical entity
Write security-aware bounded task flows and pages

21 - 20

Copyright 2008, Oracle. All rights reserved.

Securing Individual Pages


(Page Definitions)

21 - 21

Determines whether user is allowed to navigate to (view) a


page
Not needed on pages in secured task flows

Copyright 2008, Oracle. All rights reserved.

ADF BC Model Authorization

Purpose is to:
Prevent unauthorized access to entity objects or attributes
Enable developers to:
Secure access to an entire entity object or only certain
attributes
Specify the actions that members of a role can perform on
entity objects or attributes

21 - 22

Copyright 2008, Oracle. All rights reserved.

Securing Row Data


(Entity Objects or Attributes)
You can enable security on:
Entire
entity
objects:
ADF Business
Component
Entity object

Attribute of EO

21 - 23

Securable
Operation

Individual
attributes:
Expected Mapped
Action
Implementation

read

Read

View rows of result set.

removeCurrentRow

Delete

Delete a row from the


bound collection.

update

Update

Update any attribute.

update

Update

Update specific
attribute.

Copyright 2008, Oracle. All rights reserved.

Granting Privileges on Entity Objects or


Attributes

21 - 24

In Structure window, right-click


entity object or attribute and
select Edit Authorization.
Select privileges to grant to
application roles.

Copyright 2008, Oracle. All rights reserved.

Application Authentication at Run Time

Two types:
Implicit: Based on JAAS permissions for anonymousrole role

Explicit: Based on security constraint on authentication


servlet that you can define by using the Configure ADF
Security Wizard

21 - 25

Copyright 2008, Oracle. All rights reserved.

ADF Security: Implicit Authentication


J2EE Container

Implicit Authentication

JAAS Security

anonymous (User Principal)


anonymous-role (Role Principal)
Added to the Subject

/app/Public.jspx
P1

ADF
Security
Filter

P2

*.jsp
*.jspx
P3

/app/MyPage.jspx
1

Public.jsp

/adfAuthentication?success_url=/app/MyPage.jspx

2
MyPage.jspx

User: Bob

3
Authentication servlet
protected by J2EE
Security Constraint,
Triggers Container
login process

No
Session

Redirect to success
URL=/app/MyPage.jspx
as per #1

5
adfAuthentication
Servlet

J2EE Security
4

submit=j_security_check()

21 - 26

Container Authentication
Logic

Copyright 2008, Oracle. All rights reserved.

BOB

Enterprise
Identity
Management

ADF Security: Explicit Authentication


Explicit Authentication

Login Link on the


Public Page

/app/Public.jspx

/adfAuthentication?success_url=/app/Public.jspx
J2EE Security Constraint

User: Bob

2
Authentication servlet
protected by J2EE
Security Constraint,
Triggers Container
login process

No
Session

J2EE Container

J2EE Security

Redirect to success
URL=/app/MyPage.jspx
as per #1

adfAuthentication
Servlet

submit=j_security_check()

21 - 28

Container Authentication
Logic

Copyright 2008, Oracle. All rights reserved.

BOB

Enterprise
Identity
Management

ADF Security: Authorization at Run Time

J2EE Container

ADF Security performs


authorization check
ADF
Security
Filter

Bob has No

View
Privilege Defined
on the Page.

SecPage.jspx

/app/SecPage.jsp
View

/app/MyPage.jspx
*.jsp
*.jspx

/app/Public.jsp

User: Bob

PageDefs

PageDefs used as
Security Def end
points

Privilege is
granted to a Role
of which Bob is a
MyPage.jspx member.

JAAS
JAAS AuthZ
AuthZ
request
request

View Privilege
granted to the

or

anyone
Public.jsp

Policy Store
Bob is a member of the
Staff role in the policy
store.
Unlike J2EE Container
Security, authorization
is not path based.

21 - 29

<grant>
<principal>
<type>role</type>
<name>Staff</name>
</principal>
<permission>
<name>MyPage</name>
<actions>view</actions>
</permission>
</grant>

Copyright 2008, Oracle. All rights reserved.

Administrator
HR
Dev
Staff
Sales
Clerks

Role.

Programmatically Accessing
ADF Security Context
Is ADF security turned on?
if (ADFContext.getCurrent().getSecurityContext().isAuthorizationEnabled())
{ }

Is the user logged on?


public boolean isAuthenticated() {
return ADFContext.getCurrent().getSecurityContext().isAuthenticated(); }

Who is the user?


public String getCurrentUser() {
return ADFContext.getCurrent().getSecurityContext().getUserName(); }

Is the user in a specified role?


public boolean isUserInRole(String role) {
return ADFContext.getCurrent().getSecurityContext().isUserInRole(role); }

21 - 30

Copyright 2008, Oracle. All rights reserved.

Using Expression Language


to Extend Security Capabilities
You can integrate expression language in three ways:
Using a security proxy bean:
<af:commandLink action="accounts"
rendered="#{userInfo.admin}"
text="Manage Accounts"/>

See next slide for source


of this expression.

Using the JSF-Security Project extensions:


<af:commandLink action="accounts"
rendered="#{securityScope.userInRole['admin']}"
text="Manage Accounts"/>

Using built-in global security expressions:


<af:commandLink action="accounts"
rendered="#{securityContext.userInRole['admin']}"
text="Manage Accounts"/>

21 - 31

Copyright 2008, Oracle. All rights reserved.

Using a Security Proxy Bean

A managed bean can expose a Boolean property that the UI


expressions can consume.
Example: UserInfo bean:
public boolean isAdmin() {
return (ADFContext.getCurrent().
getSecurityContext().isUserInRole("admin"));
}

Example: UI expression:
#{userInfo.admin}

Checking for multiple roles is a problem; you could end up


writing many convenience methods.
21 - 32

Copyright 2008, Oracle. All rights reserved.

Using the JSF-Security Project Extensions

Expression

Purpose

#{securityScope.securityEnabled}

Is security on?

#{securityScope.remoteUser}

User name of the


authenticated user

#{securityScope.authType}

Type of authentication in
use: BASIC, DIGEST, FORM

#{securityScope.
userInRole['admin,manager']}

Is the user in any of these


roles?

#{securityScope.
userInAllRoles['admin,manager']}

Is the user in all of these


roles?

21 - 33

Copyright 2008, Oracle. All rights reserved.

Using Global Security Expressions


Expression

Purpose

#{securityContext.userName}

User name of the authenticated


user

#{securityContext.userInRole
['role list']}

Is the user in any of these roles?

#{securityContext.userInAllRoles
['role list']}

Is the user in all of these roles?

#{securityContext.
userGrantedPermission
['permission']}

Does the user have this


permission granted?

#{securityContext.taskflowViewable Does the user have view


['target']}
permission on the target task
flow?
#{securityContext.regionViewable
['target']}

21 - 34

Does the user have view


permission on the target region?

Copyright 2008, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


Explain the need to secure Web applications
Describe security aspects of a Web application
Implement ADF security:
Authentication
Authorization:

21 - 35

In the data model


In the UI for task flows and pages

Access security information programmatically


Use Expression Language to extend security capabilities

Copyright 2008, Oracle. All rights reserved.

Practice 21 Overview:
Implementing ADF Security
This practice covers the following topics:
Configuring the application to use ADF Security
Defining users, roles, and application roles
Implementing entity object security
Accessing security context programmatically

21 - 36

Copyright 2008, Oracle. All rights reserved.

Deploying ADF Applications

Copyright 2008, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do the


following:
Create deployment profiles
Configure deployment options
Use JDeveloper to deploy an application
Use WebLogic Server administration console to deploy an
application
Use Ant to deploy an application
Test the deployed application

22 - 2

Copyright 2008, Oracle. All rights reserved.

Steps in the Deployment Process

Deployment tasks:
Prepare application or project for deployment.
Prepare Oracle WebLogic Server (WLS) for ADF
deployment.
Deploy the application with one of the following
techniques:
Deploy directly from JDeveloper to WLS.
Deploy to an EAR file and use application server tool for
deploying to the application server.
Use a script to deploy.

22 - 3

Copyright 2008, Oracle. All rights reserved.

Steps in the Deployment Process

Deployment tasks:
Prepare application or project for deployment.
Prepare Oracle WebLogic Server (WLS) for ADF
deployment.
Deploy the application with one of the following
techniques:
Deploy directly from JDeveloper to WLS.
Deploy to an EAR file and use application server tool for
deploying to the application server.
Use a script to deploy.

22 - 4

Copyright 2008, Oracle. All rights reserved.

Configuring Deployment Options

To configure an application for deployment, you create:


Deployment profile, which can be one of three types:
ADF Business Components: Business Component Java
ARchive (JAR)
Fusion Web application: Enterprise ARchive (EAR) and Web
ARchive (WAR) deployment profiles
Fusion Web application with customizations: Oracle ARchive
(OAR) and Metadata ARchive (MAR)

22 - 5

Deployment descriptors

Copyright 2008, Oracle. All rights reserved.

Creating Deployment Profiles


Deployment profiles:
Specify how application is packaged for deployment
Can be application level or project level
Creating an application
deployment profile

22 - 6

For the Model project

Copyright 2008, Oracle. All rights reserved.

For the
View-Controller
project

Specifying Deployment Profile Options


Deployment profile options:
Specified in profile
properties
Different depending on
type of profile

22 - 7

Copyright 2008, Oracle. All rights reserved.

Creating a
Business Components Deployment Profile
You can create business components deployment profiles by
using one of the following:
Context menu
Project Properties dialog box
New Gallery

22 - 8

Copyright 2008, Oracle. All rights reserved.

Web Module Deployment

It is used for deploying ADF BC applications to a Web tier.


It contains ADF BC components and JSPs and servlets.
It is used for deploying JSP, JSF, and servlet applications.
Deployment is to a Java EE archive (.ear or .war file).

JDeveloper creates the archive file and deployment


descriptors.

22 - 9

Copyright 2008, Oracle. All rights reserved.

Typical Web Application Deployment Example

To deploy a typical Web application that uses ADF Business


Components:
Create a WAR deployment profile for the UI project
Create an EAR deployment profile for the application
Deploy the application to the EAR file or directly to an
application server

22 - 10

Copyright 2008, Oracle. All rights reserved.

Example: Creating a WAR Deployment Profile for


the UI Project
1

Creates both .war and


.ear files

2
4
Context root becomes part of URL
to access the Web application.
22 - 11

Copyright 2008, Oracle. All rights reserved.

Example: Creating an EAR Deployment Profile for


the Application

22 - 12

Copyright 2008, Oracle. All rights reserved.

Using Deployment Descriptors

Deployment descriptors are:


Project configuration files deployed with the application
XML files of several types depending on project
technologies and deployment target
Created in various ways:
By JDeveloper wizards
As XML source files
By using the New Gallery

22 - 13

Copyright 2008, Oracle. All rights reserved.

Steps in the Deployment Process

Deployment tasks:
Prepare application or project for deployment.
Prepare Oracle WebLogic Server (WLS) for ADF
deployment.
Deploy the application with one of the following
techniques:
Deploy directly from JDeveloper to WLS.
Deploy to an EAR file and use application server tool for
deploying to the application server.
Use a script to deploy.

22 - 14

Copyright 2008, Oracle. All rights reserved.

Preparing the Oracle WebLogic Server

To deploy an application to Oracle WebLogic Server:


Install the ADF Runtime to the WebLogic installation
Create and configure the WebLogic domain
Create a JDBC data source
Additionally, you must configure the application to use the WLS
data source that you created.

22 - 15

Copyright 2008, Oracle. All rights reserved.

Installing the ADF Runtime to the WebLogic


Installation

If you need to, use the Oracle


Installer to add ADF Runtime to
the existing WebLogic installation.
Not needed if you:
Are using integrated WLS
Installed WLS with the
JDeveloper installer and selected
ADF Runtime option when
installing

22 - 16

Copyright 2008, Oracle. All rights reserved.

Creating and Configuring the WebLogic Domain

You need to have a WebLogic domain that is configured to


accept ADF applications.
Use the Oracle WebLogic Configuration Wizard to:
Create a new domain that is configured for ADF

OR

Configure an existing
domain for ADF
22 - 17

Copyright 2008, Oracle. All rights reserved.

Creating a JDBC Data Source

2
4

22 - 19

Copyright 2008, Oracle. All rights reserved.

Configuring the Data Control to Use


the Data Source
Define a new AM configuration:

Configure the data control:

22 - 21

Copyright 2008, Oracle. All rights reserved.

Steps in the Deployment Process

Deployment tasks:
Prepare application or project for deployment.
Prepare Oracle WebLogic Server (WLS) for ADF
deployment.
Deploy the application with one of the following
techniques:
Deploy directly from JDeveloper to WLS.
Deploy to an EAR file and use application server tool for
deploying to the application server.
Use a script to deploy.

22 - 23

Copyright 2008, Oracle. All rights reserved.

Creating a Connection to an
Application Server

Start the Application Server Connection Wizard: Right-click


IDE Connections > New Application Server Connection.
Enter the following:
Connection name
Connection type
Username and
password
Host name and RMI port

22 - 24

Test the connection.

Copyright 2008, Oracle. All rights reserved.

Example: Deploying the Application

1. Invoke the Application


menu.
2. Select Deploy.

3. Select a deployment
profile.
4. Select to deploy to an
EAR file, an existing
connection, or a new
connection.

3
4

22 - 25

Copyright 2008, Oracle. All rights reserved.

Steps in the Deployment Process

Deployment tasks:
Prepare application or project for deployment.
Prepare Oracle WebLogic Server (WLS) for ADF
deployment.
Deploy the application with one of the following
techniques:
Deploy directly from JDeveloper to WLS.

Deploy to an EAR file and use application server tool


for deploying to the application server.
Use a script to deploy.

22 - 26

Copyright 2008, Oracle. All rights reserved.

Deploying the Application from the WebLogic


Administration Server Console
1

22 - 27

Copyright 2008, Oracle. All rights reserved.

Steps in the Deployment Process

Deployment tasks:
Prepare application or project for deployment.
Prepare Oracle WebLogic Server (WLS) for ADF
deployment.
Deploy the application with one of the following
techniques:
Deploy directly from JDeveloper to WLS.
Deploy to an EAR file and use application server tool for
deploying to the application server.

Use a script to deploy.

22 - 28

Copyright 2008, Oracle. All rights reserved.

Using Ant to Automate the Deployment Process

Ant is an XML scripting syntax


that enables you to build and deploy
Java EE applications.
Define named series of tasks
(called targets).
Define dependencies between targets.

Advantages of Ant:

22 - 29

Well-documented
Widely adopted
Easy to configure
Extensible

Obtain Ant information at: http://ant.apache.org


Copyright 2008, Oracle. All rights reserved.

Creating an Ant Buildfile in JDeveloper

22 - 30

Copyright 2008, Oracle. All rights reserved.

Defining Ant Deployment Tasks

Tasks for handling archive files:


<jar>
<war>
<ejbjar>
<unjar>
<ear>
<unwar>
Tasks for local server deployment:
<copy>
<delete>
<java>

22 - 31

Tasks for remote deployment:


<sleep>
<ftp>
<condition> <get>

Copyright 2008, Oracle. All rights reserved.

Adding Elements to the Buildfile

Adding a target:

Adding a task:

22 - 32

Copyright 2008, Oracle. All rights reserved.

Running Ant on Buildfile Targets

Defining project buildfile and default target

Invoking the Run Ant Wizard


to specify advanced options.

Running
on a target

Running on
a project
Running Ant from the toolbar

22 - 33

Copyright 2008, Oracle. All rights reserved.

Creating an External Ant Tool

22 - 35

Copyright 2008, Oracle. All rights reserved.

Implementing Security in Deployed Applications

After deployment, you need to migrate to WLS the


applications:
Database credential store
Security policies

To help with this migration, you can:


Run command-line script
OR
Use simplified method with the supplied Ant script

22 - 36

Copyright 2008, Oracle. All rights reserved.

Deployment Testing During Development

Bind to an Oracle WebLogic Server instance:

22 - 38

Copyright 2008, Oracle. All rights reserved.

Deployment Testing for Production

Use a URL for production testing:

22 - 39

Copyright 2008, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


Create deployment profiles
Configure deployment options
Use JDeveloper to deploy an application
Use WebLogic Server administration console to deploy an
application
Use Ant to deploy an application
Test the deployed application

22 - 40

Copyright 2008, Oracle. All rights reserved.

Practice 22 Overview:
Deploying the Web Application
This practice covers the following topics:
Creating deployment profiles
Using a WebLogic Server data source
Creating an application server connection
Deploying the application from JDeveloper
Deploying the application from the WLS console
Running the deployed application

22 - 41

Copyright 2008, Oracle. All rights reserved.

You might also like