Upload
bruno-borges
View
1.415
Download
6
Embed Size (px)
DESCRIPTION
A família de tecnologias HTML5 avançou e foi bem longe, comparado com tecnologias rich client e possibilitou clientes Web com cada vez mais capacidade de execução nos navegadores de hoje. Em particular, WebSockets trazem novas oportunidades para a comunicação eficiente peer-to-peer, fornecendo a base para uma nova geração de aplicações web interativas e "ao vivo". Esta sessão examina os esforços com JSR 356 para apoiar WebSocket no modelo de programação Java, a partir de sua integração ao nível de base nos recipientes Java Servlet e Java EE para um novo, API fácil de usar e conjunto de ferramentas que faz parte do padrão plataforma Java.
Citation preview
Criando uma aplicação HTML5 com Java EE 7 e WebSocketsBruno BorgesPrincipal Product ManagerJava Evangelist
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.3
• Java Evangelist• Orale Product Manager• Entusiasta JavaFX e IoT• Onde me encontrar
• @brunoborges
• plus.google.com/+BrunoBorges
Bruno Borges
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.4
Ascenção do Javascript
• O debate cliente ‘leve’ vs cliente ‘pesado’ é antigo...
• Frameworks web server-side mandaram por um tempo (Struts, Spring MVC, JSF)
• Ajax foi uma mudança suave para o client-side (GWT, Vaadin)
• Rich clients estão voltando voltaram, graças ao Javascript/HTML5• Motores Javascript melhoraram muito (V8, SpiderMonkey, Nashorn)
• Melhores ferramentas (jQuery, MV* frameworks, Chrome, Firefox, JavaFX)
• Melhores padrões (CSS3, HTML5, WebSockets, Web Components)
Clientes ricos HTML5
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.5
Arquitetura Rich Client
• Similar a arquiteturas cliente/servidor• Cliente responsável pela UI, input, validacao, lógica e estado
• Server responsável pela lógica de negócio, modelo de domínio, persistência
• Web/HTTP é a cola que conecta client e server
• Protocolos de comunicacao comuns• REST na maioria dos casos
• WebSocket quando precisa de comunicacao full-duplex
• Ferramentas Javascript suportam REST muito bem, mas ainda não WebSocket
• O formato comum (talvez ideal?) de troca de dados é JSON• Java EE é uma ótima plataforma server-side para esta arquitetura
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.6
Java EE + JavascriptPlataforma server-side para suportar apps ricas HTML5/Javascript
Servlet
EJB 3 CDI
Bean
Valid
ation
JavaScript/HTML5
JAX-RS WebSockets JSON-P JAXB
JPA JMS JTA JCA
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.7
JAX-RS
• API de desenvolvimento REST para Java
• Servidor e Client
• Orientada a Annotations, declarativa• @Path, @GET, @POST, @PUT, @DELETE, @PathParam,
@QueryParam, @Produces, @Consumes
• Plugável e extensível• Providers, filters, interceptors
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.8
JAX-RS
@Path("/atm/{cardId}")
public class AtmService {
@GET
@Path("/balance")
@Produces("text/plain")
public String balance(
@PathParam("cardId") String card,
@QueryParam("pin") String pin) {
return Double.toString(getBalance(card, pin));
}
Exemplo 1
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.9
JAX-RS
@POST
@Path("/withdrawal")
@Consumes("text/plain")
@Produces("application/json")
public Money withdraw(
@PathParam("card") String card,
@QueryParam("pin") String pin,
String amount) {
return getMoney(card, pin, amount);
}
}
Exemplo 2
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.10
Java API for WebSocketsJSR 356
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.11
Java API for WebSockets
• Protocolo HTTP é half-duplex
• Gambiarras• Polling
• Long polling
• Streaming
• WebSocket resolve o problema de uma vez por todas• Full-duplex
JSR 356
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.12
Java API for WebSockets
• API declarativa de alto nivel para WebSockets
• Client e server-side
• Pequena e simples, mas completa• @ServerEndpoint, @OnOpen, @OnClose, @OnMessage, @OnError,
Session, Remote
• Plugável e extensível• Encoders, decoders, sub-protocols
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.13
Java API for WebSockets
@ServerEndpoint("/chat")
public class ChatBean {
Set<Session> peers = Collections.synchronizedSet(…);
@OnOpen
public void onOpen(Session peer) {
peers.add(peer);
}
@OnClose
public void onClose(Session peer) {
peers.remove(peer);
}
Exemplo 1
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.14
Java API for WebSockets
@OnMessage
public void message(String message, Session client) {
peers.forEach( p -> p.getRemote().sendObject(message) );
}
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.15
Javascript Movers and Shakers
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.16
Projeto Avatar
• Javascript framework da Oracle
• Javascript no client e no server-side
• Nashorn/JDK8
• Utiliza algumas capacidades do Java EE
• Roda no GlassFish, e em breve no WebLogic também
• Suporte já integrado para REST, WebSocket, Server-Sent Events (SSE)
• Suporte a PhoneGap
• Versão 1.0 já disponível. Bom momento para participar!
avatar.java.net
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.17
Projetos no NetBeans
• Twitter Bootstrap
• HTML5 Boilerplate
• Initializr
• AngularJS
• Mobile Boilerplate
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.18
Demo
• github.com/brunoborges/javaee-javascript
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.19
Conclusão
• Cientes JavaScript/HTML5 conquistando desenvolvedores
• Comunicacao entre cliente e servidor em JSON via REST ou WebSocket
• Java EE funciona muito bem como um backend para clientes ricos Javascript, especialmente com JAX-RS e a Java API para WebSockets, e JSON-P
• JavaScript framework da Oracle – Projeto Avatar
• Você opde usar o código de demonstracão para comecar a explorar estas idéias
• E o mais importante, divirta-se programando! :-)
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.20
• glassfish.org
• Java EE 7
• Suporte a JDK 8
• Projeto Avatar
GlassFish Nightly Builds
GlassFish 4.0.1
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.21
Para saber mais
• Java EE Tutorials• http://docs.oracle.com/javaee/7/tutorial/doc/home.htm
• Outras páginas para iniciar os estudos• http://docs.oracle.com/javaee/7/firstcup/doc/home.htm
• https://glassfish.java.net/hol/
• https://java.net/projects/cargotracker/
• Java EE 7 Transparent Expert Groups• http://javaee-spec.java.net
• The Aquarium (blog Java EE da Oracle)• http://blogs.oracle.com/theaquarium
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.23
The preceding 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.
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.24
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.25