java ee7&avatar

Post on 08-May-2015

6.587 Views

Category:

Technology

1 Downloads

Preview:

Click to see full reader

TRANSCRIPT

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

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

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

Insert Picture Here

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

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

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

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

2005-2006 年Bill Shannon

Photo by Sakuraba san

J2EE からJava EE へ

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

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

かんたん開発の集大成

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

Now AvailableJava Platform, Enterprise Edition 7

The standard in community-driven enterprise software

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

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 をベースに進化

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

Java: 幅広い業界への適用

9,000,000JAVA 開発者

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

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

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

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

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

1ヶ月で数十万超え !!

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

GlassFish v4

NetBeans 7.3.1Java EE SDK

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

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

テクノロジー

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

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

Java EE 7 のテーマ

開発生産性

Java EE 7

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

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

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

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

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

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

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

Web

Socket

s

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

様々な HTML 5 対応

従来 アプリ

View

Model

HTTP/JS

View

Service

アプリHTTP/JS

JSON

View

次世代

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

アプリ

View

Model

HTTP/JS

JavaServer Faces 2.2

様々な HTML 5 対応

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

次世代

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

開発生産性の向上

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

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

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

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

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

Java EE 7

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

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

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

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

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

JMS の実装方法の改善

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

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

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

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

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

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

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

Project Avatar

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

Open SourcingProject Avatar

avatar.java.netDownload and try now!

Get involved!

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

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 のスケーラビリテイ・信頼性・運用保守性

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

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

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 プロバイダ

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

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)

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

Avatar アプリの作成

# avatar new [project-name]

Avatar のプロジェクトの作成

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

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

アプリサービス

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

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

html, xhtml, xml ファイル

Avatar 用JavaScript ファイル

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 ( サーバ ) の実装

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 のサーバ・サイドの実装コード

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( クライアント ) の実装

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

アプリサービス

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

Avatar のコンパイル

# avatar compile project-name Compiled: project-name

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

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

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

サーバ側の実行ファイル

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

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 にアプリケーションをデプロイ

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 サービスの  「複数ページの一括」  ダウンロード (※プラグインは不要)

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 サービスを利用

アプリサービス

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  のサービスも利用可能

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  等サーバリソースも  利用可能

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,   ローカルストレージ  等を利用可能

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

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

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

はじめての Project Avatarhttp://yoshio3.com/2013/10/10/beginning-of-project-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 とその将来

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

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

Java EE 7 の新機能

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

2. Batch アプリケーション

3. JSON 処理

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

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

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

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

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

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

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

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

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

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.)

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) { . . . }}

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 ?

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Concurrency Utilities for Java EE

Server-Managed Thread Pool Executor Component Relship

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

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

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

Concurrency Utilities for Java EE

ContextService

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

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

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

top related