SlideShare una empresa de Scribd logo
1 de 36
Descargar para leer sin conexión
Easing Offline web
application development
with GWT
Arnaud Tournier, LTE Consulting
Speaker : Arnaud Tournier


Developper, Architect and CEO at LTE Consulting. 10 years experience with
C/C++ on Windows. Since 5 years+ : GWT and Web technologies.



GWT and AppEngine trainer

Offline HTML5 apps with GWT

2
Why Offline applications ?


For mobility:


3G throughput sometimes is not enough (ex: offline blog reader)



Mitigate innoportune disconnections (ex: emails)



Moving out of covered zones

Offline HTML5 apps with GWT

3
And because Web is the plateform


HTML5 opens up lots of new possibilities, that were before only accessible to
native applications.



Accessible concepts to HTML5 applications:



Application cache,



File system,



Worker thread,



Web sockets, WebRTC,



Web GL, Audio,



Devices access (webcam, microphone, gps, …),





Data storage,

…

Benefits : lower the development cost for a multiplatform application.

Offline HTML5 apps with GWT

4
It’s also about User experience



Online / Offline, users want the same experience !



Connection is a technical concept, not for user…



Thus the most connected application works also offline !

Offline HTML5 apps with GWT

5
Summary


HTML5 APIs for Offline applications





Application Cache
Local data storage

Offline problems


Login



Local DBMS



Data synchronization




Offline HTML5 apps with GWT

Demo
Conclusion

6
HTML 5 APIs for Offline
applications
Introduction to APIs and GWT integration
Application Cache


Tell the browser to store necessary resources for the application to work
when internet is down



A « manifest » file describing the list of resources to cache



Cache management and event API

Offline HTML5 apps with GWT

8
Application Cache - GWT
GWT manages every application resources « out-of-the-box ». We just need to
write a « linker » to generate the manifest file :



All your application resources, including images, css, js, and so on, are
automatically added to the manifest: we can work offline !

Code Generator



Offline HTML5 apps with GWT

9
Our Application Cache linker
// Executes in the context of the GWT compilation

@Shardable
@LinkerOrder( Order.POST )
public class AppCacheLinker extends AbstractLinker {
…

@Override
public ArtifactSet link( LinkerContext context, … ) {
for( Artifact artifact : artifacts )
sb.append( artifact.getPartialPath() );
emitString( logger, sb.toString(), ontext.getModuleName() + ".appcache" );
}
}
Offline HTML5 apps with GWT

10
Application Cache dynamics
Initial
loading

.html

DOWNLOADING

.manifest

Server

Offline HTML5 apps with GWT

Reloading

.html

NOUPDATE

UPDATE READY

CACHED

NEW MANIFEST FILE

.manifest

11
Application Cache – GWT


Cache API integration in GWT (using JSNI / Elemental).



The browser checks if a new manifest is available when loading the app. We
can ask for further checks with the update() function.



Upon receiving an application update, we can tell the user to refresh the
page to get the latest app version.
In JavaScript, we use the object :
window.applicationCache

Offline HTML5 apps with GWT

12
Application Cache – Events management
public final class AppCache extends JavaScriptObject {
// call Javascript from Java
public static final native AppCache get()
/*-{
return $wnd.applicationCache;
}-*/;

public enum AppCacheEvent
{
// Application en cache
CACHED,

// launch an app cache update
public final native void update()
/*-{
this.update();
}-*/;

// Vérification en cours
CHECKING,
// Téléchargement en cours
DOWNLOADING,

public interface Callback {
void handleEvent( AppCacheEvent event );
}

// Une erreur s’est produite
ERROR,
// Pas de mise à jour
NOUPDATE,

// register to App Cache events
public final native void registerEvents( Callback callback )
/*-{
this.addEventListener('cached', function( s ) {
// Call Java from Javascript
callback
.@package.AppCache.Callback::handleEvent(Lpackage/AppCacheEvent;)
(@package.AppCacheEvent::CACHED);
} );
…
}-*/;
}

// Le fichier manifest n’existe plus
OBSOLETE,
// Mise à jour en cours
PROGRESS,
// Mise à jour prête à être déployée
UPDATEREADY;

}
13
Local data Storage


