+ All Categories
Home > Technology > Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

Date post: 28-Jun-2015
Category:
Upload: jagadish-prasath
View: 294 times
Download: 0 times
Share this document with a friend
Popular Tags:
87
1 Java EE 6 - Deep Dive Jagadish Ramu Sun Microsystems
Transcript
Page 1: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

1

Java EE 6 - Deep Dive

Jagadish RamuSun Microsystems

Page 2: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

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.

Page 3: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

3

Compatible Java EE 6 Impls

Today:

Announced:

Page 4: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

4

Goals for the Java EE 6 Platform

Flexible & Light-weight Web Profile 1.0 Pruning: JAX-RPC, EJB 2.x Entity Beans, JAXR, JSR 88

Extensible• Embrace Open Source Frameworks

Easier to use, develop on• Continue on path set by Java EE 5

Page 5: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

5

Java EE 6 Web Profile 1.0

Fully functional mid-sized profile• Actively discussed in the Java EE 6 Expert

Group and outside it

• Technologies• Servlets 3.0, JSP 2.2, EL 2.2, Debugging Support for Other

Languages 1.0, JSTL 1.2, JSF 2.0, Common Annotations 1.1, EJB 3.1 Lite, JTA 1.1, JPA 2.0, Bean Validation 1.0, Managed Beans 1.0, Interceptors 1.1, Context & Dependency Injection 1.0, Dependency Injection for Java 1.0

Page 6: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

6

Java EE 6 - Done

Specifications approved by the JCP Reference Implementation is GlassFish v3 TCK

Dec 2

009

Page 7: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

7

Java EE 6 Specifications The Platform Java EE 6 Web Profile 1.0 Managed Beans 1.0

Page 8: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

8

Java EE 6 SpecificationsNew

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)

Page 9: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

9

Java EE 6 SpecificationsExtreme Makeover

Java Server Faces 2.0 (JSR 314) Java Servlets 3.0 (JSR 315) Java Persistence 2.0 (JSR 317) Enterprise Java Beans 3.1 & Interceptors 1.1

(JSR 318) Java EE Connector Architecture 1.6 (JSR 322)

Page 10: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

10

Java EE 6 SpecificationsUpdates

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)

Page 11: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

11

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) {

...

}

...

}

Page 12: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

12

Servlets 3.0 (JSR 315)Annotations-based @WebServlet

http://blogs.sun.com/arungupta/entry/totd_81_getting_started_with

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>

Page 13: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

13

Servlets 3.0Annotations-based @WebServlet

@WebServlet(name="mytest",

urlPatterns={"/myurl"},

initParams={ @WebInitParam(name="n1", value="v1"), @WebInitParam(name="n2", value="v2")

})

public class TestServlet extends javax.servlet.http.HttpServlet {

....

}

Page 14: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

14

Servlets 3.0Annotations-based @WebListeners<listener> <listener-class> server.LoginServletListener </listener-class></listener>

package server;

. . .

