@arungupta	

#javaee7	

50 new features of Java EE 7
in 50 minutes
Arun Gupta
Director, Developer Advocacy, Red Hat
@arungupta	

#javaee7	

#NN: <spec>: <feature>
@arungupta	

#javaee7	

JAX-RS 2.0
JSON-P 1.0
Web Socket 1.0Servlet 3.1
JSF 2.2EL 3.0JSP JSTL
BeanValidation1.1
Interceptors1.2
CDI1.1
Concurrency1.0
JPA 2.1
JTA 1.2 EJB 3.2 JMS 2.0
Batch 1.0
JCA 1.7
Java EE 7
JavaMail 1.5
@arungupta	

#javaee7	

JAX-RS 2.0
JSON-P 1.0
Web Socket 1.0Servlet 3.1
JSF 2.2EL 3.0JSP JSTL
BeanValidation1.1
Interceptors1.2
CDI1.1
Concurrency1.0
JPA 2.1
JTA 1.2 EJB 3.2 JMS 2.0
Batch 1.0
JCA 1.7
Java EE 7
JavaMail 1.5
CDI 1.1 (JSR 346)
@arungupta	

#javaee7	

#01: CDI: Default enabling
Finer scanning control
Possible values: all, annotated (default), none!
annotated behaves like in Java EE 6!
!
<beans ... version="1.1" bean-discovery-mode="all">!
<alternatives>!
<class>org.agoncal.book.MockGenerator</class>!
</alternatives>!
</beans>!
@arungupta	

#javaee7	

#02: CDI: @Vetoed
Veto the processing of the class or package
@Vetoed!
public class NonProcessedBean {

...!
}!
!
package-info.java
@Vetoed!
package com.non.processed.package;!
@arungupta	

#javaee7	

JAX-RS 2.0
JSON-P 1.0
Web Socket 1.0Servlet 3.1
JSF 2.2EL 3.0JSP JSTL
BeanValidation1.1
Interceptors1.2
CDI1.1
Concurrency1.0
JPA 2.1
JTA 1.2 EJB 3.2 JMS 2.0
Batch 1.0
JCA 1.7
Java EE 7
JavaMail 1.5
Bean Validation 1.1 (JSR 349)
@arungupta	

#javaee7	

#03: Bean Validation: Method validation
Pre/post conditions on method and constructors
public class CardValidator {!
!
public CardValidator(@NotNull Algorithm algorithm) {!
this.algorithm = algorithm;!
}!
!
@AssertTrue!
public Boolean validate(@NotNull CreditCard creditCard) {!
return algorithm.validate(creditCard.getNumber());!
}!
}!
@arungupta	

#javaee7	

JAX-RS 2.0
JSON-P 1.0
Web Socket 1.0Servlet 3.1
JSF 2.2EL 3.0JSP JSTL
BeanValidation1.1
Interceptors1.2
CDI1.1
Concurrency1.0
JPA 2.1
JTA 1.2 EJB 3.2 JMS 2.0
Batch 1.0
JCA 1.7
Java EE 7
JavaMail 1.5
Interceptors 1.2 (JSR 318)
@arungupta	

#javaee7	

#04: Interceptors: AroundConstruct
Interceptor associated with a constructor
public class LoggingInterceptor {!
!
@AroundConstruct!
private void init(InvocationContext ic) throws Exception{!
logger.fine("Entering constructor");!
ic.proceed();!
logger.fine("Exiting constructor");!
}!
!
@AroundInvoke!
public Object logMethod(InvocationContext ic) ... {!
// ...!
}!
}!
@arungupta	

#javaee7	

#05: Interceptors: @Priority
Prioritizing interceptor bindings
PLATFORM_BEFORE (0), LIBRARY_BEFORE (1000), APPLICATION (2000),
LIBRARY_AFTER (3000), PLATFORM_AFTER (4000)!
@Interceptor!
@Loggable!
@Priority(Interceptor.Priority.LIBRARY_BEFORE + 10)!
public class LoggingInterceptor {!
!
@AroundInvoke!
...!
}!
@arungupta	

#javaee7	

JAX-RS 2.0
JSON-P 1.0
Web Socket 1.0Servlet 3.1
JSF 2.2EL 3.0JSP JSTL
BeanValidation1.1
Interceptors1.2
CDI1.1
Concurrency1.0
JPA 2.1
JTA 1.2 EJB 3.2 JMS 2.0
Batch 1.0
JCA 1.7
Java EE 7
JavaMail 1.5
Concurrency utilities 1.0 (JSR 236)
@arungupta	

#javaee7	

#06: Concurrency: ManagedExecutor
•  User threads in Java EE applications
•  Support simple and advance concurrency design patterns
•  Extend Concurrency Utilities API from Java SE (JSR 166y)
•  java.util.concurrent package
@arungupta	

#javaee7	

#06: Concurrency: ManagedExecutor
@Resource

ManagedExecutorService executor;

!


ManagedExecutorService executor = (ManagedExecutorService) ctx

.lookup("java:comp/DefaultManagedExecutorService");!
Default ManagedExectuor
@arungupta	

#javaee7	

#06: Concurrency: ManagedExecutor
<web-app … version="3.1">!
<resource-env-ref>!
<resource-env-ref-name>!
concurrent/myExecutor!
</resource-env-ref-name>!
<resource-env-ref-type>!
javax.enterprise.concurrent.ManagedExecutorService!
</resource-env-ref-type>!
</resource-env-ref>!
</web-app>!
Specify in web.xml
@arungupta	

#javaee7	

#07: Concurrency:
ManagedScheduledExecutor
Managed version of ScheduledExecutorService!
Submit delayed or periodic tasks
@Resource

ManagedScheduledExecutorService executor;!
@arungupta	

#javaee7	

#07: Concurrency:
ManagedScheduledExecutor
InitialContext ctx = new InitialContext(); 



ManagedScheduledExecutorService executor =
(ManagedScheduledExecutorService)ctx.lookup(

"java:comp/DefaultManagedScheduledExecutorService");

!
•  Can be defined in web.xml as well
Access using JNDI
@arungupta	

#javaee7	

#07: Concurrency:
ManagedScheduledExecutor
executor.schedule(new MyCallableTask(), 5, TimeUnit.SECONDS);!
executor.scheduleAtFixedRate(new MyRunnableTask(), 2, 3,
TimeUnit.SECONDS);!
executor.scheduleWithFixedDelay(new MyRunnableTask(), 2, 3,
TimeUnit.SECONDS);!
@arungupta	

#javaee7	