Locally store data in the browser (user scope !).



Many standards exist (WebSQL, IndexedDB, FileSystem ) but only one is really
multiplatform: LocalStorage



It’s a Map<String, String>.



GWT provides a LocalStorage API wrapper « out of the box », no JSNI to write.



POJO serialization into the storage space might be done with JSON (since it’s
really fast on browsers).



Data is persistent accross page refresh !



5 Mega bytes max (spec) ! (But browsers allow for more…)

Offline HTML5 apps with GWT

14
Summary


HTML5 API for Offline applications





Application Cache
Local data Storage

Offline problems


Login



Local DBMS



Data synchronization




Offline HTML5 apps with GWT

Demo
Conclusion

15
Problems you might
encounter…
A typical wish-list…


Authenticate the user (even offline).



User should be able to manipulate data even when offline.



Application should transparently synchronize its data with the server.



For our awesome developpers : they need a local DBMS (and if we can a JPA
provider).

Offline HTML5 apps with GWT

17
Offline Authentication


When online, authentication is done by the server.



We should then be able to re-authenticate him/her without the server.



Be careful ! Local storage completely unsecure !



We thus store the user’s password in the browser, salted and crypted with
SHA-3.



Find a Java SHA-3 implementation, copy-paste in the project :


String shaEncoded = SHA3.digest( String clearString );

Offline HTML5 apps with GWT

18
An in-browser DBMS ?


Complex data queries, we’re not going to implement that again (complexity,
performance, index, joints, transactions, …) !



Database oriented HTML 5 APIs are not implemented on every browser, except
Local Storage which is just a String to String map…



Jboss ERRAI is a really interesting project, aiming to implement JPA, but it is
too light for majority of cases (no joins, tx, dynamic queries…).



SQL.js is a javascript compiled version of SQLite. Done with the emscripten
compiler from Alon Zhakai. Emscripten = C/C++ to Javascript cross-compiler
based on the LLVM compiler toolkit. Is that a good idea ?

Offline HTML5 apps with GWT

19
SQL.js and GWT


SQLite is the most deployed embedded DBMS in the world (~500 millions)



SQL.js API :


a JavaScript object : window.SQL



3 functions : open(data), execute(statement), exportData(). Talks in JSON.



How to persist the DB ? With Local Storage !



JSNI code to bind the sql.js API



A mini ORM to bind SQL results to our POJOs (we like comfort a bit)



That gives us…

Offline HTML5 apps with GWT

20
SQL.js with GWT
SQL.js creates a « SQL » global
variable

public class SQLite extends JavaScriptObject
{
public static final native SQLite open( JsArrayInteger data )
/*-{
return $wnd.SQL.open( data );
}-*/;

var result = window.SQL.exec( « select… »);
// result holds the results in JSON
class DbHelper {
SQLite db;
public <T>
List<T> query( String query ) {
// parse query and generate select
…

public final native JavaScriptObject execute( String statement )
/*-{
return this.exec( statement );
}-*/;
public final native JsArrayInteger exportData()
/*-{
return this.exportData();
}-*/;
public final native void close()
/*-{
this.close();
}-*/;
}

Offline HTML5 apps with GWT

// execute query
JavaScriptObject jso = db.execute( transformedQuery );
JSON json = new JSONObject( jso );
// generate List<T> from JSON
return list;

}
}

List<Item> items = db.query( « select {Item:i}
from Item i
left join Brand b on i.brandId=b.id
where b.id=42 » ).getResultList();
21
Homogeneous service contracts
public class BusinessLogicFacade
{
public ListItem> searchItems( int id,
AsyncCallback<ListItem>> callback ) {
return currentImplementation.searchArticles( … );
}

public class RemoteBusinessLogic {
private static ApplicationServiceAsync proxy =
GWT.create(ApplicationService.class);
public List<Item> searchItems( int id,
AsyncCallback<List<Item> callback ) {
// simply delegate to remote service
return proxy.searchArticles( … );
}

public void switchImplementation( impl ) {
currentImplementation = impl
}
}

}
… On the server …
businessLogic = BusinessLogic( new JPADAO() );