@WebListener()public class LoginServletListener implements ServletContextListener {

Page 15: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

15

Servlets 3.0Annotations-based @WebFilter

<filter> <filter-name>PaymentFilter</filter-name> <filter-class>server.PaymentFilter</filter-class> <init-param> <param-name>param1</param-name> <param-value>value1</param-value> </init-param></filter><filter-mapping> <filter-name>PaymentFilter</filter-name> <url-pattern>/*</url-pattern></filter-mapping><filter-mapping> <filter-name>PaymentFilter</filter-name> <servlet-name>PaymentServlet</servlet-name> <dispatcher>REQUEST</dispatcher></filter-mapping>

package server;. . .@WebFilter( filterName="PaymentFilter", InitParams={ @WebInitParam( name="param1", value="value1") } urlPatterns={"/*"}, servletNames={"PaymentServlet"}, dispatcherTypes={DispatcherType.REQUEST})public class PaymentFilter implements Filter {. . .

Page 16: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

16

Servlets 3.0Asynchronous Servlets

Useful for Comet, long waits Must declare

@WebServlet(asyncSupported=true)AsyncContext context = request.startAsync();

context.addListener(new AsyncListener() { … });

context.dispatch(“/request.jsp”);

//context.start(Runnable action);

...

context.complete(); //marks completion

http://blogs.sun.com/arungupta/entry/totd_139_asynchronous_request_processing

Page 17: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

17

Servlets 3.0Extensibility

Plugin libraries using web fragments Modular web.xml

Bundled in framework JAR file in META-INF directory

Zero-configuration, drag-and-drop for web frameworks

• Servlets, servlet filters, context listeners for a framework get discovered and registered by the container

Only JAR files in WEB-INF/lib are used

Page 18: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

18

<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>http://blogs.sun.com/arungupta/entry/totd_91_applying_java_ee

Servlets 3.0Extensibility

Page 19: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

19

Servlets 3.0 Resource Sharing

Static and JSP no longer confined to document root of the web application

May be placed in WEB-INF/lib/[*.jar]/META-INF/resources

Resources in document root take precedence over those in bundled JAR

myapp.war WEB-INF/lib/catalog.jar /META-INF/resources/catalog/books.html

http://localhost:8080/myapp/catalog/books.html

Page 20: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

20

EJB 3.1 (JSR 318)Package & Deploy in a WAR

foo.ear

foo_web.war

WEB-INF/web.xmlWEB-INF/classes com.sun.FooServlet com.sun.TickTock

foo_ejb.jar

com.sun.FooBeancom.sun.FooHelper

foo.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/totd_95_ejb_3_1

Page 21: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

21

EJB 3.1

@Statelesspublic class App { public String sayHello(String name) { return "Hello " + name; }}

Page 22: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

22

EJB 3.1

No interface view – one source file per bean Only for Local and within WAR Required for Remote No location transparency

Component initialization in @PostConstruct No assumptions on no-arg ctor

Page 23: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

23

Java EE 6 Namespaces Global

java:global/..(for all applications) Application scoped

java:app/.. (visibile only for the app.) App-1 binds an Object by name

“java:app/myObject”, App-2 cannot see it.

All modules of the app has visibility. mod-1, mod-2 of app-1 can see “java:app/myObject”

Page 24: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

24

Java EE 6 Namespaces Module Scoped

java:module/.. (visible only for the module)

App-1 has module-1 and module-2 Module-1's namespace not accessible by module-2

All components of the module has visibility

Component

Page 25: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

25

EJB 3.1Portable Global JNDI Name Syntax

Portable Global Application/Module-scoped Derived from metadata such as name,

component name etc.

Page 26: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

26

EJB 3.1Portable Global JNDI Name Syntax

java:global[/<app-name>]/<module-name>/<bean-name>[!<fully-qualified-interface-name>]

Only within EARBase name of EAR(or application.xml)

Base name of ejb-jar/WAR(or ejb-jar.xml/web.xml)

Unqualified name of the bean classAnnotation/name attribute

Or ejb-jar.xml• Until now, only java:comp• Local & Remote business• No-interface• Also in java:app, java:module

Page 27: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

27

EJB 3.1Portable Global JNDI Name Syntax

package com.acme;

@Stateless

public class FooBean implements Foo { ... }

FooBean is packaged in fooejb.jar

java:global/fooejb/FooBean

java:global/fooejb/FooBean!com.acme.Foo

java:app/fooejb/FooBean

java:app/fooejb/FooBean!com.acme.Foo

java:module/FooBean

java:module/FooBean!com.acme.Foo

Page 28: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

28

public void testEJB() throws NamingException { EJBContainer ejbC = EJBContainer.createEJBContainer(); Context ctx = ejbC.getContext(); App app = (App) ctx.lookup("java:global/classes/App"); assertNotNull(app); String NAME = "Duke"; String greeting = app.sayHello(NAME); assertNotNull(greeting); assertTrue(greeting.equals("Hello " + NAME)); ejbC.close(); }

EJB 3.1Embeddable API – Deploy the Bean

http://blogs.sun.com/arungupta/entry/totd_128_ejbcontainer_createejbcontainer_embedded

Page 29: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

29

Screencast JSP, Servlets, EJB

Page 30: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

30

EJB 3.1Singleton Beans

One instance per app/VM, not pooled Useful for caching state CMT/BMT Access to container services for injection, resource

manager, timers, startup/shutdown callbacks, etc. Enable eager initialization using @Startup Always supports concurrent access Define initialization ordering using @DependsOn@Singletonpublic class MyEJB { . . .}

Page 31: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

31

EJB 3.1Asynchronous Session Beans

Control returns to the client before the container dispatches invocation to a bean instance

@Asynchronous – method or class Return type – void or Future<V> Transaction context does not propagate

REQUIRED REQUIRED_NEW→

Security principal propagates

Page 32: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

32

EJB 3.1Asynchronous Session Beans – Code Sample

@Stateless@Asynchronouspublic class SimpleAsyncEJB { public Future<Integer> addNumbers(int n1, int n2) { Integer result;

result = n1 + n2; try { // simulate JPA queries + reading file system Thread.currentThread().sleep(2000); } catch (InterruptedException ex) { ex.printStackTrace(); }

return new AsyncResult(result); }}

http://blogs.sun.com/arungupta/entry/totd_137_asynchronous_ejb_a

Page 33: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

33

EJB 3.1Timers

Automatically created EJB Timers Calendar-based Timers – cron like semantics

Every 14th minute within the hour, for the hours 1 & 2 am(minute=”*/14”, hour=”1,2”)

