java ee7&avatar

109
Yoshio Terada Java Evangelist http://yoshio3.com , Twitter : @yoshioterada 世世世世世世世 Java EE 7 世世世世世 Insert Picture Here

Upload: oracle-fusion-middleware

Post on 08-May-2015

6.587 views

Category:

Technology


1 download

TRANSCRIPT

Page 1: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.1

Yoshio TeradaJava Evangelisthttp://yoshio3.com, Twitter : @yoshioterada

世界が注目する Java EE 7 の最新動向

Insert Picture Here

Page 2: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.2

以下の事項は、弊社の一般的な製品の方向性に関する概要を説明するものです。また、情報提供を唯一の目的とするものであり、いかなる契約にも組み込むことはできません。以下の事項は、マテリアルやコード、機能を提供することをコミットメント(確約)するものではないため、購買決定を行う際の判断材料になさらないで下さい。オラクル製品に関して記載されている機能の開発、リリースおよび時期については、弊社の裁量により決定されます。

Oracle は、米国オラクルコーポレーション及びその子会社、関連会社の米国及びその他の国における登録商標です。文中の社名、商品名等は各社の商標または登録商標である場合があります。

Page 3: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.3

2005-2006 年Bill Shannon

Photo by Sakuraba san

J2EE からJava EE へ

Page 4: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.4

2009 年 12 月 10 日Java EE 6 リリース

かんたん開発の集大成

Page 5: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.5

Now AvailableJava Platform, Enterprise Edition 7

The standard in community-driven enterprise software

Page 6: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.6

Java EE の歴史

Java EE 7

2005-2012

かんたん開発

軽量化

開発生産性 & HTML5

32 sp

ecs

1998-2004

エンタープライズプラットフォーム

堅牢性

Web サービス J2EE

20 specs EE 5, EE 6

28 specs

2013 - Future

Page 7: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.7

Java EE 7 へ含まれる予定の JSR 一覧

Connector1.6

JPA 2.1 JTA 1.2 JMS 2.0

Managed Bean 1.0 EJB 3.2

Common Annotations

1.1

Interceptors 1.1

CDI 1.1

PortableExtensio

ns Servlet 3.1

JSP 2.2JSF 2.2

JAX-RS 2.0

EL 3.0

Bean

Valid

atio

n1

.1

Concurrency Utilities for

EE(JSR-236)

Batch Application(JSR-352)

Java API forJSON

(JSR-353)

Java API forWebSocket(JSR-356)

新規追加 大幅な更新 通常の更新

Java EE 7 は

Java EE 6 をベースに進化

Page 8: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.8

Java: 幅広い業界への適用

9,000,000JAVA 開発者

18 社による Java EE 準拠アプリケーション・サーバの提供

Page 9: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.9

「 HTML 5 、モバイル・アプリ開発の 究極のプラットフォーム」

ローンチ・イベントに世界から 1 万人超が参加

Page 10: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.10

1ヶ月で数十万超え !!

Java EE 7 関連ダウンロード数

GlassFish v4

NetBeans 7.3.1Java EE SDK

Page 11: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.11

Java EE 7 のどの機能に興味がありますか?ブログのアンケート結果より

テクノロジー

WebSocketバッチJAX-RSJSON-P並列処理

Page 12: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.12

Java EE 7 のテーマ

開発生産性

Java EE 7

HTML5 エンタープライズニーズへの対応

Page 13: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.13

Java EE 7

JSON 1.0

WebSocket 1.0

JAX-RS 2

JSF 2.2

Servlet 3.1

Expression Language 3.0

EJB 3.2

CDI 1.1

JTA 1.2

Interceptors 1.2

Bean Validation 1.1

Batch 1.0

Concurrency 1.0

JMS 2.0

JPA 2.1

各カテゴリに含まれる機能

Page 14: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.14

次世代の HTML 5 対応アプリケーション

次世代 HTML5 対応のアプリケーションの基盤

WebSockets : 低レイテンシ、レスポンスタイムの改善 JSON : シンプルなデータ・フォーマットで移植性の高いアプリケーション RESTful : 同期・非同期、スケーラブル、高パフォーマンス