// Servlet delegates the délègue au code métier
return business.searchArticles( … );
// le code métier appelle son DAO …
class BusinessLogic {
DAO dao;
…

}

public class SQLiteBusinessLogic {
BusinessLogic businessLogic =
new BusinessLogic( new SQLiteDAO() );
public List<Article> searchArticles( int id,
AsyncCallback<List<Article>> callback ) {
// simply delegate to local service
callback.onSuccess( business.searchArticles(…) );
}

Server

// … qui utilise ici JPA
return em.createQuery( « … » ).getResultList();

}
// Le même code métier appelle cette fois le DAO SQLite
return db.query( « … » );

Offline HTML5 apps with GWT

22

Client
Data Synchronization


Three offline access, three difficulty levels

Local data access mode

Related problematic

Read Only

Continuous Synchronization

Read + Add

Sending inserts to the server

Read, Add, Modification,
Suppression

Conflict management

Offline HTML5 apps with GWT

23
Continuous downstream
synchronization


Continuously feeding the local database,



Can use server-side counters or timestamps,



Client asks for unknown data,



Offline
access in
READ ONLY

For server-side deletes, a trigger feeds a log table.

Offline HTML5 apps with GWT

24
Sending local new records to the
server

Offline
access in
READ + ADD

Managing new local records Ids:


Local new records are associated to negative Ids,



Send them when going back to online mode,



Reconciliate local Ids with the server ones.

Offline HTML5 apps with GWT

25
Sending changes to the server


Worst scenarios are possible! Similar problems as for distributed systems.



Version vectors for causality tracking.



Full offline
access
READ WRITE

Conflict management, several resolution policies :


Last writer wins,



Source wins,



Destination wins,



Specified replica wins,



Merge, automatic or manual ?



Log and deffer, etc.

Offline HTML5 apps with GWT

26
So what about out Wish-list?


Ideally, we’d had a fully compliant JPA implementation, enabling us to fully
share data access code between server and client.



ERRAI may be enough in some situations,



Or an home made mini-ORM.



We are building a fully JPA compliant implementation for GWT


http://www.lteconsulting.fr/jpa-for-gwt.html



We didn’t explore security.



Quite a big impedance between HTML5 platform potential and tools we have.
Community needs better tools.



BUT, our goal is fulfilled!


An application running offline, with the same functionalities as online. User
doesn’t need to know whether he is connected or not.

Offline HTML5 apps with GWT

27
Demonstration !
Used stack
GUI
Business facade
Server watchdog

RPC Services

AppCache management

Synchro

Business layer

Synchro

DAO JPA

DAO SQL.JS/GWT

JDBC compliant DBMS

SQLite/Local storage

Server
Applis Offlines HTML5 avec GWT

Client
29
Online mode
GUI
Business facade
Server watchdog

RPC Services

AppCache management

Synchro

Business layer

Synchro

DAO JPA

DAO SQL.JS/GWT

JDBC compliant DBMS

SQLite/Local storage

Server
Applis Offlines HTML5 avec GWT

Client
30
Offline mode
GUI
Business facade
Server watchdog

RPC Services

AppCache management

Synchro

Unreachable
Server

Business layer

Synchro

DAO JPA

DAO SQL.JS/GWT

JDBC compliant DBMS

SQLite/Local storage

Server
Applis Offlines HTML5 avec GWT

Client
31
Transition to Online mode
GUI
Business facade

Server
replies

Server watchdog

RPC Services

AppCache management

Send local changes to
Business layer
the server

Synchro

Synchro

DAO JPA

DAO SQL.JS/GWT

JDBC compliant DBMS

SQLite/Local storage

Server
Applis Offlines HTML5 avec GWT

Client
32
Online mode
GUI
Business facade
Server watchdog

RPC Services

AppCache management

Synchro

Business layer

Synchro

DAO JPA

DAO SQL.JS/GWT

JDBC compliant DBMS

SQLite/Local storage

Server
Applis Offlines HTML5 avec GWT

