java ee 7 45 features

90
【14-D-6】 45 new features of Java EE 7 in 45 minutes Twitterハッシュ: #devsumiD 日本オラクル株式会社 Yoshio Terada

Upload: oracle-fusion-middleware

Post on 08-Sep-2014

25 views

Category:

Technology


5 download

DESCRIPTION

This presentation explain the 45 features of Java EE 7.

TRANSCRIPT

Page 1: Java EE 7 45 features

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

【14-D-6】 45 new features of Java EE 7 in 45 minutes          Twitterハッシュ: #devsumiD

日本オラクル株式会社 Yoshio Terada

Page 2: Java EE 7 45 features

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

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

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

Page 3: Java EE 7 45 features

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

Java EE 7

JSP/JSTL

WebSocket 1.0 JAX-RS 2.0

JSON-P 1.0

JSF 2.2

EL 3.0 Servlet 3.1

EJB 3.2

JPA 2.1

JTA 1.2

JMS 2.0

JCA 1.7

Batch 1.0 JavaMail 1.5

CD

I 1.1

Bea

n Va

lidat

ion

1.1

Inte

rcep

tors

1.2

Con

curr

ency

1.0

Java EE 7 へ含まれる機能一覧

Page 4: Java EE 7 45 features

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

Java EE 7

JSP/JSTL

WebSocket 1.0 JAX-RS 2.0

JSON-P 1.0

JSF 2.2

EL 3.0 Servlet 3.1

EJB 3.2

JPA 2.1

JTA 1.2

JMS 2.0

JCA 1.7

Batch 1.0 JavaMail 1.5

CD

I 1.1

Bea

n Va

lidat

ion

1.1

Inte

rcep

tors

1.2

Con

curr

ency

1.0

WebSocket 1.0 (JSR-356)

Page 5: Java EE 7 45 features

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

#1: WebSocket: アノテーションによるサーバ実装 @javax.websocket.server.ServerEndpoint("/chat") public class ChatServer { @OnMessage public String chat(String name, Session session) { for (Session peer : session.getOpenSessions()) {" peer.getBasicRemote().sendObject(message);" } } }"

双方向・全二重の通信を簡単に実現

Page 6: Java EE 7 45 features

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

#2: WebSocket: ライフサイクルのコールバック @javax.websocket.OnOpen public void open(Session s) { . . . } @javax.websocket.OnClose public void close(CloseReason c) { . . . } @javax.websocket.OnError public void error(Throwable t) { . . . }"

接続、切断、エラー処理

Page 7: Java EE 7 45 features

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

#3 : WebSocket: クライアント実装

