Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

65
Main sponsor Plataforma Java EE 7: Produtividade & HTML5 Bruno Borges - @brunoborges Oracle Java EE/Middleware Product Manager

description

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

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

Page 1: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

Main sponsor

Plataforma Java EE 7: Produtividade & HTML5

Bruno Borges - @brunoborgesOracle Java EE/Middleware Product Manager

Page 2: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

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.

Page 3: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java EE 610 Dezembro 2009

Page 4: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

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 EE

Page 5: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Top 10 Features do Java EE 6

1. EJB dentro de um WAR2. Injeção de Dependência type-safe3. Descritores de Deploy opcionais (web.xml, faces-config.xml)

4. JSF padronizado com Facelets5. Uma única classe por EJB6. Pontos de Extensão para Servlets e CDI7. Eventos CDI8. API de EJBContainer9. Anotação @Schedule baseado em cron10.Profile Web para desenvolvimento Java EE leve

Page 6: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Escopo do Java EE 7Produtividade e HTML5

• Mais Produtividade– Menos código “boilerplate”– Funcionalidades mais ricas– Mais padrões e convenções

• Suporte ao HTML5– WebSocket– JSON– Formulários HTML5

Page 7: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java EE 7 –JSRs Candidatas

Connector 1.6

Connector 1.6

Managed Beans 1.0Managed Beans 1.0 EJB 3.2EJB 3.2

Servlet 3.1Servlet 3.1

PortableExtensionsPortable

Extensions

JSF 2.2JSF 2.2 JAX-RS 2.0

JAX-RS 2.0

JMS 2.0JMS 2.0JPA 2.1JPA 2.1

EL 3.0EL 3.0

JTA 1.2JTA 1.2

JSP 2.2JSP 2.2

Interceptors 1.1Interceptors 1.1 CDI 1.1CDI 1.1Common Annotations 1.1

Common Annotations 1.1

AtualizaçãoNova Versão

Novo

Java Caching API(JSR 107)

Java Caching API(JSR 107)

Java API for WebSocket(JSR 356)

Java API for WebSocket(JSR 356)

Batch Applications(JSR 352)

Batch Applications(JSR 352)

Java API for JSON(JSR 353)

Java API for JSON(JSR 353)

Concurrency Utilities(JSR 236)

Concurrency Utilities(JSR 236)

Page 8: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

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

Page 9: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java API for RESTful Web Services 2.0Client 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) { //. . .}

Page 10: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java API for RESTful Web Services 2.0Client API - Agora

// Obtém instância do ClientClient client = ClientFactory.newClient(); // Obtém nome do cliente para o produto enviadoString name = client.target(“../orders/{orderId}/customer”) .resolveTemplate(”orderId", ”10”) .queryParam(”shipped", ”true”) .request() .get(String.class);

Page 11: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java API for RESTful Web Services 2.0Client API - Agora

// Sacar dinheiroMoney mon = client.target("http://.../atm/{cardId}/withdrawal") .resolveTemplate("cardId", "111122223333") .queryParam("pin", "9876") .request("application/json") .post(text("50.0"), Money.class);

Page 12: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java API for RESTful Web Services 2.0Client-side Async

Client 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) { } });

Page 13: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java API for RESTful Web Services 2.0Server-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); }}); }}

Page 14: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java API for RESTful Web Services 2.0Pré-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); …}

Page 15: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java Message Service 2.0Enviando 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); } finally { connection.close(); } } catch (JMSException ex) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); }}

13 LDCs só pra enviar a msg

Page 16: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java Message Service 2.0API simplificada para fechar objetos JMS

@Resource(lookup = "jms/connFactory")ConnectionFactory cf;