Client
33
Démonstration…

Offline HTML5 apps with GWT

34
Questions?

Offline HTML5 apps with GWT

35
Thanks, and see you soon!
Twitter: @ltearno
Email: contact@lteconsulting.fr



Links :



SQL.JS



SQLITE



EMSCRIPTEN



HTML5Rocks



JBOSS ERRAI



Offline HTML5 apps with GWT

GWT

CANIUSE.COM

36

Más contenido relacionado

La actualidad más candente

RESTful OSGi Web Applications Tutorial - Khawaja S Shams & Jeff Norris
RESTful OSGi Web Applications Tutorial - Khawaja S Shams & Jeff NorrisRESTful OSGi Web Applications Tutorial - Khawaja S Shams & Jeff Norris
RESTful OSGi Web Applications Tutorial - Khawaja S Shams & Jeff Norris
mfrancis
 
Creating REST Webservice With NetBeans
Creating REST Webservice With NetBeansCreating REST Webservice With NetBeans
Creating REST Webservice With NetBeans
Neil Ghosh
 

La actualidad más candente (20)

Ajax
AjaxAjax
Ajax
 
03 integrate webapisignalr
03 integrate webapisignalr03 integrate webapisignalr
03 integrate webapisignalr
 
M Ramya
M RamyaM Ramya
M Ramya
 
Ajax.ppt
Ajax.pptAjax.ppt
Ajax.ppt
 
Ajax Ppt
Ajax PptAjax Ppt
Ajax Ppt
 
Building a Backend with Flask
Building a Backend with FlaskBuilding a Backend with Flask
Building a Backend with Flask
 
RESTful OSGi Web Applications Tutorial - Khawaja S Shams & Jeff Norris
RESTful OSGi Web Applications Tutorial - Khawaja S Shams & Jeff NorrisRESTful OSGi Web Applications Tutorial - Khawaja S Shams & Jeff Norris
RESTful OSGi Web Applications Tutorial - Khawaja S Shams & Jeff Norris
 
Ajax presentation
Ajax presentationAjax presentation
Ajax presentation
 
Node.js and Parse
Node.js and ParseNode.js and Parse
Node.js and Parse
 
Using MongoDB with the .Net Framework
Using MongoDB with the .Net FrameworkUsing MongoDB with the .Net Framework
Using MongoDB with the .Net Framework
 
Csphtp1 20
Csphtp1 20Csphtp1 20
Csphtp1 20
 
IndexedDB and Push Notifications in Progressive Web Apps
IndexedDB and Push Notifications in Progressive Web AppsIndexedDB and Push Notifications in Progressive Web Apps
IndexedDB and Push Notifications in Progressive Web Apps
 
Building a Cloud API Server using Play(SCALA) & Riak
Building a Cloud API Server using  Play(SCALA) & Riak Building a Cloud API Server using  Play(SCALA) & Riak
Building a Cloud API Server using Play(SCALA) & Riak
 
jQuery Ajax
jQuery AjaxjQuery Ajax
jQuery Ajax
 
Java Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
Java Web Programming on Google Cloud Platform [3/3] : Google Web ToolkitJava Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
Java Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
 
06 integrate elasticsearch
06 integrate elasticsearch06 integrate elasticsearch
06 integrate elasticsearch
 
Java Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : DatastoreJava Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : Datastore
 
Ajax
AjaxAjax
Ajax
 
Creating REST Webservice With NetBeans
Creating REST Webservice With NetBeansCreating REST Webservice With NetBeans
Creating REST Webservice With NetBeans
 
04 integrate entityframework
04 integrate entityframework04 integrate entityframework
04 integrate entityframework
 

Similar a Easing offline web application development with GWT

Google Dev Day2007
Google Dev Day2007Google Dev Day2007
Google Dev Day2007
lucclaes
 
Cannibalising The Google App Engine
Cannibalising The  Google  App  EngineCannibalising The  Google  App  Engine
Cannibalising The Google App Engine
catherinewall
 
