SlideShare a Scribd company logo
1 of 41
Download to read offline
How to take your
Web Application
  Offline with
Google Gears

   Dion Almaer
      ajaxian.com
    code.google.com
The Future of Web Apps
  • It will be hard to determine what is
   and isn’t a web app

  • The web will be everywhere
   • Mobile (iPhone)
   • Desktop
   • Widgets
   • TV
  • The browser will be fast
Why?
             “How often are you on a plane?”
• Reliability
    •   1% of downtime can hurt at the wrong time

• Performance
  • Local acceleration
• Convenience
    •   Not having to find a connection

•   You are offline more than you think!
Offline Web via Open Web
• Why just solve this problem for Google?
• Why not solve it for others?
• Solution: Make it open source with a liberal license
 • New BSD
What is the philosophy?

• One application, one URL
• Seamless transitions between online and offline
• Ability to use local data, even when online
• Available to all users on all platforms
• ... and a pony
What is the philosophy?




Browser plugin: IE, Firefox, Safari (almost!)
What is the philosophy?
What is the philosophy?
         Do for offline what XMLHttpRequest did for web apps



     Ajax Libraries                  Gears Libraries
Dojo, jQuery, Prototype, GWT         Dojo Offline, GWT




   XMLHttpRequest                        Gears



       Open Web                        Open Web
Ajax Architecture
Offline Architecture




•   Read and write using local store
•   Changes are queued for later synchronization
•   Server communication is completely decoupled from UI actions, happens
    periodically whenever there is a connection
What are the pieces?
Database
                        Embedded using SQLite
                       Contributed Full Text Search




var db = google.gears.factory.create('beta.database', '1.0');
db.open('database-demo');
db.execute('create table if not exists Demo (Phrase varchar(255),
Timestamp int)');
db.execute('insert into Demo values (?, ?)', [phrase, currTime]);
var rs = db.execute('select * from Demo order by Timestamp desc');
GearsDB
                      Abstract over the API

var bob = {id: 3, name: 'Bob', url: 'http://bob.com', description: 'whee'};
db.insertRow('person', bob);
db.insertRow('person', bob, 'name = ?', ['Bob']);

db.selectAll('select * from person', null, function(person) {
  document.getElementById('selectAll').innerHTML += ' ' + person.name;
});

var person = db.selectRow('person', 'id = 1');

// update
person.name = 'Harry';
db.updateRow('person', person);
person = db.selectRow('person', 'id = 1');

// force
person.name = 'Sally';
db.forceRow('person', person);
person = db.selectRow('person', 'id = 1');

db.deleteRow('person', bob);
GearsORM
        Are we going to get a GearsHibernate?

var Person = new GearsOrm.Model(quot;Personquot;, {
   firstName: GearsOrm.Fields.String({maxLength:25}),
   lastName: GearsOrm.Fields.String({maxLength:25})
});

GearsORM.Transaction(function() {            “While developing transaction support for
                                          GearsORM i had to write a test, in that test it
   new Person({name:quot;Johnquot;}).save();      execute 100 inserts and 100 updates, this test
                                           take about 15 seconds for the inserts and
   new Person({name:quot;Doequot;}).save();        about 10 seconds for the updates without
});                                     transactions,when using transactions for each set
                                            it takes about 377ms for the inserts and
                                               200ms for the updates that is about
Person.select(quot;firstName = 'Uriel'quot;);                  39 times faster!”
Person.count(quot;lastName = ?quot;,[quot;Katzquot;])
GearShift
             DB Migrations for Gears

Gearshift.rules[1] = {
   // create the demo table
   up: function() {
       return this.e(quot;CREATE TABLE demo_table (
                id INTEGER PRIMARY KEY
                AUTOINCREMENT,
                name VARCHAR(30),
                movie VARCHAR(30)
          )quot;).success;
   },
   down: function() {
       return this.e(quot;DROP TABLE demo_tablequot;).success;
   }
};
Database Tools
Alignment with AIR
                Ext.data.SqlDB


“The APIs for AIR and Google Gears are
nothing alike. In fact, AIR's SQLite database
API is 100% asynchronous via events while
Gears API is all synchronous with results
coming immediately on execution.

So Ext.data.SqlDB was created to abstract
both of these APIs into a single API to access
both.”

                             NOTE: AIR beta 2 has added a synchronous API
Local Server
A mini-web server that groks 200 and 304
ResourceStore
                               Manually Capturing