@javax.websocket.ClientEndpoint public class MyClient { @javax.websocket.OnOpen public void open(Session session) { … } // Lifecycle callbacks }"

クライアント・エンドポイントも アノテーションで実装可能

Page 8: Java EE 7 45 features

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

#3 : WebSocket: クライアント実装 ContainerProvider .getWebSocketContainer() .connectToServer( MyClient.class, URI.create("ws://localhost:8080/ws/hello"));"

サーバ・エンドポイントへの接続コード

Page 9: Java EE 7 45 features

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

#4: WebSocket: エンコーダ・デコーダ @javax.websocket.server.ServerEndpoint( value="/chat", decoders="MyDecoder.class", encoders="MyEncoder.class") public class ChatServer { @OnMessage public String chat(ChatMessage name, Session session) { . . . } }"

オブジェクトとしてメッセージの送受信

Page 10: Java EE 7 45 features

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

#4: WebSocket: エンコーダ public class MyEncoder implements "

Encoder.Text<ChatMessage> { public String encode(ChatMessage chatMessage) { // . . . }"

  // . . .  }"

Javaオブジェクトから送信用データを生成

Page 11: Java EE 7 45 features

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

#4: WebSocket: デコーダ public class MyDecoder implements Decoder.Text<ChatMessage> { public ChatMessage decode(String s) { // . . . } public boolean willDecode(String string) { // . . . } //. . . } "受信データを Java オブジェクトに変換

Page 12: Java EE 7 45 features

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

Java EE 7

JSP/JSTL

WebSocket 1.0 JAX-RS 2.0

JSON-P 1.0

JSF 2.2

EL 3.0 Servlet 3.1

EJB 3.2

JPA 2.1

JTA 1.2

JMS 2.0

JCA 1.7

Batch 1.0 JavaMail 1.5

CD

I 1.1

Bea

n Va

lidat

ion

1.1

Inte

rcep

tors

1.2

Con

curr

ency

1.0

JAX-RS 2.0 (JSR-339)

Page 13: Java EE 7 45 features

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

#5: JAX-RS: クライアント用の API Client client = ClientBuilder.newClient();"WebTarget target = client.target("http://www.foo.com/book");"Invocation invocation = target.request(TEXT_PLAIN).get();"Response response = invocation.invoke();""Response response = ClientBuilder.newClient()" .target("http://www.foo.com/book")" .request(MediaType.TEXT_PLAIN)" .get();""String body = ClientBuilder.newClient()" .target("http://www.foo.com/book")" .request()" .get(String.class);"

Page 14: Java EE 7 45 features

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

#6: JAX-RS: 非同期クライアント Future <String> future = ClientBuilder.newClient()" .target("http://localhost:8080/JAX-RS-Client/hello/")" .request()" .async()" .get(String.class);"try {" String body = future.get(10, TimeUnit.SECONDS);" System.out.println("Server Response " + body);"} catch (InterruptedException | ExecutionException | " TimeoutException e) {" logger.log(Level.SEVERE, "Exception occured", e);"}"

Page 15: Java EE 7 45 features

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

#7: JAX-RS: 非同期サーバ @Path("/async")"public class AsyncResource {" @GET" public void asyncGet(@Suspended final AsyncResponse " asyncResp) {" mgdExecService.submit(() -> {" String result = longRunningOperation();" asyncResp.resume(Response.ok(result, "text/plain")" .build());" });" }"

非同期処理:サスペンド&レジューム

Page 16: Java EE 7 45 features

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

#8: JAX-RS: メッセージ・フィルタ § クライアント実装用のフィルタ

–  ClientRequestFilter"–  ClientResponseFilter"

§ サーバ実装用のフィルタ –  ContainerRequestFilter"–  ContainerResponseFilter"

リクエスト・レスポンスの ヘッダ用 のインターセプタ(フィルタ)を提供

Page 17: Java EE 7 45 features

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

#8: JAX-RS: メッセージ・フィルタ public class LocalCacheFilter implements ClientRequestFilter {" @Override" public void filter(ClientRequestContext req) throws " IOException{" if (req.getMethod().equals("GET")) {" CacheEntry entry = cache.getEntry(req.getURI());" if (entry != null) {" req.getHeaders().putSingle("If-Modified-Since", " entry.getLastModified());" }" }}}"

リクエスト・レスポンスの ヘッダ用 のインターセプタ(フィルタ)を提供

Page 18: Java EE 7 45 features

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

#9: JAX-RS: エンティティ・インターセプタ

§  Intercepts inbound entity streams (read from the “wire”) –  ReaderInterceptor"

§  Intercepts outbound entity streams (written to the “wire”) –  WriterInterceptor"

メッセージ・ボディ用 のインターセプタを提供

Page 19: Java EE 7 45 features

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

#10: JAX-RS: エンティティ・インターセプタ public class GZIPWriteInterceptor implements WriterInterceptor{" @Override" public void around WriteTo(WriteInterceptorContext ctx) " throws IOException, WebApplicationException{" GZIPOutputStream os = new " GZIPOutputStream(ctx.getOutputStream());" ctx.getHeader().putSingle("Content-Encoding", "gzip");" ctx.setOutputStream(os);" ctx.proceed();" }"}"

メッセージ・ボディ用 のインターセプタを提供

Page 20: Java EE 7 45 features

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

Java EE 7

JSP/JSTL

WebSocket 1.0 JAX-RS 2.0

JSON-P 1.0

JSF 2.2

EL 3.0 Servlet 3.1

EJB 3.2

JPA 2.1

JTA 1.2

JMS 2.0

JCA 1.7

Batch 1.0 JavaMail 1.5

CD

I 1.1

Bea

n Va

lidat

ion

1.1

Inte

rcep

tors

1.2

Con

curr

ency

1.0

JSF 2.2 (JSR-344)

Page 21: Java EE 7 45 features

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

#11: JSF: HTML5対応 & パス・スルー属性 <html xmlns="http://www.w3.org/1999/xhtml”"" >" <body >" <form >" <input type="url" " value=" "/>" <input type="submit" value="実行"" />" </form>" </body>"</html>"

" xmlns:jsf="http://xmlns.jcp.org/jsf“" xmlns:p="http://xmlns.jcp.org/jsf/passthrough"" jsf:id="body"" jsf:id="form"" jsf:id="url“ " p:type="url“ "#{html5.url}"" jsf:id="button" " jsf:action="#{html5.pushButton}""""

HTMLコードはそのまま

Page 22: Java EE 7 45 features

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

#12: JSF: Facesフロー(関連画面のモジュール化)

画面、画面遷移、バックエンド処理 をモジュール化

<h:body>" <h:form>"<h:commandButton id="start1" " value="フロー1の開始" action="flow1"/>" <h:commandButton id="start2" " value="フロー2の開始" action="flow2"/>" </h:form>"</h:body>

Page 23: Java EE 7 45 features

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

#13: JSF: Faces フロー・スコープ @Named(value=“flow1”) @FlowScoped("flow1") public class Flow1Bean implements Serializable {"

private String name;"

//… セッタ・ゲッタ メソッドは省略 }"

EL 式におけるフロー・スコープの利用"

#{flow1.name}"

#{flowScope.value} #{facesContext.application.flowHandler.currentFlow}"

"同一フロー中だけ有効な値の参照・取得

Page 24: Java EE 7 45 features

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

#14: JSF: リソース・ライブラリの契約

柔軟なデザイン変更が可能

Page 25: Java EE 7 45 features

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

#14: JSF:リソース・ライブラリ契約の適用 <f:view " xmlns:f="http://xmlns.jcp.org/jsf/core" " contracts=“corporate1">" <ui:composition xmlns:ui="http://java.sun.com/jsf/facelets"" template="/template.xhtml">" <ui:define name="content">" 企業1用のコンテンツ&デザイン" </ui:define>" </ui:composition>"</f:view>

テンプレート・クライアントは契約名を記述

Page 26: Java EE 7 45 features

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

#14: JSF:リソース・ライブラリ契約の適用 <f:view " xmlns:f="http://xmlns.jcp.org/jsf/core" " contracts=“ ">" <ui:composition xmlns:ui="http://java.sun.com/jsf/facelets"" template="/template.xhtml">" <ui:define name="content">" 企業2用のコンテンツ&デザイン" </ui:define>" </ui:composition>"</f:view>

テンプレート・クライアントは契約名を記述

Page 27: Java EE 7 45 features

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

#15: JSF: ファイル・アップロード <h:form enctype="multipart/form-data"> <h:inputFile value="#{fileUploadBean.file}"/><br/> <h:commandButton value="Upload"/><p/> </h:form> "

@Named @RequestScoped public class FileUploadBean { private Part file; //getter and setter } "

Servlet 3.0 API を利用

ファイル・アップロード用JSFコンポーネント

Page 28: Java EE 7 45 features

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

Java EE 7

JSP/JSTL

WebSocket 1.0 JAX-RS 2.0

JSON-P 1.0

JSF 2.2

EL 3.0 Servlet 3.1

EJB 3.2

JPA 2.1

JTA 1.2

JMS 2.0

JCA 1.7

Batch 1.0 JavaMail 1.5

CD

I 1.1

Bea

n Va

lidat

ion

1.1

Inte

rcep

tors

1.2

Con

curr

ency

1.0

JSON-P 1.0 (JSR-353)

Page 29: Java EE 7 45 features

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

JsonObject value = Json.createObjectBuilder()" .add("id", "1234")" .add("date", "19/09/2012")" .add("total_amount", "93.48")" .add("customer", Json.createObjectBuilder()" .add("first_name", "James")" .add("last_name", "Rorrison")" .add("email", "[email protected]")" .add("phoneNumber", "+44 1234 1234")" )" .build();"

JSON オブジェクトの生成

Page 30: Java EE 7 45 features

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

JsonParser parser = Json.createParser(new " FileReader(“order.json"));"while (parser.hasNext()) {" JsonParser.Event event = parser.next();" if (event.equals(JsonParser.Event.KEY_NAME) && " parser.getString().matches("email")) {" parser.next();" email = parser.getString();" }}"

JSON オブジェクトの解析

Page 31: Java EE 7 45 features

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

Java EE 7

JSP/JSTL

WebSocket 1.0 JAX-RS 2.0

JSON-P 1.0

JSF 2.2

EL 3.0 Servlet 3.1

EJB 3.2

JPA 2.1

JTA 1.2

JMS 2.0

JCA 1.7

Batch 1.0 JavaMail 1.5

CD

I 1.1

Bea

n Va

lidat

ion

1.1

Inte

rcep

tors

1.2

Con

curr

ency

1.0

Expression Language 3.0 (JSR-341)

Page 32: Java EE 7 45 features

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

<h:dataTable id="tabledata" "  value=”#{afilter = indexManagedBean.ageFileter ;" indexManagedBean.data.stream()." filter(p-> p.age >= afilter)." toList()}" var="person" border="1">" <h:column>" <f:facet name="header">" <h:outputText value="名前"/> " </f:facet>" <h:outputText value="#{person.name}"/>" </h:column>

EL 式内で Lambda 式を記述可能

Page 33: Java EE 7 45 features

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

Java EE 7

JSP/JSTL

WebSocket 1.0 JAX-RS 2.0

JSON-P 1.0

JSF 2.2

EL 3.0 Servlet 3.1

EJB 3.2

JPA 2.1

JTA 1.2

JMS 2.0

JCA 1.7

Batch 1.0 JavaMail 1.5

CD

I 1.1

Bea

n Va

lidat

ion

1.1

Inte

rcep

tors

1.2

Con

curr

ency

1.0

Servlet 3.1 (JSR-340)

Page 34: Java EE 7 45 features

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

#19: Servlet: ノンブロッキング I/O

§ ServletInputStream"–  public void setReadListener(ReadListener listener);"–  public boolean isFinished();"

–  public boolean isReady();"

§ ServletOutputStream"–  public setWriteListener(WriteListener listener);"

–  public boolean isReady();"

NIO 用に新規追加されたメソッド

Page 35: Java EE 7 45 features

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

#19: Servlet: ノンブロッキング I/O public interface ReadListener extends EventListener { public void onDataAvailable(); pubic void onAllDataRead(); public void onError(); }"

public interface WriteListener extends EventListener { public void onWritePossible(); public void onError(); }"

NIO 用に新規追加されたインタフェース

Page 36: Java EE 7 45 features

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

#19: Servlet: ノンブロッキング I/O @WebServlet(name="MyNIOServlet”,urlPatterns = "

{"/MyNIOServlet"}, asyncSupported = true)"

public class MyNIOServlet extends HttpServlet {"

protected void doGet(HttpServletRequest req, "

HttpServletResponse res){"

AsyncContext aCon = request.startAsync(req,res);"

ServletOutputStream out = res.getOutputStream();"

WriteListener wListener = new AsyncWriter(aCon,out);"

outStream.setWriteListener(wListener);"

Async Servlet の場合のみ NIO で実装可能

Page 37: Java EE 7 45 features

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

#19: Servlet: ノンブロッキング I/O public class AsyncWriter implements WriteListener {"

private LinkedBlockingQueue<String> queue = "

new LinkedBlockingQueue<>();"

public void onWritePossible() throws IOException {"

while (queue.peek() != null && outStream.isReady()) {"

String data = queue.poll();"

outStream.print(data);"

}"

if (queue.peek() == null)"

aContext.complete();"

}}"isReadyで書き込み可能な場合処理を実施

Page 38: Java EE 7 45 features

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

#20: Servlet: セキュリティの改善 HttpServletRequest request = … ;"

String oldId = request.getSession().getId();"

 //ログイン前の古いセッション ID :c59804c31c03b080db243c004e63"

request.login("user", "password");"

String newId = request.changeSessionId();"

//ログイン後の新しいセッション ID:c59f21f227d0855718446db3d61c"

Fixation Attack からの防御 ログイン後セッションID を変更しハイジャック防御

Page 39: Java EE 7 45 features

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

#20: Servlet: セキュリティの改善 <web-app . . . version="3.1"> <deny-uncovered-http-methods/> <web-resource-collection> <url-pattern>/account/*</url-pattern> <http-method>GET</http-method> </web-resource-collection> </web-app> "

"<deny-uncovered-http-methods> の追加 <http-method>で指定されていないメソッドは全て接続拒否 例:GET 以外は拒否

Page 40: Java EE 7 45 features

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

Java EE 7

JSP/JSTL

WebSocket 1.0 JAX-RS 2.0

JSON-P 1.0

JSF 2.2

EL 3.0 Servlet 3.1

EJB 3.2

JPA 2.1

JTA 1.2

JMS 2.0

JCA 1.7

Batch 1.0 JavaMail 1.5

CD

I 1.1

Bea

n Va

lidat

ion

1.1

Inte

rcep

tors

1.2

Con

curr

ency

1.0

CDI 1.1 (JSR-346)

Page 41: Java EE 7 45 features

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

<beans ... version="1.1" bean-discovery-mode="all">" <alternatives>" <class>org.agoncal.book.MockGenerator</class>" </alternatives>"</beans>"

•  all, annotated, none を指定可能 •  all は Java EE 6 と同様の振る舞い

Page 42: Java EE 7 45 features

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

@Vetoed"

public class NonProcessedBean { ..."

}"

package-info.java @Vetoed"

package com.non.processed.package;"

all 指定時インジェクション対象から除外 クラス、パッケージ単位で指定可能

Page 43: Java EE 7 45 features

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

Java EE 7

JSP/JSTL

WebSocket 1.0 JAX-RS 2.0

JSON-P 1.0

JSF 2.2

EL 3.0 Servlet 3.1

EJB 3.2

JPA 2.1

JTA 1.2

JMS 2.0

JCA 1.7

Batch 1.0 JavaMail 1.5

CD

I 1.1

Bea

n Va

lidat

ion

1.1

Inte

rcep

tors

1.2

Con

curr

ency

1.0

Bean Validation 1.1 (JSR-349)

Page 44: Java EE 7 45 features

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

#23: Bean Validation: メソッド・バリデーション public class CardValidator {" public CardValidator(@NotNull Algorithm algorithm) {" this.algorithm = algorithm;" }"" @AssertTrue" public Boolean validate(@NotNull CreditCard creditCard) {" return algorithm.validate(creditCard.getNumber());" }" }"

メソッド引数、メソッドの返り値に対する バリデーションも可能

Page 45: Java EE 7 45 features

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

Java EE 7

JSP/JSTL

WebSocket 1.0 JAX-RS 2.0

JSON-P 1.0

JSF 2.2

EL 3.0 Servlet 3.1

EJB 3.2

JPA 2.1

JTA 1.2

JMS 2.0

JCA 1.7

Batch 1.0 JavaMail 1.5

CD

I 1.1

Bea

n Va

lidat

ion

1.1

Inte

rcep

tors

1.2

Con

curr

ency

1.0

Interceptor 1.2 (JSR-318)

Page 46: Java EE 7 45 features

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

public class LoggingInterceptor {"" @AroundConstruct" private void init(InvocationContext ic) throws Exception{" logger.fine("Entering constructor");" ic.proceed();" logger.fine("Exiting constructor");" }"" @AroundInvoke" public Object logMethod(InvocationContext ic) ... {" // ..." }}"

コンストラクタに対するインターセプタが可能

Page 47: Java EE 7 45 features

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

@Interceptor"@Loggable"@Priority(Interceptor.Priority.LIBRARY_BEFORE + 10)"public class LoggingInterceptor {" @AroundInvoke" ..."}"

複数インターセプタの実行時の優先順位を指定 小さな値が優先 "

PLATFORM_BEFORE (0) > LIBRARY_BEFORE (1000) > APPLICATION (2000) > LIBRARY_AFTER (3000) > PLATFORM_AFTER (4000)"

Page 48: Java EE 7 45 features

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

Java EE 7

JSP/JSTL

WebSocket 1.0 JAX-RS 2.0

JSON-P 1.0

JSF 2.2

EL 3.0 Servlet 3.1

EJB 3.2

JPA 2.1

JTA 1.2

JMS 2.0

JCA 1.7

Batch 1.0 JavaMail 1.5

CD

I 1.1

Bea

n Va

lidat

ion

1.1

Inte

rcep

tors

1.2

Con

curr

ency

1.0

Concurrency 1.0 (JSR-236)

Page 49: Java EE 7 45 features

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

§ Java EE 環境で新規スレッドの生成が可能 § 並列処理用のデザインパターンを適用可能 § Java SE(JSR-166y) の並列処理パッケージを拡張

Page 50: Java EE 7 45 features

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

@Resource"ManagedExecutorService exec;"" public void foo(){" exec.submit(() -> {doSomething();});" }"

Java SE 8 + Java EE 7 環境で Lambda 式を使用した並列処理の実装

Page 51: Java EE 7 45 features

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

@Resource ManagedScheduledExecutorService mgdScheduledExec;

public void bar() { mgdScheduledExec.schedule( () -> {doSomething();}, 30, TimeUnit. MINUTES ); }"

スケジューリング可能な並列処理の実装

Page 52: Java EE 7 45 features

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

mgdScheduledExec.scheduleAtFixedRate ( () -> {doSomething();}, 2, 3, TimeUnit.SECONDS);"

2秒後に有効、3秒毎にタスクを実行 (定期的実行) mgdScheduledExec.scheduleWithFixedDelay ( () -> {doSomething();}, 2, 3, TimeUnit.SECONDS);"

2秒後に有効、前タスク完了3秒毎に新タスクを実行 (タスク実行間隔の調整が可能)

Page 53: Java EE 7 45 features

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

Thread thread = factory.newThread(() ->{doSomething();});"

thread.start();

@Resource ManagedThreadFactory factory; public void foo(){" ExecutorService exec = Executors.newFixedThreadPool(4, factory); " execSvs.submit(() -> {doSomething();});" }""

Page 54: Java EE 7 45 features

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

@Resource ContextService service; Runnable proxy = service.createContextualProxy"

(new MyRunnable(), Runnable.class); Future f = executor.submit(proxy);"

タスクにコンテキスト情報 (ClassLoader、JNDI、Security、Transaction) を付加して実行

Page 55: Java EE 7 45 features

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

Java EE 7

JSP/JSTL

WebSocket 1.0 JAX-RS 2.0

JSON-P 1.0

JSF 2.2

EL 3.0 Servlet 3.1

EJB 3.2

JPA 2.1

JTA 1.2

JMS 2.0

JCA 1.7

Batch 1.0 JavaMail 1.5

CD

I 1.1

Bea

n Va

lidat

ion

1.1

Inte

rcep

tors

1.2

Con

curr

ency

1.0

EJB 3.2 (JSR-345)

Page 56: Java EE 7 45 features

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

@Stateful(passivationCapable = false)"public class ShoppingCart {" ..."}"

Java EE 6 まで Stateful セッションBean は一定時間を経過後、 2次ストレージに退避し無効化 (passivate) が行われた。 再利用時に有効化(activate) が必要だった。 大量に存在する場合リソースに悪影響があった。 Java EE 7 では passivate の機能自身を無効化可能

Page 57: Java EE 7 45 features

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

@Stateless"public class OrderEJB {" @Asynchronous" public void sendEmail (Order order) {" // Very Long task" }" @Schedule(hour="2", persistent=false)" public void createDailyReport() {" // ..." }"}"

※ persistence が false の場合のみ有効

Web プロファイル版で利用可能

Page 58: Java EE 7 45 features

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

Java EE 7

JSP/JSTL

WebSocket 1.0 JAX-RS 2.0

JSON-P 1.0

JSF 2.2

EL 3.0 Servlet 3.1

EJB 3.2

JPA 2.1

JTA 1.2

JMS 2.0

JCA 1.7

Batch 1.0 JavaMail 1.5

CD

I 1.1

Bea

n Va

lidat

ion

1.1

Inte

rcep

tors

1.2

Con

curr

ency

1.0

JTA 1.2 (JSR-907)

Page 59: Java EE 7 45 features

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

@Path("book")"@Transactional(value = Transactional.TxType.REQUIRED," rollbackOn = {SQLException.class, JMSException.class}," dontRollbackOn = SQLWarning.class)"public class BookRestService {"" @PersistenceContext" private EntityManager em;"" @POST" @Consumes(MediaType.APPLICATION_XML)" public Response createBook(Book book) {...}"}"

EJB 以外でもコンテナ管理のトランザクションを利用可能

Page 60: Java EE 7 45 features

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

@TransactionScoped"public class BookBean {...}"@WebServlet"public class TxServlet extends HttpServlet {" @Inject UserTransaction tx;" @Inject BookBean b1;" @Inject BookBean b2;" protected void processRequest(...) {" tx.begin();" s_out.println(b1.getReference());" s_out.println(b2.getReference());" tx.commit();" }}"

トランザクション内でのみ有効なスコープ

Page 61: Java EE 7 45 features

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

Java EE 7

JSP/JSTL

WebSocket 1.0 JAX-RS 2.0

JSON-P 1.0

JSF 2.2

EL 3.0 Servlet 3.1

EJB 3.2

JPA 2.1

JTA 1.2

JMS 2.0

JCA 1.7

Batch 1.0 JavaMail 1.5

CD

I 1.1

Bea

n Va

lidat

ion

1.1

Inte

rcep

tors

1.2

Con

curr

ency

1.0

JPA 2.1 (JSR-338)

Page 62: Java EE 7 45 features

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

<persistence ... version="2.1">" <persistence-unit ...>" <properties>" <property name=”" javax.persistence.schema-generation.scripts.action"" value="drop-and-create"/>" <property name=”" javax.persistence.schema-generation.scripts.create-target" " value="create.sql"/>" <property name=”" javax.persistence.sql-load-script-source" " value="insert.sql"/>" </properties>"</persistence-unit>"

Page 63: Java EE 7 45 features

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

@Entity"@Table(indexes = {" @Index(columnList = "ISBN")," @Index(columnList = "NBOFPAGE")"})"public class Book {" @Id @GeneratedValue" private Long id;" private String isbn;" private Integer nbOfPage;" ..."}"