Mastering the IoT With JavaScript and C++ - Günter Obiltschnig
Mastering the IoT With JavaScript and C++ - Günter ObiltschnigMastering the IoT With JavaScript and C++ - Günter Obiltschnig
Mastering the IoT With JavaScript and C++ - Günter Obiltschnig
WithTheBest
 
Android presentation
Android presentationAndroid presentation
Android presentation
Imam Raza
 
Googleappengineintro 110410190620-phpapp01
Googleappengineintro 110410190620-phpapp01Googleappengineintro 110410190620-phpapp01
Googleappengineintro 110410190620-phpapp01
Tony Frame
 

Similar a Easing offline web application development with GWT (20)

Front-end. Global domination
Front-end. Global dominationFront-end. Global domination
Front-end. Global domination
 
Frontend. Global domination.
Frontend. Global domination.Frontend. Global domination.
Frontend. Global domination.
 
Html5
Html5Html5
Html5
 
Google Web Toolkit
Google Web ToolkitGoogle Web Toolkit
Google Web Toolkit
 
Pivorak.javascript.global domination
Pivorak.javascript.global dominationPivorak.javascript.global domination
Pivorak.javascript.global domination
 
Andriy Vandakurov about "Frontend. Global domination"
Andriy Vandakurov about  "Frontend. Global domination" Andriy Vandakurov about  "Frontend. Global domination"
Andriy Vandakurov about "Frontend. Global domination"
 
Beyond HTML: Tools for Building Web 2.0 Apps
Beyond HTML: Tools for Building Web 2.0 AppsBeyond HTML: Tools for Building Web 2.0 Apps
Beyond HTML: Tools for Building Web 2.0 Apps
 
Programming IoT Gateways with macchina.io
Programming IoT Gateways with macchina.ioProgramming IoT Gateways with macchina.io
Programming IoT Gateways with macchina.io
 
Google Dev Day2007
Google Dev Day2007Google Dev Day2007
Google Dev Day2007
 
Faites évoluer votre accès aux données avec MongoDB Stitch
Faites évoluer votre accès aux données avec MongoDB StitchFaites évoluer votre accès aux données avec MongoDB Stitch
Faites évoluer votre accès aux données avec MongoDB Stitch
 
Cannibalising The Google App Engine
Cannibalising The  Google  App  EngineCannibalising The  Google  App  Engine
Cannibalising The Google App Engine
 
Apache Cordova In Action
Apache Cordova In ActionApache Cordova In Action
Apache Cordova In Action
 
Mastering the IoT With JavaScript and C++ - Günter Obiltschnig
Mastering the IoT With JavaScript and C++ - Günter ObiltschnigMastering the IoT With JavaScript and C++ - Günter Obiltschnig
Mastering the IoT With JavaScript and C++ - Günter Obiltschnig
 
Google App Engine for Java
Google App Engine for JavaGoogle App Engine for Java
Google App Engine for Java
 
Gwt Deep Dive
Gwt Deep DiveGwt Deep Dive
Gwt Deep Dive
 
Android presentation
Android presentationAndroid presentation
Android presentation
 
Meteoro de pegasuus! Desenvolvendo aplicações realtime com MeteorJS
Meteoro de pegasuus! Desenvolvendo aplicações realtime com MeteorJSMeteoro de pegasuus! Desenvolvendo aplicações realtime com MeteorJS
Meteoro de pegasuus! Desenvolvendo aplicações realtime com MeteorJS
 
[JavaLand 2015] Developing JavaScript Mobile Apps Using Apache Cordova
[JavaLand 2015] Developing JavaScript Mobile Apps Using Apache Cordova[JavaLand 2015] Developing JavaScript Mobile Apps Using Apache Cordova
[JavaLand 2015] Developing JavaScript Mobile Apps Using Apache Cordova
 
Googleappengineintro 110410190620-phpapp01
Googleappengineintro 110410190620-phpapp01Googleappengineintro 110410190620-phpapp01
Googleappengineintro 110410190620-phpapp01
 
Rapid and Reliable Developing with HTML5 & GWT
Rapid and Reliable Developing with HTML5 & GWTRapid and Reliable Developing with HTML5 & GWT
Rapid and Reliable Developing with HTML5 & GWT
 