Web

Socket

s

Page 15: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.15

様々な HTML 5 対応

従来 アプリ

View

Model

HTTP/JS

View

Service

アプリHTTP/JS

JSON

View

次世代

Page 16: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.16

アプリ

View

Model

HTTP/JS

JavaServer Faces 2.2

様々な HTML 5 対応

Page 17: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.17

WebSocket 1.0JSON 1.0JAX-RS 2.0

様々な HTML 5 対応

View

Service

アプリHTTP/JS

JSON

View

次世代

Page 18: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.18

開発生産性の向上

簡単なアプリケーション・アーキテクチャ

オールインワンの統合プラットフォーム

冗長的なコード記述の削減による効率化

アノテーション・ベース開発の拡大による効率化

アプリケーションの移植性の向上

Java EE 7

Page 19: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.19

開発生産性の向上

Java SE 7 対応try-with-resource への対応

冗長的なコード排除冗長的なインスタンス生成の抑制

完全整理されたプラットフォーム頻繁に利用される JAX-RS の Web Profile

対応

Java EE 7

JMSContext

Connection Session

Page 20: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.20

エンタープライズ・ニーズへの対応

バッチ処理 : OLTP のパフォーマンス改善

マルチスレッド並列タスク:スケーラビリティの改善

JMS の実装方法の改善

Page 21: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.21

エンタープライズ・ニーズへの対応

Java EE 環境における並列処理実装方法の提供

バッチ・アプリケーションに対する標準化ニーズへの対応

JMS における開発生産性の向上

Page 22: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.22

DOWNLOADJava EE 7 SDKoracle.com/javaee

GlassFish 4.0Full Platform or Web Profile

glassfish.org

Page 23: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.23

Project Avatar

Page 24: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.24

Open SourcingProject Avatar

avatar.java.netDownload and try now!

Get involved!

Page 25: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.25

Page 26: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.26

先進的な HTML 5 アプリ構築フレームワーク– WebSocket, Server-Sent Event, RESTful に対応

モジュール化対応 JavaScript フレームワーク 軽量なサーバ・アーキテクチャ (Thin-Server Architecture)

コンセプト

Project Avatar とは

Avatar のメリット– サーバ・サイド JavaScript と Java EE アプリの融合– Java VM 上で稼働する JavaScrip のスケーラビリテイ・信頼性・運用保守性

Page 27: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.27

Thin-Server アーキテクチャ (TSA)

今まで アプリ

View

Modelサーバ側でマー

HTTP/JS

TSAView

Service

アプリ

クライアント側でマージ

HTTP/JS

JSON

View

Model

Page 28: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.28

Avatar の概念  ( クライアント側 : View)

ブラウザ (JavaScript/DOM)

View (UI Node) Avatar(Controller)

HTML 5JavaScriptEL

• データ・    バインディング

• ナビゲーション• ローカル・   

ストレージ

アクセス方法を提供• ローカル• RESTful• SSE• WebSocket

Model

Page 29: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.29

Avatar の概念  ( サーバ側 : Service)

Nashorn (JavaVM で稼働する JavaScript エンジン )

Service Avatar

アクセス方法を提供• RESTful• SSE• WebSocket

ルーティングJSON のシリアライズ

利用可能なデータソース• ファイル• DB(JPA)• インメモリ• JMS

Data プロバイダ

Page 30: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.30

Avatar のアーキテクチャ

UI

Avatar アプリ(HTML 5/JS/CSS)

Avatar 実行環境

HTML 5 DOM

ローカルストレージ

Avatar アプリ(HTML5/JavaScript)

Avatar コンパイラ

Nashorn (JavaScript エンジン )

ブラウザ App サーバ

Java EE アプリ

View

アプリサービス

Java EEサービス

HTTP

HTTP ・SSE ・

WebSocket

HTTP/WebSocket

Page 31: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.31

Avatar のアーキテクチャ

UI

Avatar アプリ(HTML 5/JS/CSS)

Avatar 実行環境

HTML 5 DOM

ローカルストレージ