@Resource(lookup="jms/inboundQueue")Destination dest; 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); producer.send(mess); } catch(JMSException e){ // exception handling }}

Uso do bloco try-with-resources

close() é chamado automaticamente

Page 17: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java Message Service 2.0Introdução do JMSContext e JMSProducer

@Resource(lookup = "java:global/jms/demoConnectionFactory")ConnectionFactory connectionFactory;

@Resource(lookup = "java:global/jms/demoQueue")Queue demoQueue; public void sendMessage (String payload) { try (JMSContext context = connectionFactory.createContext();){ context.createProducer().send(demoQueue, payload); } catch (JMSRuntimeException ex) { // exception handling }}

close() é chamado automaticamente

JMSContext combina Connection e Session

Mensagem enviadadiretamente

Sem checked exceptions

Page 18: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java Message Service 2.0

@InjectJMSContext context;

@Resource(lookup = "java:global/jms/demoQueue”)Queue demoQueue;

public void sendMessage(String payload) { context.createProducer().send(demoQueue, payload);}

Definição padrão de recursosDefinição de recurso

ou@JmsConnectionFactory

13 linhas 1 line

Page 19: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java API for JSON Processing 1.0

• 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, ...

Streaming API – JsonParser e JsonGenerator

Page 20: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

{

"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”

Java API for JSON Processing 1.0Streaming API – JsonParser

Page 21: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java API for JSON Processing 1.0

• JsonGenerator– Gera JSON no modo streaming

• Similar ao XMLStreamWriter do StaX

– Como criar• Json.createGenerator(…)• Json.createGeneratorFactory().createGenerator(…)

– Funcionalidades adicionais• Ex: código gerado formatado

Streaming API – JsonParser e JsonGenerator

Page 22: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java API for JSON Processing 1.0Streaming API – JsonGenerator

"phoneNumber": [ { "type": "home", "number": ”408-123-4567” }, { "type": ”work", "number": ”408-987-6543” } ]

JsonGenerator jg = Json.createGenerator(…);

jg. .beginArray("phoneNumber") .beginObject() .add("type", "home") .add("number", "408-123-4567") .endObject() .beginObject() .add("type", ”work") .add("number", "408-987-6543") .endObject() .endArray();jg.close();

Page 23: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java API for JSON Processing 1.0

• 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 JsonArray

Object Model API

Page 24: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java API for JSON Processing 1.0DOM 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();

}

Page 25: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java API for JSON Processing 1.0DOM 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);

}

Page 26: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java API for WebSocket 1.0Hello World – POJO/Annotation-drivenimport javax.websocket.*;

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

@WebSocketMessage public String sayHello(String name) { return “Hello “ + name; }}

Page 27: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java API for WebSocket 1.0Anotaçõ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ção

Page 28: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java API for WebSocket 1.0Atributos do @WebSocketEndpoint

value URI relativa ou template de URIex. “/hello” ou “/chat/{subscriber-level}”

decoders lista de decodificadores de mensagens

encoders lista de codificadores de mensagens

subprotocols lista dos protocolos suportados

Page 29: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java API for WebSocket 1.0

@WebSocketEndpoint( value="/hello", encoders={MyMessage.class}, decoders={MyMessage.class})public class MyEndpoint { . . .}

Mensagens customizadas

Page 30: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java API for WebSocket 1.0

public class MyMessage implements Decoder.Text<MyMessage>, Encoder.Text<MyMessage> { private JsonObject jsonObject;

public MyMessage decode(String s) { jsonObject = new JsonReader(new StringReader(s)).readObject(); return this;

}

public boolean willDecode(String string) { return true; // Only if can process the payload }

public String encode(MyMessage myMessage) { return myMessage.jsonObject.toString(); }}

Mensagens customizadas – Text

Page 31: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java API for WebSocket 1.0

public class MyMessage implements Decoder.Binary<MyMessage>, Encoder.Binary<MyMessage> {

public MyMessage decode(byte[] bytes) { . . . return this;

}

public boolean willDecode(byte[] bytes) { . . . return true; // Only if can process the payload }

public byte[] encode(MyMessage myMessage) { . . . }}

Mensagens customizadas – Binary

Page 32: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java API for WebSocket 1.0

• Um nível somente (1 parâmetro na URL)

URI Template Matching

@WebSocketEndpoint(“/orders/{order-id}”)public class MyEndpoint { @WebSocketMessage public void processOrder( @WebSocketPathParam(“order-id”)String orderId) { . . . }}

Page 33: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java API for WebSocket 1.0

@WebSocketClientpublic class HelloClient { @WebSocketMessage public void message(String message, Session session) { // process message from server }}

WebSocketContainer c = ContainerProvider.getClientContainer();c.connectToServer(HelloClient.class, “…/hello”);

Hello World Client

Page 34: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Bean Validation 1.1Parâmetro de Método e Validação de Resultado

Built-in

Custom

@Futurepublic Date getAppointment() { //. . .}

public void placeOrder( @NotNull String productName, @NotNull @Max(“10”) Integer quantity, @Customer String customer) { //. . .}

Page 35: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

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ída

Page 36: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Batch Applications for the Java Platform 1.0

• 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 Split

Job Specification Language

Page 37: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Batch Applications for the Java Platform 1.0

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

Job Specification Language – Exemplo

Page 38: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Batch Applications for the Java Platform 1.0

<step id=”sendStatements”> <chunk reader=”AccountReader” processor=”AccountProcessor” writer=”EmailWriter” chunk-size=”10” /></step>

@ReadItempublic Account readAccount() { // read account using JPA}

@ProcessItempublic Account processAccount(Account account) { // calculate balance}

@WriteItemspublic void sendEmail(List<Account> accounts) { // use JavaMail to send email}

Job Specification Language – Chunked

Page 39: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Batch Applications for the Java Platform 1.0

<step id=”transferFile”> <batchlet ref=“MyFileTransfer” /></step>

@Processpublic void transferFile(String name) { // Transfer file}

Job Specification Language: Batchlet

Page 40: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Batch Applications for the Java Platform 1.0Conceitos: 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, . . .

Page 41: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

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ções

Page 42: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java Temporary Caching API 1.0

CacheManager cacheManager = CacheManagerFactory.getCacheManager();

ou verbosamente

CacheManager cacheManager = CacheManagerFactory.getCacheManager(DEFAULT_CACHE_MANAGER_NAME, Thread.currentThread().getContextClassLoader());

Exemplo – Criando um CacheManager

Page 43: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java Temporary Caching API 1.0

• Obtém um cache do CacheManager

Cache<Integer, Date> cache = cacheManager.getCache(“testCache”);

Exemplo – Usando o Cache

Page 44: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java Temporary Caching API 1.0

• Configurar um cache para “read-through”

CacheManager cacheManager = getCacheManager();Cache testCache = cacheManager.createCacheBuilder(“testCache”) .setReadThrough(true) .setSize(Size.UNLIMITED) .setExpiry(Duration.ETERNAL) .build();

Exemplo – Configurando o Cache

Page 45: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java Temporary Caching API 1.0

Cache<Integer, Date> cache = cacheManager.getCache(cacheName);Integer key = 1;cache.put(key, new Date());

Exemplo – Colocando um valor no cache

Page 46: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java Temporary Caching API 1.0

Cache<Integer, Date> cache = cacheManager.getCache(cacheName);Date value = cache.get(key);

Exemplo – Obtendo um valor do cache

Page 47: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java Temporary Caching API 1.0

Cache<Integer, Date> cache = cacheManager.getCache(cacheName);Integer key = 1;cache.remove(1);

Exemplo – Removendo um valor do cache

Page 48: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java Temporary Caching API 1.0

public class BlogManager {

@CachePut(cacheName=”blogManager”) public void createEntry( @CacheKeyParam String title, @CacheValue Blog blog) {...}

. . .

Exemplo – Blog

Page 49: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java Temporary Caching API 1.0

. . .

@CacheResult(cacheName="blogManager") public Blog getBlogEntry(String title) {...}

@CacheResult(cacheName="blogManager") public Blog getEntryCached( String randomArg, @CacheKeyParam String title) {...}

. . .

Exemplo – Blog

Page 50: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java Temporary Caching API 1.0

. . .

@CacheRemoveEntry(cacheName="blogManager") public void removeBlogEntry(String title) {...}

@CacheRemoveAll(cacheName="blogManager") public void removeAllBlogs() {...}

}

Annotations – Exemplo do Blog

Page 51: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java Temporary Caching API 1.0

• Terracotta – Ehcache

• Oracle – Coherence

• JBoss – Inifinispan

• IBM – ExtremeeScale

• SpringSorce – Gemfire

• Google App Engine – Java memcache client

• Spymemcache memcache client

Possíveis implementações

Page 52: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

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 API

Page 53: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java Persistence API 2.1

• 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 final

Unsynchronized Persistence Contexts

Page 54: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java Persistence API 2.1Unsynchronized 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(); }

Page 55: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java Persistence API 2.1Unsynchronized Persistence Contexts - Exemplo

public Collection<Book> viewCart() {

// suggest other books based on interests

...}

// purchase the books

public void confirmOrder() {

em.joinTransaction();

customer.addOrder(order);

}

Page 56: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java Persistence API 2.1Stored 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);

Page 57: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Java Persistence API 2.1Update e Delete com CriteriaCriteriaUpdate<Customer> q = cb.createCriteriaUpdate(Customer.class); Root<Customer> c = q.from(Customer.class); q.set(c.get(Customer_.status), "outstanding") .where(cb.lt(c.get(Customer_.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)));. . .

UPDATE Customer cSET c.status = 'outstanding'WHERE c.balance < 10000

DELETE FROM Customer cWHERE c.status = 'inactive'AND c.orders IS EMPTY

Page 58: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

GlassFish Roadmap

20092009 20102010 20112011

GlassFish Server 3.1.2•Bug Fixes•Incremental features

GlassFish Server 3.1.2•Bug Fixes•Incremental features

GlassFish Server 3.1•Centralized administration•Clustering / HA•GlassFish Server Control

GlassFish Server 3.1•Centralized administration•Clustering / HA•GlassFish Server Control

20122012

GlassFish Server 4•Java EE 7•Productivity•HTML5

GlassFish Server 4•Java EE 7•Productivity•HTML5

GlassFish v3•Java EE 6 support•Single instance•GlassFish Enterprise Mgr

GlassFish v3•Java EE 6 support•Single instance•GlassFish Enterprise Mgr

GlassFish Server 3.0.1•Oracle branding•Oracle platform support•Oracle interoperability

GlassFish Server 3.0.1•Oracle branding•Oracle platform support•Oracle interoperability

GlassFish Server 3.1.1•Bug fixes•Updated components•Incremental features

GlassFish Server 3.1.1•Bug fixes•Updated components•Incremental features

20132013

Page 59: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

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

Page 60: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

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

Page 61: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Adopt-a-JSR

• 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– . . .

O que é ?

Page 62: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Adopt-a-JSRComo posso começar? – glassfish.org/adoptajsr

Page 63: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

Adopt-a-JSRJUGs participando do programa

Page 64: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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

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/adoptajsr

Page 65: Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

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