任意のカラムのインデックス化が可能

Page 64: Java EE 7 45 features

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

@PersistenceContext(synchronization =" SynchronizationType.UNSYNCHRONIZED)"private EntityManager em;"...""em.persist(book);""..."em.joinTransaction();"

明示的なトランザクションへのジョインまで非同期

Page 65: Java EE 7 45 features

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

@Entity"@NamedStoredProcedureQuery(" name = "archiveOldBooks", " procedureName = "sp_archive_books”," parameters = {" @StoredProcedureParameter(name = ”date", mode = IN, " type = Date.class)," @StoredProcedureParameter(name = "warehouse"," mode = IN, " type = String.class)" })"public class Book {...}"

待望のストアード・プロシージャの標準化

Page 66: Java EE 7 45 features

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

Java EE 7

JSP/JSTL

WebSocket 1.0 JAX-RS 2.0

JSON-P 1.0

JSF 2.2

EL 3.0 Servlet 3.1

EJB 3.2

JPA 2.1

JTA 1.2

JMS 2.0

JCA 1.7

Batch 1.0 JavaMail 1.5

CD

I 1.1

Bea

n Va

lidat

ion

1.1

Inte

rcep

tors

1.2

Con

curr

ency

1.0

JMS 2.0 (JSR-343)

Page 67: Java EE 7 45 features

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

