Your SlideShare is downloading. ×
0
Main sponsorPlataforma Java EE 7: Produtividade & HTML5Bruno Borges - @brunoborgesOracle Java EE/Middleware Product Manager
The following is intended to outline our general product    direction. It is intended for information purposes only, and  ...
Java EE 6                                                                 10 Dezembro 20093   Copyright © 2012, Oracle and...
Java EE 6 – Estatísticas       •      40+ Milhões de Downloads de Componentes Java EE       •      #1 Escolha para Desenvo...
Top 10 Features do Java EE 6    1. EJB dentro de um WAR    2. Injeção de Dependência type-safe    3. Descritores de Deploy...
Escopo do Java EE 7    Produtividade e HTML5    • Mais Produtividade             – Menos código “boilerplate”             ...
Java EE 7 –JSRs Candidatas                                                                                JAX-RS          ...
Agenda       •      JAX-RS 2.0       •      JMS 2.0       •      JSON API 1.0       •      WebSockets API 1.0       •     ...
Java API for RESTful Web Services 2.0    Client API - Antes      String address = String.format("http://…/orders/%0$s/cust...
Java API for RESTful Web Services 2.0     Client API - Agora      // Obtém instância do Client      Client client = Client...
Java API for RESTful Web Services 2.0     Client API - Agora       // Sacar dinheiro       Money mon = client.target("http...
Java API for RESTful Web Services 2.0     Client-side AsyncClient client = ClientFactory.newClient();Future<String> future...
Java API for RESTful Web Services 2.0     Server-side Async@Path("/async/longRunning")public class MyResource {          @...
Java API for RESTful Web Services 2.0     Pré-Configurações     public class MyApp extends javax.ws.rs.core.Application { ...
Java Message Service 2.0     Enviando mensagem com JMS 1.1 - Antes           @Resource(lookup = "java:global/jms/demoConne...
Java Message Service 2.0     API simplificada para fechar objetos JMS @Resource(lookup = "jms/connFactory") ConnectionFact...
Java Message Service 2.0                                                  JMSContext     Introdução do JMSContext e JMSPro...
Java Message Service 2.0     Definição padrão de recursos                                                                 ...
Java API for JSON Processing 1.0     Streaming API – JsonParser e JsonGenerator     • JsonParser           – Processa JSON...
Java API for JSON Processing 1.0     Streaming API – JsonParser     {                 "firstName": "John", "lastName": "Sm...
Java API for JSON Processing 1.0     Streaming API – JsonParser e JsonGenerator     • JsonGenerator           – Gera JSON ...
Java API for JSON Processing 1.0     Streaming API – JsonGenerator                                                        ...
Java API for JSON Processing 1.0     Object Model API     • JsonObject/JsonArray – Objeto JSON e estruturas       de Array...
Java API for JSON Processing 1.0     DOM API – JsonReader     • Lê JsonObject e JsonArray de algum input              – I/...
Java API for JSON Processing 1.0     DOM API – Writer     • Escreve JsonObject e JsonArray para algum output              ...
Java API for WebSocket 1.0     Hello World – POJO/Annotation-driven import javax.websocket.*; @WebSocketEndpoint("/hello")...
Java API for WebSocket 1.0     Anotações WebSocket                        Annotation                                Level ...
Java API for WebSocket 1.0     Atributos do @WebSocketEndpoint                             value                          ...
Java API for WebSocket 1.0     Mensagens customizadas     @WebSocketEndpoint(         value="/hello",         encoders={My...
Java API for WebSocket 1.0     Mensagens customizadas – Text     public class MyMessage implements Decoder.Text<MyMessage>...
Java API for WebSocket 1.0     Mensagens customizadas – Binary     public class MyMessage implements Decoder.Binary<MyMess...
Java API for WebSocket 1.0     URI Template Matching     • Um nível somente (1 parâmetro na URL)     @WebSocketEndpoint(“/...
Java API for WebSocket 1.0     Hello World Client     @WebSocketClient     public class HelloClient {       @WebSocketMess...
Bean Validation 1.1         Parâmetro de Método e Validação de Resultado         public void placeOrder(Built-in          ...
Batch Applications for the Java Platform 1.0     •   Serve para tarefas não-interativas e processos longos     •   Process...
Batch Applications for the Java Platform 1.0     Job Specification Language     • Define um Job, Steps e direciona a execu...
Batch Applications for the Java Platform 1.0     Job Specification Language – Exemplo     <job id=“myJob”>       <step id=...
Batch Applications for the Java Platform 1.0       Job Specification Language – Chunked<step id=”sendStatements”>         ...
Batch Applications for the Java Platform 1.0     Job Specification Language: Batchlet            <step id=”transferFile”> ...
Batch Applications for the Java Platform 1.0     Conceitos: Listeners     • Job listener: intercepta a execução batch     ...
Java Temporary Caching API 1.0     • API e semântica para cache temporário em memória       para objetos Java           – ...
Java Temporary Caching API 1.0     Exemplo – Criando um CacheManager     CacheManager cacheManager =     CacheManagerFacto...
Java Temporary Caching API 1.0     Exemplo – Usando o Cache     • Obtém um cache do CacheManager        Cache<Integer, Dat...
Java Temporary Caching API 1.0     Exemplo – Configurando o Cache     • Configurar um cache para “read-through”     CacheM...
Java Temporary Caching API 1.0     Exemplo – Colocando um valor no cache     Cache<Integer, Date> cache =        cacheMana...
Java Temporary Caching API 1.0     Exemplo – Obtendo um valor do cache     Cache<Integer, Date> cache =        cacheManage...
Java Temporary Caching API 1.0     Exemplo – Removendo um valor do cache     Cache<Integer, Date> cache =        cacheMana...
Java Temporary Caching API 1.0     Exemplo – Blog     public class BlogManager {           @CachePut(cacheName=”blogManage...
Java Temporary Caching API 1.0     Exemplo – Blog           . . .           @CacheResult(cacheName="blogManager")         ...
Java Temporary Caching API 1.0     Annotations – Exemplo do Blog           . . .           @CacheRemoveEntry(cacheName="bl...
Java Temporary Caching API 1.0     Possíveis implementações     •   Terracotta – Ehcache     •   Oracle – Coherence     • ...
Java Persistence API 2.1     •   Geração do schema     •   Persistence Context assíncronos     •   Converters     •   Bulk...
Java Persistence API 2.1     Unsynchronized Persistence Contexts     • Synchronized: TX aplicada no banco no commit     • ...
Java Persistence API 2.1     Unsynchronized Persistence Contexts Sample     @Stateful public class ShoppingCart {        @...
Java Persistence API 2.1     Unsynchronized Persistence Contexts - Exemplo         public Collection<Book> viewCart() {   ...
Java Persistence API 2.1     Stored Procedure Query     @Entity     @NamedStoredProcedureQuery(name="topGiftsStoredProcedu...
Java Persistence API 2.1     Update e Delete com Criteria     CriteriaUpdate<Customer> q = cb.createCriteriaUpdate(Custome...
GlassFish RoadmapGlassFish v3                                                               GlassFish Server 3.1          ...
Transparência      • JSRs de Java EE 7 da Oracle estão abertos no java.net            – http://javaee-spec.java.net       ...
Java EE 7: Status e Agenda• Todas as JSRs estão ativas e em andamento• Todas já publicaram Early Drafts, várias em Public ...
Adopt-a-JSR      O que é ?      • Iniciativa de líderes JUGs para se involverem em JSR      • Promover as JSRs para a comu...
Adopt-a-JSR      Como posso começar? – glassfish.org/adoptajsr127   Copyright © 2012, Oracle and/or its affiliates. All ri...
Adopt-a-JSR      JUGs participando do programa128   Copyright © 2012, Oracle and/or its affiliates. All rights      reserv...
Como participar      • Java EE 7 Expert Group               – javaee-spec.java.net      • Java EE 7 Reference Implementati...
130   Copyright © 2012, Oracle and/or its affiliates. All rights      reserved.
Upcoming SlideShare
Loading in...5
×

Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

4,212

Published on

Parte 1 das novidades do Java EE 7, apresentado na reunião de Janeiro do SouJava

Published in: Technology

Transcript of "Plataforma Java EE 7: Produtividade & HTML5 - Parte 1"

  1. 1. Main sponsorPlataforma Java EE 7: Produtividade & HTML5Bruno Borges - @brunoborgesOracle Java EE/Middleware Product Manager
  2. 2. The following is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle.2 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  3. 3. Java EE 6 10 Dezembro 20093 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  4. 4. Java EE 6 – Estatísticas • 40+ Milhões de Downloads de Componentes Java EE • #1 Escolha para Desenvolvedores Enterprise • #1 Plataforma de Desenvolvimento de Aplicações • Mais rápida implementação do Java EE4 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  5. 5. Top 10 Features do Java EE 6 1. EJB dentro de um WAR 2. Injeção de Dependência type-safe 3. Descritores de Deploy opcionais (web.xml, faces-config.xml) 4. JSF padronizado com Facelets 5. Uma única classe por EJB 6. Pontos de Extensão para Servlets e CDI 7. Eventos CDI 8. API de EJBContainer 9. Anotação @Schedule baseado em cron 10. Profile Web para desenvolvimento Java EE leve5 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  6. 6. Escopo do Java EE 7 Produtividade e HTML5 • Mais Produtividade – Menos código “boilerplate” – Funcionalidades mais ricas – Mais padrões e convenções • Suporte ao HTML5 – WebSocket – JSON – Formulários HTML56 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  7. 7. Java EE 7 –JSRs Candidatas JAX-RS JAX-RS Java Caching API Java Caching API JSP 2.2 JSF 2.2 JSP 2.2 JSF 2.2 2.0 EL 3.0 EL 3.0 (JSR 107) (JSR 107) Portable 2.0 PortableExtensions Extensions Concurrency Utilities Concurrency Utilities Servlet 3.1 Servlet 3.1 (JSR 236) (JSR 236) Common Common Batch Applications Batch Applications Interceptors 1.1 CDI 1.1Annotations 1.1 Interceptors 1.1 CDI 1.1 (JSR 352) (JSR 352)Annotations 1.1 Java API for JSON Java API for JSON Managed Beans 1.0 Managed Beans 1.0 EJB 3.2 EJB 3.2 (JSR 353) (JSR 353)ConnectorConnector Java API for WebSocket Java API for WebSocket JPA 2.1 JPA 2.1 JTA 1.2 JTA 1.2 JMS 2.0 JMS 2.0 (JSR 356) 1.6 1.6 (JSR 356) Novo Nova Atualização Versão 7 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  8. 8. Agenda • JAX-RS 2.0 • JMS 2.0 • JSON API 1.0 • WebSockets API 1.0 • Bean Validation 1.1 • Batch API 1.0 • JCache API 1.0 • JPA 2.18 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  9. 9. Java API for RESTful Web Services 2.0 Client API - Antes String address = String.format("http://…/orders/%0$s/customer?shipped= %1$b", "10", true); URL url = new URL(address); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.setDoOutput(false); BufferedReader br = new BufferedReader( new InputStreamReader(conn.getInputStream())); String line; while ((line = br.readLine()) != null) { //. . . }9 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  10. 10. Java API for RESTful Web Services 2.0 Client API - Agora // Obtém instância do Client Client client = ClientFactory.newClient(); // Obtém nome do cliente para o produto enviado String name = client.target(“../orders/ {orderId}/customer”) .resolveTemplate(”orderId", ”10”) .queryParam(”shipped", ”true”) .request() .get(String.class);10 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  11. 11. Java API for RESTful Web Services 2.0 Client API - Agora // Sacar dinheiro Money mon = client.target("http://.../atm/{cardId}/withdrawal") .resolveTemplate("cardId", "111122223333") .queryParam("pin", "9876") .request("application/json") .post(text("50.0"), Money.class);11 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  12. 12. Java API for RESTful Web Services 2.0 Client-side AsyncClient client = ClientFactory.newClient();Future<String> future = client.target("http://.../atm/{card}/balance") .pathParam("card", "1111222233334444") .queryParam("pin", "1234") .request("text/plain") .async() .get( new InvocationCallback<String>() { public void completed(String result) { } public void failed(InvocationException e) { } });12 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  13. 13. Java API for RESTful Web Services 2.0 Server-side Async@Path("/async/longRunning")public class MyResource { @GET public void longRunningOp(@Suspended AsyncResponse ar) { ar.setTimeoutHandler(new MyTimoutHandler()); ar.setTimeout(15, SECONDS); Executors.newSingleThreadExecutor().submit(new Runnable() { public void run() { … ar.resume(result); }}); }}13 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  14. 14. Java API for RESTful Web Services 2.0 Pré-Configurações public class MyApp extends javax.ws.rs.core.Application { public Set<Class<?>> getClasses() { Set<Class<?>> classes = new HashSet<…>(); … classes.add(JsonMessageBodyReader.class); classes.add(JsonMessageBodyWriter.class); classes.add(JsonpInterceptor.class); … return classes; } } public Set<Class<?>> getClasses() { … classes.add(JsonFeature.class); … }14 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  15. 15. Java Message Service 2.0 Enviando mensagem com JMS 1.1 - Antes @Resource(lookup = "java:global/jms/demoConnectionFactory") ConnectionFactory connectionFactory; @Resource(lookup = "java:global/jms/demoQueue") Queue demoQueue; public void sendMessage(String payload) { try { Connection connection = connectionFactory.createConnection(); try { Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE); MessageProducer messageProducer = session.createProducer(demoQueue); TextMessage textMessage = session.createTextMessage(payload); messageProducer.send(textMessage); 13 LDCs só } finally { pra enviar connection.close(); a msg } } catch (JMSException ex) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); } }15 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  16. 16. Java Message Service 2.0 API simplificada para fechar objetos JMS @Resource(lookup = "jms/connFactory") ConnectionFactory cf; Uso do bloco @Resource(lookup="jms/inboundQueue") try-with-resource Destination dest; s public void sendMessage (String payload) throws JMSException { try ( Connection conn = connectionFactory.createConnection(); Session session = conn.createSession(); MessageProducer producer = session.createProducer(dest); ){ Message mess = sess.createTextMessage(payload); close() é producer.send(mess); chamado } catch(JMSException e){ automaticamente // exception handling } }18 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  17. 17. Java Message Service 2.0 JMSContext Introdução do JMSContext e JMSProducer combina Connection e Session @Resource(lookup = "java:global/jms/demoConnectionFactory") ConnectionFactory connectionFactory; Mensagem @Resource(lookup = "java:global/jms/demoQueue") enviada Queue demoQueue; diretamente public void sendMessage (String payload) { try (JMSContext context = connectionFactory.createContext();){ context.createProducer().send(demoQueue, payload); } catch (JMSRuntimeException ex) { // exception handling } close() é } chamado Sem checked automaticamente exceptions19 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  18. 18. Java Message Service 2.0 Definição padrão de recursos Definição de recurso ou @JmsConnectionFactory @Inject JMSContext context; @Resource(lookup = "java:global/jms/demoQueue”) Queue demoQueue; public void sendMessage(String payload) { context.createProducer().send(demoQueue, payload); } 13 linhas 1 line20 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  19. 19. Java API for JSON Processing 1.0 Streaming API – JsonParser e JsonGenerator • JsonParser – Processa JSON em modo “streaming” • Similar ao XMLStreamReader do StaX – Como criar • Json.createParser(…) • Json.createParserFactory().createParser(…) – Eventos do processador • START_ARRAY, END_ARRAY, START_OBJECT, END_OBJECT, ...21 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  20. 20. Java API for JSON Processing 1.0 Streaming API – JsonParser { "firstName": "John", "lastName": "Smith", "age": 25, "phoneNumber": [ { "type": "home", "number": "212 555-1234" }, { "type": "fax", "number": "646 555-4567" } ] } Iterator<Event> it = parser.iterator(); Event event = it.next(); // START_OBJECT event = it.next(); // KEY_NAME event = it.next(); // VALUE_STRING String name = parser.getString(); // "John”29 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  21. 21. Java API for JSON Processing 1.0 Streaming API – JsonParser e JsonGenerator • JsonGenerator – Gera JSON no modo streaming • Similar ao XMLStreamWriter do StaX – Como criar • Json.createGenerator(…) • Json.createGeneratorFactory().createGenerator(…) – Funcionalidades adicionais • Ex: código gerado formatado30 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  22. 22. Java API for JSON Processing 1.0 Streaming API – JsonGenerator JsonGenerator jg = Json.createGenerator(…);"phoneNumber": [ { jg. "type": "home", .beginArray("phoneNumber") "number": ”408-123-4567” .beginObject() }, .add("type", "home") { .add("number", "408-123-4567") "type": ”work", .endObject() "number": ”408-987-6543” .beginObject() } .add("type", ”work") ] .add("number", "408-987-6543") .endObject() .endArray(); jg.close();31 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  23. 23. Java API for JSON Processing 1.0 Object Model API • JsonObject/JsonArray – Objeto JSON e estruturas de Array – JsonString e JsonNumber para valores texto e numéricos • JsonBuilder – Cria JsonObject e JsonArray • JsonReader – Lê JsonObject e JsonArray • JsonWriter – Escreve JsonObject e JsonArray32 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  24. 24. Java API for JSON Processing 1.0 DOM API – JsonReader • Lê JsonObject e JsonArray de algum input – I/O Reader, InputStream (+ encoding) • Possível configurar outras opções • Utiliza um JsonParser plugável // Leitura de um objeto JSON try(JsonReader reader = new JsonReader(io)) { JsonObject obj = reader.readObject(); }33 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  25. 25. Java API for JSON Processing 1.0 DOM API – Writer • Escreve JsonObject e JsonArray para algum output – I/O Writer, OutputStream (+ encoding) • Outras configurações, como “pretty printing” • Utiliza um JsonGenerator plugável // Escreve um objeto JSON try(JsonWriter writer = new JsonWriter(io)) { writer.writeObject(obj); }34 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  26. 26. Java API for WebSocket 1.0 Hello World – POJO/Annotation-driven import javax.websocket.*; @WebSocketEndpoint("/hello") public class HelloBean { @WebSocketMessage public String sayHello(String name) { return “Hello “ + name; } }35 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  27. 27. Java API for WebSocket 1.0 Anotações WebSocket Annotation Level Purpose @WebSocketEndpoint class Torna um POJO em um WebSocket Endpoint @WebSocketClient class Torna um POJO em um WebSocket Client @WebSocketOpen method Intercepta eventos WebSocket Open @WebSocketClose method Intercepta eventos WebSocket Close @WebSocketMessage method Intercepta eventos WebSocket Message @WebSocketPathParam method parameter Marca um segmento de um template de URI @WebSocketError method Intercepta erros durante a conversação36 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  28. 28. Java API for WebSocket 1.0 Atributos do @WebSocketEndpoint value URI relativa ou template de URI ex. “/hello” ou “/chat/{subscriber-level}” decoders lista de decodificadores de mensagens encoders lista de codificadores de mensagens subprotocols lista dos protocolos suportados37 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  29. 29. Java API for WebSocket 1.0 Mensagens customizadas @WebSocketEndpoint( value="/hello", encoders={MyMessage.class}, decoders={MyMessage.class} ) public class MyEndpoint { . . . }38 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  30. 30. Java API for WebSocket 1.0 Mensagens customizadas – Text public class MyMessage implements Decoder.Text<MyMessage>, Encoder.Text<MyMessage> { private JsonObject jsonObject; public MyMessage decode(String s) { jsonObject = new JsonReader(new StringReader(s)).readObject(); return this; } public boolean willDecode(String string) { return true; // Only if can process the payload } public String encode(MyMessage myMessage) { return myMessage.jsonObject.toString(); } } Copyright © 2012, Oracle and/or its affiliates. All rights39 reserved.
  31. 31. Java API for WebSocket 1.0 Mensagens customizadas – Binary public class MyMessage implements Decoder.Binary<MyMessage>, Encoder.Binary<MyMessage> { public MyMessage decode(byte[] bytes) { . . . return this; } public boolean willDecode(byte[] bytes) { . . . return true; // Only if can process the payload } public byte[] encode(MyMessage myMessage) { . . . } }40 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  32. 32. Java API for WebSocket 1.0 URI Template Matching • Um nível somente (1 parâmetro na URL) @WebSocketEndpoint(“/orders/{order-id}”) public class MyEndpoint { @WebSocketMessage public void processOrder( @WebSocketPathParam(“order-id”)String orderId) { . . . } }41 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  33. 33. Java API for WebSocket 1.0 Hello World Client @WebSocketClient public class HelloClient { @WebSocketMessage public void message(String message, Session session) { // process message from server } } WebSocketContainer c = ContainerProvider.getClientContainer(); c.connectToServer(HelloClient.class, “…/hello”);42 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  34. 34. Bean Validation 1.1 Parâmetro de Método e Validação de Resultado public void placeOrder(Built-in @NotNull String productName, @NotNull @Max(“10”) Integer quantity,Custom @Customer String customer) { //. . . } @Future public Date getAppointment() { //. . . } 43 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  35. 35. Batch Applications for the Java Platform 1.0 • Serve para tarefas não-interativas e processos longos • Processamento computacional intensivo • Pode executar sequencial ou paralelo • Pode ser inicializado com: – Chamada adhoc – Agendado • Não há uma API de agendamento incluída44 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  36. 36. Batch Applications for the Java Platform 1.0 Job Specification Language • Define um Job, Steps e direciona a execução • Implementado em XML – Também chamado de “Job XML” • Suporta herança de Job, Step, Flow, e Split49 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  37. 37. Batch Applications for the Java Platform 1.0 Job Specification Language – Exemplo <job id=“myJob”> <step id=“init”> <chunk reader=“R” writer=W” processor=“P” /> <next on=“initialized” to=“process”/> <fail on=“initError”/> </step> <step id=“process”> <batchlet ref=“ProcessAndEmail”/> <end on=”success”/> <fail on=”*” exit-status=“FAILURE”/> </step> </job>50 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  38. 38. Batch Applications for the Java Platform 1.0 Job Specification Language – Chunked<step id=”sendStatements”> @ReadItem <chunk reader=”AccountReader” public Account readAccount() { processor=”AccountProcessor” // read account using JPA writer=”EmailWriter” } chunk-size=”10” /></step> @ProcessItem public Account processAccount(Account account) { // calculate balance } @WriteItems public void sendEmail(List<Account> accounts) { // use JavaMail to send email } 51 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  39. 39. Batch Applications for the Java Platform 1.0 Job Specification Language: Batchlet <step id=”transferFile”> <batchlet ref=“MyFileTransfer” /> </step> @Process public void transferFile(String name) { // Transfer file }52 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  40. 40. Batch Applications for the Java Platform 1.0 Conceitos: Listeners • Job listener: intercepta a execução batch – @BeforeJob, @AfterJob • Step listener – @BeforeStep, @AfterStep • Chunk listener – @BeforeChunk, @AfterChunk, @BeforeCheckpoint, @AfterCheckpoint • Listeners para read/process/write de itens, . . .53 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  41. 41. Java Temporary Caching API 1.0 • API e semântica para cache temporário em memória para objetos Java – Criação de objetos – Acesso compartilhado – Spooling – Invalidez de objetos – Consistência entre diversas JVMs • SPI para implementações55 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  42. 42. Java Temporary Caching API 1.0 Exemplo – Criando um CacheManager CacheManager cacheManager = CacheManagerFactory.getCacheManager(); ou verbosamente CacheManager cacheManager = CacheManagerFactory.getCacheManager(DEFAULT_CACHE_M ANAGER_NAME, Thread.currentThread().getContextClassLoader());60 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  43. 43. Java Temporary Caching API 1.0 Exemplo – Usando o Cache • Obtém um cache do CacheManager Cache<Integer, Date> cache = cacheManager.getCache(“testCache”);61 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  44. 44. Java Temporary Caching API 1.0 Exemplo – Configurando o Cache • Configurar um cache para “read-through” CacheManager cacheManager = getCacheManager(); Cache testCache = cacheManager.createCacheBuilder(“testCache”) .setReadThrough(true) .setSize(Size.UNLIMITED) .setExpiry(Duration.ETERNAL) .build();62 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  45. 45. Java Temporary Caching API 1.0 Exemplo – Colocando um valor no cache Cache<Integer, Date> cache = cacheManager.getCache(cacheName); Integer key = 1; cache.put(key, new Date());63 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  46. 46. Java Temporary Caching API 1.0 Exemplo – Obtendo um valor do cache Cache<Integer, Date> cache = cacheManager.getCache(cacheName); Date value = cache.get(key);64 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  47. 47. Java Temporary Caching API 1.0 Exemplo – Removendo um valor do cache Cache<Integer, Date> cache = cacheManager.getCache(cacheName); Integer key = 1; cache.remove(1);65 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  48. 48. Java Temporary Caching API 1.0 Exemplo – Blog public class BlogManager { @CachePut(cacheName=”blogManager”) public void createEntry( @CacheKeyParam String title, @CacheValue Blog blog) {...} . . .66 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  49. 49. Java Temporary Caching API 1.0 Exemplo – Blog . . . @CacheResult(cacheName="blogManager") public Blog getBlogEntry(String title) {...} @CacheResult(cacheName="blogManager") public Blog getEntryCached( String randomArg, @CacheKeyParam String title) {...} . . .67 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  50. 50. Java Temporary Caching API 1.0 Annotations – Exemplo do Blog . . . @CacheRemoveEntry(cacheName="blogManager") public void removeBlogEntry(String title) {...} @CacheRemoveAll(cacheName="blogManager") public void removeAllBlogs() {...} }68 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  51. 51. Java Temporary Caching API 1.0 Possíveis implementações • Terracotta – Ehcache • Oracle – Coherence • JBoss – Inifinispan • IBM – ExtremeeScale • SpringSorce – Gemfire • Google App Engine – Java memcache client • Spymemcache memcache client69 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  52. 52. Java Persistence API 2.1 • Geração do schema • Persistence Context assíncronos • Converters • Bulk (batch) update/delete usando o Criteria • Acesso padronizado a FUNCTIONS pela API • Acesso padronizado a Stored Procedures pela API70 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  53. 53. Java Persistence API 2.1 Unsynchronized Persistence Contexts • Synchronized: TX aplicada no banco no commit • Unsynchronized: Não fica sincronizada com a TX do JTA até o joinTransaction ser chamado – Não permite escrita no banco de dados – Mas pode chamar: persist, merge, remove, refresh • Funciona tanto gerenciado pelo container quanto pela aplicação • Caso de uso – Conversão de modelagem – Monitorar mudanças na persistência, efetuar commit somente no final76 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  54. 54. Java Persistence API 2.1 Unsynchronized Persistence Contexts Sample @Stateful public class ShoppingCart { @PersistenceContext(type=EXTENDED, synchronization=UNSYNCHRONIZED) EntityManager em; @PersistenceContext EntityManager dataMiningEM; Customer customer; Order order; public void startToShop(Integer custId) { customer = em.find(Customer.class, custId); order = new Order(); }77 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  55. 55. Java Persistence API 2.1 Unsynchronized Persistence Contexts - Exemplo public Collection<Book> viewCart() { // suggest other books based on interests ...} // purchase the books public void confirmOrder() { em.joinTransaction(); customer.addOrder(order); }78 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  56. 56. Java Persistence API 2.1 Stored Procedure Query @Entity @NamedStoredProcedureQuery(name="topGiftsStoredProcedure”, procedureName="Top10Gifts") public class Product { . . . } StoredProcedreQuery query = EntityManager.createNamedStoredProcedureQuery("topGiftsStoredProcedure"); query.registerStoredProcedureParameter(1, String.class, ParameterMode.INOUT); query.setParameter(1, "top10"); query.registerStoredProcedureParameter(2, Integer.class, ParameterMode.IN); query.setParameter(2, 100); // there are other setParameter methods for defining the temporal type . . . query.execute(); String response = query.getOutputParameterValue(1);79 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  57. 57. Java Persistence API 2.1 Update e Delete com Criteria CriteriaUpdate<Customer> q = cb.createCriteriaUpdate(Customer.class); Root<Customer> c = q.from(Customer.class); UPDATE Customer c q.set(c.get(Customer_.status), "outstanding") SET c.status = outstanding .where(cb.lt(c.get(Customer_.balance), 10000)); WHERE c.balance < 10000 . . . @PersistenceContext EntityManager em; Query query = em.createQuery(q); query.executeUpdate(); CriteriaDelete<Customer> q = cb.createCriteriaDelete(Customer.class); Root<Customer> c = q.from(Customer.class); q.where(cb.equal(c.get(Customer_.status), "inactive"), cb.isEmpty(c.get(Customer_.orders))); DELETE FROM Customer c . . . WHERE c.status = inactive AND c.orders IS EMPTY80 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  58. 58. GlassFish RoadmapGlassFish v3 GlassFish Server 3.1 GlassFish Server 3.1.2•Java EE 6 support •Centralized administration •Bug Fixes•Single instance •Clustering / HA •Incremental features•GlassFish Enterprise Mgr •GlassFish Server Control 2009 2010 2011 2012 2013 GlassFish Server 3.0.1 GlassFish Server 3.1.1 GlassFish Server 4 •Oracle branding •Bug fixes •Java EE 7 •Oracle platform support •Updated components •Productivity •Oracle interoperability •Incremental features •HTML5 121 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  59. 59. Transparência • JSRs de Java EE 7 da Oracle estão abertos no java.net – http://javaee-spec.java.net – One project per spec – ex: jpa-spec, jax-rs-spec, jms-spec… • Mensagens de email do EG são públicas • Área de download com acesso público • Issue Tracker com acesso público • Compromisso para atualizar para o JCP 2.8122 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  60. 60. Java EE 7: Status e Agenda• Todas as JSRs estão ativas e em andamento• Todas já publicaram Early Drafts, várias em Public Review• Lançamento em: Q2 2013 123 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  61. 61. Adopt-a-JSR O que é ? • Iniciativa de líderes JUGs para se involverem em JSR • Promover as JSRs para a comunidade Java • O que posso fazer ? – Revisar a spec e os javadocs – Criar aplicações usando a spec beta – Contribuir para a RI, exemplos, docs – Apresentar para JUGs ou conferências – Blog – ...126 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  62. 62. Adopt-a-JSR Como posso começar? – glassfish.org/adoptajsr127 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  63. 63. Adopt-a-JSR JUGs participando do programa128 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  64. 64. Como participar • Java EE 7 Expert Group – javaee-spec.java.net • Java EE 7 Reference Implementation – glassfish.org • The Aquarium – blogs.oracle.com/theaquarium • Adopt-a-JSR – glassfish.org/adoptajsr129 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  65. 65. 130 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×