#08: Concurrency:
ManagedThreadFactory
@Resource(name = "DefaultManagedThreadFactory”)!
ManagedThreadFactory factory;
!
ManagedThreadFactory factory = (ManagedThreadFactory)!
ctx.lookup("java:comp/DefaultManagedThreadFactory");

@arungupta	

#javaee7	

#08: Concurrency:
ManagedThreadFactory
Thread thread = factory.newThread(new MyTask());
((ManageableThread)thread).isShutdown();

@arungupta	

#javaee7	

#09: Concurrency: DynamicProxy
•  Create dynamic proxy objects, adds contextual information available for applications
running in Java EE environment
•  Classloading, JNDI, Security, …
@arungupta	

#javaee7	

#09: Concurrency: DynamicProxy
@Resource

ContextService service;





Runnable proxy = service.createContextualProxy(new
MyRunnable(), Runnable.class);





Future f = executor.submit(proxy);!
@arungupta	

#javaee7	

JAX-RS 2.0
JSON-P 1.0
Web Socket 1.0Servlet 3.1
JSF 2.2EL 3.0JSP JSTL
BeanValidation1.1
Interceptors1.2
CDI1.1
Concurrency1.0
JPA 2.1
JTA 1.2 EJB 3.2 JMS 2.0
Batch 1.0
JCA 1.7
Java EE 7
JavaMail 1.5
JPA 2.1 (JSR 338)
@arungupta	

#javaee7	

#10: JPA: Schema Generation
Standardized database schema generation
<persistence ... version="2.1">!
<persistence-unit ...>!
<properties>!
<property name="javax.persistence.schema-generation.scripts.action"!
value="drop-and-create"/>!
<property name="javax.persistence.schema-generation.scripts.create-target"
value="create.sql"/>!
<property name="javax.persistence.sql-load-script-source" !
value="insert.sql"/>!
</properties>!
</persistence-unit>!
@arungupta	

#javaee7	

#11: JPA: @Index
Defines additional indexes in schema generation
@Entity!
@Table(indexes = {!
@Index(columnList = "ISBN"),!
@Index(columnList = "NBOFPAGE")!
})!
public class Book {!
!
@Id @GeneratedValue!
private Long id;!
private String isbn;!
private Integer nbOfPage;!
...!
}!
@arungupta	

#javaee7	

#12: JPA: Unsynchronized Persistence
Context
Persistence context is not enlisted in any tx unless explicitly joined
@PersistenceContext(synchronization =!
SynchronizationType.UNSYNCHRONIZED)!
private EntityManager em;!
...!
!
em.persist(book);!
!
...!
em.joinTransaction();!
!
@arungupta	

#javaee7	

#13: JPA: Stored Procedure
Calling a stored procedure
@Entity!
@NamedStoredProcedureQuery(name = "archiveOldBooks", !
procedureName = "sp_archive_books",!
parameters = {!
@StoredProcedureParameter(name = ”date", mode = IN, !
type = Date.class),!
@StoredProcedureParameter(name = "warehouse", mode = IN, !
type = String.class)!
})!
public class Book {...}!
@arungupta	

#javaee7	

JAX-RS 2.0
JSON-P 1.0
Web Socket 1.0Servlet 3.1
JSF 2.2EL 3.0JSP JSTL
BeanValidation1.1
Interceptors1.2
CDI1.1
Concurrency1.0
JPA 2.1
JTA 1.2 EJB 3.2 JMS 2.0
Batch 1.0
JCA 1.7
Java EE 7
JavaMail 1.5
JTA 1.2 (JSR 907)
@arungupta	

#javaee7	

#14: JTA: @Transactional
Transaction management on POJO as CDI interceptor binding
@Path("book")!
@Transactional(value = Transactional.TxType.REQUIRED,!
rollbackOn = {SQLException.class, JMSException.class},!
dontRollbackOn = SQLWarning.class)!
public class BookRestService {!
!
@PersistenceContext!
private EntityManager em;!
!
@POST!
@Consumes(MediaType.APPLICATION_XML)!
public Response createBook(Book book) {...}!
}!
@arungupta	

#javaee7	

#15: JTA: @TransactionScoped
Bean whose lifecycle is scoped to the currently active JTA transaction
@TransactionScoped!
public class BookBean {...}!
!
@WebServlet!
public class TxServlet extends HttpServlet {!
@Inject UserTransaction tx;!
@Inject BookBean b1;!
@Inject BookBean b2;!
!
protected void processRequest(...) {!
tx.begin();!
s_out.println(b1.getReference());!
s_out.println(b2.getReference());!
tx.commit();!
}!
}!
@arungupta	

#javaee7	

JAX-RS 2.0
JSON-P 1.0
Web Socket 1.0Servlet 3.1
JSF 2.2EL 3.0JSP JSTL
BeanValidation1.1
Interceptors1.2
CDI1.1
Concurrency1.0
JPA 2.1
JTA 1.2 EJB 3.2 JMS 2.0
Batch 1.0
JCA 1.7
Java EE 7
JavaMail 1.5
EJB 3.2 (JSR 345)
@arungupta	

#javaee7	

#16: EJB: Disable passivation of
stateful
In some cases increases performance, scalability and robustness
@Stateful(passivationCapable = false)!
public class ShoppingCart {!
...!
}!
@arungupta	

#javaee7	

#17: EJB-Lite: Async + Non-persistent
timer
@Stateless!
public class OrderEJB {!
!
@Asynchronous!
public void sendEmail (Order order) {!
// Very Long task!
}!
!
@Schedule(hour="2", persistent=false)!
public void createDailyReport() {!
// ...!
}!
}!
@arungupta	

#javaee7	

JAX-RS 2.0
JSON-P 1.0
Web Socket 1.0Servlet 3.1
JSF 2.2EL 3.0JSP JSTL
BeanValidation1.1
Interceptors1.2
CDI1.1
Concurrency1.0
JPA 2.1
JTA 1.2 EJB 3.2 JMS 2.0
Batch 1.0
JCA 1.7
Java EE 7
JavaMail 1.5
JMS 2.0 (JSR 343)
@arungupta	

#javaee7	

#18: JMS: JMSContext API
New simplified API to produce and consume messages
@Inject JMSContext ctx;!
!
ctx.createProducer().send(queue, "Text message sent");!
!
ctx.createConsumer(queue).receiveBody(String.class);!
!
ctx.createProducer()!
.setPriority(2)!
.setTimeToLive(1000)!
.setDeliveryMode(DeliveryMode.NON_PERSISTENT)!
.send(queue, message);!
@arungupta	

#javaee7	

#19: JMS: Autocloseable
Several JMS interfaces implement Autocloseable
try (JMSContext ctx = connectionFactory.createContext()) {!
ctx.createProducer().send(queue, "Text message sent");!
}!
!
...!
!
try (JMSContext ctx = connectionFactory.createContext()) {!
while (true) {!
String s = ctx.createConsumer(queue).receiveBody(String.class);!
}!
}!
@arungupta	

#javaee7	

#20: JMS:
JMSConnectionFactoryDefinition
A JMS ConnectionFactory defined using an annotation
@Stateless!
@JMSConnectionFactoryDefinition(!
name = "java:app/jms/MyConnectionFactory",!
interfaceName = "javax.jms.TopicConnectionFactory")!
!
!
!
public class ExpensiveOrderEJB {...}!
@arungupta	

#javaee7	

#21: JMS: JMSDestinationDefinition
A JMS queue or topic can be defined using an annotation
@Stateless!
@JMSConnectionFactoryDefinition(!
name = "java:app/jms/MyConnectionFactory",!
interfaceName = "javax.jms.TopicConnectionFactory")!
@JMSDestinationDefinition(!
name = "java:app/jms/MyTopic",!
interfaceName = "javax.jms.Topic")!
public class ExpensiveOrderEJB {...}!
@arungupta	

#javaee7	

JAX-RS 2.0
JSON-P 1.0
Web Socket 1.0Servlet 3.1
JSF 2.2EL 3.0JSP JSTL
BeanValidation1.1
Interceptors1.2
CDI1.1
Concurrency1.0
JPA 2.1
JTA 1.2 EJB 3.2 JMS 2.0
Batch 1.0
JCA 1.7
Java EE 7
JavaMail 1.5
Servlet 3.1 (JSR 340)
@arungupta	

#javaee7	

#22: Servlet: Non-blocking I/O
public class TestServlet extends HttpServlet

protected void doGet(HttpServletRequest request,

HttpServletResponse response) 

throws IOException, ServletException {

ServletInputStream input = request.getInputStream();

byte[] b = new byte[1024];

int len = -1;

while ((len = input.read(b)) != -1) {

. . .

}

}

}!
@arungupta	

#javaee7	

#22: Servlet: Non-blocking I/O
ServletInputStream!
public void setReadListener(ReadListener listener);!
public boolean isFinished();!
public boolean isReady();!
ServletOutputStream!
public setWriteListener(WriteListener listener);!
public boolean canWrite();!
New methods to existing interfaces
@arungupta	

#javaee7	

#22: Servlet: Non-blocking I/O
public interface ReadListener extends EventListener {

public void onDataAvailable();

pubic void onAllDataRead();

public void onError();

}!
public interface WriteListener extends EventListener {

public void onWritePossible();

public void onError();

}!
New interfaces
@arungupta	

#javaee7	

#22: Servlet: Non-blocking I/O
AsyncContext context = request.startAsync();

ServletInputStream input = request.getInputStream();

input.setReadListener(

new MyReadListener(input, context)); !
Only for Asynchronous Servlets
@arungupta	

#javaee7	

#23: Servlet: Protocol Upgrade
<T extends HttpUpgradeHandler> T
HttpServletRequest.upgrade(Class<T> class) throws IOException;





!
HttpUpgradeHandler!
init(WebConnection wc);!
destroy();!
@arungupta	

#javaee7	

#23: Servlet: Protocol Upgrade
public interface WebConnection {

ServletInputStream getInputStream();

ServletOutputStream getOutputStream();

}!
@arungupta	

#javaee7	

#24: Servlet: Improved Security
<web-app . . . version="3.1"> 

<web-resource-collection>

