Java EE Patterns Dan Bugariu. What is Java EE ? What is a Pattern ?
Spark IT 2011 - Java EE 6 Workshop
-
Upload
arun-gupta -
Category
Technology
-
view
2.455 -
download
3
description
Transcript of Spark IT 2011 - Java EE 6 Workshop
<Insert Picture Here>
Understanding the Nuts & Bolts of Java EE 6
Arun Gupta, Java EE & GlassFish Guyblogs.sun.com/arungupta, @arungupta
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.
3
#glassfish#sparkit2011
Are you tweeting ?
4
JPEProject
J2EE 1.2Servlet, JSP,
EJB, JMSRMI/IIOP
J2EE 1.3CMP,
ConnectorArchitecture
J2EE 1.4Web Services, Management, Deployment, Async. Connector
Java EE 5Ease of DevelopmentAnnotationsEJB 3.0JPANew and Updated Web Services
Robustness
Web Services
Enterprise Java
Platform
Java EE 6PruningExtensibilityProfilesEase-of-devEJB LiteRESTful WSCDI
Ease ofDevelopment
FlexibleJava EE: Past, Present, Future
May 1998 Dec 1999 Sep 2001 Nov 2003 May 2006 Dec 2009 10 specs 13 specs 20 specs 23 specs 28 specs
Web Profile
ManagedBean 1.0
Java EE 7HTML 5WebSocketJSON APIJCacheMulti-tenancyElasticityTech Refresh. . .
Cloud
Q3 2012?? specs
NEW
5
Compatible Java EE 6 Impls
Today:
Announced:
Web Profile Only
6
• Java EE 6 Web Profile• Pruning
• Pruned today, means• Optional in the next release• Deleted in the subsequent releases
• Technologies marked in Javadocs• EJB 2.x Entity Beans, JAX-RPC, JAXR, JSR 88
Light-weight
7
• EJB-in-WAR• No-interface EJB• Optional
“web.xml”/”faces-config.xml”
• Annotation-driven• @Schedule• @Path• @Inject• . . .
8
<web-fragment> <filter> <filter-name>wicket.helloworld</filter-name> <filter-class>org.apache.wicket.protocol.http.WicketFilter</filter-class> <init-param> <param-name>applicationClassName</param-name> <param-value>...</param-value> </init-param> </filter>
<filter-mapping> <filter-name>wicket.helloworld</filter-name> <url-pattern>/*</url-pattern> </filter-mapping></web-fragment>
9
Java EE 6 - Done
• Specifications approved by the JCP• Reference Implementation is GlassFish
Server Open Source Edition 3• TCK
Dec 1
0th 2
009
10
Java EE 6 Web Profile 1.0
Servlets 3.0
JSP 2.2
JSF 2.0
EJB 3.1 Lite
JTA 1.1ManagedBeans 1.0
JPA 2.0
CDI 1.0
BeanValidation1.0
Interceptors1.1
JAX-WS
JAX-RS
JAXB
EJB 3.1
JASPIC
JDBC
JNDI
JMS
JAXP
JAX-RPC . . .
SAAJ
JACC
JavaMail
StAX
New Updated Contributed by RedHat
11
Managed Beans 1.0
EJB CDI JPAJAX-WS JAX-RSJSF ...
@Stateful@Stateless@Singleton
@Named @Entity@WebService
@Path@Managed
Bean...
EJB
@javax.annotation.ManagedBean
12
Managed Beans 1.0
• POJO as managed component for the Java EE container• JavaBeans component model for Java EE• Simple and Universally useful• Advanced concepts in companion specs
• Basic Services• Resource Injection, Lifecycle Callbacks, Interceptors
• Available as• @Resource / @Inject• java:app/<module-name>/<bean-name>• java:module/<bean-name>
13
Lab #1Managed Beans
14
public class MyManagedBean {
public void setupResources() { // setup your resources }
public void cleanupResources() { // collect them back here }
public String sayHello(String name) { return "Hello " + name;
}
}
Managed Beans 1.0 - Sample
@ResourceMyManagedBean bean;
@javax.annotation.ManagedBean @PostConstruct
@PreDestroy
@InjectMyManagedBean bean;
http://blogs.sun.com/arungupta/entry/totd_129_managed_beans_1
15
Interceptors 1.1
• Interpose on invocations and lifecycle events on a target class
• Defined• Using annotations or DD• Default Interceptors (only in DD)
• Class & Method Interceptors• In the same transaction & security context
• Cross-cutting concerns: logging, auditing, profiling
16
Lab #2Interceptors
17
Interceptors – Business Method (Logging)
@InterceptorBinding@Retention(RUNTIME)@Target({METHOD,TYPE})public @interface LoggingInterceptorBinding {}
@LoggingInterceptorBindingpublic class MyManagedBean { . . .}
@Interceptor@LoggingInterceptorBindingpublic class @LogInterceptor { @AroundInvoke public Object log(InvocationContext context) { System.out.println(context.getMethod().getName()); System.out.println(context.getParameters()); return context.proceed(); }}
18
Why Interceptor Bindings ?
• Remove dependency from the interceptor implementation class
• Can vary depending upon deployment environment
• Allows central ordering of interceptors
19
Interceptors – Business Method (Transaction)
@InterceptorBinding
@Retention(RUNTIME)@Target({METHOD,TYPE})public @interface Transactional {}
@Transactionalpublic class ShoppingCart { . . . }
public class ShoppingCart { @Transactional public void checkOut() { . . . }
@Interceptor@Transactionalpublic class TransactionInterceptor { @Resource UserTransaction tx; @AroundInvoke public Object manageTransaction(InvocationContext context) { tx.begin() context.proceed(); tx.commit(); }}
http://blogs.sun.com/arungupta/entry/totd_151_transactional_interceptors_using
20
Servlets in Java EE 5At least 2 files
<!--Deployment descriptor web.xml -->
<web-app><servlet> <servlet-name>MyServlet
</servlet-name> <servlet-class> com.sun.MyServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name>MyServlet </servlet-name> <url-pattern>/myApp/* </url-pattern> </servlet-mapping> ... </web-app>
/* Code in Java Class */
package com.sun;public class MyServlet extends HttpServlet {public void doGet(HttpServletRequest req,HttpServletResponse res)
{
...
}
...
}
21
Servlets 3.0 (JSR 315)Annotations-based @WebServlet
http://blogs.sun.com/arungupta/entry/screencast_37_java_ee_6
package com.sun;@WebServlet(name=”MyServlet”, urlPatterns={”/myApp/*”})public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
{...
}
<!--Deployment descriptor web.xml -->
<web-app><servlet> <servlet-name>MyServlet</servlet-name>
<servlet-class> com.sun.MyServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name>MyServlet</servlet-name> <url-pattern>/myApp/*</url-pattern> </servlet-mapping> ... </web-app>
22
Lab #3Servlets
23
Servlets 3.0
• @WebServlet, @WebListener, @WebFilter, …• Asynchronous Servlets
• @WebServlet(asyncSupported=true)• Plugin libraries using web fragments• Dynamic registration of Servlets• WEB-INF/lib/[*.jar]/META-INF/resources
accessible in the root• Programmatic authentication login/logout• Default Error Page• . . .
24
Servlets 3.1 (JSR 340)http://jcp.org/en/jsr/detail?id=340
• Cloud support• Multi-tenancy
• Security / Session state / Resources isolation
• Asynchronous IO based on NIO2• Utilize Java EE concurrency utilities• Enable support for Web Sockets
NEW
25
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]
26
Lab #4Java Persistence API
27
JPA 2.1 Candidate Featureshttp://jcp.org/en/jsr/detail?id=338
● Multi-tenancy● Support for stored procedures, vendor function● Update and Delete Criteria queries, JPQL ↔
Criteria● Query by Example● Support for schema generation● UUID generator type● Persistence Context synchronization control● Dynamic definition of PU● Additional event listeners
NEW
28
EJB 3.1 (JSR 318)Package & Deploy in a WAR
myApp.ear
myWeb.war
WEB-INF/web.xmlWEB-INF/classes com.sun.FooServlet com.sun.TickTock
myBeans.jar
com.sun.FooBeancom.sun.FooHelper
myApp.war
WEB-INF/classes com.sun.FooServlet com.sun.TickTock com.sun.FooBean com.sun.FooHelper
web.xml ?
Java EE 5 Java EE 6
http://blogs.sun.com/arungupta/entry/screencast_37_java_ee_6
29
Lab #5EJB 3.1
30
EJB 3.1
• No interface view – one source file per bean• Embeddable API• @Singleton
• Initialization in @PostContruct
• Simplified Cron-like syntax for Timer• Asynchronous Session Bean• Portable Global JNDI Name
31
Contexts & Dependency Injection - CDI(JSR 299)
• Type-safe Dependency Injection• No String-based identifiers
• Strong typing, Loose coupling• Events, Interceptors, Decorators
• Context & Scope management – extensible• Portable Extensions• Bridge EJB and JSF in the platform• Works with Java EE modular and
component architecture• Integration with Unified Expression Language (UEL)
32
CDIInjection Points
• Field, Method, Constructor• 0 or more qualifiers• Type
@Inject @LoggedIn User user
RequestInjection
What ?(Type)
Which one ?(Qualifier)
@Inject @LoggedIn User user
33
Lab #6CDI Qualifiers
34
CDIMuch more ...
• Producer methods and fields• Bridging Java EE resources• Alternatives• Interceptors• Decorators• Stereotypes
35
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• ...
36
Lab #7JSF 2.0
37
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;
38
Lab #8Bean Validation
39
JAX-RS 1.1
• Java API for building RESTful Web Services• POJO based• Annotation-driven• Server-side API• HTTP-centric
40
JAX-RS 1.1Code Sample - Simple
public class HelloWorldResource {
public String sayHello() { return "Hello World"; }
public String morning() { return “Good Morning!”; }}
@Path("helloworld")
@Context UriInfo ui;
@GET @Produces("text/plain")
@GET @Path("morning")
41
JAX-RS 1.1Code Sample – Specifying Output MIME type
@Path("/helloworld")@Produces("text/plain")public class HelloWorldResource { @GET public String doGetAsPlainText() { . . . }
@GET @Produces("text/html") public String doGetAsHtml() { . . . }}
@GET@Produces({ "application/xml", "application/json"})public String doGetAsXmlOrJson() { . . .}
42
Lab #9JAX-RS
43
JAX-RS 1.1Code Sample
import javax.inject.Inject;import javax.enterprise.context.RequestScoped;
@RequestScopedpublic class ActorResource { @Inject DatbaseBean db;
public Actor getActor(int id) { return db.findActorById(id); }}
44
JAX-RS 1.1Code Sample
import javax.inject.Inject;import javax.enterprise.context.RequestScoped;
@RequestScopedpublic class ActorResource { @Inject DatbaseBean db;
public Actor getActor( int id) { return db.findActorById(id); }}
import javax.ws.rs.GET;import javax.ws.rs.Path;import javax.ws.rs.Produces;import javax.ws.rs.PathParam;
@Path("/actor/{id}")
@GET @Produces("application/json") @PathParam("id")
http://blogs.sun.com/arungupta/entry/totd_124_using_cdi_jpa
45
JAX-RS 2.0http://jcp.org/en/jsr/detail?id=339
● 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
NEW
46
http://blogs.sun.com/arungupta/entry/java_ee_6_twitter_demo
47
Lab #10Twitter App
48
49
IDE Support for Java EE 6
50
From the real users ...
Developers can concentrateon business logic, Java EE 6 is providing a standard for the infrastructure.
Jigsaw puzzle, Modular, standard, less xml, easy, easy, have I said easy?
Higher integrated specs,simple and annotation driven,single-classloader WARs,next level of industry standard
Standards compliance, vendor independence, milliseconds and kilobyte deployment
http://blogs.sun.com/arungupta/tags/community+feedback
Faster development, lessframeworks/complexity, more great code shipped
Definite excuse to avoid Spring forever
Not your fat grandfather's enterprise Java anymore, Enterprise Java Renaissance
51
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 )
Avoid “framework explosion”
http://blogs.sun.com/stories/entry/egesa_engineering_avoids_framework_explosion
52
53
GlassFish Server Chronology
GlassFish v1Java EE 5, Single Instance
2006 …
GlassFish v2Java EE 5, High Availability
GlassFish Server 3.1Java EE 6, High Availability
GlassFish Server 3Java EE 6, Single Instance
2007 2008 2009 2010 2011
GlassFish Server 3.2Virtualization, PaaS
Distribution License Features
GlassFish Server Open Source Edition 3.1Web Profile
CDDL & GPLv2
• Java EE 6 compatibility• Web Profile support• In-memory replication / clustering• Centralized Administration
GlassFish Open Source Edition 3.1
CDDL & GPLv2
• Java EE 6 compatibility• Full Java EE distribution• In-memory replication / clustering• Centralized Administration
Oracle GlassFish Server 3.1Web Profile Commercial
• Adds• Oracle GlassFish Server Control• Patches, support, knowledge base
Oracle GlassFish Server 3.1 Commercial
• Adds• Oracle GlassFish Server Control• Patches, support, knowledge base
GlassFish Server Distributions
55
GlassFish 3.1 Overview
• Built on GlassFish 3• Modular and Extensible HK2 Kernel
• ~262 modules• Clustering and High Availability
• HTTP, EJB, IIOP, SSO, Metro• Dynamic Invocation of Services• End-to-end extensibility
56
GlassFish 3.1: Fast and Furious ...
• 29% better startup/deploy/re-deploy cycle over 3.0.1
• 33% better HA performance over 2.1.1• Scalable Grizzly Adapter based on Java NIO• Full-session and Modified-attribute* scope
• Multiple clusters per domain, multiple instances per cluster, up to 100 instances per domain
http://weblogs.java.net/blog/sdo/archive/2011/03/01/whats-new-glassfish-v31-performance
57
Java EE 7 : JSR 342
• 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
NEW
58
Java EE 7 Schedule
• March 2011 Early EG Formed• Q3 2011 Early Draft• Q1 2012 Public Draft• Q3 2012 Final Release
NEW
59
Java EE JSR Soup
• Java EE 7 - JSR 342 • Servlets 3.1 – JSR 340• Expression Language 3.0 – JSR 341• Java Message Service 2.0 – JSR 343• Java Server Faces 2.2 – JSR 344• Java Persistence API 2.1 – JSR 338• JAX-RS 2.0 – JSR 339
NEW
60
Transparency Checklist
• Names of the EG members• 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
NEW
61
References
• glassfish.org• blogs.sun.com/theaquarium• facebook.com/glassfish• oracle.com/goto/glassfish• youtube.com/GlassFishVideos• Follow @glassfish
<Insert Picture Here>
Understanding the Nuts & Bolts of Java EE 6
Arun Gupta, Java EE & GlassFish Guyblogs.sun.com/arungupta, @arungupta