SlideShare a Scribd company logo
Main sponsor




Plataforma Java EE 7: Produtividade & HTML5
Bruno Borges - @brunoborges
Oracle Java EE/Middleware Product Manager
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.
Java EE 6
                                                                 10 Dezembro 2009



3   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




4   Copyright © 2012, Oracle and/or its affiliates. All rights
    reserved.
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 leve
5   Copyright © 2012, Oracle and/or its affiliates. All rights
    reserved.
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 HTML5


6   Copyright © 2012, Oracle and/or its affiliates. All rights
    reserved.
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
  Portable
Extensions
 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.1
Annotations 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)

Connector
Connector                                                                                             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.
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
8   Copyright © 2012, Oracle and/or its affiliates. All rights
    reserved.
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.
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.
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.
Java API for RESTful Web Services 2.0
     Client-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) { }
                     });




12   Copyright © 2012, Oracle and/or its affiliates. All rights
     reserved.
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.
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.
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.
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.
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
                                                                  exceptions

19   Copyright © 2012, Oracle and/or its affiliates. All rights
     reserved.
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 line



20   Copyright © 2012, Oracle and/or its affiliates. All rights
     reserved.
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.
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.
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 formatado




30   Copyright © 2012, Oracle and/or its affiliates. All rights
     reserved.
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.
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 JsonArray



32   Copyright © 2012, Oracle and/or its affiliates. All rights
     reserved.
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.
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.
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.
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ção


36   Copyright © 2012, Oracle and/or its affiliates. All rights
     reserved.
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 suportados




37   Copyright © 2012, Oracle and/or its affiliates. All rights
     reserved.
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.
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 rights
39
     reserved.
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.
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.
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.
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.
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



44   Copyright © 2012, Oracle and/or its affiliates. All rights
     reserved.
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 Split




49   Copyright © 2012, Oracle and/or its affiliates. All rights
     reserved.
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.
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.
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.
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.
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


55   Copyright © 2012, Oracle and/or its affiliates. All rights
     reserved.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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 client

69   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



70   Copyright © 2012, Oracle and/or its affiliates. All rights
     reserved.
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 final


76   Copyright © 2012, Oracle and/or its affiliates. All rights
     reserved.
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.
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.
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.
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 EMPTY

80   Copyright © 2012, Oracle and/or its affiliates. All rights
     reserved.
GlassFish Roadmap
GlassFish 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.
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



122   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




 123   Copyright © 2012, Oracle and/or its affiliates. All rights
       reserved.
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.
Adopt-a-JSR
      Como posso começar? – glassfish.org/adoptajsr




127   Copyright © 2012, Oracle and/or its affiliates. All rights
      reserved.
Adopt-a-JSR
      JUGs participando do programa




128   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

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

More Related Content

PDF
The Java Ee 6 Platform Normandy Jug
PDF
Glassfish Overview Fontys 20090520
PDF
What's new in Java EE 6
PDF
JavaEE 6 and GlassFish v3 at SFJUG
PDF
Java EE 6 & GlassFish 3
PDF
Java EE 6 Hands-on Workshop at Dallas Tech Fest 2010
PPTX
Java EE 7 for Real Enterprise Systems
PDF
Understanding the nuts & bolts of Java EE 6
The Java Ee 6 Platform Normandy Jug
Glassfish Overview Fontys 20090520
What's new in Java EE 6
JavaEE 6 and GlassFish v3 at SFJUG
Java EE 6 & GlassFish 3
Java EE 6 Hands-on Workshop at Dallas Tech Fest 2010
Java EE 7 for Real Enterprise Systems
Understanding the nuts & bolts of Java EE 6

What's hot (19)

PDF
The Java EE 7 Platform: Productivity &amp; HTML5 at San Francisco JUG
PDF
Java EE 6 : Paving The Path For The Future
PDF
Java 7 workshop
PDF
The Java EE 7 Platform: Productivity++ & Embracing HTML5
PDF
Java EE 6 & GlassFish v3: Paving the path for the future - Tech Days 2010 India
PDF
GlassFish REST Administration Backend
PDF
Andrei Niculae - JavaEE6 - 24mai2011
PDF
Java EE 6 and GlassFish portfolio
PDF
Java Summit Chennai: Java EE 7
PDF
S313557 java ee_programming_model_explained_dochez
PDF
GlassFish 3.1 at JCertif 2011
PDF
TDC 2011: OSGi-enabled Java EE Application
PDF
Web Application Architecture
PDF
N(i)2 technical architecture 2.0 (v1 1)
 