<url-pattern>/account/*</url-pattern> 

<http-method>GET</http-method>

</web-resource-collection>

<auth-constraint>

. . .

</auth-constraint>

</web-app> !
!
Deny an HTTP method request for an uncovered HTTP method
@arungupta	

#javaee7	

#24: Servlet: Improved Security
<web-app . . . version="3.1"> 

<deny-uncovered-http-methods/>

<web-resource-collection>

<url-pattern>/account/*</url-pattern> 

<http-method>GET</http-method>

</web-resource-collection>

<auth-constraint>

. . .

</auth-constraint>

</web-app> !
!
Deny an HTTP method request for an uncovered HTTP method
@arungupta	

#javaee7	

JAX-RS 2.0
JSON-P 1.0
Web Socket 1.0Servlet 3.1
JSF 2.2EL 3.0JSP JSTL
BeanValidation1.1
Interceptors1.2
CDI1.1
Concurrency1.0
JPA 2.1
JTA 1.2 EJB 3.2 JMS 2.0
Batch 1.0
JCA 1.7
Java EE 7
JavaMail 1.5
Web Socket 1.0 (JSR 356)
@arungupta	

#javaee7	

#25: WebSocket: Annotated server
endpoint
Enables full-duplex bi-directional communication over single TCP connection
@javax.websocket.server.ServerEndpoint("/chat")

public class ChatServer {



@OnMessage

public String chat(String name, Session session) {

for (Session peer : session.getOpenSessions()) {!
peer.getBasicRemote().sendObject(message);!
}

}

}!
@arungupta	

#javaee7	

#26: WebSocket: Lifecycle callbacks
@javax.websocket.OnOpen

public void open(Session s) { . . . }



@javax.websocket.OnClose

public void close(CloseReason c) { . . . }



@javax.websocket.OnError

public void error(Throwable t) { . . . }!
@arungupta	

#javaee7	

#27: WebSocket: Annotated client
endpoint
@javax.websocket.ClientEndpoint

public class MyClient {

@javax.websocket.OnOpen

public void open(Session session) { … }



// Lifecycle callbacks

}!
@arungupta	

#javaee7	

#27: WebSocket: Annotated client
endpoint
ContainerProvider

.getWebSocketContainer()

.connectToServer(

MyClient.class, 

URI.create("ws://. . ."));!
@arungupta	

#javaee7	

#28: WebSocket: Programmatic
endpoints
public class ChatServer extends Endpoint {

@Override

public void onOpen(Session s, EndpointConfig ec) {

s.addMessageHandler(new MessageHandler.Whole<String>() {

public void onMessage(String text) { . . . }

}

}



@Override

public void onClose(Session s, CloseReason cr) { . . . }



//. . . 

}!
@arungupta	

#javaee7	

#28: WebSocket: Programmatic
endpoints
public class MyApplicationConfig implements
ServerApplicationConfig {

public Set<ServerEndpointConfig> getEndpointConfigs(…) { 

ServerEndpointConfig.Builder

.create(MyEndpoint.class, "/websocket”)

.configurator(new MyConfig())

.build()

}

}!
@arungupta	

#javaee7	

#28: WebSocket: Programmatic
endpoints
public class MyConfig extends ServerEndpointConfig.Configurator {



public <T> T getEndpointInstance(. . .) { . . . }



public void modifyHandshake(. . .) { . . . }



. . .

}!
@arungupta	

#javaee7	

#29: WebSocket: Encoder and Decoder
@javax.websocket.server.ServerEndpoint(

value="/chat",

decoders="MyDecoder.class",

encoders="MyEncoder.class")

public class ChatServer {



@OnMessage

public String chat(ChatMessage name, Session session) {

. . . 

}

}!
@arungupta	

#javaee7	

#29: WebSocket: Encoder and Decoder
public class MyDecoder implements Decoder.Text<ChatMessage> {

public ChatMessage decode(String s) {

// . . .

}



public boolean willDecode(String string) {

// . . .

}



//. . .

}



!
@arungupta	

#javaee7	

#29: WebSocket: Encoder and Decoder
public class MyEncoder implements Encoder.Text<ChatMessage> {



public String encode(ChatMessage chatMessage) {

// . . .

}

!
// . . .

}!
@arungupta	

#javaee7	

JAX-RS 2.0
JSON-P 1.0
Web Socket 1.0Servlet 3.1
JSF 2.2EL 3.0JSP JSTL
BeanValidation1.1
Interceptors1.2
CDI1.1
Concurrency1.0
JPA 2.1
JTA 1.2 EJB 3.2 JMS 2.0
Batch 1.0
JCA 1.7
Java EE 7
JavaMail 1.5
Expression Language 3.0 (JSR 341)
@arungupta	

#javaee7	

#30: Expression Langauge:
ELProcessor
Use EL in a stand-alone environment
Evaluate EL expressions
Get/set bean properties
Defining a static method as an EL function
Defining an object instance as an EL name
ELProcessor elp = new ELProcessor();

elp.defineBean("employee", new Employee("Charlie Brown"));

String name = elp.eval("employee.name");!
@arungupta	

#javaee7	

JAX-RS 2.0
JSON-P 1.0
Web Socket 1.0Servlet 3.1
JSF 2.2EL 3.0JSP JSTL
BeanValidation1.1
Interceptors1.2
CDI1.1
Concurrency1.0
JPA 2.1
JTA 1.2 EJB 3.2 JMS 2.0
Batch 1.0
JCA 1.7
Java EE 7
JavaMail 1.5
JSF 2.2 (JSR 344)
@arungupta	

#javaee7	

#31: JSF: Faces Flow
./src/main/webapp/flow1

/flow1.xhtml

/flow1a.xhtml

/flow1b.xhtml

./src/main/webapp/flow2

/flow2-flow.xml

/flow2.xhtml

/flow2a.xhtml

/flow2b.xhtml

/index.xhtml!
Package reusable flows in JAR
@arungupta	

#javaee7	

#31: JSF: Faces Flow
@Named

@FlowScoped("flow1")

public class Flow1Bean implements Serializable {

}!
!
@Produces @FlowDefinition

public Flow defineFlow(@FlowBuilderParameter FlowBuilder fb) {

String flowId = "flow1";

//. . .

return fb.getFlow();

}!
Package reusable flows in JAR
@arungupta	

#javaee7	

#31: JSF: Faces Flow
Package reusable flows in JAR
#{flowScope}: Local flow storage
#{facesContext.application.flowHandler.currentFlow}: Returns true if within a flow
@arungupta	

#javaee7	

#32: JSF: Resource Library Contract
index-blue.xhtml

index-red.xhtml

WEB-INF/lib/contracts-library-1.0-SNAPSHOT.jar

/META-INF/contracts/blue

/style.css

/javax.faces.contract.xml

/template.xhtml

/META-INF/contracts/red

/style.css

/javax.faces.contract.xml

/template.xhtml!
Apply templates in a reusable and interchangeable manner
@arungupta	

#javaee7	

#32: JSF: Resource Library Contract
<f:view contracts=”red”>

<ui:composition template="/template.xhtml">

. . .

</ui:composition>

</f:view>

!
Apply templates in a reusable and interchangeable manner
@arungupta	

#javaee7	

#33: JSF: Pass-through Attributes
<h:inputText type="email" value="#{user.email}"/> 

!
<input type="text" name="j_idt6:j_idt10"/>!
HTML5-Friendly Markup
<h:inputText p:type="email" value="#{user.email}"/> 



<input type="email" name="j_idt6:j_idt10"/>!
!
@arungupta	

#javaee7	

#34: JSF: File Upload Component
<h:form enctype="multipart/form-data">

<h:inputFile value="#{fileUploadBean.file}"/><br/>

<h:commandButton value="Upload"/><p/>

</h:form> !
@Named @RequestScoped 

public class FileUploadBean {

private Part file;



//getter and setter

} !
@arungupta	

#javaee7	

JAX-RS 2.0
JSON-P 1.0
Web Socket 1.0Servlet 3.1
JSF 2.2EL 3.0JSP JSTL
BeanValidation1.1
Interceptors1.2
CDI1.1
Concurrency1.0
JPA 2.1
JTA 1.2 EJB 3.2 JMS 2.0
Batch 1.0
JCA 1.7
Java EE 7
JavaMail 1.5
JAX-RS 2.0 (JSR 339)
@arungupta	

#javaee7	

#35: JAX-RS: Client API
New API to consume rest services
Client client = ClientBuilder.newClient();!
WebTarget target = client.target("http://www.foo.com/book");!
Invocation invocation = target.request(TEXT_PLAIN).buildGet()
Response response = invocation.invoke();!
!
Response response = ClientBuilder.newClient()!
.target("http://www.foo.com/book")!
.request(MediaType.TEXT_PLAIN)!
.get();!
!
String body = ClientBuilder.newClient()!
.target("http://www.foo.com/book")!
.request()!
.get(String.class);!
@arungupta	

#javaee7	

#36: JAX-RS: Async Client
The client API also supports asynchronous invocation
Future<String> future = ClientBuilder.newClient()!
.target("http://www.foo.com/book")!
.request()!
.async()!
.get(String.class);!
!
try {!
String body = future.get(1, TimeUnit.MINUTES);!
} catch (InterruptedException | ExecutionException e) {

...

}!
@arungupta	

#javaee7	

#37: JAX-RS: Async Server
Asynchronous request processing on the server
@Path("/async")!
public class AsyncResource {!
!
@GET!
public void asyncGet(@Suspended AsyncResponse asyncResp) {!
!
new Thread(new Runnable() {!
!
public void run() {!
String result = veryExpensiveOperation();!
asyncResp.resume(result);!
}!
}).start();!
}}!
@arungupta	

#javaee7	

#38: JAX-RS: Message Filter
Used to process incoming and outgoing request or response headers
Filters on client side
ClientRequestFilter!
ClientResponseFilter!
Filters on server side
ContainerRequestFilter!
ContainerResponseFilter!
@arungupta	

#javaee7	

#38: JAX-RS: Message Filter
Used to process incoming and outgoing request or response headers
public class LogginFilter implements ClientRequestFilter {!
!
public void filter(ClientRequestContext ctx) throws IOException {!
System.out.println(ctx.getMethod());!
System.out.println(ctx.getUri());!
}!
}!
@arungupta	

#javaee7	

#39: JAX-RS: Entity Interceptors
Marshalling and unmarshalling HTTP message bodies
Intercepts inbound entity streams (reads from the “wire”)
ReaderInterceptor!
Intercepts outbound entity streams (writes to the “wire”)
WriterInterceptor!
@arungupta	

#javaee7	

#39: JAX-RS: Entity Interceptors
Marshalling and unmarshalling HTTP message bodies
public class GZipInterceptor implements WriterInterceptor {!
!
public void aroundWriteTo(WriterInterceptorContext ctx){!
OutputStream os = ctx.getOutputStream();!
ctx.setOutputStream(new GZIPOutputStream(os));!
ctx.proceed();!
}!
}!
@arungupta	

#javaee7	

JAX-RS 2.0
JSON-P 1.0
Web Socket 1.0Servlet 3.1
JSF 2.2EL 3.0JSP JSTL
BeanValidation1.1
Interceptors1.2
CDI1.1
Concurrency1.0
JPA 2.1
JTA 1.2 EJB 3.2 JMS 2.0
Batch 1.0
JCA 1.7
Java EE 7
JavaMail 1.5
JSON-P 1.0 (JSR 353)
@arungupta	

#javaee7	

#40: JSON-P: JSON Builder
Creates an object model (or an array) in memory by adding elements
JsonObject value = Json.createObjectBuilder()!
.add("id", "1234")!
.add("date", "19/09/2012")!
.add("total_amount", "93.48")!
.add("customer", Json.createObjectBuilder()!
.add("first_name", "James")!
.add("last_name", "Rorrison")!
.add("email", "j.rorri@me.com")!
.add("phoneNumber", "+44 1234 1234")!
)!
.build();!
@arungupta	

#javaee7	

#41: JSON-P: JsonParser
Event-based parser that can read JSON data from a stream
JsonParser parser = Json.createParser(new FileReader(“order.json"));!
while (parser.hasNext()) {!
JsonParser.Event event = parser.next();!
!
if (event.equals(JsonParser.Event.KEY_NAME) && !
parser.getString().matches("email")) {!
parser.next();!
email = parser.getString();!
}!
}!
@arungupta	

#javaee7	

JAX-RS 2.0
JSON-P 1.0
Web Socket 1.0Servlet 3.1
JSF 2.2EL 3.0JSP JSTL
BeanValidation1.1
Interceptors1.2
CDI1.1
Concurrency1.0
JPA 2.1
JTA 1.2 EJB 3.2 JMS 2.0
Batch 1.0
JCA 1.7
Java EE 7
JavaMail 1.5
Batch 1.0 (JSR 352)
@arungupta	

#javaee7	

#42: Batch: Chunk-style Processing
Item-oriented Processing Style (primary)
@arungupta	

#javaee7	

#42: Batch: Chunk-style Processing
<step id=”sendStatements”>!
<chunk item-count=“3”>

<reader ref=”accountReader”/>!
<processor ref=”accountProcessor”/>

<writer ref=”emailWriter”/>!
</step>!
…implements ItemReader {

public Object readItem() {

// read account using JPA!
}!
!
…implements ItemProcessor {!
public Object processItems(Object account) {

// read Account, return Statement!
}!
!
…implements ItemWriter {!
public void writeItems(List accounts) {

// use JavaMail to send email!
}!
!
@arungupta	

#javaee7	

#43: Batch: Batchlet-style Processing
Task-oriented processing style
<step id=”transferFile”>!
<batchlet ref=“MyFileTransfer” />!
</step>!
…implements Batchlet {!
@Override

public void process() {

// Transfer file!
}!
!
@arungupta	

#javaee7	

#44: Batch: Job/Step/Chunk Listeners
<job id="myJob" xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="1.0”>

<listeners>

<listener ref="myJobListener"/>

</listeners>

<step id="myStep" >

<listeners>

<listener ref="myStepListener"/>

<listener ref="myChunkListener"/>

<listener ref="myItemReadListener"/>

<listener ref="myItemProcessorListener"/>

<listener ref="myItemWriteListener"/>

</listeners>

<chunk item-count="3”>. . .</chunk>

</step>

</job>!
!
@arungupta	

#javaee7	

#44: Batch: Job/Step/Chunk Listeners
Interface Abstract Classes
JobListener! AbstractJobListener!
StepListener! AbstractStepListener!
ChunkListener! AbstractChunkListener!
ItemRead/Write/ProcessListener! AbstractItemRead/Write/ProcessListener!
SkipRead/Write/ProcessListener! AbstractSkipRead/Write/ProcessListener!
RetryRead/Write/ProcessListener! AbstractRetryRead/Write/
ProcessListener!
@arungupta	

#javaee7	

#44: Batch: Job/Step/Chunk Listeners
@Named

public class MyJobListener extends AbstractJobListener {



@Override

public void beforeJob() throws Exception { . . . }



@Override

public void afterJob() throws Exception { . . . }

}!
@arungupta	

#javaee7	

#45: Batch: Partition
<step>

<chunk item-count="3">

<reader ref="myItemReader">

<properties>

<property name="start" value="#{partitionPlan['start']}"/>

<property name="end" value="#{partitionPlan['end']}"/>

</properties> 

</reader>

. . .

</chunk>!
@arungupta	

#javaee7	

#45: Batch: Partition
<partition>

<plan partitions="2">

<properties partition="0">

<property name="start" value="1"/>

<property name="end" value="10"/>

</properties>

<properties partition="1">

<property name="start" value="11"/>

<property name="end" value="20"/>

</properties>

</plan>

</partition>

</step>!
@arungupta	

#javaee7	

#46: Batch: Creating Workflows
<flow id="flow1" next="step3">

<step id="step1" next="step2"> . . . </step>

<step id="step2"> . . . </step>

</flow>

<step id="step3"> . . . </step>!
Flow: Elements that execute together as a unit
@arungupta	

#javaee7	

#46: Batch: Creating Workflows
<split id="split1" next=" . . . ">

<flow id="flow1”>

<step id="step1”> . . . </step>

</flow>

<flow id="flow2”>

<step id="step2”> . . . </step>

</flow>

</split>!
Split: Concurrent execution of flows
@arungupta	

#javaee7	

#46: Batch: Creating Workflows
<step id="step1" next="decider1">. . .</step>

<decision id="decider1" ref="myDecider"> 

<next on="DATA_LOADED" to="step2"/> 

<end on="NOT_LOADED"/> </decision>

<step id="step2">. . .</step> !
!
Decision: Customized way of sequencing between steps, flows, splits
@Named

public class MyDecider implements Decider {

@Override

public String decide(StepExecution[] ses) throws Exception {

. . .

return "DATA_LOADED"; // or "NOT_LOADED"!
} !
}!
@arungupta	

#javaee7	

JAX-RS 2.0
JSON-P 1.0
Web Socket 1.0Servlet 3.1
JSF 2.2EL 3.0JSP JSTL
BeanValidation1.1
Interceptors1.2
CDI1.1
Concurrency1.0
JPA 2.1
JTA 1.2 EJB 3.2 JMS 2.0
Batch 1.0
JCA 1.7
Java EE 7
JavaMail 1.5
JavaMail 1.5 (JSR 919)
@arungupta	

#javaee7	

#47: JavaMail
@MailSessionDefinition(name = "java:comp/myMailSession",

properties = {

"mail.smtp.host=smtp.gmail.com",

"mail.smtp.ssl.enable=true",

"mail.smtp.auth=true",

"mail.transport.protocol=smtp",

"mail.debug=true"

})





@Resource(lookup = "java:comp/myMailSession")

Session session;!
@arungupta	

#javaee7	

JAX-RS 2.0
JSON-P 1.0
Web Socket 1.0Servlet 3.1
JSF 2.2EL 3.0JSP JSTL
BeanValidation1.1
Interceptors1.2
CDI1.1
Concurrency1.0
JPA 2.1
JTA 1.2 EJB 3.2 JMS 2.0
Batch 1.0
JCA 1.7
Java EE 7
JavaMail 1.5
JCA 1.7 (JSR 322)
@arungupta	

#javaee7	

#48: Java Connector Architecture
@ConnectionDefinition(

connection="MyConnection.class",

connectionImpl="MyConnectionImpl.class",

connectionFactory="MyConnectionFactory.class",

connectionFactoryImpl="MyConnectionFactoryImpl.class"

)

!
@AdministeredObjectDefinition(

className="MyQueueImpl.class",

name="java:comp/MyQueue",

resourceAdapter="myAdapter",

)!
@arungupta	

#javaee7	

JAX-RS 2.0
JSON-P 1.0
Web Socket 1.0Servlet 3.1
JSF 2.2EL 3.0JSP JSTL
BeanValidation1.1
Interceptors1.2
CDI1.1
Concurrency1.0
JPA 2.1
JTA 1.2 EJB 3.2 JMS 2.0
Batch 1.0
JCA 1.7
Java EE 7
JavaMail 1.5
Java EE 7 (JSR 342)
@arungupta	

#javaee7	

#49: Default Resources
JNDI name: java:comp/DefaultDataSource
Default Data Source
@Resource(lookup="java:comp/DefaultDataSource")

DataSource myDS;

!
@Resource

DataSource myDS; !
@arungupta	

#javaee7	

#49: Default Resources
JNDI name: java:comp/DefaultJMSConnectionFactory





@Resource(lookup="java:comp/DefaultJMSConnectionFactory") 

ConnectionFactory myCF;
@Resource

ConnectionFactory myCF;!
Default JMS Connection Factory
@arungupta	

#javaee7	

#49: Default Resources
JNDI names
java:comp/DefaultManagedExecutorService!
java:comp/DefaultManagedScheduledExecutorService!
java:comp/DefaultManagedThreadFactory!
java:comp/DefaultContextService!
Default Concurrency Utilities Objects
@arungupta	

#javaee7	

#50: Buy our books!
@arungupta	

#javaee7	

References
github.com/javaee-samples/javaee7-samples
github.com/javaee-samples/javaee7-hol
@arungupta	

#javaee7

50 New Features of Java EE 7 in 50 minutes @ Devoxx France 2014

  • 1.
    @arungupta #javaee7 50 new featuresof Java EE 7 in 50 minutes Arun Gupta Director, Developer Advocacy, Red Hat
  • 2.
  • 3.
    @arungupta #javaee7 JAX-RS 2.0 JSON-P 1.0 WebSocket 1.0Servlet 3.1 JSF 2.2EL 3.0JSP JSTL BeanValidation1.1 Interceptors1.2 CDI1.1 Concurrency1.0 JPA 2.1 JTA 1.2 EJB 3.2 JMS 2.0 Batch 1.0 JCA 1.7 Java EE 7 JavaMail 1.5
  • 4.
    @arungupta #javaee7 JAX-RS 2.0 JSON-P 1.0 WebSocket 1.0Servlet 3.1 JSF 2.2EL 3.0JSP JSTL BeanValidation1.1 Interceptors1.2 CDI1.1 Concurrency1.0 JPA 2.1 JTA 1.2 EJB 3.2 JMS 2.0 Batch 1.0 JCA 1.7 Java EE 7 JavaMail 1.5 CDI 1.1 (JSR 346)
  • 5.
    @arungupta #javaee7 #01: CDI: Defaultenabling Finer scanning control Possible values: all, annotated (default), none! annotated behaves like in Java EE 6! ! <beans ... version="1.1" bean-discovery-mode="all">! <alternatives>! <class>org.agoncal.book.MockGenerator</class>! </alternatives>! </beans>!
  • 6.
    @arungupta #javaee7 #02: CDI: @Vetoed Vetothe processing of the class or package @Vetoed! public class NonProcessedBean {
 ...! }! ! package-info.java @Vetoed! package com.non.processed.package;!
  • 7.
    @arungupta #javaee7 JAX-RS 2.0 JSON-P 1.0 WebSocket 1.0Servlet 3.1 JSF 2.2EL 3.0JSP JSTL BeanValidation1.1 Interceptors1.2 CDI1.1 Concurrency1.0 JPA 2.1 JTA 1.2 EJB 3.2 JMS 2.0 Batch 1.0 JCA 1.7 Java EE 7 JavaMail 1.5 Bean Validation 1.1 (JSR 349)
  • 8.
    @arungupta #javaee7 #03: Bean Validation:Method validation Pre/post conditions on method and constructors public class CardValidator {! ! public CardValidator(@NotNull Algorithm algorithm) {! this.algorithm = algorithm;! }! ! @AssertTrue! public Boolean validate(@NotNull CreditCard creditCard) {! return algorithm.validate(creditCard.getNumber());! }! }!
  • 9.
    @arungupta #javaee7 JAX-RS 2.0 JSON-P 1.0 WebSocket 1.0Servlet 3.1 JSF 2.2EL 3.0JSP JSTL BeanValidation1.1 Interceptors1.2 CDI1.1 Concurrency1.0 JPA 2.1 JTA 1.2 EJB 3.2 JMS 2.0 Batch 1.0 JCA 1.7 Java EE 7 JavaMail 1.5 Interceptors 1.2 (JSR 318)
  • 10.
    @arungupta #javaee7 #04: Interceptors: AroundConstruct Interceptorassociated with a constructor public class LoggingInterceptor {! ! @AroundConstruct! private void init(InvocationContext ic) throws Exception{! logger.fine("Entering constructor");! ic.proceed();! logger.fine("Exiting constructor");! }! ! @AroundInvoke! public Object logMethod(InvocationContext ic) ... {! // ...! }! }!
  • 11.
    @arungupta #javaee7 #05: Interceptors: @Priority Prioritizinginterceptor bindings PLATFORM_BEFORE (0), LIBRARY_BEFORE (1000), APPLICATION (2000), LIBRARY_AFTER (3000), PLATFORM_AFTER (4000)! @Interceptor! @Loggable! @Priority(Interceptor.Priority.LIBRARY_BEFORE + 10)! public class LoggingInterceptor {! ! @AroundInvoke! ...! }!
  • 12.
    @arungupta #javaee7 JAX-RS 2.0 JSON-P 1.0 WebSocket 1.0Servlet 3.1 JSF 2.2EL 3.0JSP JSTL BeanValidation1.1 Interceptors1.2 CDI1.1 Concurrency1.0 JPA 2.1 JTA 1.2 EJB 3.2 JMS 2.0 Batch 1.0 JCA 1.7 Java EE 7 JavaMail 1.5 Concurrency utilities 1.0 (JSR 236)
  • 13.
    @arungupta #javaee7 #06: Concurrency: ManagedExecutor • User threads in Java EE applications •  Support simple and advance concurrency design patterns •  Extend Concurrency Utilities API from Java SE (JSR 166y) •  java.util.concurrent package
  • 14.
    @arungupta #javaee7 #06: Concurrency: ManagedExecutor @Resource
 ManagedExecutorServiceexecutor;
 ! 
 ManagedExecutorService executor = (ManagedExecutorService) ctx
 .lookup("java:comp/DefaultManagedExecutorService");! Default ManagedExectuor
  • 15.
    @arungupta #javaee7 #06: Concurrency: ManagedExecutor <web-app… version="3.1">! <resource-env-ref>! <resource-env-ref-name>! concurrent/myExecutor! </resource-env-ref-name>! <resource-env-ref-type>! javax.enterprise.concurrent.ManagedExecutorService! </resource-env-ref-type>! </resource-env-ref>! </web-app>! Specify in web.xml
  • 16.
    @arungupta #javaee7 #07: Concurrency: ManagedScheduledExecutor Managed versionof ScheduledExecutorService! Submit delayed or periodic tasks @Resource
 ManagedScheduledExecutorService executor;!
  • 17.
    @arungupta #javaee7 #07: Concurrency: ManagedScheduledExecutor InitialContext ctx= new InitialContext(); 
 
 ManagedScheduledExecutorService executor = (ManagedScheduledExecutorService)ctx.lookup(
 "java:comp/DefaultManagedScheduledExecutorService");
 ! •  Can be defined in web.xml as well Access using JNDI
  • 18.
    @arungupta #javaee7 #07: Concurrency: ManagedScheduledExecutor executor.schedule(new MyCallableTask(),5, TimeUnit.SECONDS);! executor.scheduleAtFixedRate(new MyRunnableTask(), 2, 3, TimeUnit.SECONDS);! executor.scheduleWithFixedDelay(new MyRunnableTask(), 2, 3, TimeUnit.SECONDS);!
  • 19.
    @arungupta #javaee7 #08: Concurrency: ManagedThreadFactory @Resource(name ="DefaultManagedThreadFactory”)! ManagedThreadFactory factory; ! ManagedThreadFactory factory = (ManagedThreadFactory)! ctx.lookup("java:comp/DefaultManagedThreadFactory");

  • 20.
    @arungupta #javaee7 #08: Concurrency: ManagedThreadFactory Thread thread= factory.newThread(new MyTask()); ((ManageableThread)thread).isShutdown();

  • 21.
    @arungupta #javaee7 #09: Concurrency: DynamicProxy • Create dynamic proxy objects, adds contextual information available for applications running in Java EE environment •  Classloading, JNDI, Security, …
  • 22.
    @arungupta #javaee7 #09: Concurrency: DynamicProxy @Resource
 ContextServiceservice;
 
 
 Runnable proxy = service.createContextualProxy(new MyRunnable(), Runnable.class);
 
 
 Future f = executor.submit(proxy);!
  • 23.
    @arungupta #javaee7 JAX-RS 2.0 JSON-P 1.0 WebSocket 1.0Servlet 3.1 JSF 2.2EL 3.0JSP JSTL BeanValidation1.1 Interceptors1.2 CDI1.1 Concurrency1.0 JPA 2.1 JTA 1.2 EJB 3.2 JMS 2.0 Batch 1.0 JCA 1.7 Java EE 7 JavaMail 1.5 JPA 2.1 (JSR 338)
  • 24.
    @arungupta #javaee7 #10: JPA: SchemaGeneration Standardized database schema generation <persistence ... version="2.1">! <persistence-unit ...>! <properties>! <property name="javax.persistence.schema-generation.scripts.action"! value="drop-and-create"/>! <property name="javax.persistence.schema-generation.scripts.create-target" value="create.sql"/>! <property name="javax.persistence.sql-load-script-source" ! value="insert.sql"/>! </properties>! </persistence-unit>!
  • 25.
    @arungupta #javaee7 #11: JPA: @Index Definesadditional indexes in schema generation @Entity! @Table(indexes = {! @Index(columnList = "ISBN"),! @Index(columnList = "NBOFPAGE")! })! public class Book {! ! @Id @GeneratedValue! private Long id;! private String isbn;! private Integer nbOfPage;! ...! }!
  • 26.
    @arungupta #javaee7 #12: JPA: UnsynchronizedPersistence Context Persistence context is not enlisted in any tx unless explicitly joined @PersistenceContext(synchronization =! SynchronizationType.UNSYNCHRONIZED)! private EntityManager em;! ...! ! em.persist(book);! ! ...! em.joinTransaction();! !
  • 27.
    @arungupta #javaee7 #13: JPA: StoredProcedure Calling a stored procedure @Entity! @NamedStoredProcedureQuery(name = "archiveOldBooks", ! procedureName = "sp_archive_books",! parameters = {! @StoredProcedureParameter(name = ”date", mode = IN, ! type = Date.class),! @StoredProcedureParameter(name = "warehouse", mode = IN, ! type = String.class)! })! public class Book {...}!
  • 28.
    @arungupta #javaee7 JAX-RS 2.0 JSON-P 1.0 WebSocket 1.0Servlet 3.1 JSF 2.2EL 3.0JSP JSTL BeanValidation1.1 Interceptors1.2 CDI1.1 Concurrency1.0 JPA 2.1 JTA 1.2 EJB 3.2 JMS 2.0 Batch 1.0 JCA 1.7 Java EE 7 JavaMail 1.5 JTA 1.2 (JSR 907)
  • 29.
    @arungupta #javaee7 #14: JTA: @Transactional Transactionmanagement on POJO as CDI interceptor binding @Path("book")! @Transactional(value = Transactional.TxType.REQUIRED,! rollbackOn = {SQLException.class, JMSException.class},! dontRollbackOn = SQLWarning.class)! public class BookRestService {! ! @PersistenceContext! private EntityManager em;! ! @POST! @Consumes(MediaType.APPLICATION_XML)! public Response createBook(Book book) {...}! }!
  • 30.
    @arungupta #javaee7 #15: JTA: @TransactionScoped Beanwhose lifecycle is scoped to the currently active JTA transaction @TransactionScoped! public class BookBean {...}! ! @WebServlet! public class TxServlet extends HttpServlet {! @Inject UserTransaction tx;! @Inject BookBean b1;! @Inject BookBean b2;! ! protected void processRequest(...) {! tx.begin();! s_out.println(b1.getReference());! s_out.println(b2.getReference());! tx.commit();! }! }!
  • 31.
    @arungupta #javaee7 JAX-RS 2.0 JSON-P 1.0 WebSocket 1.0Servlet 3.1 JSF 2.2EL 3.0JSP JSTL BeanValidation1.1 Interceptors1.2 CDI1.1 Concurrency1.0 JPA 2.1 JTA 1.2 EJB 3.2 JMS 2.0 Batch 1.0 JCA 1.7 Java EE 7 JavaMail 1.5 EJB 3.2 (JSR 345)
  • 32.
    @arungupta #javaee7 #16: EJB: Disablepassivation of stateful In some cases increases performance, scalability and robustness @Stateful(passivationCapable = false)! public class ShoppingCart {! ...! }!
  • 33.
    @arungupta #javaee7 #17: EJB-Lite: Async+ Non-persistent timer @Stateless! public class OrderEJB {! ! @Asynchronous! public void sendEmail (Order order) {! // Very Long task! }! ! @Schedule(hour="2", persistent=false)! public void createDailyReport() {! // ...! }! }!
  • 34.
    @arungupta #javaee7 JAX-RS 2.0 JSON-P 1.0 WebSocket 1.0Servlet 3.1 JSF 2.2EL 3.0JSP JSTL BeanValidation1.1 Interceptors1.2 CDI1.1 Concurrency1.0 JPA 2.1 JTA 1.2 EJB 3.2 JMS 2.0 Batch 1.0 JCA 1.7 Java EE 7 JavaMail 1.5 JMS 2.0 (JSR 343)
  • 35.
    @arungupta #javaee7 #18: JMS: JMSContextAPI New simplified API to produce and consume messages @Inject JMSContext ctx;! ! ctx.createProducer().send(queue, "Text message sent");! ! ctx.createConsumer(queue).receiveBody(String.class);! ! ctx.createProducer()! .setPriority(2)! .setTimeToLive(1000)! .setDeliveryMode(DeliveryMode.NON_PERSISTENT)! .send(queue, message);!
  • 36.
    @arungupta #javaee7 #19: JMS: Autocloseable SeveralJMS interfaces implement Autocloseable try (JMSContext ctx = connectionFactory.createContext()) {! ctx.createProducer().send(queue, "Text message sent");! }! ! ...! ! try (JMSContext ctx = connectionFactory.createContext()) {! while (true) {! String s = ctx.createConsumer(queue).receiveBody(String.class);! }! }!
  • 37.
    @arungupta #javaee7 #20: JMS: JMSConnectionFactoryDefinition A JMSConnectionFactory defined using an annotation @Stateless! @JMSConnectionFactoryDefinition(! name = "java:app/jms/MyConnectionFactory",! interfaceName = "javax.jms.TopicConnectionFactory")! ! ! ! public class ExpensiveOrderEJB {...}!
  • 38.
    @arungupta #javaee7 #21: JMS: JMSDestinationDefinition AJMS queue or topic can be defined using an annotation @Stateless! @JMSConnectionFactoryDefinition(! name = "java:app/jms/MyConnectionFactory",! interfaceName = "javax.jms.TopicConnectionFactory")! @JMSDestinationDefinition(! name = "java:app/jms/MyTopic",! interfaceName = "javax.jms.Topic")! public class ExpensiveOrderEJB {...}!
  • 39.
    @arungupta #javaee7 JAX-RS 2.0 JSON-P 1.0 WebSocket 1.0Servlet 3.1 JSF 2.2EL 3.0JSP JSTL BeanValidation1.1 Interceptors1.2 CDI1.1 Concurrency1.0 JPA 2.1 JTA 1.2 EJB 3.2 JMS 2.0 Batch 1.0 JCA 1.7 Java EE 7 JavaMail 1.5 Servlet 3.1 (JSR 340)
  • 40.
    @arungupta #javaee7 #22: Servlet: Non-blockingI/O public class TestServlet extends HttpServlet
 protected void doGet(HttpServletRequest request,
 HttpServletResponse response) 
 throws IOException, ServletException {
 ServletInputStream input = request.getInputStream();
 byte[] b = new byte[1024];
 int len = -1;
 while ((len = input.read(b)) != -1) {
 . . .
 }
 }
 }!
  • 41.
    @arungupta #javaee7 #22: Servlet: Non-blockingI/O ServletInputStream! public void setReadListener(ReadListener listener);! public boolean isFinished();! public boolean isReady();! ServletOutputStream! public setWriteListener(WriteListener listener);! public boolean canWrite();! New methods to existing interfaces
  • 42.
    @arungupta #javaee7 #22: Servlet: Non-blockingI/O public interface ReadListener extends EventListener {
 public void onDataAvailable();
 pubic void onAllDataRead();
 public void onError();
 }! public interface WriteListener extends EventListener {
 public void onWritePossible();
 public void onError();
 }! New interfaces
  • 43.
    @arungupta #javaee7 #22: Servlet: Non-blockingI/O AsyncContext context = request.startAsync();
 ServletInputStream input = request.getInputStream();
 input.setReadListener(
 new MyReadListener(input, context)); ! Only for Asynchronous Servlets
  • 44.
    @arungupta #javaee7 #23: Servlet: ProtocolUpgrade <T extends HttpUpgradeHandler> T HttpServletRequest.upgrade(Class<T> class) throws IOException;
 
 
 ! HttpUpgradeHandler! init(WebConnection wc);! destroy();!
  • 45.
    @arungupta #javaee7 #23: Servlet: ProtocolUpgrade public interface WebConnection {
 ServletInputStream getInputStream();
 ServletOutputStream getOutputStream();
 }!
  • 46.
    @arungupta #javaee7 #24: Servlet: ImprovedSecurity <web-app . . . version="3.1"> 
 <web-resource-collection>
 <url-pattern>/account/*</url-pattern> 
 <http-method>GET</http-method>
 </web-resource-collection>
 <auth-constraint>
 . . .
 </auth-constraint>
 </web-app> ! ! Deny an HTTP method request for an uncovered HTTP method
  • 47.
    @arungupta #javaee7 #24: Servlet: ImprovedSecurity <web-app . . . version="3.1"> 
 <deny-uncovered-http-methods/>
 <web-resource-collection>
 <url-pattern>/account/*</url-pattern> 
 <http-method>GET</http-method>
 </web-resource-collection>
 <auth-constraint>
 . . .
 </auth-constraint>
 </web-app> ! ! Deny an HTTP method request for an uncovered HTTP method
  • 48.
    @arungupta #javaee7 JAX-RS 2.0 JSON-P 1.0 WebSocket 1.0Servlet 3.1 JSF 2.2EL 3.0JSP JSTL BeanValidation1.1 Interceptors1.2 CDI1.1 Concurrency1.0 JPA 2.1 JTA 1.2 EJB 3.2 JMS 2.0 Batch 1.0 JCA 1.7 Java EE 7 JavaMail 1.5 Web Socket 1.0 (JSR 356)
  • 49.
    @arungupta #javaee7 #25: WebSocket: Annotatedserver endpoint Enables full-duplex bi-directional communication over single TCP connection @javax.websocket.server.ServerEndpoint("/chat")
 public class ChatServer {
 
 @OnMessage
 public String chat(String name, Session session) {
 for (Session peer : session.getOpenSessions()) {! peer.getBasicRemote().sendObject(message);! }
 }
 }!
  • 50.
    @arungupta #javaee7 #26: WebSocket: Lifecyclecallbacks @javax.websocket.OnOpen
 public void open(Session s) { . . . }
 
 @javax.websocket.OnClose
 public void close(CloseReason c) { . . . }
 
 @javax.websocket.OnError
 public void error(Throwable t) { . . . }!
  • 51.
    @arungupta #javaee7 #27: WebSocket: Annotatedclient endpoint @javax.websocket.ClientEndpoint
 public class MyClient {
 @javax.websocket.OnOpen
 public void open(Session session) { … }
 
 // Lifecycle callbacks
 }!
  • 52.
    @arungupta #javaee7 #27: WebSocket: Annotatedclient endpoint ContainerProvider
 .getWebSocketContainer()
 .connectToServer(
 MyClient.class, 
 URI.create("ws://. . ."));!
  • 53.
    @arungupta #javaee7 #28: WebSocket: Programmatic endpoints publicclass ChatServer extends Endpoint {
 @Override
 public void onOpen(Session s, EndpointConfig ec) {
 s.addMessageHandler(new MessageHandler.Whole<String>() {
 public void onMessage(String text) { . . . }
 }
 }
 
 @Override
 public void onClose(Session s, CloseReason cr) { . . . }
 
 //. . . 
 }!
  • 54.
    @arungupta #javaee7 #28: WebSocket: Programmatic endpoints publicclass MyApplicationConfig implements ServerApplicationConfig {
 public Set<ServerEndpointConfig> getEndpointConfigs(…) { 
 ServerEndpointConfig.Builder
 .create(MyEndpoint.class, "/websocket”)
 .configurator(new MyConfig())
 .build()
 }
 }!
  • 55.
    @arungupta #javaee7 #28: WebSocket: Programmatic endpoints publicclass MyConfig extends ServerEndpointConfig.Configurator {
 
 public <T> T getEndpointInstance(. . .) { . . . }
 
 public void modifyHandshake(. . .) { . . . }
 
 . . .
 }!
  • 56.
    @arungupta #javaee7 #29: WebSocket: Encoderand Decoder @javax.websocket.server.ServerEndpoint(
 value="/chat",
 decoders="MyDecoder.class",
 encoders="MyEncoder.class")
 public class ChatServer {
 
 @OnMessage
 public String chat(ChatMessage name, Session session) {
 . . . 
 }
 }!
  • 57.
    @arungupta #javaee7 #29: WebSocket: Encoderand Decoder public class MyDecoder implements Decoder.Text<ChatMessage> {
 public ChatMessage decode(String s) {
 // . . .
 }
 
 public boolean willDecode(String string) {
 // . . .
 }
 
 //. . .
 }
 
 !
  • 58.
    @arungupta #javaee7 #29: WebSocket: Encoderand Decoder public class MyEncoder implements Encoder.Text<ChatMessage> {
 
 public String encode(ChatMessage chatMessage) {
 // . . .
 }
 ! // . . .
 }!
  • 59.
    @arungupta #javaee7 JAX-RS 2.0 JSON-P 1.0 WebSocket 1.0Servlet 3.1 JSF 2.2EL 3.0JSP JSTL BeanValidation1.1 Interceptors1.2 CDI1.1 Concurrency1.0 JPA 2.1 JTA 1.2 EJB 3.2 JMS 2.0 Batch 1.0 JCA 1.7 Java EE 7 JavaMail 1.5 Expression Language 3.0 (JSR 341)
  • 60.
    @arungupta #javaee7 #30: Expression Langauge: ELProcessor UseEL in a stand-alone environment Evaluate EL expressions Get/set bean properties Defining a static method as an EL function Defining an object instance as an EL name ELProcessor elp = new ELProcessor();
 elp.defineBean("employee", new Employee("Charlie Brown"));
 String name = elp.eval("employee.name");!
  • 61.
    @arungupta #javaee7 JAX-RS 2.0 JSON-P 1.0 WebSocket 1.0Servlet 3.1 JSF 2.2EL 3.0JSP JSTL BeanValidation1.1 Interceptors1.2 CDI1.1 Concurrency1.0 JPA 2.1 JTA 1.2 EJB 3.2 JMS 2.0 Batch 1.0 JCA 1.7 Java EE 7 JavaMail 1.5 JSF 2.2 (JSR 344)
  • 62.
    @arungupta #javaee7 #31: JSF: FacesFlow ./src/main/webapp/flow1
 /flow1.xhtml
 /flow1a.xhtml
 /flow1b.xhtml
 ./src/main/webapp/flow2
 /flow2-flow.xml
 /flow2.xhtml
 /flow2a.xhtml
 /flow2b.xhtml
 /index.xhtml! Package reusable flows in JAR
  • 63.
    @arungupta #javaee7 #31: JSF: FacesFlow @Named
 @FlowScoped("flow1")
 public class Flow1Bean implements Serializable {
 }! ! @Produces @FlowDefinition
 public Flow defineFlow(@FlowBuilderParameter FlowBuilder fb) {
 String flowId = "flow1";
 //. . .
 return fb.getFlow();
 }! Package reusable flows in JAR
  • 64.
    @arungupta #javaee7 #31: JSF: FacesFlow Package reusable flows in JAR #{flowScope}: Local flow storage #{facesContext.application.flowHandler.currentFlow}: Returns true if within a flow
  • 65.
    @arungupta #javaee7 #32: JSF: ResourceLibrary Contract index-blue.xhtml
 index-red.xhtml
 WEB-INF/lib/contracts-library-1.0-SNAPSHOT.jar
 /META-INF/contracts/blue
 /style.css
 /javax.faces.contract.xml
 /template.xhtml
 /META-INF/contracts/red
 /style.css
 /javax.faces.contract.xml
 /template.xhtml! Apply templates in a reusable and interchangeable manner
  • 66.
    @arungupta #javaee7 #32: JSF: ResourceLibrary Contract <f:view contracts=”red”>
 <ui:composition template="/template.xhtml">
 . . .
 </ui:composition>
 </f:view>
 ! Apply templates in a reusable and interchangeable manner
  • 67.
    @arungupta #javaee7 #33: JSF: Pass-throughAttributes <h:inputText type="email" value="#{user.email}"/> 
 ! <input type="text" name="j_idt6:j_idt10"/>! HTML5-Friendly Markup <h:inputText p:type="email" value="#{user.email}"/> 
 
 <input type="email" name="j_idt6:j_idt10"/>! !
  • 68.
    @arungupta #javaee7 #34: JSF: FileUpload Component <h:form enctype="multipart/form-data">
 <h:inputFile value="#{fileUploadBean.file}"/><br/>
 <h:commandButton value="Upload"/><p/>
 </h:form> ! @Named @RequestScoped 
 public class FileUploadBean {
 private Part file;
 
 //getter and setter
 } !
  • 69.
    @arungupta #javaee7 JAX-RS 2.0 JSON-P 1.0 WebSocket 1.0Servlet 3.1 JSF 2.2EL 3.0JSP JSTL BeanValidation1.1 Interceptors1.2 CDI1.1 Concurrency1.0 JPA 2.1 JTA 1.2 EJB 3.2 JMS 2.0 Batch 1.0 JCA 1.7 Java EE 7 JavaMail 1.5 JAX-RS 2.0 (JSR 339)
  • 70.
    @arungupta #javaee7 #35: JAX-RS: ClientAPI New API to consume rest services Client client = ClientBuilder.newClient();! WebTarget target = client.target("http://www.foo.com/book");! Invocation invocation = target.request(TEXT_PLAIN).buildGet() Response response = invocation.invoke();! ! Response response = ClientBuilder.newClient()! .target("http://www.foo.com/book")! .request(MediaType.TEXT_PLAIN)! .get();! ! String body = ClientBuilder.newClient()! .target("http://www.foo.com/book")! .request()! .get(String.class);!
  • 71.
    @arungupta #javaee7 #36: JAX-RS: AsyncClient The client API also supports asynchronous invocation Future<String> future = ClientBuilder.newClient()! .target("http://www.foo.com/book")! .request()! .async()! .get(String.class);! ! try {! String body = future.get(1, TimeUnit.MINUTES);! } catch (InterruptedException | ExecutionException e) {
 ...
 }!
  • 72.
    @arungupta #javaee7 #37: JAX-RS: AsyncServer Asynchronous request processing on the server @Path("/async")! public class AsyncResource {! ! @GET! public void asyncGet(@Suspended AsyncResponse asyncResp) {! ! new Thread(new Runnable() {! ! public void run() {! String result = veryExpensiveOperation();! asyncResp.resume(result);! }! }).start();! }}!
  • 73.
    @arungupta #javaee7 #38: JAX-RS: MessageFilter Used to process incoming and outgoing request or response headers Filters on client side ClientRequestFilter! ClientResponseFilter! Filters on server side ContainerRequestFilter! ContainerResponseFilter!
  • 74.
    @arungupta #javaee7 #38: JAX-RS: MessageFilter Used to process incoming and outgoing request or response headers public class LogginFilter implements ClientRequestFilter {! ! public void filter(ClientRequestContext ctx) throws IOException {! System.out.println(ctx.getMethod());! System.out.println(ctx.getUri());! }! }!
  • 75.
    @arungupta #javaee7 #39: JAX-RS: EntityInterceptors Marshalling and unmarshalling HTTP message bodies Intercepts inbound entity streams (reads from the “wire”) ReaderInterceptor! Intercepts outbound entity streams (writes to the “wire”) WriterInterceptor!
  • 76.
    @arungupta #javaee7 #39: JAX-RS: EntityInterceptors Marshalling and unmarshalling HTTP message bodies public class GZipInterceptor implements WriterInterceptor {! ! public void aroundWriteTo(WriterInterceptorContext ctx){! OutputStream os = ctx.getOutputStream();! ctx.setOutputStream(new GZIPOutputStream(os));! ctx.proceed();! }! }!
  • 77.
    @arungupta #javaee7 JAX-RS 2.0 JSON-P 1.0 WebSocket 1.0Servlet 3.1 JSF 2.2EL 3.0JSP JSTL BeanValidation1.1 Interceptors1.2 CDI1.1 Concurrency1.0 JPA 2.1 JTA 1.2 EJB 3.2 JMS 2.0 Batch 1.0 JCA 1.7 Java EE 7 JavaMail 1.5 JSON-P 1.0 (JSR 353)
  • 78.
    @arungupta #javaee7 #40: JSON-P: JSONBuilder Creates an object model (or an array) in memory by adding elements JsonObject value = Json.createObjectBuilder()! .add("id", "1234")! .add("date", "19/09/2012")! .add("total_amount", "93.48")! .add("customer", Json.createObjectBuilder()! .add("first_name", "James")! .add("last_name", "Rorrison")! .add("email", "j.rorri@me.com")! .add("phoneNumber", "+44 1234 1234")! )! .build();!
  • 79.
    @arungupta #javaee7 #41: JSON-P: JsonParser Event-basedparser that can read JSON data from a stream JsonParser parser = Json.createParser(new FileReader(“order.json"));! while (parser.hasNext()) {! JsonParser.Event event = parser.next();! ! if (event.equals(JsonParser.Event.KEY_NAME) && ! parser.getString().matches("email")) {! parser.next();! email = parser.getString();! }! }!
  • 80.
    @arungupta #javaee7 JAX-RS 2.0 JSON-P 1.0 WebSocket 1.0Servlet 3.1 JSF 2.2EL 3.0JSP JSTL BeanValidation1.1 Interceptors1.2 CDI1.1 Concurrency1.0 JPA 2.1 JTA 1.2 EJB 3.2 JMS 2.0 Batch 1.0 JCA 1.7 Java EE 7 JavaMail 1.5 Batch 1.0 (JSR 352)
  • 81.
    @arungupta #javaee7 #42: Batch: Chunk-styleProcessing Item-oriented Processing Style (primary)
  • 82.
    @arungupta #javaee7 #42: Batch: Chunk-styleProcessing <step id=”sendStatements”>! <chunk item-count=“3”>
 <reader ref=”accountReader”/>! <processor ref=”accountProcessor”/>
 <writer ref=”emailWriter”/>! </step>! …implements ItemReader {
 public Object readItem() {
 // read account using JPA! }! ! …implements ItemProcessor {! public Object processItems(Object account) {
 // read Account, return Statement! }! ! …implements ItemWriter {! public void writeItems(List accounts) {
 // use JavaMail to send email! }! !
  • 83.
    @arungupta #javaee7 #43: Batch: Batchlet-styleProcessing Task-oriented processing style <step id=”transferFile”>! <batchlet ref=“MyFileTransfer” />! </step>! …implements Batchlet {! @Override
 public void process() {
 // Transfer file! }! !
  • 84.
    @arungupta #javaee7 #44: Batch: Job/Step/ChunkListeners <job id="myJob" xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="1.0”>
 <listeners>
 <listener ref="myJobListener"/>
 </listeners>
 <step id="myStep" >
 <listeners>
 <listener ref="myStepListener"/>
 <listener ref="myChunkListener"/>
 <listener ref="myItemReadListener"/>
 <listener ref="myItemProcessorListener"/>
 <listener ref="myItemWriteListener"/>
 </listeners>
 <chunk item-count="3”>. . .</chunk>
 </step>
 </job>! !
  • 85.
    @arungupta #javaee7 #44: Batch: Job/Step/ChunkListeners Interface Abstract Classes JobListener! AbstractJobListener! StepListener! AbstractStepListener! ChunkListener! AbstractChunkListener! ItemRead/Write/ProcessListener! AbstractItemRead/Write/ProcessListener! SkipRead/Write/ProcessListener! AbstractSkipRead/Write/ProcessListener! RetryRead/Write/ProcessListener! AbstractRetryRead/Write/ ProcessListener!
  • 86.
    @arungupta #javaee7 #44: Batch: Job/Step/ChunkListeners @Named
 public class MyJobListener extends AbstractJobListener {
 
 @Override
 public void beforeJob() throws Exception { . . . }
 
 @Override
 public void afterJob() throws Exception { . . . }
 }!
  • 87.
    @arungupta #javaee7 #45: Batch: Partition <step>
 <chunkitem-count="3">
 <reader ref="myItemReader">
 <properties>
 <property name="start" value="#{partitionPlan['start']}"/>
 <property name="end" value="#{partitionPlan['end']}"/>
 </properties> 
 </reader>
 . . .
 </chunk>!
  • 88.
    @arungupta #javaee7 #45: Batch: Partition <partition>
 <planpartitions="2">
 <properties partition="0">
 <property name="start" value="1"/>
 <property name="end" value="10"/>
 </properties>
 <properties partition="1">
 <property name="start" value="11"/>
 <property name="end" value="20"/>
 </properties>
 </plan>
 </partition>
 </step>!
  • 89.
    @arungupta #javaee7 #46: Batch: CreatingWorkflows <flow id="flow1" next="step3">
 <step id="step1" next="step2"> . . . </step>
 <step id="step2"> . . . </step>
 </flow>
 <step id="step3"> . . . </step>! Flow: Elements that execute together as a unit
  • 90.
    @arungupta #javaee7 #46: Batch: CreatingWorkflows <split id="split1" next=" . . . ">
 <flow id="flow1”>
 <step id="step1”> . . . </step>
 </flow>
 <flow id="flow2”>
 <step id="step2”> . . . </step>
 </flow>
 </split>! Split: Concurrent execution of flows
  • 91.
    @arungupta #javaee7 #46: Batch: CreatingWorkflows <step id="step1" next="decider1">. . .</step>
 <decision id="decider1" ref="myDecider"> 
 <next on="DATA_LOADED" to="step2"/> 
 <end on="NOT_LOADED"/> </decision>
 <step id="step2">. . .</step> ! ! Decision: Customized way of sequencing between steps, flows, splits @Named
 public class MyDecider implements Decider {
 @Override
 public String decide(StepExecution[] ses) throws Exception {
 . . .
 return "DATA_LOADED"; // or "NOT_LOADED"! } ! }!
  • 92.
    @arungupta #javaee7 JAX-RS 2.0 JSON-P 1.0 WebSocket 1.0Servlet 3.1 JSF 2.2EL 3.0JSP JSTL BeanValidation1.1 Interceptors1.2 CDI1.1 Concurrency1.0 JPA 2.1 JTA 1.2 EJB 3.2 JMS 2.0 Batch 1.0 JCA 1.7 Java EE 7 JavaMail 1.5 JavaMail 1.5 (JSR 919)
  • 93.
    @arungupta #javaee7 #47: JavaMail @MailSessionDefinition(name ="java:comp/myMailSession",
 properties = {
 "mail.smtp.host=smtp.gmail.com",
 "mail.smtp.ssl.enable=true",
 "mail.smtp.auth=true",
 "mail.transport.protocol=smtp",
 "mail.debug=true"
 })
 
 
 @Resource(lookup = "java:comp/myMailSession")
 Session session;!
  • 94.
    @arungupta #javaee7 JAX-RS 2.0 JSON-P 1.0 WebSocket 1.0Servlet 3.1 JSF 2.2EL 3.0JSP JSTL BeanValidation1.1 Interceptors1.2 CDI1.1 Concurrency1.0 JPA 2.1 JTA 1.2 EJB 3.2 JMS 2.0 Batch 1.0 JCA 1.7 Java EE 7 JavaMail 1.5 JCA 1.7 (JSR 322)
  • 95.
    @arungupta #javaee7 #48: Java ConnectorArchitecture @ConnectionDefinition(
 connection="MyConnection.class",
 connectionImpl="MyConnectionImpl.class",
 connectionFactory="MyConnectionFactory.class",
 connectionFactoryImpl="MyConnectionFactoryImpl.class"
 )
 ! @AdministeredObjectDefinition(
 className="MyQueueImpl.class",
 name="java:comp/MyQueue",
 resourceAdapter="myAdapter",
 )!
  • 96.
    @arungupta #javaee7 JAX-RS 2.0 JSON-P 1.0 WebSocket 1.0Servlet 3.1 JSF 2.2EL 3.0JSP JSTL BeanValidation1.1 Interceptors1.2 CDI1.1 Concurrency1.0 JPA 2.1 JTA 1.2 EJB 3.2 JMS 2.0 Batch 1.0 JCA 1.7 Java EE 7 JavaMail 1.5 Java EE 7 (JSR 342)
  • 97.
    @arungupta #javaee7 #49: Default Resources JNDIname: java:comp/DefaultDataSource Default Data Source @Resource(lookup="java:comp/DefaultDataSource")
 DataSource myDS;
 ! @Resource
 DataSource myDS; !
  • 98.
    @arungupta #javaee7 #49: Default Resources JNDIname: java:comp/DefaultJMSConnectionFactory
 
 
 @Resource(lookup="java:comp/DefaultJMSConnectionFactory") 
 ConnectionFactory myCF; @Resource
 ConnectionFactory myCF;! Default JMS Connection Factory
  • 99.
    @arungupta #javaee7 #49: Default Resources JNDInames java:comp/DefaultManagedExecutorService! java:comp/DefaultManagedScheduledExecutorService! java:comp/DefaultManagedThreadFactory! java:comp/DefaultContextService! Default Concurrency Utilities Objects
  • 100.
  • 101.
  • 102.