You are on page 1of 390

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY.

COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

D57569

Edition 1.0

D53942GC10

September 2010

Oracle University and Egabi Solutions use only

Oracle Fusion Middleware 11g: Build Java EE Applications


Volume II Student Guide

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Authors
Bijoy Choudhury Gary Williams

Copyright 2009, 2010 Oracle. All rights reserved. Disclaimer 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. 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 Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners.

Technical Contributors and Reviewers


Ken Cooper Joe Greenwald Taj-ul Islam Pete Laseau Adam Leftik Mike Lehmann Jacobo Marcos Glenn Maslen Duncan Mills Lynn Munsinger Nagavalli Pataballa Holger Rasmussen Anand Sidgiddi Glenn Stokol Vasily Strelnikov Bonnie Vaughan

Editors
Aju Kumar Amitha Narayan

Graphic Designer
Priya Saxena

Publishers
Sujatha Nagendra Joseph Fernandez

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Contents

2 Fundamentals of Java EE Technology Objectives 2-2 Java Platform, Enterprise Edition 2-3 Java EE Platform 2-4 Distributed Multitiered Applications 2-5 Benefits of the Java EE Platform 2-6 Java EE Platform and APIs 2-8 Quiz 2-11 Java EE Components 2-12 Business-Tier Components 2-13 Enterprise JavaBeans (EJB) 2-14 Enterprise JavaBeans Application Architecture 2-16 Types of Enterprise JavaBeans 3.0 2-17 Enterprise JavaBeans 3.0 Component Architecture 2-18 Java Persistence API (JPA) 2-19 Quiz 2-21 Web Services 2-22 Java EE Web Services Architecture 2-23
iii

Oracle University and Egabi Solutions use only

1 Introduction Objectives 1-2 Course Objectives 1-3 Course Agenda 1-4 Fundamentals of Java EE Technology 1-9 Designing Java EE Applications 1-10 Developing a Web Application Using Servlets 1-11 Developing a Web Application Using JavaServer Pages 1-12 Accessing Resources with JNDI and Dependency Injection 1-13 Developing the Business Logic with Session Beans 1-14 Developing the Persistence Layer with JPA Entities 1-15 Manipulating JPA Entities with the EntityManager API 1-16 Developing the Business Logic with Web Services 1-17 Developing the Web Interface Using JavaServer Faces 1-18 Planning Navigation and Page Flow 1-19 Handling Application Events 1-20 Asynchronous Communication with Message-Driven Beans 1-21 Managing Transactions with Session and Message-Driven Beans 1-22 Securing Java EE Applications with JAAS 1-23 Packaging and Deploying Java EE Applications 1-24 Troubleshooting Java EE Applications 1-25 Summary 1-26

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

3 Designing Java EE Applications Objectives 3-2 Realizing the Benefits of Java EE 3-3 Java EE Issues 3-4 Design Patterns 3-5 Java EE Design Patterns 3-6 Implementing a Session Facade Pattern 3-7 Defining the MVC Architecture 3-8 The Model 3-9 The View 3-10 The Controller 3-11 Designing a Java EE Application 3-12 Quiz 3-13 Struts: Overview 3-14 Struts Components 3-15 Struts Architecture 3-16 Struts Page Flow Design 3-17 JSF and Struts 3-19 Implementing the User Interface with JSF and Core Java EE Patterns 3-20 Selecting a Persistence Strategy 3-21
iv

Oracle University and Egabi Solutions use only

Client-Tier Components 2-25 Java EE Web-Tier Components 2-26 Java EE Web Application Architecture 2-28 What Is a Servlet? 2-29 What Is a JavaServer Page? 2-30 What Is JavaServer Faces? 2-31 Web-Tier Components: Summary 2-32 Java EE Applications 2-33 Packaging Java EE Applications 2-34 Packaging Java EE Application Components 2-35 Security in Java EE Applications 2-36 Using Deployment Descriptors for Declarative Security 2-37 Quiz 2-38 Java EE Server 2-39 Oracle WebLogic Server 10.3 2-41 WebLogic Server Domain 2-42 WebLogic Server Servers 2-44 Administration Server 2-45 Managed Server 2-46 WebLogic Server Machines 2-47 JDeveloper and Java EE 2-48 Oracle JDeveloper 11g Environment 2-49 Oracle JDeveloper 11g Visual Design Tools 2-50 Summary 2-51 Practice: Overview 2-52

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Quiz 3-22 What Is a Data Source? 3-23 What Is a Connection Pool? 3-24 Benefits of Data Sources Plus Connection Pools 3-25 JDBC Data Source Architecture 3-26 Data Source Architecture: Connecting 3-27 Creating a Data Source in WebLogic Server 3-28 Summary 3-30 Practice: Overview 3-31 4 Developing a Web Application Using Servlets Objectives 4-2 Servlets: Overview 4-3 About Java Servlets 4-4 Principal Features of Servlets 4-5 Life Cycle of Servlets 4-6 HTTP Servlets 4-7 Inside an HTTP Servlet 4-8 doGet() Method 4-9 doPost() Method 4-10 HttpServletRequest Object 4-11 HttpServletResponse Object 4-12 HttpSession 4-13 Session Objects 4-14 Methods for Invoking Servlets 4-15 Quiz 4-16 Handling Input: The Form 4-17 Handling Input: The Servlet 4-18 Initialization and Destruction 4-19 Error Handling 4-20 Debugging a Servlet 4-21 JDeveloper Environment 4-22 Servlet Mapping 4-23 Servlet Mapping in JDeveloper 4-24 Invoking a Servlet 4-25 Specifying Java EE Web Module Settings 4-26 Summary 4-27 Practice: Overview 4-28

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

5 Developing a Web Application Using JavaServer Pages Objectives 5-2 JavaServer Pages 5-3 Comparing Servlets and JSPs 5-4 Invoking JSPs 5-5 Date.jsp 5-6 Date Servlet 5-7 Automated JSP Features 5-8 JSP Life Cycle 5-9 Basic JSP Elements 5-10 Declarations 5-11 Expressions 5-13 Scriptlets 5-14 Implicit Objects 5-15 Example 5-17 Quiz 5-19 Directives 5-20 include: Example 5-21 page Directive 5-22 JSP and JavaBeans 5-24 Using JavaBeans with JSP 5-25 scope Attribute of <jsp:useBean> Tag 5-27 Accessing and Setting Bean Properties 5-28 JSP XML Document 5-30 Traditional Syntax Versus XML Syntax 5-31 JSP Segments 5-33 Quiz 5-34 What Is a Tag Library? 5-35 Tag Interfaces 5-36 Tag Handlers 5-37 Tag Library Descriptor 5-38 Implementing Simple Tags 5-39 JSP Expression Language 5-40 Expression Language Implicit Objects 5-41 JDeveloper and JSPs 5-42 Summary 5-43 Practice: Overview 5-44 6 Accessing Resources with JNDI and Dependency Injection Objectives 6-2 Java Naming and Directory Interface 6-3 JNDI Structure 6-4 Naming Service 6-5 JNDI Tree 6-6 Contexts and Subcontexts 6-8 Referencing Java EE Resources with JNDI 6-9
vi

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

7 Developing the Business Logic with Session Beans Objectives 7-2 What Is a Session Bean? 7-3 Stateless Versus Stateful Session Beans 7-4 Dependency Injection in EJB 7-5 Life Cycle of a Stateless Session Bean 7-6 Elements of a Stateless Session Bean 7-7 Defining the Stateless Session Bean 7-8 Analyzing the Remote and Local Interfaces 7-9 Creating a Test Client for the SLSB 7-11 Life Cycle of a Stateful Session Bean 7-12 Passivation and Activation Concepts 7-14 Creating a Stateful Session Bean 7-15 Defining the Stateful Session Bean 7-16 Analyzing the Remote and Local Interfaces 7-17 Creating a Test Client for the SFSB 7-18 Calling a Stateless Bean from a Stateful Bean by Implementing DI Interceptor Methods and Classes 7-20 Interceptor Method 7-21 Interceptor Classes 7-22 Summary 7-23 Practice: Overview 7-24 8 Developing the Persistence Layer with JPA Entities Objectives 8-2 What Are JPA Entities? 8-3 Domain Modeling with Entities 8-5 Managing Persistence of Entities 8-6 Declaring an Entity 8-7 Mapping Entities 8-8 Quiz 8-9
vii

7-19

Oracle University and Egabi Solutions use only

Providing JNDI Properties 6-10 Referencing a Local Session EJB with JNDI 6-11 Referencing a Remote Session EJB with JNDI 6-12 JNDI State Replication 6-13 Quiz 6-14 What Are Annotations? 6-15 Dependency Injection 6-16 Types of Dependency Injection 6-18 Defining the @Resource Annotation 6-19 Using Java EE Resources with Dependency Injection 6-20 Working with Dependency Injection 6-21 Referencing EJBs with Dependency Injection 6-22 Summary 6-23 Practice: Overview 6-24

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

9 Manipulating JPA Entities with the EntityManager API Objectives 9-2 What Is EntityManager? 9-3 Managing an Entity Life Cycle with EntityManager 9-5 Accessing an EntityManager Instance in an Application 9-7 Creating a Container-Managed EntityManager Instance 9-8 Creating an Application-Managed EntityManager Instance 9-9 Specifying Database Operations with the EntityManager API 9-10 Commonly Used Methods in the EntityManager Interface 9-11 Quiz 9-13 Inserting New Data 9-14 Deleting Data 9-15 Updating and Synchronizing the Entity with the Database 9-16 Updating Data 9-17 Finding an Entity by Primary Key 9-18 Quiz 9-19 What Is JPA Query API? 9-20 Retrieving Entities by Using the Query API 9-21 Writing a Basic JPQL Statement 9-22 Creating Named Queries 9-23 Writing Dynamic Queries 9-24 Summary 9-25 Practice: Overview 9-26 10 Developing the Business Logic with Web Services Objectives 10-2 Web Service 10-3 Web Service Standards 10-4 SOAP: XML Messaging for Web Services 10-5 Web Services Description Language (WSDL) 10-6 UDDI Registry 10-7
viii

Oracle University and Egabi Solutions use only

Mapping Inheritance 8-10 Single-Table Strategy 8-12 Joined-Tables Strategy 8-14 Specifying Entity Identity 8-16 Generating Primary Key Values 8-17 Mapping Relationships Between Entities 8-19 Implementing One-to-One Relationships 8-21 Implementing Many-to-One Relationships 8-23 Implementing One-to-Many Relationships 8-25 Implementing Many-to-Many Relationships 8-26 Quiz 8-27 Managing Entities 8-28 Summary 8-29 Practice: Overview 8-30

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

11 Developing the Web Interface Using JavaServer Faces Objectives 11-2 JSF: Overview 11-3 JSF: Benefits 11-4 Key Terms 11-5 JSF Architecture 11-6 JSF Components 11-8 JSF UI Components 11-9 JSF Component Architecture 11-10 Quiz 11-11 Tag Handlers and Component Trees 11-12 Tag Libraries 11-13 Configuration Files 11-14 JSF Renderers 11-15 Managed Beans 11-16 Expression Language 11-17 Life Cycle of a JSF Page 11-18 JSF Life Cycle: Initial Request 11-19 JSF Life Cycle: Postback 11-20 Quiz 11-22 Using JSF Tag Libraries 11-23 JSF Applications 11-24 JSF and JDeveloper 11g 11-25 JSF Navigation Diagram 11-26 Adding to JSF with ADF Faces 11-27 Using ADF Faces Layout Components 11-28
ix

Oracle University and Egabi Solutions use only

Web Service Architecture 10-9 Quiz 10-11 Web Service Metadata for Java Platform (JSR-181) 10-12 Examining the JSR-181 Processor Model 10-13 Describing JSR-181 Annotations 10-14 Sample Annotated Java Web Service File 10-15 What Is JAX-WS? 10-16 Quiz 10-17 Web Service Development Approach 10-18 Bottom-Up Approach 10-19 Top-Down Approach 10-20 Developing a Web Service by Using the Top-Down Approach 10-21 Defining an XSD Schema 10-22 Creating the WSDL Document 10-23 Modifying the WSDL Document 10-25 Creating the Web Service by Using Oracle JDeveloper 11g 10-26 Implementing the Web Service Logic 10-27 Summary 10-28 Practice: Overview 10-29

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Creating Resizable Panes 11-29 Creating Collapsible Panes with the Panel Splitter Component 11-30 Creating Collapsible Panes with the Panel Accordion 11-31 Panel Accordion Overflow 11-32 Setting Panel Accordion Properties 11-33 Creating Titled Sections and Subsections 11-35 Grouping Related Components 11-36 Arranging Items Around a Central Area 11-37 Summary 11-39 Practice: Overview 11-40 12 Planning Navigation and Page Flow Objectives 12-2 Traditional Navigation 12-3 What Is JSF Navigation? 12-5 JSF Navigation: Example 12-6 JSF Navigation Rules 12-7 faces-config Console 12-8 JSF Navigation Modeler 12-9 JSF Navigation Diagram 12-10 Navigation Elements 12-11 Global Rules 12-13 Pattern-Based Rules 12-14 JSF: Example 12-15 JSF Navigation: Example 12-17 Using the JSF Configuration Editor 12-20 Managed Beans 12-21 Creating Managed Beans 12-23 Managed Bean: Example 12-24 Setting Managed Bean Scope 12-25 Relationships Between Managed Beans 12-26 Managed Properties 12-27 Managed Properties: Examples 12-28 Using the Managed Bean on the JSF Page 12-30 Summary 12-31 Practice: Overview 12-32 13 Handling Application Events Objectives 13-2 JSF Event Model 13-3 Types of Events 13-4 Action Events 13-5 Creating Action Events 13-6 Value Change Events 13-7 Creating Value Change Events 13-8 Event Listener Classes 13-9
x

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

14 Asynchronous Communication with Message-Driven Beans Objectives 14-2 Messaging Systems 14-3 Message-Oriented Middleware 14-4 Java Message Service 14-5 JMS Application Architecture 14-6 Point-to-Point Queue 14-7 Publish-Subscribe Topics 14-8 Quiz 14-9 WebLogic Server JMS Features 14-10 JMS Architecture: Connecting 14-11 JMS Architecture: Sending Messages 14-12 Transacted Messaging 14-13 WebLogic Server JMS Server 14-14 Creating a JMS Server 14-15 Connection Factory 14-16 JMS Destination 14-17 Creating a Queue Destination 14-18 Message-Driven Beans 14-20 Life Cycle of a Message-Driven Bean 14-21 Creating a Message-Driven Bean 14-22 Creating a JMS/MDB Client 14-24 Summary 14-26 Practice: Overview 14-27 15 Managing Transactions with Session and Message-Driven Beans Objectives 15-2 What Is a Transaction? 15-3 Example of a Transaction 15-4 Types of Transactions 15-5 Transaction Management 15-7 Two-Phase Commit Protocol 15-8
xi

Oracle University and Egabi Solutions use only

Handling Action Events 13-10 Handling Value Change Events 13-11 Event and Listener Execution Order 13-12 Validation in the JSF Life Cycle 13-13 Creating Custom Exception Handlers 13-15 Registering an Exception Handler 13-16 Changing Life Cycle Exception Reporting 13-17 JavaServer Faces Validators 13-18 Creating Backing Bean Validation in JDeveloper 13-19 Backing Bean Validator: Code Example 13-20 Input Validation 13-21 Summary 13-22 Practice: Overview 13-23

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

16 Securing Java EE Applications with JAAS Objectives 16-2 Goals of Java EE Security Architecture 16-3 Overview of Java EE Security Architecture 16-4 Java Authentication and Authorization Service (JAAS) 16-5 Authorization of a Client 16-8 Quiz 16-9 Security Process Architecture 16-10 Security Services 16-11 Security Realms 16-12 Users and Groups 16-13 Configuring New Users in WebLogic Server 16-14 Adding Users to Groups 16-16 Logical Roles 16-17 Quiz 16-19 Configuring Security 16-20 Determining Protected Resources 16-21 Defining the Logical Roles 16-22 Defining and Using Logical Roles in Web Applications (web.xml) 16-23 Defining and Using Logical Roles in EJBs (ejb-jar.xml) 16-24
xii

Oracle University and Egabi Solutions use only

Successful Two-Phase Commit 15-9 Unsuccessful Two-Phase Commit 15-10 Quiz 15-11 Java Transaction API (JTA) 15-12 EJB Transaction Model 15-13 Managing Transactions with EJBs 15-14 Types of Transaction Management 15-16 Container-Managed Transactions 15-17 Transaction Attribute: REQUIRED 15-18 Transaction Attribute: SUPPORTS 15-19 Transaction Attribute: MANDATORY 15-20 Transaction Attribute: NEVER 15-21 Transaction Attribute: REQUIRES_NEW 15-22 Transaction Attribute: NOT_SUPPORTED 15-23 Quiz 15-24 CMT: setRollbackOnly() 15-25 Container-Managed Transaction: Example 15-26 Java Transaction API (JTA) 15-27 JTA: UserTransaction Interface 15-29 Bean-Managed Transactions 15-30 Bean-Managed Transaction: Example 15-31 BMT Demarcation: Restrictions 15-32 Enlisting Database Resources 15-33 Summary 15-34 Practice: Overview 15-35

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Mapping Logical Roles to Users and Groups 16-25 Setup Authentication 16-26 Authentication Examples 16-27 Setting Access Control with JDeveloper 16-28 Creating Web Application Security Roles 16-29 Web Application Login Authentication 16-30 Web Application Authorization 16-31 EJB Security Roles 16-32 Security Annotation: Example 16-33 Summary 16-34 Practice: Overview 16-35 17 Packaging and Deploying Java EE Applications Objectives 17-2 Deploying Java EE Applications 17-3 Packaging Business-Tier Components 17-5 Packaging Web Applications 17-6 Web Application Structure 17-7 Configuring Web Applications 17-9 What Is web.xml? 17-10 What Is weblogic.xml? 17-11 Web Application Archive 17-12 Creating Web Application Archives 17-13 Quiz 17-14 EJB Application Directory Structure 17-15 Java EE Enterprise Application (EAR) 17-17 Creating EJB Archives 17-18 Creating Enterprise Archives 17-19 Deploying Entities 17-20 Persistence.xml File 17-21 Configuring Oracle WebLogic ServerSpecific Features 17-22 Deploying with the Oracle WebLogic Server Console 17-23 Deploying with Oracle JDeveloper 17-24 What Is Ant? 17-25 Ant Build Files 17-26 A Sample build.xml File 17-27 Creating a JAR File by Using Ant Task 17-28 Creating a WAR File by Using Ant Task 17-29 Creating an EAR File by Using Ant Task 17-30 Deploying an Application by Using Ant Task 17-31 Packaging Best Practices for Production Environments 17-32 Summary 17-33

xiii

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Appendix A: Practices and Solutions B Working with ADF Faces Components Objectives B-2 Using ADF Faces Layout Components B-3 Adding Spaces and Lines B-4 Stretching Components B-5 Enabling Automatic Component Stretching B-6 Stretching a Table Column B-7 Creating Resizable Panes B-8 Printing Layout Panel Content B-9 Creating Collapsible Panes with the Panel Splitter Component B-10 Creating Collapsible Panes with the Panel Accordion B-11 Panel Accordion Overflow B-13 Setting Panel Accordion Properties B-14 Arranging Items in Columns or Grids B-15 Creating Stacked Tabs B-17 Hiding and Displaying Groups of Content B-18 Arranging Items Horizontally or Vertically, with Scrollbars B-20 Displaying Table Menus, Toolbars, and Status Bars B-22 Creating Titled Sections and Subsections B-24 Grouping Semantically Related Components B-25 Displaying a Bulleted List B-26 Displaying Items in a Content Container Offset by Color B-27 Arranging Items Around a Central Area B-28 Using ADF Faces Skins B-30 Using Dynamic Page Layout B-31
xiv

Oracle University and Egabi Solutions use only

18 Troubleshooting Objectives 18-2 Troubleshooting Basics 18-3 Diagnosing the Problem 18-4 Requesting Help 18-5 Creating Test Cases 18-6 Java Logging 18-7 Configuring Java Logging 18-8 Sending Logger Output to a File 18-9 Turning on Diagnostics in JDeveloper 18-10 Sample Java Clients 18-11 Sample Client for Web Service 18-12 Tools and Utilities 18-13 Identifying Search Paths with FileMon 18-14 Testing Java Code with JUnit 18-15 Analyzing HTTP Requests 18-16 Debugging with JDeveloper 18-17 Summary 18-18

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Using Expression Language to Conditionally Display Components B-32 Characteristics of Partial Page Rendering (PPR) B-33 Enabling PPR Declaratively B-34 Native PPR Example B-36 Declarative PPR Example B-37 Enabling PPR Programmatically B-39 Conforming to PPR Guidelines B-40 Summary B-41 Index

xv

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

xvi

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Handling Application Events

Oracle University and Egabi Solutions use only

Copyright 2009, Oracle. All rights reserved.

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Objectives
After completing this lesson, you should be able to do the following: Define the types of JavaServer Faces (JSF) events Create event listeners for a JSF application Describe how the JSF life cycle handles validation List the types of validation provided by JSF

Copyright 2009, Oracle. All rights reserved.

Objectives In any application, it is important to initiate actions based on specific events. JSF allows events to be specified for user interface (UI) components. A JSF application can listen for events such as user input, and then use built-in validator and data converter classes to manipulate data. In this lesson, you learn how to use built-in validator and converter classes, as well as how to create custom classes for handling UI events.

Oracle Fusion Middleware 11g: Build Java EE Applications 13 - 2

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

JSF Event Model


The JSF Event Model is based on the event model defined by the JavaBeans specification where the event is represented by a specific class. An event source object fires an event by calling an event notification method on event listener objects registered to receive the event, passing a reference to the event object as a notification method argument. Developers can write their own event listener implementations, or reference a backing bean method by using Expression Language (EL).

Copyright 2009, Oracle. All rights reserved.

JSF Event Model For an application to be able to respond to user events, you typically register event handlers with the components. Event handling in JavaServer Faces is based on the JavaBeans event model, where event classes and event listeners are used to handle events generated by the components. All JSF events extend the javax.faces.FacesEvent class. When a user event such as clicking a button occurs, the component creates an event object that extends FacesEvent. The event object stores information about the event and identifies the component that generated the event. The event is also added to an event queue. At the appropriate time, JSF tells the component to broadcast the event to the registered listener, which invokes the listener method that processes the event.

Oracle Fusion Middleware 11g: Build Java EE Applications 13 - 3

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Types of Events
JSF supports: Action events:
Occur when a command component is activatedfor example, when a user clicks a button or a link Return a navigation case

Value change events:


Occur when the local value of an input component changesfor example, when a user selects a check box Are used for managing UI elements

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

Copyright 2009, Oracle. All rights reserved.

Types of Events An action event occurs when a command component is activated. For example, when a user clicks a button or a link, the form in which the component is enclosed is submitted, and subsequently an action event is fired. An action event may affect only the user interface (for example, a link to change the locale, causing different field prompts to display) or it may involve some logic processing in the back end (for example, a button to add a new order after entering values in some fields). The return value of an action event is usually used for navigation. A value change event occurs when the local value of an input component changes. For example, when a user selects a check box, the value of the component changes to True. A value change event is fired only after a component value has been validated successfully and the form it is enclosed in is submitted. A phase event or listener is executed as part of the standard JSF life cycle. Using a phase listener, you can listen for phase events for any of the ADF life-cycle phases, and execute your own code before and after the events. You listen for a phase event, and then use the beforePhase() and afterPhase() methods to execute your own code.

Oracle Fusion Middleware 11g: Build Java EE Applications 13 - 4

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Action Events
Command components raise action events. Code 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 application phase of the life cycle. Action events are the last to fire after other listeners (for example, value change events).

Copyright 2009, Oracle. All rights reserved.

Action Events Action events are events that are associated with command components (such as commandButton, commandLink, or commandMenuItem). Action event code can be in either the page backing bean or a separate class. The benefit of having the code in the backing bean is that the code that is associated with a specific page is local to the page (single source). However, the benefit of a separate class is reusability. For example, if you have standard code that should be executed regardless of the page, the separate-class approach makes more sense. If you use the backing-bean approach, JDeveloper creates a method stub for you, and all you have to do is add your custom code. JDeveloper also registers the action in the page source. When the page is submitted, the action event is added to the queue of application events to be executed. Action events are the last events to fire in the application phase of the life cycle.

Oracle Fusion Middleware 11g: Build Java EE Applications 13 - 5

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Creating Action Events


Two ways:
Double-click a command component in the Visual Editor. Enter a method name (including the ()) in the Action property of the component.

JDeveloper:
Creates a method in the backing bean Adds the method to the Action property in the page source
Oracle University and Egabi Solutions use only

Add your custom code. Action methods return a string outcome.

Copyright 2009, Oracle. All rights reserved.

Creating Action Events There are two ways to create an action event in JDeveloper. The first method is to double-click the component and accept the proposed method name or change it to a name of your choice. The second method is to enter the method name (including the ()) in the Action property. JDeveloper creates the method and registers it in the page source by using the Action property of the component tag. You then add whatever code you need to the action method. Remember that action methods can be used for controlling UI, modifying values, or navigation; however, action methods return a string outcome.

Oracle Fusion Middleware 11g: Build Java EE Applications 13 - 6

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Value Change Events


Input components raise value change events. Code 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 called in the application phase of the life cycle. Value change events fire before action events.

Copyright 2009, Oracle. All rights reserved.

Value Change Events Value change events are attached to input components. These events are added to the queue of application events to be executed, when there is a change to the value of the component. Just like action events, the code can be either in the backing bean or in a separate class. If you enter the name of the valueChange() method in the valueChange property of the component, JDeveloper creates the method stub in the backing bean and registers the listener in the page source using the valueChangeListener property of the component tag. The registered value change event is added to the queue of application events to be executed before any action events. Remember that action events are executed last.

Oracle Fusion Middleware 11g: Build Java EE Applications 13 - 7

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Creating Value Change Events


Select the input component in the Visual Editor. Set the valueChangeListener property to a method name that includes (). JDeveloper:
Oracle University and Egabi Solutions use only

Creates the method in the backing bean Adds the method to the valueChangeListener property in the page source

Add your custom code.

Copyright 2009, Oracle. All rights reserved.

Creating Value Change Events You create value change events by entering the name of the method in the valueChangeListener property of the component. You can also open the Code Editor and use the Component and Event selectors at the top of the Code Editor window. You select the component, and then the type of event that you want to add. JDeveloper adds the method stub to the Java class. You then add your custom code. You can register more than one value change listener tag on a component, but you can bind the components value change listener attribute to only one value change listener method.

Oracle Fusion Middleware 11g: Build Java EE Applications 13 - 8

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Event Listener Classes


Action listener:
Is a class that wants to be notified when a command component fires an action event Implements javax.faces.event.ActionListener

Value change listener:


Is a class that wants to be notified when an input component fires a value change event Implements javax.faces.event.ValueChangeListener
Oracle University and Egabi Solutions use only

Copyright 2009, Oracle. All rights reserved.

Event Listener Classes In addition to using backing bean methods as listeners, you can use an existing class to act as either an action listener or a value change listener. The behavior is the same as using backing bean code except you have the advantage of reusability. An external action listener is a class that wants to be notified when a command component fires an action event. An action listener implements the javax.faces.event.ActionListener interface and contains an action listener method that processes the action event. An external value change event listener is a class that wants to be notified when an input component fires a value change event. A value change listener implements the javax.faces.event.ValueChangeListener interface and contains a method that processes the value change event.

Oracle Fusion Middleware 11g: Build Java EE Applications 13 - 9

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Handling Action Events


To listen for an action event, you need to:
Create a class that implements a javax.faces.event.ActionListener interface Register the action listener instance on the components actionListener attribute
Oracle University and Egabi Solutions use only

To register the action listener, drag an action listener from JSF > Core to the component. You can create multiple listeners on each component.

Copyright 2009, Oracle. All rights reserved.

Handling Action Events To handle an action event, you need to: Implement a javax.faces.event.ActionListener interface or an action listener method in a bean to handle the event Implement the processAction() method for your custom code Register the action listener instance on the components actionListener attribute. When you need multiple action listeners on a component, use two or more f:actionListeners tags. You can create multiple listeners on each component. For example, you may want to check some type of security before you allow the action to go forward. If your security check fails, you raise an exception that prevents the action from executing.

Oracle Fusion Middleware 11g: Build Java EE Applications 13 - 10

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Handling Value Change Events


To handle a value change event for an input component, you need to:
Implement the ValueChangeListener interface Register the value change listener instance on the component (using the f:valueChangeListener tag)
Oracle University and Egabi Solutions use only

To register the action listener, drag a value change listener from JSF > Core to the component. You can create multiple value change listeners per component.

Copyright 2009, Oracle. All rights reserved.

Handling Value Change Events To handle a value change event, you need to: Implement a javax.faces.event.ValueChangeListener interface Implement the processValueChange() method for your custom code Register the value change listener instance on the component (by using the f:valueChangeListener tag)

Oracle Fusion Middleware 11g: Build Java EE Applications 13 - 11

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Event and Listener Execution Order


Events and listeners fire in the following order: Validators Value change listeners Action listeners Action events

Copyright 2009, Oracle. All rights reserved.

Event and Listener Execution Order There is a specific order in which the events and listeners are executed. The validators are fired first within the Process Validation phase of the JSF life cycle. The next phase is the Invoke Application phase, which handles all the events and listeners. The value change listeners are executed first, followed by the action listeners. The last event to be fired is the action event. Any of these listeners can raise an AbortProcessingException to abort the process.

Oracle Fusion Middleware 11g: Build Java EE Applications 13 - 12

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Validation in the JSF Life Cycle

1
Apply Request Values.

4
Update Model Values.

2
Process Validations.

5
Successful?
Invoke Application.

3
Successful?

Yes

No

7
No

Render Response: Display either new page, or same page with errors.

Copyright 2009, Oracle. All rights reserved.

Validation in the JSF Life Cycle A Web application can store data of many types (int, long, date, and so on) in the model layer. However, when viewed in a client browser, the user interface has to present the data in a manner that can be read or modified by the user. For example, a date field in a form might represent a java.util.Date object as a text string in the yyyy/mm/dd format. When a user edits a date and submits the form, the string must be converted back to the type that is required by the application. Then the data is validated against any rules and conditions. When viewed in terms of the JSF life cycle, on submission of the form containing the date field, the browser sends a request value to the server: 1. The request value is first stored in a component object in the Apply Request Values phase. 2. In the Process Validations phase, the submitted string value is converted to a local value of the appropriate object type that is required by the application. 3. If validation correctness checks are required, the local value is validated against the defined rules. For example, a validator might check that a user-supplied date is within a specified range. 4. If validation and conversion are successful, the Update Model phase starts and the converted and validated local value is used to update the model. 5. The application is invoked.

Oracle Fusion Middleware 11g: Build Java EE Applications 13 - 13

Oracle University and Egabi Solutions use only

Yes

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Validation in the JSF Life Cycle (continued) 6. A new page is displayed according to navigation rules. 7. If at any point validation or conversion fails, JSF invokes the Render Response phase and redisplays the current page.

Oracle Fusion Middleware 11g: Build Java EE Applications 13 - 14

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Creating Custom Exception Handlers


To create a custom error handler: 1. Create a class that extends org.eclipse.persistence.exceptions. ExceptionHandler. 2. In the new class, override the handleException() method. 3. Register the exception handler with persitence.xml.

Copyright 2009, Oracle. All rights reserved.

Creating Custom Exception Handlers You can add a custom exception handler to the JPA session by creating a class that implements the ExceptionHandler from org.eclipse.persistence.exceptions. There is one method in the class that must be overridden, which is handleException. In this method, you add any code that you want executed if the session throws an exception. These exceptions can be transaction timeout errors, database lock errors, and so on. Customizing the Exception Handler would be useful for debugging or to help resolve timeouts or other database failures. For example:
import org.eclipse.persistence.exceptions.ExceptionHandler; public class CustomExceptionHandler implements ExceptionHandler { public CustomExceptionHandler() {} public Object handleException(RuntimeException exception) { // TODO Add exception handler code here return null; } }

The last step is to register the custom handler with peristence.xml.

Oracle Fusion Middleware 11g: Build Java EE Applications 13 - 15

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Registering an Exception Handler


To register a custom error handler: 1. Open persistence.xml. 2. In TopLink Customization, add the Exception Handler Class. 3. Select your class as the exception handler.

Copyright 2009, Oracle. All rights reserved.

Registering an Exception Handler After the class is written, you open persistence.xml in the visual editor. In the TopLink Customization node, add an Exception Handler Class and point it to your custom class.

Oracle Fusion Middleware 11g: Build Java EE Applications 13 - 16

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Changing Life Cycle Exception Reporting


To customize how the life cycle reports errors: 1. Create a custom page life cycle class that extends FacesPageLifecycle. 2. Override the reportErrors() method.
Oracle University and Egabi Solutions use only

3. Create a new phase listener that returns the custom life cycle:
a. Extend the ADFPhaseListener class. b. Override the createPageLifecycle() method to return the new custom life cycle. c. Register the phase listener in faces-config.xml (Overview tab > Life Cycle > New).

Copyright 2009, Oracle. All rights reserved.

Changing Life Cycle Exception Reporting To change how the life cycle reports errors, you can create a custom ADF page life cycle class and override the reportErrors() method. You can add code to display more user-friendly messages or to keep from displaying messages that would not be helpful to the user. After you have created the custom page life cycle class, you must create a new phase listener that extends the ADFPhaseListener class. You override the createPageLifecycle() method to return the custom life cycle rather than the default one. For example:
public class MyPhaseListener extends ADFPhaseListener { protected PageLifecycle createPageLifecycle() { return new MyPageLifecycle(); } }

Finally, you use the Overview tab of the faces-config.xml editor to register the new phase listener.

Oracle Fusion Middleware 11g: Build Java EE Applications 13 - 17

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

JavaServer Faces Validators


Validation can be performed through: Separate validator components (classes), which provide a high degree of reusability Backing bean code
Oracle University and Egabi Solutions use only

Simpler to understand because code is co-located with the subject Not reusable

JSF Reference Implementation (RI). It provides default validator components.


No client-side validation code, such as JavaScript, is generated. Multiple validators can be used on one input item.

Copyright 2009, Oracle. All rights reserved.

JavaServer Faces Validators Validation can be performed in several ways within a JSF application. JSF provides standard validators and convertors that can be used with any page. The standard validators, however, have no client-side components and are, therefore, server-side only. You can create validator components (classes), which include validation code. You can also place validation code inside the backing beans for a page; however, these are less reusable. The JSF standard validators provide common validation checks for numeric ranges and string lengths. If you need more complex validation rules and checks, you can implement your own validation code by either implementing a javax.faces.validator.Validator interface, or creating a bean method that performs the custom validation.

Oracle Fusion Middleware 11g: Build Java EE Applications 13 - 18

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Creating Backing Bean Validation in JDeveloper

Copyright 2009, Oracle. All rights reserved.

Creating Backing Bean Validation in JDeveloper You can create a backing bean validator in JDeveloper by selecting a component in the UI, opening the Property Inspector, and entering a name for the methodfor example, validateDepartment(). JDeveloper automatically creates the skeleton backing binding code for it.

Oracle Fusion Middleware 11g: Build Java EE Applications 13 - 19

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Backing Bean Validator: Code Example

Copyright 2009, Oracle. All rights reserved.

Backing Bean Validator: Code Example In this example, validateDepartmentId() uses the java.util.regex Pattern and Matcher methods to validate the value of the department ID. It checks it against the pattern and if the ID does not fit the specified pattern, the code creates a FacesMessage object and restores the page. This displays the error message in an af:messages component on the page.

Oracle Fusion Middleware 11g: Build Java EE Applications 13 - 20

Oracle University and Egabi Solutions use only

public void validateDepartmentId(FacesContext facesContext, UIComponent uiComponent,Object object) { String expr = "[^0-9]{1,10}"; Pattern p = Pattern.compile(expr); Matcher m = p.matcher((String)object); //write message if input is invalid if (!m.find()){ facesContext.addMessage("RegExError",new FacesMessage( FacesMessage.SEVERITY_ERROR, "InvalidValue Provided for Deptno",null)); facesContext.getApplication().getViewHandler(). restoreView(facesContext,"/Dept.jsp"); } }

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Input Validation
Use input validation to:
Avoid garbage in, garbage out applications Block bad user input Avoid attacks Avoid misuse of form fields
Oracle University and Egabi Solutions use only

JavaServer Faces and ADF provide the following options for validation:
ADF binding validation JSF validator components Backing bean coded validation

Copyright 2009, Oracle. All rights reserved.

Types of Input Validation UI component attributes: ADF Faces input components provide attributes that can be used to validate on. For example, you can supply simple validation using the required attribute on ADF Faces input components to specify that a value must be supplied. When set to True, the component must have a value; otherwise, the application displays an error message. Default JSF and ADF Faces validators: The JSF and ADF Faces validators provide more complex validation, such as validating date ranges and validating the length of entered data. Custom ADF Faces validators: You can create your own coded validators and then select them to be used in conjunction with UI components. Note: Although input validation is a very good first line of defence against bad data, it should always be reinforced in either the model or the database.

Oracle Fusion Middleware 11g: Build Java EE Applications 13 - 21

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Summary
In this lesson, you should have learned how to: Describe how the JSF event model enables developers to write their own event listener implementations Use action events to fire when a component is activated and value change events when the local value of an input component has changed Use managed beans as the state holder of user input and the components data Describe how the JSF life cycle handles validation Implement the types of validation provided by JSF and ADF Faces to create robust applications

Copyright 2009, Oracle. All rights reserved.

Summary Event handling in JavaServer Faces is based on the JavaBeans event model, where event classes and event listeners are used to handle events generated by the components. All JSF events extend the javax.faces.FacesEvent class. An action event occurs when a command component that implements ActionSource is activated. For example, when a user clicks a button or a link, the form in which the component is enclosed is submitted, and subsequently an action event is fired. A value change event occurs when the local value of an input component changesfor example, when a user selects a check box, the value of the component changes to True. Backing beans can act as the state holder of user input and the components data. They are useful for implementing validation methods and event handler methods that invoke back-end application code with component values. A Web application can store data of many types (int, long, date, and so on) in the model layer. However, when viewed in a client browser, the user interface has to present the data in a manner that can be read or modified by the user.

Oracle Fusion Middleware 11g: Build Java EE Applications 13 - 22

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice: Overview
These practices cover the following topics: Adding a SelectionListener for the Category Tree Coordinating the values of two components Connecting multiple pages with shared values Adding Validators Creating an Edit page

Copyright 2009, Oracle. All rights reserved.

Oracle Fusion Middleware 11g: Build Java EE Applications 13 - 23

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Oracle University and Egabi Solutions use only

Asynchronous Communication with Message-Driven Beans

Copyright 2009, Oracle. All rights reserved.

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Objectives
After completing this lesson, you should be able to: Identify the features of a messaging system Describe the Java Message Service (JMS) architecture Configure a Java Message Service Create a message-driven bean (MDB) Create a JMS/MDB client

Copyright 2009, Oracle. All rights reserved.

Oracle Fusion Middleware 11g: Build Java EE Applications 14 - 2

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Messaging Systems
A messaging system is a system that: Uses messages to communicate between components (rather than direct method invocations) Enables loosely coupled components Is peer-to-peer in nature

Copyright 2009, Oracle. All rights reserved.

Messaging Systems Messaging systems have existed for many years in different forms. A messaging system uses messages rather than method invocation (for example, Remote Method Invocation [RMI]) to communicate between components. In this way, components are loosely coupled and do not need to know details of one anothers implementation or interface. Instead, each peer client communicates with a message queue to send or receive messages. Note: Email systems are not considered messaging systems because they are used for communication between humans or between a system and a human, and not strictly between systems.

Oracle Fusion Middleware 11g: Build Java EE Applications 14 - 3

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Message-Oriented Middleware
Message-oriented middleware refers to an infrastructure that supports messaging. Typical message-oriented middleware architectures define these elements:
Oracle University and Egabi Solutions use only

Message structure The way to send and receive messages Scaling guidelines

Copyright 2009, Oracle. All rights reserved.

Message-Oriented Middleware Message-oriented middleware has been in use for several decades. In the mid-1980s, when providers created architectures that could operate in a standard way on a variety of platforms, message-oriented middleware became widely used. These providers made inroads into bridging the gap between the many platforms for mainframes and those for personal computers. Today, hundreds of companies position themselves as middleware firms. Even though there is intense competition and variety in message-oriented middleware products, they all tend to fall into one of these categories: Publish/subscribe Point-to-point Request-reply Messaging Models JMS supports point-to-point and publish/subscribe messaging models. The models are very similar, except for the following: The PTP messaging model enables delivery of a message to exactly one recipient. The pub/sub messaging model enables delivery of a message to multiple recipients.

Oracle Fusion Middleware 11g: Build Java EE Applications 14 - 4

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Java Message Service


Java Message Service (JMS): Is a Java EE standard for developing messaging systems Provides an architecture for loosely coupled integration of systems through the use of messages Supports both point-to-point and publish/subscribe models for message delivery Is asynchronous in nature Enables reliable communication

Copyright 2009, Oracle. All rights reserved.

Java Message Service The JMS API is an integral part of the Java EE platform and is its standard for developing messaging systems. Before JMS, most messaging systems implemented only one of the two messaging models: point-to-point or publish-subscribe. JMS supports both models and a Java EE provider must implement both. Note: JMS can emulate synchronous communication as well, but this practice is not recommended.

Oracle Fusion Middleware 11g: Build Java EE Applications 14 - 5

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

JMS Application Architecture


The main components of a JMS application: JMS clients (producer and consumer) JMS provider Administered objects
Oracle University and Egabi Solutions use only

Connection factories Destinations (queues or topics)


Producer JMS Queue/topic JMS client JMS provider JMS client Consumer JMS

Application

Application

Copyright 2009, Oracle. All rights reserved.

JMS Application Architecture There are different participants or components in a JMS application. A JMS client is any Java application that participates in a JMS environment. A JMS client can receive and produce messages. A JMS producer produces (sends) messages and is also known as a publisher. A JMS consumer receives (requests) messages and is also known as a subscriber. A JMS provider handles the routing and delivery of messages. Oracle provides a JMS provider in its application server and database server. Administered objects, stored in the JNDI namespace of a Java EE container, consist of: Connection factories: Used by a client to create a connection with a provider Destinations: Targets of messages that are produced, or sources of messages that are consumed by client applications, such as queues for the JMS Point-To-Point model and topics for the JMS Publish/Subscribe model A JMS application generally contains one JMS provider and more than one JMS client. The messages are sent through a messaging system called the message broker (or MOM services). OC4J JMS, Oracle JMS, BEA WebLogic JMS, Sun Microsystems iPlanet Message Queue, and IBM MQSeries are examples of JMS providers.

Oracle Fusion Middleware 11g: Build Java EE Applications 14 - 6

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Point-to-Point Queue
Many producers can serialize messages to multiple receivers in a queue.
Messages are delivered to one client

Publisher

Distribution Queue 9 8 7 6 5 4 Queue Manager WebLogic Server

Subscriber

Subscriber

Publisher

Subscriber

Copyright 2009, Oracle. All rights reserved.

Point-to-Point Queue When using a PTP queue, multiple producers can put messages onto the queue. The queue serializes the messages into a linear order. Multiple receivers can take messages off the queue; the messages typically come off in a first-in, first-out (FIFO) order; the oldest message on the queue is the first one to be taken off. A message can be delivered only to one receiver. An example of when to use a PTP queue would be at a call center. Calls are routed into the network through a PBX. The PBX places incoming calls onto an Incoming Call queue. When a service representative becomes available, the representative requests the next caller in the system. The system pulls the caller who has been waiting the longest off the queue and routes the caller to the service representative.

Oracle Fusion Middleware 11g: Build Java EE Applications 14 - 7

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Publish-Subscribe Topics
Publishing and subscribing to a topic decouples producers from consumers.
Messages are delivered to more than one client

Publisher

Distribution Topic 9 8 7 6 5 4 Topic Manager WebLogic Server

Subscriber

Subscriber

Publisher

Subscriber

Copyright 2009, Oracle. All rights reserved.

Publish-Subscribe Topics Having the publishers publish to a topic rather than directly to a list of subscribers decouples the publishers and subscribers. By doing this, a publisher is not required to manage the number of subscribers (if any) that must receive the message. By delegating the work of the message delivery to the message-oriented middleware server (which manages the topic), the publisher does not have to manage the delivery of guaranteed messages, fault tolerance of its production, load balancing, or other issues. By decoupling a subscriber from the publisher, the subscriber does not have to determine whether its publisher is active. If the message-oriented middleware server is executing, the needs of both publishers and subscribers are met. An example of using a publish and subscribe topic is a stock ticker application. A typical system would set up a topic for each stock that is traded on the exchanges. When a trade is made on a stock, the respective exchange publishes a message to the topic associated with the stock traded. Clients who are interested in receiving updates about the status of their stocks use a program to subscribe to the topics of each stock they are interested in. When it receives a message, the message-oriented middleware server broadcasts the message to all interested stock ticker programs.

Oracle Fusion Middleware 11g: Build Java EE Applications 14 - 8

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Quiz
Identify the correct statements about the point-to-point or queuing model. 1. Multiple consumers will get the message. 2. The producer does not have to be running at the time the consumer consumes the message, nor does the consumer need to be running at the time the message is sent. 3. Every message successfully processed is acknowledged by the consumer.

Copyright 2009, Oracle. All rights reserved.

Answers: 2, 3

Oracle Fusion Middleware 11g: Build Java EE Applications 14 - 9

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

WebLogic Server JMS Features


WebLogic Server JMS supports: PTP and pub/sub domains Guaranteed and transactional message delivery Durable subscribers Distributed destinations Recovery from failed servers

Copyright 2009, Oracle. All rights reserved.

WebLogic Server JMS Features The WebLogic Server implementation of JMS fully supports the PTP and publish and subscribe domains of messaging middleware. WebLogic Server also provides ACK-based guaranteed message delivery (GMD). ACK-based GMD persistently stores messages until the receiver of the message issues an acknowledgement reply. WebLogic Server JMS uses its built-in support for JDBC and JDBC connection pools to persist JMS messages in a connection pool database. Transactional message delivery gives the developer the ability to put a JMS session into a transaction context. Sessions that are located in a transaction context buffer the messages that they produce and do not transmit the messages until the transaction is committed. After the transaction is committed, the messages that the session has buffered are transmitted to their respective destinations. A session can optionally roll back the transaction, which has the transaction drop the messages it had previously buffered. WebLogic Server allows clients to register themselves as a durable subscriber. A durable subscriber is a client that expects to receive all persistent (GMD) messages sent to a particular destination, whether the client is currently executing or not. If the durable subscriber is not currently executing, WebLogic Server stores the messages in a database until the durable subscriber reactivates and retrieves the stored messages. Note: WLS implements the JMS 1.1 specification.
Oracle Fusion Middleware 11g: Build Java EE Applications 14 - 10

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

JMS Architecture: Connecting


Client
ConnectionFactory
Lookup ConnectionFactory

WebLogic Server

Create a Connection.
Destination: Queue

Create a Session.

JMS Server

Destination: Topic

Session

Look up a Destination

3
To send messages, you require: - Connection - Session - Destination

Destination

Destination Returned

Copyright 2009, Oracle. All rights reserved.

JMS Architecture: Connecting The Connection Factory is a lightweight object stored on a JNDI tree used to create connections to destinations. Connection is a communication link to the JMS Server used to create sessions. Session is used to create senders, receivers, and empty messages. Session is also used to demarcate transactions. Destination, a lightweight object stored on JNDI, is the target for the messages. The JMS API provides interfaces for the production and consumption of messages. Before JMS 1.1, point-to-point messaging and publish/subscribe messaging were separated into two different domains with different interfaces. JMS 1.1 now unifies the interfaces, and new development should follow the unified API interface.

Oracle Fusion Middleware 11g: Build Java EE Applications 14 - 11

Oracle University and Egabi Solutions use only

Connection

JNDI Tree

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

JMS Architecture: Sending Messages


Connection, Session, and Destination are used to send a message.
Connection

WebLogic Server

Session Message Producer

Destination

Destination: Topic

Client

JMS Server

Copyright 2009, Oracle. All rights reserved.

JMS Architecture: Sending Messages A Message Producer is used to send any type of message to a destination. A Message receiver is used to receive messages from a destination. The unified interface classes in the javax.jms package are: Connection: Created from a ConnectionFactory Session: Created from a Connection for producers and consumers to interact MessageProducer: Created from a session to produce messages on a Destination MessageConsumer: Created from a session to consume messages from a Destination Destination: Destination for messages (for example, queue or topic)

Oracle Fusion Middleware 11g: Build Java EE Applications 14 - 12

Oracle University and Egabi Solutions use only

Destination: Queue

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Transacted Messaging
A JMS client can use JTA to participate in a distributed transaction. Alternatively, a JMS client can demarcate transactions local to the JMS Session, through a transacted session. Participation in a transaction is optional.
Begin Transaction 1 Begin Transaction 2

Producer

Consumer

All messages arrive at destination

All messages are removed from destination

Commit

Commit

Copyright 2009, Oracle. All rights reserved.

Transacted Messaging JMS clients can participate in a distributed or local transaction. There are two scenarios: On the Producer side, a transaction begins and some operations, such as sending messages, are performed. If the transaction commits, all the messages are sent to the destination. If the transaction rolls back, none of the messages arrive at the destination. On the Consumer side, a transaction begins and some operations, such as processing messages, are performed. If the transaction commits, the processed messages are removed from the destination. If the transaction rolls back, the messages stay in the destination.

Oracle Fusion Middleware 11g: Build Java EE Applications 14 - 13

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

WebLogic Server JMS Server


In WLS, the messaging service is implemented through a JMS server. A JMS server receives and distributes messages.
JMS Client Queues Queues Queues Topics Topics Topics Queues Queues Queues Topics Topics Topics
JMS Server B JMS Server A

WebLogic Server

Persistence

Copyright 2009, Oracle. All rights reserved.

WebLogic Server JMS Server A JMS server is configured within the administration console and targeted to a server. There can be more than one JMS server targeted to the same WebLogic Server instance.

Oracle Fusion Middleware 11g: Build Java EE Applications 14 - 14

Oracle University and Egabi Solutions use only

JMS Client

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Creating a JMS Server


2

1 4
Oracle University and Egabi Solutions use only

Copyright 2009, Oracle. All rights reserved.

Creating a JMS Server A JMS server is created and configured in the administration console. To create a JMS server: 1. Expand the Services node in the Domain Structure in the left pane. Expand the Messaging node. Select the JMS Servers node. This brings up the JMS Servers dialog box. 2. Click New. This action displays the Create a New JMS Server dialog box. 3. Enter values for the following configuration parameters: Name: Name of the JMS server Store: Backing store used by destinations. A value of none means the JMS server will use the default persistent store that is configured on each targeted WLS instance. 4. Click Next to target a JMS server. 5. Select one target in the Target drop-down list. Note: JMS server can be targeted to only one WebLogic Server instance. 6. Click Finish

Oracle Fusion Middleware 11g: Build Java EE Applications 14 - 15

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Connection Factory
A connection factory:
Encapsulates connection configuration information Is used to create preconfigured connections Is stored in JNDI Can be targeted to servers or clusters
Oracle University and Egabi Solutions use only

WLS provides a default connection factory that is bound in JNDI to weblogic.jms.ConnectionFactory. When a new configuration is required, a new connection factory can be created.

Copyright 2009, Oracle. All rights reserved.

Connection Factory A ConnectionFactory object encapsulates connection configuration information and enables JMS applications to create a Connection. A system administrator configures connection factories to create connections with predefined attributes. A system administrator defines and configures one or more connection factories, and WebLogic Server adds them to the JNDI space during startup. The application then retrieves a connection factory using WebLogic JNDI. The system administrator can establish clusterwide, transparent access to destinations from any server in the cluster by configuring multiple connection factories and using targets to assign them to WebLogic Servers. Each connection factory can be deployed on multiple WebLogic Servers. WebLogic JMS defines one default connection factory. It can be looked up using the JNDI name, weblogic.jms.ConnectionFactory. You must define a connection factory only if the default provided by WebLogic JMS is not suitable for your application.

Oracle Fusion Middleware 11g: Build Java EE Applications 14 - 16

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

JMS Destination
A JMS destination is a lightweight object stored in JNDI. It is the target on a JMS server for sending or receiving messages. The JMS destination types are:
Oracle University and Egabi Solutions use only

Queue Topic

Copyright 2009, Oracle. All rights reserved.

JMS Destination A JMS destination identifies a queue (point-to-point) or topic (publish/subscribe) for a JMS server. After configuring a JMS server, configure one or more queue or topic destinations for each JMS server. You configure destinations explicitly or by configuring a destination template that can be used to define multiple destinations with similar attribute settings.

Oracle Fusion Middleware 11g: Build Java EE Applications 14 - 17

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Creating a Queue Destination

A
Oracle University and Egabi Solutions use only

B C

Copyright 2009, Oracle. All rights reserved.

Creating a Queue Destination To create and configure a Queue destination in WebLogic Server, execute the following steps: 1. Log in to the WebLogic Server Administrative Console, navigate to DefaultDomain > Services > Messaging > JMS Modules. 2. Click New on the JMS Modules table and specify the details (for example, enter the name as MyJMSModule), and click Next. 3. Select the WebLogic Server instance as target. Click Next. 4. Select the Would you like to add resources to this JMS system module check box and click Finish. 5. On the Settings for MyJMSModule page, click the Subdeployments tab. 6. In the Subdeployments table, click New (as shown in figure [A] in the slide). 7. Provide the Subdeployment Name and click Next. 8. In the Targets page, select the MyJMSServer (previously configured) as the target under the JMS Servers table. Click Finish (as shown in figure [B] on the slide). 9. Click the Configuration tab. In the Settings for the Module page, under the Summary of Resources table, click New to configure a new JMS queue (as shown in figure [C] in the slide). 10. In the Create a New JMS System Module Resource page, under Choose the type of resource you want to create, select Queue, and then click Next.
Oracle Fusion Middleware 11g: Build Java EE Applications 14 - 18

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Creating a Queue Destination (continued) 11. In the JMS Destination Properties, specify the details (Name, JNDI Name) and click Next. 12. Select the Module from the subdeployments list and click Finish. To confirm the configuration settings for the queue, and its registration in the global JNDI tree, execute the following steps: 1. Navigate to the home page in the administration console. On the home page, under Environment, click Servers to get to the Summary of Servers. In the table of servers, click the WebLogic Server instance that you have used to configure the JMS Server. 2. In the Settings for server instance page, click the View JNDI Tree link. 3. The JNDI Tree opens in another window or tab. In that tab, notice the JNDI entries for the queue.

Oracle Fusion Middleware 11g: Build Java EE Applications 14 - 19

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Message-Driven Beans
A message-driven bean (MDB): Is a stateless EJB that asynchronously consumes JMS messages Is never called directly by a client Has an onMessage() method that is invoked by the EJB container when a message arrives
Message producer JMS Queue/Topic JMS client JMS provider Message-driven bean Message consumer

Application

EJB container
Copyright 2009, Oracle. All rights reserved.

Message-Driven Beans A message-driven bean is an EJB that acts like a JMS consumer. The bean is stateless (each bean transaction spans only one method invocation), and thus it is much like a stateless session bean. However, unlike SLSBs, MDBs are never directly invoked by clients; instead, MDBs have an onMessage() method that is invoked by the EJB container when a message is sent to its queue or topic. Because there are no direct client calls to the MDB, an MDB has no remote or local interfaces. Before EJB 3.0, MDBs had a MessageDrivenBean interface with a setMessageDrivenContext() method that established its environment. In EJB 3.0, the MessageDrivenContext is now set through dependency injection. MDBs do implement a MessageListener interface.

Oracle Fusion Middleware 11g: Build Java EE Applications 14 - 20

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Life Cycle of a Message-Driven Bean

Creation Ready Destruction onMessage()

Copyright 2009, Oracle. All rights reserved.

Life Cycle of a Message-Driven Bean The life cycle of a message-driven bean has the same states as a stateless session bean. Creation: Creation of a message-driven bean is initiated by the EJB container (OC4J). The container typically creates a pool of MDBs that wait to service the requests of any clients. Creation of an MDB follows the sequence of the steps below (as needed): 1. newInstance() 2. Dependency injection 3. Post-construct callback onMessage() method: When a message arrives for the MDB, the EJB container invokes the MDBs onMessage() method to consume the message. Destruction: While managing the pool of MDBs, the container may choose to destroy a bean based on its age or to manage other resources (for example, memory limitations). At this point, a predestroy callback is invoked if one is defined, and the MDB is then destroyed.

Oracle Fusion Middleware 11g: Build Java EE Applications 14 - 21

Oracle University and Egabi Solutions use only

Does not exist

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Creating a Message-Driven Bean


@MessageDriven(mappedName = "jms/demoTopic", 1 name = "MessageBean", activationConfig = { @ActivationConfigProperty( propertyName="connectionFactoryJndiName", propertyValue="jms/TopicConnectionFactory"), @ActivationConfigProperty( propertyName="destinationName", propertyValue="jms/demoTopic"), @ActivationConfigProperty( propertyName="destinationType", propertyValue="javax.jms.Topic"), @ActivationConfigProperty( propertyName="messageSelector", propertyValue="RECIPIENT = 'MDB'") } ) public class MDBBean implements MessageListener { @Resource javax.ejb.MessageDrivenContext mc; 3 public void onMessage(Message message) { 4 ... } }
Copyright 2009, Oracle. All rights reserved.

Creating a Message-Driven Bean 1. Use the @MessageDriven annotation to identify this as a message-driven bean. The mappedName attribute specifies the referenced JMS destination that has a global JNDI name of jms/demoTopic and is deployed in the WebLogic Server JNDI tree. 2. Link the MDB to its JMS resource by configuring the following attributes: - connectionFactoryJndiName: JNDI name of the JMS connection factory associated with the MDBs JMS destination - destinationName: JNDI name of the MDBs JMS destination - destinationType: javax.jms.Queue or javax.jms.Topic - messageSelector: Specifies the types of messages received by the MDB - messageListenerInterface: Specifies which listener interface to use if more than one is defined - acknowledgeMode: AUTO-ACKNOWLEDGE (default) or DUPS-OkACKNOWLEDGE 3. Apply dependency injection to the associated message-driven context. 4. Define the onMessage() method that is invoked by the container when a message is received.

Oracle Fusion Middleware 11g: Build Java EE Applications 14 - 22

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Oracle Fusion Middleware 11g: Build Java EE Applications 14 - 23

Oracle University and Egabi Solutions use only

Creating a Message-Driven Bean (continued) Note The messageSelector property defines criteria, applied to the headers and properties of the messages, specifying which messages the MDB wants to receive. For example, as shown in the slide, the propertyValue of the messageSelector property is set to retrieve all requests whose RECIPIENT property is MDB. The messages that do not match the expression are filtered (not delivered to the MDB). The acknowledgeMode property enables the JMS session, which consumes the messages and calls a message-driven beans message listener method (for example, the onMessage method for a JMS message listener) to acknowledge the delivery of a message. By default, the acknowledge mode for the underlying JMS session is AUTO_ACKNOWLEDGEthat is, the session automatically acknowledges receipt after a message has been received or is successfully processed. In case of DUPS-OkACKNOWLEDGE mode, the session can lazily acknowledge receipt of the message. This is similar to AUTO_ACKNOWLEDGE, but useful when the application can handle delivery of duplicate messages and rigorous acknowledgement is not a requirement.

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Creating a JMS/MDB Client


public class JMSClient { public static void main(String [] args) { try { Context context = new InitialContext(); ConnectionFactory connectionFactory = (ConnectionFactory) new InitialContext().lookup(" jms/TopicConnectionFactory"); Connection connection = connectionFactory.createConnection(); connection.start(); Session topicSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination topic = (Topic) new InitialContext().lookup("jms/demoTopic");

2 3 4

Copyright 2009, Oracle. All rights reserved.

Creating a JMS/MDB Client 1. Look up the JMS connection factory in JNDI. 2. Create and start a connection by using the JMS connection factory. 3. Create a session by using the JMS connection factory. 4. Look up the JMS destination in JNDI. Note: The first argument of the createSession() method specifies that the session is not transacted, and the second argument specifies that the session automatically acknowledges messages when they have been received successfully.

Oracle Fusion Middleware 11g: Build Java EE Applications 14 - 24

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Creating a JMS/MDB Client


MessageProducer publisher = 5 topicSession.createProducer(topic); Message message = topicSession.createMessage(); 6 message.setJMSType("theMessage"); message.setLongProperty("time", System.currentTimeMillis()); message.setStringProperty("subject", "Test EJB 3.0 MDB"); message.setStringProperty("message", "Test message sent to EJB 3.0 MDB"); message.setStringProperty("RECIPIENT", "MDB"); publisher.send(message); 7 publisher.close(); topicSession.close(); 8 connection.close(); } catch(Throwable ex) { ex.printStackTrace(); } } }
Copyright 2009, Oracle. All rights reserved.

Creating a JMS/MDB Client (continued) 5. Create a message producer using the session. 6. Create a message and optionally set its attributes: - subject - message - RECIPIENT 7. Send the message. 8. Close the connections. Note: The code example creates a generic JMS message instance assigned to the message variable, whose type is defined as the javax.jms.Message interface. The JMS API defines the following five message body formats: TextMessage for string data, such as the contents of an XML file MapMessage containing a set of name-value pairs. Names are string objects and values are any primitive-type value. The order of the entries is undefined. BytesMessage for a stream of uninterpreted bytes for literal encoding StreamMessage for a stream of primitive values, filled and read sequentially ObjectMessage to contain any Serializable object When the message is composed of header fields and properties only, then the Message message type is used. This message type is useful when a message body is not required. The example in the slide supplies message text as a string property.
Oracle Fusion Middleware 11g: Build Java EE Applications 14 - 25

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Summary
In this lesson, you should have learned how to: Identify the features of a messaging system Describe the Java Message Service (JMS) architecture Configure a Java Message Service Create a message-driven bean (MDB) Create a JMS/MDB client

Copyright 2009, Oracle. All rights reserved.

Oracle Fusion Middleware 11g: Build Java EE Applications 14 - 26

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice: Overview
These practices covers the following topics: Creating a message-driven bean to send emails Modifying the session bean to produce messages for the MDB to send as emails Configuring JMS resources in WebLogic Server Testing the email functionality using an email client

Copyright 2009, Oracle. All rights reserved.

Oracle Fusion Middleware 11g: Build Java EE Applications 14 - 27

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Oracle University and Egabi Solutions use only

Managing Transactions with Session and Message-Driven Beans

Copyright 2009, Oracle. All rights reserved.

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Objectives
After completing this lesson, you should be able to: Choose the appropriate type of transaction management Set the transaction attribute for container-managed transactions Create transaction demarcations

Copyright 2009, Oracle. All rights reserved.

Oracle Fusion Middleware 11g: Build Java EE Applications 15 - 2

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

What Is a Transaction?
A transaction: Is a single, logical unit of work or a set of tasks that are executed together May access one or more shared resources (such as databases) Must be atomic, consistent, isolated, and durable (ACID)

Copyright 2009, Oracle. All rights reserved.

Transactions: Overview Transactions manage changes to multiple databases in a single application as a unit of work. A transaction must be: Atomic: A transaction must either execute completely or not execute at all. For example, in an account transfer transaction, both debit and credit must be successful as a unit, or both must fail. Consistent: This refers to the integrity of the underlying database. In an account transfer example, the amount of debit to one account must equal the credit to the other account. Isolated: The steps during a transaction cannot be affected by or be visible to any other part of the system until the transaction is complete. Durable: All data changes that are made during a transaction must be written to some physical storage before the transaction is successfully completed, so that even if the system crashes, the changes are not lost.

Oracle Fusion Middleware 11g: Build Java EE Applications 15 - 3

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Example of a Transaction
Successful transfer (A) Unsuccessful transfer (accounts are left in an inconsistent state) (B)
Withdraw: $100 $500 -$100 Account 1 $400

A A

ATM

Transfer: $100 From: Acct 1 To: Acct 2

Deposit: $100

Account 2 +$100
$1100

$1000

Withdraw: $100

ATM

Transfer: $100 From: Acct 1 To: Acct 2

Bank

$500 -$100 Account 1 $400

Failed Deposit

Account 2 $1000

Copyright 2009, Oracle. All rights reserved.

Example of a Transaction Transactions are appropriate in the following scenarios. Each situation describes a transaction model supported by the WebLogic Server system. A client application must converse with an object managed by a server application, and it must make multiple invocations on a specific object instance. The conversation can be characterized by one or more of the following: Data is cached in memory or written to a database during or after each successive invocation. Data is written to a database at the end of the conversation. The client application requires that the object maintain an in-memory context between each invocation; each successive invocation uses the data that is maintained in memory. At the end of the conversation, the client application needs the capability to cancel all database write operations that may have occurred during or at the end of the conversation. Consider an Internet-based online shopping cart application. Users of the client application browse through an online catalog and make multiple purchase selections. They proceed to check out and enter credit card information to make the purchase. If the credit card check fails, the shopping application must cancel all the pending purchase selections in the shopping cart or roll back purchase transactions made during the conversation.
Oracle Fusion Middleware 11g: Build Java EE Applications 15 - 4

Oracle University and Egabi Solutions use only

Bank

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Types of Transactions
A local transaction deals with a single resource manager. It uses the non-Extended Architecture (non-XA) interface between WebLogic Server and resource managers. A distributed transaction coordinates or spans multiple resource managers. A Global transaction can deal with multiple resource managers. It uses the Extended Architecture (XA) interface between WebLogic Server and resource managers. You need to create non-XA or XA resources for local transactions. However, for global transactions, you need to create only XA resources.

Copyright 2009, Oracle. All rights reserved.

Types of Transactions A resource, like a database, is controlled through a resource manager (RM). The coordination of multiple resource managers is performed by a transaction manager (TM). A transaction is often referred to as a transaction context. A transaction originator initiates the transaction. The transaction originator can be a user application, an Enterprise JavaBean, or a JMS client. A transaction manager manages transactions on behalf of the application programs. A transaction manager coordinates commands from the application programs to start and complete transactions by communicating with all resource managers that are participating in those transactions. When resource managers fail during transactions, transaction managers help resource managers decide whether to commit or roll back pending transactions. The communication between the transaction manager and a specific resource manager is called a transaction branch. A recoverable resource provides persistent storage for data. The resource is typically a database. A resource manager provides access to a collection of information and processes. Transactionaware JDBC drivers are common resource managers. Resource managers provide transaction capabilities and permanence of actions; they are entities accessed and controlled within a distributed transaction. Resource managers are software tools that are typically provided by the vendor of the storage mechanism, such as Oracle, Sybase, DB2, and so forth. Some are available from third-party vendors. You can write your own.
Oracle Fusion Middleware 11g: Build Java EE Applications 15 - 5

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Types of Transactions (continued) Software vendors provide an RM file that specifies configuration and login information used when opening a database connection.

Oracle Fusion Middleware 11g: Build Java EE Applications 15 - 6

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Transaction Management
SQL server Database (Resource) Oracle Database (Resource)

Messaging Server

Resource Manager WebLogic Server

Resource Manager JTA


Manages Transactions End-to-End

Resource Manager Transactions Manager

Application 1

Copyright 2009, Oracle. All rights reserved.

Transaction Management A transaction is a set of related operations. These operations should either be performed together or none should be performed. For example, purchasing a product using a Web application is a transaction that involves multiple operations, such as selecting a product, placing an order, reducing the product quantity available in the application database, debiting the amount from the buyers credit card account, and crediting the sellers account. To complete this transaction successfully, all the operations involved in the transaction must be performed. In this case, the transaction is said to be committed. However, even if one operation fails, the transaction is rolled back. This implies that the effect of all the operations that were performed before the failed operation must be undone. Transaction management refers to the end-to-end management of transactions between applications and resources. Two essential components that provide end-to-end transaction management are a transaction manager and a resource manager. A transaction manager contains the logic for implementing transaction management. A resource manager is a driver that interfaces between the resource and the transaction manager. A transaction manager manages transactions on behalf of application programs. A transaction manager coordinates commands from application programs to start and complete transactions by communicating with all resource managers that are participating in those transactions.

Oracle Fusion Middleware 11g: Build Java EE Applications 15 - 7

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Two-Phase Commit Protocol


The Two-Phase Commit (2PC) protocol uses two steps to commit changes within a distributed transaction.
Phase 1 asks RMs to prepare to make the changes Phase 2 asks RMs to commit and make the changes permanent, or to roll back the entire transaction
Oracle University and Egabi Solutions use only

A global transaction ID (XID) is used to track all changes associated with a distributed transaction.

Copyright 2009, Oracle. All rights reserved.

Two-Phase Commit Protocol WebLogic Server supports distributed transactions and the two-phase commit protocol for enterprise applications. A distributed transaction is a transaction that updates multiple resource managers (such as databases) in a coordinated manner. The two-phase commit protocol is a method of coordinating a single transaction across two or more resource managers. It guarantees data integrity by ensuring that transactional updates are committed in all of the participating resources, or are fully rolled back out of all the resources, reverting to the state before the start of the transaction. In other words, either all the participating resources are updated or none of them are updated.

Oracle Fusion Middleware 11g: Build Java EE Applications 15 - 8

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Successful Two-Phase Commit


prepare Application Transaction Manager TLOG Resource Manager Resource Manager Resource Manager prepare ready commit Database Printer Another App

ready

Phase 1 Phase 2
Application Transaction Manager TLOG

Resource Manager Resource Manager Resource Manager

Database Printer Another App

committed

commit committed

Copyright 2009, Oracle. All rights reserved.

Successful Two-Phase Commit The first phase of the two-phase commit protocol is called the prepare phase. The required updates are recorded in a transaction log file, and the resource must indicate through a resource manager that it is ready to make the changes. Resources can vote either to commit the updates or to roll back to the previous state.

Oracle Fusion Middleware 11g: Build Java EE Applications 15 - 9

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Unsuccessful Two-Phase Commit


prepare Application Transaction Manager TLOG Resource Manager Resource Manager Resource Manager prepare ready not ready abort Resource Manager Resource Manager Resource Manager Database Printer Another App

ready

not ready

Phase 1 Phase 2
Application Transaction Manager TLOG

Database Printer Another App

rolled back

abort Rolled back


Copyright 2009, Oracle. All rights reserved.

Unsuccessful Two-Phase Commit What happens in the second phase depends on how the resources vote. If all resources vote to commit, all resources participating in the transaction are updated. If one or more of the resources vote to roll back, all resources participating in the transaction are rolled back to their previous state.

Oracle Fusion Middleware 11g: Build Java EE Applications 15 - 10

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Quiz
The communication between the transaction manager and a specific resource manager is called: 1. A distributed transaction 2. A local transaction 3. A transaction branch

Copyright 2009, Oracle. All rights reserved.

Answer: 3

Oracle Fusion Middleware 11g: Build Java EE Applications 15 - 11

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Java Transaction API (JTA)


WLS uses JTA to implement and manage transactions. WLS JTA provides the following support:
Creates a unique transaction identifier (XID) Supports an optional transaction name Tracks objects involved in transactions Notifies databases of transactions Orchestrates 2PC using XA Executes rollbacks Executes automatic recovery procedures when failure Manages time-outs

Copyright 2009, Oracle. All rights reserved.

Java Transaction API (JTA) WebLogics implementation of JTA provides the following support for your business transactions: It creates a unique transaction identifier when a client application initiates a transaction. It supports an optional transaction name describing the business process that the transaction represents. The transaction name makes statistics and error messages more meaningful. It works with the WebLogic Server infrastructure to track objects that are involved in a transaction and, therefore, must be coordinated when the transaction is ready to commit. It notifies the resource managers (typically, databases) when they are accessed on behalf of a transaction. Resource managers lock the accessed records until the end of the transaction. It orchestrates the two-phase commit when the transaction completes, which ensures that all the participants in the transaction commit their updates simultaneously. WebLogic Server coordinates the commit with any databases that are being updated using Open Groups XA protocol. Many popular relational databases support this standard.

Oracle Fusion Middleware 11g: Build Java EE Applications 15 - 12

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

EJB Transaction Model


Demarcating a transaction determines:
Who begins and ends a transaction When each steps occurs

A container-managed (declarative) transaction (CMT):


Oracle University and Egabi Solutions use only

Is demarcated by the container at the method level Is specified implicitly (by default) or declaratively through the use of annotations

A bean-managed (explicit) transaction (BMT):


Is demarcated by the bean Is specified programmatically in the bean through the JTA interface or the Java Database Connectivity (JDBC) interface

Copyright 2009, Oracle. All rights reserved.

EJB Transaction Model Demarcating transactions refers to defining the transaction boundariesthat is, who starts and stops the transaction and when each occurs. A transaction may involve more than one source and destination, and may span multiple client and server objects. EJB transactions can be demarcated as bean-managed transactions (BMTs) or containermanaged transactions (CMTs). The bean provider uses the EJB deployment descriptor (ejbjar.xml) to specify a value of a Bean or Container in the <transaction-type> element to define the type of transaction demarcation implemented. The CMT model allows for implicit or declarative management of transactional behavior through the use of transaction attribute annotations. The container begins and ends the transactions as necessary. The CMT transactional behavior of the bean can be changed by modifying the annotation, without changing business logic; thus it reduces code complexity. In the BMT model, the EJB client or the bean programmatically demarcates the transaction by executing the appropriate begin or commit/rollback methods by using the Oracle implementation of the Java Transaction API (JTA) specification. The Oracle JTA implementation supports JDBC, HTTP, and clients based on Internet Inter-ORB Protocol (IIOP).

Oracle Fusion Middleware 11g: Build Java EE Applications 15 - 13

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Managing Transactions with EJBs


Bean-managed transactions:
Are performed programmatically using the javax.transaction.UserTransaction interface Explicitly demarcate (start and end) transactions Enable a transaction to span method calls Are specified declaratively using annotations or the XML deployment descriptor Implicitly demarcate transaction boundaries at the start and end of each method call Can use a session facade to enable a transaction to span multiple calls to the entities
Oracle University and Egabi Solutions use only

Container-managed transactions:

Manage queries and persistence of data by implementing Java Persistence API through EntityManager.
Copyright 2009, Oracle. All rights reserved.

Managing Transactions with EJBs Applications can manage transactions programmatically or declaratively. Enterprise applications typically either manage transactions programmatically or use Enterprise JavaBeans. When using Enterprise JavaBeans, transactions can be managed in one of the following two ways: Programmatically, using bean-managed transactions. The developer programmatically uses the javax.transaction.UserTransaction interface to interact with a transaction manager in the container, and explicitly demarcates, begins, and ends the transaction. This enables a transaction to span method calls, if required. Declaratively, using container-manager transactions. The developer specifies the transactional behavior declaratively with annotations or in the EJB deployment descriptor. The container uses the declarative settings to implicitly demarcate transaction boundaries at the start and end of each method call. If a transaction needs to span multiple method calls to the Java Persistence API (JPA) entities, then make use of a session facade bean method to demarcate the start and end of a transaction, encapsulating all method calls. In EJB 3.0, you can use the JPA through the EntityManager component to manage queries and persistence of data.

Oracle Fusion Middleware 11g: Build Java EE Applications 15 - 14

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Managing Transactions with EJBs


The bean provider is not exposed to the complexity of distributed transactions. The Java EE container provides a transaction infrastructure. EJBs do not support a nested transaction model.
Oracle University and Egabi Solutions use only

Copyright 2009, Oracle. All rights reserved.

Managing Transactions with EJBs (continued) An Enterprise JavaBean is required by the specification to support flat transactions, but is not required to support nested transactions. Note: If a transaction begins within the context of another active transaction, you would have a nested transaction. That is, if you start transaction A, and then start transaction B, without ending transaction A, then you have a nested transaction, where transactions A and B might affect one another. The container and the server must provide a transaction service to the EJB components and must also provide some standard interfaces into this service. You will see in the next few slides the mandatory interfaces that must be supported by the provider of the server environment, so that the bean developer does not have to worry about the low-level details of the transaction infrastructure.

Oracle Fusion Middleware 11g: Build Java EE Applications 15 - 15

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Types of Transaction Management


Container-managed transactions:
No transactional management code in the bean Chosen implicitly by default or explicitly by use of the @TransactionManagement (TransactionManagementType.CONTAINER) annotation
Oracle University and Egabi Solutions use only

Available to entities, session beans, and message-driven beans

Bean-managed transactions:
Bean implementation must demarcate the begin, commit, or rollback for the transaction. @TransactionManagement (TransactionManagementType.BEAN) annotation Available only to session beans and MDBs

Copyright 2009, Oracle. All rights reserved.

Types of Transaction Management EJB 3.0 simplifies transaction demarcation through the use of the @TransactionManagement annotation. If this annotation is not present, the container defaults to CMT. CMT and BMT examples are examined in the following slides.

Oracle Fusion Middleware 11g: Build Java EE Applications 15 - 16

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Container-Managed Transactions
@TransactionManagement(TransactionManagementTy pe.CONTAINER) Container-managed transactions can specify one of the following @TransactionAttribute annotations:
Oracle University and Egabi Solutions use only

REQUIRED (default) SUPPORTS MANDATORY NEVER REQUIRES_NEW NOT_SUPPORTED

The transaction attribute can be specified at the:


Class level (where it applies to all business methods) Method level (where it applies to a specific method)
Copyright 2009, Oracle. All rights reserved.

Container-Managed Transactions CMT is used by default or where explicitly declared through the use of @TransactionManagement(TransactionManagementType.CONTAINER). CMT is guided by the use of @TransactionAttribute annotations. The Java EE specifications defined the following transaction attribute values and their semantics: REQUIRED: The container starts a new transaction if one has not already been started. SUPPORTS: The container does not start a new transaction, but uses one if it already exists. MANDATORY: The container throws an exception if one is not already started. NEVER: The container throws an exception if a transaction has already started. REQUIRES_NEW: The container always starts a new transaction, suspending any transaction already started. NOT_SUPPORTED: The container suspends any active transaction. Only REQUIRED and NOT_SUPPORTED transaction attributes are valid for MDBs. The use of REQUIRES_NEW and SUPPORTS with an MDB is not meaningful because there is no preexisting client transactional context, and an MDB does not have a client to handle exceptions for the MANDATORY and NEVER transactional attributes. When the transaction attribute is declared on the bean class, that type of CMT is applied to all business methods of the bean. When the transaction attribute is used on a bean method, that type of CMT is applied to that particular method, overriding the CMT type specified at the bean level.
Oracle Fusion Middleware 11g: Build Java EE Applications 15 - 17

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Transaction Attribute: REQUIRED


A client has: No transaction: The bean starts a new one. A transaction: The bean uses it.

Client (bean or servlet) No transactional context Client (bean or servlet) Clients transactional context

Threads of execution

Bean

New transactional context Threads of execution

Bean

Clients transactional context

Copyright 2009, Oracle. All rights reserved.

Transaction Attribute: REQUIRED The REQUIRED transaction attribute is the default transaction attribute value. It implies that the bean method must always be invoked within a transactional context. If the caller does not have a transactional context, the container starts a new transactional context before the bean method is being called, and finishes it when the method returns. Otherwise, if the caller already contains a transactional context, the bean method joins the existing callers transactional context. The bean methods with a transaction attribute (@TransactionAttribute annotation) value of REQUIRED must always be invoked in a transactional context, as follows: If a client calls the method with a transactional context, the container invokes the method in the clients transactional context. If the client call is not associated with a transactional context, the container starts a new transaction before delegating the method to the bean, and then tries to commit the transaction after the method returns and before returning to the client. If the bean method invokes other beans, the container passes the context with the invocation. In general, you should use the REQUIRED value if any data in an EJB method gets modified, and you are not sure whether the client invoking the EJB method starts a transaction of its own before calling the EJB method.
Oracle Fusion Middleware 11g: Build Java EE Applications 15 - 18

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Transaction Attribute: SUPPORTS


A client has: No transaction: The bean does not start a new one. A transaction: The bean uses it.

Client (bean or servlet) No transactional context Client (bean or servlet) Clients transactional context

Threads of execution

Bean

No transactional context Threads of execution

Bean

Clients transactional context

Copyright 2009, Oracle. All rights reserved.

Transaction Attribute: SUPPORTS The SUPPORTS attribute implies that the bean method inherits the transactional context of the caller. If the caller does not have a transaction, the bean method is called without a transaction. If the caller is transactional, the bean method joins the existing transaction. The bean methods with a transaction attribute value of SUPPORTS are invoked as follows: If the client calls with a transaction context, the method is invoked in the clients transactional context, and the context is passed to any other bean method that the current method calls. If the client calls the method without a transactional context, the method is executed with no transactional context. The SUPPORTS attribute is useful for methods that perform read-only operations, such as retrieving a record from a database table.

Oracle Fusion Middleware 11g: Build Java EE Applications 15 - 19

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Transaction Attribute: MANDATORY


A client has: No transaction: The bean throws the javax.transaction.EJBTransactionRequiredExc eption exception. A transaction: The bean uses it.
Client (bean or servlet) No transactional context Client (bean or servlet) Clients transactional context Threads of execution Bean

Exception thrown
Threads of execution Bean

Clients transactional context

Copyright 2009, Oracle. All rights reserved.

Transaction Attribute: MANDATORY Methods with a transaction attribute of MANDATORY should always be called with a transactional context. If the client calls the method without a transactional context, the container throws a javax.transaction.EJBTransactionRequiredException exception. If a client calls the method with a transactional context, the container invokes the method in the clients transactional context. The MANDATORY transaction attribute could be used in a method that can forcibly roll back the invokers transaction, if necessary.

Oracle Fusion Middleware 11g: Build Java EE Applications 15 - 20

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Transaction Attribute: NEVER


A client has: No transaction: The container calls the method with no transactional context. A transaction: The container throws the javax.ejb.EJBException exception.
Client (bean or servlet) Transactional context Threads of execution Bean

javax.ejb.EJBException

Copyright 2009, Oracle. All rights reserved.

Transaction Attribute: NEVER Methods with a transaction attribute of NEVER should never be called with a transaction context. If the client calls the method with a transaction context, the container throws a javax.ejb.EJBException exception. If the client calls the method without a transaction context, the container calls the method in an unspecified transaction context. The NEVER transaction attribute could be used in a method that is changing a nontransactional resource (such as a text file), and you want to make sure that the client is aware of the nontransactional nature of the method.

Oracle Fusion Middleware 11g: Build Java EE Applications 15 - 21

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Transaction Attribute: REQUIRES_NEW


A client has: No transaction: The bean starts a new one. A transaction: It is suspended; the bean starts a new one and commits it, and then reassociates the old one.
Threads of execution

Client (bean or servlet)

Bean

No transactional context
Client (bean or servlet)

Bean transactional context Suspended Resumed Bean transactional context Bean

Client transactional context

Copyright 2009, Oracle. All rights reserved.

Transaction Attribute: REQUIRES_NEW Methods with the REQUIRES_NEW transaction context are always invoked with a new transactional context, as follows: If the client invokes the method without a transaction context, the container starts a new transaction before delegating the call to the client, and then tries to commit the transaction after the method is completed and before returning the call to the client. If the client calls with a transaction context, the container suspends the clients transaction context and starts a new transaction. The suspended transaction is resumed after the bean method and the new transaction are completed. Note: A commit or rollback operation in the bean transactional context does not affect the transactional state of the suspended transaction. The REQUIRES_NEW transaction attribute has limited uses in the real world. You should use it if you need a transaction, but do not want a rollback to affect the client and vice versa.

Oracle Fusion Middleware 11g: Build Java EE Applications 15 - 22

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Transaction Attribute: NOT_SUPPORTED


A client has: No transaction: The bean does not start a new one. A transaction: The bean suspends it. The transaction resumes when the client gains control.
Threads of execution

Client (bean or servlet)

Bean

No transactional context
Client (bean or servlet)

No transactional context Suspended Resumed No transactional context Bean

Transactional context

Copyright 2009, Oracle. All rights reserved.

Transaction Attribute: NOT_SUPPORTED For a bean method whose transaction attribute value is NOT_SUPPORTED, the container invokes the method in an unspecified context. An unspecified transactional context is used in the EJB specification to refer to cases in which the EJB architecture does not fully define the transaction semantics of an enterprise bean method. This may produce unpredictable results. In WebLogic Server, an unspecified transaction context is implemented to use no transactional context. It is recommended that the transaction attributes be set to at least REQUIRED or REQUIRES_NEW. If the client calls the bean with a transactional context, the container suspends the association of the context from the current thread and resumes the association after the method is complete. If the business method invokes other enterprise beans, the container passes no transaction context with the invocation. This attribute is typically useful for an MDB supporting a JMS provider in a nontransactional AUTO_ACKNOWLEDGE mode. The acknowledgement is sent as soon as the message is successfully delivered and there is no apparent need for the MDB to support rolling back the delivered message. Note: An unspecified context means that there is no context associated with the thread.

Oracle Fusion Middleware 11g: Build Java EE Applications 15 - 23

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Quiz
The transaction demarcation in EJB 3.0 is implemented through the use of the @TransactionManagement annotation. If this annotation is not present, the container defaults to beanmanaged transaction (BMT). 1. True 2. False

Copyright 2009, Oracle. All rights reserved.

Answer: 2

Oracle Fusion Middleware 11g: Build Java EE Applications 15 - 24

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

CMT: setRollbackOnly()
The setRollbackOnly() method can control the transaction state in the bean for a CMT. The setRollbackOnly() method marks the current transaction to rollback. If a transaction is marked for rollback, the container rolls back the transaction before returning to the caller.

Copyright 2009, Oracle. All rights reserved.

CMT: setRollbackOnly() In a CMT bean, the bean cannot, and must not, directly invoke the commit() or rollback() methods to end transactions. Typically, an enterprise bean marks a transaction for rollback to protect data integrity before throwing an application exception because an application exception does not automatically cause the container to roll back the transaction. A CMT bean can invoke the javax.ejb.EJBContext.setRollbackOnly() method to ensure that the container will not commit the transaction and set the current transaction to roll back. The bean can use the javax.ejb.EJBContext.getRollbackOnly() method to detect if the current transaction has been marked for rollback.

Oracle Fusion Middleware 11g: Build Java EE Applications 15 - 25

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Container-Managed Transaction: Example


@TransactionManagement(TransactionManagementType.CONTAINER) @TransactionAttribute(TransactionAttributeType.REQUIRED) 1 @Stateful public CartBean implements Cart { public void initialize() { ... }

2 @TransactionAttribute(TransactionAttributeType.MANDATORY)
public void setTaxRate(float taxRate) { ... } @TransactionAttribute(TransactionAttributeType.MANDATORY) public void addItem(float taxRate) { ... } ...
Copyright 2009, Oracle. All rights reserved.

Container-Managed Transaction: Example Examine the following code sections. Declare use of CMT and make it REQUIRED for all method calls (unless otherwise specified). 1. Class level - @TransactionManagement(TransactionManagementType.CONTAINER): This declares use of CMT for this bean. The container will generate the proper deployment descriptors during deployment. - @TransactionAttribute(TransactionAttributeType.REQUIRED): Each method call will be contained in a transaction if necessary. Note: These two lines can be deleted from the code example in the slide because they define the default behavior. 2. Method level - @TransactionAttribute(TransactionAttributeType.MANDATORY): Calls to the setTaxRate() method must be trapped in a transaction. This attribute overrides the class-level specification for the REQUIRED transactional behavior.

Oracle Fusion Middleware 11g: Build Java EE Applications 15 - 26

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Java Transaction API (JTA)


Java Transaction API (JTA) is: Java EE standard for implementing transactions Interface between the transaction manager and the components involved in the transaction (for example, beans, EJB containers, resource managers, and so on)
The JTA package provides an application interface for managing transactions (UserTransaction).
Oracle University and Egabi Solutions use only

Used for:
Enlisting resources: Single-phase or two-phase commit Demarcating transactions

Copyright 2009, Oracle. All rights reserved.

Java Transaction API (JTA) The JTA is used to explicitly demarcate transactions. A JTA transaction involves enlisting resources (databases). The complexity of your transaction is determined by how many resources your application enlists. Enlisting can be of two types: Single-phase commit (1pc), if only a single resource is enlisted in the transaction Two-phase commit (2pc), if more than one resource is enlisted. The two-phase commit is more difficult to configure. The two-phase commit mechanism allows transactions to be managed across different servers and databases (distributed transactions). Demarcating a transaction means to initiate and terminate the transaction. You can demarcate the transaction yourself by specifying that the bean is bean-managed transactional. You can also specify that the container should demarcate the transaction by specifying that the bean is container-managed transactional, based on the transaction attributes specified in the EJB deployment descriptor. A transaction manager coordinates transactions by propagating the transaction context from one bean to another when invoked by a client, thus ensuring that all the beans invoked during the process are involved in a global transaction. The transaction manager can decide whether changes made by beans can be committed or rolled back, depending on the success or failure of the beans.

Oracle Fusion Middleware 11g: Build Java EE Applications 15 - 27

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Java Transaction API (JTA) (continued) The JTA consists of a high-level transactional client interface and a low-level X/Open XA interface. Only the high-level application interface is discussed in this lesson. This interface is accessible to the beans and is the recommended transactional interface for client applications. The low-level XA interface is used by the EJB server and container to automatically coordinate transactions with resources (such as databases).

Oracle Fusion Middleware 11g: Build Java EE Applications 15 - 28

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

JTA: UserTransaction Interface


Allows applications to explicitly manage transaction boundaries Encapsulates most of the functionality of a transaction manager
Oracle University and Egabi Solutions use only

public interface javax.transaction.UserTransaction{ public abstract void begin (); public abstract void commit (); public abstract int getStatus (); public abstract void rollback (); public abstract void setRollbackOnly (); public abstract void setTransactionTimeout(int secs); }

Copyright 2009, Oracle. All rights reserved.

JTA: UserTransaction Interface The UserTransaction interface in the javax.transaction package is the key interface that enables the bean developer to manage the scope of transactions explicitly. begin(): Starts a global transaction and associates it with the current thread. The transaction-to-thread association is performed by the transaction manager. commit(): Completes the transaction that is associated with the current thread. When this method completes, the thread is no longer associated with a transaction. getStatus(): Determines the transaction status. The return value can indicate a status of active, no transaction, marked rollback, committed, committing, rolled back, and unknown. rollback(): Rolls back the transaction associated with the current thread and reverts the updates. The thread is no longer associated with a transaction. setRollbackOnly(): Modifies the transaction so that the only outcome of the transaction is to roll back the transaction whether the updates succeeded or failed. Any BMT bean participating in the transaction can invoke this method. setTransactionTimeout(int seconds): Sets the timeout value, which indicates the time before which the transaction should complete. If this method is not called, the transaction manager automatically sets a timeout value. This method must be invoked after the begin() method.
Oracle Fusion Middleware 11g: Build Java EE Applications 15 - 29

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Bean-Managed Transactions
Are declared using
@TransactionManagement(TransactionManagementType .BEAN)

Are demarcated and managed by using the JTA UserTransaction interface to:
Oracle University and Egabi Solutions use only

Initialize a transaction context by calling the begin() method Terminate a transaction context by calling the commit(), or the rollback() method

Copyright 2009, Oracle. All rights reserved.

Bean-Managed Transactions The use of bean-managed transactions is specified through the use of the @TransactionManangement(TransactionManangementType.BEAN) annotation. With BMT, the bean manages the transactions in its code by providing begin, commit, and rollback statements. Then the begin(), commit(), and rollback() methods of the UserTransaction object are implemented in the bean. A reference to a javax.transaction.UserTransaction object can be obtained by either using the Java Naming and Directory Interface (JNDI) lookup() method, or by implementing dependency injection.

Oracle Fusion Middleware 11g: Build Java EE Applications 15 - 30

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Bean-Managed Transaction: Example


@TransactionManagement(TransactionManagementType.BEAN) 1 @Stateful public CartBean implements Cart { @Resource 2 private UserTransaction utx; public void setTaxRate(float taxRate) { utx.begin(); 3 try { ...

5 utx.commit(); } catch (Exception ex) { utx.rollback(); 5 ex.printStackTrace(); }


...
Copyright 2009, Oracle. All rights reserved.

Bean-Managed Transaction: Example The steps in the slide indicate the process of creating a BMT demarcation: 1. This declares the use of BMT for this bean. 2. A UserTransaction object (the JTA representation of BMT) is injected into the bean. 3. Start a transaction by invoking the begin() method on the UserTransaction object. 4. Execute the business logic to be included in the transaction. 5. End the transaction by invoking the commit() or rollback() method of the UserTransaction object. Note: The example shown in the slide uses dependency injection to reference a UserTransaction object. You can also look it up directly by using JNDI with the following code:
Context context = new InitialContext(); UserTransaction utx = (UserTransaction)context.lookup("java:comp/UserTransaction"); utx.begin(); ...

Oracle Fusion Middleware 11g: Build Java EE Applications 15 - 31

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

BMT Demarcation: Restrictions


Session beans and message-driven beans can have beanmanaged transactions only if they specify the use of BMT. An instance that starts a transaction must complete the transaction before it starts a new transaction. A stateful session bean can commit a transaction before a business method ends. A stateless session bean must commit the transaction before the business method returns. A message-driven bean must commit the transaction before the onMessage() method returns.

Copyright 2009, Oracle. All rights reserved.

BMT Demarcation: Restrictions BMT demarcation is available only for session beans and message-driven beans that specify use of BMT through the @TransactionManagement annotation. Entities may not use BMT. A stateful session bean can commit a transaction before a business method ends. If a transaction has not been completed by the end of a business method, the container retains the association between the transaction and instance across multiple client calls until the instance eventually completes the transaction. Stateless session beans and message-driven beans must complete the transaction before returning from the relevant method.

Oracle Fusion Middleware 11g: Build Java EE Applications 15 - 32

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Enlisting Database Resources


The process of including SQL updates in a transaction is called enlisting. JTA automatically enlists databases opened with a DataSource object in a global UserTransaction object. Starting from JDK 1.2, a DataSource published into a JNDI namespace is one way to make connections. Connections can also be made implicitly through an EJB 3.0 EntityManager instance. If your global transaction involves more than one database, you must configure a two-phase commit engine.

Copyright 2009, Oracle. All rights reserved.

Enlisting Database Resources Each resource (including databases) that you want managed in the global transaction must be enlisted. JDBC is used to connect to database resources. However, to include all the changes made to multiple databases in a transaction, you must use the JDBC connections in a JTA global transaction. The process of including database SQL updates in a transaction is referred to as enlisting a database resource. The Oracle10g JTA implementation enlists all the databases in which the JDBC connection is opened through the getConnection() method of a JTA data source published in the JNDI namespace. For OracleAS 10.1.3.1, managed data source should be used for JTA/global transactions. By default, managed data sources are configured for two-phase commit transactions. There is no need to use a special external tool to bind the data source to a JNDI name before using it. You must retrieve the connection in the context of a global transactionthat is, you retrieve the connection after the begin() method of the UserTransaction object. The JTA automatically enlists a database resource through a DataSource object. A client or server object opens a JDBC connection to a remote database through the DataSource object in the context of a global transaction. A client can open connections to remote databases through any client JDBC driver. Note: Connections are implicitly opened by an EntityManager instance in EJB 3.0.
Oracle Fusion Middleware 11g: Build Java EE Applications 15 - 33

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Summary
In this lesson, you should have learned how to: Choose between container-managed and bean-managed transactions Set the transaction attribute for container-managed transactions Create transaction demarcations

Copyright 2009, Oracle. All rights reserved.

Oracle Fusion Middleware 11g: Build Java EE Applications 15 - 34

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice: Overview
These practices cover the following topics: Adding a new product record by using explicit default container-managed persistent attributes Adding a new product by using bean-managed persistent techniques in a stateful session bean
Oracle University and Egabi Solutions use only

Copyright 2009, Oracle. All rights reserved.

Practice: Overview In this practice, you configure a supplied application that enables new product records to be added to the PRODUCTS table. In the first example, you explicitly add annotations to the application implementing the default container-manager persistent settings and observe application behavior. In the second example, you modify the same stateful session bean to perform bean-managed persistence by implementing the UserTransaction JTA methods in the session bean. Note: This practice is independent of the course application. It works on the PRODUCTS table data in the same database schema as the course application.

Oracle Fusion Middleware 11g: Build Java EE Applications 15 - 35

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Securing Java EE Applications with JAAS

Oracle University and Egabi Solutions use only

Copyright 2009, Oracle. All rights reserved.

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Objectives
After completing this lesson, you should be able to: Explain the Java EE application security design Describe Java Authentication and Authorization Service (JAAS) Implement JAAS security for Web applications and Enterprise JavaBeans (EJB)

Copyright 2009, Oracle. All rights reserved.

Oracle Fusion Middleware 11g: Build Java EE Applications 16 - 2

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Goals of Java EE Security Architecture


Lessen the burden of the application developer in securing applications Ensure fine-grained access control to EJB resources Enable portable and secured Web applications and EJBs
Oracle University and Egabi Solutions use only

Copyright 2009, Oracle. All rights reserved.

Goals of Java EE Security Architecture Security is a critical issue in the development and deployment of Java EE applications. Following are the goals of the Java EE security architecture: To ease the bean developers burden of coding the security mechanism. The security details need not be coded into the bean but can be controlled declaratively by specifying the details in the deployment descriptor when either the application package is assembled or the application is deployed. To provide a fine-grained security mechanism so that an application and its methods can be accessed only by authenticated and authorized users. You can control access to the Web application functionality, based on a URL pattern, or method specifications in an EJB component. To provide a flexible architecture that allows the Web applications or EJB to be used in any security environment. This enables the applications to be portable across multiple Java EE containers. These goals assume that the developer may not have any idea of the target security environment and its requirements. Instead, the application deployer can customize or map the security policies in the deployment descriptor, depending on the operational environment in which the applications are being deployed.

Oracle Fusion Middleware 11g: Build Java EE Applications 16 - 3

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Overview of Java EE Security Architecture


Use JAAS APIs to: Authenticate a client to access the system
Define security identities (principals and users), groups, and roles to identify clients to the container. Associate principals to the client to enable access to the bean methods.

Authorize clients to access the bean methods


Define logical roles, set method permissions, and map roles to users in the deployment descriptors. Use containers to authorize the client requests to the methods.

Copyright 2009, Oracle. All rights reserved.

Overview of Java EE Security Architecture The Java EE security architecture involves the authentication and the authorization of clients to the system and, for an EJB, the individual methods of the bean. Oracle WebLogic Server supports JAAS by implementing a JAAS provider. The JAAS provider enables an application developer to integrate authentication and authorization services into an application environment. Instead of allocating resources for developing these services, application developers can focus on the presentation and the business logic of their applications. Authentication is the process of verifying the identity of a user, device, or any other entity in a computer system, often as a prerequisite to granting this entity access to resources in a system. For example, when a user enters a username and a password to access the resources on a computer (such as a database) before being permitted access to these resources, the user must first be authenticated (verified) by means of the login information. Authorization is the process of verifying whether a particular method call request from a client should be allowed to execute the method. After a user is authenticated, the authorization process occurs. Authorization is the process of determining whether the authenticated user has the right to perform the requested operation (such as updating a table in a database).

Oracle Fusion Middleware 11g: Build Java EE Applications 16 - 4

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Java Authentication and Authorization Service (JAAS)


JAAS is a framework that: Provides a Java API package to enable applications to authenticate and enforce security Allows definition of logical security names that are mapped in deployment descriptors to users or roles defined in the run-time environment Controls access to Web applications based on URL patterns Allows fine-grained authorization to manage how clients can access bean methods A JAAS provider implements the JAAS framework and applies the Java 2 Security Model.

Copyright 2009, Oracle. All rights reserved.

Java Authentication and Authorization Service (JAAS) The JAAS provider implements JAAS and its policies, and integrates with Java SE and Java EE applications that use the Java 2 Security Model. JAAS extends the access control architecture of the Java 2 Security Model to support principal-based authorization. Policies contain the rules (permissions) that authorize a user to use resources, such as reading a file. Permissions are the basis of the Java 2 Security Model. Each permission represents a specific access to a particular resource. All Java classes (whether run locally or downloaded remotely) are subject to a configured security policy that defines the set of permissions that are available for those classes. You can use the Java 2 Security Model to configure security at all levels of restriction. This provides developers and administrators with increased control over many aspects of enterprise applet, component, servlet, and application security. JAAS is designed to complement the existing code-based security in JDK 1.3. JAAS implements a Java version of the standard Pluggable Authentication Module (PAM) framework, enabling an application to remain independent from the authentication service. The Web application security involves authentication and authorization of clients based on URL patterns, and the EJB security architecture allows fine-grained access control to the individual methods of a bean.

Oracle Fusion Middleware 11g: Build Java EE Applications 16 - 5

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Java Authentication and Authorization Service (JAAS)


JAAS supports the following authorization, authentication, and user-community (realm) features: Principals Subjects Login module authentication Roles Realms Policies Permissions

Copyright 2009, Oracle. All rights reserved.

Java Authentication and Authorization Service (JAAS) (continued) JAAS supports the following authorization, authentication, and user-community (realm) features: Principals: A principal is a specific identity, such as a user named Smith or a role named HR. A principal is associated with a subject on successful authentication to a computing service. Subjects: A subject represents a grouping of related information for a single user of a computing service, such as a person, computer, or process. Such information includes the subjects identities and security-related attributes (such as passwords and cryptographic keys). Subjects can have multiple identities, where principals represent identities in the subject. A subject becomes associated with a principal (user Smith) on successful authentication to a computing servicethat is, the subject provides evidence (such as a password) to prove its identity. Login module authentication: To associate a principal with a subject, a client attempts to log in to an application. In login module authentication, the LoginContext class provides the basic methods that are used to authenticate subjects such as users, roles, or computing services. Roles: JAAS does not explicitly define roles or groups. Instead, roles or groups are implemented as concrete classes that use the java.security.Principal interface.
Oracle Fusion Middleware 11g: Build Java EE Applications 16 - 6

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Oracle Fusion Middleware 11g: Build Java EE Applications 16 - 7

Oracle University and Egabi Solutions use only

Java Authentication and Authorization Service (JAAS) (continued) Realms: JAAS does not explicitly define user communities. However, the Java EE Reference Implementation (RI) defines a similar concept of user communities called realms. A realm provides access to users and roles (groups) and optionally provides administrative functionality. Policies: A policy is a repository of JAAS authorization rules. The policy includes grants of permissions to principals, thereby answering the following question: Given a grantee, what are the granted permissions of the grantee? Policy information is supplied by the JAAS provider, which can be file based or can use a Lightweight Directory Access Protocol (LDAP) server. Permissions: Permissions are the basis of the Java 2 Security Model. All Java classes (whether run locally or downloaded remotely) are subject to a configured security policy that defines the set of permissions available for those classes. Each permission represents a specific access to a particular resource. A permission instance consists of a class name (such as java.io.FilePermission), a target or resource to which the permission applies (for example, a directory pattern such as /home/*), and a set of actions associated with the target (such as read, write, and/or execute).

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Authorization of a Client
The authorization is specified in the Java EEspecific deployment descriptors. Security roles:
Define the security view of the application to the deployer Must be mapped to the appropriate security principals in the target environment

Every client obtains a security principal. A client can invoke a URL or a method only if the clients role has the associated invocation rights. The container provider enforces the security policies and provides the tools for managing security.

Copyright 2009, Oracle. All rights reserved.

Authorization of a Client The security roles that are defined by the application assembler provide the deployer with a logical and simplified security view of the Web application or the EJB. The deployer is responsible for mapping the logical security roles to principals or to groups of principals who are defined in the target operational environment. At run time, a client is allowed to access a URL or invoke a business method only if the principal making the request is authenticated and authorized (by being associated with an appropriate security role) to access the requested resource. The container provider enforces the security policies at run time and provides the tools for managing security during deployment and at run time. The security view defines the various types of users of the application and their rights to invoke a URL request or methods in the enterprise-bean interfaces. Note: The security roles define the logical security view of an application. They should not be confused with the user groups, users, principals, and other concepts that exist in the target enterprises operational environment. The security roles and information are configured and mapped in configuration files and deployment descriptors, as discussed in the following slides.

Oracle Fusion Middleware 11g: Build Java EE Applications 16 - 8

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Quiz
A principal is an identity assigned to a user or group as a result of authentication. 1. True 2. False
Oracle University and Egabi Solutions use only

Copyright 2009, Oracle. All rights reserved.

Answer: 1

Oracle Fusion Middleware 11g: Build Java EE Applications 16 - 9

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Security Process Architecture

WebLogic Security Framework acts as an intermediary between the WebLogic containers (Web and EJB), the Resource containers, and the security providers.

LDAP Server (Example: OID)

LDAP Provider

JNDI Tree
request

Security Service Framework Client


EJB WebApp App

WebLogic Server
Copyright 2009, Oracle. All rights reserved.

Security Process Architecture The WebLogic Security Service Framework provides a simplified application programming interface (API) that can be used by security and application developers to define security services, such as the authentication, identity assertion, principal validation, and so on. The slide shows the clients request being sent to the appropriate container on the application server. The container delegates authentication and authorization decisions to the security service. The container acts as the security policy enforcement point but the security service will act as the policy decision point. Note: The Lightweight Directory Access Protocol (LDAP) is a standard that came from X.500 and is a specification for a client-server protocol to retrieve and manage directory information. LDAP provides a hierarchical directory structure for storing information and is commonly used to store user and group information for authentication. WebLogic Server includes an embedded LDAP server that acts as the default security provider data store for the WebLogic Authentication, Authorization, Credential Mapping, and Role Mapping providers.

Oracle Fusion Middleware 11g: Build Java EE Applications 16 - 10

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Security Services
EJB Client
Authenticate

WLS
login

EJB Login Module(s)

sign Subject

MyEJB.abc( ) and Subject

validate

get role

Role Mapper Access Decision Adjudicator

is accessed allowed?

adjudicate abc( )

Copyright 2009, Oracle. All rights reserved.

Security Services In simple authentication, a user attempts to log in to a system by using a username/password combination. The WebLogic Server establishes trust by validating that users username and password and returns a Subject that is populated with Principals. This process requires the use of a JAAS Login Module and Principal Validation provider. After successfully proving a caller's identity, an authentication context is established, which allows an identified user or system to be authenticated to other entities. During the authorization process, WebLogic Server determines if a given Subject can perform a given operation on a given resource and returns the result of that decision to the client application, this process requires the use of Access Decisions, an Adjudication provider, and possibly multiple Role Mapping providers. Roles are obtained from the Role Mapping providers and input to the Access Decisions. The Access Decisions are then consulted for an authorization result. If multiple Access Decisions are configured and return conflicting authorization results (such as PERMIT and DENY), an Adjudication provider is used to resolve the contradiction by returning a final decision.

Oracle Fusion Middleware 11g: Build Java EE Applications 16 - 11

Oracle University and Egabi Solutions use only

Principal Validator(s)

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Security Realms
A security realm is a collection of system resources and security service providers. Only one security realm can be active at a given time. A single security policy is used in any realm. Users must be recognized by an authentication provider of the security realm. Administration tasks include creating security realms.

Copyright 2009, Oracle. All rights reserved.

Security Realms A security realm is a mechanism for protecting WebLogic Server resources such as authenticators, adjudicators, authorizers, auditors, role mappers, and credential mappers. A WebLogic Server resource is protected under only one security realm and by a single security policy in that security realm. A user must be defined in a security realm in order to access any resources belonging to that realm. When a user attempts to access a particular WebLogic Server resource, WebLogic Server tries to authorize the user by checking the access privileges assigned to the user in the relevant realm.

Oracle Fusion Middleware 11g: Build Java EE Applications 16 - 12

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Users and Groups


Users are entities that use WebLogic Server such as:
Application end users Client applications Other WebLogic Servers

Groups are:
Logical sets of users More efficient for managing a large number of users
Oracle University and Egabi Solutions use only

Copyright 2009, Oracle. All rights reserved.

Users and Groups Managing groups is more efficient than managing large numbers of users individually. For example, an administrator may specify permissions for fifty users at one time if those fifty users belong to the same group. Usually, group members have something in common. For example, a company may separate its sales staff into two groups, sales representatives and sales managers, because staff members have different levels of access to WebLogic Server resources depending on their job descriptions. WebLogic Server can be configured to assign users to groups. Each group shares a common set of permissions that govern access to resources of its member users. You can mix group names and user names whenever a list of users is permitted. A person can be defined as both an individual user and a group member. Individual access permissions override any group member access permissions. WebLogic Server evaluates each user by first looking for a group, and testing whether the user is a member of the group, and then looking for the user in the list of defined users.

Oracle Fusion Middleware 11g: Build Java EE Applications 16 - 13

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Configuring New Users in WebLogic Server


1 2

Copyright 2009, Oracle. All rights reserved.

Configuring New Users in WebLogic Server To configure a new user, execute the following steps: 1. Log in to the WebLogic Server Administration Console and click Security Realms. On the Summary of Security Realms page, click myrealm (the default implementation). 2. On the Settings for myrealm page, click Users and Groups > Users tab. Click the New button and enter the details for the new user.

Oracle Fusion Middleware 11g: Build Java EE Applications 16 - 14

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Configuring New Users in WebLogic Server

Copyright 2009, Oracle. All rights reserved.

Configuring New Users in WebLogic Server (continued) Groups can be organized in arbitrary ways providing greater flexibility. In WebLogic Server, groups can contain users as well as other groups. For example, users Sarah, Tim, Colleen, and Bijoy are members of the Employees group. Bijoy is also a member of the Managers group. The Managers group is also a part of the Employees group. To configure a new group, click the Users and Groups > Groups tab for your realm.

Oracle Fusion Middleware 11g: Build Java EE Applications 16 - 15

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Adding Users to Groups


1 2 3

Copyright 2009, Oracle. All rights reserved.

Adding Users to Groups To add a user to a group, execute the following steps: 1. On the Settings for myrealm page, click Users and Groups > Users tab. Click the new user. 2. Click the Groups tab. 3. Add the parent groups that the user should be a part of.

Oracle Fusion Middleware 11g: Build Java EE Applications 16 - 16

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Logical Roles
A role refers to a set of users who have the same permissions. A role differs from a group; a group has static membership; a role is conditional. A user and group can be granted multiple roles. There are two types of roles: global-scoped roles and resource-scoped roles. Roles defined in deployment descriptors can be inherited.
Occurs at deployment time Can be disabled

Copyright 2009, Oracle. All rights reserved.

Logical Roles A role definition is specific to a security realm. Roles are tightly coupled with the authorization provider. A role can be defined as resource scoped or globally scoped. Resource scoped means it is granted to a specific resource, such as a method of an EJB, or a branch of the JNDI tree. Globally scoped means a role is granted to all resources in a security realm. WebLogic Server defines a set of default global roles for protecting WebLogic resources. Roles can be assigned statically by defining them in the deployment descriptor for specified users or groups or dynamically through the administration console by defining a set of conditions. Default Global Roles Provided by WebLogic Server Admin can display and modify all resource attributes and perform start and stop operations. By default, users in the Administrators group are granted the Admin role. You can change this association or add other group associations. Operator can display all resource attributes. Users can start, suspend, resume, and stop resources. By default, users in the Operators group are granted the Operator role. You can change this association or other group associations. Deployer can display all resource attributes. Users can deploy applications, EJBs and other deployable modules. By default, users in the Deployers group are granted the Deployer role. You can change this association or other group associations.

Oracle Fusion Middleware 11g: Build Java EE Applications 16 - 17

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Logical Roles (continued) Monitor can display all resource attributes. Users can modify resource attributes and operations that are not restricted to the other roles. By default, users in the Monitors group are granted this role. You can change this association or other group associations. AppTester can test versions of applications that are deployed to Administration mode.

Oracle Fusion Middleware 11g: Build Java EE Applications 16 - 18

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Quiz
Security realm consists of a set of configured security providers, users, groups, security roles, and security policies. 1. True 2. False
Oracle University and Egabi Solutions use only

Copyright 2009, Oracle. All rights reserved.

Answer: 1

Oracle Fusion Middleware 11g: Build Java EE Applications 16 - 19

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Configuring Security
To protect a Web application with declarative security: 1. Determine Web Application resources that must be protected. 2. Define roles that should access the protected resources. 3. Map protected resources to roles that should access them. 4. Map roles to users/groups in the WLS security realm. 5. Set up an authentication mechanism.

Copyright 2009, Oracle. All rights reserved.

Configuring Security Configuration of the security environment involves: Defining logical roles in the Java EE application deployment descriptor Mapping the logical roles to users and groups in the WebLogic-specific deployment descriptor The other methods of authorization and authentication include the LDAP-based OID and the use of single sign-on features. You can use the JAAS API to build custom providers. Note: In case of EJB 3.0, the ejb-jar.xml deployment descriptor file is optional. You can use annotations instead. The ejb-jar.xml file is not used for entities. Configuration in the ejb-jar.xml file overrides annotations.

Oracle Fusion Middleware 11g: Build Java EE Applications 16 - 20

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Determining Protected Resources


Web resources are defined based on URL patterns. URL patterns provide a flexible way to define a single resource or a group of resources. Examples of URL patterns:
URL Pattern
/* /*.jsp /context/*

Role Name
Some role name (such as director, manager, guest)

... ...

Copyright 2009, Oracle. All rights reserved.

Determining Protected Resources URL patterns are used later to map security roles to Web resources.

Oracle Fusion Middleware 11g: Build Java EE Applications 16 - 21

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Defining the Logical Roles


The logical security roles defined in the Java EE deployment descriptors are: Specified in the web.xml file for Web applications, or in the ejb-jar.xml file for EJB components Defined in the <security-role> element for the application (One or more roles can be specified.) Authorized to invoke methods that are listed in the <method-permissions> element for the security role Scoped at the level of the application or all the enterprise beans in the jar file

Copyright 2009, Oracle. All rights reserved.

Defining the Logical Roles Roles are logical identities that each application uses to indicate access rights to its different objects. The Web application (web.xml) and EJB deployment descriptor (ejb-jar.xml) identify roles that are needed to access different URLs or methods of the application. In the Java EE deployment descriptors, security roles are defined in the <security-role> element that is located in the <assembly-descriptor> element. Because the application assembler provides the (logical) security view of the application, the deployers job is simplified. The application assembler defines one or more security roles in the deployment descriptor and then assigns URL patterns or groups of methods of an enterprise bean to the security roles. Because the application assembler generally does not know the security environment of the operational environment, the security roles are meant to be logical roles (or actors), each representing a type of user that should have the same access rights to the application. The application deployer can then map the logical roles to the security definitions in the execution environment of the application.

Oracle Fusion Middleware 11g: Build Java EE Applications 16 - 22

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Defining and Using Logical Roles in Web Applications (web.xml)


1. Define a logical role in the <security-role> element. 2. Use the role in the <security-constraint> element.
<security-role> <role-name>managers</role-name> <!--define--> </security-role> <security-constraint> <web-resource-collection> <web-resource-name>UpdEmployee</web-resource-name> <url-pattern>/UpdEmployees.jsp</url-pattern> </web-resource-collection> <auth-constraint> <role-name>managers</role-name> <!--apply--> </auth-constraint> <user-data-constraint> <transport-guarantee>NONE</transport-guarantee> </user-data-constraint> </security-constraint>
Copyright 2009, Oracle. All rights reserved.

Defining and Using Logical Roles in Web Applications (web.xml) The example in the slide shows how to define a logical security role named managers, which is to be used by the Web application. Each logical role is defined in the <security-role> element, and many security role elements can be defined. The logical role is applied to a URL pattern that is contained in a <securityconstraint> element. The elements that nest in the <security-constraint> definition are as follows: The <web-resource-collection> element contains a <web-resource-name> that contains one or more <url-pattern> elements. The <web-resource-name> element is the name of the Web application. The <url-pattern> element defines the URL pattern for Web application pages. The <auth-constraint> element gives access to users in the logical role to the collection of URLs that are identified in the enclosing security constraint. The <user-data-constraint> element indicates whether or not the data communicated between the client and the container is protected. Note: By default, all users have access to the URLs that are provided in the Web applications, unless you control the access by using the mechanisms that are shown in the slide.

Oracle Fusion Middleware 11g: Build Java EE Applications 16 - 23

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Defining and Using Logical Roles in EJBs (ejb-jar.xml)


1. Define a logical role in the <security-role> element. 2. Use the role in the <method-permission> element.
<assembly-descriptor> <security-role> <description>Manager</description> <role-name>managers</role-name> </security-role> <method-permission> <role-name>managers</role-name> <method> <ejb-name>HrApp</ejb-name> <method-name>incrementSalary</method-name> <method-params><method-param>int</method-param> <method-param>int</method-param></method-params> </method> </method-permission> ... </assembly-descriptor> ...
Copyright 2009, Oracle. All rights reserved.

Defining and Using Logical Roles in EJBs (ejb-jar.xml) The code in the slide shows the process of specifying the security roles and method permissions on different beans and their methods. All these details are specified in the <assemblydescriptor> element of the XML deployment descriptor. You can specify many security roles with the <security-role> element. The example in the slide shows managers being specified as a role name. The <method-permission> element specifies the role name (from the security role specified in the slide), the bean, and the method names for which this role is authenticated. The method permissions are defined for the method that is named in the <method-name> element. The name of a method can be specified as: An asterisk (*) representing all methods in the component A specific individual method name in the component, including its parameters Note: The example in the slide assumes that all the users have been granted access to all the methods of the HrApp bean, except the incrementSalary() method, which can be executed only by users belonging to the managers role.

Oracle Fusion Middleware 11g: Build Java EE Applications 16 - 24

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Mapping Logical Roles to Users and Groups


Mapping is done in the WebLogic-specific deployment descriptors. Mapping a logical role to a group or a specific user:
<?xml version = '1.0' encoding = 'windows-1252'?> <weblogic-web-app ... > <security-role-assignment> <role-name>managers</role-name> <principal-name>joe</principal-name> <principal-name>bijoy</principal-name> </security-role-assignment> ... </weblogic-web-app>
weblogic.xml

Copyright 2009, Oracle. All rights reserved.

Mapping Logical Roles to Users and Groups The mapping of the logical security roles, defined in the Java EE deployment descriptors, is done by using the Weblogic-specific deployment descriptor files. You define a mapping in: weblogic.xml for Web applications weblogic-ejb-jar.xml for EJB components weblogic-application.xml for either the Web applications or the EJB components The logical roles are mapped to the actual users or roles (groups) defined in the security provider that is configured for the Java EE environment. The slide shows examples of mapping a logical role to a group and specific users in a weblogic.xml file.

Oracle Fusion Middleware 11g: Build Java EE Applications 16 - 25

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Setup Authentication
Configure how a Web application determines users security credentials: BASIC: Uses the Web browser to display a dialog box FORM: Uses a custom HTML form CLIENT-CERT: Uses a client certificate to authenticate
requests

Configuring authentication:

<login-config> <auth-method>BASIC, FORM, or CLIENT-CERT</authmethod> <form-login-config> <form-login-page>login.jsp</form-login-page> <form-error-page>badLogin.jsp</form-error-page> </form-login-config> web.xml </login-config>
Copyright 2009, Oracle. All rights reserved.

Setup Authentication Configure how users will be authenticated in your Web application through the use of the <login-config> element. Java EE provides three types of authentication: BASIC: Uses the Web browser to display a dialog box with fields for a username and password FORM: Uses a specified HTML page, JSP, or servlet to display an HTML form with username and password text fields. The generated form must conform to a set of specifications. Use the <form-login-config> element to specify the resource containing the form. CLIENT-CERT: Uses client certificates to authenticate the request The <form-error-page> element defines the JSP, servlet, or HTML file to display if the users credentials are invalid.

Oracle Fusion Middleware 11g: Build Java EE Applications 16 - 26

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Authentication Examples
BASIC Authentication:

FORM-based Authentication:

Copyright 2009, Oracle. All rights reserved.

Oracle Fusion Middleware 11g: Build Java EE Applications 16 - 27

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Setting Access Control with JDeveloper


You can set security roles to access a Web application or an EJB by using JDeveloper deployment descriptor editors:
Use the Web Application Deployment Descriptor editor for Web applications. Use the EJB Module Editor for EJBs.

For Web applications, set the access permissions as constraints defining URL patterns for a Web resource. For EJBs, set the access permissions for either individual methods or all the methods of the bean.

Copyright 2009, Oracle. All rights reserved.

Setting Access Control with JDeveloper You can create security roles for Web applications or EJB modules by using: The Web Application Deployment Descriptor editor for Web applications The EJB Module Editor for EJBs The Web Application Deployment Descriptor editor is displayed by right-clicking the web.xml file and selecting the Settings menu option. You define the logical security role in the Security section, and you define access rules for the logical roles for a Web resource and URL patterns in the Constraints section. The EJB Module Editor is displayed by right-clicking the ejb-jar.xml file and selecting the Edit EJB Module menu option. In the EJB Module Editor, access the Security Role section to create security roles and associate them with method permissions. The slides that follow show how to use the EJB Module Editor.

Oracle Fusion Middleware 11g: Build Java EE Applications 16 - 28

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Creating Web Application Security Roles

Copyright 2009, Oracle. All rights reserved.

Creating Web Application Security Roles To declaratively create security for your Web application, you first define one or more roles to be available to the application. The security role names can be: A role name defined in Java EE environment Any logical role name of your choice If you define a logical name, you must map it to actual users or roles found in the WebLogic Server. The slide shows how to create a logical role: 1. Right-click the WEB-INF/web.xml file, and then choose Properties. 2. Choose Security Roles, and then click Add. 3. Enter the name of the new security role, and then click OK.

Oracle Fusion Middleware 11g: Build Java EE Applications 16 - 29

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Web Application Login Authentication

Copyright 2009, Oracle. All rights reserved.

Web Application Login Authentication The HTTP Server provides you with a choice of techniques for authenticating users, including the following: Basic authentication, where the browser prompts for a username and a password. This is not secure and is often combined with secure socket layer (SSL). Digest authentication, where the browser prompts for a username and password, which is more strongly encrypted than basic authentication. This lacks browser support. Form-based authentication, requiring an application to generate an HTML form to submit the username and the password. A Java EE container can authenticate the username and password that is submitted by using an HTML form if the form action attribute is set to the j_security_check string value, and the username and password fields are named j_username and j_password, respectively. With form-based authentication, you specify both a Login Page (with the login form) and an Error Page to direct failed authentication requests. Client certificate authentication, requiring that the browser use HTTPS and have a personal certificate installed

Oracle Fusion Middleware 11g: Build Java EE Applications 16 - 30

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Web Application Authorization

Copyright 2009, Oracle. All rights reserved.

Web Application Authorization After the user is authenticated, you apply authorization by granting permissions to a user or role. You need to create or modify the <security-constraint> element in the web.xml file to declaratively implement Web application authorization in a Java EE security environment. The <security-constraint> element contains: A Web resource definition in the <web-resource-collection> element An authorization part in the <auth-constraint> element allowing the security role defined for the application to use the Web resource A Web resource is given a user-defined name, contains a collection of one or more URL patterns, and is optionally combined with HTTP methods. This gives a single name for a collection of Web pages and types of HTTP requests that can be made for those pages. The authorization constraint restricts access to a set of security roles that are assigned to the Web resource. The security roles must be defined or mapped to an actual role by using the deployment descriptors. The slide shows how to create a Web resource called AllStaff, with a single URL pattern faces/app/staff/*, related to the application root context. The authorization for the AllStaff Web resource allows all users who have the manager or technician role to access the Web page. By default, all users have access to a Web resource.
Oracle Fusion Middleware 11g: Build Java EE Applications 16 - 31

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

EJB Security Roles


EJB security roles: Provide role-based access control of EJBs and their methods Are implemented through security annotations @DeclareRoles @RolesAllowed @PermitAll @DenyAll @RunAs

Copyright 2009, Oracle. All rights reserved.

EJB Security Roles EJB security is implemented through security annotations that define role-based access controls for the bean and its methods. The security annotations are: @DeclareRoles: Declares roles in a class for an EJB module. The container also generates a list of roles used based on other security annotations (such as @RolesAllowed). @RolesAllowed: Identifies roles with permission to access the bean or its methods (depending on which level the annotation is used) @PermitAll: Provides unrestricted access to the bean or its methods @DenyAll: Disables access to particular bean methods by overriding rights defined for the bean class @RunAs: Sets the security identity of a bean Security annotation may be used on a bean class or on any of its methods. When used on a bean class, the annotation sets the default control for the bean. Annotations used on bean methods override or augment the access controls defined at the bean-class level.

Oracle Fusion Middleware 11g: Build Java EE Applications 16 - 32

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Security Annotation: Example


@Stateless 1 @RolesAllowed("admin") public class AdminServiceBean implements AdminService { public void adminTask() {System.out.println("Admin");} @RolesAllowed("user") 2 public void sharedTask() { System.out.println("Shared admin/user method called"); }

3 @PermitAll public void safeTask() {System.out.println("Safe");} 4 @DenyAll public void badTask() {System.out.println("Error");}
@EJB SudoBean bean; 5 @RunAs("admin") public void privilegedTask() {bean.sudoTask();} }
Copyright 2009, Oracle. All rights reserved.

Security Annotation: Example In the code example in the slide: 1. @RolesAllowed("admin") specifies that, by default, only users with an admin role may use the beans methods. As such, only admin users can call the adminTask() method. 2. @RolesAllowed("user") used at the method level overrides the bean-level access control by granting rights to users with a user role to access the sharedTask() method. Now users with a user role or an admin role can call the sharedTask() method. 3. @PermitAll used at the method level overrides the bean-level access control by granting permission for all users to call the safeTask() method. 4. @DenyAll denies access to the badTask() method for everyone. 5. @RunAs specifies that AdminServiceBean should be identified as an admin when executing privilegedTask(). As such, when AdminServiceBean attempts to call the SudoBeans sudoTask() method, access is granted or denied according to the rights of the admin role.

Oracle Fusion Middleware 11g: Build Java EE Applications 16 - 33

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Summary
In this lesson, you should have learned how to: Describe the principles behind Java EE application security design Describe the Java Authentication and Authorization Service (JAAS) List the security attributes of the Java Naming and Directory Interface (JNDI) Context interface Implement JAAS security for Web applications Use security annotations to implement JAAS security for EJBs

Copyright 2009, Oracle. All rights reserved.

Oracle Fusion Middleware 11g: Build Java EE Applications 16 - 34

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice: Overview
These practices cover the following topics: Implementing login authentication Using JAAS to restrict access to JSF pages

Copyright 2009, Oracle. All rights reserved.

Practice: Overview In this practice set, you create JAAS users and roles for application authentication and you modify the course application to implement Web-layer security by using JAAS and form-based login authentication.

Oracle Fusion Middleware 11g: Build Java EE Applications 16 - 35

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Oracle University and Egabi Solutions use only

Packaging and Deploying Java EE Applications

Copyright 2009, Oracle. All rights reserved.

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Objectives
After completing this lesson, you should be able to: Deploy Java EE applications to the WebLogic server environment Deploy applications by using :
Oracle University and Egabi Solutions use only

Console Command line JDeveloper

Copyright 2009, Oracle. All rights reserved.

Oracle Fusion Middleware 11g: Build Java EE Applications 17 - 2

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Deploying Java EE Applications


Oracle WebLogic Server 10g release 3 (10.3): Is a Java EE 5compliant container that
Provides a Java EEcompliant infrastructure for deployment Supports deploying, undeploying, and redeploying Java EE applications and modules Supports Java SE 6 specification

Implements the Java EE Application Deployment API (JSR-88) Supports deployment with the following tools:
weblogic.Deployer Administration Console WLST

Copyright 2009, Oracle. All rights reserved.

Deploying Java EE Applications As a Java EE 5compliant container, WebLogic Server provides a Java EEcompliant infrastructure for deploying, undeploying, and redeploying Java EEcompliant applications and modules. Components that can be deployed into a WebLogic Server instance include: A Web application packaged as a Web Archive (WAR) file Stand-alone modules packaged as Java Archive files (JARs) containing Web Services, Enterprise JavaBeans (EJB JAR), application clients, or resource adapters (RAR) A complete Java EE application packaged as an Enterprise Archive (EAR) file, which may contain zero or more of the archives. All Java EEcompliant archive files deployed into the server must be packaged in accordance with the guidelines specified in the Java EE 5 specification. This includes packaging the Java EE standard deployment descriptors required for each type of component, such as the Java EE Application Descriptor (application.xml) for applications and the Java EE Web Descriptor (web.xml) for Web modules. The WebLogic Server deployment infrastructure implements the functionality outlined in the Java EE Application Deployment API (JSR-88), which defines a standard API for configuring and deploying Java EE applications and modules into a Java EEcompatible environment. Specifically, the JSR-88compliant features provide the ability to: Start an application immediately upon deployment, making it available to clients
Oracle Fusion Middleware 11g: Build Java EE Applications 17 - 3

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Deploying Java EE Applications (continued) Stop an application, making it unavailable to clients Undeploy an application or module Redeploy an application or module, essentially updating the currently installed application with an updated version The term hot deployment refers to the process of deploying archive filesEARs, WARs, JARs, and so onand their associated XML descriptor files on a production application server without shutting down or restarting (bouncing) the server. Hot deployment or redeployment of an application or a stand-alone module into WebLogic Server is generally supported as long as no changes are made during the deployment process to the existing data source, JMS, or RMI configuration files. It is also mandatory that no changes have been made to the structure of an EJB replacing an existing EJB, during the deployment process. In addition, libraries at the container level cannot be deployed in this manner. If an application is dependent upon a newer library, the server instance must be restarted. To deploy applications into WebLogic Server, you can use any of the following options: weblogic.Deployer: weblogic.Deployer provides a command-line based interface for performing both basic and advanced deployment tasks. Administration Console: The Administration Console provides a series of Web-based Deployment Assistants that guide you through the deployment process. WebLogic Scripting Tool (WLST): The WebLogic Scripting Tool is a new commandline interface that you can use to automate domain configuration tasks, including application deployment configuration and deployment operations.

Oracle Fusion Middleware 11g: Build Java EE Applications 17 - 4

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Packaging Business-Tier Components


JDeveloper Application assembly Application components
identifies

Web Archive (WAR) JSF pages WAR profile EJB Archive (EJB JAR)

application.xml

EJBs

EJB profile

creates

Application deployment profile

Oracle WebLogic Server Application Archive (EAR)

Copyright 2009, Oracle. All rights reserved.

Packaging Business-Tier Components To create an application package: Create an EJB JAR file for EJB components Create a WAR file for Web components Create an EAR file for the application, which contains: - An application.xml file describing the modules in the application - Module archives including EJB JAR, WAR, and (optionally) other JAR or Client Archive (CAR) files Packing application code into archives can be done with Oracle JDeveloper deployment profiles: An EJB deployment profile creates an EJB JAR file. A Web deployment profile creates a WAR file. An application deployment profile creates the EAR file. Note: If you do not use Oracle JDeveloper, you can create the various archive files that must conform to their required Java EE structure with Ant, with other tools, or manually. After you create the archive files, they can be deployed by using any of the deployment tools, such as Ant and JDeveloper.

Oracle Fusion Middleware 11g: Build Java EE Applications 17 - 5

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Packaging Web Applications


1. Arrange resources in a prescribed directory structure. 2. Develop the web.xml deployment descriptor (or copy as required). 3. Develop the weblogic.xml deployment descriptor (WLSspecific). 4. Archive Web App into a .war file using JAR. 5. Deploy Web App onto WLS. 6. Configure Web App with the WLS Administration Console.

Copyright 2009, Oracle. All rights reserved.

Packaging Web Applications Packaging and deploying a Web application is a relatively simple and easy process. The more difficult aspect of the process is the configuration of the XML files. But after you have configured these files once or twice, you should be able to create your own templates, which will streamline the deployment process for any later projects. We will briefly cover the purpose and description of the web.xml and weblogic.xml files in this section.

Oracle Fusion Middleware 11g: Build Java EE Applications 17 - 6

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Web Application Structure


The structure of Web applications is defined by the Servlet specification. A Web application can be either:
An archived file (.war file) An expanded directory structure
Directory/Files Description
Document root of Web application Information for archive tools (manifest) Private files that will not be served to clients Server-side classes such as servlets and applet .jar files used by Web app Web app deployment descriptor WLS-specific deployment descriptor

Copyright 2009, Oracle. All rights reserved.

Web Application Structure A Web application on WebLogic Server includes the following files: At least one servlet or JSP, along with any helper classes Optionally, a web.xml deployment descriptor, a Java EE standard XML document that describes the contents of a WAR file Optionally, a weblogic.xml deployment descriptor, an XML document containing WebLogic Server-specific elements for Web applications Can also include HTML and XML pages with supporting files such as images and multimedia files XML Deployment Descriptors A deployment configuration refers to the process of defining the deployment descriptor values required to deploy an Enterprise application to a particular WebLogic Server domain. The deployment configuration for an application or module is stored in three types of XML documents: Java EE deployment descriptors, WebLogic Server descriptors, and WebLogic Server deployment plans.

Oracle Fusion Middleware 11g: Build Java EE Applications 17 - 7

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Oracle Fusion Middleware 11g: Build Java EE Applications 17 - 8

Oracle University and Egabi Solutions use only

Web Application Structure (continued) You develop your Web application within a specified directory structure so that it can be archived and deployed on WebLogic Server. All servlets, classes, static files, and other resources belonging to a Web application are organized under a directory hierarchy. The root of this hierarchy defines the document root of your Web application. All files under this root directory can be served to the client, except for files under the special directories WEB-INF and METAINF located in the root directory. The root directory should be named with the name of your Web application. Private files should be located in the WEB-INF directory, under the root directory. All files under WEB-INF are private and are not served to a client. Make sure that the WEB-INF directory contains the following directories and files: MyWebApplicationName/: Place your static files, such as HTML files and JSP files, in this directory (or a subdirectory). This directory is the document root of your Web application. /WEB-INF/web.xml: The Web application deployment descriptor that configures the Web application /WEB-INF/weblogic.xml: The WebLogic-specific deployment descriptor file that defines how named resources in the web.xml file are mapped to resources residing elsewhere in WebLogic Server. This file is also used to define JSP and HTTP session attributes. /WEB-INF/classes: Contains server-side classes such as HTTP servlets and utility classes (optional) /WEB-INF/lib: Contains .jar files used by the Web application (optional)

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Configuring Web Applications


Web applications are configured through deployment descriptors web.xml and weblogic.xml which: Define run-time environment Map URLs to servlets and JSPs Define application defaults such as welcome and error pages Specify Java EE security constraints Define work managers for applications Set the context-root for the application

Copyright 2009, Oracle. All rights reserved.

Configuring Web Applications One of the pivotal components of a Web container and its Web applications is the ability to control deployment, which is actually a two-step process. The first step in deployment is to define the normal everyday characteristics of a given Web application through the web.xml file. Characteristics, such as what URLs should invoke what servlet or JSP page, and additional environmental information, such as where to store temporary files or who should receive error email, might be defined within the deployment descriptor of a Web application. Other information, such as the first page to be displayed when an application is accessed or the name of an error page, is also part of the static definition of a Web application. The second stage in deployment comes when an application is actually placed into service in a production environment. At this time, security roles, which were defined in the first stage, must be mapped to actual users and groups in the production system. Services such as database access, named in the first stage, must be assigned to actual resources in a production environment. Configuration of the Web application is done through web.xml and weblogic.xml. Java EE specifies that the web.xml file contains all configuration parameters necessary to deploy a Web application and is a required component for a valid .war archive. The weblogic.xml contains information to supplement the web.xml configuration, but is specific to WebLogic Server services and implementation as its name implies. Parameters such as page update check intervals and whether to keep the source files generated for JSPs, are common examples.
Oracle Fusion Middleware 11g: Build Java EE Applications 17 - 9

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

What Is web.xml?
The web.xml file is a deployment descriptor for configuring: Servlets and JSP registration Servlet initialization parameters JSP tag libraries MIME type mappings Welcome file list Error pages Security constraints and roles Resources EJB references

Copyright 2009, Oracle. All rights reserved.

What Is web.xml? The web.xml deployment descriptor file follows the Servlet 2.4 specification from Sun Microsystems. The web.xml file is packaged together with the Web application components in a .war file, which is then deployed in WebLogic Server.

Oracle Fusion Middleware 11g: Build Java EE Applications 17 - 10

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

What Is weblogic.xml?
The weblogic.xml is a WebLogic Server-specific deployment descriptor for configuring: JSP properties JNDI mappings security role mappings HTTP session parameters Work managers Context root Virtual directory mappings Logging parameters Library modules

Copyright 2009, Oracle. All rights reserved.

What Is weblogic.xml? The weblogic.xml deployment descriptor follows a proprietary schema used only by WebLogic Server. It maps resources defined in the web.xml file to resources defined in WebLogic Server.

Oracle Fusion Middleware 11g: Build Java EE Applications 17 - 11

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Web Application Archive


Web archives are created using the jar utility:

Static Resources: HTML, text images Deployment Descriptors

JSP/JSF

Pages

jar

.war

Servlets, JavaBeans and other classes

Copyright 2009, Oracle. All rights reserved.

Web Application Archive The jar utility is used in many other places besides Web archives. Typically, JAR files are used as a normal means of packaging groups of classes together. The latest versions of the JDK have most of the bootstrap classes stored in JAR files. Also, applets that are downloaded over the Internet are typically stored in JAR files. The jar utility is modeled after the popular tar utility in Unix.

Oracle Fusion Middleware 11g: Build Java EE Applications 17 - 12

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Creating Web Application Archives


To create a Web Archive (WAR) file by using JDeveloper, perform the following steps: 1. Right-click the Web Project node and select New. 2. Double-click the WAR file item in the Deployment Profiles category. 3. Configure and save profile settings. 4. Right-click the Web profile and select Deploy to WAR file.

Copyright 2009, Oracle. All rights reserved.

Creating Web Application Archives The slide outlines the main steps to create a Web Archive (WAR) file on disk. The deployment profile allows you to set items to configure what components will be added to the WAR file. By default, all files located in the projects public_html directory and output directory (classes) are included in the WAR file.

Oracle Fusion Middleware 11g: Build Java EE Applications 17 - 13

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Quiz
What is the command-line interface that you can use to automate domain configuration tasks, application deployment configuration, and deployment operations in WebLogic Server? 1. weblogic.Deployer
Oracle University and Egabi Solutions use only

2. WebLogic Scripting Tool 3. jar utility

Copyright 2009, Oracle. All rights reserved.

Answer: 2

Oracle Fusion Middleware 11g: Build Java EE Applications 17 - 14

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

EJB Application Directory Structure


EJB components come packaged in JAR files. EJBs are configured by modifying deployment descriptors.

Copyright 2009, Oracle. All rights reserved.

EJB Application Directory Structure EJB are deployed in the form of a JAR archive file. As with Web applications, EJB applications must follow a specific structure and contain XML deployment descriptors. Following is an overview of the various files and folders involved: The staging directory: The staging directory is somewhere where the JAR file image is being built. This folder does not end up inside the JAR file, but instead its contents end up as the root of the JAR file. The root of the JAR file contains class files and folders that form the packages for these EJBs. META-INF: This folder contains the deployment descriptors and the utility classes and libraries: ejb-jar.xml: Standard deployment descriptor weblogic-ejb-jar.xml: WebLogic-specific deployment descriptor weblogic-cmp-rdbms-jar.xml: WebLogic-specific deployment descriptor used for object-to-relational mapping of CMP Entity EJBs. classes folder: Contains the class files for utility objects and the folders that form the packages of these classes lib folder: Contains the library files for utility objects (JAR files)

Oracle Fusion Middleware 11g: Build Java EE Applications 17 - 15

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

EJB Application Directory Structure (continued) The Java EE-specified deployment descriptor, ejb-jar.xml, describes the enterprise beans packaged in an EJB application. It defines the beans types, names, and the names of their home and remote interfaces and implementation classes. The ejb-jar.xml deployment descriptor defines security roles for the beans, and transactional behaviors for the beans methods. Additional deployment descriptors provide WebLogic-specific deployment information. A weblogic-cmp-rdbms-jar.xml deployment descriptor unique to container-managed entity beans maps a bean to tables in a database. The weblogic-ejb-jar.xml deployment descriptor supplies additional information specific to the WebLogic Server environment, such as JNDI bind names, clustering, and cache configuration.

Oracle Fusion Middleware 11g: Build Java EE Applications 17 - 16

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Java EE Enterprise Application (EAR)


Example of the directory structure of an enterprise application:

Directory/File Directory / File

Description Description
Document root of enterprise application Enterprise application deployment descriptor WLS Enterprise application deployment descriptor EJB module Another EJB module Java module Another Java module Web application module Another Web application module

Copyright 2009, Oracle. All rights reserved.

Java EE Enterprise Application (EAR) A Java EE Enterprise Application is a group of Java EE application modules, packaged into one deployable unit: an Enterprise Archive (EAR) file. The table in the slide shows a sample enterprise application directory structure An EAR file has the .ear file name extension. It contains one or more Java EE modules (EJBs, Web applications, application client modules, and resource adapters), and any resources they require. Typically, a Java EE EAR contains a Web application archive (.war) file and the resources on which it depends. The resources can be Java EE modules, such as EJB JARs, resource adapters (RARs), and others, for example, class libraries, packaged as JARs.

Oracle Fusion Middleware 11g: Build Java EE Applications 17 - 17

Oracle University and Egabi Solutions use only

META-INF directory

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Creating EJB Archives


To create an EJB JAR file by using Oracle JDeveloper, perform the following steps: 1. Right-click the EJB Model Project node and select New. 2. Double-click the EJB JAR file item in the Deployment Profiles category. 3. Configure and save profile settings. 4. Right-click the EJB-JAR profile and select Deploy to JAR/EAR file.

Copyright 2009, Oracle. All rights reserved.

Creating EJB Archives The slide shows the Oracle JDeveloper window used to initiate creation of an EJB JAR file. By default, all the components in the Model project output directory and any deployment descriptor are included in the generated EJB JAR file. You can modify the default settings in the profile file created, if required.

Oracle Fusion Middleware 11g: Build Java EE Applications 17 - 18

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Creating Enterprise Archives


To create the EAR file by Using Oracle JDeveloper:

3 4

Copyright 2009, Oracle. All rights reserved.

Creating Enterprise Archives To create the EAR file for your application in a new project by using Oracle JDeveloper, perform the following steps: 1. Right-click the Application node, select New, and then double-click EAR File in the Deployment Profiles category. 2. Enter a name for the profile file. JDeveloper uses this name as the default value for the EAR file and application name. 3. Accept or modify the EAR file and application name in General Properties. 4. Click the Application Assembly entry, and select the check boxes next to the deployment profile files in the ViewController project (for the Web components) and the Model project (for the EJB components). This step defines the modules that are included in the EAR file for deployment. If your application requires Java EEspecific and application-specific deployment descriptors and other files, such as the application.xmlfile, you should first create them in the same project so they can be selected in the Application Assembly options and added to the EAR file generated.

Oracle Fusion Middleware 11g: Build Java EE Applications 17 - 19

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Deploying Entities
Expose the persistence module in an EJB-JAR, WAR, or JAR file depending on its execution environment. Configure the persistence.xml file to define the persistence unit name and to specify the following information:
Oracle University and Egabi Solutions use only

Specify a data source. Specify the transaction type. Specify vendor-specific extensions.

Copyright 2009, Oracle. All rights reserved.

Deploying Entities Entities can execute inside the EJB or Web container, or in a Java SE application. Thus, entities can be packaged in a standard Java EE module (such as an EJB-JAR file, a WAR file, or a JAR file), which can be stored in the root of an EAR module or as a library module in an EAR file. Entities also contain a simple deployment descriptor named persistence.xml. The persistence.xml file is a persistence descriptor file that defines one or more persistence units in an EJB 3.0 application that uses entities.

Oracle Fusion Middleware 11g: Build Java EE Applications 17 - 20

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Persistence.xml File
1 <persistence> <persistence-unit name="Entity" transaction-type="JTA"> <provider> 2
org.apache.openjpa.persistence.PersistenceProviderImpl

Copyright 2009, Oracle. All rights reserved.

Persistence.xml File The slide shows the different sections of the persistence.xml file. 1. Define a persistence unit with a name and transaction type. 2. Specify an optional factory class for the persistence provider. 3. Specify the data source that the JPA provider uses to connect to the database to store retrieved entities. 4. Specify the entity classes that comprise a single persistence unit (in case you have multiple persistence units in a single archive). 5. Specify the vendor-specific configurations using the properties element.

Oracle Fusion Middleware 11g: Build Java EE Applications 17 - 21

Oracle University and Egabi Solutions use only

</provider> 3 <jta-data-source> jdbc/MyDataSource </jta-data-source> 4 <jar-file>order.jar</jar-file> <class>demo.persistence.Order</class> <class>demo.persistence.OrderDetails</class> ... 5 <properties> <property name="kodo.Log" value="DefaultLevel=WARN, Tool=INFO"/> </properties> ...

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Configuring Oracle WebLogic ServerSpecific Features


Configure enterprisewide Oracle WebLogic Serverspecific features with the weblogic-application.xml deployment descriptor: XML parsers XML entity mappings JDBC data sources JMS connection factories and destinations Security realms

Copyright 2009, Oracle. All rights reserved.

Configuring Oracle WebLogic ServerSpecific Features Application scoping refers to configuring resources for a particular enterprise application rather than for an entire WebLogic Server configuration. In the case of XML, these resources include parser, transformer, external entity, and external entity cache configuration. The main advantage of application scoping is that it isolates the resources for a given application to the application itself. Using application scoping, you can configure different parsers for different applications, store the DTDs for an application within the EAR file or exploded enterprise directory, and so on. Another advantage of using application scoping is that by associating the resources with the EAR file, you can run this EAR file on another instance of WebLogic Server without having to configure the resources for that server. To configure XML resources for a particular application, you add information to the weblogic-application.xml deployment descriptor file located in the META-INF directory of the EAR file or exploded enterprise application directory.

Oracle Fusion Middleware 11g: Build Java EE Applications 17 - 22

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Deploying with the Oracle WebLogic Server Console


Oracle WebLogic Server Control enables: Applications to be deployed from
EAR files WAR files EJB JAR files

Applications to be undeployed Applications to be redeployed Creation and editing of deployment plans during deployment

Copyright 2009, Oracle. All rights reserved.

Deploying with the Oracle WebLogic Server Console The console is a Web-based user interface for completing deployment-related tasks, including: Deploying, undeploying, and redeploying stand-alone modules (WARs, CARs, and so on) into the selected WebLogic Server instance Creating and editing reusable deployment plans Setting application-specific security and application-clustering configurations Importing shared libraries for use by the application, as well as modifying the list of inherited libraries Using the Console deployment should be your preferred method for performing deploymentrelated tasks due to the rich functionality exposed through the Web-based user interface.

Oracle Fusion Middleware 11g: Build Java EE Applications 17 - 23

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Deploying with Oracle JDeveloper


To deploy an application with JDeveloper, perform the following steps: 1. Create the deployment profile. 2. Configure the deployment profile. 3. Create an application server connection to the target environment. 4. Right-click the application and select Deploy to <application_server_connection_name>.

Copyright 2009, Oracle. All rights reserved.

Deploying with Oracle JDeveloper JDeveloper provides the ability to deploy a Java EE application into a WebLogic Server instance directly from within the project structure. It also enables a deployment plan to be created and optionally saved as an XML file.

Oracle Fusion Middleware 11g: Build Java EE Applications 17 - 24

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

What Is Ant?
Ant is:
A Java build tool similar to GNUs make utility Written in Java and is open source Developed and maintained by the Apache organization Downloadable from and documented at http://jakarta.apache.org/ant

Ant consists of built-in tasks for:


Compiling and executing Java applications Building archives File and directory manipulation

Copyright 2009, Oracle. All rights reserved.

What Is Ant? Apache Ant is a tool for automating application build processes. It is similar to make but is implemented using the Java language, requires the Java platform, and is best suited to building Java projects. GNU is a UNIX-compatible software system developed by the Free Software Foundation (FSF). The philosophy behind GNU is to produce software that is nonproprietary. Anyone can download, modify and redistribute GNU software. The make utility controls the generation of executables and other files from a program's source files. It gets knowledge of how to build your program from a file called the makefile, which lists each of the output files and how to compute it from other files. For more information about make, see the Web site at http://www.gnu.org/software/make/make.html. Ant provides functionality similar to make, but is written with, and works with, Java.

Oracle Fusion Middleware 11g: Build Java EE Applications 17 - 25

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Ant Build Files


Ant searches for a build file to determine what work should be performed. By default, Ant looks for a file named build.xml in the current directory. Example of specifying a build file other than build.xml:
ant.bat buildfile MyBuildFile.xml ant.bat buildfile /demo/BuildApplication.xml

Copyright 2009, Oracle. All rights reserved.

Ant Build Files Ant build files are written in XML. Each build file contains one project and at least one (default) target. A target will be executed only once, regardless of the number of targets that depend on it. Targets contain task elements. Each task element of the build file can have an id attribute and can later be referred to by the value supplied to this. The value has to be unique.

Oracle Fusion Middleware 11g: Build Java EE Applications 17 - 26

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

A Sample build.xml File

<?xml version="1.0" encoding="UTF-8"?> <project name="Test Project" default="run" basedir="."> <property name="sourceDir" value="source"/> <target name="compile"> <javac srcdir="${sourceDir}" destdir="classes"/> </target> <target name="run" depends="compile"> <java classname="test.MyTester"> <classpath> <pathelement path="classes"/> </classpath> </java> </target> </project>

Copyright 2009, Oracle. All rights reserved.

A Sample build.xml File The <project> element is the root element of the build file. The <project> element contains one or more <target> elements. The <target> elements contain one or more tasks. Tasks include javac and java for compiling and executing Java applications, respectively. Targets can have dependencies upon one another, similar to GNUs make. Another child element to the <project> element is the <property> element. The <property> element defines a name/value pair that can be used throughout the build file. The <project> element has three attributes, they are: name: The name of the project default: The default target to execute if one is not specified on the command line. Every project requires a default target to execute. basedir: The base directory from which all task path calculations are done The <property> element can be used to define a set of properties to be used throughout the build file. This element can also be used to have access to environment variables.

Oracle Fusion Middleware 11g: Build Java EE Applications 17 - 27

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Creating a JAR File by Using Ant Task


The jar task archives a set of files. The resulting archives can update existing ones or replace them. Use Ant if an external, scripted solution is required. Example of creating a Java archive file:
<jar jarfile="myArchive.jar" basedir="myproject/root"/> <jar jarfile="myArchive.jar" basedir="myproject/root" excludes="*.html" update="yes"/> <jar jarfile="myArchive.jar" basedir="myproject/root" compress="false"/>

Copyright 2009, Oracle. All rights reserved.

Creating a JAR File by Using Ant Task Other attributes for the jar task include: includes: A comma-delimited list of files that must be included; wildcards are acceptable includesfile: A specific file to include; wildcards are acceptable excludes: A comma-delimited list of files that must be excluded; wildcards are acceptable excludesfile: A specific file to exclude; wildcards are acceptable manifest: The manifest file to use

Oracle Fusion Middleware 11g: Build Java EE Applications 17 - 28

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Creating a WAR File by Using Ant Task


The war task archives a set of files into the appropriate J2EE Web Application format. The webxml attribute defines the file to use as the deployment descriptor, web.xml. Use the <classes> and <lib> elements to define the applications class files. Example of creating a Web archive file:
<war warfile="myWebApp.war" basedir="myproject/root" webxml="myproject/myWebApp.xml"> <lib dir="myproject/libraries"/> <classes dir="myproject/classes"/> </war>

Copyright 2009, Oracle. All rights reserved.

Creating a WAR File by Using Ant Task All files included in the <lib> elements are found in the WEB-INF/lib directory of the archive. All files included in the <classes> elements are found in the WEB-INF/classes directory of the archive. The file given as the deployment descriptor is found in the WEB-INF directory of the archive.

Oracle Fusion Middleware 11g: Build Java EE Applications 17 - 29

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Creating an EAR File by Using Ant Task


The ear task archives a set of files into the appropriate Java EE Enterprise Application format. The appxml attribute defines the file to use as the deployment descriptor, application.xml. Example of creating an Enterprise archive file:
<ear earfile="myApp.ear" basedir="myproject/root" appxml="myproject/myApp.xml" includes="*.jar,*.war"/>

Copyright 2009, Oracle. All rights reserved.

Oracle Fusion Middleware 11g: Build Java EE Applications 17 - 30

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Deploying an Application by Using Ant Task


The wldeploy task deploys an archive (EAR, WAR, and so on) to one or more servers. The source attribute defines the archive to deploy. The adminurl attribute defines the URL of the Admin Server. The targets attribute defines the server to which the archive is deployed. Example of deploying a Web Archive (WAR):
<wldeploy source="myApp.war" name=MyApp" user="x" password="y" adminurl="t3://localhost:7001" targets="adminserver" />

Copyright 2009, Oracle. All rights reserved.

Deploying an Application by Using Ant Task The userconfigfile attribute can be used in place of the user, password attributes. It specifies the location of a user configuration file. The targets attribute can be set to a comma-separated list of targeted server and/or cluster names. JDeveloper performs an autodeploy of code that is being developed using the IDE. While this feature is very useful in a development environment, it is not recommended for production. In a typical enterprise level production environment, deployment is scripted. Several solutions exist for deployment using scripts, such as leveraging the weblogic.Admin command line tool, WLST and Ant.

Oracle Fusion Middleware 11g: Build Java EE Applications 17 - 31

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Packaging Best Practices for Production Environments


No duplicate JAR files in EARs JAR files that are supplied by the system or WebLogic classpath should not be included in the EAR Ensure all EAR files include a weblogicapplication.xml descriptor Ensure all WAR files include a weblogic.xml descriptor Ensure all EJB files include a weblogic-ejb-jar.xml descriptor Test artifacts must not be included in the EAR

Copyright 2009, Oracle. All rights reserved.

Packaging Best Practices for Production Environments Packaging applications for deployment onto production servers is an integral part of Java EE projects. When deploying applications onto production environments, security, performance, and operational agility are overriding concerns. WebLogic administrators need to be able to deploy applications quickly and with minimal manual intervention. Note: For both production and development purposes, you should package and deploy your stand-alone Web applications, EJBs, and resource adapters as part of an Enterprise application. This practice allows for easier application migration, additions, and changes. For example, to add more than one Web application, EJB, or resource adapter module to an application, you must package the modules in an Enterprise application. The following is a list of application packaging best practices: JAR files placed in APP-INF/lib will be visible to Web applications. Therefore, no JAR file should exist in both APP-INF/lib and WEB-INF/lib. This increases the size of the deliverable, increases deployment times, and risks creating class-loading problems and deployment failures. Including JAR files that are on the system or WebLogic classpath in applications can cause class-loading issues if the JAR files on these class loaders are upgraded by the infrastructure team. Therefore, avoid adding JAR files that are supplied by the system or WebLogic classpath in the achieve. Applications that use WebLogic extensions must include a weblogicapplication.xml descriptor. All test artifacts should be removed from deployable packages, for example the JUnit family of JAR files and the test cases that use them
Oracle Fusion Middleware 11g: Build Java EE Applications 17 - 32

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Summary
In this lesson, you should have learned how to: Deploy Java EE applications to the WebLogic server environment Deploy applications by using the:
Oracle University and Egabi Solutions use only

Console Deployment Command-line Deployment Deployment by using JDeveloper

Copyright 2009, Oracle. All rights reserved.

Oracle Fusion Middleware 11g: Build Java EE Applications 17 - 33

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Troubleshooting

Oracle University and Egabi Solutions use only

Copyright 2009, Oracle. All rights reserved.

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Objectives
After completing this lesson, you should be able to do the following: Use JDeveloper and tools for logging and diagnostics Test a business service in isolation from views or controllers Make use of FileMon, JUnit, and HTTP Analyzer

Copyright 2009, Oracle. All rights reserved.

Objectives As much as we like to think of our first-cut application as flawless, there are times when we need to fix problems. In this lesson, you learn how to identify problems in Java EE applications and to create simple test harnesses to reproduce the error. You learn about the various tools that are available to help you troubleshoot.

Oracle Fusion Middleware 11g: Build Java EE Applications 18 - 2

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Troubleshooting Basics
Diagnose the problem. Request help. Create a test case.

Copyright 2009, Oracle. All rights reserved.

Troubleshooting Basics The following slides examine each of the steps mentioned in the slide in detail.

Oracle Fusion Middleware 11g: Build Java EE Applications 18 - 3

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Diagnosing the Problem


Find out where it occurs:
Test the database query and the business services layer. Read any exceptions and stack traces. Set breakpoints in the custom code.
Oracle University and Egabi Solutions use only

Examine logs and diagnostic output. Strip away complexity. Search for similar problems: Google, WebIV, bug.

Copyright 2009, Oracle. All rights reserved.

Diagnosing the Problem The first step in diagnosing a problem is usually to find out where it occurs. Exceptions can give valuable information. For example, a SQL exception would indicate that the problem is at the database level, so the next step might be to test your database connections and run your queries in the SQL worksheet. Testing the business services layer without a client can pinpoint or eliminate the business services as the cause of the problem. Logs and diagnostics output can also give clues. Stripping away complexity involves removing as many components and as much custom code as possible. Lastly, many common problems have been documented in blogs, on Oracle Technology Network (OTN), in WebIV, or elsewhere. Try to Google for your problem, or search WebIV notes, or the bug database. If you are unable to fix the problem, the information you have gathered is useful when asking for help. The following slides discuss what information to provide when requesting for help with a problem.

Oracle Fusion Middleware 11g: Build Java EE Applications 18 - 4

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Requesting Help
Post a topic on the JDeveloper OTN Forum: Describe exact steps to reproduce the problem. Include a test case, if possible. List technologies and product version numbers. Provide concrete examples rather than abstract descriptions. Include a stack trace, if appropriate. Mention troubleshooting steps you have tried and how they affected the problem.

Copyright 2009, Oracle. All rights reserved.

Requesting Help If you post a topic on the JDeveloper OTN Forum, try to include as much relevant information as possible. You are not expected to include all the information listed for every problem; include what is appropriate. Provide concrete examples in your post rather than abstract descriptions. For example, you might start a topic as follows: My page contains an input form for editing customer information. Each customer can have one or more phone numbers. This is easier for the person looking at the problem to understand than an abstract description, such as My page contains an input form for editing an object, one of whose attributes can have one or more values.

Oracle Fusion Middleware 11g: Build Java EE Applications 18 - 5

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Creating Test Cases


Create the simplest possible application that reproduces the problem: Database schema: Use a standard schema, if possible. Business service: Remove components and customization. Client: Try creating a sample client to test every component of the application.

Copyright 2009, Oracle. All rights reserved.

Creating Test Cases A test case is a simple application that reproduces the problem. If the problem is simple enough, you can describe the steps to reproduce the problem. A test case is almost always worth the time it takes to create; it saves time later in examining the problem, diagnosing the problem, and testing a fix. When creating a simple test case, keep the following guidelines in mind: Simplify the database schema. Use one of the standard schemas, if possible (hr or the old emp/dept are the simplest ones). Otherwise, create a table with a few rows and columns. For example, if the problem is with a TIMESTAMP data type, try a table with one TIMESTAMP column and one primary key column. Include as few business service components as possible and include only the custom code that is necessary to reproduce the problem. If you believe the problem is in the business service layer, try reproducing it with a sample Java client. If the problem reproduces only with a client, try the simplest possible client. For example, a JSF page with a single outputText and a button.

Oracle Fusion Middleware 11g: Build Java EE Applications 18 - 6

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Java Logging
It is useful for tracing EL evaluation in JavaServer Faces (com.sun.faces). Many Java programs use the Java Logging API to produce useful messages. You can configure Java logging to produce different levels of logging output:
SEVERE WARNING INFO CONFIG FINE FINER FINEST ALL NONE

Copyright 2009, Oracle. All rights reserved.

Java Logging The Logging API is part of Java Platform, Standard Edition (Java SE) in JDK 1.4 and later versions, and it ships with the JDK. It is designed to let a Java program produce messages of interest to end users, system administrators, and software developers. It is useful in production environments where you cannot run the debugger, or where running the debugger might hide the problem. For example, timing-related problems often cannot be reproduced when running the application in the debugger. Java logging has several predefined levels: SEVERE: Extremely important messages such as fatal errors WARNING: Warning messages INFO: Informational run-time messages CONFIG: Informational messages about configuration settings FINE: Used for greater detail when diagnosing problems FINER: Even greater detail FINEST: Greatest detail There are two other values: ALL (log all messages) and NONE (no messages).

Oracle Fusion Middleware 11g: Build Java EE Applications 18 - 7

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Configuring Java Logging


Configure logging in <jdk_path>\jre\lib\logging.properties. Useful settings:
Where to send the output. For example:
Oracle University and Egabi Solutions use only

handlers= java.util.logging.ConsoleHandler Logging level for different packages. For example: com.sun.faces.el.level = FINE Level of messages to a particular output. For example: java.util.logging.ConsoleHandler.level = INFO

Copyright 2009, Oracle. All rights reserved.

Configuring Java Logging The default logging configuration file is <jdk_path>\jdk\jre\lib\logging.properties, where <jdk_path> is the path of the JDK you are using to run your application. If you are running your application in JDeveloper, the logging configuration file is <jdev_home>\jdk\jre\lib\logging.properties. The slide shows the most useful settings in logging.properties. You need to include all the packages for which you want to produce output; you can set different logging levels for different packages. You can also use levels to restrict the amount of output sent to the console. For example, send messages of level FINE and above to a file, but only output messages of level INFO and above to the console.

Oracle Fusion Middleware 11g: Build Java EE Applications 18 - 8

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Sending Logger Output to a File


Set handlers to FileHandler. For example, send output to the console and to a file:
handlers= java.util.logging.ConsoleHandler, java.util.logging.FileHandler

The log output file is created in your user.home directory. File name is java<n>.log (java0.log, java1.log, and so on).

Copyright 2009, Oracle. All rights reserved.

Sending Logger Output to a File By default, the log output file is created in your user.home directory; you can change the name and location of the file in logging.properties. You can find the value of user.home by writing a simple Java class that prints out the value of user.home as follows: System.out.println(System.getProperty("user.home"));

Oracle Fusion Middleware 11g: Build Java EE Applications 18 - 9

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Turning on Diagnostics in JDeveloper

Copyright 2009, Oracle. All rights reserved.

Turning on Diagnostics in JDeveloper To turn on diagnostics, double-click the project to edit the project properties. Select Run/Debug/Profile, and then select a run configuration and click Edit to edit it, or create a new one. The Java option for turning on diagnostics is Djbo.debugoutput=<output_type>. When running diagnostics in JDeveloper, the most common value for <output_type> is console. Following is the complete list of possible values: silent: No diagnostic output (this is the default) console: Diagnostic information printed in JDevelopers log window file: Information written to a file. The name of the file is output to JDevelopers log window; there is no option to specify the file name. You can create more than one run configuration. This makes it easier to turn the options on or off in JDeveloperyou create one configuration with the options you want, one without, and switch between them.

Oracle Fusion Middleware 11g: Build Java EE Applications 18 - 10

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Sample Java Clients


Sample Java clients are useful for testing your business service. You can quickly create a sample client for a Web service from the Applications Navigator context menu. The client is a generated Java class with code to test your service. Client code is not automatically synchronized with changes to your service. You must create a new sample client when you make changes.

Copyright 2009, Oracle. All rights reserved.

Sample Java Clients Sample clients contain basic code to test a Web service. Note that sample Java clients (also known as Web service proxies) are not automatically updated to match your service. If you make any changes to the Web service, you must create another proxy.

Oracle Fusion Middleware 11g: Build Java EE Applications 18 - 11

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Sample Client for Web Service


The sample client initializes a proxy to the Web service. You add custom code to call the Web service operations.
ws.SimpleWebServiceSoapHttpPortClient myPort = new ws.SimpleWebServiceSoapHttpPortClient(); System.out.println("calling " + myPort.getEndpoint()); // Add your own code here System.out.println(myPort.sampleMethod("hello"));

To create a sample client, select Generate Web Service Proxy in the shortcut menu.

Copyright 2009, Oracle. All rights reserved.

Sample Client for Web Service The sample Java client for a Web service initializes a proxy to the Web service, exposing the Web service operations as methods on the proxy. You then need to add code to invoke the Web service by using the methods exposed on the proxy. The client contains a comment ("// Add your own code here") indicating where to add your code. The example in the slide is from a sample client for a Web service called SimpleWebService with an operation called sampleMethod. The custom code calls sampleMethod and prints the result. To create a sample client for a Web service, right-click the Web service (.wsdl file) in the Applications Navigator and select Generate Web Service Proxy from the shortcut menu. This launches the Create Web Service Proxy Wizard. In the Port Endpoints dialog box, select the options for connecting to a remote application server and click OK. Then follow the instructions for the Wizard to create the proxy.

Oracle Fusion Middleware 11g: Build Java EE Applications 18 - 12

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Tools and Utilities


FileMon JUnit HTTP Analyzer JDeveloper Debugger
Oracle University and Egabi Solutions use only

Copyright 2009, Oracle. All rights reserved.

Oracle Fusion Middleware 11g: Build Java EE Applications 18 - 13

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Identifying Search Paths with FileMon


Useful for troubleshooting CLASSPATH problems Shows you the path that your running application is looking in for classes and files

Copyright 2009, Oracle. All rights reserved.

Identifying Search Paths with FileMon FileMon is a free utility that you can download from http://www.sysinternals.com. Its purpose is to show where a running application searches for the files that it needs, so it is useful for resolving problems with CLASSPATH settings. To use FileMon: Run filemon.exe. Set a filter for the file type in which you are interested. FileMon produces a lot of output; you probably want to set a filter to restrict the output to a more readable size. To set a filter, click the Filter button in the FileMon toolbar. If desired, save the output to a log file.

Oracle Fusion Middleware 11g: Build Java EE Applications 18 - 14

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Testing Java Code with JUnit


JUnit is an open-source regression testing framework. It is useful for creating tests to verify Java code. JDevelopers JUnit extension provides wizards for creating test components. More information and examples:
JDeveloper online documentation http://www.junit.org

Copyright 2009, Oracle. All rights reserved.

Testing Java Code with JUnit JUnit is an open-source regression testing framework (see http://www.junit.org). JUnit is more of a testing tool than a troubleshooting tool, but if you are developing an application of any complexity, it could be useful to create a suite of JUnit tests to quickly verify your Java code. JDevelopers integrated support for running JUnit tests means that any developer on the team can run a test suite with a single click, greatly increasing the chances that team members run tests to verify changes they make to the system during development and testing. JDeveloper provides two JUnit extensions: JUnit integration and JUnit integration for business components. You can install these extensions from Tools > Preferences > Extensions; click Check for Updates.

Oracle Fusion Middleware 11g: Build Java EE Applications 18 - 15

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Analyzing HTTP Requests


The HTTP Analyzer: Shows the content of HTTP request and response packets Is useful for monitoring Web services

Copyright 2009, Oracle. All rights reserved.

Analyzing HTTP Requests The HTTP Analyzer (previously called the TCP-IP packet monitor) enables you to view the content of the HTTP request and response packets. It is useful for verifying the data sent and received by a Web service. To open the HTTP Analyzer, select Tools > HTTP Analyzer from the JDeveloper main menu. You can then run a Web service and view request and response data. For more information about running the HTTP Analyzer, see the JDeveloper online documentation. Another analyzer is available from http://www.ethereal.com.

Oracle Fusion Middleware 11g: Build Java EE Applications 18 - 16

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Debugging with JDeveloper


JDeveloper Debugger is 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 a breakpoint is encountered at run time, you can step through code and view values of variables. To run a file in debug mode, right-click and select Debug.

Copyright 2009, Oracle. All rights reserved.

Debugging with JDeveloper Like any debugging task, debugging Web applications does not involve compiling Java source code. In fact, you may not realize that a problem exists until you run and attempt to use the application. Many errors arise from the interaction between the Web pages components and the Model layer of the application. Fortunately most of these are simple, easy-to-fix errors in the declarative information that the application defines. If the error cannot be easily identified, you can use the debugging tools in JDeveloper to step through the execution of the application. This process helps you to isolate exactly where the error occurred. The debugging tools enable you to pause execution of the application on specific methods, examine the data, and compare it with what you expect the data to be. You can debug any code for the current project in the same way as you would for your own Java code.

Oracle Fusion Middleware 11g: Build Java EE Applications 18 - 17

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Summary
In this lesson, you should have learned how to: Diagnose problems, request help, and create test cases to solve a problem in your application Create sample clients to eliminate client issues Use FileMon, JUnit, HTTP Analyzer, and JDeveloper Debugger to track down a problem

Copyright 2009, Oracle. All rights reserved.

Summary The first step in diagnosing a problem is usually to find out where it occurs. Exceptions can give valuable information. When you document a problem, do not include all the information listed for every problem; include what is appropriate. Use a test case to reproduce the problem. If the problem is simple enough, you can describe the steps to reproduce the problem. A test case is almost always worth the time it takes to create; it saves time later in examining the problem, diagnosing the problem, and testing a fix. Java logging is useful in production environments where you cannot run the debugger, or where running the debugger might hide the problem. Creating a sample client is a good way to isolate the client code from the business service code. JDeveloper Debugger and the JUnit extension are two tools to use to isolate a problem.

Oracle Fusion Middleware 11g: Build Java EE Applications 18 - 18

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Appendix A Practices and Solutions

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Table of Contents
Practices for Lesson 1 ......................................................................................................... 4 Practices for Lesson 2 ......................................................................................................... 5 Practice 2-1: Creating JDeveloper Connections ............................................................. 6 Practice 2-2: Browsing the FOD Schema Data............................................................... 8 Practices for Lesson 3 ......................................................................................................... 9 Practice 3-1: Run the EJB/JSF Application .................................................................. 10 Practice 3-2: Exploring the Model Project.................................................................... 11 Practice 3-3: Exploring the UI Project.......................................................................... 12 Practices for Lesson 4 ....................................................................................................... 14 Practice 4-1: Developing a Simple Servlet Application ............................................... 15 Practice 4-2: Developing a Servlet Application to Access a Database......................... 17 Practices for Lesson 5 ....................................................................................................... 21 Practice 5-1: Developing a Simple JSP Application..................................................... 22 Practice 5-2: Developing a JSP Application Using a JavaBean ................................... 27 Practice 5-3: Developing a JSP Application Using Custom Tags and Expression Language....................................................................................................................... 32 Practices for Lesson 6 ....................................................................................................... 35 Practice 6-1: Accessing Database Connectivity in a Servlet Application by Implementing Dependency Injection (DI) .................................................................... 36 Practice 6-2: Injecting an Enterprise Java Bean by Implementing DI......................... 38 Practices for Lesson 7 ....................................................................................................... 40 Practice 7-1: Creating a Stateless Session Bean ........................................................... 41 Practice 7-2: Creating a Sample Test Java Client for the CreditCardValidator Stateless Session Bean .................................................................................................. 43 Practice 7-3: Calling a Stateless Session Bean in a Stateful Session Bean .................. 45 Practice 7-4: Creating a Sample Test Java Client for the ShoppingCart Stateful Session Bean ................................................................................................................. 48 Practice 7-5: Using Interceptors in the ShoppingCart Session Bean............................ 50 Practices for Lesson 8 ....................................................................................................... 53 Practice 8-1: Coding a Simple Entity Bean .................................................................. 54 Practice 8-2: Using the JDeveloper Entity Bean Wizard.............................................. 58 Practice 8-3: Customizing Entity Beans ....................................................................... 59 Practice 8-4: Creating and Testing a Session EJB ........................................................ 62 Practices for Lesson 9 ....................................................................................................... 64 Practice 9-1: Adding Named Queries to Person ........................................................... 65 Practice 9-2: Adding Named Queries to Product.......................................................... 67 Practice 9-3: Adding Named Queries to Category ....................................................... 69 Practices for Lesson 10 ..................................................................................................... 71 Practice 10-1: Creating the ValidateCreditCardService Web Service by Using the Top-Down Web Service Development Approach ........................................................ 72 Practice 10-2: Testing the Web Service by using JDeveloper...................................... 77 Practices for Lesson 11 ..................................................................................................... 78 Practice 11-1: Creating the ProductBrowsing Managed Bean ..................................... 79 Practice 11-2: Creating a JSF Page............................................................................... 83

Oracle Fusion Middleware 11g: Build Java EE Applications A - 2

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Oracle Fusion Middleware 11g: Build Java EE Applications A - 3

Oracle University and Egabi Solutions use only

Practice 11-3: Adding Products to the Page ................................................................. 85 Practices for Lesson 12 ..................................................................................................... 89 Practice 12-1: Creating the Edit and Add Pages........................................................... 90 Practice 12-2: Building the AddProduct Page .............................................................. 92 Practice 12-3: Creating the Add Product Functionality................................................ 94 Practices for Lesson 13 ..................................................................................................... 98 Practice 13-1: Adding the Category Tree Selection Event ........................................... 99 Practice 13-2: Complete and Connect the Edit Product Page..................................... 103 Practices for Lesson 14 ................................................................................................... 106 Practice 14-1: Creating a JMS Connection Factory and Queue Destination in WebLogic Server ........................................................................................................ 107 Practice 14-2: Creating a Message-Driven Bean to Send Emails............................... 109 Practice 14-3: Creating a Session Method for Sending Email Messages ................... 112 Practice 14-4: Creating a Sample Test Client in JDeveloper...................................... 115 Practice 14-5: Testing the Confirmation Email .......................................................... 117 Practices for Lesson 15 ................................................................................................... 118 Practice 15-1: Working with Container-Managed Transactions ................................ 119 Practice 15-2: Working with EJB Client's Transactional Context.............................. 121 Practices for Lesson 16 ................................................................................................... 126 Practice 16-1: Enabling Form-based Login Authentication ....................................... 127 Practice 16-2: Creating Security Roles and URL Constraints in the Deployment Descriptors .................................................................................................................. 128 Practice 16-3: Creating the Users and Groups in WebLogic Server .......................... 132 Practice 16-4: Testing the Security Implementation................................................... 134

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

There is no practice for this lesson.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 4

Practices for Lesson 1

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practices for Lesson 2


The aim of the practices for this lesson is to explore and configure basic components in the course development environment. You perform the following set of tasks in this practice set: Creating JDeveloper connections for the FOD database schema Examining some of the seeded data in the FOD schema tables

Oracle Fusion Middleware 11g: Build Java EE Applications A - 5

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 2-1: Creating JDeveloper Connections


1) Start Oracle JDeveloper:

In this practice, you launch Oracle JDeveloper and create connections for it to the database and application server. a) Click Start > Programs > Oracle Fusion Middleware > JDeveloper Studio. b) In the Select Role dialog box, select Default Role, deselect Always prompt for role, and click OK. c) When JDeveloper starts, you may receive a message to migrate from a previous version of the product. Click No. e) In the Tips of the Day window, deselect the Show tips at startup option and click Close. 2) Create a database connection (FOD) that connects to the Oracle XE Database instance. General IDE level connections are created in the Database Navigator. a) Open the DatabaseNavigator page by selecting View > Database Navigator. b) Right-click IDE Connections and select New Connection.

c) Use the following connection details or use the screenshot as a visual guide: Step i. ii. Screen/Page Description Step 1 of 4: Type Step 2 of 4: Authentication Choices or Values Connection Name: fod Connection Type: Oracle (JDBC) Username: fod Password: fusion Select the Save Password check box. Select the Deploy Password check box. Driver: thin Host Name: localhost JDBC Port: 1521 SID: XE Click Test Connection to check whether the connection is successfully established. If the status is Success, click OK.

iii.

Step 3 of 4: Connection

iv.

Step 4 of 4: Test

Oracle Fusion Middleware 11g: Build Java EE Applications A - 6

Oracle University and Egabi Solutions use only

d) If the Configure File Type Associations window is displayed, click OK.

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 2-1: Creating JDeveloper Connections (continued)

Oracle Fusion Middleware 11g: Build Java EE Applications A - 7

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 2-2: Browsing the FOD Schema Data


In this practice, you use JDeveloper to browse a database schema object by using the database connection created in practice 2-1. You examine some of the FOD schema table structures and their data. 1) On the Database Navigator tabbed page, expand IDE Connections > fod database connection and locate and examine the structure of the PERSONS table in the FOD schema. a) In the Connections pane, click and expand the fod connection. Note: Expand the Database node, if necessary.

c) Expand the Tables node. d) Double-click the PERSONS table entry. JDeveloper opens a window showing the table definition in the Structure pane. 2) Examine the data stored in the PERSONS table. a) Click the Data subtab at the bottom of the PERSONS tabbed page. b) Approximately 50 rows of data should be present. The email address is used by the course application as the user ID for login purposes. 3) Optionally, examine the data in other tables, such as CATEGORIES and PRODUCTS. Note: Use the technique described in step 2 of this practice section. You can insert, update, and delete data in the Data tabbed page. Alternatively, right-click the fod connection and select SQL Worksheet. By using the SQL Worksheet, you can enter SQL statements to query and manipulate the data. 4) Close all open database table tabbed pages. Note: Select each tabbed page and click File > Close, or click the Close icon next to the name on the tab.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 8

Oracle University and Egabi Solutions use only

b) The FOD schema name should appear. Click the expand icon to expose the nodes for the different types of database objects.

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practices for Lesson 3


During this course, you create several small applications that demonstrate a number of Java EE development techniques. One of the applications that you will build is an MVC application based on an EJB model with a Session Faade and a JSF user interface. In this practice, you run, and then explore a pre-built application as a sample of the application you will build in later lessons.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 9

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 3-1: Run the EJB/JSF Application


1) Open Application_03.jws.

In this practice, you run the application and explore how each part works. a) In the Application Navigator, select Open Application. b) Navigate to D:/labs/labs/Application_03 folder. c) Double-click Application03.jws. 2) Expand UI in the Application Navigator. 3) Expand Web Content.

5) On the running Main page, expand one of the categories in the category tree and select one of the subcategories. 6) Notice how the products that belong to that category are displayed in the products table. 7) Select other categories to see the products table change. 8) Add a product of your own by using the Add Product button at the upper-right corner of the Main page. a) Click Add a Product. b) Notice that there are field level hints for each of the fields on the page. c) Try to enter a Name that is less than five characters. There is a validator on the field that requires at least five characters for the name. Notice the error, then enter a name with at least five characters. d) Enter values in all the fields and click Save. e) Notice that your product is added to the currently selected category. 9) Edit your product. a) Click the product name of the product you just added. b) On the Edit page, change any or all of the values and click Save. c) Notice that the changes you made are reflected in the products table. 10) Close the browser after you finish exploring the application.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 10

Oracle University and Egabi Solutions use only

4) Right-click Main.jspx and select Run from the Context Menu. This action deploys and starts the Weblogic server, deploys the Model and UI projects, and runs the Main page.

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 3-2: Exploring the Model Project


1) Expand Model in the Application Navigator. 2) Expand Application Sources.

In this practice, you explore the Model project in the application.

3) Notice the two packages, oracle.model and oracle.services. The model package contains the entity beans for the project while the services project contains the session beans. 4) Expand oracle.model. 6) Double-click Category.java to see the code in the source editor. 7) Notice that there are three Named Queries. These queries are written specifically to support parts of the application that you will be building. For example, the Category.findRoot query returns only those categories where there is no parentthat is, the Root categories. It excludes any category that has a parent. This query is used in building the category tree component that you saw in the application that is running. 8) While you are in this package, explore the other entity beans to see what queries or methods they contain. 9) Expand the oracle.services package. 10) Notice that there are three items in the package: SessionEJBBean.java is the session bean, and SessionEJB.java and SessionEJBLocal.java are the remote and local interfaces to the session bean, respectively. 11) Open SesssionEJBBean.java. 12) Notice that there are methods that expose each of the Named Queries defined in the entity beans. These methods publish access to those queries through the local and remote interfaces. 13) When you are done, close the files. 5) Notice that there are three entity beans: Category, Person, and Product.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 11

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 3-3: Exploring the UI Project


1) Expand UI in the Application Navigator. 2) Expand WEB-INF. 3) Open faces-config.xml.

In this practice, you explore the UI project and its components.

4) The file opens with the visual editor. The Diagram of the application should be displayed, if not, click the Diagram tab at the bottom of the editor. 5) Notice that there are three pages: Main.jspx, EditProduct.jspx, and AddProduct.jspx. 6) Between the pages are Navigation cases, which control which page can call or navigate to which page. Buttons or links on the pages use these Navigation cases. 7) Double-click Main.jspx. 8) Notice that there are two areas on the page: one that displays Categories and the other that displays Products. These areas are coordinated through an event. When the user clicks a new category, the event fires and refreshes the Products table with the related products. 9) Notice that the Structure window shows the structure of the entire page. 10) In the Visual Editor, click in the categories tree. Note that the Structure window reflects what item you selected. 11) Find and click af:tree categoryTree in the Structure window, if it is not selected. 12) Expand the Behavior node in the Properties Inspector. If you cannot find the Properties Inspector, open it from the Menu View > Property Inspector or press and hold Ctrl + Shift + I. 13) Note that the Selection Listener property points to a method in productBrowsingBean. This method traps the selection event and sets a variable to hold the current selected category. This is the first part of coordinating the category tree and the Products table. This application uses this managed bean to hold values and methods required for this application. 14) Click productsTable. 15) In the Properties Inspector, expand Behavior and notice the PartialTriggers property. This is set to ::categoryTree so that if there is a change in the category tree (such as a user selecting a new category), the product table refreshes itself. This is the other part of the coordination mechanism. 16) Expand the Application Sources > oracle.ui.backing package. 17) Open ProductBrowsingBean.java.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 12

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 3-3: Exploring the UI Project (continued)

18) Explore this class. Note that there are a number of set and get methods. Most of those correspond to the components you add to the three pages. These are added automatically in some cases, which you will see later. 19) Examine the code in getProductsForSelectedCategory(). You can use the search or the Structure window to find the method. Notice that it uses selectedCategory, which is set in the category selection event that you just explored. This method retrieves and returns productList for the selected category. 20) Go back to Main.jspx. 21) Select productsTable.
#{productBrowsingBean.productsForSelectedCategory}. This value is

the result of the method you just examined. When this table needs to be refreshed, it calls getProductsForSelectedCategory and displays the results. 23) Explore any part of the application that you want. 24) When you are done, close the application. You can also remove the application from the IDE if you choose.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 13

Oracle University and Egabi Solutions use only

22) Notice that the value in Property Inspector is

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practices for Lesson 4


The aim of the practices for this lesson is to develop a servlet application. You learn to develop a simple servlet application by using Oracle JDeveloper 11g integrated development environment (IDE), and execute it from a Web browser. Afterwards, you modify a login HTML form that accepts a username and password, and makes a call to the servlet application. The servlet application extracts the user credentials from the HTML form and validates it against a database table. Following are the tasks that you need to perform for this practice set: Develop a simple servlet application in JDeveloper 11g. Test the servlet in a Web browser. Modify a login HTML form to access the servlet. Modify the servlet application to extract the user credentials, connect to a database table, and validate the user.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 14

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 4-1: Developing a Simple Servlet Application

In this practice, you develop a servlet application by using JDeveloper 11g. 1) In JDeveloper, open Application_04.jws. Note: This opens a skeleton application, the Servlets project, for the servlet application components. a) In JDeveloper, select File > Open. b) In the Open window, open the Application_04 directory. c) Double-click the Application_04.jws file. 2) Create an HTTP servlet called LoginValidatorServlet in the Servlets project. Use the following details to accomplish this task: Step Screen/Page Description a. Application Navigator b. New Gallery Choices or Values Right-click Servlets. Select New. Categories: Web Tier > Servlets Items: HTTP Servlet Click OK. Click Next. Class: LoginServlet Package: oracle.servlets Generate Content Type: HTML Implement Methods: Select the doGet() option. Select the doPost() option. Click Next. Name: LoginServlet URL Pattern: /loginservlet Click Next. Click Finish.

c. d.

Create HTTP Servlet: Welcome Create HTTP Servlet - Step 1 of 3

e.

Create HTTP Servlet - Step 2 of 3 Create HTTP Servlet - Step 3 of 3

f.

3) Analyze the code in the doGet() and doPost() methods in the LoginServlet servlet class. 4) Compile the servlet class. In the Application Navigator pane of JDeveloper, right-click LoginServlet.java and select the Make option from the shortcut menu. Check the Message log to verify the successful compilation of the application.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 15

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 4-1: Developing a Simple Servlet Application (continued)

5) Test the servlet application. In the Application Navigator pane, right-click LoginServlet.java and select the Run option from the shortcut menu. Verify the output of the servlet application in the Web browser.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 16

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 4-2: Developing a Servlet Application to Access a Database


1) Modify an HTML form for logging in to an application.

In this practice, you develop a login validation application by using the HTML form and HTTP servlet. a) Expand the Servlets project and the Web Content folder. Open the Login.html file in the code editor by double-clicking the file. There is one text field and one password field in this form. (You can switch between the visual and code views using the Design and Source tabs.) The text areas have labels, but no names. b) Select each input item and using the Property Inspector, set the Name and Value properties to user_name and user_password, respectively. These are the values that you pass to the request object and, therefore, it is important to follow standard naming conventions so that you can refer to the value later. To view the Property Inspector, if not available, select View > Property Inspector. c) Modify the form so that the action tag points to LoginServlet. In the Structure window, select the form node. In the Property Inspector pane, set the Action property to /loginservlet. d) Save the Login.html file. 2) Modify the HTTP servlet to handle the login. Add the following additional code in the LoginServlet.java file. a) Import the java.sql package and declare the following variables (in bold) with their respective values:
... import java.sql.*; ... public class LoginServlet extends HttpServlet { private static final String CONTENT_TYPE = "text/html; charset=windows-1252"; private static final String DB_URL = "jdbc:oracle:thin:@localhost:1521:XE"; private static final String DB_USERNAME = "fod"; private static final String DB_PASSWORD = "fusion"; private static Connection con; private String pass; private String name; ...

b) Define and implement the configureConnection() method to create a JDBC connection to the database.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 17

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 4-2: Developing a Servlet Application to Access a Database (continued)


... public void configureConnection() throws SQLException { try{ Class.forName("oracle.jdbc.OracleDriver"); con = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD); con.setAutoCommit(true); } catch (Exception e){ System.out.println("Connection failed: " +e.toString()); } } ...

c) Define and implement the getConnection() method to retrieve the JDBC connection.
... public Connection getConnection() throws SQLException { configureConnection(); return con; }
...

d) Define and implement the verifyPassword() method to validate the users credentials.
... protected boolean verifyPassword(String theuser, String password) { String originalPassword=null; try { con=getConnection(); Statement stmt= con.createStatement(); stmt.executeQuery("select password from login where uname='"+theuser+"'"); ResultSet rs = stmt.getResultSet(); if(rs.next()) { originalPassword=rs.getString(1); } stmt.close();

Oracle Fusion Middleware 11g: Build Java EE Applications A - 18

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 4-2: Developing a Servlet Application to Access a Database (continued)


if(originalPassword.equals(password)) { return true; } else { return false; } } catch (Exception e){ System.out.println("Exception in verifyPassword()="+e.toString()); return false; } } ...

e) Add the code to the doPost() method to retrieve the user_name parameter from the request object. Remember that the value being passed is the parameter that you specified in step 1.b, (not User Name). The code extracts the user credentials from the HTML form, validates the user, and prints appropriate messages in HTML. Note that the out.println statements replace the default messages in the doPost method.
... public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ response.setContentType(CONTENT_TYPE); PrintWriter out = response.getWriter(); name = request.getParameter("user_name"); pass = request.getParameter("user_password"); boolean result = verifyPassword(name, pass); out.println ("<html>"); out.println ("<body>"); if (result == true){ out.println ("Hello " + name + ": Your login module is working great!"); } else{ out.println ("Invalid user name or password"); } out.println ("</body></html>"); out.close(); } ...

Oracle Fusion Middleware 11g: Build Java EE Applications A - 19

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 4-2: Developing a Servlet Application to Access a Database (continued)


f) Right-click LoginServlet.java and select Make to compile the class. 3) Run Login.html to test the functionality. a) Right-click Login.html and select Run. b) Enter the username as sking and password as oracle, and then click Login. 4) When you are done, close the browser and close Application_04. You can also remove it from the IDE if you want.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 20

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practices for Lesson 5


In Web-based applications, it is common that data from one page is used on others. There are several ways to exchange data between pages. One way is to use explicit objects such as the JSP Session object. You can also use a JavaBean to store data, as well as execute business logic and data validation. With JSPs, you can also create custom tags that perform specific formatting or logic that you may use across applications. In this practice, you create a JavaServer Page that pass values using Session variables. You also use a JavaBean to execute some business logic. In the last section of this practice, you create several custom tags to perform special formatting for your page.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 21

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 5-1: Developing a Simple JSP Application

In this practice, you create a JavaServer Pages (JSP) application that interacts with two other pages. The first page accepts a couple of values and when the user clicks the Submit button, the second page appears. The second page displays the values for the first page, creates session variables, and accepts two additional values. When the user clicks the Submit button, the third page appears displaying the values from the first two. 1) Open Application_05.jws. Note: This opens a skeleton of all the JSP application projects used in this practice.

b) In the Open window, open the Application_05 directory. c) Double-click the Application_05.jws file. 2) Expand the JSPApplication01 project in the Application Navigator pane. 3) Create a JSP page called page2.jsp in the JSPApplication01 project. Use the following details to accomplish this task: Step Screen/Page Description a. Application Navigator b. c. New Gallery Create JSP Choices or Values Right-click JSPApplication01. Select New. Categories: Web Tier > JSP Items: JSP Click OK. File Name: page2.jsp Click OK.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 22

Oracle University and Egabi Solutions use only

a) In JDeveloper, select File > Open or choose Open Application in the Application Navigator.

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 5-1: Developing a Simple JSP Application (continued)


4) Add two text fields and a submit button to the JSP page and include a form tag when prompted. Name the text fields streetAddress and city. Use the following details to accomplish this task: Step Screen/Page Description a. Component Palette b. c. d e Component Palette Insert Text Field Wizard Insert Form page2.jsp Choices or Values Select HTML > Forms. Click Forms > Text Field.

f. g. h. i. j. k. l.

Component Palette Component Palette Insert Text Field Wizard page2.jsp Component Palette Component Palette Insert Submit Button Wizard

Click Forms > Text Field. Name: city Click OK. Enter City: as plain text before the text field. Click to the right of the empty text field and press Enter to insert a new line. Select HTML > Forms. Click Forms > Submit Button. Value: Next page Click OK.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 23

Oracle University and Egabi Solutions use only

Name: streetAddress Click OK. Action: page3.jsp Click OK. Enter Street Address: as plain text before the text field. Click to the right of the empty text field and press Enter to insert a new line. Select HTML > Forms.

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 5-1: Developing a Simple JSP Application (continued)


5) In the next set of steps, you add tags to display the firstName and lastName fields from page1.jsp. You also add Set tags to store those values on the implicit session object. This makes those values available on any page accessed within the current user session. In page3.jsp, you use the session and request objects to display the values the user has entered in both page1.jsp and page2.jsp pages. Use the following details to accomplish this task: Step Screen/Page Description a. page2.jsp Choices or Values Place the cursor to the left of the form (the dotted gray line) and press Enter to insert a new line. This inserts a new line above the form tag. Select JSTL > Core. Click Core > Out. Value: ${param.firstName} Click OK. Place the cursor to the right of the new Out tag and press Enter to add a new line. Select JSTL > Core. Click Core > Out. Value: ${param.lastName} Click OK.

b. c. d. e. f. g. h.

Component Palette Component Palette Insert Out page2.jsp Component Palette Component Palette Insert Out

6) Now that you have added the display tags, you add tags to store the values of firstName and lastName on the session object. You use a Set tag for this. Use the following details to accomplish this task:

Oracle Fusion Middleware 11g: Build Java EE Applications A - 24

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 5-1: Developing a Simple JSP Application (continued)


Step Screen/Page Description a. page2.jsp b. c. d. Component Palette Component Palette Set Property Inspector page2.jsp Component Palette Component Palette Set Property Inspector Choices or Values Place the cursor to the right of the second Out tag and press Enter to add a new line. Select JSTL > Core. Click Core > Set. Value: ${param.firstName} Var: firstName Scope: session Place the cursor to the right of the Set tag and press Enter to add a new line. Select JSTL > Core. Click Core > Set. Value: ${param.lastName} Var: lastName Scope: session

e. f. g. h.

7) Run page1.html to test the functionality. a) Right-click page1.jsp and select Run. b) Enter values in the First Name and Last Name fields, and then click Next Page. c) Enter values in the Street Address and City fields, and then click Next Page.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 25

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 5-1: Developing a Simple JSP Application (continued)


d) The result pages should look something like the following:

e) When you have verified that your page works, close the browser.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 26

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 5-2: Developing a JSP Application Using a JavaBean

In this practice, you modify a JavaBean that exposes a couple of properties that you use in your JSP application. You modify the code in the JSP page to invoke the JavaBean. You also add the code to include an HTML document in the JSP page. The BookCart application enables you to add and remove books from a shopping cart. You can also view the details of the books that you want to add in the shopping cart. 1) In the Application Navigator, expand JSPApplication02. Note: Minimize or close the JSPApplication01 project. 2) Navigate to CartBean.java in the Application Navigator and double-click it to open in the code editor. Modify the code in the CartBean class as follows: Hint: Expand JSPApplication02 > Application Sources > oracle.jsp > CartBean.java. a) Define the following two properties (in bold) in the CartBean class:
... public class CartBean { Vector vector = new Vector(); String submit = null; String item = null; ...

b) Define and implement the addItem() and removeItem() methods to add and remove books, respectively in a shopping cart.
... public CartBean() { } private void addItem(String name) { vector.addElement(name); } private void removeItem(String name) { vector.removeElement(name); } ...

c) Define and implement the getItems()method to retrieve the shopping details from the shopping cart.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 27

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 5-2: Developing a JSP Application Using a JavaBean (continued)


... public String[] getItems() { String[] s = new String[vector.size()]; vector.copyInto(s); return s; } ...

... public String[] getItems() { String[] s = new String[vector.size()]; vector.copyInto(s); return s; }

public void processRequest() { if (submit == null) addItem(item); if (submit.equals("Add")) addItem(item); else if (submit.equals("Remove")) removeItem(item); reset(); } ...

3) Save and compile the CartBean.java file. a) Select the Save option from the File menu, or click the Save icon in the toolbar. b) Right-click CartBean.java in the Application Navigator and select the Make option from the context menu. c) View the Message-Log to verify the successful compilation. 4) Navigate to BookCatalog.jsp in the Application Navigator and double-click it to open in the visual editor. Click the Source tab to view the JSP code. Modify the code in the BookCatalog.jsp as follows: Hint: Expand JSPApplication02 > Web Content > BookCatalog.jsp.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 28

Oracle University and Egabi Solutions use only

d) Define and implement the processRequest() method that you will be using in your JSP page to invoke the CartBean.

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 5-2: Developing a JSP Application Using a JavaBean (continued)


a) Add the following code (in bold) to reference the CartBean in the JSP application, and to set the bean properties.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@ page contentType="text/html;charset=windows-1252"%> <html> <jsp:useBean id="cart" scope="session" class="oracle.jsp.CartBean" />

...

b) Add the following scriptlet to invoke the beans processRequest() method.


... <html> <jsp:useBean id="cart" scope="session" class="oracle.jsp.CartBean" /> <jsp:setProperty name="cart" property="*" /> <% cart.processRequest(); %> ...

c) Add the <%@ include %> directive to insert an HTML file (Books.html) in the JSP.
... <html> <jsp:useBean id="cart" scope="session" class="oracle.jsp.CartBean" /> <jsp:setProperty name="cart" property="*" /> <% cart.processRequest(); %> <%@ include file ="Books.html" %> ...

Oracle Fusion Middleware 11g: Build Java EE Applications A - 29

Oracle University and Egabi Solutions use only

<jsp:setProperty name="cart" property="*" />

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 5-2: Developing a JSP Application Using a JavaBean (continued)


d) Add the following scriptlet to show the details of the selected book.
... <%@ include file ="Books.html" %> <div align="center"> <table width="66%" border="0" height="159" align="left"> <tr> <td width="54%" height="206"> <p align="left"><font face="Comic Sans MS">Book Details: </font><br> <br/> <% String res = ""; res = request.getParameter("item"); out.print(cart.showDetails(res)); %> ...

e) Add the following scriptlets to retrieve the content from the cart and display the selected books.
... <p align="left"> <font face="Comic Sans MS"> You have the following items in your cart: </font> </p> <p align="left"> <select name="select" size="10"> <% String[] items = cart.getItems(); for (int i=0; i<items.length; i++) { %> <option> <% out.print((items[i])); %> </option> <% } %> </select> ...

Oracle Fusion Middleware 11g: Build Java EE Applications A - 30

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 5-2: Developing a JSP Application Using a JavaBean (continued)


5) Save and compile the JSPApplication02 project. 6) Run Books.html to test the functionality. a) Right-click Books.html and select Run. b) Select any book from the Add/Remove Book drop-down list. c) Click the Add button. Note that the book has been added in the cart. d) Select the same book in the Add/Remove Book drop-down list and click the Remove button. Note that the book has been removed from the cart. f) Select any book in the Add/Remove Book drop-down list and click the Show_Details button to view the details of the book. g) Close the browser window.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 31

Oracle University and Egabi Solutions use only

e) Add and remove any number of books.

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 5-3: Developing a JSP Application Using Custom Tags and Expression Language

In this practice, you develop your own JSP tags and use it to build a JSP application. You create a simple tag handler class (SearchBookTag.java) where you define the functionally of the JSP tag. You also develop a JSP tag library file (MyTagLibrary.tld) to reference the Java class in the JSP application. The BookDetails application displays the details of a book in different formats. It extracts the book details from the BookDetailsBean.java bean. The different formatting functions are defined in the Functions.java file. 2) Open bookdetails.oracle.tag > SearchBookTag.java. 3) Modify the code in the SearchBookTag class as follows: a) Implement the doTag() method to initialize an instance of the BookDetailsBean bean. The tag handler pretends to search for a book, and stores the result in a scoped variable.
... public void doTag() throws JspException { BookDetailsBean book = new BookDetailsBean( BOOK_TITLE, BOOK_AUTHOR, BOOK_DESCRIPTION, BOOK_ISBN ); getJspContext().setAttribute( this.var, book ); } ...

b) Save and compile the file. 4) Open bookdetails.oracle.el > Functions.java. 5) Modify the code in the Functions class as follows: a) Implement the reverse() and caps() methods. The reverse() method reverses any given string, and the caps() method changes all the characters in a string to uppercase.
... public class Functions { public static String reverse( String text ) { return new StringBuffer( text ).reverse().toString(); } public static String caps( String text ) { return text.toUpperCase(); } }

Oracle Fusion Middleware 11g: Build Java EE Applications A - 32

Oracle University and Egabi Solutions use only

1) In the Application Navigator, expand JSPApplication03.

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 5-3: Developing a JSP Application Using Custom Tags and Expression Language (continued)
b) Save and compile the file. 6) View the contents of Web Content > WEB-INF > MyTaglibrary.tld. a) Open the tag library in the code editor and analyze the contents of the <tag> and <function> elements in the file. Observe and relate the code that you just added to SearchBookTag.java and Function.java. 7) Open BookDetails.jsp. Switch to the Source code view and modify the code as follows: a) Add the <%@ taglib> directive to refer to MyTaglibrary.tld.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@ page contentType="text/html;charset=windows-1252"%> <%@ taglib prefix="ns" uri="/WEB-INF/MyTagLibrary.tld"%> <html> ...

b) Add the custom tag in the JSP file.


... </br> <b><u>Result:</u></b> <br></br> <ns:searchBook var="book"/> <table border="1"> ...

c) Add the following expression language in the JSP code to retrieve the book title and apply the formatting functions.
... <tr> <td width="91">Title</td> <td width="182"> ${book.title} </td>

Oracle Fusion Middleware 11g: Build Java EE Applications A - 33

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 5-3: Developing a JSP Application Using Custom Tags and Expression Language (continued)
<td width="248"> ${ns:caps(book.title)} </td> <td width="271"> ${ns:reverse(book.title)} </td> </tr> ...

d) Save the JSP file. 8) Save and compile the JSPApplication03 project. 9) Run BookDetails.jsp to test the functionality. a) Right-click BookDetails.jsp and select Run. b) Observe the contents in each column to verify the functionality. c) Close the browser when you are done.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 34

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practices for Lesson 6


In this practice set, you learn to access a database resource in a servlet application by injecting a javax.sql.DataSource objects instance variable with the @Resource annotation. You modify the LoginServlet servlet class to access and query the Login table stored in the FOD database schema. You perform the following set of tasks in this practice set: Use the @Resource annotation in the LoginServlet servlet class to access the Login table.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 35

Oracle University and Egabi Solutions use only

Test the servlet application. Use the @EJB annotation in a servlet class to reference/inject an Enterprise JavaBean.

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 6-1: Accessing Database Connectivity in a Servlet Application by Implementing Dependency Injection (DI)
In this practice, you modify the LoginServlet servlet class to access the Login table stored in the FOD database schema. You inject the database table in the servlet class by using the @Resource annotation. The primary task of this practice is to modify the database connectivity code to access the database table. The existing logic validates the username and password against predefined database constants (hard-coded in the application). You can make the database connectivity code much simpler in the application by enabling dependency injection. 1) In JDeveloper, open Application_06_01.jws. Note: This opens a skeleton application, the Servlets project, for the servlet application components. a) In JDeveloper, select File > Open. b) In the Open window, open the
D:\labs\labs\Application_06\Application_06_01 directory.

c) Double-click the Application_06_01.jws file. 2) Modify the code in the LoginServlet servlet class to access and query the Login table: a) Navigate to DI_Application01 > Application Sources > oracle.servlets in the Application Navigator and double-click LoginServlet.java to open it in the code editor. b) Add the @Resource annotation inside the LoginServlet class definition. Use the name attribute of the @Resource annotation to specify the data source name. Specify the data source name as jdbc/fodDS. Press and hold ALT + Enter to add the javax.annotation.Resource package that defines the @Resource annotation. Note: jdbc/fodDS is the data source JNDI name that was automatically created when you configured the database connection in JDeveloper to connect to the FOD database schema. This data source is only for testing an application, and not being used in any production environment.
... @Resource(name = "jdbc/fodDS") ...

Oracle Fusion Middleware 11g: Build Java EE Applications A - 36

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 6-1: Accessing Database Connectivity in a Servlet Application by Implementing Dependency Injection (DI) (continued)
c) Define a javax.sql.DataSource instance as the injection field.
... @Resource (name = "jdbc/fodDS") private javax.sql.DataSource myDs; ...

d) Define the instance variables for the Connection object.


... @Resource (name = "jdbc/fodDS") private javax.sql.DataSource myDs; private Connection con; ...

e) Modify the code in the configureConnection()method to establish a database connection.


... public void configureConnection() throws SQLException { try{ con = myDs.getConnection(); } catch (Exception e){ System.out.println("Connection failed: " +e.toString()); } } ...

3) Right-click LoginServlet.java and select Make to compile the class. 4) Run Login.html to test the functionality. a) Right-click Login.html and select Run. b) Enter the username as sking and password as oracle, and click Login. 5) When you are done, close the browser.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 37

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

1) In JDeveloper, open Application_06_02.jws. a) In JDeveloper, select File > Open b) In the Open window, open the D:\labs\labs\Application_06\Application_06_02 directory. c) Double-click the Application_06_02.jws file. 2) Modify the code in the ValidationServlet servlet class to access and query the CreditCardValidatorBean session bean: a) Navigate to DI_Application02 > Application Sources > org.demo.controller in the Application Navigator and double-click ValidationServlet.java to open it in the code editor. b) Add the @EJB annotation inside the ValidationServlet class definition. Use the mappedName attribute of the @EJB annotation to specify the session bean that the servlet has to invoke. Press and hold ALT + Enter to add the javax.ejb.EJB package that defines the @EJB annotation.
... public class ValidationServlet extends HttpServlet { // add code .... @EJB(mappedName = "CreditCardValidatorSessionEJB") ...

Note: You will know more about the EJBs and their implementation in the later practices. The mappedName attribute refers to the global JNDI name of the target EJB. c) Define a CreditCardValidator (Enterprise JavaBeans remote interface) instance as the injection field.
... @EJB(mappedName = "CreditCardValidatorSessionEJB") private CreditCardValidator ccEJB; ...

Oracle Fusion Middleware 11g: Build Java EE Applications A - 38

Oracle University and Egabi Solutions use only

The primary task of this practice is to inject an Enterprise JavaBean (EJB) in a Java EE application by implementing dependency injection. In this practice, you modify the ValidationServlet servlet class to reference an EJB by incorporating the @EJB annotation. The application takes a credit card type and a credit card number, and verifies the credit card to be valid or invalid. The credit card validation logic is implemented in the CreditCardValidatorBean session bean. The ValidationServlet servlet accepts the credit card details from the CreditCardValidationForm HTML form and passes it on to the EJB for validation. Based on the response from the EJB, the servlet displays appropriate message.

Practice 6-2: Injecting an Enterprise Java Bean by Implementing DI

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 6-2: Injecting an Enterprise Java Bean by Implementing DI (continued)


d) Add the code in the servlets class doPost()method to invoke the Enterprise JavaBeans validateCreditCard() business method that implements the logic to validate a credit card.
... public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(CONTENT_TYPE); PrintWriter out = response.getWriter(); ccType = request.getParameter("card_type"); ccNum = Integer.parseInt(request.getParameter("card_number")); boolean result = ccEJB.validateCreditCard(ccType, ccNum); ...

3) Compile DI_Application02. 4) Run CreditCardValidationForm.html to test the functionality. a) Right-click CreditCardValidationForm.html and select Run. b) Enter the card type as AMEX and card number as 123456789, and click Enter. 5) When you are done, close the browser and close Application_06. You can also remove it from the IDE if you want.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 39

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practices for Lesson 7


In this practice set, you learn to work with session beans by using JDeveloper. You create both the stateless and stateful session beans and execute them by creating a sample test Java client. You perform the following set of tasks in this practice set: Creating a stateless session bean and implementing a business method Creating a test client to invoke the stateless session bean Creating a stateful session bean that calls the stateless session bean by implementing dependency injection. Here you expose a set of methods to store the clients information. Creating a test client to invoke the stateful session bean Creating an interceptor class to be used in a session bean

Oracle Fusion Middleware 11g: Build Java EE Applications A - 40

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 7-1: Creating a Stateless Session Bean

Use the JDeveloper wizard to create a stateless session bean. Expose a business method in the stateless session bean that takes the user ID and credit card number of a client (as the method parameters) and validates the credit card number against simple logic. After the validation, the method returns an appropriate message to the client. 1) Open Application_07. Note: This opens a skeleton course application, the Model project, for the bean components. 2) In JDeveloper, create a stateless session bean called CreditCardValidator in the Model project. Use the following details to accomplish this task: Step Screen/Page Description a. Application Navigator b. c. New Gallery Create Session Bean - Step 2 of 5 Create Session Bean - Step 3 of 5 Create Session Bean - Step 4 of 5 Choices or Values Right-click Application_07 > Model. Select New. Categories: Business Tier > EJB Items: Session Bean Click OK. EJB Name: CreditCardValidator Session Type: Stateless (verify) Transaction Type: Container (verify) Mapped Name: CreditCardValidatorSessionEJB Click Next. Bean Class:
org.demo.business.CreditCardValidatorBean

d. e.

Click Next. Implement a Remote Interface: Selected (verify) Implement a Local Interface: Selected (verify) Click Finish.

3) The Application Navigator should look like the following:

Oracle Fusion Middleware 11g: Build Java EE Applications A - 41

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 7-1: Creating a Stateless Session Bean (continued)


4) In CreditCardValidatorBean.java (displayed in the source code editor pane of JDeveloper), define a public methodvalidateCC()that takes two integer parameters (user ID and credit card number). Implement the validateCC() method by coding a simple logic to validate the credit card number against a predefined value. Enter the following code (shown in bold) before the no-argument constructor in the CreditCardValidatorBean.java class:
... public CreditCardValidatorBean() { } public String validateCC(int uid, int ccNum){ if (uid==10 && ccNum==123456789) return "Authentic"; else return "Invalid"; } ...

5) The validateCC() method should be reflected in the session beans remote and local interfaces. Execute the following steps to accomplish this task: a) Open CreditCardValidator.java. b) Add the following code in the CreditCardValidator.java class (session beans remote interface) to define the validateCC() business method:
... @Remote public interface CreditCardValidator { public String validateCC(int uid, int ccNum); }

c) Open CreditCardValidatorLocal.java (the session beans local interface) and define the validateCC() business method:
... @Local public interface CreditCardValidatorLocal { public String validateCC(int uid, int ccNum); }

6) Save and compile the session bean:

Oracle Fusion Middleware 11g: Build Java EE Applications A - 42

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 7-2: Creating a Sample Test Java Client for the CreditCardValidator Stateless Session Bean
In this practice, you generate a Java client for the CreditCardValidator bean. 1) Use JDeveloper to generate a sample Java client for the CreditCardValidator bean: a) In the Applications Navigator pane, right-click CreditCardValidatorBean.java and select New Sample Java Client. b) In the Create Sample Java Client window, specify the following details and click OK. Client Class Name: org.demo.client.CreditCardValidatorClient Application Server Connection: IntegratedWLSConnection. 2) Add the following code in the main() method of the CreditCardValidatorClient class (the test clients class) to set the parameters and execute the beans business method:
... // Call any of the Remote methods below to access the EJB
CreditCardValidator creditCardValidator = (CreditCardValidator) ...

System.out.println(creditCardValidator.validateCC(10, 123456789)); } catch (Exception ex) { ...

3) Save and compile the test client. 4) Execute the CreditCardValidator session bean in the integrated WebLogic Server instance in JDeveloper: a) In the Applications Navigator pane, right-click CreditCardValidatorBean.java and select Run. b) Observe the Running: DefaultServer Log tabbed page and verify that the WebLogic Server instance has been initialized, and the application has deployed successfully. 5) Execute the CreditCardValidatorClient test client to test the session bean. a) In the Applications Navigator pane, navigate to Model > Application Sources > org.demo.client node, right-click CreditCardValidatorClient.java, and select Run. b) View the result of executing the test client on Running: Model.jpr - Log.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 43

Oracle University and Egabi Solutions use only

Client Project: Model.jpr

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 7-2: Creating a Sample Test Java Client for the CreditCardValidator Stateless Session Bean (continued)

Note: Try to execute the test client by changing the values in the parameters field of the validateCC() method. For example:
... // Call any of the Remote methods below to access the EJB // creditCardValidator.validateCC( uid, ccNum ); System.out.println(creditCardValidator.validateCC(10, 100000000)); } catch (Exception ex) { ...

Oracle Fusion Middleware 11g: Build Java EE Applications A - 44

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 7-3: Calling a Stateless Session Bean in a Stateful Session Bean


In this practice, you create an instance of the CreditCardValidator stateless session bean in the ShoppingCart stateful session bean by implementing dependency injection. You define instance variables to store the user ID and credit card number in the ShoppingCart bean and also generate the accessor methods. You then define a business methodgenerateBill()within the ShoppingCart bean that invokes the CreditCardValidator bean and returns an appropriate message to the client. 1) Create a stateful session bean called ShoppingCart in the Model project. Use the following details to accomplish this task: Step Screen/Page Description a. Application Navigator b. c. New Gallery Create Session Bean - Step 2 of 5 Create Session Bean - Step 3 of 5 Create Session Bean - Step 4 of 5 Choices or Values Right-click Application_07 > Model. Select New. Categories: Business Tier > EJB Items: Session Bean Click OK. EJB Name: ShoppingCart Session Type: Stateful (verify) Transaction Type: Container (verify) Mapped Name: ShoppingCartSessionEJB Click Next. Bean Class: org.demo.business.ShoppingCartBean Click Next. Implement a Remote Interface: Selected (verify) Implement a Local Interface: Selected (verify) Click Finish.

d. e.

2) Open ShoppingCartBean.java and add the following set of code in the ShoppingCart session bean to call and invoke the CreditCardValidator stateless session bean, by implementing dependency injection: a) Declare the @EJB annotation in the ShoppingCart session bean (ShoppingCartBean.java) to obtain a reference of the CreditCardValidator bean. Also define an instance variable of the CreditCardValidator bean in ShoppingCartBean.java. Note: Import the javax.ejb.EJB package to support the @EJB annotation.
... @Stateful(name = "ShoppingCart", mappedName = "ShoppingCartSessionEJB") @Remote @Local

Oracle Fusion Middleware 11g: Build Java EE Applications A - 45

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 7-3: Calling a Stateless Session Bean in a Stateful Session Bean (continued)
public class ShoppingCartBean implements ShoppingCart, ShoppingCartLocal { @EJB private CreditCardValidator ccv; ...

b) Define two instance variables in ShoppingCartBean.java to store the user ID and credit card number of the client:
private int uid; private int ccNum;

c) Generate the accessors methods for the uid and ccNum instance variables. To perform this task, right-click the source code editor of JDeveloper (inside ShoppingCartBean.java) and select Generate Accessors. In the Generate Accessors window, select the uid and ccNum check boxes and click OK. Note: Do not generate accessors for the ccv instance variable. d) Define and implement the following business method (generateBill()) in ShoppingCartBean.java that invokes the CreditCardValidator bean to validate the credit card number. Based on the validation, the method returns an appropriate message to the client.
... public ShoppingCartBean() { } public String generateBill(){ String res = ccv.validateCC(getUid(),getCcNum()); if (res.equals("Authentic")) return "Order Confirmed"; else return "Invalid Transaction"; } ...

3) The generateBill(), setUid(), and setCcNum() methods should be reflected in the session beans remote and local interfaces. Execute the following steps to accomplish this task: a) Open ShoppingCart.java in the source code editor. b) Add the following code in the ShoppingCart.java class (session beans remote interface) to define the generateBill(), setUid(), and setCcNum() methods:

Oracle Fusion Middleware 11g: Build Java EE Applications A - 46

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 7-3: Calling a Stateless Session Bean in a Stateful Session Bean (continued)
... @Remote public interface ShoppingCart { public void setUid(int uid); public void setCcNum(int ccNum); public String generateBill(); }

c) Add the following code in the ShoppingCartLocal.java class (session beans local interface) to define the generateBill(), setUid(), and setCcNum() methods:
... @Local public interface ShoppingCartLocal { public void setUid(int uid); public void setCcNum(int ccNum); public String generateBill(); }

4) Save and compile the Model project.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 47

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 7-4: Creating a Sample Test Java Client for the ShoppingCart Stateful Session Bean
In this practice, you generate a Java client for the ShoppingCart bean. 1) Use JDeveloper to generate a sample Java client for the ShoppingCart bean: a) In the Navigator, right-click ShoppingCartBean.java and select New Sample Java Client. b) In the Create Sample Java Client window, specify the following details and click OK. Client Class Name: org.demo.client.ShoppingCartClient Application Server Connection: IntegratedWLSConnection. 2) Add the following code in the main() method of the ShoppingCartClient class (the test clients class) to set the parameters and execute the beans business method:
... ShoppingCart shoppingCart = (ShoppingCart)context.lookup( ... ); shoppingCart.setUid(10); shoppingCart.setCcNum(123456789); System.out.println( shoppingCart.generateBill( } catch (Exception ex) { ...

) );

3) Save and compile the test client. 4) Execute the ShoppingCartBean session bean in the integrated WebLogic Server instance in JDeveloper: a) In the Applications Navigator pane, right-click ShoppingCartBean.java and select Run. b) Observe the Running: DefaultServer - Log tabbed page and verify that the WebLogic Server instance has been initialized, and the application has deployed successfully. 5) Execute the ShoppingCartClient test client to test the session bean. 6) View the result of executing the test client on the Running: Model.jpr - Log tabbed page.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 48

Oracle University and Egabi Solutions use only

Client Project: Model.jpr

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 7-4: Creating a Sample Test Java Client for the ShoppingCart Stateful Session Bean (continued)

7) Execute the test client again after changing the values in the parameters field of the setCcNum() method. For example:
... shoppingCart.setUid(10); shoppingCart.setCcNum(123878789); System.out.println( shoppingCart.generateBill( ...

) );

Oracle Fusion Middleware 11g: Build Java EE Applications A - 49

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 7-5: Using Interceptors in the ShoppingCart Session Bean

Interceptors are used to intercept either a business method or a life-cycle event. An interceptor that intercepts a business method is typically called an AroundInvoke method because it can be defined by annotating the method with an @AroundInvoke annotation. In this practice, you develop an external interceptor class that defines a method, which can be used to determine the time that a method takes to execute. You can then use the interceptor class in any of the session beans to find out the exact time a beans method take to execute.

Step Screen/Page Description a. Application Navigator b. c. New Gallery Create Java Class

Choices or Values Right-click Application_07 > Model. Select New. Categories: General > Java Items: Java Class Click OK. Name: BeanMethodProfile Package: org.demo.interceptors Click OK.

2) Add the following packages in the BeanMethodProfile class:


import javax.interceptor.AroundInvoke; import javax.interceptor.InvocationContext;

Note: If the IDE indicates it cannot find the classes that you need to add the Java EE 1.5 API library to the Model project to support these packages, execute the following set of tasks to add the library: a) Right-click Model and select Project Properties from the shortcut menu. b) In the Project Properties window, select Libraries and Classpath in the left pane of the window. You can see classpath entries and the libraries description of the default project libraries in the right pane. c) Click the Add Library button. Select Java EE 1.5 API from the Add Library window and click OK. The library is added to the Model project. 3) Define and implement the profile() method in the BeanMethodProfile class.
import javax.interceptor.AroundInvoke; import javax.interceptor.InvocationContext; Oracle Fusion Middleware 11g: Build Java EE Applications A - 50

Oracle University and Egabi Solutions use only

1) Create the BeanMethodProfile interceptor class that defines the profile() method. The profile() method calculates the time that a session beans method takes to execute (if the interceptor class is used in that session bean). Use the following details to create the Java class:

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 7-5: Using Interceptors in the ShoppingCart Session Bean (continued)


public class BeanMethodProfile { ... private Object profile(InvocationContext invCtx) throws Exception { long time1 = System.nanoTime(); Object result = invCtx.proceed(); long time2 = System.nanoTime(); System.out.println(invCtx.getMethod().getName() + " took: " + ((time2 - time1)/ 1000.0) + " nano seconds."); return result; } ...

4) Add the @AroundInvoke annotation to the profile() method.


public class BeanMethodProfile { ... @AroundInvoke private Object profile(InvocationContext invCtx) throws Exception { long time1 = System.nanoTime(); Object result = invCtx.proceed(); long time2 = System.nanoTime(); System.out.println(invCtx.getMethod().getName() + " took: " + ((time2 - time1)/ 1000.0) + " nano seconds."); return result; } ...

5) Save and compile the BeanMethodProfile Java class. 6) Add the BeanMethodProfile interceptor class to the ShoppingCartBean session bean. a) Open ShoppingCartBean.java. b) Add the following code (in bold) in the ShoppingCartBean class to implement the BeanMethodProfile interceptor class.
... import javax.interceptor.Interceptors;

Oracle Fusion Middleware 11g: Build Java EE Applications A - 51

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 7-5: Using Interceptors in the ShoppingCart Session Bean (continued)


import org.demo.interceptors.BeanMethodProfile; @Stateful(name = "ShoppingCart", mappedName = "ShoppingCartSessionEJB") @Remote @Local @Interceptors(BeanMethodProfile.class) ...

8) Run the ShoppingCartClient test client to test the ShoppingCartBean session bean. 9) View the result of executing the test client in Running: Model.jpr - Log. To view the execution time of the ShoppingCartBean session beans methods, click the Running: DefaultServer tab in the Log tabbed page.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 52

Oracle University and Egabi Solutions use only

7) Run the ShoppingCartBean session bean in the integrated WebLogic Server instance in JDeveloper.

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practices for Lesson 8


In this practice set, you use JPA entity beans to create an application model layer. You create several beans and a Session bean that provides client access. You also use a JDeveloper wizard to create a simple Java client to test your Session bean. You perform the following set of tasks in this practice set: Create a simple entity bean by coding the bean. Use the JDeveloper wizards to create a set of entity beans. Create and manage a Session bean that provides client access to the entity beans. Creating a test client to invoke the session bean

Oracle Fusion Middleware 11g: Build Java EE Applications A - 53

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 8-1: Coding a Simple Entity Bean


1) Create an Application. a) Invoke the New Application Wizard. b) Name the Application Application_08. c) Set the Application Package Prefix to oracle.

In this practice, you create a simple entity bean in a new Application.

d) Select Java EE Web Application as the Application Template. e) Rename the ViewController project UI. g) Ensure that the name of the Model project is Model. h) Ensure that the Default Package is oracle.model. i) Ensure that the EJB Version is Enterprise JavaBeans 3.0. j) Click Finish. 2) Create an Offline Database based on the FOD schema. a) Invoke the New Gallery from the Model project. b) Select Database Tier > Offline Database Objects > Copy Database Objects to a Project. c) Create a new connection named FOD based on FOD / fusion. (Click the green plus symbol next to Connection.) d) Name the Offline Database FOD. e) Select PERSONS and PERSON_SEQ from the list of available objects. (Click Query to retrieve the list of available objects.) f) Click Next, then Finish to create the Offline Database. 3) Next, create a Persistence Unit. a) Invoke the New Gallery on the Model projec.t b) Select Business Tier > TopLink/JPA > JPA Persistence Unit. c) Name the Persistence Unit FOD, and click OK to create the Persistence Unit. 4) Set the Development Database to the Offline Database you just created (FOD). a) Open persistence.xml in the visual editor. b) Select FOD in the Structure window. c) Select Connection in the visual editor. d) Use the drop-down list to select FOD (Oracle) for the Development Database. 5) Create a Java class named Person in the oracle.model package. It should be public with a default constructor.
Oracle Fusion Middleware 11g: Build Java EE Applications A - 54

Oracle University and Egabi Solutions use only

f) The Default Package should be oracle.view.

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 8-1: Coding a Simple Entity Bean (continued)


6) Add the Entity annotation. a) @Entity(name=Person) b) Add the import of javax.persistence.Entity. c) Change the Person class to implement Serializable and include the import. 7) Change the constructor to protected. 8) Add private class variables and column annotations for the following: Column ID FIRST_NAME LAST_NAME EMAIL PHONE_NUMBER Name id firstName lastName email phoneNumber Type private Long private String private String private String private String

Note: You will need to include the import for javax.persistence.Column. 9) Add the @Table annotation because the source table for this Person entity is PERSONS. 10) Identify the id attribute as the Id for the entity. a) Add the @Id annotation to the attribute. b) Add nullable=false to the @Column annotation. i) Add annotation to use a generated value for ID as follows: GeneratedValue using the generator named PER_SEQ with a strategy of
GenerationType.SEQUENCE. SequenceGenerator using sequenceName PERSON_SEQ.

ii) You will need to import:


javax.persistence.GenerationType javax.persistence.GeneratedValue javax.persistence.SequenceGenerator

The class should look like the following:


@Entity(name="Person") @Table(name="PERSONS") public class Person implements Serializable{ @Id @Column(name="PERSON_ID", nullable=false) @GeneratedValue(generator = "PER_SEQ", strategy = GenerationType.SEQUENCE) @SequenceGenerator(name="PER_SEQ", sequenceName = "PERSON_SEQ") private Long id; @Column(name="FIRST_NAME") private String firstName;

Oracle Fusion Middleware 11g: Build Java EE Applications A - 55

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 8-1: Coding a Simple Entity Bean (continued)


@Column(name="LAST_NAME") private String lastName; @Column(name="EMAIL") private String email; @Column(name="PHONE_NUMBER") private String phoneNumber; protected Person() { } }

a) Add a @NamedQueries annotation like:


@NamedQueries({ })

b) Inside the braces add annotation for the NamedQuery:


@NamedQueries({ @NamedQuery(name = Person.findAll, query = select o from Person o) })

12) The class should now look like the following:


package oracle.model; import java.io.Serializable; import import import import import import import import import javax.persistence.Column; javax.persistence.Entity; javax.persistence.GeneratedValue; javax.persistence.GenerationType; javax.persistence.Id; javax.persistence.NamedQueries; javax.persistence.NamedQuery; javax.persistence.SequenceGenerator; javax.persistence.Table;

@Entity(name="Person") @NamedQueries({ @NamedQuery(name="Person.findAll", query = "select o from Person o") }) @Table(name = "PERSONS") public class Person implements Serializable{ @Id @Column(name="PERSON_ID", nullable=false) @GeneratedValue(generator = "PER_SEQ", strategy = GenerationType.SEQUENCE)

Oracle Fusion Middleware 11g: Build Java EE Applications A - 56

Oracle University and Egabi Solutions use only

11) Add a generic findAll query as follows:

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 8-1: Coding a Simple Entity Bean (continued)


@SequenceGenerator(name="PER_SEQ", sequenceName = "PERSON_SEQ") private Long id; @Column(name="FIRST_NAME") private String firstName; @Column(name="LAST_NAME") private String lastName; @Column(name="EMAIL") private String email; @Column(name="PHONE_NUMBER") private String phoneNumber;

13) Add accessors for each of the attributes in the Person Entity. a) Right-click one of the attributes and select Generate Accessors. b) Click Select All in the Generate Accessors dialog box. c) Click OK. 14) Compile and save your work You have now created an entity bean completely from scratch. In the next section, you use JDeveloper wizards to create the remaining entity beans.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 57

Oracle University and Egabi Solutions use only

protected Person() { }

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 8-2: Using the JDeveloper Entity Bean Wizard


In this practice, you create two entity beans using the Entity Bean wizard. 1) Invoke the New Gallery on the Model project. 2) Select Business Tier > EJB > Entities from Tables. 3) In the Create Entities from Tables Wizard: a) Select FOD as the Persistence Unit. b) Select Online Database Connection and choose FOD as the connection. c) On the Select Tables page, click Query to populate the Available list. e) If it is not already, set the package name to oracle.model. f) In Entity Details, change the names of both the entities to singular (Products to Product, Categories to Category). g) Click Finish to create the entities. 4) Examine persistence.xml. a) Open persistence.xml. b) In the Structure window, expand Mapped Classes > oracle.model and notice the Category and Product entities are now mapped. 5) Examine Product.java and Category.java to see what was created for you.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 58

Oracle University and Egabi Solutions use only

d) Select Categories and Products and move them to the Selected list.

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 8-3: Customizing Entity Beans

In this practice, you customize the Product and Category entity beans you created with the Entity Bean wizard. The wizard creates attributes for each column in the source table. Your application may not need every attribute. It also creates set and get methods for each attribute that you may or may not need. You will also rename some attributes to better fit the business use of the attributes. 1) Open Product.java in the visual editor. 2) Remove the following attributes and related accessors:
attributeCategory createdBy creationDate lastUpdatedBy lastUpdateDate objectVersionId

3) Remove the same attributes from the constructor. The attributes you removed will be underlined in red to show there is a problem. Remove them from the method signature as well. You will notice the removed attributes will be in a light gray font. 4) Change the no-arg constructor to protected. 5) Right-click anywhere in the editor and select Make. 6) Add annotation to use a generated value for Id as follows: a) GeneratedValue using the generator named PROD_SEQ with a strategy of GenerationType.SEQUENCE (You will need to import javax.persistence.GeneratedValue and javax.persistence.GenerationType.) b) SequenceGenerator named PROD_SEQ using the sequenceName PRODUCT_SEQ. (You will need to import javax.persistence.SequenceGenerator.) The code should look like the following:
@Id @Column(name="PRODUCT_ID", nullable = false) @GeneratedValue(generator = "PROD_SEQ", strategy = GenerationType.SEQUENCE) @SequenceGenerator(name="PROD_SEQ", sequenceName = "PRODUCT_SEQ") private Long productId;

7) Now that you have Id to be generated from a sequence, remove the setProductId() method and productId from the constructor. Remove it from the constructor argument list and the method. 8) Make the class to check for errors.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 59

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 8-3: Customizing Entity Beans (continued)


9) Open Category.java in the visual editor. 10) Remove the following attributes and related accessors:
createdBy creationDate lastUpdatedBy lastUpdateDate objectVersionId

11) Remove the same attributes from the constructor. The attributes you removed will be underlined in red to show there is a problem. Remove them from the method signature as well. You will notice the removed attributes will be in a light gray font. The attributes defined in this Entity may be accessed from any number of client applications. It is important to name the attributes so that they are readily recognizable for what they represent. In some cases, the generated names may not reflect their content precisely, especially when they are created as part of a relationship. 13) Use Refactor to rename the category attribute that is in the PARENT_CATEGORY_ID relationship to parent. Right-click the category attribute and select Refactor > Rename. When asked to rename the accessors, click Yes. When client applications access this attribute, they will use the notation category.parent, which better describes the content and purpose of this attribute. 14) Examine the accessors to see that the names have changed. The accessor methods should look like the following:
public Category getParent() { return parent; } public void setParent(Category category) { this.parent = category; }

15) Notice also that the addCategory and removeCategory methods have also been refactored to reflect the change to the method name. 16) The constructor is also changed to reflect the new attribute name. The constructor should now look like the following:
public Category(String categoryDescription, Long categoryId, String categoryLockedFlag, String categoryName, Category category) { this.categoryDescription = categoryDescription; this.categoryId = categoryId; Oracle Fusion Middleware 11g: Build Java EE Applications A - 60

Oracle University and Egabi Solutions use only

12) Change the no-arg constructor to protected.

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 8-3: Customizing Entity Beans (continued)


this.categoryLockedFlag = categoryLockedFlag; this.categoryName = categoryName; this.parent = category; }

17) Because you refactored category to parent, you need to change the OneToMany mappedBy from category to parent. The code should now look like the following:
@OneToMany(mappedBy = "parent") private List<Category> categoryList;

private List<Category> categoryList; to private List<Category> children;

This will make client code more understandable because to access child categories now, the access will be category.children. 19) The refactor will also modify the get, set, addCategory, and removeCategory methods to reflect the new name. The methods should look like the following:
public List<Category> getChildren() { return children; } public void setChildren(List<Category> categoryList) { this.children = categoryList; } public Category addCategory(Category category) { getChildren().add(category); category.setParent(this); return category; } public Category removeCategory(Category category) { getChildren().remove(category); category.setParent(null); return category; }

20) Right-click anywhere in the editor and select Make.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 61

Oracle University and Egabi Solutions use only

18) Refactor the following attributes:

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 8-4: Creating and Testing a Session EJB


1) Invoke the New Gallery on the Model project 2) Select Business Tier > EJB > Session Bean. 3) In the Create Session Bean wizard: a) Set the EJB Name to SessionEJB08. b) Ensure that Generate Session Faade Methods is selected. c) The Entity Implementation should be JPA Entities.

In this practice, you create a Session EJB to provide client access to the entity beans you just created.

d) On the Session Faade page, select all the methods except those that have findAllByRange and RemovePerson. e) Accept the Bean class name, but change the package to oracle.services such as oracle.services.SessionEJB08Bean f) Implement both Remote and Local Interfaces. g) Click Finish to create the Session EJB. 4) Open SessionEJB08Bean.java in the visual editor and examine the generated methods. Now that you have a Session EJB, you can create a simple Java client to test your model. 5) Right-click SessionEJB08Bean.java in the Application Navigator. 6) Select New Sample Java Client. 7) Accept the default settings and click OK to create the java class. 8) The class opens in the visual editor. 9) Examine the contents: a) Notice that each of the queries is called with a set of System.out.println statements to return the row values. Those are nested in for loops that will display all the rows in the entity. b) Notice the getInitialContext method, which provides the connection details to the WLS server. 10) Test the SessionEJB08 and entity beans by performing the following steps: a) Right-click SessionEJB08Bean.java and select Run. b) After you see the message indicating that the application has been deployed successfully to the Server Instance Default Server, right-click SessionEJB08Client.java and select Run. You will see a list of the selected data in the log window.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 62

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 8-4: Creating and Testing a Session EJB (continued)


11) Stop the Application Server instance (Run > Terminate > Default Server). 12) You can close and remove the Application from the IDE when you are done.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 63

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practices for Lesson 9


As you design and develop an application, you will discover the need for queries specific to your application. For example, you may want a query for finding a person by ID and by Name. You may also need to find a product by ID or Name. In this practice, you create and test several Named Queries.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 64

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 9-1: Adding Named Queries to Person


1) In JDeveloper, open Application_09.jws. 2) Open Person.java in the visual editor.

In this practice, you add two Named Queries to the Person Entity, and test them.

3) Add a Named Query named Person.findById that selects a row based on Id. a) Within the NamedQueries annotation and after the first NamedQuery, add a NamedQuery named Person.findById. b) The query should select from Person where o.id is equal to an :id parameter.
@NamedQuery(name = "Person.findById", query = "select o from Person o where o.id = :id")

4) Add another NamedQuery named Person.findByLastName that selects the Person by lastName. The completed code should look like the following:
@NamedQueries({ @NamedQuery(name = "Person.findAll", query = "select o from Person o"), @NamedQuery(name = "Person.findById", query="select o from Person o where o.id = :id"), @NamedQuery(name = "Person.findByLastName", query = "select o from Person o where o.lastName like :lastName") })

5) Add the new NamedQueries to the SessionEJB. a) Right-click SessionEJB09Bean and select Edit Session Faade. b) Expand Person in Faade Options. c) Select Person.findById and Person.findByLastName. (Leave the original queries selected.) d) Click OK to add them to the Faade. 6) Create a new Sample Java Test Client. Accept the default name. 7) JDeveloper opens the new test client in the visual editor. Notice that there are two red marks or indicators in the margin at the right of the editor. Click the first one and the editor highlights the line of code where there is a problem. 8) Notice that the generated code has a notation where the query is expecting a parameter. 9) Add a parameter to the queryPersonFindById query. You can use any valid PersonId (100129).

Oracle Fusion Middleware 11g: Build Java EE Applications A - 65

Oracle University and Egabi Solutions use only

c) The code should look like the following:

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 9-1: Adding Named Queries to Person (continued)


10) Add a String parameter to queryPersonFindByLastName. You can use a wildcard such as A% to return all Persons whose last name begins with A. 11) Test the queries by running SessionEJB09Bean, and then the new Java client. Hint: It will be easier to see your test results if you comment out the other queries in the test client. 12) If you used 106 and A%, the results should look like the following: (results truncated for space)
id = 106 firstName = Valli lastName = Pataballa email = VPATABAL phoneNumber = 256.555.0130 id = 105 firstName = David lastName = Austin email = DAUSTIN phoneNumber = 401.555.0129 id = 207 firstName = Jose lastName = Armstrong email = JARMSTRONG phoneNumber = 818.555.0116

Oracle Fusion Middleware 11g: Build Java EE Applications A - 66

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 9-2: Adding Named Queries to Product


1) Open Product.java in the visual editor.

In this practice, you add two named queries to Product. In your application, you need to query a Product based on the Id and the name. 2) Add a Named Query named Product.findById that selects a row based on Id. a) Within the NamedQueries annotation and after the first NamedQuery, add a NamedQuery named Product.findById. b) The query should select from Product where the o.id is equal to an :id parameter. c) The code should look like the following:
@NamedQuery(name = "Product.findById", query = "select o from Product o where o.id = :id")

3) Add another NamedQuery that selects the Product by name. The completed code should look like the following:
@NamedQueries({ @NamedQuery(name = "Product.findAll", query = "select o from Product o"), @NamedQuery(name = "Product.findById", query="select o from Product o where o.productId = :id"), @NamedQuery(name = "Product.findByName", query = "select o from Product o where o.productName like :name") })

a) Add the new NamedQueries to the SessionEJB09Bean. 4) Create a new Sample Java Test Client. Accept the default name. 5) JDeveloper opens the new test client in the visual editor. 6) Add a parameter to the queryProductFindById query. You can use any valid ProductId (120). 7) Add a String parameter to queryProductFindByName. You can use a wildcard such as I% to return all Products that have a name beginning with I. 8) Test the queries by running SessionEJB09Bean, and then the new java client. Hint: It will be easier to see your test results if you comment out the other queries in the test client. 9) If you used 1 and I%, the results should look like the following:
additionalInfo = HDMI (High-Definition Multimedia Interface) is a lossless, costPrice = 1499.99 description = The TH-42PX60U 42-inch Diagonal Plasma HDTV gives you deep blacks, Oracle Fusion Middleware 11g: Build Java EE Applications A - 67

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 9-2: Adding Named Queries to Product (continued)


externalUrl = images/1.jpg listPrice = 1999.99 minPrice = 1599.99 productId = 1 productName = Plasma HD Television shippingClassCode = CLASS3 supplierId = 112 warrantyPeriodMonths = 6 category = oracle.model.Category@179d854 additionalInfo = null costPrice = 35.0 description = The Portable Audio System for iPod externalUrl = images/15.jpg listPrice = 89.99 minPrice = 55.99 productId = 15 productName = Ipod Speakers shippingClassCode = CLASS2 supplierId = 106 warrantyPeriodMonths = 6 category = oracle.model.Category@3a835d additionalInfo = null costPrice = 200.0 description = Apple iPod - Continuing its tradition externalUrl = images/17.jpg listPrice = 339.99 minPrice = 299.95 productId = 17 productName = Ipod Video 80Gb shippingClassCode = CLASS2

Oracle Fusion Middleware 11g: Build Java EE Applications A - 68

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 9-3: Adding Named Queries to Category

In the application that you are building, you will need a couple of specialized queries on Category. The application needs to be able to find all the root categories. Root categories are defined as those categories that do not have a parent category. You also need a query that returns only those leaf categories, which do have a parent category. These two queries will be used to populate a tree control in the UI. 1) Open Category.java in the visual editor. 2) Add a NamedQuery called Category.findRoot, which queries all categories where the parent is null.

4) The completed code should look like the following:


@NamedQueries({ @NamedQuery(name = "Category.findAll", query = "select o from Category o"), @NamedQuery(name = "Category.findRoot", query="select o from Category o where o.parent is null"), @NamedQuery(name = "Category.findLeaf", query="select o from Category o where o.parent is not null") })

5) Add the two new NamedQueries to the Session Facade (SessionEJB09Bean). 6) Create a Sample Java Test Client. (Accept the default name.) 7) Comment out all test code except the two new Category queries. 8) Run the test. (Remember to run SessionEJB09Bean first.) 9) The results should look something like the following:
categoryDescription = Office Supplies categoryId = 2 parent = null children = {IndirectList: not instantiated} categoryDescription = Consumer Electronics categoryId = 3 parent = null children = {IndirectList: not instantiated} categoryDescription = Books, Music, and Movies categoryId = 1 parent = null children = {IndirectList: not instantiated} categoryDescription = Books categoryId = 8

Oracle Fusion Middleware 11g: Build Java EE Applications A - 69

Oracle University and Egabi Solutions use only

3) Add a NamedQuery called Category.findLeaf which queries only the categories that have parent categories.

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 9-3: Adding Named Queries to Category (continued)


parent = oracle.model.Category@1198ff2 children = {IndirectList: not instantiated} categoryDescription = DVDs categoryId = 9 parent = oracle.model.Category@1198ff2 children = {IndirectList: not instantiated}

10) Notice that the parent in the first query is null.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 70

Oracle University and Egabi Solutions use only

11) Notice that the parent in the second query returns oracle.model.Category@nnnn. That is because the query returns only a reference to the parent category object.

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practices for Lesson 10


This practice set enables you to create and deploy a Web service application to Oracle WebLogic Server. You use Oracle JDeveloper 11g IDE as the development tool for developing the Web service applications with the top-down Web service development approach. In this practice set, you create a credit card validation Web service. It is a simple validation Web service that validates a credit card by using a credit card type and credit card number. The XML artifacts (XSD and WSDL files) have been provided to you. You have to use these artifacts to generate and implement a Web service method. The method takes two parameters (credit card type and credit card number) and validates it with specific business logic, and returns a string value to the caller function. You perform the following set of tasks in this practice set: Creating a Web service application by using the top-down Web service development approach Testing the Web service application by using JDeveloper

Oracle Fusion Middleware 11g: Build Java EE Applications A - 71

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 10-1: Creating the ValidateCreditCardService Web Service by Using the Top-Down Web Service Development Approach

Your task is to create a Web service application to validate a credit card by using the topdown approach. The Web service takes the credit card type and credit card number, and validates it against a simple logic (no database implementation). After validating, it returns an appropriate string message. Perform the following steps: 1) Open Application_10.jws. 2) In the Model project, you see the following XML artifacts (in the Application Sources folder): request.xsd response.xsd WSDLDocument.wsdl

3) Edit the request.xsd schema in the Source view of the code editor. The schema defines the input parameter of the Web service operation. Edit the schema with the following modification: a) Set the name property of the complex type to input. The complex type contains two XML elements. Set the elements name and type attributes as: For the first element: name="arg0", type="xsd:string" For the second element: name="arg1", type="xsd:int"

b) Use the input complex type to create an XSD element. Set the name attribute of the XSD element to request.
<?xml version="1.0" encoding="windows-1252" ?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://www.example.org" targetNamespace="http://www.example.org" elementFormDefault="qualified"> <xsd:complexType name="input"> <xsd:sequence> <xsd:element name="arg0" type="xsd:string"/> <xsd:element name="arg1" type="xsd:int"/> </xsd:sequence> </xsd:complexType> <xsd:element name="request" type="tns:input"/> </xsd:schema>

c) Save the modification.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 72

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 10-1: Creating the ValidateCreditCardService Web Service by Using the Top-Down Web Service Development Approach (continued)
4) Modify the WSDLDocument.wsdl file in the Source view of the code editor. The file defines each aspect of the Web service operation. WSDLDocument.wsdl incorporates the two XML schemas, one of that you have modified earlier. a) Import the request.xsd schema by specifying the namespace property of the <import> element as "http:// www.example.org", and the schemaLocation property as "request.xsd".
... <wsdl:types> <xsd:schema> <xsd:import namespace="http://www.example.org" schemaLocation="request.xsd"/> ...

b) Set the first <message> elements name property to "validateCCInput".


... <wsdl:types> <xsd:schema> <xsd:import namespace="http://www.example.org" schemaLocation="request.xsd"/> <xsd:import namespace="http://www.example.org" schemaLocation="response.xsd"/> </xsd:schema> </wsdl:types> <wsdl:message name="validateCCInput"> <wsdl:part name="parameters" element="tns:request"/> </wsdl:message> <wsdl:message name="validateCCOutput"> <wsdl:part name="parameters" element="tns:response"/> </wsdl:message> ...

c) Set the <portType> elements name property to "ValidateCreditCardService". d) Set the <operation> elements name property to "validateCC".
... <wsdl:message name="validateCCOutput"> Oracle Fusion Middleware 11g: Build Java EE Applications A - 73

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 10-1: Creating the ValidateCreditCardService Web Service by Using the Top-Down Web Service Development Approach (continued)
<wsdl:part name="parameters" element="tns:response"/> </wsdl:message> <wsdl:portType name="ValidateCreditCardService"> <wsdl:operation name="validateCC"> <wsdl:input message="tns:validateCCInput" xmlns:ns1="http://www.w3.org/2006/05/addressing/wsdl" ns1:Action=""/> <wsdl:output message="tns:validateCCOutput" xmlns:ns1="http://www.w3.org/2006/05/addressing/wsdl" ns1:Action=""/> </wsdl:operation> </wsdl:portType> ...

e) Modify the <soap12:address> elements location property to http://localhost:7101/contextroot/ValidateCreditCardSe rviceSoap12HttpPort.


... <wsdl:service name="ValidateCreditCardService"> <wsdl:port name="ValidateCreditCardServiceSoap12HttpPort" binding="tns:ValidateCreditCardServiceSoapHttp"> <soap12:address location="http://localhost:7101/ contextroot/ValidateCreditCardServiceSoap12HttpPort"/> </wsdl:port> </wsdl:service> ...

5) Because you will be deploying the Web service from JDeveloper, you need to change the deployment setting for the applications Java EE context root in JDeveloper. Execute the following steps to perform the task: a) In the Applications Navigator, right-click the Model project and select Project Properties. b) Select Java EE Application in the left pane. In the Java EE Application pane, change the value of the Java EE Web Context Root to contextroot. c) Click OK. 6) Save the modifications in the WSDL file. 7) Create the Web Service artifacts by using the Create Java Web Service from WSDL Wizard. Create a Web service called ValidateCreditCardService in the org.demo.business package by using the JDeveloper wizard. Use the following details to accomplish this task:

Oracle Fusion Middleware 11g: Build Java EE Applications A - 74

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 10-1: Creating the ValidateCreditCardService Web Service by Using the Top-Down Web Service Development Approach (continued)
Step Screen/Page Description a. Applications Navigator b. New Gallery c. Create Java Web Service from WSDL Step 1 of 6 Create Java Web Service from WSDL Step 2 of 6 Create Java Web Service from WSDL Step 3 of 6 Choices or Values Right-click Application_10 > Model. Select New. Categories: Business Tier > Web Services Items: Java Web Service from WSDL Click OK. Click Next.

d.

WSDL Document URL: <LAB_HOME>/


Application_10/Model/src/WSDLDocument.wsdl

Click Next.

e.

Package Name: org.demo.business Click Finish.

8) Expand Model > Application Sources > org.demo.business, and open ValidateCreditCardServiceImpl.java. You see the validateCC() method being defined and not implemented. Add the following code (in bold) in the validateCC() method to implement the Web service business logic.
... public class ValidateCreditCardServiceImpl { public ValidateCreditCardServiceImpl() { } @javax.jws.soap.SOAPBinding(parameterStyle = javax.jws.soap.SOAPBinding.ParameterStyle.BARE) @WebMethod @WebResult(name = "response", targetNamespace = "http://www.example.org", partName = "parameters") public Output validateCC(@WebParam(name = "request", partName = "parameters", targetNamespace = "http://www.example.org") Input parameters) { Output res = new Output(); if(parameters.getArg0().equalsIgnoreCase("AMEX") && parameters.getArg1()==123456789) res.setArg0("Valid credit card"); else

Oracle Fusion Middleware 11g: Build Java EE Applications A - 75

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 10-1: Creating the ValidateCreditCardService Web Service by Using the Top-Down Web Service Development Approach (continued)
res.setArg0("Invalid credit card type or credit card number");

return res; } } ...

Oracle Fusion Middleware 11g: Build Java EE Applications A - 76

Oracle University and Egabi Solutions use only

9) Save and compile the Model project.

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 10-2: Testing the Web Service by using JDeveloper

In this practice, you test the Web service that you created in your previous practice by using Oracle JDeveloper 11g. 1) Right-click org.demo.business > ValidateCreditCardService and select Test Web Service. 2) You see the HTTP Analyzer: Unsent Message pane being displayed. Add the following values to the respective parameters and click the Send Request button. arg0:string arg1:int AMEX 123456789

3) In the right pane, you see the value of the arg0 response parameter being displayed as Valid credit card.

4) Click Copy Request in the left pane and modify the parameters to something like VISA and 12345678989, and then click Send Request. You see Invalid credit card type or credit card number in the response pane. 5) Close the application and remove it from the IDE when you are done.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 77

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practices for Lesson 11


In an earlier practice, you completed the FOD Storefront model with entities for Products and Categories. Next you move on to building the user interface for your application. The first part, building the UI, is to create a managed bean that will serve as the interface to the Session Faade. This behavior of this bean is similar to the Sample Java Test Client you built in a previous practice. After you build the managed bean, you create a page that shows a tree of Categories and a list of Products.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 78

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 11-1: Creating the ProductBrowsing Managed Bean


1) Open Application_11.jws.

In this practice, you create a managed bean that provides an interface between the client UI and the Session Faade. 2) In the UI project, create a new Java class named ProductBrowsingBean, in the oracle.ui.backing package. Make it public with a default constructor. The code should look something like the following:
package oracle.ui.backing;

The first thing you need in the bean is a method that will find and return the SessionBean. Remember that the SessionBean is the object that you use to get access to all the underlying entity beans and methods. 3) Add the following code to the bean:
public SessionEJB11Local getSessionBean() throws NamingException { InitialContext ic = new InitialContext(); Object lookupObject = ic.lookup("java:comp/env/ejb/local/SessionEJB11"); return (SessionEJB11Local)lookupObject; }

4) Import the following two classes:


javax.naming.InitialContext javax.naming.NamingException

5) You will see that SessionEJB11Local is not found in the current active project because it is defined in the Model project. Add a Model project dependency to this project: a) Open the UI project properties. b) Select Dependencies. c) Click the Edit icon (pencil). d) Expand Model.jpr, select Build Output, and click OK. e) While you have the project properties open, add the following library in Libraries and Classpath.
Trinidad Runtime 11

f) Click OK. g) Select JSP Tag Libraries and add:


ADF Faces Components 11 Oracle Fusion Middleware 11g: Build Java EE Applications A - 79

Oracle University and Egabi Solutions use only

public class ProductBrowsingBean { public ProductBrowsingBean() { } }

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 11-1: Creating the ProductBrowsing Managed Bean (continued)


h) Click OK and close the Project Properties. 6) Press and hold Alt + Enter to add the import for oracle.services.SessionEJB11Local. 7) Before your code can lookup the session bean, it must be registered with Web.xml. a) Open Web Content > WEB-INF > web.xml. b) On the Overview page, click References. c) Expand EJB References e) Complete the entry as follows: Field Name EJB Name Interface Type EJB Type Home Interface Local/Remote Interface EJB Link Value
ejb/local/SessionEJB11

Local Session (leave blank)


oracle.services.SessionEJB11Local

SessionEJB11

f) Save your work and close web.xml. The page you are going to build later in this practice contains a tree of Categories. The root of this tree is based on the NamedQuery you created earlier that returns all Categories that do not have a parent. The Leaf of the tree will be from the children OneToMany relationship within a Category. The UI you will be building uses a TreeModel object as the source of data for the tree component. The TreeModel object has a method that accepts the root objects and traverses the OneToMany relationship to get their children. In the next few steps, you create the TreeModel object and write the methods to populate it. 8) Open ProductBrowsingBean.java. 9) Create a private variable treeModel of type TreeModel and import org.apache.myfaces.trinidad.model.TreeModel. 10) Right-click the variable and select Generate Accessors, choose only the get method and click OK. 11) In this getTreeModel method, you want to check if the treeModel is null and if it is, call the methods (which you will code next) to build the treeModel. The method should look something like:
public TreeModel getTreeModel() throws NamingException { if (treeModel == null) {

Oracle Fusion Middleware 11g: Build Java EE Applications A - 80

Oracle University and Egabi Solutions use only

d) Click the EJB References Plus icon at the right of the window.

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 11-1: Creating the ProductBrowsing Managed Bean (continued)


} return treeModel; }

12) If the treeModel is null, you need to create a List<Category> and set it to the results of a call to the NamedQuery queryCategoryFindRoot in the SessionBean. The code should look something like:

13) Import java.util.List and oracle.model.Category. 14) Because getSessionBean throws a NamingException, this method needs to throw it also. Click the Light bulb icon in the left column in the code editor and choose Add Exceptions to Method Header. 15) Add the code to set treeModel to the results of the query using ChildPropertyTreeModel(root, relationship). Remember the relationship of the Category to its children is named children. The completed method should look something like:
public TreeModel getTreeModel() throws NamingException { if (treeModel == null) { List<Category> categories = getSessionBean().queryCategoryFindRoot(); this.treeModel = new ChildPropertyTreeModel(categories, "children"); } return treeModel; }

16) Import org.apache.myfaces.trinidad.model.ChildPropertyTreeModel. 17) You now have a bean that will return the object required for a Tree component on a page. Before your page can use the bean, you have to register it with faces.config.xml. a) Open faces-config.xml in the visual editor. b) Add ProductBrowsingBean as a session scope managed bean. i) Click the Overview tab. ii) Select Managed Bean if it is not already selected.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 81

Oracle University and Egabi Solutions use only

public TreeModel getTreeModel() throws NamingException { if (treeModel == null) { List<Category> categories = getSessionBean().queryCategoryFindRoot(); } return treeModel; }

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 11-1: Creating the ProductBrowsing Managed Bean (continued)


iii) Click the Plus sign in the upper-right corner of the window. iv) In the Create Managed Bean dialog box, specify productBrowsingBean as the Bean Name. v) Set the class name to ProductBrowsingBean. vi) Set the package name to oracle.ui.backing. vii) Set the Scope to session. viii) Deselect Generate Class If It Does Not Exist. x) Save your work. 18) The productBrowsingBean is now registered as a managed bean and will be available to your pages. ix) Click OK to register the bean.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 82

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 11-2: Creating a JSF Page


In this practice, you create a JSF page that uses objects in the productBrowsingBean as sources of data. 1) Open faces-config.xml. 2) Create a JSF page: a) Click the Diagram tab. b) Drag a JSF Page from the Component Palette to the diagram. c) Name the component Main. Notice that the name shows as /Main on the page. e) Accept the default name, which is Main.jspx. f) If it is not selected, select Create as XML Document. g) Expand Page Implementation and choose to Automatically Expose UI Components in an Existing Bean, and select productBrowsingBean. By selecting the bean, JDeveloper will add variables and get and set methods to the bean for each component you add to your page. You probably will not need all of them, but it makes it easy to access values and components later. h) Click OK to create the page. 3) Add a Tree component to the page and populate it from the bean. a) In the Component Palette, select ADF Faces from the drop-down list at the top of the Palette. b) Drag a Tree component to the page and enter the following values: Field Id Value Var Value CategoryTree
#{productBrowsingBean.treeModel}

category

c) Click OK to add the component to the page. d) Expand af:tree categoryTree > Tree facets, in the Structure window. e) Drag an Output Text component to NodeStamp. f) In the Properties Inspector, set the Value property to:
#{category.categoryName}

4) You are now ready to run and test your page: a) Rebuild both the UI and Model projects. (Right-click the project and select Rebuild) b) Run the SessionEJB11Bean from the Model project. (Remember that the session bean is in the oracle.services package.) c) Click anywhere on your page and select Run.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 83

Oracle University and Egabi Solutions use only

d) Double-click Main. This opens the Create Page dialog box.

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 11-2: Creating a JSF Page (continued)


5) Your running page should look something like:

6) The page uses the treeModel component, which uses the SessionEJBBean methods to return a list of Categories and their children. For now, you just display the tree structure. In a later practice, you connect the results of the product table to the selected category. 7) When you are done, close the browser.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 84

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 11-3: Adding Products to the Page

In this practice, you add some layout components to the Main page, and then add a Table component that displays Products. You will also add the access methods to the managed bean. The completed Main page will look something like:

1) Open Main.jspx in the visual editor. 2) Drag a Layout > Panel Splitter to af:form in the Structure window. The Panel Splitter is what creates the two sections on the page: one for the Category Tree and the other for Products. 3) In the Properties Inspector, set the Splitter Position to 120. 4) Set the Style > Box > Width to 100 Percent. 5) Still in the Structure window, expand the Panel Splitter facets to show the first and second facets. 6) Add a Panel Accordion to the first facet. 7) Expand af:PanelAccordion and drag the af:tree - categoryTree component to the af:showDetailItem in the Structure window. 8) The Structure should look something like:

Oracle Fusion Middleware 11g: Build Java EE Applications A - 85

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 11-3: Adding Products to the Page (continued)


9) Select af:showDetailItem and set the Text property to Categories. 10) Add the Panel Group Layout component to the second facet. 11) Set the Layout property to horizontal. 12) Set the Style > Box > Width to 100 Percent. 13) Add a Panel Header to the af:panelGroupLayout. 14) Set the Text property to Products. 15) The Structure window should look something like:

Before you can add a table to display Products, you need to add the method to the productBrowsingBean. For now, you will add a method that returns all the Products. In a later practice, you will change it to return only the Products for a selected Category. 16) Open ProductBrowsingBean.java. 17) You should first notice that there have been a number of variables and methods added to the class. These are added as you create components on the page because the bean is registered as an automatic backing bean. 18) Add a method called getAllProducts that returns a List and throws NamingException.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 86

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 11-3: Adding Products to the Page (continued)


19) Use the queryProductFindAll() method on the Session bean to populate a List<Product> object. 20) Return the results. 21) You will need to import oracle.model.Product. 22) The code should look something like:
public List<Product> getAllProducts() throws NamingException{ List<Product> products = this.getSessionBean().queryProductFindAll(); return products; }

23) Save your work. Now that you have the method that returns Products, you can add the table to the page. 24) Open Main.jspx. 25) Add a Table component to af:panelHeader - Products in the Structure window. 26) In the Create ADF Faces Table dialog box, select Bind Data Now. 27) Click Browse for Table Data Collection. 28) Select productBrowsingBean.allProducts from the JSF Managed Beans list, and click OK. 29) Set the list of columns in the table to include only the following columns in this order: Product Name Description List Price Additional Info 30) Click OK. 31) Set the Id to productsTable. 32) Set Appearance > Column Stretching to Last. 33) Set the Style > Box > Width to 100 Percent. 34) Test the page. (Remember that the Session bean has to be running.)

Oracle Fusion Middleware 11g: Build Java EE Applications A - 87

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 11-3: Adding Products to the Page (continued)


35) The page should look something like:

Remember that you have not yet coordinated the two areas on the page. The Category tree shows all the Categories and children and the Products table displays all the Products. 36) When you are done, close the browser. You can also Close and remove the application from the IDE. 37) Stop the deployed application.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 88

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practices for Lesson 12


In this practice, you add a couple of pages to the application. One page will be used to edit a product and the other will be used to add a product. You will add navigation cases to the pages and navigation elements to each page so that the user can move easily between pages. You will create only the page and navigation for the Edit page but you will complete the Add page. In the next practice, you add the event mechanisms to complete the Edit page.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 89

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 12-1: Creating the Edit and Add Pages


1) Open Application_12. 2) Open faces-config.xml in the UI project.

In this practice, you create both the EditProduct and AddProduct pages. You also add the Navigation cases to the application page flow.

3) Add two JSF pages to the diagram. Name one AddProduct and the other EditProduct. 4) Orient the new objects to look something like this:

5) Double-click the EditProduct page to create an empty JSF page. Accept the default name, create it as an XML Document and do not automatically expose the UI components in a Managed Bean (in Page Implementation). 6) Go back to the faces-config.xml diagram. 7) Double-click the AddProduct page to create an empty JSF page. Accept the default name, create it as an XML Document. But this time, select the ProductBrowsingBean as the Managed Bean. IMPORTANT NOTE: If ProductBrowsingBean is not selectable, choose Do Not Automatically Expose UI Components in a Managed Bean. Then edit the source code of addProduct.jspx. Add the following line (in bold) near the bottom of the XML, just before the closing </jsp:root> tag:
</f:view> <!--oracle-jdev-comment:auto-binding-backing-beanname:productBrowsingBean--> </jsp:root>

Now that you have created the pages, you can add the Navigation Cases that control the page navigation. 8) Open the faces-config.xml diagram.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 90

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 12-1: Creating the Edit and Add Pages (continued)


9) Add the following Navigation Cases: From Page /Main.jspx /Main.jspx /EditProduct /AddProduct To Page /EditProduct.jspx /AddProduct.jspx /Main.jspx /Main.jspx Name editProduct addProduct success success

10) The diagram should now look something like:

Now that the navigation is in place, you can start working on building the AddProduct page.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 91

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 12-2: Building the AddProduct Page

In this practice, you add the data components and the necessary managed bean code to complete the AddProduct page. The page can be accessed from a button on the Main page, which you also add. 1) Open AddProduct.jspx and go to the Design tab. 2) Add the ADF Faces layout components to the page. a) Drag a Panel Header to the page and set Text to Add Product. b) Drag a Panel Form Layout to the af:panelHeader. (You can drag it to the Structure window.) 3) Next, add Input Text components to the af:panelFormLayout as follows: Id npName npDescription npAdditionalInfo npListPrice npMinPrice npCostPrice Label Name Description Additional Information List Price Minimum Price Cost Price

4) The page and Structure window should look something like:

5) Right-click anywhere on the page and select Run to run the page and see how it looks.
Oracle Fusion Middleware 11g: Build Java EE Applications A - 92

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

6) The page should look something like:

Practice 12-2: Building the AddProduct Page (continued)

Oracle Fusion Middleware 11g: Build Java EE Applications A - 93

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 12-3: Creating the Add Product Functionality

Now that you have a page skeleton with fields, you add the code and buttons to the page that make the Add Product work. The way the page works is that once a user navigates to the AddProduct page, he or she enters values in the six fields, and then click an Add Product button which calls a method to persist the data and navigate back to the Main page. 1) Still on the AddProduct page, add an ADF Faces Toolbar to the Panel Form Layout facets > footer. 2) Add an ADF Faces Toolbar Button to the toolbar. 3) Change the Text to Save and the Id to addProduct. 4) Double-click the Save button. In the Bind Action Property dialog box, ensure that the Managed Bean is productBrowsingBean, change the Method to addProduct, and then click OK. The editor opens productBrowsingBean at the new method. In the next few steps, you add code that uses the values stored in the managed bean that correspond to each of the fields in the form (npName, npDescription, and so on) to create a new product. The code then persists that new row. Because the page you are building contains a subset of all the columns in the table, you will set default values for a number of the columns. 5) Create default values in the addProduct() method for the following columns: Type String String Long Long String Category Attribute Name url shippingClassCode supplierId warrantyMonths status category Value images/17.jpg CLASS1 123L 12L Null Null

6) Add code that uses the Product constructor to create a new Product object named newProduct. The values for the Product constructor arguments come from either the default values you just added or the values from the page. Remember the field values are stored in the managed bean, so they are accessible by name (npName, npDescription, and so on). You can look at the Product constructor in the Model project to see what arguments are used. However, you can also use the following code.
Product newProduct = new Product( (String).getNpAdditionalInfo().getValue() ,category ,Double.parseDouble(getNpCostPrice() .getValue().toString()) ,getNpDescription().getValue().toString() ,url ,Double.parseDouble(getNpListPrice() .getValue().toString())

Oracle Fusion Middleware 11g: Build Java EE Applications A - 94

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 12-3: Creating the Add Product Functionality (continued)


,Double.parseDouble(getNpMinPrice() .getValue().toString()) ,getNpName().getValue().toString() ,shippingClassCode ,supplierId

,warrantyMonths);

7) Now that you have a new Product object, you can add a try-catch block to persist the new Product. a) In the try block, call persistEntity on the SessionBean passing newProduct as an argument. This is where the object is persisted to the database. b) Next set the status variable to success. c) In the catch block, set the status to fail. d) Next change the return statement to return status. That should complete the code for the AddProduct page. The completed method should look something like:
public String addProduct() { String url = "images/17.jpg"; String shippingClassCode = "CLASS1"; Long supplierId = 123L; Long warrantyMonths = 12L; String status = null; Category category = null; Product newProduct = new Product( (String)getNpAdditionalInfo().getValue() , category , Double.parseDouble(getNpCostPrice().getValue().toString()) , getNpDescription().getValue().toString() , url , Double.parseDouble(getNpListPrice().getValue().toString()) , Double.parseDouble(getNpMinPrice().getValue().toString()) , getNpName().getValue().toString() , shippingClassCode , supplierId , warrantyMonths ); try { getSessionBean().persistEntity(newProduct); status = "success"; } catch (Exception ex) { ex.printStackTrace(); status = "fail"; } finally { } return status; }

8) Compile and save your work.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 95

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 12-3: Creating the Add Product Functionality (continued)


9) Open Main.jspx. 10) Add a Button to the toolbar facet of the Products Panel Header. 11) Set the Id to addProductButton and the Text to Add a Product.

Next you need to add a button to the Main page that will navigate to the AddProduct page.

12) Set the Action to addProduct. (This is the Navigation Case that references the AddProduct.jspx page.) 13) Run Main.jspx from the faces.config.xml diagram. 14) Click Add a Product. 15) On the Add Product page, enter any values you want. Use values that you will be able to recognize when you go back to the main page. Also, use valid values for the number fields. 16) When you have finished adding values, click Save. 17) You will now be back on the Main page. Use the scroll bars to scroll down to find the row you just added. 18) Click Add Product again and notice that the values you entered for the new row are still in the form. That is because the form fields are persisted in the managed bean. 19) When you are done, close the browser. In the next few steps, you create a method that resets those fields. You can then create a Cancel button and method that calls the reset method and returns to the Main page. 20) In the productBrowsingBean, create a resetAddProductFields() method that calls resetValue() on each of the fields on the page. The completed code should look something like:
private void resetAddProductFields() { getNpName().resetValue(); getNpDescription().resetValue(); getNpAdditionalInfo().resetValue(); getNpListPrice().resetValue(); getNpMinPrice().resetValue(); getNpCostPrice().resetValue(); }

21) The first use of this method is to reset the values after a successful persist of the values. Add a call to this method to the addProduct() method, just after persistEntity(newProduct). 22) Now add a Toolbar button to the AddProducts page which calls resetAddProductsFields() and returns success. This will clear the fields and return to the Main page.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 96

Oracle University and Egabi Solutions use only

Now you can test the page to see that you can add a Product.

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 12-3: Creating the Add Product Functionality (continued)


b) Set the Id to cancelButton and Text to Cancel.

a) Add a Toolbar button to the right of the Save button. (It may be easier to drag it to the Structure window.) c) Double-click the button to create the cancelButton_action method in the productBrowsingBean. d) Add code to this method to call resetAddProductsFields() and return success. e) The code should look something like:
public String cancelButton_action() { resetAddProductFields(); return "success"; }

23) Compile, save, and test the page. a) Add another Product and save it. b) Start to add another Product and click Cancel instead of Save. 24) When you are done, close the browser. 25) You may also close the application and remove it from the IDE. 26) Stop the running application.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 97

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practices for Lesson 13


The application you have built so far has not accounted for selecting a category in the Category tree or the coordinated display of Products. In the completed application, the user clicks a category in the tree and the products within that category are displayed in the Products section of the page. From the Products section, the user can choose to either add a product or can click a product and edit it. To add a product, the product should be added to the currently selected Category. This is one part of the application that you did not add in the previous practice.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 98

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 13-1: Adding the Category Tree Selection Event

In this practice, you create a SelectionListener for the Category Tree. This listener will determine which category the user has selected, and then set a class variable to the selected category. You also modify the Products table to get its data from a new method that retrieves the products for the selected category. 1) Open Application_13.jws. 2) Open Main.jspx. 3) Select the af:tree component in either the Structure window or the Design editor. 5) Set SelectionListener to categoryTreeSelectionListener. This also adds the method to productsBrowsingBean. 6) Open productBrowsingBean.java. 7) Add a private class variable to hold the selected Category. Name it selectedCategory and create a default get method using Generate Accessors. The variable declaration should look like the following:
private Category selectedCategory;

8) Locate the categoryTreeSelectionListener() method you just created. (It will probably be at the bottom of the class.) 9) The technique for retrieving the selected row from the tree is not difficult, but it requires using methods that belong to a UIXTree component. 10) The first thing you need to do is get the current instance of the UIXTree. Remember the bean has get and set methods for all of the components on the page. The code is:
public void categoryTreeSelectionListener (SelectionEvent selectionEvent) { // Add event code here... UIXTree treeTable = getCategoryTree(); }

11) Import org.apache.myfaces.trinidad.component.UIXTree. 12) Because of the native behavior of the component, you need to create an Iterator of selectedRowKeys from the treeTable. Note that even though our UI supports only one row selection, the component supports multiple selections; therefore, we have to use the iterator.
public void categoryTreeSelectionListener (SelectionEvent selectionEvent) { // Add event code here... UIXTree treeTable = getCategoryTree(); Iterator selection = treeTable.getSelectedRowKeys().iterator();

13) Import java.util.Iterator.


Oracle Fusion Middleware 11g: Build Java EE Applications A - 99

Oracle University and Egabi Solutions use only

4) In the Properties Inspector, set Behavior > RowSelection to single.

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 13-1: Adding the Category Tree Selection Event (continued)

14) Next you loop through the iterator (knowing there should only be one row). You get the selection Object, and use it as a rowKey. You then call setRowKey(rowKey) on the treeTable. After that is set, you set this.selectedCategory to treeTable.getRowData() cast to a Category object. The code should look something like:
public void categoryTreeSelectionListener (SelectionEvent selectionEvent) { // Add event code here... UIXTree treeTable = getCategoryTree(); Iterator selection = treeTable.getSelectedRowKeys().iterator(); for (;selection.hasNext();) { Object rowKey = selection.next(); System.out.println("Here is the rowKey: " + rowKey); treeTable.setRowKey(rowKey); this.selectedCategory = (Category)treeTable.getRowData(); }

With this listener code, you can now know what category the user selects. With that information, you then populate the products table with only the related products. In the next few steps, you create a method that returns a list of products for the selected category. 15) Create a method that returns a List<Product> named getProductsForSelectedCategory. The method should throw a NamingException.
public List<Product> getProductsForSelectedCategory() throws NamingException { }

16) In the method, check whether this.selectedCategory is not null and if it is not, return the results of a call to getProductList() in the selected category. If it is null, return Collection.emptyList().
public List<Product> getProductsForSelectedCategory() throws NamingException { if (this.selectedCategory != null) { return this.selectedCategory.getProductList(); } else { return Collections.emptyList(); }

17) Import java.util.Collections. 18) Compile and save your work. Now that you have a method that returns the related categories, you just need to modify the products table to use it.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 100

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 13-1: Adding the Category Tree Selection Event (continued)


19) Open Main.jspx. 20) Select the productsTable and change the Value attribute to use productsForSelectedCategory. Note: Use the Expression Builder to select this method. 21) Set the Partial Trigger (under Behavior) to use categoryTree. a) Click the arrow to the right of the PartialTrigger property and select Edit. b) In the Edit property dialog box, expand the facet (first) to find tree categoryTree. c) Shuttle it to the Selected pane and click OK. 22) Run and test the page. You will see that as you click a category, the products within that category are displayed. The last thing you need to do is coordinate the Add Product page with the currently selected category. In other words, when the user adds a product, the product will be defaulted to the currently selected category. You also want to disable the Add Product button when there is no category selected. Because we want any new products to be within a selected category, you need to ensure that the user can only go to the Add Product page if there is a selected category. 23) To disable the button, you need to create a method in the managed bean named isAddProductButtonDisabled that returns a boolean:
public boolean isAddProductButtonDisabled () { return true; }

24) You want to add code that returns true if selectedCategory is null or if the selectedCategory does not have children. The code looks like:
public boolean isAddProductButtonDisabled () { return (selectedCategory == null || !selectedCategory.getChildren().isEmpty()); }

25) Now that you have the method, bind the Disabled property to the method. a) Click the Add a Product button in Main.jspx. b) Click the Expression Builder on the Behavior > Disabled property. c) Select addProductButtonDisabled in the Expression Builder. (You added it to the productBrowsingBean.) d) Click OK. e) Set the Partial Trigger property to categoryTree using Edit. 26) Run the main page and notice that the button is disabled until you select a leaf node category in the tree.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 101

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 13-1: Adding the Category Tree Selection Event (continued)


27) Open productBrowsingBean.java. 28) Find the addProduct() method.

Now that the button only works when a category is selected, you must use that category on the Add Product page.

29) Change the category variable definition from initializing to null to initializing to the selectedCategory. Now that you are attaching a product to a specific category (it used to be null), you need to call the addProduct() on the selectedCategory before you persist the product. 30) Add the call to selectedCategory.addProduct(newProduct) to the try block just before the persist. 31) Run and test the application. Add several products to several different categories. 32) When you are done, close the browser. Each of the fields on the AddProduct page is mandatory. The last step in creating the AddProduct page is to add validation to the fields. 33) Open AddProduct.jspx. 34) To apply the following validations from the Structure window, right-click Insert Inside (field) > ADF Faces. Add appropriate text for Hints and Messages. Field Name Description Additional Information Validator Validate Length Validate Length Validate Length Rules Minimum 5, Maximum 30 Minimum 5, Maximum 3000 Minimum 5, Maximum 3000

35) Set the Behavior > Required property to True for each of the fields. 36) Run and test the page (remember to start with Main.jspx). a) Add products to several categories. b) Test the validators by entering less than the minimum length. c) Test the maximum length in the Name field. d) Try to add a product with one or more of the price fields blank or out of range. The Add Product page is now complete. In the next section, you add the Edit Page.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 102

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 13-2: Complete and Connect the Edit Product Page

In this practice, you complete and connect the Edit page to the main page. Before you add fields to the Edit page, you need to add the elements to the Main page that will allow the user to select a row to edit. That selection gesture will also navigate to the Edit page. 1) Open Main.jspx. 2) Select the Products table and set the Behavior > RowSelection property to single. 3) Expand af:column Product Name, right-click af:outputText, and choose Surround With. 5) Remove the default value of the Command Link Text. (That should reset the displayed value to ProductName.) 6) Set the Action property to editProduct. 7) Add a method to ProductBrowsingBean that returns the row data from the selected row. a) Open ProductBrowsingBean.java. b) Add a public method that returns a Product object from the ProductsTable using the getSelectedRowData() method. The code should look something like:
public Product getSelectedProduct () { return (Product)getProductsTable().getSelectedRowData(); }

You will use this method as the source data for the Edit page fields. Next, you add the fields and buttons to the Edit page. 8) Open EditProduct.jspx. 9) Add a Panel Header and set the Text property to Edit Product. 10) Add a Panel Form Layout. 11) Add a Toolbar to the Panel Form Layout footer facet. 12) Add a Toolbar Button to the Toolbar. Set the Text to Save. 13) Add Input Text components to the af:panelFormLayout as follows: Id prName prDescription prAdditionalInfo prListPrice prMinPrice prCostPrice Label Name Description Additional Information List Price Minimum Price Cost Price

Oracle Fusion Middleware 11g: Build Java EE Applications A - 103

Oracle University and Egabi Solutions use only

4) Choose Link and click OK.

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 13-2: Complete and Connect the Edit Product Page (continued)
14) The Structure window should look something like:

15) The page should look something like:

Next, you need to set the Value property of all the fields to get their data from selectedProduct (that is the method you added in the last section). 16) Select the Name field and set the Value property to:
#{productBrowsingBean.selectedProduct.productName}

17) You can use the Property Inspector or the Expression builder. 18) Set the rest of the fields to their corresponding attributes in selectedProduct. The last step is to create a method that persists the changes and to connect the Save and Cancel buttons. 19) Open productBrowsingBean.java. 20) Add a public method named updateProduct() which returns a String. 21) Add a try-catch block.
Oracle Fusion Middleware 11g: Build Java EE Applications A - 104

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 13-2: Complete and Connect the Edit Product Page (continued)
22) In the try block, call mergeEntity on the SessionBean and pass it this.getSelectedProduct(). Create a String variable named status. Set status to success after the call to mergeEntity. 23) Return status. 24) Add e.printStackTrace to the catch block followed by setting status to success. 25) The completed code should look something like:
public String updateProduct() { String status = null; try { this.getSessionBean().mergeEntity(this.getSelectedProduct()); status = "success"; } catch (NamingException e) { e.printStackTrace(); status = "success"; } return status; }

26) Set the Save button to call updateProduct(). a) Open EditProduct.jspx. b) Double-click the Save button. c) In the Bind Action Property dialog box, choose producBrowsingBean and updateProduct as the method. d) Click OK. 27) Run Main.jspx to test your Edit page. a) Select a category and any product. b) Make changes to the product and click Save. c) Check whether the changes show in the Product table. 28) When you are done, close the browser. 29) You may also close the application and remove it from the IDE.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 105

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practices for Lesson 14


In this practice, you create a message-driven JMS application to send emails to notify the users. You perform the following set of tasks in this practice set: Creating a JMS connection factory and a queue destination by using the WebLogic Server Administration Console Creating a message-driven bean that accepts messages sent to the JMS queue and sends emails based on those messages. You use Oracle JDeveloper as the development tool to develop the message bean Creating a business method in a session bean that sends messages to the JMS queue when an email message needs to be sent Creating a sample test client in JDeveloper to test the behavior of the confirmation email by creating a service request

Oracle Fusion Middleware 11g: Build Java EE Applications A - 106

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 14-1: Creating a JMS Connection Factory and Queue Destination in WebLogic Server

A JMS server implements the JMS infrastructure on a WebLogic server. Destinations (queues or topics) are targeted to a WebLogic server that has the JMS server configured. In this practice, you configure a JMS server, a JMS module, a Connection Factory, and a queue. 1) Open Application14.jws. 2) In the Menu, select Run > Start Server Instance. 3) Configure a WebLogic JMS Server by using the WebLogic Server Administration Console. a) Open a browser and enter http://127.0.0.1:7101/console. b) Log in to the WebLogic Server Administration Console using weblogic/weblogic. c) On the Home page, click JMS Servers under the Services of Domain Configurations section. d) Click New under the JMS Servers table to create a new JMS Server. e) Specify the following properties and click Next: Name: MyJMSServer Persistent Store: none f) Select DefaultServer as the target JMS server. Click Finish. 4) Configure a JMS module and a queue. a) In the WebLogic Server Administration Console, navigate to DefaultDomain > Services > Messaging > JMS Modules. b) Click New in the JMS Modules table and specify the following properties and click Next. Name: MyJMSModule Descriptor File Name: MyJMSModule c) Select DefaultServer as the target. Click Next. d) Select the Would you like to add resources to this JMS system module check box, and click Finish. e) In the Settings for the MyJMSModule page, click the Subdeployments tab. f) In the Subdeployments table, click New. Enter MyJMSSubmodule as the Subdeployment Name and click Next. g) On the Targets page, select the MyJMSServer as the target under the JMS Servers table. Click Finish. h) Click the Configuration tab.
Oracle Fusion Middleware 11g: Build Java EE Applications A - 107

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 14-1: Creating a JMS Connection Factory and Queue Destination in WebLogic Server (continued)
i) On the Settings for MyJMSModule page, under the Summary of Resources table, click New to configure a new connection factory for the JMS module. j) On the Create a New JMS System Module Resource page, under Choose the type of resource you want to create, select Connection Factory, and then click Next. k) In Connection Factory Properties, specify the following parameters and click Next. Name: demoConnectionFactory JNDI name: weblogic.jms.demoConnectionFactory l) Select Advanced Targeting. Select MyJMSSubmodule from the subdeployments list. Click Finish. m) On the Settings for MyJMSModule page, under the Summary of Resources table, click New to configure a new JMS queue for the JMS module. n) On the Create a New JMS System Module Resource page, under Choose the type of resource you want to create, select Queue, and then click Next. o) In JMS Destination Properties, specify the following parameters and click Next. Name: demoQueue JNDI name: weblogic.jms.demoQueue Template: None p) Select MyJMSSubmodule from the subdeployments list. Click Finish. 5) Confirm the registration of weblogic.jms.demoConnectionFactory and weblogic.jms.demoQueue in the WebLogic Servers JNDI tree. a) Navigate to the Home page. On the Home page, under Environment, click Servers to get to the Summary of Servers. In the table of servers, click DefaultServer. b) On the Settings for DefaultServer page, click the View JNDI Tree link. c) The JNDI Tree opens in another window or tab. In that tab, notice the JNDI entries of weblogic.jms.demoConnectionFactory and weblogic.jms.demoQueue. Note: Expand DefaultServer > weblogic > jms in the JNDI Tree Structure to view the connection factory and the queue.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 108

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 14-2: Creating a Message-Driven Bean to Send Emails


In this practice, you create a message-driven bean that accepts messages from the JMS resource jms/demoQueue and sends out email messages to an SMTP server using the Java Email API.

1) In the Model project, create a message-driven bean called SendMailMessage in the org.demo.business package using the JDeveloper wizard. Use the following details to accomplish this task: Step Screen/Page Description a. Applications Navigator b. c. New Gallery Create MessageDriven Bean Step 2 of 4 Create MessageDriven Bean Step 3 of 4 Choices or Values Right-click Application_14 > Model. Select New. Categories: Business Tier > EJB Items: Message-Driven Bean Click OK. EJB Name: SendMailMessage Transaction Type: Container (verify) Mapped Name: weblogic.jms.demoQueue Click Next. Bean Class:
org.demo.business.SendMailMessageBean

e.

Click Finish.

2) Modify the @MessageDriven annotation to specify the use of the JMS resource jms/demoQueue by including an activationConfig that has three properties:
connectionFactoryJNDIName = weblogic.jms.demoConnectionFactory destinationName = weblogic.jms.demoQueue destinationType = javax.jms.Queue

Note: Ensure that the following classes are imported:


javax.ejb.MessageDriven javax.ejb.ActivationConfigProperty import javax.ejb.ActivationConfigProperty; ... @MessageDriven( mappedName = "weblogic.jms.demoQueue", name = "SendMailMessageBean", activationConfig = { @ActivationConfigProperty( propertyName = "connectionFactoryJndiName",
propertyValue = "weblogic.jms.demoConnectionFactory"),

@ActivationConfigProperty( propertyName = "destinationName",

Oracle Fusion Middleware 11g: Build Java EE Applications A - 109

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 14-2: Creating a Message-Driven Bean to Send Emails (continued)


propertyValue = "demoQueue"), @ActivationConfigProperty( propertyName = "destinationType", propertyValue = "javax.jms.Queue") }) public class SendMailMessageBean implements MessageListener {

Hint: Import the required packages.


import javax.mail.Session; import java.util.Properties; ... public class SendMailMessageBean implements MessageListener { public void onMessage(Message message) { Properties props = new Properties(); props.put("mail.smtp.host", "srdemo.org"); Session session = Session.getInstance(props); ...

Note: If there are any errors in importing the javax.mail.* package, add the Java EE 1.5 library to the Model project. Execute the following set of tasks to add the library: i. ii. Right-click Model and select Project Properties from the shortcut menu. In the Project Properties window, select Libraries and Classpath in the left pane of the window. You can see classpath entries and the libraries description of the default project libraries in the right pane. Click the Add Library button. Select Java EE 1.5 from the Add Library window and click OK. The library is added to the Model project.

iii.

4) In a try-catch block, create the from, to, subject, and content String variables and use them to store corresponding properties from the message parameter. Use these variables and the current date to construct a javax.mail.Message using the MimeMessage implementation class. Send the message using javax.mail.Transport. Note: Ensure that the required classes are imported from the javax.mail and javax.mail.internet packages.
import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage;

Oracle Fusion Middleware 11g: Build Java EE Applications A - 110

Oracle University and Egabi Solutions use only

3) In the onMessage()method, declare a new variable called prop whose type is java.util.Properties. With the Properties.put() method, add the mail.smtp.host property name with a value of srdemo.org as a name-value pair property to the prop object, and get a javax.mail.Session using that property.

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 14-2: Creating a Message-Driven Bean to Send Emails (continued)


... public void onMessage(Message message) { Properties props = new Properties(); props.put("mail.smtp.host", "srdemo.org"); Session session = Session.getInstance(props); try { String from = message.getStringProperty("from"); String to = message.getStringProperty("to"); String subject = message.getStringProperty("subject"); String content = message.getStringProperty("content"); javax.mail.Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); InternetAddress[] address = {new InternetAddress(to)}; msg.setRecipients( javax.mail.Message.RecipientType.TO, address); msg.setSubject(subject); msg.setSentDate(new java.util.Date()); msg.setContent(content, "text/html"); Transport.send(msg); } catch (Throwable ex) { ex.printStackTrace(); } }

5) Save and compile the message-driven bean.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 111

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 14-3: Creating a Session Method for Sending Email Messages


In this practice, you add a general-purpose sendMailMessage method to the ServiceRequestSessionBean bean that is used to send JMS messages to the weblogic.jms.demoQueue JNDI resource for processing by the message-driven bean created in the preceding task. 1) Edit ServiceRequestSessionBean.java and add a SendMailMessage() method that accepts four String parameters: from, to, subject, and content.
... public void sendMailMessage(String from, String to, String subject, String content) { } ...

2) In a try-catch block, use JNDI to look up the name, weblogic.jms.demoConnectionFactory, and use it to create and start a connection. Note: Be sure to import the following interfaces: javax.jms.Connection, javax.jms.ConnectionFactory, and javax.naming.InitialContext.
... public void sendMailMessage(String from, String to, String subject, String content) { try { System.out.println("Looking up CF"); ConnectionFactory connectionFactory =
(ConnectionFactory) new InitialContext() .lookup("weblogic.jms.demoConnectionFactory");

Connection connection = connectionFactory.createConnection(); connection.start(); } catch (Throwable ex) { ex.printStackTrace(); } } ...

3) Use the connection to start a JMS Session. Then perform a JNDI lookup for the weblogic.jms.demoQueue name to create a JMS Destination; typecast the result of the JNDI lookup as a Queue. Finally, use the JMS Session and JMS Destination to create a JMS MessageProducer. Note: Be sure to import the following interfaces: javax.jms.Session, javax.jms.Destination, and javax.jms.MessageProducer.
... public void sendMailMessage(String from, String to, String subject, String content) { try { ... connection.start(); System.out.println("Starting Queue Session"); Oracle Fusion Middleware 11g: Build Java EE Applications A - 112

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 14-3: Creating a Session Method for Sending Email Messages (continued)
Session queueSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination queue = (Queue) new InitialContext() .lookup("weblogic.jms.demoQueue");

MessageProducer publisher = queueSession.createProducer(queue); } ...

Note: Be sure to import the javax.jms.Message interface.


... public void sendMailMessage(String from, String to, String subject, String content) { try { ... MessageProducer publisher = queueSession.createProducer(queue); Message message = queueSession.createMessage(); message.setJMSType("MailMessage"); message.setStringProperty("from", from); message.setStringProperty("to", to); message.setStringProperty("subject", subject); message.setStringProperty("content", content); } ...

5) Send the message with the MessageProducer, and then close the MessageProducer, the Session, and the Connection.
... public void sendMailMessage(String from, String to, String subject, String content) { try { ... Message message = queueSession.createMessage(); message.setJMSType("MailMessage"); message.setStringProperty("from", from); message.setStringProperty("to", to); message.setStringProperty("subject", subject); message.setStringProperty("content", content); publisher.send(message); System.out.println("Message Sent to JMS Queue"); publisher.close(); queueSession.close(); connection.close(); } Oracle Fusion Middleware 11g: Build Java EE Applications A - 113

Oracle University and Egabi Solutions use only

4) Create a JMS Message with the JMS Session. Call the setJMSType() method of the Message instance to set its parameter string to MailMessage, and set String properties for from, to, subject, and content using the corresponding method parameters.

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 14-3: Creating a Session Method for Sending Email Messages (continued)
...

6) Modify the local and remote interfaces for the Session Facade to include the signature for the sendMailMessage method. In ServiceRequestSession.java and ServiceRequestSessionLocal.java, add the following code:
... void sendMailMessage(String from, String to, String subject, String content); ...

Oracle Fusion Middleware 11g: Build Java EE Applications A - 114

Oracle University and Egabi Solutions use only

7) Save and compile the Model project.

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 14-4: Creating a Sample Test Client in JDeveloper

In this practice, you create a sample test client in JDeveloper to create a service request and test the SendMailMessage() method of the ServiceRequestSessionBean.java. After the application sends an email confirmation, you use an email client to verify receipt of the confirmation email. 1) Generate a sample Java client to test the ServiceRequestSessionBean. a) In the Application Navigator, right-click ServiceRequestSessionBean.java and select the New Sample Java Client option from the shortcut menu. b) In the Create Sample Java Client window, specify the following details and click OK. Client Project: Model.jpr Client Class Name:
org.demo.client.ServiceRequestSessionClient

Application Server Connection: IntegratedWLSConnection 2) Add and implement the confirmByEmail() method in the ServiceRequestSessionClient.java. The method creates the email message and invokes the SendMailMessage() method.
import org.demo.business.ServiceRequestSession; ... public class ServiceRequestSessionClient { ...
public static void confirmByEmail(ServiceRequestSession message) { System.out.println("*** Confirm By Email requested for Service Request Id: \"SKING11296\""); try { String from = "support@srdemo.org"; String to = "steve.king@srdemo.org"; String subject = "Notification: OrderID #SKING11296 Created"; String msgText = "<html>" + "<body>" + "<h2>OrderID #SKING11296 Created</h2>" + "<p>Dear Steve,</p>" + "<p>Thanks for submitting the order. Your ordered has been entered into our system, and will be processed in a couple of days.</p>" + "<p>Yours sincerely,<br>Support</p>" + "</body></html>"; System.out.println("*** before sendMailMessage "); message.sendMailMessage(from, to, subject, msgText); } catch (Exception e) { System.out.println(e.toString()); }

Oracle Fusion Middleware 11g: Build Java EE Applications A - 115

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 14-4: Creating a Sample Test Client in JDeveloper (continued)


} ...

3) Modify the main() method of the ServiceRequestSessionClient class to invoke the confirmByEmail() method.
... public static void main(String[] args) { try { final Context context = getInitialContext(); ServiceRequestSession serviceRequestSession =
(ServiceRequestSession)context.lookup("ServiceRequestSessionEJB#org. demo.business.ServiceRequestSession");

confirmByEmail(serviceRequestSession); System.out.println("Mail Sent...."); } catch (Exception ex) { ex.printStackTrace(); } } ...

4) Save and compile the Model project

Oracle Fusion Middleware 11g: Build Java EE Applications A - 116

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 14-5: Testing the Confirmation Email


In this practice, you execute ServiceRequestSessionBean on integrated WebLogic server, and test the bean by using the sample ServiceRequestSessionClient Java client. You also use an email client to verify receipt of the confirmation email. 1) Execute the ServiceRequestSessionBean on the integrated WebLogic server. a) In the Application navigator pane, right-click ServiceRequestSessionBean .java and select the Run option from the shortcut menu.

2) Execute the sample Java client. a) In the Application navigator pane, right-click ServiceRequestSessionClient .java and select the Run option from the shortcut menu. b) Observe the Log pane for the successful execution of the client. Note: Click the Running:DefaultServer tab in the Log pane to verify the successful delivery of the message to the client. You can see the following message on the successful execution of the application: Looking up CF Starting Queue Session Message Sent to JMS Queue 3) Start Outlook Express application window, and view the email messages for Steve King. Use the information in the following table to perform this task or use the screenshots after the table as a guide: Step Screen/Page Description a. Outlook Express - Main Identity b. Login - soademo.org c. Outlook Express - Main Identity Choices or Values Click the Send/Recv icon on the toolbar. User Name: steve.king Password: oracle Click OK. In the Email section, confirm that there is an unread mail message.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 117

Oracle University and Egabi Solutions use only

b) Observe the Message:Log pane for the successful deployment of the bean to the WebLogic Server.

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practices for Lesson 15


In this practice, you open and modify a simple JSF application that enables book records to be inserted, updated, and deleted from the database. The JSF application uses a session-scoped backing bean to interact with an instance of the BooksFacadeEJBBean stateful session bean, which executes the persistence and transactional logic. You perform the following set of tasks in this practice set: Executing the application to observe the default container-managed transaction rules applied, and modifying the transaction attributes Modifying the BooksFacadeEJBBean class to use an EJB clients transactional context. It enables the beans methods to be invoked by a clients in its own transactional context.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 118

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 15-1: Working with Container-Managed Transactions


In this practice, you open the Application_15.jws workspace to examine the container-managed transaction annotations, and run the application with the default container settings. 1) Open Application_15.jws. 2) In the Model project, open the BooksFacadeEJBBean.java source in the org.demo.business package. 3) In BooksFacadeEJBBean.java, in the line after the @Stateful (name =
"BooksFacadeEJB", mappedName = "BooksFacadeSessionEJB") annotation text, add the @TransactionManagement annotation with a value of TransactionManagementType.CONTAINER as its parameter, and the @TransactionAttribute annotation with its parameter set to TransactionAttributeType.REQUIRED. Import the required packages to

support the annotations. Compile the class.

import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.ejb.TransactionManagement; import javax.ejb.TransactionManagementType; ... @Stateful(name = "BooksFacadeEJB", mappedName = "BooksFacadeSessionEJB") @TransactionManagement(TransactionManagementType.CONTAINER) @TransactionAttribute(TransactionAttributeType.REQUIRED) public class BooksFacadeEJBBean implements BooksFacadeEJB, ProductsFacadeEJBLocal { ... }

4) Save and compile BooksFacadeEJBBean. 5) Execute the application. In the ViewController project, run ListBooks.jsp. In the Add Product window, use the Product ID, Name, and Description fields to insert, update, and delete product data in/from the BOOKS database table by clicking the appropriate button. a) Insert a new product with the following details: Book ID: 200 Book Name: Pride and Prejudice Genre: Romantic comedy, Novel of manners. Click Insert. Verify that the new row is visible in the Book List when the page is updated. b) The newly inserted record should be visible in the HTML under the Book List heading.
Oracle Fusion Middleware 11g: Build Java EE Applications A - 119

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 15-1: Working with Container-Managed Transactions (continued)

A new record is always visible to the session that inserted it. Check whether the new book has been committedthat is, it is visible to other users. This can be done by executing the following SELECT statement in a SQL Worksheet window:
SELECT * FROM BOOKS

To access the SQL Worksheet, right-click the fod database connection on the JDeveloper Database Navigator tabbed page and select SQL Worksheet. 6) Close the browser window and terminate the Integrated Oracle WebLogic Server in JDeveloper. Hint: In JDeveloper, terminate the WebLogic Server by selecting Run > Terminate > DefaultServer.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 120

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 15-2: Working with EJB Client's Transactional Context

In this practice, you execute the session beans methods within a JSF clients transactional context. The JSF client starts a transaction and calls the session beans methods within its transactional context. You use javax.transaction.UserTransaction, which is part of the Java Transaction API (JTA) to demarcate the boundaries of a transaction explicitly. 1) Open the BooksFacadeEJBBean.java source in the org.demo.business package. 2) In BooksFacadeEJBBean.java, change the @TransactionAttribute annotation with its parameter set to TransactionAttributeType.SUPPORTS. The SUPPORTS attribute implies that the bean method inherits the transactional context of the caller. Compile the class.
import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.ejb.TransactionManagement; import javax.ejb.TransactionManagementType; ... @Stateful(name = "BooksFacadeEJB", mappedName = "BooksFacadeSessionEJB") @TransactionManagement(TransactionManagementType.CONTAINER) @TransactionAttribute(TransactionAttributeType.SUPPORTS) public class BooksFacadeEJBBean implements BooksFacadeEJB, ProductsFacadeEJBLocal { ... }

3) Save and compile BooksFacadeEJBBean. 4) In the ViewController project, open the ListBooks.java source in the org.demo.view.backing package. In ListBooks.java add the following code that implements the JTA transactional APIs to enable the JSF client to start and end a transactional context, and call the BooksFacadeEJBBean session bean.
a)

Declare a private UserTransaction instance variable named userTx. You need to include an import statement for javax.transaction.UserTransaction.
... private private private private ... List<Books> books; BooksFacadeEJB BooksFacade; HtmlDataTable dataTable1; UserTransaction userTx;

Oracle Fusion Middleware 11g: Build Java EE Applications A - 121

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 15-2: Working with EJB Client's Transactional Context (continued)


b) Add the code (in bold) in the constructor of the ListBooks class to use JNDI to return an Object reference to the UserTransaction object.
... public ListBooks() { InitialContext context = null; System.out.println("ListBooks()"); try { context = new InitialContext(); BooksFacade = (BooksFacadeEJB)context.lookup("BooksFacadeSessionEJB#org.demo .business.BooksFacadeEJB"); userTx = (UserTransaction)context.lookup("javax.transaction.UserTransac tion"); } catch (Exception e) { e.printStackTrace(); } } ...

c) Add the code (in bold) to start and commit/rollback a transaction for the insertBook() method, which in turn calls the session beans findBookById() and persistEntity() methods.
... public String insertBook() { try{ userTx.begin(); } catch(Exception e){ addMessage(e.getMessage(), true); } Books prod = new Books(); Long bkId = Long.parseLong(bookId.getValue().toString()); prod.setBookId(bkId); prod.setName(bookName.getValue().toString()); prod.setGenre(genre.getValue().toString()); List<Books> book = null;

Oracle Fusion Middleware 11g: Build Java EE Applications A - 122

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 15-2: Working with EJB Client's Transactional Context (continued)


book = BooksFacade.findBookById(bkId); if (book.size() == 1){ try { userTx.rollback(); addMessage("Book with ID " +
prod.getBookId() + " already exist", false);

} catch (Exception e){ addMessage(e.getMessage(), true); } } try{ System.out.println ("In insertBook() method....."); BooksFacade.persistEntity(prod); bookId.setValue(prod.getBookId()); userTx.commit(); addMessage("Book " + prod.getBookId() + " inserted", false); } catch (Exception e) { addMessage(e.getMessage(), true); } } return "success"; } ...

d) Add the code (in bold) to start and commit/rollback a transaction for the updateBook() method, which in turn calls the session beans findBookById() and mergeEntity() methods.
... public String updateBook() { List<Books> prods = null; Long bookId = (Long)this.bookId.getValue(); System.out.println("updateBook() bookId: " + bookId); try { userTx.begin(); prods = BooksFacade.findBookById(bookId); if (prods.size() == 1) { Books prod = prods.get(0); prod.setName((String)bookName.getValue()); prod.setGenre((String)genre.getValue()); BooksFacade.mergeEntity(prod); addMessage("Book " + prod.getBookId() + " updated", false); userTx.commit();

Oracle Fusion Middleware 11g: Build Java EE Applications A - 123

Oracle University and Egabi Solutions use only

else{

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 15-2: Working with EJB Client's Transactional Context (continued)


} else { addMessage("Book " + bookId + " not Found", false); userTx.rollback(); } } catch (Exception e) { addMessage(e.getMessage(), true); } return "success";

e) Add the code (in bold) to start and commit/rollback a transaction for the deleteBook() method, which in turn calls the session beans findBookById() and mergeEntity() methods.
... public String deleteBook() { List<Books> prods = null; Long bookId = (Long)this.bookId.getValue(); System.out.println("deleteBook() bookId: " + bookId); try { userTx.begin(); prods = BooksFacade.findBookById(bookId); if (prods.size() == 1) { Books prod = prods.get(0); BooksFacade.removeBooks(prod); addMessage("Book " + prod.getBookId() + " Deleted", false); userTx.commit(); } else { addMessage("Book " + bookId + " not found", false); userTx.rollback(); } } catch (Exception e) { addMessage(e.getMessage(), true); } return "success"; } ...

Oracle Fusion Middleware 11g: Build Java EE Applications A - 124

Oracle University and Egabi Solutions use only

} ...

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 15-2: Working with EJB Client's Transactional Context (continued)


f) Save and compile the JSF backing bean. 5) Run ListBooks.jsp. In the Add Product window, use the Product ID, Name, and Description fields to insert, update, and delete product data in/from the BOOKS database table by clicking the appropriate button. a) Insert a new product with the following details and an existing Book ID: Book ID: 200 Book Name: Pride and Prejudice Genre: Romantic comedy, Novel of manners. Click Insert. b) Verify that the book is not inserted and you see an appropriate error message on the Web page. 6) When you are done, close the browser. 7) You can also remove the application from the IDE.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 125

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practices for Lesson 16


In this practice, you secure a Web application by using JAAS in Oracle WebLogic Server. You perform the following set of tasks in this practice set: Enabling form-based login authentication for the Web application using the provided login and error JSP pages Restricting access to portions of the Web application by declaring security roles and URL-based security constraints in the application deployment descriptors Creating users and groups in WebLogic Server by using the WebLogic Server Administration Console Testing the login authentication and authorization functionality of the Web application

Oracle Fusion Middleware 11g: Build Java EE Applications A - 126

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 16-1: Enabling Form-based Login Authentication

In this practice, you enable form-based login authentication for a Web application. You modify the web.xml deployment descriptor file by creating the necessary login tags using a JDeveloper interface. 1) Open Application_16.jws. 2) Expand ViewController > Web Content > WEB-INF node, right-click web.xml select Properties. 3) In the Web Application Deployment Descriptor window, modify the Login Configuration properties to specify use of form-based authentication using the Login.jsp and Error.jsp pages in the infrastructure folder: a) In the left pane of the window, scroll down and select Login Configuration. b) In the right pane, select Form-Based Authentication and enter the following values into the Login Page and Error Page fields: Login Page: /infrastructure/Login.jsp Error Page: /infrastructure/Errors.jsp c) Click OK. d) Double-click web.xml and click the Source tab to see how those changes are applied to the deployment descriptor properties.
<login-config> <auth-method>FORM</auth-method> <form-login-config> <form-login-page>/infrastructure/Login.jsp</form-login-page> <form-error-page>/infrastructure/Errors.jsp</form-error-page> </form-login-config> </login-config>

Oracle Fusion Middleware 11g: Build Java EE Applications A - 127

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 16-2: Creating Security Roles and URL Constraints in the Deployment Descriptors

In this practice, you restrict access to portions of the course application by defining JAAS security roles and URL-based security constraints that authorize access based on those security roles. 1) Edit the web.xml deployment and add the following logical security groups: myadmin and myuser. Use the following details to accomplish this task: Step Screen/Page Description a. Applications Navigator b. Web Application Deployment Descriptor Security Roles Create Security Roles Security Roles Create Security Roles Security Roles Choices or Values Right-click web.xml. Select Properties. On the left pane of the screen select Security Roles.

c. d. e. f. g.

Click Add. Security Role Name: myadmin Click OK. Click Add. Security Role Name: myuser Click OK. Click OK.

JDeveloper added the following XML elements to the web.xml deployment descriptor:
... <security-role> <role-name>myadmin</role-name> </security-role> <security-role> <role-name>myuser</role-name> </security-role> ...

2) Edit the web.xml deployment and add a security constraint called AdminPages that allows the myadmin security role to access URL matching the pattern: /admin/edit.jsp. Use the following details to accomplish this task: Step Screen/Page Description a. Applications Navigator b. Web Application Deployment Descriptor Choices or Values Right-click web.xml. Select Properties. On the left pane select Security Constraints. Click New (located under the left pane).

Oracle Fusion Middleware 11g: Build Java EE Applications A - 128

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 16-2: Creating Security Roles and URL Constraints in the Deployment Descriptors (continued)
c. d. e. f. g. h. Constraint Create Web Resource Collections Constraint URL Pattern Constraint Constraint Click Add (next to Web Resource Collections field). Web Resource name: AdminPages Click OK. Click Add (next to next to URL Patterns field). URL Pattern: /admin/edit.jsp Click OK. Click the HTTP Methods tab. Select Choose, and subsequently the GET, POST check box. Click the Authorization tab. Select the myadmin check box. Click OK.

JDeveloper should have added the following XML elements to the web.xml deployment descriptor:
... <security-constraint> <web-resource-collection> <web-resource-name>AdminPages</web-resource-name> <url-pattern>/admin/edit.jsp</url-pattern> <http-method>GET</http-method> <http-method>POST</http-method> </web-resource-collection> <auth-constraint> <role-name>myadmin</role-name> </auth-constraint> </security-constraint> ...

3) Edit the web.xml deployment and add another security constraint called AllStaff that allows both the myadmin and myuser security roles to access URL matching the pattern: /common/*. Use the following details to accomplish this task: Step Screen/Page Description a. Applications Navigator b. Web Application Deployment Descriptor Constraint Create Web Resource Collections Choices or Values Right-click web.xml. Select Properties. Select Security Constraints. Click New (located under the left pane). Click Add (next to Web Resource Collections field). Web Resource name: AllStaff Click OK.

c. d.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 129

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 16-2: Creating Security Roles and URL Constraints in the Deployment Descriptors (continued)
e. f. g. h. Constraint URL Pattern Constraint Constraint Click Add (next to next to URL Patterns field). URL Pattern: /common/* Click OK. Click the HTTP Methods tab. Select Choose, and subsequently the GET, POST check box. Click the Authorization tab. Select the myadmin and myuser check boxes. Click OK.

... <security-constraint> <web-resource-collection> <web-resource-name>AllStaff</web-resource-name> <url-pattern>/common/*</url-pattern> <http-method>GET</http-method> <http-method>POST</http-method> </web-resource-collection> <auth-constraint> <role-name>myadmin</role-name> <role-name>myuser</role-name> </auth-constraint> </security-constraint> ...

4) Edit the web.xml deployment and add a <welcome-file-list> element. Use the following details to accomplish this task: Step Screen/Page Description a. Applications Navigator b. c. d. e. Web Application Deployment Descriptor WelcomeFileList0 Create Welcome File Web Application Deployment Descriptor Choices or Values Right-click web.xml. Select Properties. Select Welcome File Lists. Click New (located under the left pane). Click Add. Welcome File: /index.jsp Click OK. Click OK.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 130

Oracle University and Egabi Solutions use only

JDeveloper should have added the following XML elements to the web.xml deployment descriptor:

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 16-2: Creating Security Roles and URL Constraints in the Deployment Descriptors (continued)
5) Save the web.xml file. 6) Create the weblogic.xml deployment descriptor. In this file, you map the security role names to users and groups. Use the following details to create the weblogic.xml deployment descriptor. Step Screen/Page Description a. Applications Navigator b. c. New Gallery Create WebLogic Deployment Descriptor Step 1 of 4 Create WebLogic Deployment Descriptor Step 2 of 4 Choices or Values Right-click ViewController Select New.

d.

Deployment Descriptor Version: 10.3 Click Finish.

7) Edit the weblogic.xml deployment descriptor to map the myadmin and myuser security role defined in the <security-role> tag in the web.xml file.
<?xml version = '1.0' encoding = 'windows-1252'?> <weblogic-web-app xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance" xsi:schemaLocation="http://www.bea.com/ns/weblogic/weblogicweb-app.xsd" xmlns="http://www.bea.com/ns/weblogic/weblogicweb-app"> <security-role-assignment> <role-name>myadmin</role-name> <principal-name>chen</principal-name> <principal-name>mike</principal-name> </security-role-assignment> <security-role-assignment> <role-name>myuser</role-name> <principal-name>joe</principal-name> </security-role-assignment> </weblogic-web-app>

8) Save the weblogic.xml file.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 131

Oracle University and Egabi Solutions use only

Categories: Deployment Descriptors Items: WebLogic Deployment Descriptor Click OK Select weblogic.xml. Click Next

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 16-3: Creating the Users and Groups in WebLogic Server

In this practice, you define the users and groups that will have access to the URL resource. In the weblogic.xml file, the <role-name> tag defines myadmin as the group that has access to the edit.jsp, file and defines the user mike as a member of that group. Therefore, use the WebLogic Server Administration Console to define the myadmin group, define user mike, and add mike to the myadmin group. You can also define other users and add them to the group and they will also have access to the protected WebLogic resource. 1) Create the myadmin and myuser group.

b) Log in to the Console using weblogic/weblogic. c) In the Domain Structure pane, click Security Realms. d) On the Summary of Security Realms page, click myrealm. e) On the Settings for myrealm page, click the Users and Groups > Groups tab. f) Click New. g) Enter myadmin in the Name field and click OK. The myadmin group is added to the security realm. h) Execute the same sequence of steps to add the myuser group. 2) Create the users: mike, chen, and joe. a) In the Domain Structure pane, Click Security Realms. b) On the Summary of Security Realms page, click myrealm. c) On the Settings for myrealm page, click the Users and Groups > Users tab. d) Click New. e) Enter mike in the Name field, welcome1 in the Password and Confirm Password fields, and click OK. The user mike is added to the security realm. f) Execute the same sequence of steps to add users chen and joe. 3) Add the users to their respective groups: mike and chen to myadmin, and joe to the myuser group. a) On the Settings for myrealm page, click the Users and Groups > Users tab. b) Click the new user, mike. c) On the Settings for mike page, click the Groups tab. d) Add the myadmin parent group from the Available column to the Chosen column.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 132

Oracle University and Egabi Solutions use only

a) Start the default server in JDeveloper, and open a browser and enter http://127.0.0.1:7101/console.

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 16-3: Creating the Users and Groups in WebLogic Server (continued)
e) Click Save. f) Execute the same sequence of steps to add the user chen and joe to the myuser groups.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 133

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Practice 16-4: Testing the Security Implementation


1) Run index.jsp.

In this practice, you deploy the Web application to Oracle WebLogic Server and test its security implementation. Note: You might need to activate the changes in the WebLogic Server by clicking the Activate Changes button in WebLogic Server Administration Console. The Activate Changes button is visible when you click the View changes and restarts link in the Change Center pane of the administration console. 2) Enter the username as mike and password as welcome1. Click Sign On. 3) Click the link for the shopping cart page on the Security Login Example page. You see the contents of the shopping cart page. 4) Click the Back button of the Internet browser window. Click the Configure Background link in the Security Login Example page. Mike has the authorization to access the administrative page. Try executing the same sequence of steps, and log in to the Web application by providing joe as the username and welcome1 as the password. Joe has the privilege to access the shopping cart page, but will get the Error 403 Forbidden message when he clicks the Configure Background link on the Security Login Example page.

Oracle Fusion Middleware 11g: Build Java EE Applications A - 134

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Working with ADF Faces Components

Oracle University and Egabi Solutions use only

Copyright 2009, Oracle. All rights reserved.

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Objectives
After completing this lesson, you should be able to do the following: Use complex layout components Use styles to define page layout Use dynamic page layout

Copyright 2009, Oracle. All rights reserved.

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

Oracle Fusion Middleware 11g: Build Java EE Applications B - 2

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Using ADF Faces Layout Components


You can use the following components to achieve the desired layout:
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 2009, Oracle. All rights reserved.

Using ADF Faces Complex Layout Components ADF Faces layout components include the following: spacer, separator: To add blank space and divider lines panelSplitter, panelStretchLayout: To enable automatic component stretching in your pages panelSplitter, panelAccordion: To create collapsible panes panelFormLayout: To arrange items in columns or grids panelTabbed: To create stacked tabs showDetail: To hide and display groups of content panelGroupLayout: To enable automatic scrollbars in your pages, and arrange items horizontally or vertically panelCollection: To add menus, toolbars, and status bars to data aggregation components such as tables, trees, and tree tables panelHeader, showDetailHeader: To create titled sections and subsections group: To group semantically related components panelList, panelBox: To create styled lists and content boxes panelBorderLayout: To place items in fixed, peripheral areas around a central area The following slides show how to use these components for various layout tasks.

Oracle Fusion Middleware 11g: Build Java EE Applications B - 3

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Adding Spaces and Lines


No spacers With spacers and separator

Copyright 2009, Oracle. All rights reserved.

Adding Spaces and Lines You can use the af:spacer component to incorporate some blank space on your page between components, so that the page appears less cluttered than it would if all the components were right next to each other. You can include either or both vertical and horizontal space in a page by using the following attributes: height: The amount of vertical space to include in the page; use with width not set to create vertical spacer, surrounded with a paragraph tag so that it appears in its own line width: The amount of horizontal space to include between components; use with height not set to create horizontal spacer The af:separator component creates a horizontal line on the page.

Oracle Fusion Middleware 11g: Build Java EE Applications B - 4

Oracle University and Egabi Solutions use only

<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>

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Stretching Components
Enable stretching so that the component fills the designated area, such as browser window:

Copyright 2009, Oracle. All rights reserved.

Stretching Components By default, the maximized attribute on af:document is set to true. Upon rendering content, any outer margin, border, and padding are removed, and the body is stretched to fill the entire browser window. However, this does not mean that setting maximized to true is sufficient when you want your page contents to fill a browser window. When the user resizes the browser window, the af:document component does not reposition and resize its children components accordingly. If you want a component to fill an area, such as the browser or a designated part of another component, you must enable stretching for that component.

Oracle Fusion Middleware 11g: Build Java EE Applications B - 5

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Enabling Automatic Component Stretching


Table on page:

Same table within stretched Panel Stretch component:

Copyright 2009, Oracle. All rights reserved.

Enabling Automatic Component Stretching Some ADF Faces components, however, do reposition and resize their children when the browser size changes. Such components include af:panelSplitter and af:panelStretchLayout, which automatically use client-side geometry management to control the stretching of their child components. You do not have to write any code to enable the stretching; simply use either af:panelSplitter or af:panelStretchLayout to contain your page contents. While a geometry management component stretches its children, the component itself does not stretch automatically. So when you use a geometry management component as a root component for your page contents, you must set a property to tell it to fill up the browser window. To stretch and position your outermost layout panel component, you can set the maximized property of af:document to true (the default). If the root component is stretchable, it then stretches, both vertically and horizontally, to fit the browser viewport.

Oracle Fusion Middleware 11g: Build Java EE Applications B - 6

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Stretching a Table Column


Table with no stretched columns:

Table with last column stretched :

Copyright 2009, Oracle. All rights reserved.

Stretching a Table Column Certain components have attributes that relate to stretching their subcomponents. One of these is the ADF table. You can stretch a table column to fill up the available space. On the Appearance tab of the tables Property Inspector, you can set the ColumnStretching property to one of the following values: none (default): Provides optimal performance blank: Inserts an empty blank column that is stretched; use this so that the rows background colors will span the entire width of the table last: Stretches the last column to fill up any unused space inside the viewport column:<id>: Stretches a specified column; use the Id of the column that you want to stretch (requires that you explicitly set the columns Id property)

Oracle Fusion Middleware 11g: Build Java EE Applications B - 7

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Creating Resizable Panes


Panel Splitters af:panelSplitter

Horizontal orientation:

Nested:

Vertical orientation:

Copyright 2009, Oracle. All rights reserved.

Creating Resizable Panes When you have groups of unique content to present to users, consider using multiple panes separated by adjustable splitters. When viewing the page in a client browser, users can change the size of panes by dragging a splitter, and also choose to collapse or restore panes. When a pane is collapsed, its contents are hidden; when a pane is restored, the contents are displayed. The af:panelSplitter component enables you to organize contents into two panes separated by an adjustable splitter. Clicking the arrow button on a splitter collapses a pane (and its contents) in the direction of the arrow. The value of the orientation attribute determines whether the panes are horizontal (default) or vertical. The pane contents are specified in the facets first and second. The slide shows a page divided into two horizontal panes (placed left to right), and another page divided into two vertical panes (placed top to bottom). It also shows a nested panelSplitter, created by a horizontal panelSplitter into the first facet of a vertical panelSplitter. The af:panelSplitter component uses geometry management to stretch its children components at run time. That is, when the user collapses one pane, the contents in the other pane are explicitly resized to fill up available space. If af:panelSplitter is the root component for your page contents, you have to set the inlineStyle attribute on af:panelSplitter for maximum stretching.
Oracle Fusion Middleware 11g: Build Java EE Applications B - 8

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Printing Layout Panel Content

<af:commandButton text="Printable Page"> <af:showPrintablePageBehavior/> </af:commandButton>

Copyright 2009, Oracle. All rights reserved.

Printing Layout Panel Content The af:showPrintablePageBehavior operation creates a printable page that the user can print by using the browsers Print button. To allow printing, place the af:showPrintablePageBehavior component (an Operations component) within the page. The showPrintablePageBehavior tag is an operation, so you can drag it from the Operations section of the Component Palette to a button or other component that executes an operation. If the page contains a layout component with panes, such as a panel splitter, place the button that contains the af:showPrintablePageBehavior component in the facet whose pane contents you want users to be able to print. For example, in a panel splitter, if the second facet is the main content area of the af:panelSplitter component, insert the button that contains the af:showPrintablePageBehavior component into that facet. If you insert af:showPrintablePageBehavior anywhere outside of af:panelSplitter, the printed result may not contain all of the main content area. Therefore, it is important to place the print operation within the af:panelSplitter facet whose pane contents users would normally want to print. If both facets need printing support, insert one af:showPrintablePageBehavior component into each facet. To print contents of both panes, the user then has to execute the print command one pane at a time.
Oracle Fusion Middleware 11g: Build Java EE Applications B - 9

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Creating Collapsible Panes with the Panel Splitter Component


Attributes:
collapsed positionedFromEnd
true true false false true true

Behavior
First pane hidden; second pane stretches

Both panes displayed, with splitterPosition governing size of second pane and splitter arrow pointed toward second pane Both panes displayed, with splitterPosition governing size of first pane and splitter arrow pointed toward first pane

false

false

Copyright 2009, Oracle. All rights reserved.

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

Oracle Fusion Middleware 11g: Build Java EE Applications B - 10

Oracle University and Egabi Solutions use only

Second pane hidden; first pane stretches

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Creating Collapsible Panes with the Panel Accordion


With default settings

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


Copyright 2009, Oracle. All rights reserved.

Creating Collapsible Panes with the Panel Accordion Component Another component that enables you to create collapsible panes is panel accordion. A series of af:showDetailItem components inside af:panelAccordion make up the accordion panes, with one af:showDetailItem component corresponding to one pane. The pane contents are the children components inside each af:showDetailItem. You can use more than one af:panelAccordion component on a page, typically in different areas of the page, or nested. After adding the af:panelAccordion component, insert a series of af:showDetailItem components to provide the panes by using one af:showDetailItem for one pane. Then insert components into each af:showDetailItem to provide the pane contents.

Oracle Fusion Middleware 11g: Build Java EE Applications B - 11

Oracle University and Egabi Solutions use only

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

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

You can add toolbars and toolbar buttons in the pane headers. To add toolbar buttons to a pane, insert the af:toolbar component into the toolbar facet of the af:showDetailItem component that defines that pane. Then insert the desired number of af:commandToolbarButton components into the af:toolbar component. Although the toolbar facet is on af:showDetailItem, it is the parent component af:panelAccordion that renders the toolbar and its buttons. To allow users to print the contents of a single pane, place the af:showPrintablePageBehavior component (wrapped in af:commandButton) within the af:showDetailItem whose pane contents you want users to be able to print.

Oracle Fusion Middleware 11g: Build Java EE Applications B - 12

Oracle University and Egabi Solutions use only

Creating Collapsible Panes with the Panel Accordion Component (continued) The discloseMany attribute governs how many panes can be visible at once: Set to true if you want users to be able to expand and see the contents of more than one pane at the same time. By default, discloseMany is false. This means only one pane can be expanded at any one time. For example, suppose there is one expanded pane A and one collapsed pane B when the page first loads. If the user expands pane B, pane A will be collapsed, as only one pane can be expanded at any time. The discloseNone attribute governs whether users can collapse all panes. Set the discloseNone attribute to true to enable users to collapse all panes. By default, discloseNone is false. This means one pane must remain expanded at any time.

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Panel Accordion Overflow


Automatic overflow icons to display content out of view

Copyright 2009, Oracle. All rights reserved.

Panel Accordion Overflow At run time, when the available browser space is less than the space needed to display expanded pane contents, ADF Faces automatically displays overflow icons that enable users to select and navigate to those panes that are out of view. The slide shows overflow icons at the upper left (first example) and at the lower right (second example). When the user clicks the overflow icon, ADF Faces displays the overflow menu, as shown in the slide, for the user to select and navigate to a pane that is out of view.

Oracle Fusion Middleware 11g: Build Java EE Applications B - 13

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

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">

Copyright 2009, Oracle. All rights reserved.

Setting Panel Accordion Properties The following properties govern the behavior of panel accordion at run time: discloseNone: Allows all panes to be collapsed at once (default is false) discloseMany: Allows multiple panes to be expanded at once (default is false) The following properties of showDetailItem affect the behavior of the accordion panes: text: Specifies the text string to display as the title in the header of the container. flex: Specifies a non-negative integer that determines how much space is distributed among the af:showDetailItem components of one af:panelAccordion. By default, flex is 0 (zero), that is, the pane contents of each af:showDetailItem are inflexible. To enable flexible contents in a pane, specify a flex number larger than 0. inflexibleHeight: Specifies the number of pixels a pane will use. Default is 100 pixels. This means if a pane has a flex value of 0 (zero), ADF Faces will use 100 pixels for that pane, and then distribute the remaining space among the non-zero panes. If the contents of a pane cannot fit within the af:panelAccordion container given the specified inflexibleHeight value, ADF Faces automatically pushes out nearby contents into overflow menus, as described previously. Because neither of the above components automatically stretches its children, you may need to set the width and height of any children of showDetailItem to 100%.
Oracle Fusion Middleware 11g: Build Java EE Applications B - 14

Oracle University and Egabi Solutions use only

With discloseMany="true" discloseNone="true"

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Arranging Items in Columns or Grids


Use af:panelFormLayout with labels above or below the text:

Use rows and maxColumns attributes to arrange items on the form:

Copyright 2009, Oracle. All rights reserved.

Arranging Items in Columns or Grids The af:panelFormLayout component lets you lay out multiple form input components such as input fields and selection list fields in one or more columns. They can be arranged in one of two ways: With the field labels right-aligned and the fields left-aligned, as shown in the first example on the slide With the labels above the fields, as shown in the second example. To place the labels above the fields, set the labelAlignment attribute on af:panelFormLayout to top. When you nest an af:panelFormLayout component inside another, by default the label alignment in the nested layout is top. The following attributes determine the number of rows and columns to display the children components: rows: The number of rows after which a new column will start. The default is 2,147,483,647 (Integer.MAX_VALUE), which means all visible, rendered children components display in a single column. When rows is a nondefault value, the number of columns is dependent on the number of rendered children. For example, if rows is set to 6 and there are 7 to 12 rendered children, the list is displayed in two columns.
Oracle Fusion Middleware 11g: Build Java EE Applications B - 15

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Arranging Items in Columns or Grids (continued) maxColumns: The maximum number of columns to display the children components. The default is 3 (2 on PDAs). For nested panel form layout components, the inner components maxColumns value is always 1. The row-column split is based solely on the number of rendered children and not on their size. If the number of rendered children does not fit in the number of rows and columns specified, ADF Faces automatically increases the number of rows to accommodate the number of children. To add content below the children input components, insert the desired component into the footer facet of af:panelFormLayout. Facets accept only one child. If you have to insert more than one footer child, use af:panelGroupLayout or af:group to wrap the footer children.

Oracle Fusion Middleware 11g: Build Java EE Applications B - 16

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

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>

Copyright 2009, Oracle. All rights reserved.

Creating Stacked Tabs Using af:panelTabbed to create tabbed panes is similar to using af:panelAccordion to create accordion panes. After adding an af:panelTabbed component, insert a series of af:showDetailItem components to provide the tabbed pane contents for display. To display and hide contents using PanelTabbed, perform the following steps: 1. Add the af:panelTabbed component to the JSF page. 2. Set the position attribute to below if you want the tabs to be rendered below the contents in the display area. By default, position is above. This means the tabs are rendered above the contents in the display area. The other acceptable value is both, where tabs are rendered above and below the display area. 3. To add a tabbed pane, insert the af:showDetailItem component inside af:panelTabbed. You can add as many tabbed panes as you want. 4. To add contents for display in a pane, insert the desired children components into each af:showDetailItem component. The example in the slide shows three tabs, positioned at both top and bottom. Each tab is defined by a show detail item component, each of which contains a table as content for the tab.

Oracle Fusion Middleware 11g: Build Java EE Applications B - 17

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

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>

Copyright 2009, Oracle. All rights reserved.

Hiding and Displaying Groups of Content You can use the af:showDetail component to display and hide groups of content. Its child components can be displayed or hidden at run time. To display or hide contents using af:showDetail: 1. Add the af:showDetail component to the JSF page and set its properties: - disclosed: Set to true if you want the component to show its children - disclosedText: Set to the label you want to display next to the toggle icon when the contents are disclosed (shown). By default, the label is Hide. - undisclosedText: Set to the label you want to display next to the toggle icon when the contents are undisclosed (hidden). The default label is Show. Note: If you specify a value for either disclosedText or for undisclosedText, but not for both, then that value is used for both the disclosed state and undisclosed state. Instead of using the text specified in disclosedText and undisclosedText, you could use the prompt facet to add a component that will render next to the toggle icon. 2. Insert the children components for display into af:showDetail. You can wrap the children in, for example, af:panelGroupLayout, to achieve the desired layout.

Oracle Fusion Middleware 11g: Build Java EE Applications B - 18

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Hiding and Displaying Groups of Content (continued) An org.apache.myfaces.trinidad.event.DiscloserEvent is raised when the user clicks the toggle icon. You can perform special handling of this event by binding the components disclosureListener attribute to a DisclosureListener method in a backing bean. The DisclosureListener method must be a public method with a single
DisclosureEvent event object and a void return type, as shown in the following example: public void some_disclosureListener(DisclosureEvent disclosureEvent) { // Add event handling code here }

Oracle Fusion Middleware 11g: Build Java EE Applications B - 19

Oracle University and Egabi Solutions use only

By default, DisclosureEvent events are usually delivered in the Invoke Application phase, unless the components immediate attribute is set to true. When immediate is true, the event is delivered in the earliest possible phase, usually the Apply Request Values phase. On the client-side component, the AdfDisclosureEvent is fired. The event root for the client AdfDisclosureEvent is set to the event source component; only the event for the pane whose disclosed attribute is true is sent to the server.

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Arranging Items Horizontally or Vertically, with Scrollbars


Panel group layout arrangements Panel group layout inside stretched panel splitter does not stretch its children.

Copyright 2009, Oracle. All rights reserved.

Arranging Items Horizontally or Vertically, with Scrollbars The af:panelGroupLayout component enables you to arrange a series of children components vertically or horizontally without wrapping, or consecutively with wrapping, as shown in the first example in the slide. The layout attribute value determines the arrangement of the children. In all arrangements, each pair of adjacent children components can be separated by a line or white space using the separator facet on af:panelGroupLayout. When using the horizontal layout, the children can also be vertically or horizontally aligned. For example, you could make a short component beside a tall component align at the middle, as shown in the second layout in the slide. Unlike af:panelSplitter or af:panelStretchLayout, the af:panelGroupLayout component does not stretch its children. You can use af:panelGroupLayout in situations where you are already using af:panelSplitter or af:panelStretchLayout as the root component for the page, and you have a large number of children components to flow normally but are not to be stretched, as in the second example in the slide.

Oracle Fusion Middleware 11g: Build Java EE Applications B - 20

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Oracle Fusion Middleware 11g: Build Java EE Applications B - 21

Oracle University and Egabi Solutions use only

Arranging Items Horizontally or Vertically, with Scrollbars (continued) To provide scrollbars when flowing the children components, wrap the children in the af:panelGroupLayout component with its layout attribute set to scroll, and then place the af:panelGroupLayout component inside the af:panelSplitter or af:panelStretchLayout facet. The second example in the slide shows a panel splitter that is stretched. It contains a panel group layout with its layout attribute set to scroll. Although the child table is not stretched, it displays scrollbars to enable users to see all of its content. When layout is set to scroll on af:panelGroupLayout, ADF Faces automatically provides a scrollbar at run time when the contents contained by the af:panelGroupLayout component are larger than the af:panelGroupLayout itself. You do not have to write any code to enable the scrollbars, or set any inline styles to control the overflow. For example, when you use layout components such as af:showDetail that enable users to expand and collapse children contents, you do not have to write code to show the scrollbars when the contents expand, and to hide the scrollbars when the contents collapse. Simply wrap the af:showDetail component inside an af:panelGroupLayout component, and set the layout attribute to scroll. To get the layout you desire for the af:showDetail children, you can use nested af:panelGroupLayout components.

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Displaying Table Menus, Toolbars, and Status Bars


Use panelCollection for table with menus and toolbars:

Copyright 2009, Oracle. All rights reserved.

Displaying Table Menus, Toolbars, and Status Bars You can use the af:panelCollection component to add menus, toolbars, and status bars to data aggregation components such as tables, trees, and tree tables. You would create the af:panelCollection component, then add the table, tree, or tree table component as a direct child of the panelCollection. You cannot use a switcher to hold the table component (the af:switcher operation component dynamically renders different components based on type, name, hint, or other attributes of the model.) The af:panelCollection tag contains a menu facet for af:menu, a toolbar facet for af:toolbar, a secondaryToolbar facet for another af:toolbar, and a statusbar facet. The table, tree, or tree table is added after the last facet. The default top-level menu and toolbar items depend on the child component being used: Tables and trees: The default top-level menu is View. Tables and tree table: The default toolbar menu is Detach. Tree and tree table (when the pathStamp is used): The toolbar buttons Go Up, Go To Top, and Show as Top also appear.

Oracle Fusion Middleware 11g: Build Java EE Applications B - 22

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Displaying Table Menus, Toolbars, and Status Bars (continued) The example shown in the slide has the following source code:
<af:panelCollection binding="#{editor.component}"> <f:facet name="menus"> <af:menu text="Actions"> <af:commandMenuItem text="Add..." /> <af:commandMenuItem text="Create.." /> <af:commandMenuItem text="Update..." disabled="true"/> <af:commandMenuItem text="Copy"/> <af:commandMenuItem text="Delete"/> <af:commandMenuItem text="Remove" accelerator="control A"/> <af:commandMenuItem text="Preferences"/> </af:menu> </f:facet> <f:facet name="toolbar"> <af:toolbar> <af:commandToolbarButton shortDesc="Create" icon="/new_ena.png"> </af:commandToolbarButton> <af:commandToolbarButton shortDesc="Update" icon="/update_ena.png"> </af:commandToolbarButton> <af:commandToolbarButton shortDesc="Delete" icon="/delete_ena.png"> </af:commandToolbarButton> </af:toolbar> </f:facet> <f:facet name="secondaryToolbar"> </f:facet> <f:facet name="statusbar"> <af:toolbar> <af:outputText id="statusText" ... value="Custom Statusbar Message"/> </af:toolbar> </f:facet> <af:table rowSelection="multiple" columnSelection="multiple" ... <af:column ... </af:column>

The panelCollection component is a naming container. If you want to add its contained component, such as a table, as partialTriggers (described later in this lesson), you must use its fully qualified name. For example, if you have a panelCollection with id=entriesCollection and a contained table with id=deptTable, and you want to update a panelForm on the selection change of the table, you would declare the panelForm's partialTriggers as: <panelForm partialTriggers="entriesCollection:deptTable">

Oracle Fusion Middleware 11g: Build Java EE Applications B - 23

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Creating Titled Sections and Subsections


Panel header component with sections and subsections: af:panelHeader
Oracle University and Egabi Solutions use only

Show detail header component with sections that expand or collapse: af:showDetailHeader

Copyright 2009, Oracle. All rights reserved.

Creating Titled Sections and Subsections You may want to divide a page into sections and subsections, starting each section or subsection with a header. The af:panelHeader component enables you to create sections and subsections with a label and an icon at the top of each section or subsection header, as shown in the first example in the slide. To enable users to toggle the display of contents under each section or subsection header, use the af:showDetailHeader component instead. This is similar to the af:panelHeader component, except that it renders a toggle icon that enables users to hide or display the section or subsection contents. The second example in the slide shows a top section with its contents displayed, and a subsection with its contents hidden. Partial page rendering (PPR), which you learn about later in this lesson, is automatically used to refresh a section of the page when the user selects to hide or show contents under the header. The disclosed attribute on af:showDetailHeader specifies whether to show or hide the contents under its header. The default is false, which means that the contents are hidden. When the user clicks the toggle icon, an org.apache.myfaces.trinidad.event.DiscloserEvent is raised to the server. If you want to perform special handling of this event, you can bind the components disclosureListener attribute to a DisclosureListener method in a backing bean.
Oracle Fusion Middleware 11g: Build Java EE Applications B - 24

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Grouping Semantically Related Components


Use af:group to: Add multiple components to a facet Group related children 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 2009, Oracle. All rights reserved.

Grouping Semantically Related Components The af:group component aggregates or groups together children components that are related semantically. The af:group component does not provide any layout for its children. Used on its own, the af:group component does not render anything; only the children components inside of af:group render at run time. You can use any number of af:group components to group related components together. For example, you might want to group some of the input fields in a form layout created by af:panelFormLayout, as shown in the example on the slide that groups two sets of children components inside af:panelFormLayout. When the af:group component is used as a child in a parent component that does provide special rendering for af:group children, then visible separators, such as bars or dotted lines, display around the children of each af:group. For example, af:panelFormLayout and af:toolbar support special rendering for af:group children. The example in the slide shows how at run time the af:panelFormLayout component renders dotted separator lines before and after the first and second af:group of children components. Children inside af:group are never split across a column in a form. The af:group component is especially useful when you need to group components under a facet, because a facet may have only one child.
Oracle Fusion Middleware 11g: Build Java EE Applications B - 25

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

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:
Oracle University and Egabi Solutions use only

Create a list hierachy with nested af:panelList components: Specify bullet style by setting list-style-type to:
disc square circle decimal lower-alpha upper-alpha

Copyright 2009, Oracle. All rights reserved.

Displaying a Bulleted List You can use af:panelList to display a bulleted list in one or more columns. Use one af:panelList component to create each list of items. By default, all rendered child components of af:panelList are displayed in a single column. You can surround the child components in a Panel Form Layout component to split the list into two or more columns. To create a styled list of items, perform the following steps: 1. Add the Panel List component to the JSF page. 2. Insert the desired number of child components (to display as bulleted items). 3. To style the child components, set the ListStyle attribute to a valid CSS 2.1 list style value, such as one of the following:
list-style-type:disc list-style-type:square list-style-type:circle - list-style-type:decimal - list-style-type:lower-alpha - list-style-type:upper-alpha

For example, entering list-style-type:disc into the ListStyle property corresponds to a disc bullet. You can nest af:panelList components to create a list hierarchy that has outer items and inner items, where the inner items belonging to an outer item are indented under the outer item. You can use an af:panelGroupLayout component to wrap the components that make up each group of outer item and its inner items.
Oracle Fusion Middleware 11g: Build Java EE Applications B - 26

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Displaying Items in a Content Container Offset by Color


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

Copyright 2009, Oracle. All rights reserved.

Displaying Items in a Content Container Offset by Color You can display content in a container that can have a colored background. The af:panelBox component enables you create a container that has a header, which can contain a title with an optional icon. Under the header is the box for your contents, as shown in the slide. To use a colored content container for your contents, perform the following steps: 1. Add the Panel Box component to the JSF page. 2. Set attributes as needed: - Background: Set to light (default), medium, dark, or transparent. - Text: Set to the text string to display as the title in the header of the container. - Icon: Set to the URI of the icon image you want to display before the header text. Note: If both the Text and Icon attributes are not set, ADF Faces does not display the header portion of the content container. - TitleHalign: Set the horizontal alignment of the title to one of the following values: center, start, end, left, or right. - InlineStyle: Set the width of the container box to the exact pixel size or a percent. - ContentStyle: Change style of contents inside the containerfor example, set to background-color:Lime to change the color of the box to lime green. Note: Color should never be used to convey information because of accessibility issues.
Oracle Fusion Middleware 11g: Build Java EE Applications B - 27

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Arranging Items Around a Central Area

Copyright 2009, Oracle. All rights reserved.

Arranging Items Around a Central Area The af:panelBorderLayout component is a layout element for arranging components in predefined, named areas around a center area. The center area is where direct children components of af:panelBorderLayout render consecutively. In addition to the center area, the af:panelBorderLayout component supports the following named areas, each of which is defined by a facet bearing the name for the area: top: Renders children above the center area bottom: Renders children below the center area start: Renders children on the left of the center area between top and bottom facet children, if the reading direction of the client browser is left-to-right. If the reading direction is right-to-left, it renders children on the right of the center area. end: Renders children on the right of the center area between top and bottom facet children, if the reading direction of the client browser is left-to-right. If the reading direction is right-to-left, it renders children on the left of the center area. left: Renders children on the left of the center area between top and bottom facet children. If the reading direction is left-to-right, left has precedence over start if both left and start facets are used. If the reading direction is right-to-left, left also has precedence over end if both left and end facets are used.

Oracle Fusion Middleware 11g: Build Java EE Applications B - 28

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Note: For BiDi support (right to left layout), Oracle Applications developers should not use the left and right areas of af:panelBorderLayout. Start and end should be used instead of left and right. To add items in predefined areas using PanelBorderLayout, perform the following steps: 1. Add the Panel Border Layout component to the JSF page. 2. To place content in the center area, insert the desired components inside af:panelBorderLayout. 3. The children components are displayed consecutively in the order in which you inserted the desired components. If you want some other type of layout for the children, wrap the components inside af:panelGroupLayout. 4. To place content in one of the named areas around the center area, perform one of the following: - If the facet is visible (for example, start or end), insert the desired components into the facet, grouping multiple components because a facet can take only one child. - If the facet is not visible, right-click af:panelBorderLayout, select Facets Panel Border Layout from the context menu, and choose a facet name from the list. Visible facets are indicated by a check mark in front of the facet name. Insert the desired components into the visible facet.

Oracle Fusion Middleware 11g: Build Java EE Applications B - 29

Oracle University and Egabi Solutions use only

Arranging Items Around a Central Area (continued) right: Renders children on the right of the center area between top and bottom facet children. If the reading direction is left-to-right, right has precedence over end if both right and end facets are used. If the reading direction is right-to-left, right also has precedence over start if both right and start facets are used. innerTop: Renders children above the center area but below the top facet children innerBottom: Renders children below the center area but above the bottom facet children innerLeft: Similar to left, but renders between innerTop and innerBottom, and between left and the center area innerRight: Similar to right, but renders between innerTop and innerBottom, and between right and the center area innerStart: Similar to innerLeft, if the reading direction is left-to-right; similar to innerRight, if the reading direction is right-to-left innerEnd: Similar to innerRight, if the reading direction is left-to-right; similar to innerLeft, if the reading direction is right-to-left

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

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
Oracle University and Egabi Solutions use only

Copyright 2009, Oracle. All rights reserved.

Using ADF Faces Skins You can change the appearance or look and feel of an application without having to rewrite the user interface. A skin in ADF Faces is a global style sheet that only needs to be set in one place for the entire application. Every component automatically uses the styles as described by the skin. Any changes to the skin are picked up at run time, so no change to code is needed. Skins are based on the Cascading Style Sheet specification, using CSS 3.0 syntax. In addition to using a CSS file to determine the styles, skins also use a resource bundle to determine the text. For example, the words Previous and Next in the navigation bar of the ADF Faces table component are determined by using the skins resource bundle. All the included skins use the same resource bundle. ADF Faces provides three main skins that are provided for you to use in your applications: Oracle (oracle): The default skin that conforms to Oracles UI standards (Browser Look and Feel BLAF) for applications Minimal (minimal): Provides some formatting Simple (simple): Contains almost no special formatting

Oracle Fusion Middleware 11g: Build Java EE Applications B - 30

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Using Dynamic Page Layout


Dynamic page layout is made possible by using: Expression Language (EL) Partial Page Rendering (PPR)

Copyright 2009, Oracle. All rights reserved.

Oracle Fusion Middleware 11g: Build Java EE Applications B - 31

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Using Expression Language to Conditionally Display Components


You can use EL for any of a components attributes. Example of setting attributes with EL:

Copyright 2009, Oracle. All rights reserved.

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

Oracle Fusion Middleware 11g: Build Java EE Applications B - 32

Oracle University and Egabi Solutions use only

<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>

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Characteristics of Partial Page Rendering (PPR)


PPR: Is enabled by ADF Faces Enables redrawing only a portion of a page Requires server round-trip:
Oracle University and Egabi Solutions use only

Re-renders only a portion of the server-side component tree Downloads only the appropriate fragment of HTML

Currently supported on IE 7.0+ and Firefox 2.0.0.2 + Implements certain ADF Faces patterns
Single component refresh Cross-component refresh

Can be enabled declaratively or programmatically

Copyright 2009, Oracle. All rights reserved.

Partial Page Rendering Unlike standard JSF events, ADF Faces events support Ajax-style partial postbacks to enable partial page rendering (PPR), which enables refreshing portions of page content that have minimal processing without the need to redraw the entire page. In ADF Faces components, this is implemented by a hidden IFrame, which is automatically added to a Web page when one of the following ADF Faces elements is used: af:document, afh:body or af:panelPartialRoot. PPR is currently supported on the following browsers: Internet Explorer 7.0 and above on Windows Firefox 2.0.0.2 and above Two main Ajax patterns are implemented with PPR: Single component refresh: Implemented natively through declarative property settings; for example, the ADF Faces table component comes with built-in functionality that lets you scroll through the table, sort the table by clicking on a column header, mark a line or several lines for selection, and expand specific rows in the table Cross-component refresh: Implemented declaratively or programmatically by the application developer by defining ADF Faces UI components to act either as a trigger for a partial update, or as a partial listener to be updated
Oracle Fusion Middleware 11g: Build Java EE Applications B - 33

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Enabling PPR Declaratively


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

Target component: (must specify triggering component)


Copyright 2009, Oracle. All rights reserved.

Enabling PPR Declaratively For a component to trigger another component to refresh, the trigger component must have a unique ID, which is a valid XML name, and must cause a submit when an appropriate action takes place. For a component to be refreshed as triggered by another component, it must declare which other components are the triggers. The following are the three main component attributes used in PPR: autoSubmit: When set to true, and an appropriate action takes place (such as a value change), the component automatically submits the enclosing form. For PPR, you might use this in conjunction with a listener attribute bound to a method that performs some logic when an event that is based on the submit is launched. partialSubmit: When set to true, the page partially submits when the button or link is clicked. You might use this in conjunction with an actionListener method that performs some logic when the button or link is clicked. partialTriggers: Use this attribute to list the IDs of components whose change events are to trigger this component to be refreshed. Use a space between multiple IDs. When any of those triggering components is updated (for example, through an autoSubmit) or submitted, this component is also updated. All rendered components support the partialTriggers attribute.

Oracle Fusion Middleware 11g: Build Java EE Applications B - 34

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

<af:commandButton text="Toggle" id="commandButton1" partialSubmit="true" actionListener="#{backing_page.commandButton1_actionListener}"/> <af:outputText value="Hello World" binding="#{backing_page.outputText1}" id="outputText1" partialTriggers="commandButton1"/>

Setting partialSubmit to true (the default value is false) on af:commandButton causes ADF Faces to perform the action through a partial page submit when the button is clicked. The partialTriggers attribute on af:outputText tells the component to listen for any event triggered by the af:commandButton; when an event is triggered, the af:outputText component automatically refreshes itself. ADF Faces does not re-render the entire page, but only those components (for example, af:outputText) that are listening for events fired by trigger components (for example, af:commandButton) are re-rendered. Note that only the following ADF Faces command components use full page rendering for their action events by default (that is, partialSubmit is false by default): af:commandButton af:commandLink af:commandNavigationItem In contrast, the following command components always use PPR for their action events (that is, partialSubmit is true by default), unless explicitly set otherwise: af:commandMenuItem af:commandToolbarButton Like action events, value change events in ADF Faces components can also use PPR. ADF Faces input and select components (such as af:inputText and af:selectOneChoice) automatically trigger partial page requests when their autoSubmit attribute is set to true.

Oracle Fusion Middleware 11g: Build Java EE Applications B - 35

Oracle University and Egabi Solutions use only

Enabling PPR Declaratively (continued) To enable a component to partially refresh another component: 1. On the trigger component: - Set the id attribute to a unique value. - If it is an input component in a form, set the autoSubmit attribute of the component to true. Otherwise, set the partialSubmit attribute of the component to true. 2. On the target component that you want to partially refresh when the trigger command component is activated, set the partialTriggers attribute to the ID of the trigger component. If the component refresh is to be triggered by more than one other component, list their IDs separated by spaces. It is recommended that you use the partial trigger editor for choosing the ID values. If the target component is inside a *container* component, the partialTrigger value might contain that *container* id as well, which the partial trigger editor would automatically pick up. At run time, when the triggering component fires a partial event, the output component, which is listening for partial events from the triggering component, refreshes its values using partial page rendering. Example:

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Native PPR Example

Copyright 2009, Oracle. All rights reserved.

Native PPR Example As an example, the first example in the slide shows a page with two af:showDetailItem components in a tabbed panel near the bottom of the display, one for Product Details and the other for Stock Levels. When the user selects one of the tabs, the page renders only that portion of the page, not the whole page. This behavior is built into the components; you do not need to add any code.

Oracle Fusion Middleware 11g: Build Java EE Applications B - 36

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Declarative PPR Example

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

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

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

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

Copyright 2009, Oracle. All rights reserved.

Declarative PPR Example The example in the slide is the View Cart page of the course application, which contains the following code:
<af:panelCollection id="tableCollection"> <f:facet name="toolbar"> <af:toolbar> <af:commandToolbarButton actionListener="#{FODShoppingCartBean.onDeleteRow}" text="Delete" disabled="#{!bindings.Delete.enabled}" id="deleteToolbarButton"> <af:setActionListener from="#{'Modified'}" to="#{requestScope.cartStatus}"/> </af:commandToolbarButton> <af:commandToolbarButton id="updateToolbarButton" text="Update Shopping Cart"/> </af:toolbar> </f:facet>

Oracle Fusion Middleware 11g: Build Java EE Applications B - 37

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Declarative PPR Example (continued)


<af:table value="#{bindings.ShoppingCartItem1.collectionModel}" var="row" rows="#{bindings.ShoppingCartItem1.rangeSize}" first="#{bindings.ShoppingCartItem1.rangeStart}" emptyText="#{bindings.ShoppingCartItem1.viewable ? 'No rows yet.' : 'Access Denied.'}" fetchSize="#{bindings.ShoppingCartItem1.rangeSize} selectedRowKeys= "#{bindings.ShoppingCartItem1.collectionModel.selectedRow}" selectionListener= "#{bindings.ShoppingCartItem1.collectionModel.makeCurrent}" rowSelection="single" id="table1" inlineStyle="width:100%" contextMenuId="tablePopup" partialTriggers="deleteToolbarButton menuDelete updateToolbarButton"> //list of columns //... //... </af:table> <af:popup id="tablePopup"> <af:menu text="menu 1" id="tablePopupMenu"> <af:commandMenuItem text="Delete" actionListener="#{FODShoppingCartBean.onDeleteRow}" id="menuDelete" partialSubmit="true"> <af:setActionListener from="#{'Modified'}" to="#{requestScope.cartStatus}"/> </af:commandMenuItem> </af:menu> </af:popup> </af:panelCollection>

This example illustrates setting partialTriggers on a table to the IDs of three components. You can see that it is not necessary to explicitly set partialSubmit on the toolbar buttons, because it is set to true by default on this type of component. However, partialSubmit has been explicitly set to true on the command menu item, even though it was not necessary to explicitly do so because it is also set to true by default on this type of component.

Oracle Fusion Middleware 11g: Build Java EE Applications B - 38

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Enabling PPR Programmatically


Why? You need logic to determine if the 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). How? Use the addPartialTarget() method.

Copyright 2009, Oracle. All rights reserved.

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

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Conforming to PPR Guidelines


Purposes of PPR:
Improve application performance Improve the user experience

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

PPR may cause accessibility issues

Copyright 2009, Oracle. All rights reserved.

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

Oracle University and Egabi Solutions use only

Guidelines for using PPR: http://www.oracle.com/technology/tech/blaf/ specs/ppr.html

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Summary
In this lesson, you should have learned how to: Use complex layout components Use styles to define page layout Use dynamic page layout
Oracle University and Egabi Solutions use only

Copyright 2009, Oracle. All rights reserved.

Oracle Fusion Middleware 11g: Build Java EE Applications B - 41

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Index
Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

A abstract schema name 9-24 abstract-schema-name 9-22 ACID 15-3 acknowledgeMode 14-22, 14-23 activation 1-14, 7-2, 7-13, 7-14, 7-23, 14-22 Administration Server 2-45, 2-46, 3-29 afterBegin 7-12 afterCompletion 7-12 annotated 6-17, 7-6, 7-16, 8-3, 8-16, 8-17, 9-6, 10-12, 10-15 annotation 1-14, 1-15, 2-15, 2-19, 6-15, 6-16, 6-17, 6-18, 6-19, 6-20, 6-21, 6-22, 6-24, 7-2, 7-5, 7-7, 7-8, 7-9, 7-10, 7-13, 7-15, 7-16, 7-17, 7-19, 7-21, 7-23, 8-2, 8-3, 8-4, 8-5, 8-7, 8-8, 8-10, 8-12, 8-13, 8-14, 8-15, 8-16, 8-17, 8-18, 8-19, 8-20, 8-21, 8-22, 8-23, 8-24, 8-25, 8-26, 8-29, 9-2, 9-6, 9-7, 9-8, 9-9, 9-15, 9-23, 9-25, 10-12, 10-13, 10-14, 10-15, 10-16, 10-17, 12-10, 14-22, 15-13, 15-14, 15-16, 15-17, 15-18, 15-24, 15-30, 15-32, 15-35, 16-20, 16-32, 16-34 Ant 17-5, 17-25, 17-26, 17-28, 17-29, 17-30, 17-31 APIs 1-3, 1-13, 1-16, 2-3, 2-6, 2-8, 2-9, 2-10, 2-22, 2-25, 2-28, 6-2, 6-23, 9-3, 10-7, 10-8, 11-11, 11-27, 16-4 applets 2-12, 2-26, 4-4, 4-20, 17-12 application-client.xml 6-12 application.xml 2-34, 16-25, 17-3, 17-5, 17-19, 17-22, 17-30, 17-32 AQ 2-18 @AroundInvoke 7-21, 7-22 asynchronous 1-3, 1-21, 2-17, 14-5, 14-20 <auth-constraint> 16-23, 16-31 Authentication 1-3, 1-23, 2-10, 6-19, 16-2, 16-4, 16-5, 16-6, 16-7, 16-10, 16-26, 16-27, 16-30, 16-34 authenticationType 6-19 Authorization 1-3, 1-23, 2-9, 2-10, 16-2, 16-4, 16-5, 16-6, 16-7, 16-8, 16-10, 16-31, 16-34 AUTO 8-17, 14-22, 14-23, 14-24, 15-23

Oracle Fusion Middleware 11g: Build Java EE Applications

Index - 2

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

B backing beans 3-20, 11-7, 11-25, 13-18 Basic authentication 16-30 batch 9-16 bean-managed 15-13, 15-14, 15-24, 15-27, 15-30, 15-32, 15-34, 15-35 beanInterface 6-22, 7-19 beanName 6-22 beforeCompletion 7-12 begin() 15-29, 15-30, 15-31, 15-33 BMT 15-13, 15-16, 15-24, 15-29, 15-30, 15-31, 15-32 bouncing 17-4 Business Delegate 3-20 BytesMessage 14-25 C callback 7-6, 7-12, 7-13, 7-16, 9-6, 14-21 cascade 8-23, 8-26, 9-6, 9-15 Class level 15-17, 15-26 CLASSPATH 6-10, 6-12, 18-14 clear() 9-11 Client certificate authentication 16-30 cluster 2-41, 3-3, 3-26, 3-29, 6-13, 7-10, 14-16, 17-16, 17-23, 17-31 clustered 3-3, 6-13, 7-10 clustering 2-41, 17-16, 17-23 CMT 15-13, 15-16, 15-17, 15-25, 15-26 collection 2-42, 5-35, 5-40, 8-25, 9-21, 9-22, 9-23, 9-24, 10-21, 15-5, 16-12, 16-23, 16-31, B-38 @Column 8-3, 8-4, 8-5, 8-7, 8-8, 8-17, 8-24 commit() 15-25, 15-29, 15-30, 15-31 commit 2-8, 9-4, 9-5, 9-10, 14-10, 14-13, 15-5, 15-7, 15-8, 15-9, 15-10, 15-12, 15-13, 15-16, 15-18, 15-22, 15-25, 15-27, 15-29, 15-30, 15-31, 15-32, 15-33 conditions 9-22, 13-13, 16-17 Connection 3-24, 3-25, 3-26, 3-27, 3-29, 6-20, 14-6, 14-11, 14-12, 14-16, 14-22, 14-24, 15-33

Oracle Fusion Middleware 11g: Build Java EE Applications

Index - 3

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

C connection factories 14-16, 17-22 connection pool 3-2, 3-23, 3-24, 3-25, 3-26, 3-27, 3-30, 4-19, 14-10 connectionFactoryJndiName 14-22 CONTAINER 6-19, 15-16, 15-17, 15-26 container-managed 1-22, 9-7, 15-2, 15-13, 15-27, 15-34, 15-35, 17-16 contains() 9-6 context.lookup 7-11, 7-18, 7-19, 15-31 createNamedQuery() 9-10, 9-12, 9-21, 9-23 createQuery() 9-10, 9-12, 9-21, 9-24 creation 1-12, 2-8, 2-10, 2-30, 2-51, 5-2, 7-12, 12-22, 17-18 D Data Source 3-23, 3-25, 3-26, 3-27, 3-28, 3-29 Data sources 6-3, 6-20 database 1-14, 1-15, 2-4, 2-5, 2-9, 2-13, 2-14, 2-16, 2-18, 2-19, 2-20, 2-25, 2-26, 2-29, 2-35, 2-51, 2-52, 3-3, 3-10, 3-11, 3-21, 3-23, 3-24, 3-25, 3-27, 3-28, 3-29, 4-3, 4-6, 4-19, 4-28, 5-3, 5-35, 6-16, 6-24, 7-3, 7-4, 7-5, 8-3, 8-4, 8-5, 8-6, 8-7, 8-8, 8-9, 8-10, 8-17, 8-18, 8-24, 8-28, 9-3, 9-4, 9-5, 9-6, 9-10, 9-11, 9-14, 9-16, 9-19, 13-15, 13-21, 14-6, 14-10, 15-3, 15-4, 15-5, 15-6, 15-7, 15-8, 15-12, 15-19, 15-27, 15-28, 15-33, 15-35, 16-4, 17-9, 17-16, 17-21, 18-4, 18-6, B-40 Database Connection 3-29 DataSource 2-39, 6-5, 6-9, 6-17, 6-18, 6-20, 15-33, 17-21 declarative 2-8, 2-20, 2-34, 2-36, 2-37, 8-3, 15-13, 15-14, 16-3, 16-20, 16-29, 16-31, 18-17, B-33 @DeclareRoles 16-32 DELETE 9-5, 9-10, 9-21 demarcate 14-11, 14-13, 15-13, 15-14, 15-16, 15-27, 15-30 @DenyAll 16-32, 16-33 dependency 1-13, 1-16, 3-6, 3-21, 6-11, 6-12, 6-16, 6-17, 6-18, 6-20, 6-21, 6-22, 7-5, 7-12, 7-19, 7-24, 9-2, 9-7, 9-8, 9-25, 10-20, 11-11, 14-20, 14-22, 15-30, 15-31

Oracle Fusion Middleware 11g: Build Java EE Applications

Index - 4

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

D dependency injection 1-13, 1-16, 6-16, 6-17, 6-18, 6-20, 6-21, 6-22, 7-5, 7-12, 7-19, 7-24, 9-2, 9-7, 9-8, 9-25, 11-11, 14-20, 14-22, 15-30, 15-31 Deploy 1-8, 1-24, 2-7, 2-9, 2-36, 2-37, 10-13, 10-21, 16-17, 16-28, 17-1, 17-2, 17-3, 17-4, 17-6, 17-7, 17-12, 17-13, 17-14, 17-18, 17-19, 17-20, 17-23, 17-24, 17-31, 17-33 deployment 1-9, 1-10, 1-24, 2-2, 2-6, 2-7, 2-8, 2-9, 2-19, 2-26, 2-33, 2-34, 2-35, 2-36, 2-37, 2-48, 2-49, 2-51, 6-11, 6-12, 6-15, 6-17, 6-20, 6-21, 6-22, 7-7, 8-8, 9-8, 9-9, 14-18, 14-19, 15-13, 15-14, 15-26, 15-27, 16-3, 16-4, 16-5, 16-8, 16-17, 16-20, 16-22, 16-24, 16-25, 16-28, 16-31, 17-3, 17-4, 17-5, 17-6, 17-7, 17-8, 17-9, 17-10, 17-11, 17-13, 17-14, 17-15, 17-16, 17-17, 17-18, 17-19, 17-20, 17-22, 17-23, 17-24, 17-29, 17-30, 17-31, 17-32 deployment descriptor 1-24, 2-19, 2-34, 2-35, 2-36, 2-37, 6-11, 6-12, 6-17, 6-20, 6-21, 6-22, 8-8, 9-8, 9-9, 15-13, 15-14, 15-26, 15-27, 16-3, 16-4, 16-5, 16-8, 16-17, 16-20, 16-22, 16-24, 16-25, 16-28, 16-31, 17-3, 17-6, 17-7, 17-8, 17-9, 17-10, 17-11, 17-15, 17-16, 17-17, 17-18, 17-19, 17-20, 17-22, 17-29, 17-30 deployment plan 17-7, 17-23, 17-24 deployment profiles 17-5 deserializing 7-14 design pattern 1-10, 3-2, 3-4, 3-6, 3-8, 3-12, 3-13, 3-14, 3-20, 3-22, 3-30, 3-31, 6-16, 7-5, 11-3, 11-39 destination 2-18, 6-20, 14-10, 14-11, 14-12, 14-13, 14-15, 14-16, 14-17, 14-18, 14-22, 14-24, 15-13, 17-22 destinationName 14-22 destinationType 14-22 destruction 7-13 detached entity 9-5, 9-6, 9-16 Digest authentication 16-30 DML 8-6 domains 2-43, 14-10, 14-11 durable 14-10, 15-3

Oracle Fusion Middleware 11g: Build Java EE Applications

Index - 5

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

D dynamic 1-11, 1-16, 2-9, 2-19, 2-25, 2-26, 2-29, 2-30, 2-32, 2-51, 3-24, 3-25, 4-2, 4-3, 5-3, 5-4, 5-6, 5-7, 5-8, 5-9, 5-10, 5-20, 5-35, 5-43, 9-2, 9-12, 9-20, 9-21, 9-24, 9-25, 10-4, 11-27, 12-4, 12-13, 12-22, 12-32, 16-17, B-2, B-22, B-32, B-41 dynamic queries 1-16, 2-19, 9-2, 9-20, 9-24, 9-25 E EAR 2-34, 2-49, 6-11, 7-16, 10-12, 10-13, 17-3, 17-4, 17-5, 17-17, 17-18, 17-19, 17-20, 17-22, 17-23, 17-30, 17-31, 17-32 EAR file 2-34, 2-49, 17-5, 17-17, 17-18, 17-19, 17-20, 17-22, 17-23, 17-32 EIS 2-4, 2-5, 2-9, 2-14, 2-35 @EJB 6-16, 6-17, 6-22, 6-24, 7-5, 7-19, 10-17, 16-33 EJB Archives 17-18 EJB container 2-8, 2-14, 2-16, 2-18, 2-19, 3-21, 6-16, 7-3, 7-4, 7-5, 7-6, 7-7, 7-11, 7-12, 7-14, 7-20, 8-3, 14-20, 14-21, 15-27 EJB context 6-20 EJB deployment descriptors 6-11 EJB JAR 17-3, 17-5, 17-17, 17-18, 17-23 ejb-jar.xml 1-24, 2-34, 6-11, 6-12, 15-13, 16-20, 16-22, 16-24, 16-25, 16-28, 17-15, 17-16, 17-32 <ejb-local-ref> 6-11 <ejb-ref> 6-12, 6-22 Enterprise Java Beans 2-21 Entities 1-6, 1-15, 1-16, 2-5, 2-17, 2-18, 2-20, 3-12, 8-1, 8-3, 8-4, 8-5, 8-6, 8-8, 8-10, 8-19, 8-20, 8-28, 9-1, 9-3, 9-4, 9-21, 15-32, 17-20 @Entity 8-3, 8-4, 8-5, 8-7, 8-8, 8-12, 8-14, 8-17, 8-23 EntityManager 1-6, 1-16, 2-18, 2-20, 8-6, 8-28, 9-1, 9-2, 9-3, 9-4, 9-5, 9-6, 9-7, 9-8, 9-9, 9-10, 9-11, 9-12, 9-13, 9-14, 9-15, 9-16, 9-17, 9-18, 9-19, 9-20, 9-21, 9-23, 9-24, 9-25, 15-14, 15-33 EntityManager API 1-6, 1-16, 2-18, 2-20, 8-6, 8-28, 9-1, 9-2, 9-4, 9-5, 9-10, 9-16, 9-18, 9-25

Oracle Fusion Middleware 11g: Build Java EE Applications

Index - 6

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

E <env-entry> 6-20 executeUpdate() 9-21 explicit 4-6, 5-4, 5-15, 6-17, 7-13, 11-29, 12-4, 12-13, 12-28, 14-17, 15-13, 15-14, 15-16, 15-17, 15-27, 15-29, 15-35, 16-6, 16-7, B-7, B-8, B-35, B-38 F faces-config.xml 3-19, 3-20, 11-14, 11-16, 11-24, 11-25, 11-39, 12-4, 12-6, 12-8, 12-9, 12-10, 12-19, 12-22, 12-24, 12-26, 12-28, 12-29, 12-32, 13-17 failover 2-41 field injection 6-18 find() 8-6, 9-5, 9-10, 9-11, 9-14, 9-18, 13-20 flat transactions 15-15 flush() 9-5, 9-10, 9-11, 9-16, 9-19 Form-based authentication 16-30 FROM 5-21, 9-22, 9-23, 9-24 G generate 2-23, 2-25, 2-26, 2-30, 2-32, 2-51, 4-3, 4-9, 4-12, 4-20, 4-21, 5-3, 5-4, 5-8, 5-9, 5-10, 5-11, 5-12, 5-15, 5-22, 5-23, 5-35, 5-42, 5-43, 7-7, 7-11, 8-4, 8-17, 8-18, 9-14, 10-9, 10-12, 10-14, 10-15, 10-18, 10-19, 10-20, 10-21, 10-26, 10-27, 11-8, 11-15, 13-3, 13-5, 13-7, 13-18, 13-22, 15-26, 16-26, 16-30, 16-32, 17-9, 17-18, 17-19, 18-11 generator 8-17, 8-18 getConnection() 3-27, 6-20, 15-33 getResultList() 9-21, 9-23, 9-24 getSingleResult() 9-21, 9-23 getStatus() 15-29 global 5-20, 12-5, 12-6, 12-12, 12-14, 12-15, 12-21, 12-26, 12-32, 14-19, 14-22, 15-5, 15-8, 15-27, 15-29, 15-33, 16-17, B-30 global transaction 15-5, 15-8, 15-27, 15-29, 15-33 groups 11-28, 11-29, 11-36, 16-4, 16-6, 16-7, 16-8, 16-13, 16-15, 16-16, 16-17, 16-19, 16-20, 16-22, 16-25, 17-9, 17-12, B-3, B-8, B-18, B-25

Oracle Fusion Middleware 11g: Build Java EE Applications

Index - 7

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

H Hashtable 6-9, 6-10 helper classes 6-21, 7-19, 17-7 Hibernate 3-21 high availability 2-41 I IBM MQSeries 14-6 @Id 8-3, 8-4, 8-5, 8-7, 8-8, 8-16, 8-17 identities 7-20, 8-16, 16-4, 16-6, 16-22 IDENTITY 8-17 IDL 2-9 impliesAll 16-25 Init 4-6, 4-19, 6-6, 6-9, 6-10, 6-11, 6-12, 7-11, 7-12, 7-18, 7-19, 11-19, 14-24, 15-30, 15-31 initial context 6-3, 6-6, 6-9, 6-11, 6-12, 6-17 initial context factory class 6-9 InitialContext() 6-11, 6-12, 7-11, 7-18, 7-19, 14-24, 15-31 inject 1-13, 1-16, 6-2, 6-16, 6-17, 6-18, 6-19, 6-20, 6-21, 6-22, 6-23, 6-24, 7-5, 7-6, 7-12, 7-19, 7-24, 9-2, 9-7, 9-8, 9-9, 9-14, 9-25, 11-11, 14-20, 14-21, 14-22, 15-30, 15-31 INSERT 9-5, 9-10 integration 1-17, 1-21, 2-17, 2-23, 10-3, 14-5, 18-15 interceptor 1-14, 7-2, 7-20, 7-21, 7-22, 7-23, 7-24 interceptor class 7-22, 7-24 interceptor method 1-14, 7-2, 7-20, 7-21, 7-22, 7-23 InvocationContext 7-21, 7-22 isolated 15-3 J j_security_check 16-30 JAAS 1-3, 1-8, 1-23, 2-10, 2-39, 16-1, 16-2, 16-4, 16-5, 16-6, 16-7, 16-11, 16-20, 16-34, 16-35 JACC 2-8, 2-9 JAF 2-8, 2-9 JARs 17-3, 17-4, 17-17 Java 2 Security Model 16-5, 16-7

Oracle Fusion Middleware 11g: Build Java EE Applications

Index - 8

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

J Java API for XML Processing 2-9 Java API for XML Registries 2-9 Java API for XML Web Services 2-9, 6-17, 10-16 Java API for XML-based RPC 2-9 Java Archive 2-34, 2-35, 17-3 Java Authentication and Authorization Service 1-3, 1-23, 2-10, 16-2, 16-5, 16-6, 16-7, 16-34 Java Database Connectivity 2-9, 3-21, 6-3, 15-13 Java EE 1-3, 1-4, 1-8, 1-9, 1-10, 1-11, 1-13, 1-18, 1-23, 1-24, 1-25, 2-1, 2-2, 2-3, 2-4, 2-5, 2-6, 2-7, 2-8, 2-9, 2-10, 2-11, 2-12, 2-15, 2-16, 2-18, 2-20, 2-22, 2-23, 2-24, 2-25, 2-26, 2-27, 2-28, 2-29, 2-33, 2-34, 2-35, 2-36, 2-37, 2-38, 2-39, 2-40, 2-41, 2-48, 2-49, 2-51, 3-1, 3-2, 3-3, 3-4, 3-6, 3-12, 3-14, 3-20, 3-21, 3-22, 3-23, 3-30, 3-31, 4-2, 4-15, 4-19, 4-21, 4-23, 4-24, 4-25, 4-26, 4-27, 5-9, 6-3, 6-9, 6-11, 6-12, 6-17, 6-18, 6-20, 6-21, 7-9, 8-3, 9-7, 9-8, 9-9, 9-13, 10-12, 10-16, 11-2, 11-4, 14-5, 14-6, 15-15, 15-17, 15-27, 16-1, 16-2, 16-3, 16-4, 16-5, 16-7, 16-8, 16-20, 16-22, 16-25, 16-26, 16-29, 16-30, 16-31, 16-34, 17-1, 17-2, 17-3, 17-4, 17-5, 17-7, 17-9, 17-16, 17-17, 17-19, 17-20, 17-24, 17-30, 17-32, 17-33, 18-2 Java EE Connector Architecture 2-9 Java EE container 2-9, 2-18, 4-15, 5-9, 6-3, 6-11, 6-12, 6-17, 6-18, 6-21, 9-7, 9-13, 14-6, 15-15, 16-3, 16-30 Java EE platform 2-4, 2-6, 2-7, 2-11, 2-22, 2-39, 14-5 Java Interface Definition Language (IDL) 2-9 Java Management Extensions 2-9 Java Message Service 1-21, 2-8, 2-23, 6-3, 14-2, 14-5, 14-26 Java Naming and Directory Interface 1-13, 2-10, 2-39, 6-2, 6-3, 6-23, 7-5, 15-30, 16-34 Java Persistence API 1-3, 1-15, 2-9, 2-15, 2-17, 2-18, 2-19, 2-20, 3-21, 8-3, 9-3, 9-6, 9-10, 15-14 Java Transaction API 2-8, 9-7, 15-12, 15-13, 15-27, 15-28 java.io.Serializable 8-3, 8-7, 8-8, 8-12, 8-17 java.naming.factory.initial 6-9, 6-10

Oracle Fusion Middleware 11g: Build Java EE Applications

Index - 9

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

J java.naming.provider.url 6-9, 6-10 java.naming.security.credentials 6-9, 6-10 java.naming.security.principal 6-9, 6-10 java.security.Principal 16-6 java.util.Hashtable 6-10 java:comp/env 6-11, 6-12, 7-19 java:comp/UserTransaction 15-31 JavaBeans Activation Framework 2-9 JavaMail 2-8 JavaServer Faces 1-3, 1-6, 1-18, 2-4, 2-31, 3-2, 3-12, 3-14, 3-30, 11-1, 11-2, 11-3, 11-6, 11-11, 11-13, 11-18, 11-23, 11-27, 11-39, 12-2, 12-5, 12-22, 13-2, 13-3, 13-18, 13-21, 13-22, 18-7 JavaServer Pages 1-5, 1-12, 2-8, 3-14, 4-2, 5-1, 5-2, 5-3, 11-2 javax.ejb.* 7-8, 7-16 javax.ejb 6-17, 6-20, 7-8, 7-9, 7-10, 7-16, 7-17, 7-21, 14-22, 15-21, 15-25 javax.ejb.AroundInvoke 7-21 javax.ejb.EJBContext.getRollbackOnly() 15-25 javax.ejb.EJBContext.setRollbackOnly() 15-25 javax.ejb.EnterpriseBean 7-8 javax.ejb.InvocationContext 7-21 javax.ejb.Local 7-9, 7-10, 7-17 javax.ejb.Remote 7-9, 7-17 javax.ejb.SessionContext 6-20 javax.ejb.Stateful 7-16 javax.ejb.Stateless 7-8, 7-21 javax.ejb.Timer 6-20 javax.ejb.TimerService 6-20 javax.jms 14-12, 14-22, 14-25 javax.naming.* 6-10, 7-11 javax.persistence.Query 9-21 javax.rmi.PortableRemoteObject.narrow() 6-12 javax.sql.DataSource 6-9, 6-18, 6-20

Oracle Fusion Middleware 11g: Build Java EE Applications

Index - 10

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

J javax.transaction.UserTransaction 15-14, 15-29, 15-30 JAX-RPC 2-8, 2-9, 10-16 JAXP 2-9 JAXR 2-8, 2-9 JCA 2-8, 2-9 JDBC 2-8, 2-9, 2-14, 2-16, 2-26, 2-35, 2-39, 3-21, 3-23, 3-24, 3-25, 3-26, 3-27, 3-28, 3-29, 6-3, 11-10, 14-10, 15-5, 15-13, 15-33, 17-22 JDBC Driver 3-27 JDBC drivers 2-35, 3-23, 3-28, 15-5 JDeveloper 1-11, 1-12, 1-14, 1-15, 1-17, 1-18, 1-24, 1-25, 2-48, 2-49, 2-50, 2-52, 3-17, 3-19, 4-2, 4-9, 4-21, 4-22, 4-24, 4-25, 4-26, 4-27, 4-28, 5-2, 5-42, 5-43, 7-7, 7-11, 7-24, 8-30, 10-2, 10-13, 10-19, 10-21, 10-22, 10-25, 10-26, 10-27, 10-28, 10-29, 11-2, 11-4, 11-23, 11-25, 11-26, 11-39, 12-6, 12-10, 12-12, 12-23, 12-30, 13-5, 13-6, 13-7, 13-8, 13-19, 16-28, 17-2, 17-5, 17-13, 17-18, 17-19, 17-24, 17-31, 17-33, 18-2, 18-5, 18-8, 18-10, 18-13, 18-15, 18-16, 18-17, 18-18 JMS 1-21, 2-8, 2-18, 2-23, 6-3, 6-5, 6-16, 6-17, 6-20, 7-5, 14-2, 14-4, 14-5, 14-6, 14-10, 14-11, 14-12, 14-13, 14-14, 14-15, 14-16, 14-17, 14-18, 14-19, 14-20, 14-22, 14-23, 14-24, 14-25, 14-26, 14-27, 15-5, 15-23, 17-4, 17-22 JMS client 14-6, 14-13, 14-20, 15-5 JMS consumer 14-6, 14-20 JMS destination 2-18, 6-20, 14-17, 14-22, 14-24 JMS producer 14-6 JMS provider 14-6, 14-20, 15-23 JMS queue 2-18, 6-5, 6-20, 14-18 JMS resources 6-16, 6-17, 6-20, 7-5, 14-27 JNDI lookup 2-39, 3-27, 6-17, 7-8, 7-11, 7-19, 9-7 JNDI namespace 6-10, 6-13, 14-6, 15-33 JNDI properties 6-3, 6-9, 6-10, 6-11, 6-12 jndi.properties 6-10, 6-11, 6-12 JOIN 8-14 JoinColumn 8-5, 8-14, 8-15, 8-21, 8-22, 8-23, 8-24, 8-25, 8-26

Oracle Fusion Middleware 11g: Build Java EE Applications

Index - 11

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

J JSF backing beans 3-20 JSF Page 3-20, 11-18, 11-25, 12-10, 12-31 JSF pages 1-18, 3-19, 3-20, 11-2, 11-23, 11-24, 12-33, 16-35, 17-5 JSR-88 17-3 JTA 2-8, 2-39, 9-7, 14-13, 15-7, 15-12, 15-13, 15-27, 15-28, 15-29, 15-30, 15-31, 15-33, 15-35, 17-21 L LDAP 6-3, 6-4, 12-26, 16-7, 16-10, 16-20 LDAP-based 16-20 libraries 1-18, 2-28, 2-35, 3-14, 4-21, 5-30, 6-15, 7-11, 7-21, 11-2, 11-23, 11-25, 11-39, 17-4, 17-10, 17-15, 17-17, 17-23, 17-29 library 5-23, 5-35, 5-36, 5-38, 5-39, 6-3, 7-17, 11-8, 11-13, 11-23, 17-4, 17-15, 17-20 life cycle 1-11, 1-14, 1-16, 1-18, 1-20, 3-20, 4-2, 4-4, 4-6, 4-27, 5-9, 5-36, 5-37, 7-3, 7-12, 7-13, 7-14, 7-19, 8-6, 8-28, 9-3, 9-4, 9-5, 9-6, 9-7, 11-2, 11-4, 11-16, 11-18, 11-19, 11-20, 11-39, 13-2, 13-4, 13-5, 13-7, 13-12, 13-13, 13-17, 13-22, 14-21 @Local 7-7, 7-9, 7-10, 7-17 local and remote interfaces 7-10 local client 6-11, 7-7, 7-9, 7-11 local interface 2-14, 7-7, 7-9, 7-10, 7-11, 7-17, 14-20 logging 1-25, 2-10, 2-45, 7-20, 18-2, 18-7, 18-8, 18-9, 18-18 logical roles 16-4, 16-20, 16-22, 16-25, 16-28 logical security roles 16-8, 16-22, 16-25 Login module authentication 16-6 Login Page 16-30 LoginContext 16-6 look up 1-13, 3-28, 6-2, 6-23 lookup() 6-11, 15-30 lookup 2-19, 2-23, 2-39, 3-6, 3-27, 6-3, 6-9, 6-10, 6-11, 6-12, 6-16, 6-17, 7-5, 7-8, 7-11, 7-18, 7-19, 9-7, 14-24, 15-30, 15-31 loosely coupled 14-3, 14-5 M mail resource 6-20

Oracle Fusion Middleware 11g: Build Java EE Applications

Index - 12

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

mappedName 6-19, 6-22, 7-8, 7-16, 7-19, 7-22, 14-22 mapping 1-11, 1-15, 2-9, 2-19, 2-20, 3-15, 3-18, 3-21, 4-2, 4-23, 4-24, 4-25, 5-32, 6-4, 6-5, 8-2, 8-3, 8-4, 8-5, 8-7, 8-8, 8-10, 8-11, 8-12, 8-14, 8-25, 8-26, 8-28, 8-29, 9-3, 9-15, 10-12, 10-13, 10-14, 11-14, 16-8, 16-25, 17-10, 17-11, 17-15, 17-22 MAX B-15 memory 4-5, 7-3, 7-6, 7-14, 8-6, 8-20, 9-15, 9-16, 11-9, 14-21, 15-4 merge() 8-6, 9-5, 9-10, 9-11, 9-16, 9-17 MERGE 8-23 Message-Driven Beans 1-3, 1-7, 1-21, 1-22, 14-1, 14-20, 15-1 Message-oriented middleware 14-4 MessageConsumer 14-12 @MessageDriven 14-22 MessageDrivenBean 14-20 MessageListener 14-20, 14-22 messageListenerInterface 14-22 MessageProducer 14-12, 14-25 messages 1-21, 2-8, 2-9, 2-17, 2-18, 2-23, 5-20, 10-3, 10-4, 10-5, 10-6, 10-8, 10-9, 10-11, 11-13, 11-20, 13-17, 13-20, 14-3, 14-4, 14-5, 14-6, 14-7, 14-8, 14-10, 14-11, 14-12, 14-13, 14-14, 14-17, 14-20, 14-22, 14-23, 14-24, 14-27, 15-12, 18-7, 18-8, B-40

Oracle Fusion Middleware 11g: Build Java EE Applications

Index - 13

Oracle University and Egabi Solutions use only

M managed beans 1-18, 1-19, 3-19, 3-20, 7-19, 11-2, 11-11, 11-14, 11-16, 11-17, 11-22, 11-24, 11-25, 11-39, 12-2, 12-22, 12-23, 12-24, 12-27, 12-29, 12-32, 13-22 Managed Beans 11-16, 12-22, 12-23, 12-24, 12-27 managed classes 6-21, 7-19 Managed Server 2-45, 2-46 Management 2-9, 15-7, 15-16, 15-17, 15-24, 15-26, 15-30, 15-31, 15-32 MANDATORY 15-17, 15-20, 15-26 ManyToMany 8-5, 8-19, 8-20, 8-23, 8-26 ManyToOne 8-19, 8-20, 8-23, 8-25 MapMessage 14-25 mappedBy 8-20, 8-22, 8-25, 8-26

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

Multitiered 2-4, 2-5 MVC 1-3, 1-10, 1-12, 1-18, 2-31, 2-32, 3-2, 3-6, 3-8, 3-11, 3-12, 3-13, 3-14, 3-19, 3-20, 3-30, 3-31, 5-2, 11-2, 11-3, 11-7, 11-39 N Named Queries 9-23 NamedQuery 9-10, 9-11, 9-12, 9-21, 9-23 @NamedQuery 9-23 native 2-35, 3-25, 5-14, 6-16, 6-22, 7-5, 7-9, 9-10, 9-12, 9-20, 9-21, 9-22, 14-13, B-33 nested transactions 15-15 networking 2-7, 2-10, 2-47 NEVER 15-17, 15-21 newInstance 7-6, 7-12, 14-21 no-op 7-8 no-op methods 7-8 NONE 16-23, 18-7 NOT_SUPPORTED 15-17, 15-23 O O-R mapping 1-15, 3-21 Object) 1-15, 9-21 OBJECT 9-22

Oracle Fusion Middleware 11g: Build Java EE Applications

Index - 14

Oracle University and Egabi Solutions use only

M messageSelector 14-22, 14-23 messaging system 1-21, 14-2, 14-3, 14-5, 14-6, 14-26 META-INF 2-34, 5-38, 17-8, 17-15, 17-17, 17-22 Metadata 10-12 Method level 15-17, 15-26 <method-permissions> 16-22 Model 1-3, 1-10, 1-12, 2-31, 2-48, 3-2, 3-8, 3-9, 3-12, 3-16, 3-20, 3-30, 5-2, 5-22, 8-5, 9-8, 9-9, 9-14, 9-15, 9-17, 9-18, 10-13, 11-26, 12-3, 12-6, 12-10, 12-21, 13-3, 13-13, 14-4, 15-13, 16-5, 16-7, 17-18, 17-19, 18-17, B-38 MOM 14-6 MOM services 14-6

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

onMessage() 14-20, 14-21, 14-22, 15-32 optimistic locking strategy 9-4 Oracle ADF Faces 2-28, 3-12, 11-27 Oracle Advanced Queuing 2-17, 2-18 Oracle JMS 14-6 Oracle JTA 15-13 Oracle TopLink 3-21 P Packaging 1-8, 1-24, 2-33, 2-34, 2-35, 17-1, 17-5, 17-6, 17-32 PAM 2-10, 16-5 passivate 7-13, 7-14 passivated 7-14 passivation 1-14, 7-2, 7-13, 7-14, 7-23 pattern 1-3, 1-10, 3-2, 3-4, 3-5, 3-6, 3-7, 3-8, 3-9, 3-12, 3-13, 3-14, 3-20, 3-22, 3-30, 3-31, 4-24, 6-15, 6-16, 6-21, 7-3, 7-5, 10-18, 11-3, 11-14, 11-39, 12-5, 12-6, 12-12, 12-14, 12-15, 12-21, 13-20, 16-3, 16-5, 16-7, 16-21, 16-22, 16-23, 16-28, 16-31, B-33 Permissions 16-5, 16-6, 16-7 @PermitAll 16-32, 16-33 persist() 8-6, 9-5, 9-6, 9-8, 9-9, 9-10, 9-11, 9-14 PERSIST 8-23, 8-26

Oracle Fusion Middleware 11g: Build Java EE Applications

Index - 15

Oracle University and Egabi Solutions use only

O object-relational 2-9, 2-19, 2-20, 3-21, 8-2, 8-28, 9-3 ObjectMessage 14-25 OC4J 14-6, 14-21 OC4J JMS 14-6 oci 2-44, 3-23, 3-24, 3-26, 4-19, 5-15, 5-22, 5-25, 5-27, 5-41, 6-6, 7-3, 7-22, 8-6, 8-7, 8-19, 8-21, 8-23, 8-25, 8-26, 9-4, 9-5, 9-6, 9-14, 10-5, 10-24, 11-7, 11-9, 11-22, 12-16, 12-18, 12-20, 12-32, 13-5, 14-8, 14-22, 15-8, 15-18, 15-22, 15-23, 15-29, 15-32, 16-4, 16-6, 16-7, 16-8, 16-17, 16-18, 16-28, 17-4, 17-22, B-39 OID 16-10, 16-20 OneToMany 8-5, 8-19, 8-20, 8-23, 8-25 OneToOne 8-5, 8-19, 8-20, 8-21, 8-22

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

P Persistence 1-3, 1-6, 1-15, 1-16, 2-5, 2-9, 2-15, 2-17, 2-18, 2-19, 2-20, 3-21, 8-1, 8-3, 8-6, 8-9, 9-2, 9-3, 9-4, 9-5, 9-6, 9-7, 9-8, 9-9, 9-10, 9-14, 9-15, 9-17, 9-18, 9-20, 9-25, 11-10, 14-14, 15-14, 17-21 persistence context 9-4, 9-5, 9-6, 9-10, 9-11, 9-14, 9-16, 9-18, 9-19 persistence data 8-3 persistence layers 3-12 persistent 2-19, 2-20, 5-16, 7-3, 8-3, 8-6, 8-7, 8-8, 8-16, 9-4, 9-5, 9-6, 9-10, 9-14, 9-20, 14-10, 14-15, 15-5, 15-35 placeholders 9-24 Pluggable Authentication Module 2-10, 16-5 Point-to-Point 14-7 POJO 1-15, 2-15, 2-28, 3-21, 7-8, 8-3, 8-5, 8-7, 10-12, 10-16, 12-22 Policies 16-5, 16-6, 16-7 pool 2-8, 3-2, 3-23, 3-24, 3-25, 3-26, 3-27, 3-30, 4-19, 7-4, 7-6, 7-14, 14-10, 14-21 portability 2-6, 2-14, 3-3, 3-4 Post-activate 7-13 Post-construct callback 14-21 @PostConstruct 7-6, 7-16 Pre-passivate 7-13 presentation layer 3-20, 11-6 primary key 1-15, 1-16, 8-2, 8-3, 8-7, 8-8, 8-14, 8-16, 8-17, 8-18, 8-21, 8-22, 8-23, 8-26, 8-29, 9-2, 9-4, 9-5, 9-11, 9-14, 9-15, 9-17, 9-18, 9-24, 9-25, 18-6 principals 16-4, 16-6, 16-7, 16-8 proceed() 7-21 producer 14-6, 14-7, 14-8, 14-9, 14-12, 14-20, 14-25 produces 2-29, 4-15, 14-6, 18-6, 18-14 programmatic 2-36, 6-10, 9-9, 10-3, 11-16, 15-13, 15-14, B-33 programmatically 6-10, 10-3, 11-16, 15-13, 15-14, B-33 Publish-Subscribe 14-8

Oracle Fusion Middleware 11g: Build Java EE Applications

Index - 16

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

P Publish/Subscribe 14-6 publish/subscribe model 14-5 Q Query API 1-16, 8-6, 9-2, 9-10, 9-14, 9-20, 9-21, 9-23, 9-24, 9-25 Query object 9-10, 9-21, 9-23 R RAR 2-35, 17-3, 17-17 realm 16-6, 16-7, 16-12, 16-14, 16-15, 16-16, 16-17, 16-19, 16-20, 17-22 Realms 16-6, 16-7, 16-12, 16-14 Redeploy 17-4 refresh() 8-6, 9-11 REFRESH 8-23 Relationships 8-19, 8-20, 8-21, 8-22, 8-23, 8-24, 8-25, 8-26, 12-27 reliable 14-5 @Remote 7-7, 7-9, 7-17 remote client 6-11, 6-13, 7-7, 7-10 remote interface 2-14, 7-9, 7-10, 7-11, 8-3, 17-16 Remote Method Invocation 2-10, 2-14, 2-16, 6-3, 6-4, 14-3 Remote Method Invocation- Internet InterORB Protocol 2-10 remove() 8-6, 9-5, 9-6, 9-10, 9-11, 9-15 REMOVE 8-23, 9-15 @Remove 7-13, 7-16 REQUIRED 15-17, 15-18, 15-23, 15-26 REQUIRES_NEW 15-17, 15-22, 15-23 @Resource 6-16, 6-17, 6-18, 6-19, 6-20, 6-24, 7-5, 10-17, 14-22, 15-31 resource adapter 2-35, 17-3, 17-17, 17-32 RMI Registry 6-3 RMI-IIOP 2-10 Roles 16-6, 16-11, 16-17, 16-18, 16-22, 16-23, 16-24, 16-25, 16-29, 16-32, 16-33 @RolesAllowed 16-32, 16-33

Oracle Fusion Middleware 11g: Build Java EE Applications

Index - 17

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

R rollback() 15-25, 15-29, 15-30, 15-31 rollback 9-5, 15-12, 15-13, 15-16, 15-22, 15-25, 15-29, 15-30, 15-31 rules 2-7, 2-12, 2-13, 2-18, 2-25, 3-9, 7-14, 10-10, 10-12, 11-5, 11-14, 11-26, 12-4, 12-5, 12-6, 12-11, 12-14, 12-15, 12-19, 12-21, 12-32, 13-13, 13-14, 13-18, 16-5, 16-7, 16-28 @RunAs 16-32, 16-33 S SAAJ 2-8, 2-9 scalability 2-41, 3-4, 7-14 secondary storage 7-14 security policies 16-3, 16-8, 16-19 security policy 2-25, 16-5, 16-7, 16-10, 16-12 security roles 2-35, 2-36, 16-8, 16-19, 16-21, 16-22, 16-24, 16-25, 16-28, 16-31, 16-32, 17-9, 17-16 Security services 2-39 <security-constraint> 16-23, 16-31 <security-role> 16-22, 16-23, 16-24 SELECT 9-5, 9-10, 9-21, 9-22, 9-23 SEQUENCE 8-17 Serializable 4-14, 8-3, 8-7, 8-8, 8-12, 8-17, 14-25 Service Locator 3-6 service locator pattern 6-21 servlets 1-11, 1-12, 2-4, 2-25, 2-26, 2-28, 2-29, 2-30, 2-33, 2-35, 2-49, 2-51, 3-12, 3-14, 4-2, 4-3, 4-7, 4-8, 4-13, 4-15, 4-21, 4-22, 4-24, 4-25, 4-27, 5-2, 5-3, 5-4, 5-8, 5-27, 5-43, 7-5, 7-19, 17-7, 17-8, 17-9 Session Beans 1-5, 1-14, 7-1, 7-4, 7-24 SessionContext 6-20 setFirstResult(int) 9-21 setMaxResults(int) 9-21 setParameter() 9-23, 9-24 setParameter(String 9-21 setRollbackOnly() 15-25, 15-29 setter (or property) injection 6-18

Oracle Fusion Middleware 11g: Build Java EE Applications

Index - 18

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

S Setter (property) injection 6-18 setter injection 6-18 SFSB 7-4, 7-12, 7-14, 7-18 SFSBs 7-4 SID 8-26 Simple Object Access Protocol 1-17 Single-phase commit 15-27 SLSB 7-4, 7-6, 7-8, 7-11, 7-13, 14-20 SOAP 1-17, 2-9, 2-16, 2-23, 10-2, 10-3, 10-4, 10-5, 10-7, 10-8, 10-9, 10-14, 10-16, 10-17, 10-28 SOAP with Attachments API for Java 2-9 SonicMQ 2-17 SPI 6-3, 6-4, B-32 SQL 1-16, 2-23, 8-6, 9-12, 9-20, 9-21, 10-26, 15-7, 15-33, 18-4 stateful 1-14, 2-18, 7-2, 7-4, 7-12, 7-15, 7-16, 7-17, 7-20, 7-23, 7-24, 11-9, 15-32, 15-35 @Stateful 7-15, 7-16, 7-19, 15-26, 15-31 stateless 1-14, 2-14, 2-18, 2-23, 7-2, 7-4, 7-6, 7-7, 7-8, 7-12, 7-15, 7-16, 7-17, 7-19, 7-20, 7-23, 7-24, 10-16, 14-20, 14-21, 15-32 @Stateless 7-7, 7-8, 7-21, 7-22, 9-8, 16-33 storage 2-5, 2-13, 7-3, 7-14, 8-6, 15-3, 15-5 StreamMessage 14-25 Struts 1-10, 2-48, 3-2, 3-11, 3-14, 3-15, 3-16, 3-17, 3-18, 3-19, 3-22, 3-30, 11-26 subscribe 2-8, 2-18, 14-4, 14-5, 14-6, 14-8, 14-10, 14-11, 14-17 SUPPORTS 15-17, 15-19 suspended transaction 15-22 Swing 2-25, 11-3, 11-6 synchronous 1-3, 1-7, 1-21, 2-17, 14-1, 14-5, 14-20 T TABLE 5-11, 5-12, 8-12, 8-17 @Table 8-3, 8-4, 8-5, 8-7, 8-8, 8-12, 8-14, 8-15, 8-17, 8-22, 8-23, 8-25

Oracle Fusion Middleware 11g: Build Java EE Applications

Index - 19

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

T Tasks 17-27 Test Client 7-11, 7-18 TextMessage 14-25 thin 1-19, 1-25, 2-17, 2-18, 2-36, 2-43, 2-44, 2-49, 3-3, 3-15, 3-19, 3-21, 3-24, 4-6, 4-13, 4-22, 4-27, 5-3, 5-11, 5-14, 5-30, 5-40, 6-11, 6-18, 8-5, 9-4, 10-5, 10-12, 11-8, 11-14, 11-15, 11-17, 11-21, 11-33, 11-34, 11-36, 12-2, 12-23, 12-26, 12-28, 12-29, 13-12, 13-13, 13-18, 14-14, 15-5, 15-8, 15-15, 15-18, 16-13, 17-8, 17-9, 17-22, 17-24, 18-2, B-6, B-9, B-12, B-14, B-25 Timer service 6-20 TimerService 6-20, 7-11 TopLink 3-21, 11-25, 13-16 transaction 1-22, 2-8, 2-14, 2-16, 2-35, 2-39, 3-7, 3-12, 3-21, 7-12, 7-20, 8-28, 9-4, 9-5, 9-6, 9-7, 9-10, 9-16, 10-4, 13-15, 14-10, 14-11, 14-13, 14-20, 15-2, 15-3, 15-4, 15-5, 15-7, 15-8, 15-9, 15-10, 15-11, 15-12, 15-13, 15-14, 15-15, 15-16, 15-17, 15-18, 15-19, 15-20, 15-21, 15-22, 15-23, 15-24, 15-25, 15-26, 15-27, 15-28, 15-29, 15-30, 15-31, 15-32, 15-33, 15-34, 17-16, 17-20, 17-21 transaction attribute 1-22, 2-35, 15-2, 15-13, 15-17, 15-18, 15-19, 15-20, 15-21, 15-22, 15-23, 15-27, 15-34 transaction boundaries 3-12, 9-7, 15-13, 15-14, 15-29 transaction context 9-10, 14-10, 15-5, 15-19, 15-21, 15-22, 15-23, 15-27, 15-30 transaction demarcations 1-22, 15-2, 15-34 transaction manager 1-22, 15-5, 15-7, 15-11, 15-14, 15-27, 15-29 @TransactionAttribute 15-17, 15-18, 15-26 @TransactionManagement 15-16, 15-17, 15-24, 15-26, 15-30, 15-31, 15-32 transactions 1-22, 2-8, 3-7, 8-28, 9-7, 10-4, 14-11, 14-13, 15-2, 15-4, 15-5, 15-7, 15-8, 15-12, 15-13, 15-14, 15-15, 15-16, 15-17, 15-25, 15-27, 15-28, 15-29, 15-30, 15-32, 15-33, 15-34 Transactions 1-7, 1-22, 7-12, 15-1, 15-3, 15-4, 15-5, 15-6, 15-7, 15-14, 15-15, 15-17, 15-30 transient 3-21, 7-3, 7-4 trigger 2-17, 7-12, B-33, B-34, B-35, B-39

Oracle Fusion Middleware 11g: Build Java EE Applications

Index - 20

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

T triggers B-34, B-39 two-phase commit 15-8, 15-9, 15-12, 15-27, 15-33 Two-phase commit 15-27 U UDDI 1-17, 2-9, 2-23, 2-24, 10-2, 10-4, 10-7, 10-8, 10-9, 10-10, 10-28 Undeploy 17-4 URL patterns 16-5, 16-21, 16-22, 16-28, 16-31 <url-pattern> 4-24, 16-23 user groups 16-8 <user-data-constraint> 16-23 V ViewController 17-19 W WAR 2-35, 2-49, 5-38, 17-3, 17-4, 17-5, 17-7, 17-13, 17-20, 17-21, 17-23, 17-29, 17-31, 17-32, 18-7 Web Application Archives 17-13 Web Archive 2-35, 17-3, 17-5, 17-13, 17-31 Web browser 2-4, 2-25, 2-29, 2-51, 3-15, 4-3, 4-4, 4-7, 4-8, 4-15, 4-28, 5-26, 16-26 Web services 1-3, 1-17, 2-3, 2-9, 2-13, 2-14, 2-16, 2-22, 2-23, 2-24, 2-28, 2-36, 2-51, 6-17, 10-2, 10-3, 10-4, 10-6, 10-7, 10-8, 10-9, 10-10, 10-12, 10-16, 10-18, 10-19, 10-26, 10-28, 18-16 Web Services 1-6, 1-17, 2-5, 2-8, 2-9, 2-22, 2-23, 2-24, 6-17, 10-1, 10-2, 10-5, 10-6, 10-9, 10-10, 10-14, 10-16, 17-3 Web tier 1-3, 2-5, 2-25, 2-26, 2-28, 3-12, 7-5 WEB-INF/web.xml 16-29, 17-8 <web-resource-collection> 16-23, 16-31 <web-resource-name> 16-23 Web-tier 2-4, 2-13, 2-25, 2-26, 2-28, 2-32, 2-39, 2-40, 2-48, 2-51, 3-12 web.xml 1-24, 2-34, 3-16, 4-19, 4-20, 4-22, 4-24, 4-25, 6-11, 6-12, 11-14, 11-25, 16-22, 16-23, 16-26, 16-28, 16-29, 16-31, 17-3, 17-6, 17-7, 17-8, 17-9, 17-10, 17-11, 17-29

Oracle Fusion Middleware 11g: Build Java EE Applications

Index - 21

Oracle University and Egabi Solutions use only

THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED

@WebServiceRef 6-17 WSDL 1-17, 2-16, 2-23, 10-2, 10-4, 10-6, 10-7, 10-9, 10-10, 10-11, 10-12, 10-13, 10-14, 10-18, 10-19, 10-20, 10-21, 10-23, 10-24, 10-25, 10-26, 10-27, 10-28 X XML deployment descriptors 17-15 XML descriptor 17-4

Oracle Fusion Middleware 11g: Build Java EE Applications

Index - 22

Oracle University and Egabi Solutions use only

W WebLogic Server 1-9, 1-10, 1-13, 1-24, 2-2, 2-14, 2-41, 2-42, 2-43, 2-44, 2-45, 2-46, 2-47, 2-48, 2-49, 2-51, 3-2, 3-24, 3-25, 3-26, 3-27, 3-28, 3-29, 3-30, 4-6, 4-23, 5-35, 6-5, 6-13, 10-14, 14-7, 14-8, 14-10, 14-11, 14-14, 14-15, 14-16, 14-18, 14-19, 14-22, 14-27, 15-4, 15-5, 15-7, 15-8, 15-12, 15-23, 16-4, 16-10, 16-11, 16-12, 16-13, 16-14, 16-15, 16-17, 16-29, 17-3, 17-4, 17-7, 17-8, 17-9, 17-10, 17-11, 17-14, 17-16, 17-22, 17-23, 17-24 WebLogic Server Administration Console 16-14 WebLogic Server Domain 2-42, 2-43 weblogic-application.xml 16-25, 17-22, 17-32 weblogic-ejb-jar.xml 16-25, 17-15, 17-16, 17-32 weblogic.xml 16-25, 17-6, 17-7, 17-8, 17-9, 17-11, 17-32

You might also like