javaone 2012 using java with html5 and css3

35
Using Java with HTML5 and CSS3 (+ the whole HTML5 world: WebSockets, SVG, etc...) Helder da Rocha Independent Java & Web professional Argo Navis Informatica Ltda. São Paulo, Brazil [email protected]

Upload: helder-da-rocha

Post on 07-Aug-2015

50 views

Category:

Technology


1 download

TRANSCRIPT

Page 1: JavaONE 2012 Using Java with HTML5 and CSS3

Using Java with HTML5 and CSS3

(+ the whole HTML5 world: WebSockets, SVG, etc...)

Helder da RochaIndependent Java & Web professional

Argo Navis Informatica Ltda. São Paulo, [email protected]

Page 2: JavaONE 2012 Using Java with HTML5 and CSS3

Agenda

• A short introduction to some cool HTML5 features

• Some ideas about how to explore the power of HTML5 in Java Web apps

Page 3: JavaONE 2012 Using Java with HTML5 and CSS3

Who am I?

h"p://www.youtube.com/watch?v=jHteVqfKhNo  

Java,  Web,  iOS  programmer,  consultant,  instructor  Java  enthusiast  since  1995  (also  actor,  musician  and  visual  arLst  :)  From  Brazil

Page 4: JavaONE 2012 Using Java with HTML5 and CSS3

Java & HTML: old friends

• 1995: Applets running inside HotJava & Netscape browsers

• Client-side Java

• First attempt at rich interactive interfaces

• Before applets there was no such thing as animation and interactivity on the Web

• Scripting and Netscape extensions allowed Java-HTML communication

Page 5: JavaONE 2012 Using Java with HTML5 and CSS3

Today

• Proprietary solutions like Flash became de facto standards for interactive client-side apps

• Java became popular for server-side apps

• Many tasks that would fit better on the client-side are still done on the server-side because of inconsistent browser support

Page 6: JavaONE 2012 Using Java with HTML5 and CSS3

HTML5

• Still a versioned spec under W3C, but a versionless dynamic spec under WHAT-WG (Web Hypertext Application Technology Working Group)

• Has among its goals to simplify HTML code and drastically reduce the need for scripting and plugins

• Deals not only with graphical aspects and structure, but also with networking, multithreading, storage, etc. (which are no longer part of the official spec)

Page 7: JavaONE 2012 Using Java with HTML5 and CSS3

HTML5 is not just HTML

• The “HTML5 solution” includes

• CSS, JavaScript, audio & video, vector graphics

• But also Web sockets, geolocation, offline cache, Web workers, client-side database, local storage, etc.

• More than just graphical technologies

Page 8: JavaONE 2012 Using Java with HTML5 and CSS3

JSF support?

• There is not yet any official support for HTML5 from HTML-generating frameworks such as JSF

• HTML5 support is expected for JSF 2.2 (Java EE 7)

• But any server-side Java apps can use data sent by HTML5 client-side apps

Page 9: JavaONE 2012 Using Java with HTML5 and CSS3

Some cool graphical features

• HTML5 Canvas

• WebGL

• CSS3 animations and transitions

• SVG

• Audio and video control

Page 10: JavaONE 2012 Using Java with HTML5 and CSS3

HTML5 Canvas• API-based vector graphics

1. Place the <canvas> element somewhere (or create it via scripting) <canvas id=”mycanvas” width=”200″ height=”200″/>

2. Change its style if you wish <style> canvas {border: solid black 1px} </style>

3. Get the 2D context var acanvas = document.getElementById("mycanvas"); var ctx = acanvas.getContext("2d");

4. Use the API to paint your canvas ctx.fillStyle = "rgb(255,0,0)”; ctx.fillRect(50, 50, 100, 100);

Page 11: JavaONE 2012 Using Java with HTML5 and CSS3

WebGL: 3D animations• Not really HTML5, but built on Canvas

Page 12: JavaONE 2012 Using Java with HTML5 and CSS3

Saving and retrieving graphics

• Server-side applications can be used to save the state of HTML5 graphics

• Serializing Canvas or SVG to the server

• Saving parameters that were changed by the user

• Saved state may be recovered later and be used to restore page

• Ex: collaborative images, signatures, etc.

Page 13: JavaONE 2012 Using Java with HTML5 and CSS3

Saving the state of the canvas• You can use a Java server-side app to save

the state of a canvas drawn by the client

• Canvas can be converter to image via API methods (toDataUrl())

Canvas

Servlet

Page 14: JavaONE 2012 Using Java with HTML5 and CSS3

CSS3 transforms

