boost development with java ee7 on eap7 (demitris andreadis)

78
Boost development with Java EE7 on JBoss EAP7 Dimitris Andreadis EAP Engineering Manager June 29, 2016 Jason Greene EAP Architect

Upload: red-hat-developers

Post on 16-Apr-2017

359 views

Category:

Software


0 download

TRANSCRIPT

Page 1: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

Boost development with Java EE7 onJBoss EAP7

Dimitris AndreadisEAP Engineering Manager

June 29, 2016

Jason GreeneEAP Architect

Page 2: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

About Me

JBoss AS/EAP, WildFly Fan(atic)•2001, JBoss User•2003, JBoss Committer•2004, JBoss Full-time Core Developer•2006, JBoss AS Lead (v3.2.8+, v4.0.4+, v4.2.x, 5.0.x)•2009, JBoss AS Engineering Manager•2013, JBoss EAP/WildFly Sr. Engineering Manager

And before JBoss?●7y experience in distributed systems (telcos, NMS/OSS)●BSc/MSc Computer Science (Athens/Dublin)

about.me/dandreadis

Page 3: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

JBoss EAP 7

Page 4: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

WildFly vs JBoss EAP

Open Source Red Hat & Community Resources Rapid Innovation Focus on delivering features

Volunteer community support

Open Source Enterprise Subscription Stability & Compatibility ~ 6 week CPs delivered regularly,

features backported by customerdemand

Industry leading support withguaranteed SLAs

Security certifications and hardening

Open Source Enterprise Subscription Stability & Compatibility ~ 6 week CPs delivered regularly,

features backported by customerdemand

Industry leading support withguaranteed SLAs

Security certifications and hardening

WildFly EAP

Page 5: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

WildFly / EAP Relationship

AS 7.1AS 7.1

EAP 6.1EAP 6.1 EAP 6.2EAP 6.2 EAP 6.3EAP 6.3 EAP 6.4EAP 6.4EAP 6.0EAP 6.0

AS 7.0AS 7.0 AS 7.2AS 7.2

WildFly 8WildFly 8 WildFly 9WildFly 9 WildFly 10WildFly 10

EAP 7.0EAP 7.0 EAP 7.1EAP 7.1

WildFly 11WildFly 11Some Backported Features

Page 6: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

Project vs EE spec vs Product

JBoss AS 2 J2EE 1.2 JBoss AS 3 J2EE 1.3 JBoss AS 4 J2EE 1.4 JBoss EAP 4 JBoss AS 5 Java EE 5 JBoss EAP 5 JBoss AS 6 , AS7 Java EE 6 JBoss EAP 6 WildFly 8, 9, 10 Java EE 7 JBoss EAP 7

Page 7: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

EAP 7 Highlights

100% Java EE7 certified (Web & Full profiles) plus CDI 1.2, WebSockets 1.1 Java SE 8 (OpenJDK, Oracle, IBM and HP JDKs) High Performance Web Server (Undertow) Port reduction (8080, 9990) Reverse Proxy / HTTP/2 HornetQ ActiveMQ Artemis IIOP Implementation switched to OpenJDK ORB CLI Migration Operations (from JBoss Web, JacORB, and HornetQ)

Page 8: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

EAP 7 Highlights (cont.)

HA MDBs & Singleton Deployments Server Suspend Mode/Graceful Shutdown Offline CLI Mode (including Domain mode) Improved UI for large domains Hierarchical Profiles Batch Enhancements Hibernate 5

…and more

Page 9: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

Java EE 7

Page 10: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

Java EE7: Central Themes

Improving Productivity New Web Technologies Better Integration Embracing CDI

Page 11: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

Java EE7 Improvements From Above

Page 12: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

EE7 Highlights – New Techs

JSR-352 Batch Applications for the Java Platform Runtime & Artifact API, XML-based Job specification lang.

JSR-236 Concurrency Utilities for JavaEE Executor, Scheduled Executor, Thread Factory, Context

JSR-353 Java API for JSON Processing (JSON-P) Parse, transform and query JSON data