var pageFiles = [
   location.pathname,
   'gears_base.js',
   '../scripts/gears_db.js',
   ‘foo.html’
];

try {
  localServer = google.gears.factory.create('beta.localserver', '1.0');
} catch (e) {
  alert('Could not create local server: ' + e.message);
  return;
}

var store = localServer.openStore(this.storeName) ||
            localServer.createStore(this.storeName);

store.capture(pageFiles, function(url, success, captureId) {
  console.log(url + ' capture ' + (success ? 'succeeded' : 'failed'));
});
ManagedResourceStore
          Capture entire applications

• List application resources in a separate
    manifest
•   Gears captures and updates the list
    atomically
•   Gears auto-updates automatically on each
    view (within reason)
•   Supports multiple users per application
ManagedResourceStore
                                  Sample Code



var localserver = google.gears.factory.create('beta.localserver', '1.0');

var store = localserver.createManagedStore('mystore');

store.manifestUrl = 'http://myapp.com/offline-manifest.json';

store.checkForUpdates();
ManagedResourceStore
                                                 JSON Me
{
    // version of the manifest file format
    quot;betaManifestVersionquot;: 1,

    // version of the set of resources described in this manifest file
    quot;versionquot;: quot;my_version_stringquot;,

    // optional
    // If the store specifies a requiredCookie, when a request would hit
    // an entry contained in the manifest except the requiredCookie is
    // not present, the local server responds with a redirect to this URL.
    quot;redirectUrlquot;: quot;login.htmlquot;,

    // URLs to be cached (URLs are given relative to the manifest URL)
    quot;entriesquot;: [
        { quot;urlquot;: quot;main.htmlquot;, quot;srcquot;: quot;main_offline.htmlquot; },
        { quot;urlquot;: quot;.quot;, quot;redirectquot;: quot;main.htmlquot; },
        { quot;urlquot;: quot;main.jsquot; }
        { quot;urlquot;: quot;formHandler.htmlquot;, quot;ignoreQueryquot;: true },
      ]
}
Gears Manifest Generator
                                  Ruby Me



json = Google::Gears::LocalServer::Manifest.new do |m|
  m.version = 'MyNewVer'
  m.add_entry({ :url => 'main.html', :src => 'foo.html' })
  m.add_extra_info :to => 'main.html', :redirect => 'foo_redirect.html'
  m.find_entries :in => '.', :ignore =>
            Google::Gears::LocalServer::Manifest::LEADING_PERIOD
end
HTML 5
                                Offline in General

<html application=”manifest-of-urls.txt”>

<html application>
“There’s a concept of an application cache. An application cache is a group
of resources, the group being identified by a URI (which typically happens
to resolve to a manifest). Resources in a cache are either top-level or
not; top-level resources are those that are HTML or XML and when parsed
with scripting disabled have with the value of
the attribute pointing to the same URI as identifies the cache.

When you visit a page you first check to see if you have that page in a
cache as a known top-level page.”
Worker Pool
      JavaScript needs threads after all? Brendan!



                        WorkerPool

Browser JavaScript
     Engine
                        WorkerPool



window, document          no access
Worker Pool
   Run JavaScript in the background

• Provides thread-like functionality to JavaScript
• No more blocking the browser UI
• Communication is via IPC, no shared state or
  threading primitives
Worker Pool Code
function nextPrime(n) {
   // TODO: New top-secret prime-finding algorithm goes here.
   google.gears.workerPool.sendMessage(result);
}

var pool = google.gears.factory.create('beta.workerpool', '1.0');
pool.onmessage = function(message) {
   alert('next prime is: ' + message);
}

var worker = pool.createWorker(String(nextPrime) + '; nextPrime()');
Worker Pool Improved!
  •   Cross-origin API allows Gears apps from different sites to work
      together

  •    WorkerPool improvements:
      • createWorkerFromUrl()
      • onerror allows handling exceptions thrown by workers
  •   New HttpRequest module allows fetching from WorkerPools

  •    New Timer module allows timer events in WorkerPools
      • Implements the WhatWG Timer specification
var timer = google.gears.factory.create(quot;beta.timerquot;, quot;1.0quot;);
timer.setTimeout(function() { alert(quot;Hello, from the future!quot;); },1000);
Why?
 How about Encryption
dojox.sql(quot;INSERT INTO CUSTOMERS VALUES (?, ?,
           ENCRYPT(?))quot;, quot;Neubergquot;, quot;Bradquot;,
                 quot;555-34-8962quot;)
