Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Java EE 7 45 features

19,403 views

Published on

This presentation explain the 45 features of Java EE 7.

Published in: Technology

Java EE 7 45 features

  1. 1. 【14-D-6】 45 new features of Java EE 7 in 45 minutes 日本オラクル株式会社 Yoshio Terada     1      Twitterハッシュ: #devsumiD Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  2. 2. 以下の事項は、弊社の一般的な製品の方向性に関する概要を説明するもの です。また、情報提供を唯一の目的とするものであり、いかなる契約にも 組み込むことはできません。以下の事項は、マテリアルやコード、機能を 提供することをコミットメント(確約)するものではないため、購買決定 を行う際の判断材料になさらないで下さい。オラクル製品に関して記載さ れている機能の開発、リリースおよび時期については、弊社の裁量により 決定されます。 Oracleは、米国オラクルコーポレーション及びその子会社、関連会社の米国及びその他の国における登録商 標です。文中の社名、商品名等は各社の商標または登録商標である場合があります。 2 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  3. 3. Java EE 7 へ含まれる機能一覧 JPA 2.1 JMS 2.0 JCA 1.7 Batch 1.0 JavaMail 1.5 Java EE 7 3 Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Concurrency 1.0 Servlet 3.1 JTA 1.2 EJB 3.2 EL 3.0 Interceptors 1.2 JSON-P 1.0 Bean Validation 1.1 JSP/JSTL JSF 2.2 CDI 1.1 JAX-RS 2.0 WebSocket 1.0
  4. 4. WebSocket 1.0 (JSR-356) JPA 2.1 JMS 2.0 JCA 1.7 Batch 1.0 JavaMail 1.5 Java EE 7 4 Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Concurrency 1.0 Servlet 3.1 JTA 1.2 EJB 3.2 EL 3.0 Interceptors 1.2 JSON-P 1.0 Bean Validation 1.1 JSP/JSTL JSF 2.2 CDI 1.1 JAX-RS 2.0 WebSocket 1.0
  5. 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);" }
 }
 }" 双方向・全二重の通信を簡単に実現 5 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  6. 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) { . . . }" 接続、切断、エラー処理 6 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  7. 7. #3 : WebSocket: クライアント実装 @javax.websocket.ClientEndpoint
 public class MyClient {
 @javax.websocket.OnOpen
 public void open(Session session) { … }
 
 // Lifecycle callbacks
 }" クライアント・エンドポイントも アノテーションで実装可能 7 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  8. 8. #3 : WebSocket: クライアント実装 ContainerProvider
 .getWebSocketContainer()
 .connectToServer(
 MyClient.class, 
 URI.create("ws://localhost:8080/ws/hello"));" サーバ・エンドポイントへの接続コード 8 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  9. 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) {
 . . . 
 }
 }" オブジェクトとしてメッセージの送受信 9 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  10. 10. #4: WebSocket: エンコーダ public class MyEncoder implements " Encoder.Text<ChatMessage> {
 
 public String encode(ChatMessage chatMessage) {
 // . . .
 }"   // . . . 
 }" Javaオブジェクトから送信用データを生成 10 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  11. 11. #4: WebSocket: デコーダ public class MyDecoder implements Decoder.Text<ChatMessage> {
 public ChatMessage decode(String s) {
 // . . .
 }
 public boolean willDecode(String string) {
 // . . .
 }
 //. . .
 }
 
 " 受信データを Java オブジェクトに変換 11 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  12. 12. JAX-RS 2.0 (JSR-339) JPA 2.1 JMS 2.0 JCA 1.7 Batch 1.0 JavaMail 1.5 Java EE 7 12 Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Concurrency 1.0 Servlet 3.1 JTA 1.2 EJB 3.2 EL 3.0 Interceptors 1.2 JSON-P 1.0 Bean Validation 1.1 JSP/JSTL JSF 2.2 CDI 1.1 JAX-RS 2.0 WebSocket 1.0
  13. 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);" 13 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  14. 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);" }" 14 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  15. 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());" });" }" 非同期処理:サスペンド&レジューム 15 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  16. 16. #8: JAX-RS: メッセージ・フィルタ §  クライアント実装用のフィルタ –  ClientRequestFilter" –  ClientResponseFilter" §  サーバ実装用のフィルタ –  ContainerRequestFilter" –  ContainerResponseFilter" リクエスト・レスポンスの ヘッダ用 のインターセプタ(フィルタ)を提供 16 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  17. 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());" }" }}}" リクエスト・レスポンスの ヘッダ用 のインターセプタ(フィルタ)を提供 17 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  18. 18. #9: JAX-RS: エンティティ・インターセプタ §  Intercepts inbound entity streams (read from the “wire”) –  ReaderInterceptor" §  Intercepts outbound entity streams (written to the “wire”) –  WriterInterceptor" メッセージ・ボディ用 のインターセプタを提供 18 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  19. 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();" }" }" メッセージ・ボディ用 のインターセプタを提供 19 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  20. 20. JSF 2.2 (JSR-344) JPA 2.1 JMS 2.0 JCA 1.7 Batch 1.0 JavaMail 1.5 Java EE 7 20 Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Concurrency 1.0 Servlet 3.1 JTA 1.2 EJB 3.2 EL 3.0 Interceptors 1.2 JSON-P 1.0 Bean Validation 1.1 JSP/JSTL JSF 2.2 CDI 1.1 JAX-RS 2.0 WebSocket 1.0
  21. 21. #11: JSF: HTML5対応 & パス・スルー属性 <html xmlns="http://www.w3.org/1999/xhtml”" " " xmlns:jsf="http://xmlns.jcp.org/jsf“" >" xmlns:p="http://xmlns.jcp.org/jsf/passthrough"" <body jsf:id="body"" >" <form jsf:id="form"" >" <input type="url" jsf:id="url“ " " "/>" p:type="url“ value=" "#{html5.url}"" <input type="submit" value="実行"" jsf:id="button" " />" jsf:action="#{html5.pushButton}"" " </form>" " </body>" </html>" HTMLコードはそのまま 21 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  22. 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> 画面、画面遷移、バックエンド処理 をモジュール化 22 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  23. 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}" " 同一フロー中だけ有効な値の参照・取得 23 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  24. 24. #14: JSF: リソース・ライブラリの契約 柔軟なデザイン変更が可能 24 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  25. 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> テンプレート・クライアントは契約名を記述 25 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  26. 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> テンプレート・クライアントは契約名を記述 26 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  27. 27. #15: JSF: ファイル・アップロード <h:form enctype="multipart/form-data">
 <h:inputFile value="#{fileUploadBean.file}"/><br/>
 <h:commandButton value="Upload"/><p/>
 </h:form> " ファイル・アップロード用JSFコンポーネント @Named @RequestScoped 
 public class FileUploadBean {
 private Part file;
 //getter and setter
 } " Servlet 3.0 API を利用 27 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  28. 28. JSON-P 1.0 (JSR-353) JPA 2.1 JMS 2.0 JCA 1.7 Batch 1.0 JavaMail 1.5 Java EE 7 28 Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Concurrency 1.0 Servlet 3.1 JTA 1.2 EJB 3.2 EL 3.0 Interceptors 1.2 JSON-P 1.0 Bean Validation 1.1 JSP/JSTL JSF 2.2 CDI 1.1 JAX-RS 2.0 WebSocket 1.0
  29. 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", "j.rorri@me.com")" .add("phoneNumber", "+44 1234 1234")" )" .build();" JSON オブジェクトの生成 29 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  30. 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 オブジェクトの解析 30 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  31. 31. Expression Language 3.0 (JSR-341) JPA 2.1 JMS 2.0 JCA 1.7 Batch 1.0 JavaMail 1.5 Java EE 7 31 Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Concurrency 1.0 Servlet 3.1 JTA 1.2 EJB 3.2 EL 3.0 Interceptors 1.2 JSON-P 1.0 Bean Validation 1.1 JSP/JSTL JSF 2.2 CDI 1.1 JAX-RS 2.0 WebSocket 1.0
  32. 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 式を記述可能 32 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  33. 33. Servlet 3.1 (JSR-340) JPA 2.1 JMS 2.0 JCA 1.7 Batch 1.0 JavaMail 1.5 Java EE 7 33 Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Concurrency 1.0 Servlet 3.1 JTA 1.2 EJB 3.2 EL 3.0 Interceptors 1.2 JSON-P 1.0 Bean Validation 1.1 JSP/JSTL JSF 2.2 CDI 1.1 JAX-RS 2.0 WebSocket 1.0
  34. 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 用に新規追加されたメソッド 34 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  35. 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 用に新規追加されたインタフェース 35 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  36. 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 で実装可能 36 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  37. 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で書き込み可能な場合処理を実施 37 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  38. 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 を変更しハイジャック防御 38 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  39. 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 以外は拒否 39 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  40. 40. CDI 1.1 (JSR-346) JPA 2.1 JMS 2.0 JCA 1.7 Batch 1.0 JavaMail 1.5 Java EE 7 40 Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Concurrency 1.0 Servlet 3.1 JTA 1.2 EJB 3.2 EL 3.0 Interceptors 1.2 JSON-P 1.0 Bean Validation 1.1 JSP/JSTL JSF 2.2 CDI 1.1 JAX-RS 2.0 WebSocket 1.0
  41. 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 と同様の振る舞い 41 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  42. 42. @Vetoed" public class NonProcessedBean {
 ..." }" package-info.java @Vetoed" package com.non.processed.package;" all 指定時インジェクション対象から除外 クラス、パッケージ単位で指定可能 42 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  43. 43. Bean Validation 1.1 (JSR-349) JPA 2.1 JMS 2.0 JCA 1.7 Batch 1.0 JavaMail 1.5 Java EE 7 43 Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Concurrency 1.0 Servlet 3.1 JTA 1.2 EJB 3.2 EL 3.0 Interceptors 1.2 JSON-P 1.0 Bean Validation 1.1 JSP/JSTL JSF 2.2 CDI 1.1 JAX-RS 2.0 WebSocket 1.0
  44. 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());" }" }" メソッド引数、メソッドの返り値に対する バリデーションも可能 44 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  45. 45. Interceptor 1.2 (JSR-318) JPA 2.1 JMS 2.0 JCA 1.7 Batch 1.0 JavaMail 1.5 Java EE 7 45 Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Concurrency 1.0 Servlet 3.1 JTA 1.2 EJB 3.2 EL 3.0 Interceptors 1.2 JSON-P 1.0 Bean Validation 1.1 JSP/JSTL JSF 2.2 CDI 1.1 JAX-RS 2.0 WebSocket 1.0
  46. 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) ... {" // ..." }}" コンストラクタに対するインターセプタが可能 46 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  47. 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)" 47 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  48. 48. Concurrency 1.0 (JSR-236) JPA 2.1 JMS 2.0 JCA 1.7 Batch 1.0 JavaMail 1.5 Java EE 7 48 Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Concurrency 1.0 Servlet 3.1 JTA 1.2 EJB 3.2 EL 3.0 Interceptors 1.2 JSON-P 1.0 Bean Validation 1.1 JSP/JSTL JSF 2.2 CDI 1.1 JAX-RS 2.0 WebSocket 1.0
  49. 49. §  Java EE 環境で新規スレッドの生成が可能 §  並列処理用のデザインパターンを適用可能 §  Java SE(JSR-166y) の並列処理パッケージを拡張 49 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  50. 50. @Resource" ManagedExecutorService exec;" " public void foo(){" exec.submit(() -> {doSomething();});" }" Java SE 8 + Java EE 7 環境で Lambda 式を使用した並列処理の実装 50 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  51. 51. @Resource ManagedScheduledExecutorService mgdScheduledExec; public void bar() { mgdScheduledExec.schedule( () -> {doSomething();}, 30, TimeUnit. MINUTES ); }" スケジューリング可能な並列処理の実装 51 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  52. 52. mgdScheduledExec.scheduleAtFixedRate ( () -> {doSomething();}, 2, 3, TimeUnit.SECONDS);" 2秒後に有効、3秒毎にタスクを実行 (定期的実行) mgdScheduledExec.scheduleWithFixedDelay ( () -> {doSomething();}, 2, 3, TimeUnit.SECONDS);" 2秒後に有効、前タスク完了3秒毎に新タスクを実行 (タスク実行間隔の調整が可能) 52 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  53. 53. @Resource ManagedThreadFactory factory; public void foo(){" ExecutorService exec = Executors.newFixedThreadPool(4, factory); " execSvs.submit(() -> {doSomething();});" }" " Thread thread = factory.newThread(() ->{doSomething();});" thread.start(); 53 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  54. 54. @Resource
 ContextService service;
 
 Runnable proxy = service.createContextualProxy" (new MyRunnable(), Runnable.class);
 
 Future f = executor.submit(proxy);" タスクにコンテキスト情報 (ClassLoader、JNDI、 Security、Transaction) を付加して実行 54 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  55. 55. EJB 3.2 (JSR-345) JPA 2.1 JMS 2.0 JCA 1.7 Batch 1.0 JavaMail 1.5 Java EE 7 55 Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Concurrency 1.0 Servlet 3.1 JTA 1.2 EJB 3.2 EL 3.0 Interceptors 1.2 JSON-P 1.0 Bean Validation 1.1 JSP/JSTL JSF 2.2 CDI 1.1 JAX-RS 2.0 WebSocket 1.0
  56. 56. @Stateful(passivationCapable = false)" public class ShoppingCart {" ..." }" Java EE 6 まで Stateful セッションBean は一定時間を経過後、 2次ストレージに退避し無効化 (passivate) が行われた。 再利用時に有効化(activate) が必要だった。 大量に存在する場合リソースに悪影響があった。 Java EE 7 では passivate の機能自身を無効化可能 56 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  57. 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 プロファイル版で利用可能 57 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  58. 58. JTA 1.2 (JSR-907) JPA 2.1 JMS 2.0 JCA 1.7 Batch 1.0 JavaMail 1.5 Java EE 7 58 Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Concurrency 1.0 Servlet 3.1 JTA 1.2 EJB 3.2 EL 3.0 Interceptors 1.2 JSON-P 1.0 Bean Validation 1.1 JSP/JSTL JSF 2.2 CDI 1.1 JAX-RS 2.0 WebSocket 1.0
  59. 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 以外でもコンテナ管理のトランザクションを利用可能 59 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  60. 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();" }}" トランザクション内でのみ有効なスコープ 60 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  61. 61. JPA 2.1 (JSR-338) JPA 2.1 JMS 2.0 JCA 1.7 Batch 1.0 JavaMail 1.5 Java EE 7 61 Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Concurrency 1.0 Servlet 3.1 JTA 1.2 EJB 3.2 EL 3.0 Interceptors 1.2 JSON-P 1.0 Bean Validation 1.1 JSP/JSTL JSF 2.2 CDI 1.1 JAX-RS 2.0 WebSocket 1.0
  62. 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>" 62 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  63. 63. @Entity" @Table(indexes = {" @Index(columnList = "ISBN")," @Index(columnList = "NBOFPAGE")" })" public class Book {" @Id @GeneratedValue" private Long id;" private String isbn;" private Integer nbOfPage;" ..." }" 任意のカラムのインデックス化が可能 63 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  64. 64. @PersistenceContext(synchronization =" SynchronizationType.UNSYNCHRONIZED)" private EntityManager em;" ..." " em.persist(book);" " ..." em.joinTransaction();" 明示的なトランザクションへのジョインまで非同期 64 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  65. 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 {...}" 待望のストアード・プロシージャの標準化 65 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  66. 66. JMS 2.0 (JSR-343) JPA 2.1 JMS 2.0 JCA 1.7 Batch 1.0 JavaMail 1.5 Java EE 7 66 Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Concurrency 1.0 Servlet 3.1 JTA 1.2 EJB 3.2 EL 3.0 Interceptors 1.2 JSON-P 1.0 Bean Validation 1.1 JSP/JSTL JSF 2.2 CDI 1.1 JAX-RS 2.0 WebSocket 1.0
  67. 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 67 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  68. 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() の実装は不要 68 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  69. 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 が存在 69 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  70. 70. Batch (JSR-352) JPA 2.1 JMS 2.0 JCA 1.7 Batch 1.0 JavaMail 1.5 Java EE 7 70 Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Concurrency 1.0 Servlet 3.1 JTA 1.2 EJB 3.2 EL 3.0 Interceptors 1.2 JSON-P 1.0 Bean Validation 1.1 JSP/JSTL JSF 2.2 CDI 1.1 JAX-RS 2.0 WebSocket 1.0
  71. 71. 71 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  72. 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に記述 72 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  73. 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>" 73 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  74. 74. 74 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  75. 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>" 75 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  76. 76. import javax.batch.api.chunk.ItemReader ; <reader" ref="MyItemReader”/> @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 も可 76 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  77. 77. import javax.batch.api.chunk.ItemProcessor ; <processor " ref="MyItemProcessor”/> @Named public class MyItemProcessor implements ItemProcessor { public Object processItem(Object item) throws Exception { } } 77 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  78. 78. import javax.batch.api.chunk.ItemWriter; <writer" ref="MyItemWriter”/> @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 も可 78 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  79. 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 {" }" }" 79 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  80. 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>" " 80 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  81. 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" 81 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  82. 82. @Named
 public class MyJobListener extends AbstractJobListener {
 
 @Override
 public void beforeJob() throws Exception { . . . }
 
 @Override
 public void afterJob() throws Exception { . . . }
 }" 82 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  83. 83. <flow id="flow1" next="step3">
 <step id="step1" next="step2"> . . . </step>
 <step id="step2"> . . . </step>
 </flow>
 <step id="step3"> . . . </step>" flow : 複数のステップを束ね単一ユニットを生成 (ステップのグループ化) 83 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  84. 84. <split id="split1" next=" . . . ">
 <flow id="flow1”>
 <step id="step1”> . . . </step>
 </flow>
 <flow id="flow2”>
 <step id="step2”> . . . </step>
 </flow>
 </split>" split : flow の並列実行 84 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  85. 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 の条件分岐のカスタマイズ 85 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  86. 86. Java EE 7 共通 JPA 2.1 JMS 2.0 JCA 1.7 Batch 1.0 JavaMail 1.5 Java EE 7 86 Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Concurrency 1.0 Servlet 3.1 JTA 1.2 EJB 3.2 EL 3.0 Interceptors 1.2 JSON-P 1.0 Bean Validation 1.1 JSP/JSTL JSF 2.2 CDI 1.1 JAX-RS 2.0 WebSocket 1.0
  87. 87. #45: デフォルト・データソース  JDBCリソース @Resource(lookup="java:comp/DefaultDataSource")
 @Resource
 myDataSource;" DataSource myDataSource; " Appサーバでデフォルト・リソースが設定済 デフォルトを使用する場合リソース設定を省略可能 87 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  88. 88. #45: デフォルト・データソース  JMS 接続ファクトリ @Resource
 ConnectionFactory myConnectionFactory;" デフォルトを使用する場合リソース設定を省略可能 88 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  89. 89. #45: デフォルト・データソース  並列処理リソース 開発時: デフォルト・リソース を使用し設定を統一 @Resource
 ManagedExecutorService execService; " 89 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  90. 90. DOWNLOAD Java EE 7 SDK oracle.com/javaee GlassFish 4.0 Full Platform or Web Profile glassfish.org 90 Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

×