Every 10 seconds starting at 30(second=”30/10”)

Every 5 minutes of every hour(minute=”*/5”, hour=”*”)

2pm on Last Thur of Nov of every year(hour=”14”, dayOfMonth=”Last Thu”, month=”Nov”)

Every Mon & Wed midnight @Schedule(dayOfWeek=”Mon,Wed”)

Page 34: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

34

EJB 3.1Timers

Single persistent timer across JVMs Automatically created EJB Timers

@Schedule(hour=”15”,dayOfWeek=”Fri”)

Can be chained @Schedules({

@Schedule(hour=”6”,dayOfWeek=”Tue,Thu,Fri-Sun”), @Schedule(hour=”12”,dayOfWeek=”Mon,Wed”)})

May be associated with a TimeZone Non-persistent timer, e.g. Cache

@Schedule(..., persistent=false)

Page 35: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

35

EJB 3.1EJB 3.1 Lite – Feature Comparison

Page 36: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

36

Managed Beans 1.0

EJB CDI JPAJAX-WS JAX-RSJSF ...

@Stateful@Stateless@Singleton

@Named @Entity@WebService

@Path@Managed

Bean...

EJB

@javax.annotation.ManagedBean

Page 37: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

37

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>

Page 38: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

38

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

Page 39: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

39

Collection of basic types

@Entity

public class Person { @Id protected String ssn; protected String name; protected Date birthDate; . . . @ElementCollection @CollectionTable(name=”ALIAS”) protected Set<String> nickNames;

}

Java Persistence API 2 (JSR 317)Sophisticated mapping/modeling options

Page 40: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

40

Collection of embeddables

@Embeddable public class Address { String street; String city; String state; . . .}

@Entity public class RichPerson extends Person { . . . @ElementCollection protected Set<Address> vacationHomes; . . . }

Java Persistence API 2Sophisticated mapping/modeling options

Page 41: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

41

Java Persistence API 2Sophisticated mapping/modeling options

Multiple levels of embedding

@Embeddable public class ContactInfo { @Embedded Address address; . . .}

@Entity public class Employee { @Id int empId; String name;

@Embedded ContactInfo contactInfo; . . . }

Page 42: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

42

Java Persistence API 2Sophisticated mapping/modeling options

Improved Map support

@Entity public class VideoStore { @Id Integer storeId; Address location; . . . @ElementCollection Map<Movie, Integer> inventory;}

@Entity public class Movie { @Id String title; @String director; . . .}

Page 43: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

43