Último

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Último (20)

Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 

Easing offline web application development with GWT

  • 1. Easing Offline web application development with GWT Arnaud Tournier, LTE Consulting
  • 2. Speaker : Arnaud Tournier  Developper, Architect and CEO at LTE Consulting. 10 years experience with C/C++ on Windows. Since 5 years+ : GWT and Web technologies.  GWT and AppEngine trainer Offline HTML5 apps with GWT 2
  • 3. Why Offline applications ?  For mobility:  3G throughput sometimes is not enough (ex: offline blog reader)  Mitigate innoportune disconnections (ex: emails)  Moving out of covered zones Offline HTML5 apps with GWT 3
  • 4. And because Web is the plateform  HTML5 opens up lots of new possibilities, that were before only accessible to native applications.  Accessible concepts to HTML5 applications:   Application cache,  File system,  Worker thread,  Web sockets, WebRTC,  Web GL, Audio,  Devices access (webcam, microphone, gps, …),   Data storage, … Benefits : lower the development cost for a multiplatform application. Offline HTML5 apps with GWT 4
  • 5. It’s also about User experience  Online / Offline, users want the same experience !  Connection is a technical concept, not for user…  Thus the most connected application works also offline ! Offline HTML5 apps with GWT 5
  • 6. Summary  HTML5 APIs for Offline applications    Application Cache Local data storage Offline problems  Login  Local DBMS  Data synchronization   Offline HTML5 apps with GWT Demo Conclusion 6
  • 7. HTML 5 APIs for Offline applications Introduction to APIs and GWT integration
  • 8. Application Cache  Tell the browser to store necessary resources for the application to work when internet is down  A « manifest » file describing the list of resources to cache  Cache management and event API Offline HTML5 apps with GWT 8
  • 9. Application Cache - GWT GWT manages every application resources « out-of-the-box ». We just need to write a « linker » to generate the manifest file :  All your application resources, including images, css, js, and so on, are automatically added to the manifest: we can work offline ! Code Generator  Offline HTML5 apps with GWT 9
  • 10. Our Application Cache linker // Executes in the context of the GWT compilation @Shardable @LinkerOrder( Order.POST ) public class AppCacheLinker extends AbstractLinker { … @Override public ArtifactSet link( LinkerContext context, … ) { for( Artifact artifact : artifacts ) sb.append( artifact.getPartialPath() ); emitString( logger, sb.toString(), ontext.getModuleName() + ".appcache" ); } } Offline HTML5 apps with GWT 10
  • 11. Application Cache dynamics Initial loading .html DOWNLOADING .manifest Server Offline HTML5 apps with GWT Reloading .html NOUPDATE UPDATE READY CACHED NEW MANIFEST FILE .manifest 11
  • 12. Application Cache – GWT  Cache API integration in GWT (using JSNI / Elemental).  The browser checks if a new manifest is available when loading the app. We can ask for further checks with the update() function.  Upon receiving an application update, we can tell the user to refresh the page to get the latest app version. In JavaScript, we use the object : window.applicationCache Offline HTML5 apps with GWT 12
  • 13. Application Cache – Events management public final class AppCache extends JavaScriptObject { // call Javascript from Java public static final native AppCache get() /*-{ return $wnd.applicationCache; }-*/; public enum AppCacheEvent { // Application en cache CACHED, // launch an app cache update public final native void update() /*-{ this.update(); }-*/; // Vérification en cours CHECKING, // Téléchargement en cours DOWNLOADING, public interface Callback { void handleEvent( AppCacheEvent event ); } // Une erreur s’est produite ERROR, // Pas de mise à jour NOUPDATE, // register to App Cache events public final native void registerEvents( Callback callback ) /*-{ this.addEventListener('cached', function( s ) { // Call Java from Javascript callback .@package.AppCache.Callback::handleEvent(Lpackage/AppCacheEvent;) (@package.AppCacheEvent::CACHED); } ); … }-*/; } // Le fichier manifest n’existe plus OBSOLETE, // Mise à jour en cours PROGRESS, // Mise à jour prête à être déployée UPDATEREADY; } 13
  • 14. Local data Storage  Locally store data in the browser (user scope !).  Many standards exist (WebSQL, IndexedDB, FileSystem ) but only one is really multiplatform: LocalStorage  It’s a Map<String, String>.  GWT provides a LocalStorage API wrapper « out of the box », no JSNI to write.  POJO serialization into the storage space might be done with JSON (since it’s really fast on browsers).  Data is persistent accross page refresh !  5 Mega bytes max (spec) ! (But browsers allow for more…) Offline HTML5 apps with GWT 14
  • 15. Summary  HTML5 API for Offline applications    Application Cache Local data Storage Offline problems  Login  Local DBMS  Data synchronization   Offline HTML5 apps with GWT Demo Conclusion 15
  • 17. A typical wish-list…  Authenticate the user (even offline).  User should be able to manipulate data even when offline.  Application should transparently synchronize its data with the server.  For our awesome developpers : they need a local DBMS (and if we can a JPA provider). Offline HTML5 apps with GWT 17
  • 18. Offline Authentication  When online, authentication is done by the server.  We should then be able to re-authenticate him/her without the server.  Be careful ! Local storage completely unsecure !  We thus store the user’s password in the browser, salted and crypted with SHA-3.  Find a Java SHA-3 implementation, copy-paste in the project :  String shaEncoded = SHA3.digest( String clearString ); Offline HTML5 apps with GWT 18
  • 19. An in-browser DBMS ?  Complex data queries, we’re not going to implement that again (complexity, performance, index, joints, transactions, …) !  Database oriented HTML 5 APIs are not implemented on every browser, except Local Storage which is just a String to String map…  Jboss ERRAI is a really interesting project, aiming to implement JPA, but it is too light for majority of cases (no joins, tx, dynamic queries…).  SQL.js is a javascript compiled version of SQLite. Done with the emscripten compiler from Alon Zhakai. Emscripten = C/C++ to Javascript cross-compiler based on the LLVM compiler toolkit. Is that a good idea ? Offline HTML5 apps with GWT 19
  • 20. SQL.js and GWT  SQLite is the most deployed embedded DBMS in the world (~500 millions)  SQL.js API :  a JavaScript object : window.SQL  3 functions : open(data), execute(statement), exportData(). Talks in JSON.  How to persist the DB ? With Local Storage !  JSNI code to bind the sql.js API  A mini ORM to bind SQL results to our POJOs (we like comfort a bit)  That gives us… Offline HTML5 apps with GWT 20
  • 21. SQL.js with GWT SQL.js creates a « SQL » global variable public class SQLite extends JavaScriptObject { public static final native SQLite open( JsArrayInteger data ) /*-{ return $wnd.SQL.open( data ); }-*/; var result = window.SQL.exec( « select… »); // result holds the results in JSON class DbHelper { SQLite db; public <T> List<T> query( String query ) { // parse query and generate select … public final native JavaScriptObject execute( String statement ) /*-{ return this.exec( statement ); }-*/; public final native JsArrayInteger exportData() /*-{ return this.exportData(); }-*/; public final native void close() /*-{ this.close(); }-*/; } Offline HTML5 apps with GWT // execute query JavaScriptObject jso = db.execute( transformedQuery ); JSON json = new JSONObject( jso ); // generate List<T> from JSON return list; } } List<Item> items = db.query( « select {Item:i} from Item i left join Brand b on i.brandId=b.id where b.id=42 » ).getResultList(); 21
  • 22. Homogeneous service contracts public class BusinessLogicFacade { public ListItem> searchItems( int id, AsyncCallback<ListItem>> callback ) { return currentImplementation.searchArticles( … ); } public class RemoteBusinessLogic { private static ApplicationServiceAsync proxy = GWT.create(ApplicationService.class); public List<Item> searchItems( int id, AsyncCallback<List<Item> callback ) { // simply delegate to remote service return proxy.searchArticles( … ); } public void switchImplementation( impl ) { currentImplementation = impl } } } … On the server … businessLogic = BusinessLogic( new JPADAO() ); // Servlet delegates the délègue au code métier return business.searchArticles( … ); // le code métier appelle son DAO … class BusinessLogic { DAO dao; … } public class SQLiteBusinessLogic { BusinessLogic businessLogic = new BusinessLogic( new SQLiteDAO() ); public List<Article> searchArticles( int id, AsyncCallback<List<Article>> callback ) { // simply delegate to local service callback.onSuccess( business.searchArticles(…) ); } Server // … qui utilise ici JPA return em.createQuery( « … » ).getResultList(); } // Le même code métier appelle cette fois le DAO SQLite return db.query( « … » ); Offline HTML5 apps with GWT 22 Client
  • 23. Data Synchronization  Three offline access, three difficulty levels Local data access mode Related problematic Read Only Continuous Synchronization Read + Add Sending inserts to the server Read, Add, Modification, Suppression Conflict management Offline HTML5 apps with GWT 23
  • 24. Continuous downstream synchronization  Continuously feeding the local database,  Can use server-side counters or timestamps,  Client asks for unknown data,  Offline access in READ ONLY For server-side deletes, a trigger feeds a log table. Offline HTML5 apps with GWT 24
  • 25. Sending local new records to the server Offline access in READ + ADD Managing new local records Ids:  Local new records are associated to negative Ids,  Send them when going back to online mode,  Reconciliate local Ids with the server ones. Offline HTML5 apps with GWT 25
  • 26. Sending changes to the server  Worst scenarios are possible! Similar problems as for distributed systems.  Version vectors for causality tracking.  Full offline access READ WRITE Conflict management, several resolution policies :  Last writer wins,  Source wins,  Destination wins,  Specified replica wins,  Merge, automatic or manual ?  Log and deffer, etc. Offline HTML5 apps with GWT 26
  • 27. So what about out Wish-list?  Ideally, we’d had a fully compliant JPA implementation, enabling us to fully share data access code between server and client.  ERRAI may be enough in some situations,  Or an home made mini-ORM.  We are building a fully JPA compliant implementation for GWT  http://www.lteconsulting.fr/jpa-for-gwt.html  We didn’t explore security.  Quite a big impedance between HTML5 platform potential and tools we have. Community needs better tools.  BUT, our goal is fulfilled!  An application running offline, with the same functionalities as online. User doesn’t need to know whether he is connected or not. Offline HTML5 apps with GWT 27
  • 29. Used stack GUI Business facade Server watchdog RPC Services AppCache management Synchro Business layer Synchro DAO JPA DAO SQL.JS/GWT JDBC compliant DBMS SQLite/Local storage Server Applis Offlines HTML5 avec GWT Client 29
  • 30. Online mode GUI Business facade Server watchdog RPC Services AppCache management Synchro Business layer Synchro DAO JPA DAO SQL.JS/GWT JDBC compliant DBMS SQLite/Local storage Server Applis Offlines HTML5 avec GWT Client 30
  • 31. Offline mode GUI Business facade Server watchdog RPC Services AppCache management Synchro Unreachable Server Business layer Synchro DAO JPA DAO SQL.JS/GWT JDBC compliant DBMS SQLite/Local storage Server Applis Offlines HTML5 avec GWT Client 31
  • 32. Transition to Online mode GUI Business facade Server replies Server watchdog RPC Services AppCache management Send local changes to Business layer the server Synchro Synchro DAO JPA DAO SQL.JS/GWT JDBC compliant DBMS SQLite/Local storage Server Applis Offlines HTML5 avec GWT Client 32
  • 33. Online mode GUI Business facade Server watchdog RPC Services AppCache management Synchro Business layer Synchro DAO JPA DAO SQL.JS/GWT JDBC compliant DBMS SQLite/Local storage Server Applis Offlines HTML5 avec GWT Client 33
  • 36. Thanks, and see you soon! Twitter: @ltearno Email: contact@lteconsulting.fr  Links :   SQL.JS  SQLITE  EMSCRIPTEN  HTML5Rocks  JBOSS ERRAI  Offline HTML5 apps with GWT GWT CANIUSE.COM 36