JMSContext ctx = connectionFactory.createContext()""ctx.createProducer().send(queue, "Text message sent");""ctx.createConsumer(queue).receiveBody(String.class);""ctx.createProducer()" .setPriority(2)" .setTimeToLive(1000)" .setDeliveryMode(DeliveryMode.NON_PERSISTENT)" .send(queue, message);"

送受信用の新規簡易APIの提供:JMSContext

Page 68: Java EE 7 45 features

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

try(JMSContext ctx = connectionFactory.createContext()){" ctx.createProducer().send(queue, "Text message sent");"  ...""  while (true) {" String s = ctx.createConsumer(queue)"                 .receiveBody(String.class);" }"}"

finaly 節での close() の実装は不要

Page 69: Java EE 7 45 features

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

@JMSConnectionFactoryDefinition(" name="java:comp/jms/MyConnectionFactory"," interfaceName = "javax.jms.TopicConnectionFactory"," maxPoolSize = 30," minPoolSize= 20)"@JMSDestinationDefinition(" name = "java:comp/jms/MyTopic"," destinationName = "mytopic"," interfaceName = "javax.jms.Topic")"

Java EE 6 で DBリソース設定のために @DataSourceDefinition が存在

Page 70: Java EE 7 45 features

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

Java EE 7

JSP/JSTL