PDF
The State of Java under Oracle at JCertif 2011
PDF
The Java EE 7 Platform: Developing for the Cloud
PDF
Java EE 7 at JAX London 2011 and JFall 2011
PDF
TDC 2011: The Java EE 7 Platform: Developing for the Cloud
PDF
Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ Silicon Val...
The Java EE 7 Platform: Productivity &amp; HTML5 at San Francisco JUG
Java EE 6 : Paving The Path For The Future
Java 7 workshop
The Java EE 7 Platform: Productivity++ & Embracing HTML5
Java EE 6 & GlassFish v3: Paving the path for the future - Tech Days 2010 India
GlassFish REST Administration Backend
Andrei Niculae - JavaEE6 - 24mai2011
Java EE 6 and GlassFish portfolio
Java Summit Chennai: Java EE 7
S313557 java ee_programming_model_explained_dochez
GlassFish 3.1 at JCertif 2011
TDC 2011: OSGi-enabled Java EE Application
Web Application Architecture
N(i)2 technical architecture 2.0 (v1 1)
 
The State of Java under Oracle at JCertif 2011
The Java EE 7 Platform: Developing for the Cloud
Java EE 7 at JAX London 2011 and JFall 2011
TDC 2011: The Java EE 7 Platform: Developing for the Cloud
Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ Silicon Val...
Ad

Similar to Plataforma Java EE 7: Produtividade & HTML5 - Parte 1 (20)

PDF
The Java EE 7 Platform: Productivity & HTML5 at JavaOne Latin America 2012
PDF
Arun Gupta: London Java Community: Java EE 6 and GlassFish 3
PDF
Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ JAX London ...
PDF
Java EE 6 Component Model Explained
PDF
Spark IT 2011 - Java EE 6 Workshop
PDF
Java EE 6 Aquarium Paris
PDF
Java E
PDF
Java EE6 Overview
PDF
Jcp adopt jsr
PDF
Whats New In Java Ee 6
PDF
Vaadin 7 - Java Enterprise Edition integration
PDF
Java EE 6 & GlassFish = Less Code + More Power at CEJUG
PDF
Java EE 6 = Less Code + More Power
PDF
Java EE 6 & GlassFish = Less Code + More Power @ DevIgnition
PDF
Java EE 6 & GlassFish v3: Paving the path for the future - Spark IT 2010
PDF
JBoss AS7 Reloaded
PDF
JBoss AS / EAP and Java EE6
PDF
Java EE 6 & GlassFish v3 at Vancouver JUG, Jan 26, 2010
PDF
Sun Java EE 6 Overview
The Java EE 7 Platform: Productivity & HTML5 at JavaOne Latin America 2012
Arun Gupta: London Java Community: Java EE 6 and GlassFish 3
Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ JAX London ...
Java EE 6 Component Model Explained
Spark IT 2011 - Java EE 6 Workshop
Java EE 6 Aquarium Paris
Java E
Java EE6 Overview
Jcp adopt jsr
Whats New In Java Ee 6
Vaadin 7 - Java Enterprise Edition integration
Java EE 6 & GlassFish = Less Code + More Power at CEJUG
Java EE 6 = Less Code + More Power
Java EE 6 & GlassFish = Less Code + More Power @ DevIgnition
Java EE 6 & GlassFish v3: Paving the path for the future - Spark IT 2010
JBoss AS7 Reloaded
JBoss AS / EAP and Java EE6
Java EE 6 & GlassFish v3 at Vancouver JUG, Jan 26, 2010
Sun Java EE 6 Overview
Ad

More from Bruno Borges (20)

PDF
Secrets of Performance Tuning Java on Kubernetes
PDF
[Outdated] Secrets of Performance Tuning Java on Kubernetes
PDF
From GitHub Source to GitHub Release: Free CICD Pipelines For JavaFX Apps
PDF
Making Sense of Serverless Computing
PPTX
Visual Studio Code for Java and Spring Developers
PDF
Taking Spring Apps for a Spin on Microsoft Azure Cloud
PDF
A Look Back at Enterprise Integration Patterns and Their Use into Today's Ser...
PPTX
Melhore o Desenvolvimento do Time com DevOps na Nuvem
PPTX
Tecnologias Oracle em Docker Containers On-premise e na Nuvem
PPTX
Java EE Arquillian Testing with Docker & The Cloud
PPTX
Migrating From Applets to Java Desktop Apps in JavaFX
PDF
Servidores de Aplicação: Por quê ainda precisamos deles?
PDF
Build and Monitor Cloud PaaS with JVM’s Nashorn JavaScripts [CON1859]
PDF
Cloud Services for Developers: What’s Inside Oracle Cloud for You? [CON1861]
PDF
Booting Up Spring Apps on Lightweight Cloud Services [CON10258]
PDF
Java EE Application Servers: Containerized or Multitenant? Both! [CON7506]
PDF
Running Oracle WebLogic on Docker Containers [BOF7537]
PPTX
Lightweight Java in the Cloud
PDF
Tweet for Beer - Beertap Powered by Java Goes IoT, Cloud, and JavaFX
PDF
Integrando Oracle BPM com Java EE e WebSockets
Secrets of Performance Tuning Java on Kubernetes
[Outdated] Secrets of Performance Tuning Java on Kubernetes
From GitHub Source to GitHub Release: Free CICD Pipelines For JavaFX Apps
Making Sense of Serverless Computing
Visual Studio Code for Java and Spring Developers
Taking Spring Apps for a Spin on Microsoft Azure Cloud
A Look Back at Enterprise Integration Patterns and Their Use into Today's Ser...
Melhore o Desenvolvimento do Time com DevOps na Nuvem
Tecnologias Oracle em Docker Containers On-premise e na Nuvem
Java EE Arquillian Testing with Docker & The Cloud
Migrating From Applets to Java Desktop Apps in JavaFX
Servidores de Aplicação: Por quê ainda precisamos deles?
Build and Monitor Cloud PaaS with JVM’s Nashorn JavaScripts [CON1859]
Cloud Services for Developers: What’s Inside Oracle Cloud for You? [CON1861]
Booting Up Spring Apps on Lightweight Cloud Services [CON10258]
Java EE Application Servers: Containerized or Multitenant? Both! [CON7506]
Running Oracle WebLogic on Docker Containers [BOF7537]
Lightweight Java in the Cloud
Tweet for Beer - Beertap Powered by Java Goes IoT, Cloud, and JavaFX
Integrando Oracle BPM com Java EE e WebSockets