• 2D and 3D transforms on any element: scale, translate, rotate, etc.

• Can be combined with animations and transitions

• Sophisticated effects can be obtained with no scripting at all

Page 15: JavaONE 2012 Using Java with HTML5 and CSS3

CSS3 animations• Declarative transitions, 3D animations and

effects like shadows, reflections, etc.

• Reduces the need for scripting#frente { position:absolute; top: 0px; left: 0px; -webkit-transform: translateZ(10px) scaleZ(1.2) scale(0.5); -webkit-transform-style: preserve-3d;}#verso { position:absolute; top: 0px; left: 0px; -webkit-transform: translateZ(-10px) scaleZ(1.2) scale(0.5); -webkit-transform-style: preserve-3d;}#cena { -webkit-animation: flip 8s infinite linear; -webkit-transform-style: preserve-3d;}

@-webkit-keyframes flip { from { -webkit-transform: rotateY(0deg);} to {-webkit-transform: rotateY(-360deg);}}

Page 16: JavaONE 2012 Using Java with HTML5 and CSS3

SVG - Scalable Vector Graphics• W3C XML standard initially based on Microsoft

VML and Adobe PostScript

• Initially supported by Adobe and Microsoft

• Can be embedded in HTML or linked via the <img> element

<?xml  version="1.0"  encoding="UTF-­‐8"?><svg  xmlns="http://www.w3.org/2000/svg"            width="100%"  height="100%">        <circle  r="50"  cx="100"  cy="100"  fill="green"/>          <circle  r="50"  cx="125"  cy="125"  fill="green"                                                                            fill-­‐opacity="0.5"/>          <circle  r="50"  cx="150"  cy="150"  fill="green"                                                                            fill-­‐opacity="0.2"/>  </svg>

Page 17: JavaONE 2012 Using Java with HTML5 and CSS3

Saving SVG

• It is not as easy as saving Canvas, since it requires serializing by third-party client-side XML processors which are browser-dependent (need to save the DOM tree)

• But you can easily collect data from the client side and generate SVG on the server side

• Frameworks like Apache Batik can also convert SVG to images

Page 18: JavaONE 2012 Using Java with HTML5 and CSS3

SVG generation

• Since SVG is XML, it can be generated on the server-side using XML authoring APIs,

• Can also be generated a a template by vector software (like Illustrator) and later modified (inserting DOM nodes, removing, reordering, etc.)

Page 19: JavaONE 2012 Using Java with HTML5 and CSS3

Generating SVG through XSLT and Java

SVG template

XSLT

Java component

javax.xml APIs

SVG for embedding

Parameters

PNG, PDF

Page 20: JavaONE 2012 Using Java with HTML5 and CSS3

Servlet-generated SVG

Page 21: JavaONE 2012 Using Java with HTML5 and CSS3

Other features

• Web database

• Local storage

• Web workers

• Web sockets

• Geolocation

Page 22: JavaONE 2012 Using Java with HTML5 and CSS3

Web storage• Safer local and session storage objects

• Two objects which accept any properties: localStorage and sessionStorage

• Ex: localStorage.field = “Hi!”;

• localStorage is not shared among tabs or windows.

• You can’t insert data into them directly from the server (it has to be via scripting)

Page 23: JavaONE 2012 Using Java with HTML5 and CSS3

Client-side database

var db = openDatabase('mydb', '1.0', 'hellodb', 2 * 1024 * 1024);