JSR-356 Web Sockets support Annotation driven endpoints and lifecycle callbacks

Page 13: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

EE7 Highlights – Spec. Updates

JSR-345 EJB 3.2, plus Interceptors 1.2, Annotations 1.2 Misc. improvements

JSR-340 Servlet 3.1 Non-blocking I/O, HTTP upgrade, etc.

JSR-342 JMS 2.0 Shared topic subs, delayed delivery, async send, etc.

JSR-344 JSF 2.2 HTML 5, FaceFlows, Stateless Views, Resource lib contracts

JSR-322 JCA 1.7 Activation name for msg endpoints

Page 14: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

EE7 Highlights – Optional Techs

EJB 2.1 Entity Beans (CMP/BMP) JAX-RPC (API for XML-based RPC) JAXR (API for XML Registries) JSR-88 (Deployment API) it has re-surfaced in JSR 373 (JSR-77 successor) JavaTM EE Management API 2.0

Page 15: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

Batch Processing - JSR-352

Based on decades of industry experience Balances transactional integrity and performance Separates responsibilities into reusable components Customizable execution using job specification language

Item Reader

Item Processor

Item Writer

Step

Job Repository

Job Operator Job

Page 16: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

Batch Processing

Item Reader

Item Processor

Item Writer

<job id="job"> <step id="step1"> <chunk item-count=“3”> <reader ref="AccReader"/> <processor ref="AccProcessor"/> <writer ref="AccWriter"/> </chunk> </step></job>

Chunk 1A

Item 1

Item 2

Item 3

Item 1

Page 17: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

Parallelism Using Chunks & Partitions

<chunk item-count=“3”> <reader ref=“AccReader”> <properties> <property name="start" value="#{partitionPlan['start']}"/> <property name="end" value="#{partitionPlan['end']}"/> </properties> </reader> <processor ref="AccProcessor"/> <writer ref=“AccWriter"/> </chunk> <partition> <plan partitions=“2”> <properties partition="0"> <property name="start" value="1"/> <property name="end" value="10"/> </properties> ... </partition>

Job XML

Chunk 1A

Item 1

Item 2

Item 3

Chunk 2A

Item 4

Item 5

Item 6

Chunk 1B

Item 11

Item 12

Item 13

Chunk 2B

Item 14

Item 15

Item 16

Thread 1 Thread 2

Page 18: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

Starting a Job

Easily called from a Servlet or an EJB or common shared code Can also abort and resume jobs

JobOperator jobOperator = BatchRuntime.getJobOperator();Properties props = new Properties();props.setProperty(...)long id = jobOperator.start(JOB_NAME, props);

Page 19: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

EE Concurrency

Adds Java EE variants of SE Executors ManagedExecutorService ManagedScheduledExecutorService ManagedThreadFactory

Provides Contextual Proxies ContextService

Supports Task listeners in addition to futures Supports UserTransaction

Page 20: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

Simple Executor Example

@ResourceManagedExecutorService executor;Future res;

void startSearch() { res = executor.submit(new Callable<Long>() { public Long call() { return findNeedleInHaystack(); } });} long waitForNeedle() { return res.get();}

Page 21: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

Context Servicepublic interface MessageProcessor { public void process(Message msg);}