Recently uploaded (20)

PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
PDF
NewMind AI Weekly Chronicles – August ’25 Week III
PDF
Univ-Connecticut-ChatGPT-Presentaion.pdf
PPT
Geologic Time for studying geology for geologist
PDF
Architecture types and enterprise applications.pdf
PDF
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
PPTX
Web Crawler for Trend Tracking Gen Z Insights.pptx
PPTX
Final SEM Unit 1 for mit wpu at pune .pptx
PDF
Transform Your ITIL® 4 & ITSM Strategy with AI in 2025.pdf
PDF
A comparative study of natural language inference in Swahili using monolingua...
DOCX
search engine optimization ppt fir known well about this
PDF
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
PPTX
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
PDF
DP Operators-handbook-extract for the Mautical Institute
PDF
TrustArc Webinar - Click, Consent, Trust: Winning the Privacy Game
PDF
Taming the Chaos: How to Turn Unstructured Data into Decisions
PDF
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
PDF
Hindi spoken digit analysis for native and non-native speakers
PDF
1 - Historical Antecedents, Social Consideration.pdf
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
NewMind AI Weekly Chronicles – August ’25 Week III
Univ-Connecticut-ChatGPT-Presentaion.pdf
Geologic Time for studying geology for geologist
Architecture types and enterprise applications.pdf
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
Web Crawler for Trend Tracking Gen Z Insights.pptx
Final SEM Unit 1 for mit wpu at pune .pptx
Transform Your ITIL® 4 & ITSM Strategy with AI in 2025.pdf
A comparative study of natural language inference in Swahili using monolingua...
search engine optimization ppt fir known well about this
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
DP Operators-handbook-extract for the Mautical Institute
TrustArc Webinar - Click, Consent, Trust: Winning the Privacy Game
Taming the Chaos: How to Turn Unstructured Data into Decisions
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
Hindi spoken digit analysis for native and non-native speakers
1 - Historical Antecedents, Social Consideration.pdf

Plataforma Java EE 7: Produtividade & HTML5 - Parte 1

  • 1. Main sponsor Plataforma Java EE 7: Produtividade & HTML5 Bruno Borges - @brunoborges Oracle Java EE/Middleware Product Manager
  • 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. Java EE 6 10 Dezembro 2009 3 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 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 EE 4 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 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 leve 5 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 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 HTML5 6 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 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 Portable Extensions 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.1 Annotations 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) Connector Connector 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. 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 8 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 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. 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. 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. Java API for RESTful Web Services 2.0 Client-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) { } }); 12 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 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. 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. 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. 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. 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 exceptions 19 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 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 line 20 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 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. 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. 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 formatado 30 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 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. 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 JsonArray 32 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 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. 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. 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. 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ção 36 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 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 suportados 37 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 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. 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 rights 39 reserved.
  • 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. 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. 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. 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. 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 44 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 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 Split 49 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 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. 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. 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. 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. 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 55 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 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. 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. 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. 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. 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. 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. 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. 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. 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. 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 client 69 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 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 API 70 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 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 final 76 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 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. 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. 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. 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 EMPTY 80 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 58. GlassFish Roadmap GlassFish 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. 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 122 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 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. 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. Adopt-a-JSR Como posso começar? – glassfish.org/adoptajsr 127 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 63. Adopt-a-JSR JUGs participando do programa 128 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 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/adoptajsr 129 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 65. 130 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.