Avatar コンパイラ

Nashorn (JavaScript エンジン )

ブラウザ App サーバ

Java EE アプリ

Viewサービス

Dataサービス

Java EEサービス

HTTP

HTTP/WebSocket

HTTP/WebSocket

① Avatar アプリの作成

Avatar アプリ(HTML5/JavaScript)

Page 32: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.32

Avatar アプリの作成

# avatar new [project-name]

Avatar のプロジェクトの作成

※ デフォルトで  View のみ生成

Page 33: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.33

Avatar のアーキテクチャ

UI

Avatar アプリ(HTML 5/JS/CSS)

Avatar 実行環境

HTML 5 DOM

ローカルストレージ

Avatar アプリ( XML/JavaScript )

Avatar コンパイラ

Nashorn (JavaScript エンジン )

ブラウザ App サーバ

Java EE アプリJava EEサービス

HTTP

HTTP/WebSocket

HTTP/WebSocket

② View とサービスを実装

View

アプリサービス

Page 34: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.34

View( クライアント ) と Serivce( サーバ ) の実装ディレクトリ構成

html, xhtml, xml ファイル

Avatar 用JavaScript ファイル

Page 35: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.35

var avatar = require("org/glassfish/avatar");var message = 'The Server Time is ';var getTime = function(){ var current = new Date(); return{ msg: message, h: current.getHours(), m: current.getMinutes(), s: current.getSeconds() };};

… 続く Service ( サーバ ) の実装

Page 36: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.36

… 続き