WebSocket 1.0 JAX-RS 2.0

JSON-P 1.0

JSF 2.2

EL 3.0 Servlet 3.1

EJB 3.2

JPA 2.1

JTA 1.2

JMS 2.0

JCA 1.7

Batch 1.0 JavaMail 1.5

CD

I 1.1

Bea

n Va

lidat

ion

1.1

Inte

rcep

tors

1.2

Con

curr

ency

1.0

Batch (JSR-352)

Page 71: Java EE 7 45 features

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

Page 72: Java EE 7 45 features

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

@Stateless"public class MyBatchTimer {" @Schedule(minute = "0,10,20,30,40,50", " second = "0", dayOfMonth = "*", month = "*", " year = "*", hour = "9-17", " dayOfWeek = "Mon-Fri", persistent = false)" public void executeBatchLikeCron() {" JobOperator job = " BatchRuntime.getJobOperator();" long id = job.start("my-batch-job", " new Properties());}}

処理の詳細は XMLに記述

Page 73: Java EE 7 45 features

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

<job id="my-batch-job”"  xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="1.0">"  <step id=”first-step" next=”next-step">"    ……"  </step>"  <step id="next-step">"    ……"  </step>"</job>"

Page 74: Java EE 7 45 features

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

Page 75: Java EE 7 45 features

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

