Intro to J2EE 5
Transcript of Intro to J2EE 5
Agenda
Java EE 5 Theme: Ease of development EJB 3.0
Programming model Persistence
JAXB 2.0 JAX-WS 2.0(Used to be called JAX-RPC) JavaSever Faces 1.2 JBI 1.0 (Java Business Integration) & SOA
Not part of Java EE 5
The J2EE ChallengeTM
J2EE is enormously powerful
The industry standard for robust enterprise appsToo difficult to get started Even simple apps need boring boilerplate
But that power sometimes gets in the way
Can we keep the power, but make typical development tasks simpler?
YES: and that is the focus of Java EE 5!
EoD Improvements in JavaTM EE 5
POJO-based programming
More freedom, fewer requirements Reduced need for deployment descriptors Inversion of control
Extensive use of annotations
Resource Injection
New APIs and frameworks
Annotations in JavaTM EE 5
Making extensive use of annotations
For defining and using web services To map Java classes to XML To greatly simplify EJB development To map Java classes to databases To specify external dependencies To reduce need for deployment descriptors
JavaTM EE 5 Major Features
Simplified web services support More web service standards support Greatly simplified EJBTM development New persistence API Easy web applications with JavaServerTM Faces
Java EE 5 Platform
JSR 220 (EJB 3.0) JSR 224 (JAX-WS 2.0) JSR 222 (JAXB 2.0) JSR 252 (JavaServer Faces 1.2) JSR 52 (JSTL 1.1) JSR 181 (WS Annotations) JSR 245 (JSP 2.1)
EJB 3.0
Primary Goal of EJB 3.0
Ease of Development!
EJB 2.1
Very powerful, but complex to use
Too many classes, interfaces Java Naming and Directory Interface (JNDI) API lookups javax.ejb interfaces Awkward programming model Deployment descriptors Entity bean anti-patterns ...
Ease of Development in EJB 3.0
Makes EJB technology easier to learn and use
Fewer classes and interfaces Dependency injection Simple lookups No required container interfaces No required deployment descriptor Simplified persistence Object/relational mapping Improves developer productivity
Designed to draw new developers to J2EE platform
Compatibility and Migration
All existing applications continue to work Provides integration path for preexisting applications and components Allows components to be updated or replaced (using EJB 3.0 APIs) without affecting existing clients Facilitates EJB 3.0 technology adoption with incremental migration
EJB 3.0 Approach
Simplification of the EJB APIs Removal of need for EJBHomes and EJBObjects Removal of JNDI APIs from developer and client view Elimination of need for deployment descriptors Utilizes advantages of Java language metadata
Leverages defaulting for typical cases Metadata designed so that the most common cases are the easiest to express
EJB 3.0 Approach
More work is done by container, less by developer Inversion of contracts
Bean specifies what it needs through metadata
No longer written to unneeded container interfaces
Container interpositions to provide requested services
Simplification of EJB Bean Types
Elimination of requirement for EJB component interfaces
Business interfaces are plain Java interfaces Elimination of requirements for Home interfacesOnly need business interface, not home Elimination of requirements for javax.ejb.EnterpriseBean interfaces Annotations for (optional) callbacks Elimination of need for use of JNDI API
Use dependency injection, simple lookup method
EJB 2.1 Example// EJB 2.1 public class PayrollBean implements javax.ejb.SessionBean {
SessionContext ctx; DataSource empDB;public void setSessionContext(SessionContext ctx) { this.ctx = ctx; } public void ejbCreate() { Context initialContext = new InitialContext(); empDB = (DataSource)initialContext.lookup( java:comp/env/jdbc/empDB); }
EJB 2.1 Example// EJB 2.1 (cont.) public void ejbActivate() {} public void ejbPassivate() {} public void ejbRemove() {} public void setBenefitsDeduction (int empId, double deduction) { ... Connection conn = empDB.getConnection(); ... } ... } // NOTE deployment descriptor needed
EJB 2.1 Example PayrollBean PayrollHome Payroll com.example.PayrollBean Stateless Container jdbc/empDB javax.sql.DataSource Container ... ...
EJB 3.0 Example// Same example, EJB 3.0 @Stateless public class PayrollBean implements Payroll {
@Resource DataSource empDB;public void setBenefitsDeduction (int empId, double deduction) { ... Connection conn = empDB.getConnection(); ... } ... }
Dependency Injection
Resources a bean depends upon are injected when bean instance is constructed References to:
EJBContext DataSources UserTransaction Environment entries EntityManager TimerService Other EJB beans ...
Dependency Injection
Annotations
@EJB
References to EJB business interfaces References to Home interfaces (when accessing EJB 2.1 components) Almost everything else
@Resource
Number of annotations is simplified from EJB 3 specification early draft
Injection can also be specified using deployment descriptor elements
Simplified Client View
Session beans have plain Java language business interface
No more EJB(Local)Home interface No more EJB(Local)Object interface Looks like normal Java class to bean developer
Bean class implements interface
Looks like normal Java language interface to client (POJI)
EJB 2.1 Client Example// EJB 2.1 Client view of the ShoppingCart bean ... Context initialContext = new InitialContext(); ShoppingCartHome myCartHome = (ShoppingCartHome) initialContext.lookup(java:comp/env/ejb/cart); ShoppingCart myCart= myCartHome.create(); //Use the bean Collection widgets = myCart.startToShop(widgets) ... // Don't forget code to handle javax.ejb.CreateException ...
EJB 3.0 Client Example// EJB 3.0 client view @EJB ShoppingCart myCart; ... Collection widgets = myCart.startToShop(widgets); ...
Container Services: TransactionsContainer-managed transaction (CMT) by default
Bean-managed transaction (BMT) by annotation
Container-managed transactions REQUIRED transaction attribute by default Any transaction attribute by annotation Specified at class level => applies to all business methods of the class Specified at method level => applies to method (overriding any class-level specification) Typical case (CMT + REQUIRED) is default
EJB 3.0 Transaction Example// Uses container-managed transction, REQUIRED attribute @Stateless public PayrollBean implements Payroll { public void setBenefitsDeduction(int empId, double deduction) {...} public double getBenefitsDeduction(int empId) {...} public double getSalary(int empId) {...}
public void setSalary(int empId, double salary) {...}}
EJB 3.0 Transaction Example@Stateless public PayrollBean implements Payroll { @TransactionAttribute(MANDATORY) public void setBenefitsDeduction(int empId, double deduction) {...} public double getBenefitsDeduction(int empId) {...} public double getSalary(int empid) {...} @TransactionAttribute(MANDATORY) public void setSalary(int empId, double salary) {...} }
Container Services: Security
Security configuration typically done at deployment in enterprise environments
Developer can provide guidance Security attributes
If not specified => set on deployment or unchecked Method permissions by annotation Specified at class level => applies to all business methods of the class Specified at method level => applies to method (overriding any class-level specification) @Unchecked, @RolesAllowed
EJB 3.0 Security Example// Security view @Stateless public PayrollBean implements Payroll { public void setBenefitsDeduction(int empId, double deduction) {...} public double getBenefitsDeduction(int empId) {...} public double getSalary(int empid) {...} // salary setting is intended to be more restricted @RolesAllowed(HR_PayrollAdministrator) public void setSalary(int empId, double salary) {...} }
Container Services: Event Notification
Container calls bean upon lifecycle events
@PostConstruct @PreDestroy @PrePassivate @PostActivate Removes boilerplate code, magic methods ejbCreate, ejbRemove... just become special cases
Bean specifies events it needs to know about
Callback methods can be specified on lifecycle listener class instead of on bean class
EJB 3.0 Event Notification Example class AccountManagementBean @Stateful publicimplements AccountManagement { Socket cs; @PostConstruct @PostActivate public void initRemoteConnectionToAccountSystem { ... } @PreDestroy @PrePassivate public void closeRemoteConnectionToAccountSystem { ... } ... }
Interceptors
Ease of use facility for more advanced developers Interception of invocations of business methods and/or message listener methods Invocation model: around methods
Wrapped around business method invocations Interceptor has control over invocation of next method Can manipulate arguments and results Context data can be carried across invocation chain Execute in specified order Can use deployment descriptor to override order or add interceptors
Example@Interceptors({ com.acme.AccountAudit.class, com.acme.Metrics.class, com.acme.CustomSecurity.class }) @Stateless public class AccountManagementBean implements AccountManagement { public void details) {...} public void public void public void ... } createAccount(int accountId, Details
deleteAccount(int accountId) {...} activateAccount(int accountId) {...} deactivateAccount(int accountId) {...}
EJB 3.0
Persistence
Persistence Goals of EJB 3.0
Simplify entity bean programming model Support for light-weight domain modeling, including: Inheritance and polymorphism Complete query capabilities Support for object/relational mapping specification Make entity instances usable outside the EJB container
Remove need for DTOs and similar antipatterns
Persistence Model in EJB 3.0
Entities are simple Java classes
Concrete classessupport use of newGetter/setter property methods or persistent instance variables No required bean interfaces No required callback interfaces
Usable as detached objects in other application tiers
No more need for DTOs
EntityManager
EntityManager serves as untyped home for entity operations
Methods for lifecycle operations
Persist, remove, merge, flush, refresh, etc.
Similar in functionality to Hibernate Session, JDO PersistenceManager, etc. Manages persistence context
Both transaction-scoped and extended persistence contexts
Persistence Focus: O/R Mapping
Ease-of-use facility for Java developers mapping domain object model to a relational database Developer is aware of mapping between DB schema and domain object model Developer is in control of mapping Developer can rely on mapping and its semantics Mappings may be expressed using metadata annotations or XML
Default mappings provided
Current Status
Public draft released June, 2005 Three (3) public draft documents
EJB Simplified API Java Persistence API EJB Core Contracts and Requirements
Several preview releases now available
Web Services: JAX-WS, JAXB
Java Support for Web Services
JAX-RPC 2.0 renamed to JAX-WS 2.0 (Java API for XML Web Services) Implements new WS stack
JAX-WS 2.0 and JAXB 2.0 Designed for growth (JAX-WSA, others) Ease-of-development Portability Better Performance
Heavy use of annotations
Supports Fast Infoset
JAX-WS and JAXB Integration
JAX-WS delegates all data binding to JAXBDevelopment time JAXB generates Java types from a WSDLs schemas JAXB generates the WSDLs schema from Java types Runtime
JAX-WS un/marshalls the message (soap:envelope) JAXB un/marshalls the payload (soap:body child, soap:header and soapfault elements) StAX based parser is the handoff
Division of Labor 33 JAX-WS JAXB Fred Jones
JAXB 2.0
JAXB 2.0 Is Now Bi-Directional
1.0: Schema
Java only
JAXB is for compiling schema Dont touch the generated code
2.0: Java
XML + schema compiler
JAXB is about persisting POJOs to XML Annotations for controlling XML representation Modify the generated code to suit your taste
JAX-WS 2.0
JAX-RPC 1.1 RI Issues
Supports only SOAP 1.1over HTTP Limited XML Schema support Little Control of Mapping Java and WSDL/ XML Schema Large non-portable applications Large runtime Web Service development is too complex Servlet container is required
JAX-WS 2.0 RI
New Architecture Improved Data Binding Annotations Java SE 6 Endpoints
JAX-WS 2.0 New Architecture
Multiple protocols
SOAP 1.1, SOAP 1.2, XML XML, MTOM/XOP, FAST Infoset (Binary XML) HTTP Others to be added in future releases
Multiple encodings
Multiple transports
Improved Data Binding
JAX-RPC 1.1 IssuesDefines its own data binding rules Only a portion of XML Schema supported javax.xml.soap.SOAPElement (DOM) No control of the generated Java SEI JAX-WS 2.0
Uses JAXB 2.0 for data binding (100% XML Schema) Very few DOM-like mappings Customizations to control the generated SEI
Customizations in WSDL/XML Schema to Java Mapping
JAXB customizations
XML Schema to Java Similar to JAXB customizations WSDL to Java In-lined in the WSDL as WSDL extension As external file (pass to JAX-WS tools)
JAX-WS customizations
Can live
Customizations Example
JBI 1.0: Foundation for SOA
What Is SOA?A set of services that a business wants to expose to customers and clients An architectural style which requires a service provider, requestor and a service description A set of architectural principles and patterns which address characteristics such as modularity, encapsulation, loose coupling, separation of concerns, reuse, composable and single implementation A programming model complete with standards, tools, methods and technologies such as web servicesArchitecture
RolesBusiness
Implementation
SOA Architectural PrinciplesCoarse Grained Business Services XML Document-based
Mostly Async
Conversational
SOA Architectural PrinciplesReliable Secure/Identity
Policy Driven
Registered and Retrieved
SOA Architectural PrinciplesWSDL Described BPEL Orchestrated
JBI-based
What is JBI (JSR-208)?
JBI does for application integration what J2EE did for application development
One of the biggest motivation for SOA is to reduce the cost of application integration
Open, pluggable infrastructure for integrating applications
Standards-based way to build an Enterprise Service Bus (ESB) for the Java platform
Why JBI?
Standard framework
Solves M * M adaptors (connectors) problem for application integration Integration components from multiple vendors can be plugged-in Portability with innovation in implementation Abstract, technology-neutral model of services De-coupling of interface from implementation
Vendor independent integration framework
Standard service description via WSDL
Scope of JBI Specification
Standard framework for pluggable Service Engines (SE's) Binding Components (BC's) Defining abstract communication protocolneutral Normalized Message Service (NMS) Standard mechanism for Normalized Messages to flow between Binding Components and Process Engines Standard for the packaging and deployment of SE's and BC's
JBI Architecture
JavaServer Faces 1.2
JavaServer Faces (JSF) Framework IsA server side user interface (UI) component framework for Java technology-based web applications. Drag-and-drop UI components to build a web Application.
JSF ArchitectureServerJSF Page
Desktop Browser
HTML HTML RenderKit
Fron t ctrl
JSF Page WML RenderKit
App Backen d
PhoneWML
Important Basic Capabilities
Extensible UI component model Flexible rendering model Event handling model Validation framework Basic page navigation support Internationalization Accessibility Tool friendly