Java Persistence API 2Metamodel

Abstract “schema-level” model over managed classes of a Persistence Context Entities, Mapped classes, Embeddables, ...

Accessed dynamically EntityManager or

EntityManagerFactory.getMetamodel()

And/or statically materialized as metamodel classes Use annotation processor with javac

Page 44: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

44

import javax.persistence.metamodel.*;

@StaticMetamodel(Customer.class) public class Customer_ { public static SingularAttribute<Customer, Integer> custId; public static SingularAttribute<Customer, String> name; public static SingularAttribute<Customer, Address> address; public static SingularAttribute<Customer, SalesRep> rep; public static SetAttribute<Customer, Order> orders;}

Java Persistence API 2Metamodel Example

@Entity public class Customer { @Id Integer custId; String name; ... Address address; @ManyToOne SalesRep rep; @OneToMany Set<Order> orders; }

Page 45: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

45

Java Persistence API 2Caching

1st-level Cache by PersistenceContext Only one object instance for any database row

2nd-level by “shared-cache-mode” ALL, NONE UNSPECIFIED – Provider specific defaults ENABE_SELECTIVE - Only entities with Cacheable(true) DISABLE_SELECTIVE - All but with Cacheable(false) Optional feature for PersistenceProvider

Page 46: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

46

Java Persistence API 2Much more ...

New locking modes PESSIMISTIC_READ – grab shared lock PESSIMISTIC_WRITE – grab exclusive lock PESSIMISTIC_FORCE_INCREMENT – update version em.find(<entity>.class, id, LockModeType.XXX)

em.lock(<entity>, LockModeType.XXX)

Standard configuration options javax.persistence.jdbc.[driver | url | user | password]

Page 47: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

47

Screencast - JPA

Page 48: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

48

@DataSourceDefinition@DataSourceDefinition( name="java:global/MyApp/MyDataSource",

className="org.apache.derby.jdbc.ClientDataSource"

databaseName=”testdb”,

serverName=”localhost”,

portNumber=”1527”,

user="dbuser",

password="dbpassword" )

• Equivalents in DDs as <datasource-definition> element• Can be defined in Servlet, EJB, Managed Beans, Application Client and their DDs.• Can be defined in 'global', 'app', 'module', 'comp' scopes

Page 49: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

49

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

Page 50: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

50

Interceptors 1.1 - Code@InterceptorBinding

@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.METHOD, ElementType.TYPE})public @interface MyInterceptorBinding {}

@Interceptor@MyInterceptorBindingpublic class MyInterceptor { @AroundInvoke public Object intercept(InvocationContext context) { System.out.println(context.getMethod.getName()); System.out.println(context.getParameters()); Object result = context.proceed();

return result; } . . .}

Page 51: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

51

Interceptors 1.1 – Sample Code

@Interceptors(MyInterceptor.class)public class MyManagedBean { . . .}

http://blogs.sun.com/arungupta/entry/totd_134_interceptors_1_1

@InjectMyManagedBean bean;

Page 52: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

52

Interceptors 1.1 – Sample Code

@MyInterceptorBindingpublic class MyManagedBean { . . .}

public class MyManagedBean { @Interceptors(MyInterceptor.class) public String sayHello(String name) { . . . }}

Single instance of Interceptor per

target class instance

Page 53: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

53

Interceptors 1.1 – Sample Code

@Named@Interceptors(MyInterceptor.class)public class MyManagedBean { . . .

@Interceptors(AnotherInterceptor.class) @ExcludeDefaultInterceptors @ExcludeClassInterceptors public void someMethod() { . . . }}

Page 54: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

54

Java Server Faces 2.0 Facelets as “templating language” for the

page• Custom components much easier to develop

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html"> <h:head> <title>Enter Name &amp; Password</title> </h:head> <h:body> <h1>Enter Name &amp; Password</h1> <h:form> <h:panelGrid columns="2"> <h:outputText value="Name:"/> <h:inputText value="#{simplebean.name}" title="name" id="name" required="true"/> <h:outputText value="Password:"/> <h:inputText value="#{simplebean.password}" title="password" id="password" required="true"/> </h:panelGrid> <h:commandButton action="show" value="submit"/> </h:form> </h:body></html>