db.transaction( function (tx) { tx.executeSql( 'CREATE TABLE IF NOT EXISTS

mytable(id unique, name)'); tx.executeSql( 'INSERT INTO mytable(id, name) VALUES (1, ”Jack")'); }

);

• For applications which require a lot of structured offline data (ex: animations)

Page 24: JavaONE 2012 Using Java with HTML5 and CSS3

Web workers• Threading API for JavaScript

• Create thread code in a JS file, and attach it to a Worker object var worker = new Worker(“worker.js”);

• Attach a listener function worker.onmessage = function(evt) {

alert(evt.data); };

• Send an asynchronous messageworker.postMessage(“data”);

Page 25: JavaONE 2012 Using Java with HTML5 and CSS3

Geolocation

• Uses the navigator object to store geolocation coordinates

position.coords.latitude & longitude

• Once collected, you can send them anywhere

• Ex: if you send them to a Java server-side application, they can be used to generate an SVG map, for example.

Page 26: JavaONE 2012 Using Java with HTML5 and CSS3

Web Sockets

• A completely new protocol that uses HTTP as a bootstrap

• Also has an IETF spec: RFC 6455

• Allows real-time bidirectional communication (like Comet)

• Requires support from both the server-side and the client-side

Page 27: JavaONE 2012 Using Java with HTML5 and CSS3

Protocol• Starts with an HTTP handshake via headers

• After communication is established, data packets can be exchanged

• Packet format is defined by the protocol spec

GET /mychat HTTP/1.1Host: server.example.comUpgrade: websocketConnection: UpgradeSec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==Sec-WebSocket-Protocol: chatSec-WebSocket-Version: 13Origin: http://example.com

HTTP/1.1 101 Switching ProtocolsUpgrade: websocketConnection: UpgradeSec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=Sec-WebSocket-Protocol: chat

Page 28: JavaONE 2012 Using Java with HTML5 and CSS3

WebSocket API• Interface

WebSocket(url, [protocols])

• Eventsonopenonerroroncloseonmessage

• States0 – CONNECTING 1 – OPEN 2 – CLOSING 3 - CLOSED

• Methodssend(String | blob | arraybuffer )close()

Page 29: JavaONE 2012 Using Java with HTML5 and CSS3

Client  JavaScript  API• How  to  use  it  (client-­‐side)

var  ws  =  new  WebSocket("ws://localhost:8080/myapp");  

ws.onopen  =  funcLon(event)  {     alert("Opened  connecLon!");    }  ws.onmessage  =  funcLon(event)  {     alert("Message:  "  +  event.data);  }  ws.onclose  =  funcLon(event)  {        alert("Closed  connecLon!");        }  

ws.send("Hello  World!");

send()  method

Event  handlers

WebSocket  object

Page 30: JavaONE 2012 Using Java with HTML5 and CSS3

What about the server side?

• Still no standard. But there should be one soon (JSR 356 + Java EE 7)

• You can write your own WebSocket server, of course (study the protocol and handle it with a java.net.ServerSocket or javax.servlet implementation)

• You can use Glassfish+Grizzly, Jetty, JBoss, or some other proprietary solution

Page 31: JavaONE 2012 Using Java with HTML5 and CSS3

Battleship Client-side

var ws; function initWS() { ws = new WebSocket("ws://localhost:8080/../WSBattleship"); ws.onmessage = function(event) { if (gameStarted) { var msg = event.data.split(":"); if (msg[0] != playerId) { hitOrMiss(msg[1], msg[2]); } } alert(event.data); } } function hitOrMiss(coords, event) { if (event == 0) { markMiss(coords); } else { markHit(coords); } } function shoot(ship) { if (gameStarted && !gameFinished) { ws.send(playerId + ":" + shotPosition); } } function addShip(ship) { if (!gameStarted && totalShips < maxShips) { ships[totalShips++] = ship.id; ship.style.fill = "red"; } if (totalShips == maxShips) { ready = true; ws.send(playerId); // ready signal! } }

Page 32: JavaONE 2012 Using Java with HTML5 and CSS3

WebSockets  app  using  Grizzly• Write the component & socket

• Register the component using a servletpublic class MyServlet extends HttpServlet {

public void init(ServletConfig config) throws ServletException { WebSocketEngine.getEngine().register(new BattleShipComponent());

}}

public class BattleShipComponent extends WebSocketApplication {public WebSocket createSocket(WebSocketListener... listeners) {

return new BattleShipSocket(listeners);}public void onMessage(WebSocket socket, String data) {

String gameData = data.split(":");...

}} public class BattleShipSocket extends BaseServerWebSocket {

public BattleShipSocket(WebSocketListener... listeners) {super(listeners);

} }

Page 33: JavaONE 2012 Using Java with HTML5 and CSS3

WebSockets: battleship

WS Component

WebSocket

WebSocket

Servlet WebSocket Engine

1:a2

Text

Grizzly 1.9 + Glassfish 3.1.2

Page 34: JavaONE 2012 Using Java with HTML5 and CSS3

Summary• Although there is no official support for HTML5 in Java

Web technologies such as JSF (expected for Java EE 7), Java server-side apps can enhance client-side HTML5 apps

• Information collected by HTML5 can be used as parameters for server-side processing, where many Java APIs can be used

• SVG can be easily generated on the server-side and embedded into HTML pages

• Canvas (and SVG) can be serialized and stored on the server

• WebSocket applications require server-side support. Currently there are several Java-based proprietary solutions. JSR 356 aims to standardize this.

• Of course, browser support is still the main concern

Page 35: JavaONE 2012 Using Java with HTML5 and CSS3

Thank youHelder da Rocha

Twitter @helderdarochawww.argonavis.com.br