public class UserUpdate implements MessageProcessor { public void process(Message msg) { // requires user’s principal to update updateUserLastMessageTime(msg); } }// On Servletpublic void doPost() { ... MessageProcessor callback = service.createContextualProxy(new UserUpdate(), execProps, MessageProcessor.class); producer.send(dest, session.createObjectMessage(callback));} public class ProcessingMDB { public void onMessage(Message msg) { ObjectMessage omsg = (ObjectMessage)msg; ((MessageProcessor)omsg.getObject()).process(); }}

Page 22: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

JMS 2.0 - API Simplification

@Inject JMSContext context;@Resource(lookup=”java:module/myqueue”) Queue queue;

void sendSomething(String data) { context.createProducer().send(queue, data);}

Page 23: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

JMS 2: Shared Subscriptions

ProducerProducer TopicTopic

Consumer Job AConsumer Job A

Shared Sub BShared Sub B

Consumer Job B 1Consumer Job B 1

Consumer Job B 2Consumer Job B 2

Consumer Job B 3Consumer Job B 3

Message 1 - Job AMessage 1 - Job A

Message 2 - Job BMessage 2 - Job B

Message 3 - Job BMessage 3 - Job B

Consumer Job AConsumer Job AMessage 1 - Job AMessage 1 - Job A

Page 24: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

JAX-RS 2 Client API

Client client = ClientBuilder.newClient(); WebTarget target = client.target(“.../people"); Person p = target .path("{id}") .resolveTemplate("id", "1") .request(MediaType.APPLICATION_XML) .get(Person.class);

GET /people/1 HTTP/1.1Accept: application/xml

Page 25: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

JSON API (JSR 353): DOM-Like API

JsonObject jsonObject = Json.createObjectBuilder() .add("apple", "red") .add("banana", "yellow") .build(); StringWriter w = new StringWriter();JsonWriter writer = Json.createWriter(w); writer.write(jsonObject);

JsonReader reader = Json.createReader(…);JSonObject jsonObject = (JsonObject)reader.read();

Page 26: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

JSON API (JSR 353): StAX-Like API

JsonParser parser = Json.createParser(new StringReader(jsonData));while (parser.hasNext()) { JsonParser.Event event = parser.next(); switch(event) { case START_OBJECT: System.out.println("Name = " + parser.getString()); break; case KEY_NAME: System.out.println("Key = " + parser.getString()); break;

case VALUE_STRING: System.out.println("Value = " + parser.getString()); break;

}}

Page 27: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

CDI Everywhere

Automatic enablement for beans with scope annotation and EJBs “beans.xml” is optional Bean discovery mode all: All types annotated: Types with bean defining annotation none: Disable CDI

@Vetoed for programmatic disablement of classes Global ordering/priority of interceptors and decorators

Page 28: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

Web Sockets Overview

Full-duplex Communication Framed Messages Binary and Text Messages Supports Fragmentation

Page 29: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

JS Web Socket Client Example

var socket = new WebSocket(“ws://www.example.com/websocket/johndoe“);

// Every message we get, dump it to the logsocket.onmessage = function (event) { console.log(event.data);}

// Send a text messageexampleSocket.send(“Hi There!”);

Page 30: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

Web Sockets - Server Endpoint (Text Messages)

@ServerEndpoint("/websocket/{name}") //note the URL template.public class HelloEndpoint {

@OnOpen //invoked when the client first connects public void onOpen(final Session session) { session.getAsyncRemote().sendText("hi"); }

@OnMessage //handles text messages public String message(String message, @PathParam("name") String name) { return "Hello " + name + " you sent" + message; }}

Page 31: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

Web Sockets - Server Endpoint (Binary Messages)

@ServerEndpoint("/websocket/{name}") //note the URL template.public class HelloEndpoint {

@OnMessage //handles binary messages public byte[] binaryMessage(byte[] binaryMessage) { return binaryMessage; //echo binary data }

@OnClose //invoked when the connection is closed public void onClose(final Session session) { System.out.println("Connection closed"); }}

Page 32: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

Web Socket - Client Connections

ServerContainer sc = (ServerContainer)servletContext.getAttribute("javax.websocket.server.ServerContainer");

Session session = sc.connectToServer(AnnotatedClientEndpoint.class, new URI("ws://example.com/chat"));

Future<Void> future = session.getAsyncRemote() .sendText("Hello Websocket");

Page 33: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

Web Socket - Client Endpoint

@ClientEndpointpublic class AnnotatedClientEndpoint {

@OnOpen public void onOpen(final Session session) { session.getAsyncRemote().sendText("hi"); }

@OnMessage public void onMessage(final String message, final Session session) { System.out.println(message); }}

Page 34: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

Servlet 3.1

Non-Blocking Listeners Improved Async Processing

Custom Http Upgrade Support Security enhancements

Page 35: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

Non-Blocking Async Example

protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { final AsyncContext context = req.startAsync(); final ServletOutputStream outputStream = resp.getOutputStream(); final String[] messages = {"Hello ", "async ", "world"}; outputStream.setWriteListener(new WriteListener() { int pos = 0; @Override public synchronized void onWritePossible() throws IOException { while (outputStream.isReady() && pos < messages.length()) { outputStream.write(messages[pos++].getBytes()); } if (pos == messages.length()) context.complete(); } });}

Page 36: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

Beyond Servlet - HTTP Handlers

public class HelloWorldHandler implements HttpHandler { @Override public void handleRequest(final HttpServerExchange exchange) throws Exception { exchange.getResponseHeaders() .put(Headers.CONTENT_TYPE, "text/plain"); exchange.getResponseSender() .send("Hello World"); }}

Page 37: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

Beyond Servlet - HTTP Handlers

public class MyBlockingHandler implements HttpHandler { @Override public void handleRequest(final HttpServerExchange exchange) throws Exception { if (exchange.isInIoThread()) { exchange.dispatch(this); return; } // Do blocking stuff }}

Page 39: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)
Page 40: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

Welcome to this presentation about JavaEE7 on EAP.

We were to do this presentation togetherwith Jason Greene, EAP7 architect, buthe had a conflict so here I am.

To help me with the presentation lets makea quick poll:

Who uses EAP 4/5/6?

Community WildFly?

Who doesn’t know anything aboutWildFly/EAP?

Page 41: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

Few words about me, I’ve been involed withJBossAS/EAP now WildFly for 15 years now, indifferent capacities.

Page 42: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

JBoss EAP 7

Page 43: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

WildFly vs JBoss EAP

Open Source Red Hat & Community Resources Rapid Innovation Focus on delivering features

Volunteer community support

Open Source Enterprise Subscription Stability & Compatibility ~ 6 week CPs delivered regularly,

features backported by customerdemand

Industry leading support withguaranteed SLAs

Security certifications and hardening

Open Source Enterprise Subscription Stability & Compatibility ~ 6 week CPs delivered regularly,

features backported by customerdemand

Industry leading support withguaranteed SLAs

Security certifications and hardening

WildFly EAP

Page 44: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

WildFly / EAP Relationship

AS 7.1AS 7.1

EAP 6.1EAP 6.1 EAP 6.2EAP 6.2 EAP 6.3EAP 6.3 EAP 6.4EAP 6.4EAP 6.0EAP 6.0

AS 7.0AS 7.0 AS 7.2AS 7.2

WildFly 8WildFly 8 WildFly 9WildFly 9 WildFly 10WildFly 10

EAP 7.0EAP 7.0 EAP 7.1EAP 7.1

WildFly 11WildFly 11Some Backported Features

Page 45: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

Project vs EE spec vs Product

JBoss AS 2 J2EE 1.2 JBoss AS 3 J2EE 1.3 JBoss AS 4 J2EE 1.4 JBoss EAP 4 JBoss AS 5 Java EE 5 JBoss EAP 5 JBoss AS 6 , AS7 Java EE 6 JBoss EAP 6 WildFly 8, 9, 10 Java EE 7 JBoss EAP 7

Page 46: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

Migration to Red Hat JBoss Middleware—easy, predictable, proven - Thursday,Jun 30, 11:30 AM - 12:30 PM

• Port ReductionJBoss EAP 7 now hasalmost all protocols multiplexed overtwo ports. The two ports include:

• a management port (HTTP/JSONManagement, HTTP UpgradedRemoting - Native Management & JMX,management console).

• an application port (HTTP Servlet, JAX-RS, JAX-WS, WebSocket, HTTPUpgraded Remoting-EJB Invocation-Remote JNDI).

Page 47: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

• Server Suspend Mode/GracefulShutdown - The new server suspendmode in JBoss EAP 7, once activated,rejects new requests but allows existingones to complete. When the suspensionprocess completes, the server caneither be stopped without aborting in-flight transactions; left in suspendedstate while maintenance is performed;or returned to the running state wherenew requests are again allowed.(Excluding Messaging andTransactions; including Web, EJB,mod_cluster, Batch, Naming, andpartially for EE Concurrency).

• Port ReductionJBoss EAP 7 now hasalmost all protocols multiplexed overtwo ports. The two ports include:

• a management port (HTTP/JSONManagement, HTTP UpgradedRemoting - Native Management & JMX,management console).

• an application port (HTTP Servlet, JAX-RS, JAX-WS, WebSocket, HTTPUpgraded Remoting-EJB Invocation-Remote JNDI).

• Batch Enhancements include:• improvements in monitoring, such as

the ability to list active jobs, finishedjobs, and job execution steps.

• the ability to start, stop, and resumebatch jobs using management API.

• the ability to restart batch jobs that failedbecause of a server failure. It can reset(i.e., ignore/log) the previous status sothat the batch job can be executed onanother server in the domain servergroup.

Page 48: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

Java EE 7

Page 49: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

Java EE7 will improve the productivity ofyour team by

• reducing code bloat, enhancing and• simplifying APIs you are already using,• and introducing new frameworks that

make it easy to build advanced nextgeneration applications.

Page 50: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

Java EE7 Improvements From Above

Page 51: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

EE7 Highlights – New Techs

JSR-352 Batch Applications for the Java Platform Runtime & Artifact API, XML-based Job specification lang.

JSR-236 Concurrency Utilities for JavaEE Executor, Scheduled Executor, Thread Factory, Context

JSR-353 Java API for JSON Processing (JSON-P) Parse, transform and query JSON data

JSR-356 Web Sockets support Annotation driven endpoints and lifecycle callbacks

Page 52: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

EE7 Highlights – Spec. Updates

JSR-345 EJB 3.2, plus Interceptors 1.2, Annotations 1.2 Misc. improvements

JSR-340 Servlet 3.1 Non-blocking I/O, HTTP upgrade, etc.

JSR-342 JMS 2.0 Shared topic subs, delayed delivery, async send, etc.

JSR-344 JSF 2.2 HTML 5, FaceFlows, Stateless Views, Resource lib contracts

JSR-322 JCA 1.7 Activation name for msg endpoints

Page 53: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

EE7 Highlights – Optional Techs

EJB 2.1 Entity Beans (CMP/BMP) JAX-RPC (API for XML-based RPC) JAXR (API for XML Registries) JSR-88 (Deployment API) it has re-surfaced in JSR 373 (JSR-77 successor) JavaTM EE Management API 2.0

Page 54: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

Batch was an IBM lead specification, witha major goal to enhance Java EE so thatit could handle batch processing use-cases that were currently bettersupported on mainframe environments.

Red Hat was a contributing EG memberand developments an implementationcalled jBeret, which provides the batchcapabilities in EAP7

A central principal of the specification isthat it follows a read->process(transform) ->write paradigm, withplugable components for each phase ofprocessing.

Those components are then orchestratedusing a job specification language.

A job encapsulates the entire batchprocess. A job contains one or moresteps. A job is put together using a JobSpecification Language (JSL) thatspecifies the sequence in which thesteps must be executed. In JSR 352,JSL is specified in an XML file called thejob XML file. In short, a job (with JSR352) is basically a container for steps.

A step is a domain object thatencapsulates an independent, sequentialphase of the job. A step contains all thenecessary logic and data to perform theactual processing. The batchspecification deliberately leaves thedefinition of a step vague because thecontent of a step is purely application-specific and can be as complex orsimple as the developer desires. Thereare two kinds of steps: chunk andbatchlet.

A chunk-style step contains exactly oneItemReader, one ItemProcessor, andone ItemWriter. In this pattern,ItemReader reads one item at a time,ItemProcessor processes the item basedupon the business logic (such as"calculate account balance"), and handsit to the batch runtime for aggregation.Once the "chunk-size" number of itemsare read and processed, they are givento an ItemWriter, which writes the data(for example, to a database table or aflat file). The transaction is thencommitted.

JSR 352 also defines a roll-your-own kindof a step called a batchlet. A batchlet isfree to use anything to accomplish thestep, such as sending an e-mail.

JobOperator provides an interface tomanage all aspects of job processing,including operational commands, suchas start, restart, and stop, as well as jobrepository commands, such as retrievalof job and step executions. See section10.4 of the JSR 352 specification formore details about JobOperator.

JobRepository holds information aboutjobs currently running and jobs that ranin the past. JobOperator provides APIsto access this repository. AJobRepository could be implementedusing, say, a database or a file system.

Page 55: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

In order to balance transactional integritywith the performance implications ofprocessing thousands or perhapsmillions of records, batch uses the notionof a “chunk” to define a transactionalboundary. Additionally, when a job isstopped it saves a checkpoint at aboundary such that it can later beresumed.

This example processes 3 records in achunk, by invoking a separate readerand processor class for each “item” (arecord), and accumulating the resultsbefore writing them together, in onetransaction, using a writer class. Theidea here is that you can swap each ofthese independently which is useful ifyou are migrating data storagetechnologies.

Page 56: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

The execution engine and the jobspecification is quite powerful, and as anexample of that we can modify the jobdescription from the previous example todefine a partition block, and with no codechanges we get parallel processing!

Following this new example, the containerwill internally create two threads, andeach thread will process 3 record chunksoffset, and each handling half the data.

Overall the specification is quite rich andincludes a number of other advancedcapabilities like the ability to define batchflows which involve many steps anddecision points, the ability to definedynamic partitioning, and the ability tohave customized failure handling andbackout of changes.

Page 57: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

Once a batch job is defined, it’s quitesimple to introspect, to start, to restart(which really means resuming), and stopa job. For example, you can use thistrivial 4-line snippet of code in a servlet,or EJB to launch a batch job.

Page 58: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

Batch is just one of the new ways toexecute background tasks in Java EE7.Additionally the EE concurrency featuresin Java EE7 allow you to use simpleexecutors.

This solves a long standing issue withJava EE. Since Java 5, the languagehas had the ability to take a “runnable”code block, and pass it to an executorwhich manages a pool of worker threadsfor you. While the feature worked greatin an SE environment, some EEcontainers would outright disallow it,some not (JBoss allowed it), but moreimportantly there was unexpectedconsequences, like you could lose thingsyou normally expect in an EE context,such as the deployments namingenvironment, or the security context ofthe current invocation. It was also notguaranteed that you could interact withthe transaction manager.

The EE concurrency spec introduces“managed” variants of the SE executors,which give your runnable’s a traditionalEE context that you would expect.

Page 59: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

???Callable call()???

An executor is now looks and behaves likeany other EE capability. If you need anexecutor, you can simply inject it using@Resource, and from there you call itjust like you would an SE executor.

This example shows a use-case whereyou need a long running backgroundsearch capability. A callable is defined toperform our search, and the returnedfuture can either be polled or blocked on.

Page 60: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

A more advanced capability in EEconcurrency is that you can pass an EEcontext from one EE thread to anotherEE thread. In this example we want topass the context of a servlet into ourMDB code. This can be useful if you arejust trying to run code that you alreadyhad in your servlet, and that codeexpects values in the servlets namingcontext, and perhaps the current userexecuting the request. In the examplewe have a User record of some sort, andit has a last message received time. Sowe can take the implementation of thatcode, put it into an inner class that weinstantiate and wrap with a contextproxy. The context proxy can then beserialized on a message, and whenreceived, you simply deserialize it, andinvoke it, and it will restore the relevantcontext.

Page 61: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

Another major improvement is that JMSwas heavily simplified. Previously if youwanted to send a message you wouldneed to get a connection factory, createa connection, then from the connectioncreate a session, then from the sessioncreate a producer, and from the producercreate a message, which you finallysend on the producer. This also involvednested try finally blocks, so you couldeasily end up with 20 lines of code, fornow something that is a couple injectionpoints and a single line. You inject aJMSContext, and the destination, whichis a queue in this case. The consumercase looks identical, you just flipproducer to consumer and call receiveinstead of send

Page 62: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

Normally with a JMS topic, everysubscriber receives a duplicate copy ofthe same message. This works wellwhen you have separate subscribersthat perform unrelated actions that withthe message. However if you want toscale up a subscriber by subdividing itinto multiple threads or processes, youwould either have to write customconcurrency and hand-off code or useMDBs. ???Why not use MDBs???

JMS 2 adds the notion of sharedsubscriptions, which allows you to havemultiple subscribers that share the samemessage stream. So when a messagecomes in they act more like a queue,and each receives only one message.You can then scale up by just creatingmore threads or more processes with thesame code.

In this example we have threesubscriptions on a topic that areinterested in a particular message type(job A or job B). Message 1 is deliveredto the two consumers that have aselector on Job B, while Messages 2 and3 are received by only one consumer ona shared subscription.

Page 63: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

A major change in JAX-RS 2.0 is theintroduction of a rich client side facility,that allows you to do template styleprocessing.

This example creates a template andpopulates the ID field, which is thenassembled into the request URL. Theprovided media-type is mapped to anAccept header, and also facilitates theselection of the unmarshaller. In thisexample Person is unmarshalled usingJAXB to give us a usable Person object.

Page 64: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

Another major addition to the Java EE 7 isa rich JSON API. It has two processingmodes, the first is a DOM like API whichallows you to easily read and write aJSON object structure. As with DOM,The API models the JSON structure as atree, and it can walked in a similarfashion. This is useful for transformationactions.

Page 65: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

Additionally there is a streaming mode,which is similar to the StAX API withXML. As with StAX, you create a pullparser, and pull out events in an iterativefashion. This is handy when you need tooperate on very large JSON objects thatwould otherwise consume significantmemory resources.

Page 66: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

CDI was introduced in Java EE6, but toenable it you needed to define abeans.xml file in your deployment. InJava EE7, CDI is now enabled for alldeployments by default, so thisdescriptor is no longer required. CDI hasalso been tightly integrated with JAX-RS.

If you aren’t extensively using CDI, anddon't want to pay for the scanningoverhead you can disable it by providinga beans.xml file and altering the beandiscovery mode to either annotated ornone. Although, the overhead is fairlysmall, so its not likely noticeable unlessyou have a massive deployment withhundreds of thousands of classes.

Another reason you might need to do this,is if you are using another injectionframework, like google guice, that alsouses the JSR 330 SE injectionannotations.

Page 67: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

A major Java EE 7, and EAP7 feature isfull support for web sockets

Web sockets allows HTML5 applications toconvert an HTTP connection into a full-duplex communication pipe, as if it was aTCP socket. This is useful for real-timeapplications, like chat clients, stocktickers and games. Instead of polling theserver for new information, the servercan push the update as soon as itsavailable, which reduces the extraround-trip time that is typically incurred.

Web sockets is a framed protocol wheredata is sent in messages with a smallheader. Messages can be fragmentedacross multiple data frames which allowssending of large messages where thelength is unknown. Messages can eitherhave a text payload (UTF-8) or a binarypayload

Page 68: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

Creating a web socket in the browser isvery simple, you construct a WebSocketobject using a web socket URL. TheURL is the same as a standard http URL,with just http changes to ws. Internallythis makes a new HTTP connection tothe server, and then it utilizes HTTPupgrade to convert the connection to aweb sockets connection.

Using the created Web Socket object, youcan register message handlers and/orsend messages. In this example wedump every message the server sendsus to the log, and immediately send ahello text message.

Page 69: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

On the server side in EAP, all you need todo is define a server endpoint using theServerEndpoint annotation on a newclass. On the class you define variousevent methods to respond toconnections and messages. In thisexample when a new client connects weasynchronously send back a textmessage, and when we receive anymessage we echo back what they sentus. It’s also possible to send messagessynchronously, if we wanted the serverto wait on a successful transmissionbefore taking further action.

The web sockets API also has the ability tobind path parameters much like a JAX-RS application. In this example we sendback the “name” portion of the URL inresponse to a message.

Page 70: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

Binary messages work in a similar fashionbut with a byte[] or ByteBuffers.Additionally you can receive anInputSream, and process the data in ablocking fashion.

Much like JAX-RS the web socketsfacilities in EE7 allow you to registercustom encoders and decoders whichmap arbitrary Java objects to messages.If we were to apply this facility to ourexample, the @OnMessage handlercould have returned a Java POJOdirectly. ???Where/How???

Page 71: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

???getAttribute(ServerContainer)

The EE7 Web Sockets facility can also beused as a client, either from astandalone Java application, or within adeployment on EAP7.

This example shows how a servlet canobtain a WebSocket session and registera client endpoint. It additionally sends amessage right after connecting.

Page 72: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

The client endpoint operates the same asa server endpoint, this example has anOnMessage handler and an OnOpenhandler the same as our server example

Page 73: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

In addition to web sockets, EE7 also madesignificant improvements to the Servletspec, notably support for non-blockingI/O.

Page 74: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

With traditional blocking I/O on the readingside you develop your application to readas if the data is already all there, and theserver blocks the thread waiting asnecessary. Likewise on the write side,you write as if the client is ready, and theserver blocks in any case that it isn’t.This makes the programming modelsimple, but it ties up server resources(everything allocated on a currentthread) while the connection is blocking.

Non-blocking i/o addresses this issue byreading and writing only what you can, inarbitrary chunks, and then immediatelyreturning control back to the server. Youthen receive additional callbacks as theconnection becomes ready for readingand writing. This does make theprogramming model a bit morecomplicated because you have to trackstate, however, it can yield significantperformance if the scenario maps well toa non-blocking paradigm.

In this example we register a write listener,and receive an “onWritePossible” eventwhenever the underlying connection isready for data. Each write has to checkisReady on the stream and return if itsfalse.

Another thing to note is that the underlyingweb server in EAP7, Undertow, is a high-performance non-blocking server. Even ifyou are using blocking i/o in yourapplication, all of the server interactionup until the point at which your code iscalled are processed in a non-blockingfashion. So idle connections, andrequest routing still receive theperformance benefits.

Page 75: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

Another way to implement non-blockingweb handling on EAP7 is to directlyimplement HttpHandlers. HttpHandlershave a richer API than the ReadListenerand WriteListener facility of Servlet 3.1,and they allow you to truly customizeserver behavior. You can relate them toTomcat valves, if you have everextended Tomcat.

As with any non-blocking implementation,its important that you never block thethread in your callback. Any APIs youcall must also be non-blocking (as anexample JDBC and JPA are blocking), oryou must call dispatch to run yourhandler in the worker pool

Page 76: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

Background: Undertow has two threadpools, a small I/O thread pool which pollsnon-ready connections for availabilityand executes non-blocking tasks againstthem. This pool is optimally sized to oneor two threads per execution unit on theCPU. In the case of an Intel CPU anexecution unit is a Hyperthread. Thisallows efficient handling for efficientscalability for tens of thousands ofconnections. It also has an additionalworker thread pool that is typically muchlarger, to handle any operation that isblocking.

This example shows how you dispatch to aworker pool so that you can performblocking actions. The example firstchecks that it is in an I/O thread anddispatches if so. This check is importantbecause any handler can move the restof the chain to a worker thread, and oncethat occurs its best to stay in the workerthread until no further action on theconnection/request can be taken, andthe connection moves back to the I/Othread.

Page 77: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)

More Resources

Download EAP 7 For Free http://www.jboss.org/products/eap/download/

Check out the documentation https://access.redhat.com/documentation/en/red-hat-jboss-enterprise-application-pla

tform/ Download Summit Slides for EAP7 Sessions!

Page 78: Boost Development With Java EE7 On EAP7 (Demitris Andreadis)