Page 55: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

55

JSF 2 Composite Components

Page 56: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

56

JSF 2 Composite Components<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:ez="http://java.sun.com/jsf/composite/ezcomp"> <h:head> <title>Enter Name &amp; Password</title> </h:head> <h:body> <h1>Enter Name &amp; Password</h1> <h:form> <ez:username-password/> <h:commandButton action="show" value="submit"/> </h:form> </h:body></html>

http://blogs.sun.com/arungupta/entry/totd_135_jsf2_custom_components

. . .WEB-INFindex.xhtmlresources/ ezcomp/ username-password.xhtml

Page 57: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

57

Screencast - JSF

Page 58: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

58

Contexts & Dependency Injection – CDI (JSR 299)

Type-safe Dependency Injection No String-based identifiers Selected at development/deployment time

Strong typing, Loose coupling Context & Scope management - extensible Works with Java EE modular and

component architecture Integration with Unified Expression Language (UEL)

Page 59: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

59

CDIInjection Points

Field, Method, Constructor 0 or more qualifiers Type

@Inject @LoggedIn User user

RequestInjection

What ?(Type)

Which one ?(Qualifier)

@Inject @LoggedIn User user

Page 60: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

60

CDI – Sample Client CodeField and Method Injection

public class CheckoutHandler {

@Inject @LoggedIn User user;

@Inject PaymentProcessor processor;

@Inject void setShoppingCart(@Default Cart cart) { … }

}

Page 61: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

61

CDI – Sample Client CodeConstructor Injection

public class CheckoutHandler {

@Inject CheckoutHandler(@LoggedIn User user, PaymentProcessor processor, @Default Cart cart) { ... }

}

• Only one constructor can have @Inject

Page 62: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

62

CDI - Sample Client CodeMultiple Qualifiers and Qualifiers with Arguments

public class CheckoutHandler {

@Inject CheckoutHandler(@LoggedIn User user, @Reliable @PayBy(CREDIT_CARD) PaymentProcessor processor, @Default Cart cart) { ... }

}

Page 63: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

63

CDI - Scopes Beans can be declared in a scope

Everywhere: @ApplicationScoped, @RequestScoped Web app: @SessionScoped JSF app: @ConversationScoped : begin(), end()

Transient and long-running Pseudo-scope (default): @Dependent Custom scopes via @Scope

CDI runtime makes sure the right bean is created at the right time

Client do NOT have to be scope-aware

Page 64: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

64

CDI - Named BeansBuilt-in support for the Unified EL

Beans give themselves a name with @Named(“cart”)

Then refer to it from a JSF or JSP page using the EL:

<h:commandButton value=”Checkout”

action=“#{cart.checkout}”/>

Page 65: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

65

CDI - EventsEven more decoupling

Annotation-based event model A bean observes an event

void logPrintJobs(@Observes PrintEvent event){…}

Another bean fires an event@Inject @Any Event<PrintEvent> myEvent;

void doPrint() { . . . myEvent.fire(new PrintEvent());}

Events can have qualifiers too void logPrintJobs(@Observes @LargeFile PrintEvent event){…}

Page 66: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

66

CDIMuch more ...

Producer methods and fields Alternatives Interceptors Decorators Stereotypes . . .

Page 67: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

67

Screencast - CDI

Page 68: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

68

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;

Page 69: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

69

Bean ValidationIntegration with JPA

Managed classes may be configured Entities, Mapped superclasses, Embeddable classes

Applied during pre-persist, pre-update, pre-remove lifecycle events

How to enable ? “validation-mode” in persistence.xml “javax.persistence.validation.mode” key in

Persistence.createEntityManagerFactory

Specific set of classes can be targeted javax.persistence.validation.group.pre-[persist|

update|remove]

Page 70: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

70

Bean ValidationIntegration with JSF

Individual validators not required Integration with EL

f:validateBean, f:validateRequired