<job id="my-batch-job”"  xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="1.0">" <step id=”first-step" next=”next-step">" <chunk>" <reader ref="MyItemReader”/>" <processor ref="MyItemProcessor”/>" <writer ref="MyItemWriter”/>" </chunk>" </step>"</job>"

Page 76: Java EE 7 45 features

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

import javax.batch.api.chunk.ItemReader ; @Named public class MyItemReader implements ItemReader { public void open(Serializable checkpoint) throws Exception {} public void close() throws Exception {} public Object readItem() throws Exception {} public Serializable checkpointInfo() throws Exception { } } もしくは public class MyItemReader extends AbstractItemReader も可

<reader" ref="MyItemReader”/>

Page 77: Java EE 7 45 features

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

import javax.batch.api.chunk.ItemProcessor ; @Named public class MyItemProcessor implements ItemProcessor { public Object processItem(Object item) throws Exception { } }

<processor " ref="MyItemProcessor”/>

Page 78: Java EE 7 45 features

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

import javax.batch.api.chunk.ItemWriter; @Named public class MyItemWriter implements ItemWriter{ public void open(Serializable checkpoint) throws Exception { } public void close() throws Exception { } public void writeItems(List<Object> items) throws Exception { } public Serializable checkpointInfo() throws Exception { } } もしくは public class MyItemWriter extends AbstractItemWriter も可