avatar.registerPushService({ url:"data/time"},   function(){     this.$onOpen = this.$onTimeout = function(context){       context.$setTimeout(1000); // 1秒後に配信 return context.$sendMessage(getTime()); }; } );

Service ( サーバ ) の実装

Server-Sent Event のサーバ・サイドの実装コード

Page 37: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.37

<!DOCTYPE html><html><head>…</head> <body> <script data-model="push"> var Time = function(){ this.msg = this.h = this.m = this.s =''; }; </script> <script data-type="Time" data-instance="time" data-url="data/time"></script> <output class="time"> #{time.msg}#{time.h}:#{time.m}:#{time.s} </output></body></html>

View( クライアント ) の実装

Page 38: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.38

Avatar のアーキテクチャ

UI

Avatar アプリ(HTML 5/JS/CSS)

Avatar 実行環境

HTML 5 DOM

ローカルストレージ

Avatar アプリ( XML/JavaScript )

Avatar コンパイラ

Nashorn (JavaScript エンジン )

ブラウザ App サーバ

Java EE アプリJava EEサービス

HTTP

HTTP/WebSocket

HTTP/WebSocket

③ View とサービスを  コンパイル

View

アプリサービス

Page 39: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.39

Avatar のコンパイル

# avatar compile project-name Compiled: project-name

Avatar アプリケーションのコンパイル

Page 40: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.40

コンパイル後のディレクトリ構成

サーバ側の実行ファイル

クライアント側の実行ファイル

Page 41: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.41

Avatar アプリケーションのデプロイ

# asadmin deploy project-name Application deployed with name project-name. Command deploy executed successfully.

GlassFish にアプリケーションをデプロイ

Page 42: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.42

Avatar アプリケーションのダウンロード

UI

Avatar アプリ(HTML 5/JS/CSS)

Avatar 実行環境

HTML 5 DOM

ローカルストレージ

Avatar アプリ( XML/JavaScript )

Avatar コンパイラ

Nashorn (JavaScript エンジン )

ブラウザ App サーバ

Java EE アプリ

Viewサービス

Dataサービス

Java EEサービス

HTTP

HTTP/WebSocket

HTTP/WebSocket

④ View サービスの  「複数ページの一括」  ダウンロード (※プラグインは不要)

Page 43: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.43

Avatar サービスの呼び出し

UI

Avatar アプリ(HTML 5/JS/CSS)

Avatar 実行環境

HTML 5 DOM

ローカルストレージ

Avatar アプリ( XML/JavaScript )

Avatar コンパイラ

Nashorn (JavaScript エンジン )

ブラウザ App サーバ

Java EE アプリ

Viewサービス

Java EEサービス

HTTP

HTTP/WebSocket

HTTP/WebSocket

⑤ WebSocket/Server-Sent Event/ RESTful で Data サービスを利用

アプリサービス

Page 44: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.44

Java EE サービスの呼び出し

UI

Avatar アプリ(HTML 5/JS/CSS)

Avatar 実行環境

HTML 5 DOM

ローカルストレージ

Avatar アプリ( XML/JavaScript )

Avatar コンパイラ

Nashorn (JavaScript エンジン )

ブラウザ App サーバ

Java EE アプリ

Viewサービス

Dataサービス

Java EEサービス

HTTP

HTTP/WebSocket

HTTP/WebSocket

⑥ サーバ側は Java EE  のサービスも利用可能

Page 45: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.45

アプリケーション・サーバ側のリソースも利用可能

UI

Avatar アプリ(HTML 5/JS/CSS)

Avatar 実行環境

HTML 5 DOM

ローカルストレージ

Avatar アプリ( XML/JavaScript )

Avatar コンパイラ

   Nashorn (JavaScript エンジン )

ブラウザ App サーバ

Java EE アプリ

Viewサービス

アプリサービス

Java EEサービス

HTTP

HTTP/WebSocket

⑦ JPA, JMS, NoSQL  等サーバリソースも  利用可能

Page 46: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.46

Avatar のアーキテクチャ

UI

Avatar アプリ(HTML 5/JS/CSS)

Avatar 実行環境

HTML 5 DOM

ローカルストレージ

Avatar アプリ( XML/JavaScript )

Avatar コンパイラ

Nashorn (JavaScript エンジン )

ブラウザ App サーバ

Java EE アプリ

Viewサービス

Dataサービス

Java EEサービス

HTTP

HTTP/WebSocket

HTTP/WebSocket

⑧ クライアント側は   HTML 5, DOM,   ローカルストレージ  等を利用可能

Page 47: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.47

JDK 8 (b103 移行 )Avatar バンドル済 GlassFish v4

Page 48: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.48

はじめての Project Avatarhttp://yoshio3.com/2013/10/10/beginning-of-project-avatar/

手始めにここからはじめてみてください

Page 49: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.49

Java EE 7

StateManagement

PaaS

NoSQL

JSON-B

Modularity

HTML5++

Caching

Cloud

Java EE 8 とその将来

Page 50: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.50

Page 51: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.51

Java EE 7 の新機能

1. WebSocket クライアント・サーバ実装

2. Batch アプリケーション

3. JSON 処理

4. Java EE における並列処理

Page 52: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.52

Java API for WebSocket

API for WebSocket Client/Endpoints– Annotated (@ServerEndpoint, @ClientEndpoint)

– Programmatic (Endpoint) WebSocket opening handshake negotiation

Lifecycle methods Packaging and Deployment

Overview – JSR 356

Page 53: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.53

Java API for WebSocket

import javax.websocket.*;

@ServerEndpoint("/hello")public class HelloBean {

@OnMessage public String sayHello(String name) { return “Hello “ + name; }}

POJO/Annotation-driven

Page 54: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.54

Java API for WebSocketWebSocket Annotations

Annotation Level Purpose

@ServerEndpoint class Turns a POJO into a WebSocket Endpoint

@ClientEndpoint class Turns a POJO into a WebSocket Client

@OnMessage method Intercepts WebSocket Message events

@PathParam method parameter

Flags a matched path segment of a URI-template

@OnOpen method Intercepts WebSocket Open events

@OnClose method Intercepts WebSocket Close events

@OnError method Intercepts errors during a conversation

Page 55: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.55

Java API for WebSocket@ServerEndpoint Attributes

value Relative URI or URI templatee.g. “/hello” or “/chat/{subscriber-level}”

decoders list of message decoder classnames

encoders list of message encoder classnames

subprotocols list of the names of the supported subprotocols

Page 56: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.56

Java API for WebSocket

@ServerEndpoint( value="/hello", encoders={MyMessage.class}, decoders={MyMessage.class})public class MyEndpoint { . . .}

Custom Payloads

Page 57: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.57

Java API for WebSocket 1.0

public class MyMessage implements Decoder.Text<MyMessage>, Encoder.Text<MyMessage> { private JsonObject jsonObject;

public MyMessage decode(String s) { jsonObject = new JsonReader(new StringReader(s)).readObject(); return this;

}

public boolean willDecode(String string) { return true; // Only if can process the payload }

public String encode(MyMessage myMessage) { return myMessage.jsonObject.toString(); }}

Custom Payloads – Text

Page 58: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.58

Java API for WebSocket 1.0

public class MyMessage implements Decoder.Binary<MyMessage>, Encoder.Binary<MyMessage> {

public MyMessage decode(byte[] bytes) { . . . return this;

}

public boolean willDecode(byte[] bytes) { . . . return true; // Only if can process the payload }

public byte[] encode(MyMessage myMessage) { . . . }}

Custom Payloads – Binary

Page 59: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.59

Java API for WebSocket 1.0

@ServerEndpoint("/chat”)public class ChatBean {

static Set<Session> peers = Collections.synchronizedSet(…);

@OnOpen public void onOpen(Session peer) { peers.add(peer); }

@OnClose public void onClose(Session peer) { peers.remove(peer); }

. . .

Canonical Chat Example

Page 60: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.60

Java API for WebSocket 1.0

. . .

@OnMessage

public void message(String message, Session client) {

for (Session peer : peers) { peer.getBasicRemote().sendObject(message); } }}

Chat (contd.)

Page 61: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.61

Java API for WebSocket 1.0

Level 1 only

URI Template Matching

@ServerEndpoint(“/orders/{order-id}”)public class MyEndpoint { @OnMessage public void processOrder( @PathParam(“order-id”)String orderId) { . . . }}

Page 62: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.62

Java API for WebSocket

Exactly one of the following– Text: String, Java primitive or equivalent class, String and boolean, Reader, any type for which there is a decoder

– Binary: byte[], ByteBuffer, byte[] and boolean, ByteBuffer and boolean, InptuStream, any type for which there is a decoder

– Pong messages: PongMessage

An optional Session parameter 0..n String parameters annotated with @PathParam Return type: String, byte[], ByteBuffer, Java primitive or class

equivalent or any type for which there is a encoder

Which methods can be @OnMessage ?

Page 63: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.63

Java API for WebSocket

void m(String s); void m(Float f, @PathParam(“id”)int id); Product m(Reader reader, Session s); void m(byte[] b); or void m(ByteBuffer b); Book m(int i, Session s, @PathParam(“isbn”)String isbn, @PathParam(“store”)String store);

Sample Messages

Page 64: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.64

Java API for WebSocket

@ClientEndpointpublic class HelloClient { @OnMessage public void message(String message, Session session) { // process message from server }}

WebSocketContainer c = ContainerProvider.getWebSocketContainer();c.connectToServer(HelloClient.class, “hello”);

WebSocket Client

Page 65: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.65

Java API for WebSocket

public class MyEndpoint extends Endpoint {

@Override public void onOpen(Session session) { session.addMessageHandler(new MessageHandler.Text() { public void onMessage(String name) { try { session.getBasicRemote().sendText(“Hello “ + name); } catch (IOException ex) { } } }); }}

Interface-driven Endpoint

Page 66: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.66

Java API for WebSocket

ServerEndpointConfiguration config = ServerEndpointConfigurationBuilder .create(MyEndpoint.class, “/foo”) .build();

Interface-driven Endpoint Server Packaging

Page 67: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.67

Java API for WebSocket

Server– URI matching algorithm

– Subprotocol and extension negotiation

– Message encoders and decoders

– Origin check

– Handshake response

Client– Requested subprotocols and extensions

– Message encoders and decoders

– Request URI

Server and Client Configuration

Page 68: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.68

Java API for WebSocket

Authenticates using Servlet security mechanism during opening handshake

– Endpoint mapped by ws:// is protected using security model defined using the corresponding http:// URI

Authorization defined using <security-constraint>– TBD: Add/reuse security annotations

Transport Confidentiality using wss://– Access allowed over encrypted connection only

Security

Page 69: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.69

Batch Applications 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

Overview – JSR 352

Page 70: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.70

Batch Applications 1.0

Job: Entire batch process– Put together through a Job Specification Language (XML)

Step: Independent, sequential phase of a job– ItemReader: Retrieval of input for a step, one at a time

– ItemProcessor: Business processing of an item

– ItemWriter: Output of an item, chunks of items at a time

JobOperator: Manage batch processing JobRepository: Metadata for jobs

Concepts

Page 71: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.71

Batch Applications 1.0

JobInstance: Logical Job Run JobExecution: Single attempt to run a job StepExecution: Single attempt to run a step

Concepts

Page 72: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.72

Batch Applications 1.0

Chunked: Item-oriented processing (Recommended)– Using a reader-processor-writer pattern

– Configurable check-pointing and transactions

– E.g. sending monthly bank statements

Batchlet: Task-oriented processing– Roll-your-own batch pattern

– Invoke once, runs to completion, and exits

– E.g., file transfer

Types of Step

Page 73: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.73

Batch Applications 1.0

Primary processing style– Read and Process one item

– Do the above ‘n’ times (called ‘commit interval’)

– Write the ‘n’ processed items

– Commit the transaction

Page 74: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.74

Batch Applications 1.0

Specifies a job, steps and directs their execution Implemented in XML

– Referred as “Job XML”

Supports inheritance of job, step, flow, and split

Job Specification Language

Page 75: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.75

Batch Applications 1.0

<job id=“myJob”> <step id=“init”> <chunk …/> <next on=“initialized” to=“process”/> <fail on=“initError”/> </step> <step id=“process”> <batchlet …/> <end on=”success”/> <fail on=”*” exit-status=“FAILURE”/> </step></job>

Job Specification Language – Simple Job

Page 76: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.76

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

Batch Applications 1.0Chunked Job Specification

Page 77: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.77

<step id=”transferFile”> <batchlet ref=“MyFileTransfer” /></step>

…implements Batchlet {@Overridepublic void process() { // Transfer file}

Batch Applications 1.0Job Specification Language – Batchlet

Page 78: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.78

Batch Applications 1.0Listeners – Intercept Batch Execution

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

Page 79: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.79

Batch Applications 1.0

Steps can be run in parallel Parallelization models

– Partitioned Multiple instances across multiple threads Each thread runs the same step, unique parameters identify data E.g., process accounts from 1-100, 101-200, etc.

– Concurrent Steps defined by a split run concurrently across multiple threads One step per thread

Job Parallelization

Page 80: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.80

Java API for JSON Processing 1.0

API to parse and generate JSON Streaming API

– Low-level, efficient way to parse/generate JSON

– Provides pluggability for parsers/generators

Object Model– Simple, easy-to-use high-level API

– Implemented on top of Streaming API

Binding JSON to Java objects forthcoming

Overview – JSR 353

Page 81: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.81

Java API for JSON Processing 1.0

Parses JSON in a streaming way from input sources– Similar to StaX’s XMLStreamReader, a pull parser

Created using– Json.createParser(…)

– Json.createParserFactory().createParser(…)

Parser state events– START_ARRAY, END_ARRAY, START_OBJECT, END_OBJECT, …

Streaming API

Page 82: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.82

{

"firstName": "John", "lastName": "Smith", "age": 25,

"phoneNumber": [

{ "type": "home", "number": "212 555-1234" },

{ "type": "fax", "number": "646 555-4567" }

]

}

Java API for JSON ProcessingStreaming Parser

Page 83: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.83

START_OBJECT

Java API for JSON Processing

{

"firstName": "John", "lastName": "Smith", "age": 25,

"phoneNumber": [

{ "type": "home", "number": "212 555-1234" },

{ "type": "fax", "number": "646 555-4567" }

]

}

Streaming Parser

Page 84: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.84

KEY_NAME

Java API for JSON Processing

{

"firstName": "John", "lastName": "Smith", "age": 25,

"phoneNumber": [

{ "type": "home", "number": "212 555-1234" },

{ "type": "fax", "number": "646 555-4567" }

]

}

Streaming Parser

Page 85: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.85

VALUE_STRING

Java API for JSON Processing

{

"firstName": "John", "lastName": "Smith", "age": 25,

"phoneNumber": [

{ "type": "home", "number": "212 555-1234" },

{ "type": "fax", "number": "646 555-4567" }

]

}

Streaming API

Page 86: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.86

VALUE_NUMBER

Java API for JSON Processing

{

"firstName": "John", "lastName": "Smith", "age": 25,

"phoneNumber": [

{ "type": "home", "number": "212 555-1234" },

{ "type": "fax", "number": "646 555-4567" }

]

}

Streaming API

Page 87: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.87

START_ARRAY

Java API for JSON Processing

{

"firstName": "John", "lastName": "Smith", "age": 25,

"phoneNumber": [

{ "type": "home", "number": "212 555-1234" },

{ "type": "fax", "number": "646 555-4567" }

]

}

Streaming API

Page 88: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.88

END_ARRAY

Java API for JSON Processing 1.0

{

"firstName": "John", "lastName": "Smith", "age": 25,

"phoneNumber": [

{ "type": "home", "number": "212 555-1234" },

{ "type": "fax", "number": "646 555-4567" }

]

}

Streaming API

Page 89: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.89

Java API for JSON Processing 1.0

{ "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”

Streaming API

Page 90: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.90

Java API for JSON Processing 1.0

JsonGenerator– Generates JSON in a streaming way to output sources

Similar to StaX’s XMLStreamWriter

– Created using Json.createGenerator(…) Json.createGeneratorFactory().createGenerator(…)

– Optionally, configured with features E.g. for pretty printing

Streaming API

Page 91: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.91

"phoneNumber": [ { "type": "home", "number": ”408-123-4567” }, { "type": ”work", "number": ”408-987-6543” } ]

JsonGenerator jg = Json.createGenerator(…);

jg. .beginArray("phoneNumber") .beginObject() .add("type", "home") .add("number", "408-123-4567") .endObject() .beginObject() .add("type", ”work") .add("number", "408-987-6543") .endObject() .endArray();jg.close();

Java API for JSON ProcessingStreaming API

Page 92: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.92

Java API for JSON Processing 1.0

JsonObject/JsonArray – JSON object and array structures– JsonString and JsonNumber for string and number values

JsonBuilder – Builds JsonObject and JsonArray JsonReader – Reads JsonObject and JsonArray from input source JsonWriter – Writes JsonObject and JsonArray to output source

Object Model API

Page 93: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.93

// Reads a JSON object

try(JsonReader reader = Json.createReader(io)) {

JsonObject obj = reader.readObject();

}

Java API for JSON Processing

Reads JsonObject and JsonArray from input source– i/o Reader, InputStream (+ encoding)

Optionally, configured with features Uses pluggable JsonParser

Object API

Page 94: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.94

// Writes a JSON object

try(JsonWriter writer = Json.createWriter(io)) {

writer.writeObject(obj);

}

Java API for JSON Processing

Writes JsonObject and JsonArray to output source– i/o Writer, OutputStream (+ encoding)

Optionally, configured with features. For e.g. pretty printing Uses pluggable JsonGenerator

Object API

Page 95: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.95

// Writes a JSON object prettily

JsonConfiguration config = new JsonConfiguration().withPrettyPrinting();

try(JsonWriter writer = Json.createWriter(io, config)) {writer.writeObject(obj);

}

Java API for JSON Processing

Configuration is a set of parser/generator features– Pretty Printing, Single-Quoted strings

Supports extensibility (custom features) Can be used in streaming & object-model API

Configuration

Page 96: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.96

Concurrency Utilities for Java EE

Provide concurrency capabilities to Java EE application components – Without compromising container integrity

Support simple (common) and advanced concurrency patterns Provide consistency between Java SE and Java EE concurrency

programming model– Extend the Concurrency Utilities API (JSR 166y)

java.util.concurrent package Largely by providing a managed version of java.util.concurrent.ExecutorService

Overview – JSR 236

Page 97: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.97

Concurrency Utilities for Java EE

Managed version of java.util.concurrent.ExecutorService– Lookup using JNDI

Java EE components create task classes– Implement java.lang.Runnable or java.util.concurrent.Callable

Submitted using submit or invoke methods Multiple (configurable) executors are permitted

ManagedExecutorService

Page 98: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.98

Concurrency Utilities for Java EE

Recommended to bind in java:comp/env/concurrent subcontext

<resource-env-ref> <resource-env-ref-name> concurrent/BatchExecutor </resource-env-ref-name> <resource-env-ref-type> javax.enterprise.concurrent.ManagedExecutorService </resource-env-ref-type></resource-env-ref>

Defining ManagedExecutorService using JNDI

Page 99: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.99

Concurrency Utilities for Java EE

public class TestServlet extends HTTPServlet { @Resource(name=“concurrent/BatchExecutor”) ManagedExecutorService executor;

Future future = executor.submit(new MyTask());

class MyTask implements Runnable { public void run() { . . . // task logic } }}

Submit Tasks to ManagedExecutorService using JNDI

Page 100: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.100

Concurrency Utilities for Java EE

class MyTask implements Callable<Long> { public Long call() { . . .}}

class MyTask2 implements Callable<Account> {}

ArrayList<Callable> tasks = new ArrayList<>();tasks.add(new MyTask());tasks.add(new MyTask2());List<Future<Object>> res = executor.invokeAll(tasks);

Submitting multiple tasks

Page 101: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.101

Concurrency Utilities for Java EE

ThreadFactory: Reference to ManagedThreadFactory Thread Use: Short vs long-running tasks, pooled vs daemon Hung Task Threshold: Time before task is considered hung PoolInfo

– Core Size: Minimum number of threads

– Maximum Size: Maximum number of threads (unbounded)

– Keep Alive: TTL for idle threads if > core size

– Work Queue Capacity: Inbound buffer size (unbounded)

ManagedExecutorService Configuration

Page 102: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.102

Concurrency Utilities for Java EE

Reject Policy: Policy if a task is rejected by executor – Abort: Throw an exception when rejected

– Retry and Abort: Automatically submit to another instance and abort if it fails

Run Location: Distributable or Local Contextual Callback: Boolean indicating whether container context

propagated to threads or not

ManagedExecutorService Configuration

Page 103: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.103

Concurrency Utilities for Java EE

Server-Managed Thread Pool Executor Component Relship

Page 104: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.104

Concurrency Utilities for Java EE

Adds delay and periodic task running capabilities provided to ManagedExecutorService

Accessible via javax.enterprise.concurrent.ManagedScheduledExecutorService JNDI reference

Tasks submitted using submit, invokeXXX or scheduleXXX methods

ManagedScheduledExecutorService

Page 105: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.105

Concurrency Utilities for Java EE

public class TestServlet extends HTTPServlet { @Resource(name=“concurrent/LoggerExecutor”) ManagedScheduledExecutorService executor;

Future future = executor.schedule( new MyTask(), 5, TimeUnit.SECONDS);

ManagedScheduledExecutorService Sample

Page 106: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.106

Concurrency Utilities for Java EE

ContextService

Page 107: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.107

Concurrency Utilities for Java EE

Provides a method for creating threads for execution in a managed environment

Lookup using JNDI <resource-env-ref> <resource-env-ref-name> concurrent/LoggerThreadFactory </resource-env-ref-name> <resource-env-ref-type> javax.enterprise.concurrent.ManagedThreadFactory </resource-env-ref-type> </resource-env-ref>

ManagedThreadFactory

Page 108: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.108

Concurrency Utilities for Java EE 1.0

@Resource(“concurrent/LoggerThreadFactory”)ManagedThreadFactory threadFactory;

LoggerTask task = new LoggerTask();Thread thread = threadFactory.newThread(task);

LoggerTask implements Runnable { public void run() { . . . }}

ManagedThreadFactory Sample

Page 109: Java EE7&Avatar

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.109