<h:form> <f:validateBean> <h:inputText value=”#{model.property}” /> <h:selectOneRadio value=”#{model.radioProperty}” > … </h:selectOneRadio> <!-- other input components here --> </f:validateBean></h:form>

Page 71: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

71

JAX-RS 1.1

Java API for building RESTful Web Services POJO based Annotation-driven Server-side API HTTP-centric

Page 72: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

72

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")

Page 73: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

73

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() { . . .}

Page 74: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

74

JAX-RS 1.1Code Sample – Specifying Input MIME type

@POST@Consumes("text/plain")public String saveMessage() { . . .}

Page 75: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

75

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); }}

Page 76: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

76

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

Page 77: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

77

JAX-RS 1.1Integration with Java EE 6 – Servlets 3.0

No or Portable “web.xml”<web-app>

<servlet>

<servlet-name>Jersey Web Application</servlet-name>

<servlet-class>

com.sun.jersey.spi.container.servlet.ServletContainer

</servlet-class>

<init-param>

<param-name>javax.ws.rs.Application</param-name>

<param-value>com.foo.MyApplication</param-value>

</init-param>

</servlet>

<servlet-mapping>

<servlet-name>Jersey Web Application</servlet-name>

<url-pattern>/resources/*</url-pattern>

</servlet-mapping>

</web-app>

public class MyApplication extends javax.ws.rs.core.Application {

}

@ApplicationPath(“resources”)

Page 78: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

78

Screencast - JAX-RS

Page 79: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

79

GlassFish DistributionsDistribution License Features

GlassFish Open Source Edition 3.0.1

CDDL & GPLv2

• Java EE 6 Compatibility• No Clustering• Clustering planned in 3.1• mod_jk for load balancing

GlassFish Open Source Edition 2.1.1

CDDL & GPLv2

• Java EE 5 Compatibility• In memory replication• mod_loadbalancer

Oracle GlassFish Server 3.0.1

Commercial • GlassFish Open Source Edition 3.0.1• Oracle GlassFish Server Control• Clustering planned in 3.1

Oracle GlassFish Server 2.1.1

Commercial • GlassFish Open Source Edition 2.1.1• Enterprise Manager • HADB

Clustering Coming Soon!

Page 80: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

80

GlassFish 3 & OSGi No OSGi APIs are used in GlassFish

HK2 provides abstraction layer

All GlassFish modules are OSGi bundles

Felix is default, also runs on Knopflerfish & Equinox Can run in an existing shell 200+ modules in v3

http://blogs.sun.com/arungupta/entry/totd_103_glassfish_v3_with

Page 81: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

81

Light Weight & On-demand Monitoring

Event-driven light-weight and non-intrusive monitoring

Modules provide domain specific probes (monitoring events)

• EJB, Web, Connector, JPA, Jersey, Orb, Ruby

End-to-end monitoring on Solaris using DTrace

3rd party scripting clients• JavaScript to begin with

Page 82: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

82

Boost your productivityRetain session across deployment

asadmin redeploy –properties keepSessions=true helloworld.war

Page 83: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

83

Boost your productivityDeploy-on-Save

Page 84: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

84

84

GlassFish Roadmap Detail

©2010 Oracle Corporation

Page 85: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

85

GlassFish 3.1 = 3.0 + 2.1.1 Main Features

Clustering and Centralized Administration High Availability

Other ... Application Versioning Application-scoped Resources SSH-based remote management and monitoring Embedded (extensive) Admin Console based on RESTful API

http://wikis.sun.com/display/glassfish/GlassFishv3.1

Page 86: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

86

References & Queries download.oracle.com/javaee/6/tutorial/doc

glassfish.org

blogs.sun.com/theaquarium

oracle.com/goto/glassfish

glassfish.org/roadmap

youtube.com/user/GlassFishVideos

Follow @glassfish

[email protected]

[email protected]

Page 87: Java EE 6 - Deep Dive - Indic Threads, Pune - 2010

87

Thank You !

[email protected] Microsystems


Recommended