<writer" ref="MyItemWriter”/>

Page 79: Java EE 7 45 features

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

<step id=”transferFile”>" <batchlet ref=“MyBatchlet” />"</step>"@Named"

public class MyBatchlet implements Batchlet{" @Override" public String process() throws Exception {" //一括処理(ファイル転送、)" }" @Override" public void stop() throws Exception {" }"}"

Page 80: Java EE 7 45 features

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

<job id="myJob" xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="1.0”> <listeners> <listener ref="myJobListener"/> </listeners> <step id="myStep" > <listeners> <listener ref="myItemReadListener"/> <listener ref="myItemProcessorListener"/> <listener ref="myItemWriteListener"/> </listeners> <chunk item-count="3”>. . .</chunk> </step> </job>"

"

Page 81: Java EE 7 45 features

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

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 82: Java EE 7 45 features

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

@Named public class MyJobListener extends AbstractJobListener { @Override public void beforeJob() throws Exception { . . . } @Override public void afterJob() throws Exception { . . . } }"

Page 83: Java EE 7 45 features

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

<flow id="flow1" next="step3"> <step id="step1" next="step2"> . . . </step> <step id="step2"> . . . </step> </flow> <step id="step3"> . . . </step>"

flow : 複数のステップを束ね単一ユニットを生成 (ステップのグループ化)

Page 84: Java EE 7 45 features

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

<split id="split1" next=" . . . "> <flow id="flow1”> <step id="step1”> . . . </step> </flow> <flow id="flow2”> <step id="step2”> . . . </step> </flow> </split>"

split : flow の並列実行

Page 85: Java EE 7 45 features

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

<step id="step1" next="decider1">. . .</step> <decision id="decider1" ref="myDecider"> <next on="DATA_LOADED" to="step2"/> <end on="NOT_LOADED"/> </decision> <step id="step2">. . .</step> "

"@Named public class MyDecider implements Decider { @Override public String decide(StepExecution[] ses) throws Exception{ . . . return "DATA_LOADED"; // or "NOT_LOADED"" }}"

