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 Detail

70,695 views

Published on

This explain the new feature of Java EE 7 by Japanese.
F

Published in: Technology, News & Politics
  • Be the first to comment

Java EE 7 Detail

  1. 1. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.1Yoshio TeradaJava Evangelisthttp://yoshio3.com, Twitter : @yoshioterada
  2. 2. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.2以下の事項は、弊社の一般的な製品の方向性に関する概要を説明するものです。また、情報提供を唯一の目的とするものであり、いかなる契約にも組み込むことはできません。以下の事項は、マテリアルやコード、機能を提供することをコミットメント(確約)するものではないため、購買決定を行う際の判断材料になさらないで下さい。オラクル製品に関して記載されている機能の開発、リリースおよび時期については、弊社の裁量により決定されます。Oracleは、米国オラクルコーポレーション及びその子会社、関連会社の米国及びその他の国における登録商標です。文中の社名、商品名等は各社の商標または登録商標である場合があります。
  3. 3. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.3Make the Future Java(Java の未来を創造)
  4. 4. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.4§ Java EE 7–  HTML 5 とシンプル化にフォーカス§ Java EE 8–  クラウド対応とモジュール化対応への継続的な投資Java EE の今後Java EEHasan Rizvi
  5. 5. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.5Java EE 7 : 2013年 春頃提供開始予定テーマ:HTML5 と開発生産性の向上Java EE 7 SDK の提供開始
  6. 6. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.6Java EE 7 へ含まれる予定の JSR 一覧Connector1.6JPA 2.1 JTA 1.2 JMS 2.0Managed Bean 1.0 EJB 3.2CommonAnnotations 1.1Interceptors 1.1 CDI 1.1PortableExtensionsServlet 3.1JSP 2.2 JSF 2.2JAX-RS2.0EL3.0BeanValidation1.1ConcurrencyUtilities for EE(JSR-236)BatchApplication(JSR-352)Java API forJSON(JSR-353)Java API forWebSocket(JSR-356)新規追加 大幅な更新 通常の更新
  7. 7. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.7Java EE 7 よりWeb Profileに追加•  JAX-RS•  WebSocket•  JSON-P
  8. 8. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.8JSR 344 :JavaServer™ Faces 2.2
  9. 9. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.9§  HTML5 マークアップ・サポート–  Pass through attributes and elements§  Faces フロー§  ステートレス・モードの追加§  ファイル・アップロード§  リソース・ハンドリング機能の改善§  viewAction コンポーネント§  CSRF (クロス・サイト・リクエスト・フォージェリ) 対策新機能の一覧JSF 2.2
  10. 10. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.10HTML 5 マークアップ・サポート今後、素の HTML ファイル中にJSF コードを埋め込みましょう!!
  11. 11. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.11HTML 5 マークアップ・サポートJSF のライフサイクルに適用可
  12. 12. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.12HTML 5 マークアップ・サポートHTML 5 の表現力をそのままに!!
  13. 13. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.13HTML 5 マークアップ・サポート<input type=“color” jsf:value=“#{colorBean.color2}”/><input type=“date” jsf:value=“#{calendarBean.date1}” /><keygen jsf:id jsf:value="#{bean.pubKey}"/>標準の HTML 5 タグに jsf:value , jsf:action 等の要素を追加<jsf:element p:elementName="keygen" id=”myKey"p:name="myKey" value="#{bean.myKey}"/>直接要素を JSF ランタイムにスルーも可能
  14. 14. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.14ステートレス・モード§  既存の Facelets コードに対する少ない修正–  <f:view transient="true”>§  パフォーマンスの改善§  メモリ使用率の減少§  クラスタ環境における負荷分散の改善
  15. 15. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.15<?xml version=1.0 encoding=UTF-8 ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"xmlns:h="http://xmlns.jcp.org/jsf/html"xmlns:f="http://xmlns.jcp.org/jsf/core"><f:view transient="true"><h:head><title>Facelet Title</title></h:head><h:body>ステートレス・モード
  16. 16. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.16ファイル・アップロード<h:form prependId="false" enctype="multipart/form-data"> !<h:inputFile id="fileUpload" value="#{test.upfile}"/><h:commandButton value="upload" !action="#{test.doUpload}"/>!</h:form> 将来的には Ajax 対応(Java EE 7 の正式リリース時)のファイルアップロード機能も提供予定ご参考 : http://yoshio3.com/2012/10/20/jsf22-env-on-gf3122/
  17. 17. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.17ファイル・アップロード@Named(value = "test") !@RequestScoped !public class TestManagedBean { !  private javax.servlet.http.Part upfile;!!  public String doUpload() {!    try { !      String fileName = getFilename(upfile); !      upfile.write(fileName); !    } catch (IOException ex) { ex.printStackTrace(); }return ""; !  }
  18. 18. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.18JSR 341:Expression Language3.0EL3.0
  19. 19. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.19§  Lambda 式対応–  Array, List, Map の構成§  コレクションに対するクエリ演算子(LINQ式)§  Java SE 環境で利用するためのAPIを提供§  デフォルトの EL 実行環境マネージャの追加§  クラス(static)変数、クラス(static)メソッド、enum 定数対応§  クラス、パッケージのインポート新機能の一覧EL 3.0
  20. 20. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.20§  名前空間を持つ Name–  reference, import§  関数定義§  コンストラクタ§  新しい演算子–  文字列連結演算子、変数割当用演算子§  型変換§  表記の評価用のリスナー新機能の一覧EL 3.0
  21. 21. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.21<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 式を記述 (コレクション操作)
  22. 22. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.22JSR 339 : JAX-RS 2.0The Java API forRESTful Web Services
  23. 23. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.23§  クライアント用の API§  フィルターとインターセプタ§  非同期処理対応§  コネクションのネゴシエーション§  Validation§  ハイパーメディア対応§  JSR-330 との統合新機能の一覧JAX-RS 2.0
  24. 24. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.24クライアント API の必要性HTTP クライアント・ライブラリは低レベルJAX-RS のサーバ側の実装と共有可能JAX-RS 1.0 の実装側で提供済標準化の必要性
  25. 25. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.25URL url = new URL(http://foo/data1/data2);!HttpURLConnection con =(HttpURLConnection)url.openConnection();!con.setRequestMethod(“GET”);!con.setDoInput(true);!con.setDoOutput(false);!!BufferedReader br = new BufferedReader(newInputStreamReader(con.getInputStream()));!String line;!While ((line = br.readLine()) != null){!out.println(line);!}!JAX-RS クライアント (低レベルでの実装が必要)
  26. 26. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.26//クライアントのインスタンスを取得Client client = ClientFactory.newClient();!!String name = client.target(“../order/{orderId}/customer”)!.pathParam(“orderId”,”1111”)!.queryParam(“shipped”, “true”)!.request(“application/json”)!.get(String.class); JAX-RS クライアント
  27. 27. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.27//預金の引き下ろしMoney money = client.target(http://SERVER/atm/withdraw)!.pathParam(“card”,”xxxx-xxx-xxxx”)!.queryParam(“secNumber”,”1122”)!.request(“application/json”)!.post(text(“50.0”),Money.class); JAX-RS クライアント
  28. 28. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.28Invocation inv1 = client.target(http://SERVER/foo/bar)!.request().buildGet(); JAX-RS クライアント(コマンド&バッチ)Invocation inv2 = client.target(http://SERVER/foo/bar)!.request().buildPost(text(“50.0”); buildXXX()は Invocation を返し後からコマンド、バッチとして実行可能
  29. 29. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.29Collection<Invocation> invks = Array.asList(inv1,inv2);!!Collection<Response> res = Collection.transform(!invks,new F<Invocation,Response>(){!public Response apply(Invocation inv){!return inv.invoke();!}!});!JAX-RS クライアント(コマンド&バッチ)Invocation を配列に代入しMap 経由で Invocation を実行
  30. 30. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.30JSR 343:Java™ Message Service 2.0
  31. 31. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.31§  かんたんに実装できるようになったAPI–  JMSContext, JMSProducer, JMSConsumer の追加§  例外の実装方法の変更§  既存 API に対する改善§  CDI を利用した冗長コードの排除§  クラウド機能は Java EE 8 へ新機能の一覧JMS 2.0注意:去年の JavaOne 2011,JavaOne Tokyo 2012 の内容から若干変更あり
  32. 32. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.32@Resource( mappedName="jms/MyConnectionFactory” )!private static ConnectionFactory connectionFactory; !@Resource( mappedName="jms/mySampleQueue” )!private static Queue queue;!public void sendMessage(String text){!Connection con = connectionFactory.createConnection();!Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);!MessageProducer prod = session.createProducer(queue);!TextMessage message = session.createTextMessage(text);!message.setText(message);!prod.send(message);!con.close();} 既存のメッセージ送信コード
  33. 33. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.33@Resource( mappedName="jms/MyConnectionFactory” )!private static ConnectionFactory connectionFactory; !@Resource( mappedName="jms/mySampleQueue” )!private static Queue queue;!public void sendMessage(String text){!Connection con = connectionFactory.createConnection();!Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);!MessageProducer prod = session.createProducer(queue);!TextMessage message = session.createTextMessage(text);!message.setText(message);!prod.send(message);!con.close();} 既存のコードの課題単なるメッセージ送信に中間オブジェクトが必要
  34. 34. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.34@Resource( mappedName="jms/MyConnectionFactory” )!private static ConnectionFactory connectionFactory; !@Resource( mappedName="jms/mySampleQueue” )!private static Queue queue;!public void sendMessage(String text){!Connection con = connectionFactory.createConnection();!Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);!MessageProducer prod = session.createProducer(queue);!TextMessage message = session.createTextMessage(text);!message.setText(message);!prod.send(message);!con.close();} 既存のコードの課題定型的なコード
  35. 35. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.35javax.jms.JMSContext インタフェースJMSContextConnection Session•  別々のクラスを1つに統合–  Connection–  Session•  JMSProducer の提供•  JMSConsumer の提供新規に JMSContext インタフェースを提供
  36. 36. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.36 public void sendMessage(String text){!  Connection con = null;!  try{!  con = connectionFactory.createConnection();!  Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);!  MessageProducer prod = session.createProducer(queue);!  TextMessage message = session.createTextMessage(text);!  message.setText(message);!  prod.send(message);! }finally{!  con.close();! } 使用後コネクションのクローズが必要送信コードにおける既存のコードの課題
  37. 37. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.37AutoCloseable による実装 (close()の実装が不要)public void sendMessage(String text){!try(JMSContext context = conn.createContext()){!context.createProducer().send(queue, text);!}!}!Java SE 7 try-with-resource に対応
  38. 38. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.38 public void sendMessage(String text){!  try{!  ……// 送信処理!  prod.send(message);!  }catch(JMSException jmse){!  // 例外処理!  }finally{!  try{!  if(con != null) con.close();!  }catch (JMSException jmse2){!  // 例外処理!  }}} 例外処理の実装が必要送信コードにおける既存のコードの課題
  39. 39. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.39チェック例外から非チェック例外へ過去の例外クラス 今後の例外クラスJMSException JMSRuntimeExceptionTransactionRolledBackException TransactionRolledBackRuntimeExceptionIllegalStateException IllegalStateRuntimeException!InvalidDestinationException IllegalDestinationRuntimeException!InvalidSelectorException InvalidSelectorRuntimeExceptionMessageFormatException MessageFormatRuntimeException例外の実装方法が変更
  40. 40. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.40例外が RuntimeException に変更public void sendMessage(String text){!try{!……// 送信処理prod.send(message);!} catch (JMSRuntimeException ex) {!Logger.getLogger(getClass().getName()).!log(Level.SEVERE, null, ex); !}!}例外の実装方法が変更
  41. 41. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.41§  JNDI ルックアップでコンテナの接続ファクトリを使用–  コネクション・プール等を利用可能§  JNDI 名を未指定時、システムのデフォルト使用JMSContext に対する注入@Inject!@JMSConnectionFactory(“jms/MyConFactory”)!private JMSContext context;アノテーションを利用した依存性注入
  42. 42. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.42JMSContext に対する注入@Inject!@JMSConnectionFactory(“jms/MyConFactory”) !@JMSPasswordCredential(userName=“admin”,password=“admin”)!@JMSSessionMode(JMSContext.AUTO_ACKNOWLEDGE)!private JMSContext context;パスワードやセッションモードの設定 アノテーションを利用した依存性注入
  43. 43. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.43
  44. 44. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.44@Resource( mappedName="jms/MyConnectionFactory” )!private static ConnectionFactory connectionFactory; !@Resource( mappedName="jms/mySampleQueue” )!private static Queue queue;!!public void sendMessage(String text){!Connection con = connectionFactory.createConnection();!Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);!MessageProducer prod = session.createProducer(queue);!TextMessage message = session.createTextMessage(text);!message.setText(message);!prod.send(message);!con.close(); Java EE 6 までのメッセージ送信コード
  45. 45. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.45@Resource(mappedName = "java:comp/DefaultJMSConnectionFactory")!ConnectionFactory conn;!@Resource(mappedName = "jms/mailRegistQueue")!Queue queue;!public void sendMessages(String text){!try(JMSContext context = conn.createContext()){!context.createProducer().send(queue, text);!}!}Java EE 7 からのメッセージ送信コード
  46. 46. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.46Java API forJSON(JSR-353)JSR 353 :Java API forProcessing JSON
  47. 47. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.47JSON API のアーキテクチャJSON プロバイダSPIStreaming APIObject ModelAPIAPP1 APP2 APP n・・・ 便利な機能低レベルAPI
  48. 48. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.48{!"firstName": "John", "lastName": "Smith", "age": 25,!"phoneNumber": [!{ "type": "home", "number": "212 555-1234" },!{ "type": "fax", "number": "646 555-4567" }!]!}JSON データのサンプル
  49. 49. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.49Streaming API(低レベル : StAXライクな実装)
  50. 50. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.50JsonParser インスタンスの生成方法(読み込み2通り)JsonParser parser = javax.json.Json#createParser() JsonParser parser = Json#createParserFactory()#createParser()
  51. 51. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.51{!"firstName": ”Taro", "lastName": ”Yamada", "age": 25,!"phoneNumber": [!{ "type": "home", "number": "212 555-1234" },!{ "type": "fax", "number": "646 555-4567" }!]!}START_OBJECT Streaming API ‒ JsonParser (低レベル操作)
  52. 52. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.52{!"firstName": ”Taro", "lastName": ”Yamada", "age": 25,!"phoneNumber": [!{ "type": "home", "number": "212 555-1234" },!{ "type": "fax", "number": "646 555-4567" }!]!}KEY_NAME Streaming API ‒ JsonParser (低レベル操作)
  53. 53. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.53{!"firstName": ”Taro", "lastName": ”Yamada", "age": 25,!"phoneNumber": [!{ "type": "home", "number": "212 555-1234" },!{ "type": "fax", "number": "646 555-4567" }!]!}VALUE_STRING Streaming API ‒ JsonParser (低レベル操作)
  54. 54. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.54{!"firstName": ”Taro", "lastName": ”Yamada", "age": 25,!"phoneNumber": [!{ "type": "home", "number": "212 555-1234" },!{ "type": "fax", "number": "646 555-4567" }!]!}VALUE_NUMBER Streaming API ‒ JsonParser (低レベル操作)
  55. 55. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.55{!"firstName": ”Taro", "lastName": ”Yamada", "age": 25,!"phoneNumber": [!{ "type": "home", "number": "212 555-1234" },!{ "type": "fax", "number": "646 555-4567" }!]!}START_ARRAY Streaming API ‒ JsonParser (低レベル操作)
  56. 56. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.56{!"firstName": ”Taro", "lastName": ”Yamada", "age": 25,!"phoneNumber": [!{ "type": "home", "number": "212 555-1234" },!{ "type": "fax", "number": "646 555-4567" }!]!}END_ARRAY Streaming API ‒ JsonParser (低レベル操作)
  57. 57. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.57{!"firstName": ”Taro", "lastName": ”Yamada", "age": 25,!"phoneNumber": [!{ "type": "home", "number": "212 555-1234" },!{ "type": "fax", "number": "646 555-4567" }!]!} END_OBJECT Streaming API ‒ JsonParser (低レベル操作)
  58. 58. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.58{!"firstName": ”Taro", "lastName": ”Yamada", "age": 25,!"phoneNumber": [!{ "type": "home", "number": "212 555-1234" },!{ "type": "fax", "number": "646 555-4567" }!]!}例 ‒ 値 John の取得方法 (低レベル)
  59. 59. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.59 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.59try (Reader reader = !new FileReader(”~/json.dat");) {!JsonParser parser = Json.createParser(reader);!JsonParser.Event event = null;!!event = parser.next(); //START_OBJECT の取得!event = parser.next(); //KEY_NAME “firstName” の取得!System.out.println(parser.getString());} catch (IOException ioe) {!logger.log(Level.SEVERE, null ,ioe);!}{"firstName": Taro"
  60. 60. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.60Object Model API(扱い易い : DOM ライクな実装)
  61. 61. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.61try (JsonReader jsonReader = Json.createReader(reader)) {!JsonObject jObj = jsonReader.readObject();!if(jObj.containsKey("firstName")){!String value = jObj.getString("firstName");!System.out.println(value); // Taro!}!}JSonObject から特定 Key の Value を取得Key と Value の型が分かっている場合に有効{ "firstName": Taro", ……}
  62. 62. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.62if(jObj.containsKey("phoneNumber")){!JsonArray array = jObj.getJsonArray("phoneNumber");!for(JsonValue phoneValue : array){!if(phoneValue.getValueType() == !JsonValue.ValueType.OBJECT){!JsonObject arrayElem = !array.getJsonObject(array.indexOf(phoneValue));!if(arrayElem.containsKey("type")){ }!"phoneNumber": [{ "type": "home , ..}, { "type": "home , ..} …… ]JSonObject から特定 Array を取得
  63. 63. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.63Builder からJsonObject の生成JsonObject jsonObject = Json.createObjectBuilder(). // {!add(”KEY1", ”VALUE1"). //”KEY1": ”VALUE1”!add(”KEY2", //”KEY2": !Json.createArrayBuilder(). // [!add(Json.createObjectBuilder(). //{!add(”KEY3", ”VALUE3"))). //”KEY3": ”VALUE3" }!build();!!{"KEY1":"VALUE1","KEY2":[{"KEY3","VALUE3 }]}
  64. 64. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.64try (BufferedReader br =!new BufferedReader(new FileReader(”~/json.dat"));!JsonReader jsonReader = Json.createReader(br)) {!JsonObject jObj = jsonReader.readObject();!...!} catch (IOException ex) {!logger.log(Level.SEVERE, null, ex);!}I/O から JSonObject の読み込み
  65. 65. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.65ConcurrencyUtilities for EE
  66. 66. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.66Application ServersJava SEWeb/EJB コンテナ EJB JSP Servlet Runnable Callable Java EE 関連機能 (JAX-RS,JavaMail, CDI など) Java EE 環境で禁止されていた Thread 生成コンテナ外部で動作必要な情報の伝搬が不可能
  67. 67. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.67Application ServersJava SEWeb/EJB コンテナ EJB JSP Servlet Runnable Callable Java EE とConcurrencyのアーキテクチャJava EE 関連機能(JAX-RS,JavaMail, CDI など) ManagedExecutor ServiceManagedScheduledExecutorServiceContextServiceManagedThreadFactory Concurrency Utilities for EE
  68. 68. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.68 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.68Memoコンテナ(Web, EJB)からスレッドの生成が可能に !!独自スレッドプールの作成も可能 !!スレッド・ライフサイクル管理も可能 !!
  69. 69. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.69JSR-236 の歴史2003 年冬:エキスパート・グループ結成(BEA, IBM : commonj を元に)J2EE 1.4, Java EE5 で取り込む予定だったJSR-236 : Timer for Application Servers
  70. 70. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.70JSR-236 の歴史2008 年 6 月:仕様の名前が変更2006 年 4 月 : Version 0.1: Early DraftPreviewJSR-236 : Concurrency Utilities for Java EE2012 年 Q2 : エキスパート・グループ再結成→ Java EE 7 へ !!
  71. 71. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.71参照実装 :https://cu-javaee.java.net/
  72. 72. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.72 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.72Memo導入はとてもかんたん !!柔軟なカスタマイズも可能 !!小さなパッケージ:全12 class
  73. 73. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.73 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.73使いどころ Memo処理時間のかかる重い処理に !!サーバの H/W を有効活用 !!定期的に実行する処理に !!
  74. 74. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.74 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.74使いどころ Memoコンテナ (Web, EJB) のスレッド・ プールとは別スレッドで処理をしたいクライアントからのリクエストに影響を与えたくない
  75. 75. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.75 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.75使いどころ MemoJava SE 環境で作成したタスクをJava EE 環境で再利用したい3rdパーティ製スレッド・ライブラリを利用したい
  76. 76. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.76 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.76重要なインタフェース Best 4• ManagedExecutorService• ManagedScheduledExecutorService• ManagedThreadFactory• ContextService
  77. 77. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.77とてもかんたんEE 環境の非同期タスク実装手順(ManagedExecutorService の利用例)
  78. 78. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.78 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.78Memoこれから示す方法はサーバまかせでとてもかんたん !!
  79. 79. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.79タスクを実装A implements RunnableB implements Callable非同期タスクを実装リソース・インジェクションでサーバ管理スレッドを利用サーバ側で設定を実施デフォルト設定も利用可 1 2EE環境の非同期タスクの実装手順3
  80. 80. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.80 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.80public class MyRunnableTask implements Runnable {!@Override!public void run() { !try {!Thread.sleep(10000); //何らかの処理} catch (InterruptedException ex) {!logger.log(Level.SEVERE, null, ex);!}!}!}!Runnable のタスクを作成1
  81. 81. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.81 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.81Callable のタスクを作成    ● call() は返り値を持つ事が可能    ● チェック例外のスローが可能1public class MyCallableTask implements !Callable<String> {!@Override!public String call() throws Exception {!return “Hello World”;!}!}!
  82. 82. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.82サーバ側の設定例2
  83. 83. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.83 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.83@Stateless!public class MyManagedExecutorService {!@Resource(name = !"concurrent/DefaultManagedExecutorService")!ManagedExecutorService managedExecsvc; !public void execExecutorService() {!MyRunnableTask task = new MyRunnableTask();!managedExecsvc.submit(task);!      MyCallableTask singleTask = !          new MyCallableTask("Foo Bar");!Future<String> singleFuture =    !managedExecsvc.submit(singleTask);}!非同期タスクを実行する EJB3サーバ設定のリソースをインジェクト
  84. 84. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.84非同期タスクのスケジューリング(ManagedScheduledExecutorServiceの利用例)
  85. 85. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.85 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.85Memo実行命令から指定した時間経過後タスクを実行 !!トリガーも指定可能
  86. 86. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.86タスクを実装A implements RunnableB implements Callable非同期タスクを実装リソース・インジェクションでサーバ管理スレッドを利用サーバ側で設定を実施デフォルト設定も利用可 1 2EE環境の非同期タスクの実装手順3
  87. 87. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.87サーバ側の設定例2
  88. 88. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.88 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.88@Stateless!public class MyManagedScheduledExecutorService{!@Resource(name = "concurrent/!DefaultManagedScheduledExecutorService")!ManagedScheduledExecutorService managedScheduledExecsvc;!!public void execScheduledExecutorService() {!MyRunnableTask task = new MyRunnableTask();!managedScheduledExecsvc.schedule(!task, 60L, TimeUnit.SECONDS);!}!非同期タスクを実行する EJB31分後にタスクを実行
  89. 89. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.89 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.89@Stateless!public class MyManagedScheduledExecutorService{!@Resource(name = "concurrent/!DefaultManagedScheduledExecutorService")!ManagedScheduledExecutorService managedScheduledExecsvc;!!public void execScheduledExecutorService() {!MyRunnableTask task = new MyRunnableTask();!managedScheduledExecsvc.schedule(!task, new MyTrigger(new Date(), 10, 1000) }!非同期タスクを実行する EJB3独自トリガーも指定可能
  90. 90. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.90 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.90import javax.enterprise.concurrent.Trigger;!public class MyTrigger implements Trigger {!!@Override!public Date getNextRunTime(LastExecution le, !Date date){!}!!@Override!public boolean skipRun(LastExecution le, !Date date) {!!}!}! いつ、どのような時にタスクを実行するかスキップするかプログラミング上から制御
  91. 91. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.91タスクのライフサイクル管理・監視
  92. 92. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.92タスクのライフサイクルtaskSubmitted Submitted taskStarting taskAborted Started taskDone Done submit()の実行submit成功キャンセル・中止タスクの実行準備タスク実行キャンセル・中止タスク実行完了タスク状態の監視が可能  部分を実装
  93. 93. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.93 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.93public class MyManagedTaskListener implements !ManagedTaskListener {!public void taskSubmitted(Future<?> future, !ManagedExecutorService mes, Object o) {!}!public void taskStarting(Future<?> future, !ManagedExecutorService mes, Object o) {!}!public void taskAborted(Future<?> future, !ManagedExecutorService mes, Object o, Throwable thrwbl){!}!public void taskDone(Future<?> future, !ManagedExecutorService mes, Object o, Throwable thrwbl){!}!}!ManagedTaskListenerインタフェースを実装した独自のタスク・リスナーを作成
  94. 94. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.94 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.94@Resource(name = "concurrent/!MyManagedExecutorService")!ManagedExecutorService manageExecsvc;!!public void invokeMyTaskListener() {!MyRunnableTask task = new MyRunnableTask();!MyManagedTaskListener listener = !new MyManagedTaskListener();!Runnable taskWithListener = !ManagedExecutors.managedTask(task, listener);!manageExecsvc.execute(taskWithListener);!}!
  95. 95. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.95内部動作の詳細ContextSerivce
  96. 96. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.96 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.96ManagedExecutorServiceManagedScheduledExecutorServiceリソース・インジェクションで簡単に実装できる事はわかった。タスクのライフサイクルの管理もできる事がわかったサーバ管理者との分業もわかった。
  97. 97. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.97 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.97でも内部的にどのようにして動いているの?
  98. 98. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.98 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.98Memo内部的に Dynamic Proxy を利用して付加情報(コンテキスト情報)を付加してタスク実行
  99. 99. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.99 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.99MemoDynamic Proxy をちょっと復習(java.lang.reflect.Proxy)
  100. 100. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.100Dynamic Proxy によるメソッド呼び出しpublic class MyRunnable implements Runnable{!@Override!public void run() {!    System.out.println(“オリジナル・メソッド呼び出し");!  }!} このタスクを動的プロキシ経由で実行
  101. 101. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.101独自 InvocationHandler の実装public class MyInvocationHandler implements InvocationHandler {!private Object underlying;!public MyInvocationHandler(Object underlying) {!this.underlying = underlying;!}!@Override!public Object invoke(Object proxy, Method method, !                            Object[] args) throws Throwable {!System.out.println("オリジナル・メソッド呼び出しの前処理");!Object ret = method.invoke(underlying, args);!System.out.println("オリジナル・メソッド呼び出しの前処理");!return ret;}}
  102. 102. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.102Dynamic Proxy 経由でタスク実行public class MyDynamicProxy {!public static void main(String argv[]){!MyRunnable task = new MyRunnable();!InvocationHandler handler = new !                            MyInvocationHandler(task);!Runnable proxy = (Runnable)Proxy.newProxyInstance(!                     MyRunnable.class.getClassLoader(), !                     new Class[]{Runnable.class}, handler);!    ExecutorService exec = Executors.newSingleThreadExecutor();!    exec.submit(proxy);!}}!
  103. 103. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.103Dynamic Proxy のタスク実行結果オリジナル・メソッド呼び出しの前処理オリジナル・メソッドの呼び出しオリジナル・メソッド呼び出しの前処理ExecutorService exec =  !Executors.newSingleThreadExecutor();!exec.submit(proxy);! AOP として利用可能
  104. 104. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.104 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.104MemoJava EE 環境ではInvocationHandler はサーバ側で実装済み※ GlassFish v4.0 では下記のクラスで実装  org.glassfish.enterprise.concurrent.internal.  ContextProxyInvocationHandler
  105. 105. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.105サーバ側の設定例1
  106. 106. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.106 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.106@Stateless!public class ContextServiceManager {!@Resource(name = "concurrent/DefaultContextService")!ContextService ctxSvc;!!  public void execSimpleContextService() {!ExecutorService singleThreadExecutor = !Executors.newSingleThreadExecutor(threadFactory);!MyRunnableTask task = new MyRunnableTask();!Runnable proxiedTask =!ctxSvc.createContextualProxy(task,Runnable.class);!singleThreadExecutor.submit(proxiedTask);}}!!動的プロキシを生成コンテキスト付タスクの実行2
  107. 107. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.107 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.107オリジナルのタスクDynamic Proxy で生成されたタスクMemoコンテキス情報を付加しEE環境で実行可能に !!
  108. 108. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.108内部動作の詳細ThreadFactory
  109. 109. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.109 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.109MemoManagedThreadFactory が解決することコンテナ管理のスレッドを生成機能を提供
  110. 110. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.110 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.110Memoカスタムのスレッド・プールをプログラムで定義し、そこからスレッド生成が可能※ スレッドの生成方法をプログラムでカスタマイズ可能
  111. 111. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.111サーバ側の設定例1
  112. 112. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.112 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.112@Resource(name = "concurrent/!DefaultManagedThreadFactory")!ManagedThreadFactory threadFactory;!public void execThreadFactory() {!MyRunnableTask task = new MyRunnableTask();!Thread taskThread = !threadFactory.newThread(task);!taskThread.start();!}!ThreadFactory からスレッド生成(長時間実行タスクに有効)2簡単版
  113. 113. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.113 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.113ExecutorService threadPoolExecutor = !Executors.newFixedThreadPool(4,threadFac);!!!threadPoolExecutor = new ThreadPoolExecutor(4, 4,!                    0L, TimeUnit.MILLISECONDS,!                    new LinkedBlockingQueue<Runnable>(), !                    threadFac);!ThreadPoolExecutor を使用するとカスタム・スレッドプールの生成が可能上記は全く同じ(Java SE APIを利用)java.util.concurrent.ThreadPoolExecutor
  114. 114. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.114 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.114@Resource(name = "concurrent/!DefaultManagedThreadFactory")!ManagedThreadFactory threadFactory;!public void execThreadFactory() {!  MyRunnableTask task = new MyRunnableTask();!  ExecutorService exec = !           new ThreadPoolExecutor(4, 4,!           0L, TimeUnit.MILLISECONDS,!new LinkedBlockingQueue<Runnable>(), !           threadFactory);!  exec.submit(task);}!カスタム・スレッド・プールからスレッド生成
  115. 115. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.115さいごに
  116. 116. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.116 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.116制限事項 Memo1CDI のビーンをタスクとして利用可能しかし、下記スコープで利用@ApplicationScoped@DependentCDI が 持つ CDI のライフサイクルに注意 !!
  117. 117. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.117 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.117制限事項 Memo2アプリケーション・クライアント・コンテナでは利用不可能
  118. 118. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.118 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.118制限事項 Memo3タスクのリモートからの呼び出しは不可能(Ver 1.0)
  119. 119. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.119 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.119制限事項 Memo4Fork/Join(ForkJoinPool)は利用不可能
  120. 120. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.120 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.120制限事項 Memo5ExecutorService から継承したライフサイクル・メソッドの呼び出しは不可能(shutdown, shutdownNow)※ ManagedExecutorService※ ManagedScheduledExecutorService
  121. 121. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.121JSR 352:Batch Applicationsfor the Java Platform
  122. 122. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.122§  バッチ処理用のフレームワーク§  Java SE / EE 環境で利用可能§  バッチ処理に必要な、入力、処理、出力の実装を標準化§  シーケンシャル、並列処理に対応§  各処理における前処理、後処理などの実装方法を提供機能の一覧jbatch
  123. 123. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.123jbatch のアーキテクチャJob RepositoryJobOperatorItemReader ItemProcessor Item Writer Job Step1 *111 111全体アーキテクチャ
  124. 124. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.124JobOperatorJob RepositoryJobOperatorItemReader ItemProcessor Item Writer Job Step1 *111 111ジョブ処理の全体を管理(起動・停止・再起動・レポジトリ情報取得など)
  125. 125. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.125JobJob RepositoryJobOperatorItemReader ItemProcessor Item Writer Job Step1 *111 111バッチの処理内容を隠JSL(ジョブ仕様記述言語)で記載した内容と関連付け
  126. 126. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.126StepJob RepositoryJobOperatorItemReader ItemProcessor Item Writer Job Step1 *111 111バッチの処理内容を隠JSL(ジョブ仕様記述言語)で記載した内容と関連付け方式:chunk, batchlet
  127. 127. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.127<job id="job1" xmlns="http://batch.jsr351/js1">!<split id="split1">!<flow id="flow1" next="flow2">!<step id="step1" next="step2">!<batchlet ref="MyBatchlet"/>!</step>!<step id="step2" next="stepDONE">!<batchlet ref="MyBatchlet2"/>!</step>!</flow>… </job>!Job Specification Language(JSL : ジョブ仕様記述言語)
  128. 128. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.128<flow id="flow2">!<step id="step3">!<chunk reader="MyReader" processor="MyProcessor" !write="MyWriter” commit-interval=“2”>!<properties>!<property name="audit" value="true"/>!</properties>!</chunk>!</step>!</flow></split></job>!Job Specification Language(JSL : ジョブ仕様記述言語)
  129. 129. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.129chunk 方式Job RepositoryJobOperatorItemReader ItemProcessor Item Writer Job Step1 *111 111バッチをアイテム(入力、処理、出力)毎に分けて実装ItemReader : データの入力ItemProcessor : データの処理ItemWriter : データの出力
  130. 130. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.130chunk 方式のシーケンス図の例commit-interval = 2 の場合
  131. 131. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.131package javax.batch.api;!import java.io.Externalizable;!public interface ItemReader <T> {!public void open(Externalizable checkpoint) throws Exception;!public void close() throws Exception;!public T readItem() throws Exception;!public Externalizable checkpointInfo() throws Exception;!}ItemReader インタフェース
  132. 132. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.132import javax.batch.api.ItemReader;!@Named!public class MyReader implements ItemReader { ! ...!}ItemReader の実装例(インタフェース実装有)
  133. 133. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.133ItemReader の実装例(インタフェース実装無)import javax.batch.annotation.*;!@Named!public class MyReader {!@Open void open(MyCheckpointData checkpoint) !throws Exception {...}!@Close void close() throws Exception {...}!@ReadItem MyBatchInputRecord read() throws Exception {...}!@CheckpointInfo Externalizable MyCheckpointData getChkpt() !throws Exception {...}!}
  134. 134. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.134package javax.batch.api;!public interface ItemProcessor <T, R> {!public R processItem(T item) throws Exception;!}!ItemProcessor インタフェース
  135. 135. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.135ItemReader と同様 ●インタフェースの実装有 ●インタフェースの実装無  (メソッドレベル・アノテーション)
  136. 136. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.136package javax.batch.api; !import java.io.Externalizable;!import java.util.List;!public interface ItemWriter <T> {!public void open(Externalizable checkpoint) throws Exception;!public void close() throws Exception;!public void writeItems(List<T> items) throws Exception;!public Externalizable checkpointInfo() throws Exception;!}!ItemWriter インタフェース
  137. 137. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.137ItemReader と同様 ●インタフェースの実装 ●インタフェースの未実装  (メソッドレベル・アノテーション)
  138. 138. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.138Batchlet Batchlet 方式Job RepositoryJobOperatorJob Step1 *1 1バッチを1つのタスクとして実装一旦処理を実行すると最後まで処理を続行
  139. 139. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.139package javax.batch.api;!public interface Batchlet {!public String process() throws Exception;!public void stop() throws Exception;!}!Batchlet インタフェース
  140. 140. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.140@Named !public class implements Batchlet {!public String process() throws Exception;!public void stop() throws Exception;!}!Batchlet インタフェース@Named!public class MyBatchLet{!@Process String process() throws Exception {...} !@Stop void stopMe() throws Exception {...}!}!インタフェース実装有インタフェース実装無
  141. 141. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.141Job RepositoryJob RepositoryJobOperatorItemReader ItemProcessor Item Writer Job Step1 *111 111Job に関する現在・過去の情報を保持
  142. 142. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.142JSR 356:JavaTM API for WebSocket
  143. 143. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.143WebSocket の背景 ‒ Server PushPollingLong PollingComet/Ajax複雑・非効率・無駄
  144. 144. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.144WebSocket とはTCP ベース双方向・全二重通信RFC 6455JavaScript API by W3C
  145. 145. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.145ブラウザの対応状況http://caniuse.com/websockets現バージョンの対応状況
  146. 146. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.146WebSocket の基本概念コネクションの確立双方向のメッセージ送信コネクションの切断
  147. 147. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.147コネクションの確立HandShake リクエストHandShake レスポンスクライアント サーバ
  148. 148. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.148HandShake リクエスト (RFC 6455で定義)サーバクライアントGET /mychat HTTP/1.1!Host: server.example.com!Upgrade: websocket!Connection: Upgrade!Sec-WebSocket-Key:x3JJHMbDL1EzLkh9GBhXDw==!Sec-WebSocket-Protocol: megachat,chat!Sec-WebSocket-Extensions :compress, mux!Sec-WebSocket-Version: 13!Origin: http://example.com
  149. 149. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.149HandShake レスポンス (RFC 6455で定義)サーバクライアントHTTP/1.1 101 Switching Protocols!Upgrade: websocket!Connection: Upgrade!Sec-WebSocket-Accept:HSmrc0sMlYUkAGmm5OPpG2HaGWk=!Sec-WebSocket-Protocol: chat!Sec-WebSocket-Extensions: compress,mux
  150. 150. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.150コネクションの確立クライアント サーバ
  151. 151. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.151WebSocket のライフサイクルクライアント サーバOpen OpenCloseMessageMessageMessageMessageMessageMessageError接続確立接続切断
  152. 152. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.152WebSocket APIwww.w3.org/TR/websockets/
  153. 153. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.153Java API for WebSocket (JSR-356)http://jcp.org/en/jsr/detail?id=356http://java.net/projects/websocket-spec仕様ステータス: Early Draft
  154. 154. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.154参照実装http://java.net/projects/tyrus最新の GlassFish v4開発ビルドにバンドル済
  155. 155. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.155アノテーション レベル 内容@ServerEndpoint クラス WebSocket のエンドポイントを示す@OnOpen メソッド 接続確立時に呼び出すメソッドを指定@OnClose メソッド 接続切断時に呼び出すメソッドを指定@OnMessage メソッド メッセージを受信した時に呼び出すメソッドを指定@PathParam メソッドパラメータエンドポイントのURI 引数に指定されたパラメータを取得する際に仕様@OnError メソッド エラー発生時に呼び出すメソッドを指定WebSocket アノテーション
  156. 156. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.156WebSocket アプリケーション・ライフサイクル@ServerEndpoint("/hello")var wsUri = "ws://HOST/foo/hello";var websocket = new WebSocket(wsUri); @OnOpenwebsocket.onopen = function(evt){ onOpen(evt) }; websocket.onmessage = function(evt){ onMessage(evt) }; @OnMessagewebsocket.onerror = function(evt){ onError(evt) }; @OnErrorwebsocket.onclose = function(evt){ onClose (evt) }; @OnCloseJavaScript WebSocket API
  157. 157. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.157import javax.net.websocket.annotations.*;

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

@OnMessage
public void sayHello(Session session, String msg) {
session.getRemote().sendString(“Hello” + msg);
}
}!HelloWorld アプリケーション (1対1)
  158. 158. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.158デモ
  159. 159. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.159TwitterSingleton サンプル・アプリケーションの構成 (多対1)RemoteEndpointRE RE RE Session Session Session WebSocketEndpointTwitter4J
  160. 160. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.160@ServerEndpoint(value= "/twitter")!public class TwitterWebSocket {!@OnOpen!public void initOpen(Session session) {!TwitterClientSingleton.peers.add(session);!}!@OnClose!public void closeWebSocket(Session session){!TwitterClientSingleton.peers.remove(session);!}!}!Twitter Streaming アプリ
  161. 161. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.161@Startup @Singleton!public class TwitterClientSingleton extends StatusAdapter {!public static Set<Session> peers = null;! static {!peers = Collections.synchronizedSet(new HashSet());!}!...続く!Twitter Streaming アプリSession Session Session Session クライアントの参照情報を保持RE RE RE RE ・・・・・・
  162. 162. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.162public void onStatus(Status status) {!User user = status.getUser();!String resStr = "@" +user.getScreenName() + " : " +!status.getText() ;!try {!for (Session peer : peers) {!peer.getBasicRemote().sendText(resStr);!}!} catch (IOException ioe) {!ioe.printStackTrace();!}!}!データ送信コード (ブロッキング)シーケンシャルに配信を実施 (大量のデータで待ち)全ピア(RE)に対して配信Session Session Session Session RE RE RE RE
  163. 163. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.163データ送信コード (ノン・ブロッキングfor (Session peer : peers) {!Future<Void> futureSend = !peer.getAsyncRemote().sendText (resStr);!while (!futureSend.isDone()) {!// wait here ?!}!SendResult status = futureSendResult.get();!if (status.isOK()) {!// ok!} else {!// whoops, send failed.!}} !
  164. 164. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.164
  165. 165. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.165

×