The Digg Oracle
Full Text Search
• Gears added FTS2 to SQLite
• Create the database
 db.execute('CREATE VIRTUAL TABLE recipe USING
 fts2(dish, ingredients)');


• Search the database
 db.execute('SELECT dish FROM recipe WHERE recipe
 MATCH ?', ['tomatoes']);

 Fun queries: dish:stew tomatoes
   Find rows with 'stew' in the dish field, and 'tomatoes' in any field.
What didn’t you see
      here?
     Hint: Sync, sync, sync
Syncing is hard
• Read only, small data
• Read write, small data
• Read only, huge data
• Read write, huge data

            start simple, like Zoho Writer
Think about users




   and don’t make them think
Offline UI




When to ask for user input?
Working with and without
            Gears
              We aren’t that arrogant!



content = hasGears() ? new GearsBaseContent()
                     : new CookieBaseContent();
Two Versions? Really?
           Only in the extreme



{
    ‘url’: ‘main.html’,
    ‘src’: ‘main_offline.html’
    }
Debugging is a Pain
                 On the web? Duh.



• Add Helper Code
  • To clear out the DB
  • Remove captured files
• Disable the cache
• Use Firebug / Lite
Debugging is a Pain
                             On the web? Duh.
GearsBaseContent.prototype.clearServer = function() {
  if (this.localServer.openStore(this.storeName)) {
    this.localServer.removeStore(this.storeName);
    this.store = null;
  }
}

GearsBaseContent.prototype.clearTables = function() {
  if (this.db) {
    this.db.run('delete from BaseQueries');
    this.db.run('delete from BaseFeeds');
  }
  displayQueries();
}
GWT and Gears
try {
  db = new Database(quot;database-demoquot;);
  db.execute(quot;create table if not exists Demo (Phrase varchar(255), Timestamp int)quot;);
} catch (GearsException e) { ... }

button.addClickListener(new ClickListener() {
  public void onClick(Widget sender) {
    try {
      String phrase = input.getText();
      if (phrase.length() > 0) {
        db.execute(quot;insert into Demo values (?, ?)quot;, new String[] {
           phrase, Integer.toString((int) System.currentTimeMillis())});
        displayRecentPhrases();
      }
    } catch (DatabaseException e) {
      Window.alert(e.toString());
    }
  }
});

More Related Content

What's hot

Everybody Loves AFNetworking ... and So Can you!
Everybody Loves AFNetworking ... and So Can you!Everybody Loves AFNetworking ... and So Can you!
Everybody Loves AFNetworking ... and So Can you!jeffsoto
 
Rails 3: Dashing to the Finish
Rails 3: Dashing to the FinishRails 3: Dashing to the Finish
Rails 3: Dashing to the FinishYehuda Katz
 
Javascript call ObjC
Javascript call ObjCJavascript call ObjC
Javascript call ObjCLin Luxiang
 
Python Code Camp for Professionals 1/4
Python Code Camp for Professionals 1/4Python Code Camp for Professionals 1/4
Python Code Camp for Professionals 1/4DEVCON
 
Automated release management with team city & octopusdeploy - NDC 2013
Automated release management with team city & octopusdeploy - NDC 2013Automated release management with team city & octopusdeploy - NDC 2013
Automated release management with team city & octopusdeploy - NDC 2013Kristoffer Deinoff
 
Europython 2011 - Playing tasks with Django & Celery
Europython 2011 - Playing tasks with Django & CeleryEuropython 2011 - Playing tasks with Django & Celery
Europython 2011 - Playing tasks with Django & CeleryMauro Rocco
 
IndexedDB - Querying and Performance
IndexedDB - Querying and PerformanceIndexedDB - Querying and Performance
IndexedDB - Querying and PerformanceParashuram N
 
Python Code Camp for Professionals 3/4
Python Code Camp for Professionals 3/4Python Code Camp for Professionals 3/4
Python Code Camp for Professionals 3/4DEVCON
 
Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4DEVCON
 
iPhone Appleless Apps
iPhone Appleless AppsiPhone Appleless Apps
iPhone Appleless AppsRemy Sharp
 
Building and deploying React applications
Building and deploying React applicationsBuilding and deploying React applications
Building and deploying React applicationsAstrails
 
Python Code Camp for Professionals 2/4
Python Code Camp for Professionals 2/4Python Code Camp for Professionals 2/4
Python Code Camp for Professionals 2/4DEVCON
 
async/await in Swift
async/await in Swiftasync/await in Swift
async/await in SwiftPeter Friese
 
Hidden Treasures in Project Wonder
Hidden Treasures in Project WonderHidden Treasures in Project Wonder
Hidden Treasures in Project WonderWO Community
 
Good karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with KarmaGood karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with KarmaExoLeaders.com
 

What's hot (20)

Everybody Loves AFNetworking ... and So Can you!
Everybody Loves AFNetworking ... and So Can you!Everybody Loves AFNetworking ... and So Can you!
Everybody Loves AFNetworking ... and So Can you!
 
Rails 3: Dashing to the Finish
Rails 3: Dashing to the FinishRails 3: Dashing to the Finish
Rails 3: Dashing to the Finish
 
Javascript call ObjC
Javascript call ObjCJavascript call ObjC
Javascript call ObjC
 
Python Code Camp for Professionals 1/4
Python Code Camp for Professionals 1/4Python Code Camp for Professionals 1/4
Python Code Camp for Professionals 1/4
 
Automated release management with team city & octopusdeploy - NDC 2013
Automated release management with team city & octopusdeploy - NDC 2013Automated release management with team city & octopusdeploy - NDC 2013
Automated release management with team city & octopusdeploy - NDC 2013
 
Sane Async Patterns
Sane Async PatternsSane Async Patterns
Sane Async Patterns
 
Europython 2011 - Playing tasks with Django & Celery
Europython 2011 - Playing tasks with Django & CeleryEuropython 2011 - Playing tasks with Django & Celery
Europython 2011 - Playing tasks with Django & Celery
 
IndexedDB - Querying and Performance
IndexedDB - Querying and PerformanceIndexedDB - Querying and Performance
IndexedDB - Querying and Performance
 
Python Code Camp for Professionals 3/4
Python Code Camp for Professionals 3/4Python Code Camp for Professionals 3/4
Python Code Camp for Professionals 3/4
 
Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4
 
iPhone Appleless Apps
iPhone Appleless AppsiPhone Appleless Apps
iPhone Appleless Apps
 
Building and deploying React applications
Building and deploying React applicationsBuilding and deploying React applications
Building and deploying React applications
 
Python Code Camp for Professionals 2/4
Python Code Camp for Professionals 2/4Python Code Camp for Professionals 2/4
Python Code Camp for Professionals 2/4
 
JavaScript Promise
JavaScript PromiseJavaScript Promise
JavaScript Promise
 
Practical Celery
Practical CeleryPractical Celery
Practical Celery
 
async/await in Swift
async/await in Swiftasync/await in Swift
async/await in Swift
 
Hidden Treasures in Project Wonder
Hidden Treasures in Project WonderHidden Treasures in Project Wonder
Hidden Treasures in Project Wonder
 
Introduction to Celery
Introduction to CeleryIntroduction to Celery
Introduction to Celery
 
Good karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with KarmaGood karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with Karma
 
Dan Webb Presentation
Dan Webb PresentationDan Webb Presentation
Dan Webb Presentation
 

Viewers also liked (20)

Types of Gears
Types of GearsTypes of Gears
Types of Gears
 
GWT + Gears : The browser is the platform
GWT + Gears : The browser is the platformGWT + Gears : The browser is the platform
GWT + Gears : The browser is the platform
 
Gears and Gear Trains
Gears and Gear Trains Gears and Gear Trains
Gears and Gear Trains
 
Introduction to Gears
Introduction to GearsIntroduction to Gears
Introduction to Gears
 
Spur gears
Spur gearsSpur gears
Spur gears
 
Types of gears
Types of gearsTypes of gears
Types of gears
 
Gears & Power Transmission
Gears & Power TransmissionGears & Power Transmission
Gears & Power Transmission
 
Gears
GearsGears
Gears
 
INTRODUCTION OF GEARS AND GEAR KINEMATICS
INTRODUCTION OF GEARS AND GEAR KINEMATICSINTRODUCTION OF GEARS AND GEAR KINEMATICS
INTRODUCTION OF GEARS AND GEAR KINEMATICS
 
GEARS
GEARSGEARS
GEARS
 
Gears
GearsGears
Gears
 
Introduction to Lego EV3
Introduction to Lego EV3Introduction to Lego EV3
Introduction to Lego EV3
 
WORM GEAR PPT
WORM GEAR PPTWORM GEAR PPT
WORM GEAR PPT
 
Gear terminologies
Gear terminologiesGear terminologies
Gear terminologies
 
A presentation On Epicycle Gear Train
A presentation On Epicycle Gear TrainA presentation On Epicycle Gear Train
A presentation On Epicycle Gear Train
 
Introduction to gears
Introduction to gearsIntroduction to gears
Introduction to gears
 
Study of Gear Technology
Study of Gear TechnologyStudy of Gear Technology
Study of Gear Technology
 
Gears and gears types and gear making
Gears and gears types and gear makingGears and gears types and gear making
Gears and gears types and gear making
 
Gears
GearsGears
Gears
 
Gear trains
Gear trainsGear trains
Gear trains
 

Similar to Future of Web Apps: Google Gears

Google Back To Front: From Gears to App Engine and Beyond
Google Back To Front: From Gears to App Engine and BeyondGoogle Back To Front: From Gears to App Engine and Beyond
Google Back To Front: From Gears to App Engine and Beyonddion
 
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...BradNeuberg
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenerytoddbr
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applicationsTom Croucher
 
Going Offline with Gears And GWT
Going Offline with Gears And GWTGoing Offline with Gears And GWT
Going Offline with Gears And GWTtom.peck
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsMike Subelsky
 
Quick and Easy Development with Node.js and Couchbase Server
Quick and Easy Development with Node.js and Couchbase ServerQuick and Easy Development with Node.js and Couchbase Server
Quick and Easy Development with Node.js and Couchbase ServerNic Raboy
 
BlackBerry DevCon 2011 - PhoneGap and WebWorks
BlackBerry DevCon 2011 - PhoneGap and WebWorksBlackBerry DevCon 2011 - PhoneGap and WebWorks
BlackBerry DevCon 2011 - PhoneGap and WebWorksmwbrooks
 
Running Vue Storefront in production (PWA Magento webshop)
Running Vue Storefront in production (PWA Magento webshop)Running Vue Storefront in production (PWA Magento webshop)
Running Vue Storefront in production (PWA Magento webshop)Vendic Magento, PWA & Marketing
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)Igor Bronovskyy
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyDavid Padbury
 
Integrating React.js Into a PHP Application
Integrating React.js Into a PHP ApplicationIntegrating React.js Into a PHP Application
Integrating React.js Into a PHP ApplicationAndrew Rota
 
Express Presentation
Express PresentationExpress Presentation
Express Presentationaaronheckmann
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js frameworkBen Lin
 
Cross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App EngineCross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App EngineAndy McKay
 
Mobile webapplication development
Mobile webapplication developmentMobile webapplication development
Mobile webapplication developmentGanesh Gembali
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVCAlive Kuo
 

Similar to Future of Web Apps: Google Gears (20)

Google Back To Front: From Gears to App Engine and Beyond
Google Back To Front: From Gears to App Engine and BeyondGoogle Back To Front: From Gears to App Engine and Beyond
Google Back To Front: From Gears to App Engine and Beyond
 
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Going Offline with Gears And GWT
Going Offline with Gears And GWTGoing Offline with Gears And GWT
Going Offline with Gears And GWT
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web Apps
 
Having Fun with Play
Having Fun with PlayHaving Fun with Play
Having Fun with Play
 
Quick and Easy Development with Node.js and Couchbase Server
Quick and Easy Development with Node.js and Couchbase ServerQuick and Easy Development with Node.js and Couchbase Server
Quick and Easy Development with Node.js and Couchbase Server
 
BlackBerry DevCon 2011 - PhoneGap and WebWorks
BlackBerry DevCon 2011 - PhoneGap and WebWorksBlackBerry DevCon 2011 - PhoneGap and WebWorks
BlackBerry DevCon 2011 - PhoneGap and WebWorks
 
Running Vue Storefront in production (PWA Magento webshop)
Running Vue Storefront in production (PWA Magento webshop)Running Vue Storefront in production (PWA Magento webshop)
Running Vue Storefront in production (PWA Magento webshop)
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
 
Integrating React.js Into a PHP Application
Integrating React.js Into a PHP ApplicationIntegrating React.js Into a PHP Application
Integrating React.js Into a PHP Application
 
Express Presentation
Express PresentationExpress Presentation
Express Presentation
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
 
Cross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App EngineCross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App Engine
 
Mobile webapplication development
Mobile webapplication developmentMobile webapplication development
Mobile webapplication development
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC
 

More from dion

Palm Developer Day: Opening Keynote
Palm Developer Day: Opening KeynotePalm Developer Day: Opening Keynote
Palm Developer Day: Opening Keynotedion
 
The Mobile Web @ 2010 JSConf
The Mobile Web @ 2010 JSConfThe Mobile Web @ 2010 JSConf
The Mobile Web @ 2010 JSConfdion
 
Google Developer Day: State of Ajax
Google Developer Day: State of AjaxGoogle Developer Day: State of Ajax
Google Developer Day: State of Ajaxdion
 
Gears and HTML 5 @media Ajax London 2008
Gears and HTML 5 @media Ajax London 2008Gears and HTML 5 @media Ajax London 2008
Gears and HTML 5 @media Ajax London 2008dion
 
App Engine On Air: Munich
App Engine On Air: MunichApp Engine On Air: Munich
App Engine On Air: Munichdion
 
Google I/O State Of Ajax
Google I/O State Of AjaxGoogle I/O State Of Ajax
Google I/O State Of Ajaxdion
 
Javaone 2008: What’s New In Ajax
Javaone 2008: What’s New In AjaxJavaone 2008: What’s New In Ajax
Javaone 2008: What’s New In Ajaxdion
 
Web 2.0 Expo Ria Offline Desktop
Web 2.0 Expo Ria Offline DesktopWeb 2.0 Expo Ria Offline Desktop
Web 2.0 Expo Ria Offline Desktopdion
 

More from dion (8)

Palm Developer Day: Opening Keynote
Palm Developer Day: Opening KeynotePalm Developer Day: Opening Keynote
Palm Developer Day: Opening Keynote
 
The Mobile Web @ 2010 JSConf
The Mobile Web @ 2010 JSConfThe Mobile Web @ 2010 JSConf
The Mobile Web @ 2010 JSConf
 
Google Developer Day: State of Ajax
Google Developer Day: State of AjaxGoogle Developer Day: State of Ajax
Google Developer Day: State of Ajax
 
Gears and HTML 5 @media Ajax London 2008
Gears and HTML 5 @media Ajax London 2008Gears and HTML 5 @media Ajax London 2008
Gears and HTML 5 @media Ajax London 2008
 
App Engine On Air: Munich
App Engine On Air: MunichApp Engine On Air: Munich
App Engine On Air: Munich
 
Google I/O State Of Ajax
Google I/O State Of AjaxGoogle I/O State Of Ajax
Google I/O State Of Ajax
 
Javaone 2008: What’s New In Ajax
Javaone 2008: What’s New In AjaxJavaone 2008: What’s New In Ajax
Javaone 2008: What’s New In Ajax
 
Web 2.0 Expo Ria Offline Desktop
Web 2.0 Expo Ria Offline DesktopWeb 2.0 Expo Ria Offline Desktop
Web 2.0 Expo Ria Offline Desktop
 

Recently uploaded

How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 

Recently uploaded (20)

How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 

Future of Web Apps: Google Gears

  • 1. How to take your Web Application Offline with Google Gears Dion Almaer ajaxian.com code.google.com
  • 2. The Future of Web Apps • It will be hard to determine what is and isn’t a web app • The web will be everywhere • Mobile (iPhone) • Desktop • Widgets • TV • The browser will be fast
  • 3. Why? “How often are you on a plane?” • Reliability • 1% of downtime can hurt at the wrong time • Performance • Local acceleration • Convenience • Not having to find a connection • You are offline more than you think!
  • 4. Offline Web via Open Web • Why just solve this problem for Google? • Why not solve it for others? • Solution: Make it open source with a liberal license • New BSD
  • 5. What is the philosophy? • One application, one URL • Seamless transitions between online and offline • Ability to use local data, even when online • Available to all users on all platforms • ... and a pony
  • 6. What is the philosophy? Browser plugin: IE, Firefox, Safari (almost!)
  • 7. What is the philosophy?
  • 8. What is the philosophy? Do for offline what XMLHttpRequest did for web apps Ajax Libraries Gears Libraries Dojo, jQuery, Prototype, GWT Dojo Offline, GWT XMLHttpRequest Gears Open Web Open Web
  • 10. Offline Architecture • Read and write using local store • Changes are queued for later synchronization • Server communication is completely decoupled from UI actions, happens periodically whenever there is a connection
  • 11. What are the pieces?
  • 12. Database Embedded using SQLite Contributed Full Text Search var db = google.gears.factory.create('beta.database', '1.0'); db.open('database-demo'); db.execute('create table if not exists Demo (Phrase varchar(255), Timestamp int)'); db.execute('insert into Demo values (?, ?)', [phrase, currTime]); var rs = db.execute('select * from Demo order by Timestamp desc');
  • 13. GearsDB Abstract over the API var bob = {id: 3, name: 'Bob', url: 'http://bob.com', description: 'whee'}; db.insertRow('person', bob); db.insertRow('person', bob, 'name = ?', ['Bob']); db.selectAll('select * from person', null, function(person) { document.getElementById('selectAll').innerHTML += ' ' + person.name; }); var person = db.selectRow('person', 'id = 1'); // update person.name = 'Harry'; db.updateRow('person', person); person = db.selectRow('person', 'id = 1'); // force person.name = 'Sally'; db.forceRow('person', person); person = db.selectRow('person', 'id = 1'); db.deleteRow('person', bob);
  • 14. GearsORM Are we going to get a GearsHibernate? var Person = new GearsOrm.Model(quot;Personquot;, { firstName: GearsOrm.Fields.String({maxLength:25}), lastName: GearsOrm.Fields.String({maxLength:25}) }); GearsORM.Transaction(function() { “While developing transaction support for GearsORM i had to write a test, in that test it new Person({name:quot;Johnquot;}).save(); execute 100 inserts and 100 updates, this test take about 15 seconds for the inserts and new Person({name:quot;Doequot;}).save(); about 10 seconds for the updates without }); transactions,when using transactions for each set it takes about 377ms for the inserts and 200ms for the updates that is about Person.select(quot;firstName = 'Uriel'quot;); 39 times faster!” Person.count(quot;lastName = ?quot;,[quot;Katzquot;])
  • 15. GearShift DB Migrations for Gears Gearshift.rules[1] = { // create the demo table up: function() { return this.e(quot;CREATE TABLE demo_table ( id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(30), movie VARCHAR(30) )quot;).success; }, down: function() { return this.e(quot;DROP TABLE demo_tablequot;).success; } };
  • 17. Alignment with AIR Ext.data.SqlDB “The APIs for AIR and Google Gears are nothing alike. In fact, AIR's SQLite database API is 100% asynchronous via events while Gears API is all synchronous with results coming immediately on execution. So Ext.data.SqlDB was created to abstract both of these APIs into a single API to access both.” NOTE: AIR beta 2 has added a synchronous API
  • 18. Local Server A mini-web server that groks 200 and 304
  • 19. ResourceStore Manually Capturing var pageFiles = [ location.pathname, 'gears_base.js', '../scripts/gears_db.js', ‘foo.html’ ]; try { localServer = google.gears.factory.create('beta.localserver', '1.0'); } catch (e) { alert('Could not create local server: ' + e.message); return; } var store = localServer.openStore(this.storeName) || localServer.createStore(this.storeName); store.capture(pageFiles, function(url, success, captureId) { console.log(url + ' capture ' + (success ? 'succeeded' : 'failed')); });
  • 20. ManagedResourceStore Capture entire applications • List application resources in a separate manifest • Gears captures and updates the list atomically • Gears auto-updates automatically on each view (within reason) • Supports multiple users per application
  • 21. ManagedResourceStore Sample Code var localserver = google.gears.factory.create('beta.localserver', '1.0'); var store = localserver.createManagedStore('mystore'); store.manifestUrl = 'http://myapp.com/offline-manifest.json'; store.checkForUpdates();
  • 22. ManagedResourceStore JSON Me { // version of the manifest file format quot;betaManifestVersionquot;: 1, // version of the set of resources described in this manifest file quot;versionquot;: quot;my_version_stringquot;, // optional // If the store specifies a requiredCookie, when a request would hit // an entry contained in the manifest except the requiredCookie is // not present, the local server responds with a redirect to this URL. quot;redirectUrlquot;: quot;login.htmlquot;, // URLs to be cached (URLs are given relative to the manifest URL) quot;entriesquot;: [ { quot;urlquot;: quot;main.htmlquot;, quot;srcquot;: quot;main_offline.htmlquot; }, { quot;urlquot;: quot;.quot;, quot;redirectquot;: quot;main.htmlquot; }, { quot;urlquot;: quot;main.jsquot; } { quot;urlquot;: quot;formHandler.htmlquot;, quot;ignoreQueryquot;: true }, ] }
  • 23. Gears Manifest Generator Ruby Me json = Google::Gears::LocalServer::Manifest.new do |m| m.version = 'MyNewVer' m.add_entry({ :url => 'main.html', :src => 'foo.html' }) m.add_extra_info :to => 'main.html', :redirect => 'foo_redirect.html' m.find_entries :in => '.', :ignore => Google::Gears::LocalServer::Manifest::LEADING_PERIOD end
  • 24. HTML 5 Offline in General <html application=”manifest-of-urls.txt”> <html application> “There’s a concept of an application cache. An application cache is a group of resources, the group being identified by a URI (which typically happens to resolve to a manifest). Resources in a cache are either top-level or not; top-level resources are those that are HTML or XML and when parsed with scripting disabled have with the value of the attribute pointing to the same URI as identifies the cache. When you visit a page you first check to see if you have that page in a cache as a known top-level page.”
  • 25. Worker Pool JavaScript needs threads after all? Brendan! WorkerPool Browser JavaScript Engine WorkerPool window, document no access
  • 26. Worker Pool Run JavaScript in the background • Provides thread-like functionality to JavaScript • No more blocking the browser UI • Communication is via IPC, no shared state or threading primitives
  • 27. Worker Pool Code function nextPrime(n) { // TODO: New top-secret prime-finding algorithm goes here. google.gears.workerPool.sendMessage(result); } var pool = google.gears.factory.create('beta.workerpool', '1.0'); pool.onmessage = function(message) { alert('next prime is: ' + message); } var worker = pool.createWorker(String(nextPrime) + '; nextPrime()');
  • 28. Worker Pool Improved! • Cross-origin API allows Gears apps from different sites to work together • WorkerPool improvements: • createWorkerFromUrl() • onerror allows handling exceptions thrown by workers • New HttpRequest module allows fetching from WorkerPools • New Timer module allows timer events in WorkerPools • Implements the WhatWG Timer specification var timer = google.gears.factory.create(quot;beta.timerquot;, quot;1.0quot;); timer.setTimeout(function() { alert(quot;Hello, from the future!quot;); },1000);
  • 29. Why? How about Encryption dojox.sql(quot;INSERT INTO CUSTOMERS VALUES (?, ?, ENCRYPT(?))quot;, quot;Neubergquot;, quot;Bradquot;, quot;555-34-8962quot;)
  • 31. Full Text Search • Gears added FTS2 to SQLite • Create the database db.execute('CREATE VIRTUAL TABLE recipe USING fts2(dish, ingredients)'); • Search the database db.execute('SELECT dish FROM recipe WHERE recipe MATCH ?', ['tomatoes']); Fun queries: dish:stew tomatoes Find rows with 'stew' in the dish field, and 'tomatoes' in any field.
  • 32. What didn’t you see here? Hint: Sync, sync, sync
  • 33. Syncing is hard • Read only, small data • Read write, small data • Read only, huge data • Read write, huge data start simple, like Zoho Writer
  • 34. Think about users and don’t make them think
  • 35. Offline UI When to ask for user input?
  • 36. Working with and without Gears We aren’t that arrogant! content = hasGears() ? new GearsBaseContent() : new CookieBaseContent();
  • 37. Two Versions? Really? Only in the extreme { ‘url’: ‘main.html’, ‘src’: ‘main_offline.html’ }
  • 38. Debugging is a Pain On the web? Duh. • Add Helper Code • To clear out the DB • Remove captured files • Disable the cache • Use Firebug / Lite
  • 39. Debugging is a Pain On the web? Duh. GearsBaseContent.prototype.clearServer = function() { if (this.localServer.openStore(this.storeName)) { this.localServer.removeStore(this.storeName); this.store = null; } } GearsBaseContent.prototype.clearTables = function() { if (this.db) { this.db.run('delete from BaseQueries'); this.db.run('delete from BaseFeeds'); } displayQueries(); }
  • 40.
  • 41. GWT and Gears try { db = new Database(quot;database-demoquot;); db.execute(quot;create table if not exists Demo (Phrase varchar(255), Timestamp int)quot;); } catch (GearsException e) { ... } button.addClickListener(new ClickListener() { public void onClick(Widget sender) { try { String phrase = input.getText(); if (phrase.length() > 0) { db.execute(quot;insert into Demo values (?, ?)quot;, new String[] { phrase, Integer.toString((int) System.currentTimeMillis())}); displayRecentPhrases(); } } catch (DatabaseException e) { Window.alert(e.toString()); } } });