decision : step, split, flow の条件分岐のカスタマイズ

Page 86: Java EE 7 45 features

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

Java EE 7

JSP/JSTL

WebSocket 1.0 JAX-RS 2.0

JSON-P 1.0

JSF 2.2

EL 3.0 Servlet 3.1

EJB 3.2

JPA 2.1

JTA 1.2

JMS 2.0

JCA 1.7

Batch 1.0 JavaMail 1.5

CD

I 1.1

Bea

n Va

lidat

ion

1.1

Inte

rcep

tors

1.2

Con

curr

ency

1.0

Java EE 7 共通

Page 87: Java EE 7 45 features

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

#45: デフォルト・データソース  JDBCリソース

@Resource(lookup="java:comp/DefaultDataSource") DataSource myDataSource;"@Resource DataSource myDataSource; "

Appサーバでデフォルト・リソースが設定済 デフォルトを使用する場合リソース設定を省略可能

Page 88: Java EE 7 45 features

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

#45: デフォルト・データソース  JMS 接続ファクトリ

@Resource ConnectionFactory myConnectionFactory;"

デフォルトを使用する場合リソース設定を省略可能

Page 89: Java EE 7 45 features

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

#45: デフォルト・データソース  並列処理リソース

@Resource ManagedExecutorService execService; "

開発時: デフォルト・リソースを使用し設定を統一

Page 90: Java EE 7 45 features

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

DOWNLOAD Java EE 7 SDK oracle.com/javaee

GlassFish 4.0 Full Platform or Web Profile glassfish.org