aai-1713 introduction to java ee 7
TRANSCRIPT
© 2015 IBM Corporation
AAI-1713Introduction to Java EE 7Kevin Sutter, STSMWebSphere Java EE Architect
Java: Broadest Industry Adoption
9,000,000JAVA DEVELOPERS
DEPLOYING TO 18 COMPLIANT APPLICATION SERVERS
Java EE 7 PlatformJun 12, 2013
Java EE 7 Themes
Batch Concurrency Simplified JMS
More annotated POJOs Less boilerplate code Cohesive integrated
platform
DEVELOPERPRODUCTIVITY
WebSockets JSON Servlet 3.1 NIO REST
MEETINGENTERPRISEDEMANDS
Java EE 7
Top Ten Features in Java EE 7
1. WebSocket client/server endpoints
2. Batch Applications
3. JSON Processing
4. Concurrency Utilities
5. Simplified JMS API
6. @Transactional and @TransactionScoped
7. JAX-RS Client API
8. Default Resources
9. More annotated POJOs
10. Faces Flow
Java API for WebSocket 1.0
• Server and Client WebSocket Endpoint
• Annotated: @ServerEndpoint, @ClientEndpoint
• Programmatic: Endpoint
• Lifecycle events support
• Standard Packaging and Deployment@ServerEndpoint("/chat")public class ChatServer {@OnMessagepublic void chat(String m) {. . .
}}
Available 4Q2014 via Liberty Repository!
Java API for WebSocket 1.0
@ServerEndpoint("/chat")
public class ChatBean {
static Set<Session> peers = Collections.synchronizedSet(...);
@OnOpenpublic void onOpen(Session peer) {
peers.add(peer);}
@OnClosepublic void onClose(Session peer) {
peers.remove(peer);}
. . .
Chat Server
Java API for WebSocket 1.0
. . .
@OnMessage
public void message(String message) {
for (Session peer : peers) {peer.getRemote().sendObject(message);
}}
}
Chat Server (contd.)
JSON Processing 1.0
• API to parse and generate JSON
• Streaming API
• Low-level, efficient way to parse/generate JSON
• Similar to StAX API in XML world
• Object Model API
• Simple, easy to use high-level API
• Similar to DOM API in XML world
Available 4Q2014 via Liberty Repository!
{
"firstName": "John", "lastName": "Smith", "age": 25,"phoneNumber": [
{ "type": "home", "number": "212 555-1234" },{ "type": "fax", "number": "646 555-4567" }
]}
JsonParser p = Json.createParser(...);JsonParser.Event event = p.next(); // START_OBJECTevent = p.next(); // KEY_NAMEevent = p.next(); // VALUE_STRINGString name = p.getString(); // "John”
Java API for JSON Processing 1.0
Streaming API
Batch Applications for Java Platform 1.0
• Suited for non-interactive, bulk-oriented, and long-running tasks
• Batch execution: sequential, parallel, decision-based
• Processing Styles
• Item-oriented: Chunked (primary)
• Task-oriented: Batchlet
Available via Liberty Beta!
Batch Applications 1.0
Concepts
Metadata for jobs
Managebatchprocess
Batchprocess
Independentsequentialphase of job
Chunk
<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 statements) {
// use JavaMail to send email}
Batch Applications 1.0
Chunked Job Specification
Concurrency Utilities for Java EE 1.0
• Extension of Java SE Concurrency Utilities API
• Provide asynchronous capabilities to Java EE application components
• Provides 4 types of managed objects
• ManagedExecutorService
• ManagedScheduledExecutorService
• ManagedThreadFactory
• ContextService
• Context Propagation
Available 4Q2014 via Liberty Repository!
Concurrency Utilities for Java EE 1.0
public class TestServlet extends HttpPServlet {
@Resource(name="java:comp/DefaultManagedExecutorService")ManagedExecutorService executor;
Future future = executor.submit(new MyTask());
class MyTask implements Runnable {public void run() {
. . . // task logic}
}}
Submit Tasks to ManagedExecutorService using JNDI
Java Message Service 2.0
• New JMSContext interface
• AutoCloseable JMSContext, Connection, Session, …
• Use of runtime exceptions
• Method chaining on JMSProducer
• Simplified message sending
Get More from LessJava EE 7
Available via Liberty Beta!
@Resource(lookup = "myConnectionFactory")ConnectionFactory connectionFactory;
@Resource(lookup = "myQueue")Queue myQueue;
public void sendMessage (String payload) {Connection connection = null;try {
connection = connectionFactory.createConnection();Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);MessageProducer messageProducer = session.createProducer(myQueue);TextMessage textMessage = session.createTextMessage(payload);messageProducer.send(textMessage);
} catch (JMSException ex) {//. . .
} finally {if (connection != null) {
try {connection.close();
} catch (JMSException ex) {
//. . .}
}}
}
Application ServerSpecific Resources
Boilerplate Code
Exception Handling
Java Message Service 2.0
Sending a Message using JMS 1.1
Java Message Service 2.0
@InjectJMSContext context;
@Resource(lookup = "java:global/jms/demoQueue")Queue demoQueue;
public void sendMessage(String payload) {context.createProducer().send(demoQueue, payload);
}
Sending a Message
Java API for RESTful Web Services 2.0
• Client API
• Message Filters and Entity Interceptors
• Asynchronous Processing – Server and Client
• Common Configuration
Available via Liberty Beta!
Java API for RESTful Web Services 2.0
// Get instance of ClientClient client = ClientBuilder.newClient();
// Get customer name for the shipped productsString name =client.target("../orders/{orderId}/customer")
.resolveTemplate("orderId", "10")
.queryParam("shipped", "true")
.request()
.get(String.class);
Client API
Contexts and Dependency Injection 1.1
• Automatic enablement for beans with scope annotation andEJBs
• “beans.xml” is optional
• Bean discovery mode
• all: All types
• annotated: Types with bean defining annotation (default)
• none: Disable CDI
• @Vetoed for programmatic disablement of classes
• Global ordering/priority of interceptors and decorators
Available via Liberty Beta!
Bean Validation 1.1
• Alignment with Dependency Injection
• Method-level validation
• Constraints on parameters and return values
• Check pre-/post-conditions
• Integration with JAX-RS
Java EE 7
Available via Liberty Beta!
Built-in
Custom
@Futurepublic Date getAppointment() {
//. . .}
public void placeOrder(@NotNull String productName,@NotNull @Max("10") Integer quantity,@Customer String customer) {
//. . .}
Bean Validation 1.1
Method Parameter and Result Validation
Java Persistence API 2.1
• Schema Generation
• javax.persistence.schema-generation.* properties
• Unsynchronized Persistence Contexts
• Bulk update/delete using Criteria
• User-defined functions using FUNCTION
• Stored Procedure Query
• Entity Graphs
Available via Liberty Beta!
Servlet 3.1
• Non-blocking I/O
• Protocol Upgrade
• HttpUpgradeHandler – necessary for Web Sockets
• Security Enhancements
• <deny-uncovered-http-methods>: Deny request to HTTP
methods not explicitly covered by specified constaints
Available 4Q2014 via Liberty Repository!
Servlet 3.1
public class TestServlet extends HttpServletprotected 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) {. . .
}}
}
Non-blocking I/O Traditional
Servlet 3.1
AsyncContext context = request.startAsync();ServletInputStream input = request.getInputStream();input.setReadListener(
new MyReadListener(input, context));
Non-blocking I/O: doGet
Servlet 3.1
@Overridepublic void onDataAvailable() {
try {StringBuilder sb = new StringBuilder();int len = -1;byte b[] = new byte[1024];while (input.isReady() && (len = input.read(b)) != -1) {
String data = new String(b, 0, len);System.out.println("--> " + data);
}} catch (IOException ex) {
. . .}
}. . .
Non-blocking read
JavaServer Faces 2.2
• Faces Flow
• Resource Library Contracts
• HTML5 Friendly Markup Support
• Pass through attributes and elements
• Cross Site Request Forgery Protection
• Loading Facelets via ResourceHandler
• h:inputFile: New File Upload Component
Java Transaction API 1.2
@Transactional: Define transaction boundaries on CDI managed
beans
• @TransactionScoped: CDI scope for bean instances
scoped to the active JTA transaction
Java EE 7
Available via Liberty Beta!
EJB 3.2
Servlet 3.1
CDIExtensions
Be
an
Va
lid
ati
on
1.1
Batch 1.0
WebFragments
Java EE 7 JSRs
JCA 1.7JMS 2.0JPA 2.1
Managed Beans 1.0
Concurrency 1.0Common
Annotations 1.1Interceptors1.2, JTA 1.2
CDI 1.1
JSF 2.2,JSP 2.3,EL 3.0
JAX-RS 2.0,JAX-WS 2.2
JSON 1.0WebSocket
1.0
WebSphere Java EE 7 “Roadmap”
• Java EE 7 Statement of Direction• http://www-
01.ibm.com/common/ssi/ShowDoc.wss?docURL=/common/ssi/rep_ca/4/897/ENUS214-184/index.html&lang=en&request_locale=en
• IBM intends to deliver a Java EE 7 full platform compliant implementation of WebSphereApplication Server.
• IBM intends to deliver additional Java EE 7 components and additional technologies forWebSphere Application Server through continuous delivery of new features in the comingmonths.
• Liberty GA Deliverables of Java EE Features• Web Sockets 1.0 (4Q2014) and Web Sockets 1.1 (1Q2015)• Servlet 3.1 (4Q2014)• JSON-P 1.0 (4Q2014)• Concurrency Utilities 1.0 (4Q2014)• Java Server Pages (JSP) 2.3 (1Q2015)• Expression Language 3.0 (1Q2015)• Common Annotations 1.2 (1Q2015)• JDBC 4.1 (1Q2015)
• Liberty Beta (Preliminary versions of Java EE features)• https://www.ibmdw.net/wasdev/downloads/liberty-profile-beta/
• Future Content …• Extrapolate at your own speed…
Adopt-a-JSR
Participating JUGs
Sampling of Related Sessions…
• AAI-1713A: Introduction to Java EE 7• Monday, 2-3pm, Mandalay Bay, Reef Ballroom E
• AAI-1641A: Introduction to Web Sockets• Monday, 5-6pm, Mandalay Bay, Reef Ballroom E
• AAI-1313A: Agile Development Using Java EE 7 with WebSphere Liberty Profile(LAB)• Tuesday, 8-10am, Mandalay Bay, South Seas Ballroom D
• AAI-2236A: Using the New Java Concurrency Utilities with IBM WebSphere• Tuesday, 2-3pm, Mandalay Bay, Reef Ballroom D
• AAI-2235A: OpenJPA and EclipseLink Usage Scenarios Explained• Wednesday, 5:30-6:30pm, Mandalay Bay, Surf Ballroom A
• AAI-1610A: Configuring IBM WebSphere Application Server for EnterpriseMessaging Needs• Wednesday, 5:30-6:30pm, Mandalay Bay, Surf Ballroom E
• AAI-3085A: Don’t Wait! Develop Responsive Applications with Java EE7 Instead• Thursday, 10:30-11:30am, Mandalay Bay, Lagoon L
33
Questions?
Notices and DisclaimersCopyright © 2015 by International Business Machines Corporation (IBM). No part of this document may be reproduced ortransmitted in any form without written permission from IBM.
U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP Schedule Contract withIBM.
Information in these presentations (including information relating to products that have not yet been announced by IBM) has beenreviewed for accuracy as of the date of initial publication and could include unintentional technical or typographical errors. IBMshall have no responsibility to update this information. THIS DOCUMENT IS DISTRIBUTED "AS IS" WITHOUT ANY WARRANTY,EITHER EXPRESS OR IMPLIED. IN NO EVENT SHALL IBM BE LIABLE FOR ANY DAMAGE ARISING FROM THE USE OFTHIS INFORMATION, INCLUDING BUT NOT LIMITED TO, LOSS OF DATA, BUSINESS INTERRUPTION, LOSS OF PROFITOR LOSS OF OPPORTUNITY. IBM products and services are warranted according to the terms and conditions of theagreements under which they are provided.
Any statements regarding IBM's future direction, intent or product plans are subject to change or withdrawal withoutnotice.
Performance data contained herein was generally obtained in a controlled, isolated environments. Customer examples arepresented as illustrations of how those customers have used IBM products and the results they may have achieved. Actualperformance, cost, savings or other results in other operating environments may vary.
References in this document to IBM products, programs, or services does not imply that IBM intends to make such products,programs or services available in all countries in which IBM operates or does business.
Workshops, sessions and associated materials may have been prepared by independent session speakers, and do notnecessarily reflect the views of IBM. All materials and discussions are provided for informational purposes only, and are neitherintended to, nor shall constitute legal or other guidance or advice to any individual participant or their specific situation.
It is the customer’s responsibility to insure its own compliance with legal requirements and to obtain advice of competent legalcounsel as to the identification and interpretation of any relevant laws and regulatory requirements that may affect the customer’sbusiness and any actions the customer may need to take to comply with such laws. IBM does not provide legal advice orrepresent or warrant that its services or products will ensure that the customer is in compliance with any law.
Notices and Disclaimers (con’t)
Information concerning non-IBM products was obtained from the suppliers of those products, their publishedannouncements or other publicly available sources. IBM has not tested those products in connection with thispublication and cannot confirm the accuracy of performance, compatibility or any other claims related to non-IBMproducts. Questions on the capabilities of non-IBM products should be addressed to the suppliers of those products.IBM does not warrant the quality of any third-party products, or the ability of any such third-party products tointeroperate with IBM’s products. IBM EXPRESSLY DISCLAIMS ALL WARRANTIES, EXPRESSED OR IMPLIED,INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR APARTICULAR PURPOSE.
The provision of the information contained herein is not intended to, and does not, grant any right or license under anyIBM patents, copyrights, trademarks or other intellectual property right.
• IBM, the IBM logo, ibm.com, Bluemix, Blueworks Live, CICS, Clearcase, DOORS®, Enterprise DocumentManagement System™, Global Business Services ®, Global Technology Services ®, Information on Demand,ILOG, Maximo®, MQIntegrator®, MQSeries®, Netcool®, OMEGAMON, OpenPower, PureAnalytics™,PureApplication®, pureCluster™, PureCoverage®, PureData®, PureExperience®, PureFlex®, pureQuery®,pureScale®, PureSystems®, QRadar®, Rational®, Rhapsody®, SoDA, SPSS, StoredIQ, Tivoli®, Trusteer®,urban{code}®, Watson, WebSphere®, Worklight®, X-Force® and System z® Z/OS, are trademarks ofInternational Business Machines Corporation, registered in many jurisdictions worldwide. Other product andservice names might be trademarks of IBM or other companies. A current list of IBM trademarks is available onthe Web at "Copyright and trademark information" at: www.ibm.com/legal/copytrade.shtml.
Thank YouYour Feedback is
Important!
Access the InterConnect 2015Conference CONNECT AttendeePortal to complete your sessionsurveys from your smartphone,
laptop or conference kiosk.