KEMBAR78
Java EE7 Demystified | PDF
Çağatay ÇİVİCİ
Mert ÇALIŞKAN
July ’13
DEMYSTIFIED
Released on June 12, 2013.
Focuses on HTML 5, higher productivity, more to meet industrial
standards.
Glassfish 4.0 is EE 7 ready.
Java EE 7
Enterprise JAVA
• Java EE = Java Enterprise Edition
• Extends Java SE
javax.faces.* UI + JSF Related Stuff
javax.servlet.* Handling HTTP invocations
javax.enterprise.inject.* CDI, Like Spring depedency Inj.
javax.ejb.* EJB Stuff
javax.validation.* BeanValidation
javax.persistence.* Persistency
javax.transaction.* Stuff for transactions
javax.jms.* Messaging Stuff
CHRONOLOGY OF JAVA EE
Java EE 5
May 11, 2006
Java EE 6
December 10, 2009
J2EE 1.2
December 12, 1999
J2EE 1.3
Sept. 12, 2001
J2EE 1.4
Nov. 11, 2003
Servlet 2.2 Servlet 2.3 Servlet 2.4
JSP
EJB
JMS
JTA
JAAS
JSF
EL
JAX-WS
JAX-RS
JAX-B
JPA
JSTL
any many
more...
Servlet 2.5
Servlet 3.0
Java EE 7 Agenda
Java API for RESTful Web Services 2.0
Java Message Service 2.0
Java API for JSON Processing 1.0
Java API for WebSocket 1.0
CDI 1.1
Batch Applications for the Java Platform 1.0
Java Persistence API 2.1
Servlet 3.1
JavaServer Faces 2.2
Java EE 7
Project Creation
NetBeans, current version 7.3.1, supports Java EE 7.
Can be downloaded with Glassfish 4.0, which also supports
EE 7.
Maven archetypes are @ https:/
/nexus.codehaus.org/
content/repositories/releases/org/codehaus/mojo/archetypes
Archetypes can easily be integrated into NetBeans.
Servlets
3.0 recap
Managing state on stateless HTTP protocol by processing
HTML pages back and forth between client and server.
highlights with 3.0:
- ease of development: the annotations like,
@Servlet @ServletFilter and etc.
- partial web.xml with metadata-complete attribute and
web-fragment.xml files under .jar/META-INF
- static resources & jsps inside a jar file to be reused.
Servlets
3.1 highlights
Async Non-Blocking IO
New interface javax.servlet.ReadListener
void onDataAvailable() throws IOException
void onAllDataRead() throws IOException
void onError(Throwable t)
New interface javax.servlet.WriteListener
void onWritePossible() throws IOException
void onError(Throwable t)
Upgrade Mode, Transition to some other, incompatible protocol
like websockets.
API to track down session fixation attacks
HttpServletRequest.changeSessionId
HttpSessionIdListener
JSF
2.0 recap
JSF : Java Server Faces. Provided standardization on building
server-side user interfaces.
- Data Conversion & Validation
- Event handling
- Managing state of UI Components
- Page Navigation
- i18n and accessibility and many others...
2.0 provided:
- composite components, single file w/ no JAVA code
- standardized AJAX Lifecycle, <f:ajax>, PartialViewContext...
- implicit navigation based on view-id.
- conditional and preemptive navigation (GET based nav.)
- @ViewScoped, flash scope and custom scopes.
- annotations: @ManagedBean, Component Annotations
@FacesComponent, @FacesRenderer, @FacesConverter
JSF
2.2 highlights - 1
File Upload Component
<h:inputFile> since its JSF component, supports converters &
validators
Faces Flow
@FlowScoped in action.
n-number of flows.
programmatic or xml configuration of flows.
JSF
2.2 highlights - 2
HTML5 Friendly Markup
<!DOCTYPE html>
<html xmlns="http:/
/www.w3.org/1999/xhtml"
xmlns:jsf="http:/
/java.sun.com/jsf"
xmlns:p="http:/
/primefaces.org/ui"
xmlns:f="http:/
/java.sun.com/jsf/core">
<head jsf:id="head">
<title>Putting it all together</title>
<script jsf:target="body" jsf:name="js.js"/>
<link jsf:name="css.css" rel="stylesheet" type="text/css" />
</head>
...
</html>
JSF
2.2 highlights - 3
HTML5 Friendly Markup
<body jsf:id="body">
<form jsf:id="form" jsf:prependId="false">
<p:panelGrid id="panel" columns="2">
<label jsf:for="name">Name</label>
<input jsf:id="name" type="text" jsf:value="#{friendlyMarkupBean.name}" />
<label jsf:for="tel">Phone</label>
<input jsf:id="tel" type="tel" jsf:value="#{friendlyMarkupBean.phone}" />
<label jsf:for="email">Email</label>
<input jsf:id="email" type="email" jsf:value="#{friendlyMarkupBean.email}" />
<label for="progress">Progress</label>
<progress jsf:id="progress" max="3">#{friendlyMarkupBean.progress} of 3</progress>
</p:panelGrid>
</form>
</body>
JSF
2.2 highlights - 4
Resource Library Contracts
better templating than facelets
/contracts in the web application root & META-INF/contracts on
the classpath.
Passthrough attributes
<p:inputText value=”#{bean.value}” pt:placeholder=”Watermark
here” />
JMS
Message Oriented Middleware (MOM)
P2P or PubSub Models
Versions
JMS 1.1 (March 2002)
JMS 2.0 (May 2013)
JMS
JMS 1.x
@Resource(lookup = "java:global/jms/ankarajugconnectionfactory")
ConnectionFactory connectionFactory;
@Resource(lookup = "java:global/jms/ankarajugdemoqueue")
Queue demoQueue;
public void sendMessage(String payload) {
try {
Connection connection = connectionFactory.createConnection();
try {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer messageProducer = session.createProducer(demoQueue);
TextMessage textMessage = session.createTextMessage(payload);
messageProducer.send(textMessage);
} finally {
connection.close();
}
} catch (JMSException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
JMS 2
Cleaner APIs
Dependency Injection
Async Send
Delivery delay
JMS Resource
JMS 2.0
@Inject
private JMSContext context;
@Resource(mappedName = "jms/ankarajugqueue")
private Queue inboundQueue;
public void sendMessage (String payload) {
context.createProducer().send(inboundQueue, payload);
}
CDI 1.0
recap
Cool stuff like: Bean Definition and Dependency Injection
CDI brings transactional support to the web tier.
(EJB-JPA <> JSF)
Type Safe,
POJO based,
Interceptors,
Decorators,
Events,
Unified EL Integration
CDI 1.1 highlights
auto CDI activation w/out beans.xml, just annotate the bean with
@*Scoped and it will be picked up.
bean exclusing in beans.xml with
<scan>
<exclude name=”com.primetek.badbeans.* />
</scan>
@Vetoed: Ignored by CDI
Global Enablement of @Interceptor, @Decorator, @Alternative
with prioritization like @Priority(APPLICATION+100)
APPLICATION range: 2000-3000, LIBRARY and SYSTEM ranges
@Initialized qualifier to observe objects like
@Initialized(SessionScoped.class)
http:/
/in.relation.to/Bloggers/CDI11Available
more @
WebSocket
Full-Duplex
TCP Based
Handshake and Transfer
Non-Standard in pre JavaEE7
Java WebSocket API
Endpoints
Programmatic
Annotated
Send/Receive Messages
Path Parameters
Encoder/Decoder
Java WebSocket API
@ServerEndpoint("/echo")
public class EchoEndpoint {
@OnMessage
public void onMessage(Session session, String msg) {
try {
session.getBasicRemote().sendText(msg);
} catch (IOException e) { ... }
}
}
Java API for JSON
JSON Processing
Generate, Parse, Transform, Query
Object Model and Streaming APIs
JSON
{
"firstName": "John",
"lastName": "Smith",
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": 10021
},
"phoneNumbers": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "fax",
"number": "646 555-4567"
}
]
}
Java API for JSON
JsonBuilderFactory factory = Json.createBuilderFactory(null);
JsonArray jsonArray = factory.createArrayBuilder()
.add(factory.createObjectBuilder().
add("type", "home").
add("number", "(800) 111-1111"))
.add(factory.createObjectBuilder().
add("type", "cell").
add("number", "(800) 222-2222")).build();
[
{
"type": "home”,
"number": "(800) 111-1111"
},{
"type": "fax”,
"number": "646 555-4567"
}
]
JavaPersistence API
Map Objects to Relational Database
Versions
JPA 1.0 - May 2006
JPA 2.0 - Dec 2009
JPA 2.1 - April 2013
JPA 2.1
Standard Schema Generation
Stored Procedures
Unsynchronized Persistence Contexts
Converters
Criteria Update-Delete
JPA 2.1
@Entity
@NamedStoredProcedureQuery(name="topGiftsStoredProcedure”,
procedureName="Top10Gifts")
public class Product {
StoredProcedreQuery query = EntityManager.createNamedStoredProcedureQuery(
"topGiftsStoredProcedure");
query.registerStoredProcedureParameter(1, String.class, ParameterMode.INOUT);
query.setParameter(1, "top10");
query.registerStoredProcedureParameter(2, Integer.class, ParameterMode.IN);
query.setParameter(2, 100);
. . .
query.execute();
String response = query.getOutputParameterValue(1);
JAX-RS
1.1 recap
JAVA API to provide Web Services on REST Architecture.
v1.1 provided:
- part of EE 6, zero config for usage.
- annotations: @GET, @POST, @Produces, @Consumes and
others.
- Utility Classes:
MediaType,
UriBuilder,
Response.ResponseBuilder
JAX-RS
2.0 highlights
Client Framework, request builder
Async Client API, w/ java.util.concurrent.Future
Server Side Async API
Filters and Entity Interceptors,
filters to modify request/response headers.
interceptors to wrap MessageBodyReader & MessageBodyWriter
Batch Apps for Java
Batch Apps for Java
<job id="myJob" xmlns="http:/
/batch.jsr352/jsl">
<step id="myStep" >
<chunk reader="MyItemReader"
writer="MyItemWriter"
processor="MyItemProcessor"
buffer-size="5"
checkpoint-policy="item"
commit-interval="10" />
</step>
</job>
Step Example
<step id=”sendStatements”>
<chunk reader=”accountReader”
processor=”accountProcessor”
writer=”emailWriter”
item-count=”10” />
</step>
@Named(“accountReader")
...implements ItemReader... {
public Account readItem() {
/
/ read account using JPA
@Named(“emailWriter")
...implements ItemWriter... {
public void
writeItems(List<Statements>
statements) {
/
/ use JavaMail to send email
@Named(“accountProcessor")
...implements ItemProcessor... {
Public Statement
processItems(Account account)
{ /
/ read Account, return
Statement
Concurrency Utilities
ManagedExecutorService
Options (pool, threads, timeout)
ManagedScheduledExecutorService
ManagedThreadFactory
Concurrency Utilities
<resource-env-ref>
<resource-env-ref-name>
concurrent/BatchExecutor
</resource-env-ref-name>
<resource-env-ref-type>
javax.enterprise.concurrent.ManagedExecutorService
</resource-env-ref-type>
<resource-env-ref>
@Resource(name="concurrent/BatchExecutor")
ManagedExecutorService executor;
Future<String> future = executor.submit(new
MyRunnableTask(), String.class);
Config
Inject
Execute
JAVA EE 8
Stuff to Read on EE 7
@ankarajug
#javaEE7

Java EE7 Demystified

  • 1.
  • 2.
    Released on June12, 2013. Focuses on HTML 5, higher productivity, more to meet industrial standards. Glassfish 4.0 is EE 7 ready. Java EE 7
  • 3.
    Enterprise JAVA • JavaEE = Java Enterprise Edition • Extends Java SE javax.faces.* UI + JSF Related Stuff javax.servlet.* Handling HTTP invocations javax.enterprise.inject.* CDI, Like Spring depedency Inj. javax.ejb.* EJB Stuff javax.validation.* BeanValidation javax.persistence.* Persistency javax.transaction.* Stuff for transactions javax.jms.* Messaging Stuff
  • 4.
    CHRONOLOGY OF JAVAEE Java EE 5 May 11, 2006 Java EE 6 December 10, 2009 J2EE 1.2 December 12, 1999 J2EE 1.3 Sept. 12, 2001 J2EE 1.4 Nov. 11, 2003 Servlet 2.2 Servlet 2.3 Servlet 2.4 JSP EJB JMS JTA JAAS JSF EL JAX-WS JAX-RS JAX-B JPA JSTL any many more... Servlet 2.5 Servlet 3.0
  • 5.
    Java EE 7Agenda Java API for RESTful Web Services 2.0 Java Message Service 2.0 Java API for JSON Processing 1.0 Java API for WebSocket 1.0 CDI 1.1 Batch Applications for the Java Platform 1.0 Java Persistence API 2.1 Servlet 3.1 JavaServer Faces 2.2
  • 6.
    Java EE 7 ProjectCreation NetBeans, current version 7.3.1, supports Java EE 7. Can be downloaded with Glassfish 4.0, which also supports EE 7. Maven archetypes are @ https:/ /nexus.codehaus.org/ content/repositories/releases/org/codehaus/mojo/archetypes Archetypes can easily be integrated into NetBeans.
  • 8.
    Servlets 3.0 recap Managing stateon stateless HTTP protocol by processing HTML pages back and forth between client and server. highlights with 3.0: - ease of development: the annotations like, @Servlet @ServletFilter and etc. - partial web.xml with metadata-complete attribute and web-fragment.xml files under .jar/META-INF - static resources & jsps inside a jar file to be reused.
  • 9.
    Servlets 3.1 highlights Async Non-BlockingIO New interface javax.servlet.ReadListener void onDataAvailable() throws IOException void onAllDataRead() throws IOException void onError(Throwable t) New interface javax.servlet.WriteListener void onWritePossible() throws IOException void onError(Throwable t) Upgrade Mode, Transition to some other, incompatible protocol like websockets. API to track down session fixation attacks HttpServletRequest.changeSessionId HttpSessionIdListener
  • 11.
    JSF 2.0 recap JSF :Java Server Faces. Provided standardization on building server-side user interfaces. - Data Conversion & Validation - Event handling - Managing state of UI Components - Page Navigation - i18n and accessibility and many others... 2.0 provided: - composite components, single file w/ no JAVA code - standardized AJAX Lifecycle, <f:ajax>, PartialViewContext... - implicit navigation based on view-id. - conditional and preemptive navigation (GET based nav.) - @ViewScoped, flash scope and custom scopes. - annotations: @ManagedBean, Component Annotations @FacesComponent, @FacesRenderer, @FacesConverter
  • 12.
    JSF 2.2 highlights -1 File Upload Component <h:inputFile> since its JSF component, supports converters & validators Faces Flow @FlowScoped in action. n-number of flows. programmatic or xml configuration of flows.
  • 13.
    JSF 2.2 highlights -2 HTML5 Friendly Markup <!DOCTYPE html> <html xmlns="http:/ /www.w3.org/1999/xhtml" xmlns:jsf="http:/ /java.sun.com/jsf" xmlns:p="http:/ /primefaces.org/ui" xmlns:f="http:/ /java.sun.com/jsf/core"> <head jsf:id="head"> <title>Putting it all together</title> <script jsf:target="body" jsf:name="js.js"/> <link jsf:name="css.css" rel="stylesheet" type="text/css" /> </head> ... </html>
  • 14.
    JSF 2.2 highlights -3 HTML5 Friendly Markup <body jsf:id="body"> <form jsf:id="form" jsf:prependId="false"> <p:panelGrid id="panel" columns="2"> <label jsf:for="name">Name</label> <input jsf:id="name" type="text" jsf:value="#{friendlyMarkupBean.name}" /> <label jsf:for="tel">Phone</label> <input jsf:id="tel" type="tel" jsf:value="#{friendlyMarkupBean.phone}" /> <label jsf:for="email">Email</label> <input jsf:id="email" type="email" jsf:value="#{friendlyMarkupBean.email}" /> <label for="progress">Progress</label> <progress jsf:id="progress" max="3">#{friendlyMarkupBean.progress} of 3</progress> </p:panelGrid> </form> </body>
  • 15.
    JSF 2.2 highlights -4 Resource Library Contracts better templating than facelets /contracts in the web application root & META-INF/contracts on the classpath. Passthrough attributes <p:inputText value=”#{bean.value}” pt:placeholder=”Watermark here” />
  • 17.
    JMS Message Oriented Middleware(MOM) P2P or PubSub Models Versions JMS 1.1 (March 2002) JMS 2.0 (May 2013)
  • 18.
  • 19.
    JMS 1.x @Resource(lookup ="java:global/jms/ankarajugconnectionfactory") ConnectionFactory connectionFactory; @Resource(lookup = "java:global/jms/ankarajugdemoqueue") Queue demoQueue; public void sendMessage(String payload) { try { Connection connection = connectionFactory.createConnection(); try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer messageProducer = session.createProducer(demoQueue); TextMessage textMessage = session.createTextMessage(payload); messageProducer.send(textMessage); } finally { connection.close(); } } catch (JMSException ex) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); } }
  • 20.
    JMS 2 Cleaner APIs DependencyInjection Async Send Delivery delay JMS Resource
  • 21.
    JMS 2.0 @Inject private JMSContextcontext; @Resource(mappedName = "jms/ankarajugqueue") private Queue inboundQueue; public void sendMessage (String payload) { context.createProducer().send(inboundQueue, payload); }
  • 22.
    CDI 1.0 recap Cool stufflike: Bean Definition and Dependency Injection CDI brings transactional support to the web tier. (EJB-JPA <> JSF) Type Safe, POJO based, Interceptors, Decorators, Events, Unified EL Integration
  • 23.
    CDI 1.1 highlights autoCDI activation w/out beans.xml, just annotate the bean with @*Scoped and it will be picked up. bean exclusing in beans.xml with <scan> <exclude name=”com.primetek.badbeans.* /> </scan> @Vetoed: Ignored by CDI Global Enablement of @Interceptor, @Decorator, @Alternative with prioritization like @Priority(APPLICATION+100) APPLICATION range: 2000-3000, LIBRARY and SYSTEM ranges @Initialized qualifier to observe objects like @Initialized(SessionScoped.class) http:/ /in.relation.to/Bloggers/CDI11Available more @
  • 24.
    WebSocket Full-Duplex TCP Based Handshake andTransfer Non-Standard in pre JavaEE7
  • 25.
  • 26.
    Java WebSocket API @ServerEndpoint("/echo") publicclass EchoEndpoint { @OnMessage public void onMessage(Session session, String msg) { try { session.getBasicRemote().sendText(msg); } catch (IOException e) { ... } } }
  • 27.
    Java API forJSON JSON Processing Generate, Parse, Transform, Query Object Model and Streaming APIs
  • 28.
    JSON { "firstName": "John", "lastName": "Smith", "age":25, "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": 10021 }, "phoneNumbers": [ { "type": "home", "number": "212 555-1234" }, { "type": "fax", "number": "646 555-4567" } ] }
  • 29.
    Java API forJSON JsonBuilderFactory factory = Json.createBuilderFactory(null); JsonArray jsonArray = factory.createArrayBuilder() .add(factory.createObjectBuilder(). add("type", "home"). add("number", "(800) 111-1111")) .add(factory.createObjectBuilder(). add("type", "cell"). add("number", "(800) 222-2222")).build(); [ { "type": "home”, "number": "(800) 111-1111" },{ "type": "fax”, "number": "646 555-4567" } ]
  • 31.
    JavaPersistence API Map Objectsto Relational Database Versions JPA 1.0 - May 2006 JPA 2.0 - Dec 2009 JPA 2.1 - April 2013
  • 32.
    JPA 2.1 Standard SchemaGeneration Stored Procedures Unsynchronized Persistence Contexts Converters Criteria Update-Delete
  • 33.
    JPA 2.1 @Entity @NamedStoredProcedureQuery(name="topGiftsStoredProcedure”, procedureName="Top10Gifts") public classProduct { StoredProcedreQuery query = EntityManager.createNamedStoredProcedureQuery( "topGiftsStoredProcedure"); query.registerStoredProcedureParameter(1, String.class, ParameterMode.INOUT); query.setParameter(1, "top10"); query.registerStoredProcedureParameter(2, Integer.class, ParameterMode.IN); query.setParameter(2, 100); . . . query.execute(); String response = query.getOutputParameterValue(1);
  • 34.
    JAX-RS 1.1 recap JAVA APIto provide Web Services on REST Architecture. v1.1 provided: - part of EE 6, zero config for usage. - annotations: @GET, @POST, @Produces, @Consumes and others. - Utility Classes: MediaType, UriBuilder, Response.ResponseBuilder
  • 35.
    JAX-RS 2.0 highlights Client Framework,request builder Async Client API, w/ java.util.concurrent.Future Server Side Async API Filters and Entity Interceptors, filters to modify request/response headers. interceptors to wrap MessageBodyReader & MessageBodyWriter
  • 37.
  • 38.
    Batch Apps forJava <job id="myJob" xmlns="http:/ /batch.jsr352/jsl"> <step id="myStep" > <chunk reader="MyItemReader" writer="MyItemWriter" processor="MyItemProcessor" buffer-size="5" checkpoint-policy="item" commit-interval="10" /> </step> </job>
  • 39.
    Step Example <step id=”sendStatements”> <chunkreader=”accountReader” processor=”accountProcessor” writer=”emailWriter” item-count=”10” /> </step> @Named(“accountReader") ...implements ItemReader... { public Account readItem() { / / read account using JPA @Named(“emailWriter") ...implements ItemWriter... { public void writeItems(List<Statements> statements) { / / use JavaMail to send email @Named(“accountProcessor") ...implements ItemProcessor... { Public Statement processItems(Account account) { / / read Account, return Statement
  • 40.
    Concurrency Utilities ManagedExecutorService Options (pool,threads, timeout) ManagedScheduledExecutorService ManagedThreadFactory
  • 41.
  • 42.
  • 43.
  • 44.