Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Java EE 6 Component Model Explained
1. <Insert Picture Here>
Java EE Component Model Explained
Shreedhar Ganapathy, Java EE & GlassFish Guy
Oracle Corporation Inc.
2. The following/preceding is intended to outline our
general product direction. It is intended for
information purposes only, and may not be
incorporated into any contract. It is not a
commitment to deliver any material, code, or
functionality, and should not be relied upon in
making purchasing decisions.
The development, release, and timing of any
features or functionality described for Oracle’s
products remains at the sole discretion of Oracle.
2
4. Cloud
Past, Present, Future Flexible Java EE 7
Ease of Multi-tenancy
Development Java EE 6 Elasticity
Pruning
Java EE 5 JSON
Web Extensibility
Ease of Profiles HTML 5
Services Development Web Sockets
Ease-of-dev
Annotations ...
J2EE 1.4 EJB 3.0
EJB Lite
Web Services, Persistence API RESTful WS
Robustness Management, New and CDI
Enterprise Deployment, Updated
Java J2EE 1.3 Async. Web Services
CMP, Connector
Platform
Connector
J2EE 1.2
Architecture Java EE 6
Servlet, JSP, Web Profile
EJB, JMS
JPE RMI/IIOP
Project
Managed
Bean 1.0
May 98 Dec 99 Sep 01 Nov 03 May 06 Dec 09 H2 CY12
10 specs 13 specs 20 specs 23 specs 28 specs ?? specs
4
5. Compatible Java EE 5 Impl
http://java.sun.com/javaee/overview/compatibility-javaee5.jsp
5
8. Java EE 6 Specifications
• The Platform
• Java EE 6 Web Profile 1.0
• Managed Beans 1.0
8
9. Java EE 6 Specifications
New
• Contexts and Dependency Injection for
Java EE (JSR 299)
• Bean Validation 1.0 (JSR 303)
• Java API for RESTful Web Services (JSR 311)
• Dependency Injection for Java (JSR 330)
9
11. Java EE 6 Specifications
Updates
• Java API for XML-based Web Services 2.2 (JSR 224)
• Java API for XML Binding 2.2 (JSR 222)
• Web Services Metadata MR3 (JSR 181)
• JSP 2.2/EL 2.2 (JSR 245)
• Web Services for Java EE 1.3 (JSR 109)
• Common Annotations 1.1 (JSR 250)
• Java Authorization Contract for Containers 1.3 (JSR 115)
• Java Authentication Service Provider Interface for
Containers 1.0 (JSR 196)
11
12. Java EE 6 Specifications
As is
• JDBC 4.0 API
• Java Naming and Directory Interface 1.2
• Java Message Service 1.1
• Java Transaction API 1.1
• Java Transaction Service 1.0
• JavaMail API Specification 1.4
• JavaBeans Activation Framework 1.1
• Java API for XML Processing 1.3
• Java API for XML-based RPC 1.1
• SOAP with Attachments API for Java 1.3
• Java API for XML Registries 1.0
• Java EE Management Specification 1.1 (JSR 77)
• Java EE Deployment Specification 1.2 (JSR 88)
• Java Management Extensions 1.2
• Java Authentication and Authorization Service 1.0
• Debugging Support for Other Languages (JSR 45)
• Standard Tag Library for JSP 1.2 (JSR 52)
• Streaming API for XML 1.0 (JSR 173)
12
15. Java EE 6 – New Concepts
Lightweight & Flexible
• Pruning the unused
• Profiles
• Web Profile Support
• EJB Lite in Web Tier
15
16. Java EE 6 – New Concepts
Ease-Of-Use Programming Model
Improvements
• Managed Beans
• Context and Dependency Injection (CDI)
• Servlet 3.0 annotations support
• EJB 3.1 - Singletons, Stateless and Stateful Bean
Annotations, Timer Service, Portable JNDI Name
• Bean Validation
• JPA 2.0
• JSF 2.0
• JAX-RS
16
17. Java EE 6 – New Concepts
Extensible
• Servlet 3.0 Pluggability
• CDI Extenions
17
18. Lightweight & Flexible
Pruning
• Pruned today, means
• Optional in the next Java EE release
• Deleted in the subsequent releases
• Technologies marked as optional for EE 6
• EJB 2.x Entity Beans,
• JAX-RPC,
• JAXR,
• JSR 88
• Might go away in Java EE 7
18
20. Lightweight & Flexible
Web Profile Support
JSF 2.0
• Subset of full platform
Servlet 3.0
• For web development JSP 2.2
• Packages in a war EL 2.2
JSTL 1.2
• Separate specification
EJB Lite 3.1
• Other Profiles Can Come Managed Beans 1.0
• Minimal (Servlet/JSP) Interceptors 1.1
JTA 1.1
• Portal, etc. JPA 2.0
Bean Validation 1.0
Java CDI 1.0
@Inject 1.0
20
21. Lightweight & Flexible
EJB Lite
• Descriptor OK But
• Subset of EJB 3.1 Optional
API • Annotation-driven
• Part of Web Profile • @Schedule
• Web Apps can package • @Path
Local Session Beans in
WAR • @Inject . . .
• No Interface EJBs
• Session Bean
• Transactions (CMT/BMT)
Programming Model
• Interceptors
• Stateful, Stateless,
• Declarative Security
Singleton
21
23. Programming Model Improvements
Managed Beans
• Separate spec shipped with Java EE 6
• Managed Beans are container- managed
POJOs
• Support a small set of basic services
• Injection (@Resource, @Inject)
• Life-cycle (@PostConstruct, @PreDestroy)
• Interceptor (@Interceptor, @AroundInvoke)
• Lightweight component model
• Foundation for other component types
23
25. EJBs & REST Services are Managed
Beans
• All Managed Beans core services available in
EJBs, and REST Services
• EJB component model extends managed
beans with
• Transaction support,
• Security,
• Multi-threading
• REST Service is a Managed Bean with HTTP
support
25
26. EJBs and REST Service Managed
Beans
New capabilities engaged on demand via
annotations
• @Stateful, @Stateless, @Singleton
• @TransactionAttribute
• @RolesAllowed, @DenyAll, @PermitAll
• @Remote
• @WebService
• @Path
26
27. Incremental Programming Model
• Start with POJOs (@ManagedBean)
• Use all the basic services
• Turn them into session beans as needed
• Take advantage of new capabilities
• No changes to (local) clients
@ManagedBean
public class A {
@Resource DataSource myDB; ....
}
@Stateful
public class A {
@Resource DataSource myDB; ...
}
27
28. Contexts & Dependency Injection
JSR 299
• Standards-based Dependency Injection
• Type-safe – Builds on @Inject API
• Context/Scope management
• Strong Typing, Loose Coupling
• Includes ELResolver
@Inject @LoggedIn User user
Request What ?
Which one ?
Injection (Type)
(Qualifier)
28
30. Contexts and Dependency Injection
(CDI)
• Managed beans on steroids
• Opt-in technology on a per-module basis
• META-INF/beans.xml
• WEB-INF/beans.xml
• @Resource only for container-provided objects
• Use @Inject for application classes
@Inject @LoggedIn User user;
The type describes the capabilities (= methods)
Qualifiers describe qualities/characteristics/identity.
30
31. CDI Extensibility
• Drag-and-drop model
• Bean archives can contain reusable sets of beans
• Extensions can process any annotated types and
define beans on-the-fly
• Clients only need to use @Inject
• No XYZFactoryManagerFactory horrors!
@Inject @Reliable PayBy(CREDIT_CARD) PaymentProcessor;
31
32. Servlet 3.0
• Annotations based programming model
• @WebServlet – Define a Servlet
• @WebFilter – Define a Filter
• @WebListener – Define a Listener
• @WebInitParam – Define Init Param
• @MultipartConfig – Define file upload
properties
• @ServletSecurity – Define security constraints
• Optional web.xml
32
33. Servlet 3.0 Pluggability
• Drag-and-drop model
• Web frameworks as fully configured libraries (Only jars
in WEB-INF/lib considered as fragment)
• META-INF/web-fragment.xml
• Use <web-fragment> instead of <web-app>
• Annotations and web fragments are merged following
a configurable order
• Overridden by main web.xml
• Extensions can register listeners, servlets, filters
dynamically
• Extensions can discover and process annotated
classes
@HandlesTypes(WebService.class)
public class MyWebServiceExtension implements
ServletContanerInitializer { ... }
33
37. Asynchronous Support
• Servlets block waiting for a response
• Now they can start an asynchronous task...
• then, use a container callback ... that invokes
the servlet to end processing
• Better scalability
• New APIs for ServletRequest and Response
• Does not require NIO
37
38. Why Asynchronous Servlets?
• Not for Async IO
• Requests mostly small (single packet)
• Hard to asynchronously produce large
responses
• Async IO support waiting for NIO2
• Async Servlets are for:
• Waiting for resources (eg JDBC connection)
• Waiting for events (eg Chat)
• Waiting for responses (eg web services)
38
39. Blocking Waiting Consumes
Resources
• Web Application using remote web
services
• Handling 1000 requests / sec
• 50% requests call remote web service
• 500 threads in container thread pool
• If remote web service is slow
(1000ms)
• Thread starvation in 1 second!
• 50% of requests use all 500 threads
39
40. WebServlet Async Code Sample
@WebServlet(urlPatterns=“/myApp”,
name=”MyServlet”, asyncSupported=true)
public class SimpleSample extends HttpServlet
{
public void doGet(HttpServletRequest
req,HttpServletResponse res)
{
}
}
40
41. Asynchronous API
Enable asynchronous support
• Configured in
• web.xml:
<async-supported>true</async-
supported>
• With annotation:
@WebServlet(asyncSupported=true)
• Programmatic:
registration.setAsyncSupported(true)
41
42. EJB 3.1
• Packaging in a war
• Interceptors
• Optional Local Interfaces
• Singleton
• Asynchronous calls
• Cron-based Timer Service
• Embeddable Container
• EJB Lite
42
43. EJB 3.1 (JSR 318)
Package & Deploy in a WAR
Java EE 5 Java EE 6
myApp.war
myApp.ear
WEB-INF/classes
web.war com.sun.FooServlet
com.sun.TickTock
WEB-INF/web.xml com.sun.FooBean
WEB-INF/classes com.sun.FooHelper
com.sun.FooServlet
com.sun.TickTock
beans.jar
com.sun.FooBean web.xml ?
com.sun.FooHelper
http://blogs.sun.com/arungupta/entry/totd_95_ejb_3_1
43
45. Optional Local Business Interface
• Sometimes separate local interface isn't needed
• Particularly for fine-grained EJBs whose callers are co-
located
• Better to completely remove this from developer's view
• Result : “no-interface” Local view
• Just a bean class
• All public methods exposed to client
• Client programming model almost identical to local business
interface
• Client does not call new() on bean class
45
46. EJB 3.1 – Sample Session Bean with
No-Interface View, and Client
@Stateless @EJB / @Inject
public class MySessionBean { MySessionBean bean;
@PostConstruct
public void setupResources() { ...
// setup your resources
} bean.sayHello(“Bob”);
@PreDestroy
public void cleanupResources() {
// collect them back here
}
public String sayHello(String name) {
return "Hello " + name;
}
}
46
47. Intercepters 1.1
• Intercepters were part of EJB 3.0 Spec
• Pulled out to address broad EE 6 component needs
• Now a separate spec shipped with EJB 3.1
• Use with EJBs and any ManagedBean
• Intercepters invoked through @AroundInvoke for
ManagedBeans and for Timers through
@AroundTimeout
47
48. Intercepters 1.1
• With CDI, you can use interceptor bindings
@Logged
@ManagedBean
public class A { ... }
where
@InterceptorBinding
public @interface Logged { ... }
and
@Interceptor @Logged
public class Logger {
@AroundInvoke void do(InvocationContext c){...}
}
48
49. Portable Global JNDI Name
• Prior to EJB 3.1, each vendor chose a vendor
specific name to publish EJB references in JNDI
• Client code had to be modified when deployed on other
vendor product
• With EJB3.1, each vendor is required to publish
session beans with spec mandated names
49
50. Portable Global JNDI Names
EJB 3.1 mandates that each session bean is
published in JNDI with the following names
• Globally unique name
java:global[/<app-name>]/<module-name>/<ejb-
name>
• Unique name within same application
java:app/<module-name>/<ejb-name>
• Unique name within defining module
java:module/<ejb-name>
50
51. Portable JNDI Name – No-Interface
Session Bean
@Stateless
public class HelloBean {
public String sayHello(String msg) {
return “Hello “ + msg;
}
}
If deployed as hello.jar, JNDI entries are:
java:global/hello/HelloBean
java:app/hello/HelloBean
java:module/HelloBean
51
52. EJB Singletons
• New session bean component type
• Provides easy sharing of state within application
• Designed for concurrent access
• One bean instance per bean type per VM
• Lots in common with stateless / stateful EJBs
• Provides Local, Remote, Web Service client view
• Supports CMT / BMT
• Same container services are available
• resource managers, timer service, method
authorization, etc.
52
53. Simple Singleton
@Singleton
public class SharedBean {
private SharedData data = new
SharedData();
public int getIntData() {
return data.getIntValue();
}
public void setIntValue(int value {
data.setIntValue(value);
}
}
53
54. Singleton Client
@Stateless
public class FooBean {
@EJB // Inject Singleton reference
private SharedBean shared;
public void foo() {
int value = shared.getIntValue();
...
}
}
54
55. Asynchronous Session Bean Invocations
• Async processing in JavaEE 5 apps
• JavaEE apps resorted to JMS / MDBs
• Must know JMS APIs and setup JMS Queue etc.
• EJB 3.1 makes it very easy
• Annotate your method with @Asynchronous
• Control returns to the client before actual method invocation
• Persistent delivery guarantees are not required by spec
@Stateless Asyc Client
public class DocBean { @EJB DocBean docBean;
@Asynchronous Document d1 = new Document(...);
public void processDoc( Document d2 = new Document(...);
Document d, String toType){ docBean.processDoc(d1, “pdf”);
} docBean.processDoc(d2, “text”);
}
55
56. EJB Timers – Calendar Based Timouts
Problem
• EJB Timer to expire at 5pm on the 14th and one day
before the last day of the month (“payroll” application)
Solution
• Cron-like semantics with improved syntax
• Named attributes
• Relative to optionally specif ed time zone
i
• Can be created programmatically or automatically
56
58. Embeddable API
• Portable API for running EJB components in
same process as client code
• Same component behavior / life cycle as
server-side
• CMT/BMT, injection, threading guarantees, etc.
• “Single Application” model
• Only required to support 3.1 “Lite” API
• Vendors can optionally support additional functionality
58
59. Embeddable API Sample
public class BankTester {
public static void main(String[] args) {
EJBContainer container =
EJBContainer.createEJBContainer();
// Acquire Local EJB reference
Bank bank = (Bank)
container.getContext().
lookup(“java:global/bank/BankBean”);
double balance = bank.deposit(100.00);
...
container.close();
}
}
59
61. JPA 2.0
• Evolves separately from EJB now
• JSR 317
• Richer mappings
• Richer JPQL
• Pessimistic Locking
• Criteria API
• Cache API
61
62. Richer Mapping
• Supports collection of embeddables and
basic types
• Supports multiple levels of embeddables
• Embeddables containing collection of
embeddables and basic types
• PK can be derived entities
• More support for Maps
62
63. Java Persistence API 2 (JSR 317)
•Improved O/R mapping
•Type-safe Criteria API
•Expanded and Richer JPQL
•2nd-level Cache
•New locking modes
•PESSIMISTIC_READ – grab shared lock
•PESSIMISTIC_WRITE – grab exclusive lock
•PESSIMISTIC_FORCE_INCREMENT – update
version
•Standard configuration options
•javax.persistence.jdbc.[driver | url | user | password]
63
64. Java Server Faces 2.0 (JSR 314)
• Facelets as “templating language” for the page
• Custom components much easier to develop
• Integrated Ajax
• “faces-config.xml” optional in common cases
• Default navigation rules
• Much more …
• Runs on Servlet 2.5+
• Bookmarkable URLs
• Conditional navigation
• ...
64
65. Bean Validation (JSR 303)
• Tier-independent mechanism to define
constraints for data validation
• Represented by annotations
• javax.validation.* package
• Integrated with JSF and JPA
• JSF: f:validateRequired, f:validateRegexp
• JPA: pre-persist, pre-update, and pre-remove
• @NotNull(message=”...”), @Max, @Min,
@Size
• Fully Extensible
• @Email String recipient;
65
66. JAX-RS 1.1 (JSR 311)
• Java API for building RESTful Web Services
• POJO based
• Annotation-driven
• Server-side API
• HTTP-centric
66
67. JAX-RS 1.1
Code Sample - Simple
@Path("helloworld")
@Produces("text/plain")
public class PersonResource {
@Context UriInfo ui;
@GET
public List<Person> getPersons() {
return personList;
}
@GET
@Path("{id}")
public Person getPerson(@PathParam("id")int id) {
return getPersons().get(id);
}
}
67
69. 9 Reasons why Java EE 6 will save $$
• Prototyping (multiple IDEs)
• Development (~30MB, incremental deployment, ...)
• Production (Variety, Start small/then scale)
• Support (Pick the best one)
• Training (“Only” Java EE 6 APIs)
• Portability (Backwards compatibility)
• Adoption (Growing)
• Freedom of choice (Multiple vendors)
• Plan B (Similar component models)
http://www.adam-bien.com/roller/abien/entry/8_reasons_why_java_ee
69
70. Jigsaw puzzle,
From the real users ... Modular, standard, less
xml, easy, easy, have I
Developers can concentrate said easy?
on business logic, Java EE 6 is
providing a standard for
Standards compliance, vendor
the infrastructure.
independence, milliseconds
and kilobyte deployment
Faster development,
Higher integrated specs, less frameworks, less
simple and annotation driven, complexity, more great
single-classloader WARs, code shipped
next level of industry
standard Definite excuse to
avoid Spring forever
Simplified Java
Not your fat grandfather's Development, Focus on
enterprise Java anymore, building great products
enterprise Java renaissance
http://blogs.sun.com/arungupta/tags/community+feedback
70
71. Avoid “framework explosion”
In selecting an application server our main goal
was to avoid the framework explosion that
happens when you use a "custom" Enterprise
stack like Tomcat + Spring + Hibernate +
Myfaces +... Java EE 6 had 80% of what we
needed out of the box: strong persistence
support ( JPA ), inversion of control ( CDI ), and
a lightweight component model ( EJB 3.1 )
http://blogs.sun.com/stories/entry/egesa_engineering_avoids_framework_explosion
71
72. What does Java EE offer to Cloud ?
●
Containers
●
Injectable services
●
Scale to large clusters
●
Security model
●
...
72
73. Java EE 7 : JSR 342 NEW
• Theme: Cloud
• More easily operate on private or public clouds
• Deliver functionality as a service with support for
features such as multi-tenancy and elasticity
• Technology refresh: JMS 2.0, CDI 1.1, ...
• Latest web standards: HTML 5 and Web Sockets
• Possible JSRs inclusion
• Concurrency Utilities for Java EE (JSR 236)
• JCache (JSR 107)
• New JSRs: Web Sockets, Java JSON API
• Modularity and Versioning
73
74. What is GlassFish ?
• A community
• Users, Partners, Testers, Developers, ...
• Started in 2005 on java.net
• Application Server
• Open Source (CDDL & GPL v2)
• Basis for Java EE Reference Implementation
74
75. GlassFish Server Distributions
Distribution License Features
• Java EE 6 compatibility
GlassFish Server Open CDDL & • Web Profile support
Source Edition 3.1 GPLv2 • In-memory replication / clustering
Web Profile
• Centralized Administration
• Java EE 6 compatibility
GlassFish Open Source CDDL & • Full Java EE distribution
Edition 3.1 GPLv2 • In-memory replication / clustering
• Centralized Administration
• Adds
Oracle GlassFish Server 3.1 Commercial • Oracle GlassFish Server Control
Web Profile • Patches, support, knowledge
base
• Adds
Oracle GlassFish Server 3.1 Commercial • Oracle GlassFish Server Control
• Patches, support, knowledge
base
80. JPA 2.1 (JSR 338)
http://jcp.org/en/jsr/detail?id=338 NEW
http://jpa-spec.java.net
●
Multi-tenancy
●
Support for stored procedures, vendor function
●
Update and Delete Criteria queries, JPQL ↔
Criteria
●
Query by Example
●
Support for schema generation
●
Persistence Context synchronization control
●
Dynamic definition of PU
●
Additional event listeners
80
81. JAX-RS 2.0 (JSR 339) NEW
http://jcp.org/en/jsr/detail?id=339
http://jax-rs-spec.java.net
●
Client API
●
Low level using Builder pattern, Higher-level
●
Hypermedia
●
MVC Pattern
●
Resource controllers, Pluggable viewing technology
●
Bean Validation
●
Form or Query parameter validation
●
Closer integration with @Inject, etc.
●
Server-side asynchronous request processing
●
Server-side content negotiation
81
82. Servlets 3.1 (JSR 340) NEW
http://jcp.org/en/jsr/detail?id=340
http://servlet-spec.java.net
• Cloud support
• Multi-tenancy
• Security / Session state / Resources isolation
• Asynchronous IO based on NIO2
• Simplified Asynchronous Servlets
• Utilize Java EE concurrency utilities
• Enable support for Web Sockets
82
83. Expression Language 3.0 (JSR 341) NEW
http://jcp.org/en/jsr/detail?id=341
http://el-spec.java.net
• A JSR by itself
• Make EL easier to use outside EE container
• Simplified to use in Java SE
• EL Context is split into Parsing and
Evaluation context
• Explicit coercion rules using API
• Criteria-based selection from Collection
• Operators: ==, concat, sizeof
• CDI events for expression evaluation
83
84. JMS 2.0 (JSR 343) NEW
http://jcp.org/en/jsr/detail?id=343
http://jms-spec.java.net
• Long overdue – after 9 years
• Modest scope, major extensions
deferred to a subsequent revision
• Ease-of-development
• Clarification of relationship with other
Java EE specs
• New mandatory API for pluggable JMS
provider
84
85. JSF 2.2 (JSR 344) NEW
http://jcp.org/en/jsr/detail?id=344
http://jsf-spec.java.net.
• Ease of development
• cc:interface is optional
• JSF lifecycle is CDI aware
• Runtime configuration options change
• Support implementation of Portlet Bridge 2.0
• Support for HTML5 features
• Forms, Heading/Section content model, ...
• New components like FileUpload and
BackButton
85
86. EJB 3.2 (JSR 345)
http://jcp.org/en/jsr/detail?id=345 NEW
• Enablement for use in cloud
• Factorization of the EJB technology
• Interceptors was the first example
• Container-managed transactions as target
• Alignment with other specifications
• Mark “pruned” technologies as optional
• EJB 1.x and 2.x entity beans
• Web service invocation using JAX-RPC
86
87. CDI 1.1 (JSR 346)
http://www.jcp.org/en/jsr/proposalDetails?id=346 NEW
• Global ordering of interceptors and
decorators
• API for managing built-in contexts
• Embedded mode to startup outside Java
EE container
• Send Servlet events as CDI events
87
88. Bean Validation 1.1 (JSR TBD)
http://in.relation.to/Bloggers/JSRBeanValidation11WhatToPutIn NEW
• Integration with other specs
• JAX-RS: Validate parameters on HTTP calls
• JAXB: convert into XML schema descriptor
• JPA: DDL generation
• Method level validation
public void processOrder(@Valid Order order,
@Min(0) @Max(30) int retry) {
}
• @Valid and group propagation
• Apply constraints on element collection
88
89. Data Grids (JSR 347)
http://jcp.org/en/jsr/detail?id=347 NEW
• Accessing, storing, managing data in a
distributed data grid
• Build and extend JSR 107 (JCache)
• Map-like API to access a Cache
• Spooling in-memory data to persistent storage
• Register event listeners
• Eviction, replication and distribution of data
• Transactions
• Async and non-blocking API to access data
•
89
90. Transparency Checklist NEW
http://jcp.org/en/resources/transparency
• EG members names
• EG business reported on publicly
readable alias
• Schedule is public, current and updated
regularly
• Public can read/write to a wiki
• Discussion board on jcp.org
• Public read-only issue tracker
90
91. <Insert Picture Here>
Java EE 6 Core Programming Model Explained
Shreedhar Ganapathy, Java EE & GlassFish Guy
Oracle Corporation Inc.