Commit 9af14f8a authored by Tristan Cavelier's avatar Tristan Cavelier Committed by Sebastien Robin

Trailing spaces deleted.

console.log no longer in scripts.
JIO classes are more secure now.
parent b149e374
...@@ -7,38 +7,46 @@ ...@@ -7,38 +7,46 @@
</head> </head>
<body> <body>
<script type="text/javascript" src="js/jquery/jquery.js"></script> <script type="text/javascript" src="js/jquery/jquery.js"></script>
<script type="text/javascript" src="unhosted/localorcookiestorage.js"></script> <script type="text/javascript" src="unhosted/localorcookiestorage.js">
</script>
<script type="text/javascript" src="unhosted/jio.js"></script> <script type="text/javascript" src="unhosted/jio.js"></script>
<script type="text/javascript" src="unhosted/base64.js"></script> <script type="text/javascript" src="unhosted/base64.js"></script>
<script type="text/javascript" src="unhosted/jio.storage.js"></script> <script type="text/javascript" src="unhosted/jio.storage.js"></script>
<script type="text/javascript"> <script type="text/javascript">
<!-- <!--
var mammal = function (description) { var maClassPasProtegee = function () {
this.caracteristics = description; this.monAttributPasProtegee = 0;
};
mammal.prototype = {
createMammal: function () {
// c'est un chat alors
var mycat = new cat(this.caracteristics);
var t = this;
mycat.say = function () { return t.caracteristics.say; };
mycat.name = function () { return t.caracteristics.name; };
return mycat;
}
}; };
var cat = function (detaileddescription) { maClassPasProtegee.prototype = {
// (...) getMonAttribut: function () {
}; return this.monAttributPasProtegee;
cat.prototype = { },
talk: function () { logMonAttribut: function () {
alert('My name is ' + this.name() + ', ' + this.say()); console.log (this.monAttributPasProtegee);
} }
}; };
var maclass1 = new maClassPasProtegee();
maclass1.logMonAttribut();
maclass1.monAttributPasProtegee ++;
maclass1.logMonAttribut();
var mam = new mammal({'say':'meow','name':'nyancat'}); var maClassProtegee = function () {
var mycat = mam.createMammal(); var publ = {}, priv = {};
mycat.talk(); priv.monAttributProtegee = 0;
//--> publ.getMonAttribut = function () {
return priv.monAttributProtegee;
};
publ.logMonAttribut = function () {
console.log (priv.monAttributProtegee);
};
return publ;
};
var maclass2 = new maClassProtegee();
maclass2.logMonAttribut();
maclass2.monAttributProtegee ++;
maclass2.logMonAttribut();
//-->
</script> </script>
</body> </body>
</html> </html>
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
// - dummyallnotfound // - dummyallnotfound
// - dummyall3tries // - dummyall3tries
;(function ( Jio ) { ;(function ( Jio ) {
// check dependencies // check dependencies
var errorDependencies=function(){$.error('Cannot find Jio');}; var errorDependencies=function(){$.error('Cannot find Jio');};
try{if (!Jio){ try{if (!Jio){
...@@ -19,7 +19,7 @@ ...@@ -19,7 +19,7 @@
var jioGlobalObj = Jio.getGlobalObject(), var jioGlobalObj = Jio.getGlobalObject(),
// end globals // end globals
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
// Dummy Storage 1 : all ok // Dummy Storage 1 : all ok
DummyStorageAllOk = function ( args ) { DummyStorageAllOk = function ( args ) {
...@@ -45,7 +45,7 @@ ...@@ -45,7 +45,7 @@
that.loadDocument = function () { that.loadDocument = function () {
// Returns a document object containing all information of the // Returns a document object containing all information of the
// document and its content. // document and its content.
// document object is {'fileName':string,'fileContent':string, // document object is {'fileName':string,'fileContent':string,
// 'creationDate':date,'lastModified':date} // 'creationDate':date,'lastModified':date}
...@@ -96,7 +96,7 @@ ...@@ -96,7 +96,7 @@
// Dummy Storage 2 : all fail // Dummy Storage 2 : all fail
DummyStorageAllFail = function ( args ) { DummyStorageAllFail = function ( args ) {
var that = Jio.newBaseStorage( args ); var that = Jio.newBaseStorage( args );
that.checkNameAvailability = function () { that.checkNameAvailability = function () {
// Fails to check [job.userName]. // Fails to check [job.userName].
...@@ -117,7 +117,7 @@ ...@@ -117,7 +117,7 @@
that.loadDocument = function () { that.loadDocument = function () {
// Returns a document object containing nothing. // Returns a document object containing nothing.
// document object is {'fileName':string,'fileContent':string, // document object is {'fileName':string,'fileContent':string,
// 'creationDate':date,'lastModified':date} // 'creationDate':date,'lastModified':date}
...@@ -157,7 +157,7 @@ ...@@ -157,7 +157,7 @@
// Dummy Storage 3 : all not found // Dummy Storage 3 : all not found
DummyStorageAllNotFound = function ( args ) { DummyStorageAllNotFound = function ( args ) {
var that = Jio.newBaseStorage( args ); var that = Jio.newBaseStorage( args );
that.checkNameAvailability = function () { that.checkNameAvailability = function () {
// [job.userName] not found, so the name is available. // [job.userName] not found, so the name is available.
...@@ -178,7 +178,7 @@ ...@@ -178,7 +178,7 @@
that.loadDocument = function () { that.loadDocument = function () {
// Returns a document object containing nothing. // Returns a document object containing nothing.
// document object is {'fileName':string,'fileContent':string, // document object is {'fileName':string,'fileContent':string,
// 'creationDate':date,'lastModified':date} // 'creationDate':date,'lastModified':date}
...@@ -218,7 +218,7 @@ ...@@ -218,7 +218,7 @@
// Dummy Storage 4 : all 3 tries // Dummy Storage 4 : all 3 tries
DummyStorageAll3Tries = function ( args ) { DummyStorageAll3Tries = function ( args ) {
var that = Jio.newBaseStorage( args ), priv = {}; var that = Jio.newBaseStorage( args ), priv = {};
priv.doJob = function (ifokreturn) { priv.doJob = function (ifokreturn) {
// wait a little in order to simulate asynchronous operation // wait a little in order to simulate asynchronous operation
setTimeout(function () { setTimeout(function () {
...@@ -236,7 +236,7 @@ ...@@ -236,7 +236,7 @@
return that.fail('Too much tries.'); return that.fail('Too much tries.');
} }
}; };
that.checkNameAvailability = function () { that.checkNameAvailability = function () {
priv.doJob (true); priv.doJob (true);
}; // end userNameAvailable }; // end userNameAvailable
......
...@@ -40,7 +40,7 @@ test ( "Jio simple methods", function () { ...@@ -40,7 +40,7 @@ test ( "Jio simple methods", function () {
deepEqual ( o.jio.isReady(), true, '1 must be not ready'); deepEqual ( o.jio.isReady(), true, '1 must be not ready');
ok ( o.jio2.id !== o.jio.id, '1 and 2 must be different'); ok ( o.jio2.getID() !== o.jio.getID(), '1 and 2 must be different');
deepEqual ( o.jio.stop(), true, '1 must be stopped'); deepEqual ( o.jio.stop(), true, '1 must be stopped');
...@@ -67,11 +67,11 @@ test ( 'Jio Publish/Sububscribe/Unsubscribe methods', function () { ...@@ -67,11 +67,11 @@ test ( 'Jio Publish/Sububscribe/Unsubscribe methods', function () {
// And publish the event. // And publish the event.
o.jio.publish('pubsub_test'); o.jio.publish('pubsub_test');
ok (spy1.calledOnce, 'subscribing & publishing, event called once'); ok (spy1.calledOnce, 'subscribing & publishing, event called once');
o.jio.unsubscribe('pubsub_test',spy1); o.jio.unsubscribe('pubsub_test',spy1);
o.jio.publish('pubsub_test'); o.jio.publish('pubsub_test');
ok (spy1.calledOnce, 'unsubscribing, same event not called twice'); ok (spy1.calledOnce, 'unsubscribing, same event not called twice');
o.jio.stop(); o.jio.stop();
}); });
...@@ -108,7 +108,7 @@ test ('All tests', function () { ...@@ -108,7 +108,7 @@ test ('All tests', function () {
{'fileName':'memo','creationDate':20000,'lastModified':25000}]); {'fileName':'memo','creationDate':20000,'lastModified':25000}]);
mytest('remove document OK','removeDocument','isRemoved',true); mytest('remove document OK','removeDocument','isRemoved',true);
o.jio.stop(); o.jio.stop();
// All Fail Dummy Storage // All Fail Dummy Storage
o.jio = JIO.createNew({'type':'dummyallfail','userName':'Dummy'}, o.jio = JIO.createNew({'type':'dummyallfail','userName':'Dummy'},
{'ID':'jiotests'}); {'ID':'jiotests'});
...@@ -140,25 +140,21 @@ test ('Simple Job Elimination', function () { ...@@ -140,25 +140,21 @@ test ('Simple Job Elimination', function () {
o.jio = JIO.createNew({'type':'dummyallok','userName':'dummy'}, o.jio = JIO.createNew({'type':'dummyallok','userName':'dummy'},
{'ID':'jiotests'}); {'ID':'jiotests'});
id = o.jio.id; id = o.jio.getID();
o.jio.saveDocument({'fileName':'file','fileContent':'content', o.jio.saveDocument({'fileName':'file','fileContent':'content',
'callback':o.f1,'maxtries':1}); 'callback':o.f1,'maxtries':1});
console.log (localStorage.getItem('jio/jobObject/'+id));
ok(LocalOrCookieStorage.getItem('jio/jobObject/'+id)['1'], ok(LocalOrCookieStorage.getItem('jio/jobObject/'+id)['1'],
'job creation'); 'job creation');
console.log (localStorage.getItem('jio/jobObject/'+id));
clock.tick(10); clock.tick(10);
console.log (localStorage.getItem('jio/jobObject/'+id));
o.jio.removeDocument({'fileName':'file','fileContent':'content', o.jio.removeDocument({'fileName':'file','fileContent':'content',
'callback':o.f2,'maxtries':1}); 'callback':o.f2,'maxtries':1});
o.tmp = LocalOrCookieStorage.getItem('jio/jobObject/'+id)['1']; o.tmp = LocalOrCookieStorage.getItem('jio/jobObject/'+id)['1'];
console.log (localStorage.getItem('jio/jobObject/'+id));
ok(!o.tmp || o.tmp.status === 'fail','job elimination'); ok(!o.tmp || o.tmp.status === 'fail','job elimination');
}); });
test ('Simple Job Replacement', function () { test ('Simple Job Replacement', function () {
// Test if the second job write over the first one // Test if the second job write over the first one
var o = {}, clock = this.sandbox.useFakeTimers(), id = 0; var o = {}, clock = this.sandbox.useFakeTimers(), id = 0;
o.f1 = function (result) { o.f1 = function (result) {
o.status = result.status; o.status = result.status;
...@@ -168,7 +164,7 @@ test ('Simple Job Replacement', function () { ...@@ -168,7 +164,7 @@ test ('Simple Job Replacement', function () {
o.jio = JIO.createNew({'type':'dummyallok','userName':'dummy'}, o.jio = JIO.createNew({'type':'dummyallok','userName':'dummy'},
{'ID':'jiotests'}); {'ID':'jiotests'});
id = o.jio.id; id = o.jio.getID();
o.jio.saveDocument({'fileName':'file','fileContent':'content', o.jio.saveDocument({'fileName':'file','fileContent':'content',
'callback':o.f1,'maxtries':1}); 'callback':o.f1,'maxtries':1});
clock.tick(10); clock.tick(10);
...@@ -184,8 +180,8 @@ test ('Simple Job Replacement', function () { ...@@ -184,8 +180,8 @@ test ('Simple Job Replacement', function () {
o.jio.stop(); o.jio.stop();
}); });
test ('Simple Job Waiting', function () { test ('Simple Job Waiting', function () {
// Test if the second job doesn't erase the first ongoing one // Test if the second job doesn't erase the first ongoing one
var o = {}, clock = this.sandbox.useFakeTimers(), id = 0; var o = {}, clock = this.sandbox.useFakeTimers(), id = 0;
...@@ -193,7 +189,7 @@ test ('Simple Job Waiting', function () { ...@@ -193,7 +189,7 @@ test ('Simple Job Waiting', function () {
o.jio = JIO.createNew({'type':'dummyallok','userName':'dummy'}, o.jio = JIO.createNew({'type':'dummyallok','userName':'dummy'},
{'ID':'jiotests'}); {'ID':'jiotests'});
id = o.jio.id; id = o.jio.getID();
o.jio.saveDocument({'fileName':'file','fileContent':'content', o.jio.saveDocument({'fileName':'file','fileContent':'content',
'callback':o.f3,'maxtries':1}); 'callback':o.f3,'maxtries':1});
clock.tick(200); clock.tick(200);
...@@ -220,7 +216,7 @@ test ('Simple Job Waiting', function () { ...@@ -220,7 +216,7 @@ test ('Simple Job Waiting', function () {
test ('Simple Time Waiting' , function () { test ('Simple Time Waiting' , function () {
// Test if the job that have fail wait until a certain moment to restart. // Test if the job that have fail wait until a certain moment to restart.
// It will use the dummyall3tries, which will work after the 3rd try. // It will use the dummyall3tries, which will work after the 3rd try.
var o = {}, clock = this.sandbox.useFakeTimers(), id = 0; var o = {}, clock = this.sandbox.useFakeTimers(), id = 0;
o.f = function (result) { o.f = function (result) {
o.res = (result.status === 'done'); o.res = (result.status === 'done');
...@@ -273,7 +269,7 @@ test ('Check name availability', function () { ...@@ -273,7 +269,7 @@ test ('Check name availability', function () {
test ('Document save', function () { test ('Document save', function () {
// Test if LocalStorage can save documents. // Test if LocalStorage can save documents.
// We launch a saving to localstorage and we check if the file is // We launch a saving to localstorage and we check if the file is
// realy saved. Then save again and check if // realy saved. Then save again and check if
var o = {}, clock = this.sandbox.useFakeTimers(), t = this, tmp, var o = {}, clock = this.sandbox.useFakeTimers(), t = this, tmp,
mytest = function (message,value,lmcd){ mytest = function (message,value,lmcd){
...@@ -306,7 +302,7 @@ test ('Document save', function () { ...@@ -306,7 +302,7 @@ test ('Document save', function () {
mytest('saving document',true,function(cd,lm){ mytest('saving document',true,function(cd,lm){
return (cd === lm); return (cd === lm);
}); });
// re-save and check modification date // re-save and check modification date
mytest('saving again',true,function(cd,lm){ mytest('saving again',true,function(cd,lm){
return (cd < lm); return (cd < lm);
...@@ -337,7 +333,7 @@ test ('Document load', function () { ...@@ -337,7 +333,7 @@ test ('Document load', function () {
// load a non existing file // load a non existing file
LocalOrCookieStorage.deleteItem ('jio/local/MrLoadName/jiotests/file'); LocalOrCookieStorage.deleteItem ('jio/local/MrLoadName/jiotests/file');
mytest ('status','fail'); mytest ('status','fail');
// re-load file after saving it manually // re-load file after saving it manually
doc = {'fileName':'file','fileContent':'content', doc = {'fileName':'file','fileContent':'content',
'lastModified':1234,'creationDate':1000}; 'lastModified':1234,'creationDate':1000};
...@@ -418,7 +414,7 @@ module ('Jio DAVStorage'); ...@@ -418,7 +414,7 @@ module ('Jio DAVStorage');
test ('Check name availability', function () { test ('Check name availability', function () {
// Test if DavStorage can check the availabality of a name. // Test if DavStorage can check the availabality of a name.
var o = {}, clock = this.sandbox.useFakeTimers(), t = this, var o = {}, clock = this.sandbox.useFakeTimers(), t = this,
mytest = function (value,errno) { mytest = function (value,errno) {
var server = t.sandbox.useFakeServer(); var server = t.sandbox.useFakeServer();
...@@ -436,7 +432,7 @@ test ('Check name availability', function () { ...@@ -436,7 +432,7 @@ test ('Check name availability', function () {
if (!o.f.calledOnce) if (!o.f.calledOnce)
ok(false, 'no response / too much results'); ok(false, 'no response / too much results');
}; };
o.jio = JIO.createNew({'type':'dav','userName':'davcheck', o.jio = JIO.createNew({'type':'dav','userName':'davcheck',
'password':'checkpwd', 'password':'checkpwd',
'location':'https://ca-davstorage:8080'}, 'location':'https://ca-davstorage:8080'},
...@@ -479,8 +475,8 @@ test ('Document load', function () { ...@@ -479,8 +475,8 @@ test ('Document load', function () {
'location':'https://ca-davstorage:8080'}, 'location':'https://ca-davstorage:8080'},
{'ID':'jiotests'}); {'ID':'jiotests'});
// note: http errno: // note: http errno:
// 200 OK // 200 OK
// 201 Created // 201 Created
// 204 No Content // 204 No Content
// 207 Multi Status // 207 Multi Status
// 403 Forbidden // 403 Forbidden
...@@ -614,7 +610,7 @@ test ('Remove document', function () { ...@@ -614,7 +610,7 @@ test ('Remove document', function () {
'password':'checkpwd', 'password':'checkpwd',
'location':'https://ca-davstorage:8080'}, 'location':'https://ca-davstorage:8080'},
{'ID':'jiotests'}); {'ID':'jiotests'});
mytest('remove document',true,204) mytest('remove document',true,204)
mytest('remove an already removed document',true,404) mytest('remove an already removed document',true,404)
o.jio.stop(); o.jio.stop();
...@@ -720,7 +716,7 @@ test ('Document load', function () { ...@@ -720,7 +716,7 @@ test ('Document load', function () {
'fileName':'file','fileContent':'content2', 'fileName':'file','fileContent':'content2',
'lastModified':17000, 'lastModified':17000,
'creationDate':10000}); 'creationDate':10000});
o.jio.stop(); o.jio.stop();
}); });
......
;var JIO = ;var JIO =
(function () { (function () {
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
// constants // constants
var jioConstObj = { var jioConstObj = {
...@@ -43,7 +43,7 @@ ...@@ -43,7 +43,7 @@
- o: options - o: options
- =: are equal - =: are equal
- !: are not equal - !: are not equal
select ALL s= a= n= select ALL s= a= n=
removefailordone fail|done removefailordone fail|done
/ elim repl nacc wait / elim repl nacc wait
...@@ -99,7 +99,7 @@ ...@@ -99,7 +99,7 @@
Save ongoing Check 0 0 0 0 Save ongoing Check 0 0 0 0
Save !ongoing GetList 0 0 0 0 Save !ongoing GetList 0 0 0 0
Save !ongoing Check 0 0 0 0 Save !ongoing Check 0 0 0 0
For more information, see documentation For more information, see documentation
*/ */
'canSelect':function (job1,job2) { 'canSelect':function (job1,job2) {
...@@ -131,7 +131,7 @@ ...@@ -131,7 +131,7 @@
}, },
'canReplace':function (job1,job2) { 'canReplace':function (job1,job2) {
if (job1.status !== 'ongoing' && if (job1.status !== 'ongoing' &&
job1.method === job2.method && job1.method === job2.method &&
job1.date < job2.date) { job1.date < job2.date) {
return true; return true;
} }
...@@ -195,32 +195,12 @@ ...@@ -195,32 +195,12 @@
catch (e) { err('LocalOrCookieStorage'); } catch (e) { err('LocalOrCookieStorage'); }
return retval; return retval;
}, },
getNewQueueID = function () {
// Returns a new queueID
var localStor = jioGlobalObj.localStorage.getAll(), id = 0, k = 'key',
splitk = ['splitedkey'];
for (k in localStor) {
splitk = k.split('/');
if (splitk[0] === 'jio' &&
splitk[1] === 'id') {
if (JSON.parse(localStor[k]) < Date.now() - 10000) { // 10 sec ?
jioGlobalObj.localStorage.deleteItem(k);
}
if (JSON.parse(splitk[2]) >= jioGlobalObj.queueID) {
jioGlobalObj.queueID = JSON.parse(splitk[2]) + 1;
}
}
}
id = jioGlobalObj.queueID;
jioGlobalObj.queueID ++;
return id;
},
// end Tools // end Tools
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
// Classes // Classes
PubSub,Job,JobQueue,JobListener,ActivityUpdater,BaseStorage,JioCons,Jio; PubSub,Job,JobQueue,JobListener,ActivityUpdater,BaseStorage,JioCons,Jio;
// end Classes // end Classes
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
...@@ -230,8 +210,9 @@ ...@@ -230,8 +210,9 @@
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
// Publisher Subcriber // Publisher Subcriber
PubSub = function () { PubSub = function () {
var topics = {}, callbacks, topic; var that = {}, priv = {},
this.eventAction = function (id) { topics = {}, callbacks, topic;
priv.eventAction = function (id) {
topic = id && topics[id]; topic = id && topics[id];
if (!topic) { if (!topic) {
callbacks = $.Callbacks(); callbacks = $.Callbacks();
...@@ -246,21 +227,20 @@ ...@@ -246,21 +227,20 @@
} }
return topic; return topic;
}; };
}; that.publish = function (eventname,obj) {
PubSub.prototype = {
publish: function (eventname,obj) {
// publish an event // publish an event
this.eventAction(eventname).publish(obj); priv.eventAction(eventname).publish(obj);
}, };
subscribe: function (eventname,callback) { that.subscribe = function (eventname,callback) {
// subscribe and return the callback function // subscribe and return the callback function
this.eventAction(eventname).subscribe(callback); priv.eventAction(eventname).subscribe(callback);
return callback; return callback;
}, };
unsubscribe: function (eventname,callback) { that.unsubscribe = function (eventname,callback) {
// unsubscribe the callback from eventname // unsubscribe the callback from eventname
this.eventAction(eventname).unsubscribe(callback); priv.eventAction(eventname).unsubscribe(callback);
} };
return that;
}; };
// end Publisher Subcriber // end Publisher Subcriber
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
...@@ -269,7 +249,7 @@ ...@@ -269,7 +249,7 @@
// Job & JobQueue // Job & JobQueue
Job = function ( options ) { Job = function ( options ) {
// Job constructor // Job constructor
var job = $.extend({},options); var job = $.extend({},options);
job['id']=0; job['id']=0;
job['status']='initial'; job['status']='initial';
...@@ -283,106 +263,116 @@ ...@@ -283,106 +263,116 @@
// publisher: the publisher to use to send event // publisher: the publisher to use to send event
// options.useLocalStorage: if true, save jobs into localStorage, // options.useLocalStorage: if true, save jobs into localStorage,
// else only save on memory. // else only save on memory.
this.useLocalStorage = options.useLocalStorage;
this.publisher = publisher;
this.jobid = 1;
this.jioID = 0;
this.jobObjectName = '';
this.jobObject = {};
// reset all jobs' status to initial
this.resetAll();
}; var that = {}, priv = {};
JobQueue.prototype = { that.init = function ( options ) {
init: function ( options ) {
// initialize the JobQueue // initialize the JobQueue
// options.publisher : is the publisher to use to send events // options.publisher : is the publisher to use to send events
// options.jioID : the jio ID // options.jioID : the jio ID
if (options.publisher) if (options.publisher)
this.publisher = publisher; priv.publisher = publisher;
this.jioID = options.jioID; priv.jioID = options.jioID;
this.jobObjectName = 'jio/jobObject/'+options.jioID; priv.jobObjectName = 'jio/jobObject/'+options.jioID;
this.jobObject = {}; priv.jobObject = {};
this.copyJobQueueToLocalStorage(); that.copyJobQueueToLocalStorage();
}, };
close: function () { that.close = function () {
// close the job queue. // close the job queue.
// it also deletes from local storage only if the job list is // it also deletes from local storage only if the job list is
// empty. // empty.
if (JSON.stringify(this.jobObject) === '{}') { if (JSON.stringify(priv.jobObject) === '{}') {
jioGlobalObj.localStorage.deleteItem(this.jobObjectName); jioGlobalObj.localStorage.deleteItem(priv.jobObjectName);
} }
}, };
isThereJobsWhere: function( func ) { that.getNewQueueID = function () {
// Returns a new queueID
var localStorageObject = jioGlobalObj.localStorage.getAll(),
id = 0, k = 'key', splitk = ['splitedkey'];
for (k in localStorageObject) {
splitk = k.split('/');
if (splitk[0] === 'jio' &&
splitk[1] === 'id') {
if (JSON.parse(localStorageObject[k]) < Date.now() - 10000){
// 10 sec ?
jioGlobalObj.localStorage.deleteItem(k);
}
if (JSON.parse(splitk[2]) >= jioGlobalObj.queueID) {
jioGlobalObj.queueID = JSON.parse(splitk[2]) + 1;
}
}
}
id = jioGlobalObj.queueID;
jioGlobalObj.queueID ++;
return id;
};
that.isThereJobsWhere = function( func ) {
// Check if there is jobs, in the queue, // Check if there is jobs, in the queue,
// where [func](job) == true. // where [func](job) == true.
var id = 'id'; var id = 'id';
if (!func) { return true; } if (!func) { return true; }
for (id in this.jobObject) { for (id in priv.jobObject) {
if (func(this.jobObject[id])) if (func(priv.jobObject[id]))
return true; return true;
} }
return false; return false;
}, };
copyJobQueueToLocalStorage: function () { that.copyJobQueueToLocalStorage = function () {
// Copy job queue into localStorage. // Copy job queue into localStorage.
if (this.useLocalStorage) { if (priv.useLocalStorage) {
return jioGlobalObj.localStorage.setItem( return jioGlobalObj.localStorage.setItem(
this.jobObjectName,this.jobObject); priv.jobObjectName,priv.jobObject);
} else { } else {
return false; return false;
} }
}, };
createJob: function ( options ) { that.createJob = function ( options ) {
return this.addJob ( new Job ( options ) ); return that.addJob ( new Job ( options ) );
}, };
addJob: function ( job ) { that.addJob = function ( job ) {
// Add a job to the queue, browsing all jobs // Add a job to the queue, browsing all jobs
// and check if the new job can eliminate older ones, // and check if the new job can eliminate older ones,
// can replace older one, can be accepted, or must wait // can replace older one, can be accepted, or must wait
// for older ones. // for older ones.
// It also clean fail or done jobs. // It also clean fail or done jobs.
// job : the job object // job = the job object
var res = {'newone':true,'elimArray':[],'waitArray':[], var res = {'newone':true,'elimArray':[],'waitArray':[],
'removeArray':[]}, basestorage = null, id = 'id'; 'removeArray':[]}, basestorage = null, id = 'id';
//// browsing current jobs //// browsing current jobs
for (id in this.jobObject) { for (id in priv.jobObject) {
if (jioGlobalObj.jobManagingMethod.canSelect( if (jioGlobalObj.jobManagingMethod.canSelect(
this.jobObject[id],job)) { priv.jobObject[id],job)) {
if (jioGlobalObj.jobManagingMethod.canRemoveFailOrDone( if (jioGlobalObj.jobManagingMethod.canRemoveFailOrDone(
this.jobObject[id],job)) { priv.jobObject[id],job)) {
res.removeArray.push(id); res.removeArray.push(id);
continue; continue;
} }
if (jioGlobalObj.jobManagingMethod.canEliminate( if (jioGlobalObj.jobManagingMethod.canEliminate(
this.jobObject[id],job)) { priv.jobObject[id],job)) {
res.elimArray.push(id); res.elimArray.push(id);
continue; continue;
} }
if (jioGlobalObj.jobManagingMethod.canReplace( if (jioGlobalObj.jobManagingMethod.canReplace(
this.jobObject[id],job)) { priv.jobObject[id],job)) {
basestorage = new BaseStorage( basestorage = new BaseStorage(
{'queue':this,'job':this.jobObject[id]}); {'queue':that,'job':priv.jobObject[id]});
basestorage.replace(job); basestorage.replace(job);
res.newone = false; res.newone = false;
break; break;
} }
if (jioGlobalObj.jobManagingMethod.cannotAccept( if (jioGlobalObj.jobManagingMethod.cannotAccept(
this.jobObject[id],job)) { priv.jobObject[id],job)) {
// Job not accepted // Job not accepted
return false; return false;
} }
if (jioGlobalObj.jobManagingMethod.mustWait( if (jioGlobalObj.jobManagingMethod.mustWait(
this.jobObject[id],job)) { priv.jobObject[id],job)) {
res.waitArray.push(id); res.waitArray.push(id);
continue; continue;
} }
...@@ -391,61 +381,61 @@ ...@@ -391,61 +381,61 @@
} }
} }
//// end browsing current jobs //// end browsing current jobs
if (res.newone) { if (res.newone) {
// if it is a new job, we can eliminate deprecated jobs and // if it is a new job, we can eliminate deprecated jobs and
// set this job dependencies. // set this job dependencies.
for (id in res.elimArray) { for (id in res.elimArray) {
basestorage = new BaseStorage( basestorage = new BaseStorage(
{'queue':this,'job':this.jobObject[res.elimArray[id]]}); {'queue':that,'job':priv.jobObject[res.elimArray[id]]});
basestorage.eliminate(); basestorage.eliminate();
} }
if (res.waitArray.length > 0) { if (res.waitArray.length > 0) {
job.status = 'wait'; job.status = 'wait';
job.waitingFor = {'jobIdArray':res.waitArray}; job.waitingFor = {'jobIdArray':res.waitArray};
for (id in res.waitArray) { for (id in res.waitArray) {
if (this.jobObject[res.waitArray[id]]) { if (priv.jobObject[res.waitArray[id]]) {
this.jobObject[res.waitArray[id]].maxtries = 1; priv.jobObject[res.waitArray[id]].maxtries = 1;
} }
} }
} }
for (id in res.removeArray) { for (id in res.removeArray) {
this.removeJob(this.jobObject[res.removeArray[id]]); that.removeJob(priv.jobObject[res.removeArray[id]]);
} }
// set job id // set job id
job.id = this.jobid; job.id = priv.jobid;
job.tries = 0; job.tries = 0;
this.jobid ++; priv.jobid ++;
// save the new job into the queue // save the new job into the queue
this.jobObject[job.id] = job; priv.jobObject[job.id] = job;
} }
// save into localStorage // save into localStorage
this.copyJobQueueToLocalStorage(); that.copyJobQueueToLocalStorage();
return true; return true;
}, // end addJob }; // end addJob
removeJob: function ( options ) { that.removeJob = function ( options ) {
// Remove job(s) from queue where [options.where](job) === true. // Remove job(s) from queue where [options.where](job) === true.
// If there is no job in [options], then it will treat all job. // If there is no job in [options], then it will treat all job.
// If there is no [where] function, then it will remove all selected // If there is no [where] function, then it will remove all selected
// job. It means that if no option was given, it'll remove all jobs. // job. It means that if no option was given, it'll remove all jobs.
// options.job : the job object containing at least {id:..}. // options.job = the job object containing at least {id:..}.
// options.where : remove values where options.where(job) === true // options.where = remove values where options.where(job) === true
var settings = $.extend ({'where':function (job) {return true;}}, var settings = $.extend ({'where':function (job) {return true;}},
options),andwhere,found=false,k='key'; options),andwhere,found=false,k='key';
//// modify the job list //// modify the job list
if (settings.job) { if (settings.job) {
if (this.jobObject[settings.job.id] && settings.where( if (priv.jobObject[settings.job.id] && settings.where(
this.jobObject[settings.job.id]) ) { priv.jobObject[settings.job.id]) ) {
delete this.jobObject[settings.job.id]; delete priv.jobObject[settings.job.id];
found = true; found = true;
} }
}else { }else {
for (k in this.jobObject) { for (k in priv.jobObject) {
if (settings.where(this.jobObject[k])) { if (settings.where(priv.jobObject[k])) {
delete this.jobObject[k]; delete priv.jobObject[k];
found = true; found = true;
} }
} }
...@@ -454,39 +444,39 @@ ...@@ -454,39 +444,39 @@
$.error ('No jobs was found, when trying to remove some.'); $.error ('No jobs was found, when trying to remove some.');
} }
//// end modifying //// end modifying
this.copyJobQueueToLocalStorage(); that.copyJobQueueToLocalStorage();
}, };
resetAll: function () { that.resetAll = function () {
// Reset all job to 'initial'. // Reset all job to 'initial'.
// TODO manage jobs ! All jobs are not 'initial'. // TODO manage jobs ! All jobs are not 'initial'.
var id = 'id'; var id = 'id';
for (id in this.jobObject) { for (id in priv.jobObject) {
this.jobObject[id].status = 'initial'; priv.jobObject[id].status = 'initial';
} }
this.copyJobQueueToLocalStorage(); that.copyJobQueueToLocalStorage();
}, };
invokeAll: function () { that.invokeAll = function () {
// Do all jobs in the queue. // Do all jobs in the queue.
var i = 'id', ok; var i = 'id', ok;
//// do All jobs //// do All jobs
for (i in this.jobObject) { for (i in priv.jobObject) {
ok = false; ok = false;
if (this.jobObject[i].status === 'initial') { if (priv.jobObject[i].status === 'initial') {
// if status initial // if status initial
// invoke new job // invoke new job
this.invoke(this.jobObject[i]); that.invoke(priv.jobObject[i]);
} else if (this.jobObject[i].status === 'wait') { } else if (priv.jobObject[i].status === 'wait') {
ok = true; ok = true;
// if status wait // if status wait
if (this.jobObject[i].waitingFor.jobIdArray) { if (priv.jobObject[i].waitingFor.jobIdArray) {
// wait job // wait job
// browsing job id array // browsing job id array
for (var j in this.jobObject[i].waitingFor.jobIdArray) { for (var j in priv.jobObject[i].waitingFor.jobIdArray) {
if (this.jobObject[this.jobObject[i]. if (priv.jobObject[priv.jobObject[i].
waitingFor.jobIdArray[j]]) { waitingFor.jobIdArray[j]]) {
// if a job is still exist, don't invoke // if a job is still exist, don't invoke
ok = false; ok = false;
...@@ -494,9 +484,9 @@ ...@@ -494,9 +484,9 @@
} }
} }
} }
if (this.jobObject[i].waitingFor.time) { if (priv.jobObject[i].waitingFor.time) {
// wait time // wait time
if (this.jobObject[i].waitingFor.time > Date.now()) { if (priv.jobObject[i].waitingFor.time > Date.now()) {
// it is not time to restore the job! // it is not time to restore the job!
ok = false; ok = false;
} }
...@@ -504,19 +494,18 @@ ...@@ -504,19 +494,18 @@
// else wait nothing // else wait nothing
if (ok) { if (ok) {
// invoke waiting job // invoke waiting job
this.invoke(this.jobObject[i]); that.invoke(priv.jobObject[i]);
} }
} }
} }
this.copyJobQueueToLocalStorage(); this.copyJobQueueToLocalStorage();
//// end, continue doing jobs asynchronously //// end, continue doing jobs asynchronously
}, };
invoke: function (job) { that.invoke = function (job) {
// Do a job invoking the good method in the good storage. // Do a job invoking the good method in the good storage.
var t = this, basestorage, var basestorage;
userName = job.userName ? job.userName : job.storage.userName;
//// analysing job method //// analysing job method
// if the method does not exist, do nothing // if the method does not exist, do nothing
...@@ -524,12 +513,12 @@ ...@@ -524,12 +513,12 @@
return false; // suppose never happen return false; // suppose never happen
// test if a similar job is on going, in order to publish a start // test if a similar job is on going, in order to publish a start
// event if it is the first of his kind (method). // event if it is the first of his kind (method).
if (!this.isThereJobsWhere(function (testjob){ if (!that.isThereJobsWhere(function (testjob){
return (testjob.method === job.method && return (testjob.method === job.method &&
testjob.method === 'initial'); testjob.method === 'initial');
})) { })) {
job.status = 'ongoing'; job.status = 'ongoing';
this.publisher.publish(jioConstObj.jobMethodObject[ priv.publisher.publish(jioConstObj.jobMethodObject[
job.method].start_event); job.method].start_event);
} else { } else {
job.status = 'ongoing'; job.status = 'ongoing';
...@@ -538,21 +527,21 @@ ...@@ -538,21 +527,21 @@
basestorage = new BaseStorage({'queue':this,'job':job}); basestorage = new BaseStorage({'queue':this,'job':job});
basestorage.execute(); basestorage.execute();
//// end method analyse //// end method analyse
}, };
ended: function (job) { that.ended = function (job) {
// It is a callback function called just before user callback. // It is a callback function called just before user callback.
// It is called to manage jobObject according to the ended job. // It is called to manage jobObject according to the ended job.
switch (job.status) { switch (job.status) {
case 'done': case 'done':
// This job is supposed done, we can remove it from queue. // This job is supposed done, we can remove it from queue.
this.removeJob ({'job':job}); that.removeJob ({'job':job});
break; break;
case 'fail': case 'fail':
// This job cannot be done. // This job cannot be done.
// save to local storage // save to local storage
this.copyJobQueueToLocalStorage (); that.copyJobQueueToLocalStorage ();
break; break;
case 'wait': case 'wait':
break; break;
...@@ -565,29 +554,41 @@ ...@@ -565,29 +554,41 @@
if (!jioConstObj.jobMethodObject[job.method]) if (!jioConstObj.jobMethodObject[job.method])
return false; return false;
// if there isn't some job to do, then send stop event // if there isn't some job to do, then send stop event
if (!this.isThereJobsWhere(function(testjob){ if (!that.isThereJobsWhere(function(testjob){
return (testjob.method === job.method && return (testjob.method === job.method &&
// testjob.status === 'wait' || // TODO ? // testjob.status === 'wait' || // TODO ?
testjob.status === 'ongoing' || testjob.status === 'ongoing' ||
testjob.status === 'initial'); testjob.status === 'initial');
})) { })) {
this.publisher.publish( priv.publisher.publish(
jioConstObj.jobMethodObject[ jioConstObj.jobMethodObject[
job.method].stop_event); job.method].stop_event);
return; return;
} }
//// end returnedJobAnalyse //// end returnedJobAnalyse
}, };
clean: function () { that.clean = function () {
// Clean the job list, removing all jobs that have failed. // Clean the job list, removing all jobs that have failed.
// It also change the localStorage job queue // It also change the localStorage job queue
this.removeJob ( that.removeJob (
undefined,{ undefined,{
'where':function (job) { 'where':function (job) {
return (job.status === 'fail'); return (job.status === 'fail');
} }); } });
} };
//// end Methods
//// Initialize
priv.useLocalStorage = options.useLocalStorage;
priv.publisher = publisher;
priv.jobid = 1;
priv.jioID = 0;
priv.jobObjectName = '';
priv.jobObject = {};
//// end Initialize
return that;
}; };
// end Job & JobQueue // end Job & JobQueue
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
...@@ -596,43 +597,42 @@ ...@@ -596,43 +597,42 @@
// jio job listener // jio job listener
JobListener = function ( queue ) { JobListener = function ( queue ) {
// A little daemon which will start jobs from the joblist // A little daemon which will start jobs from the joblist
var that = {}, priv = {};
this.interval = 200;
this.id = null; priv.interval = 200;
this.queue = queue; priv.id = null;
}; priv.queue = queue;
JobListener.prototype = { that.setIntervalDelay = function (interval) {
setIntervalDelay: function (interval) {
// Set the time between two joblist check in millisec // Set the time between two joblist check in millisec
this.interval = interval; priv.interval = interval;
}, };
start: function () { that.start = function () {
// Start the listener. It will always check if there are jobs in the // Start the listener. It will always check if there are jobs in the
// queue // queue
var queue = this.queue;
if (!priv.id) {
if (!this.id) { priv.id = setInterval (function () {
this.id = setInterval (function () {
// if there is jobs // if there is jobs
if (JSON.stringify(queue.jobObject) !== '{}') { if (JSON.stringify(queue.jobObject) !== '{}') {
queue.invokeAll(); priv.queue.invokeAll();
} }
},this.interval); },priv.interval);
return true; return true;
} else { } else {
return false; return false;
} }
}, };
stop: function () { that.stop = function () {
if (this.id) { if (priv.id) {
clearInterval (this.id); clearInterval (priv.id);
this.id = null; priv.id = null;
return true; return true;
} }
return false; return false;
} };
return that;
} }
// end jio job listener // end jio job listener
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
...@@ -643,38 +643,42 @@ ...@@ -643,38 +643,42 @@
// The activity updater is a little thread that proves activity of this // The activity updater is a little thread that proves activity of this
// jio instance. // jio instance.
this.interval = 400; var that = {}, priv = {};
this.id = null;
}; //// private vars
ActivityUpdater.prototype = { priv.interval = 400;
start: function (id) { priv.id = null;
//// end private vars
//// methods
that.start = function (id) {
// start the updater // start the updater
var t = this; if (!priv.id) {
that.touch(id);
if (!this.id) { priv.id = setInterval (function () {
this.touch(id); that.touch(id);
this.id = setInterval (function () { },priv.interval);
t.touch(id);
},this.interval);
return true; return true;
} else { } else {
return false; return false;
} }
}, };
stop: function () { that.stop = function () {
// stop the updater // stop the updater
if (this.id) { if (priv.id) {
clearInterval (this.id); clearInterval (priv.id);
this.id = null; priv.id = null;
return true; return true;
} }
return false; return false;
}, };
touch: function (id) { that.touch = function (id) {
jioGlobalObj.localStorage.setItem ('jio/id/' + id, jioGlobalObj.localStorage.setItem ('jio/id/' + id,
Date.now() ); Date.now() );
} };
//// end methods
return that;
}; };
// end ActivityUpdater // end ActivityUpdater
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
...@@ -684,7 +688,7 @@ ...@@ -684,7 +688,7 @@
BaseStorage = function ( options ) { BaseStorage = function ( options ) {
// The base storage, will call the good method from the good storage, // The base storage, will call the good method from the good storage,
// and will check and return the associated value. // and will check and return the associated value.
var that = {}, priv = {}; var that = {}, priv = {};
//// Private attributes //// Private attributes
...@@ -735,7 +739,7 @@ ...@@ -735,7 +739,7 @@
priv.retryLater = function () { priv.retryLater = function () {
// Change the job status to wait for time. // Change the job status to wait for time.
// The listener will invoke this job later. // The listener will invoke this job later.
priv.job.status = 'wait'; priv.job.status = 'wait';
priv.job.waitingFor = {'time':Date.now() + priv.job.waitingFor = {'time':Date.now() +
(priv.job.tries*priv.job.tries*1000)}; (priv.job.tries*priv.job.tries*1000)};
...@@ -841,7 +845,7 @@ ...@@ -841,7 +845,7 @@
// Execute the good function from the good storage. // Execute the good function from the good storage.
priv.job.tries = that.getTries() + 1; priv.job.tries = that.getTries() + 1;
if ( !jioGlobalObj.storageTypeObject[ priv.job.storage.type ] ) { if ( !jioGlobalObj.storageTypeObject[ priv.job.storage.type ] ) {
return null; return null;
} }
...@@ -872,116 +876,93 @@ ...@@ -872,116 +876,93 @@
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
// JIO Constructor // JIO Constructor
JioCons = function ( storage , applicant, options ) { JioConstructor = function ( storage , applicant, options ) {
// JIO Constructor, create a new JIO object. // JIO Constructor, create a new JIO object.
// It just initializes values. // It just initializes values.
// storage : the storage that contains {type:..,[storageinfos]} // storage : the storage that contains {type:..,[storageinfos]}
// applicant : the applicant that contains {ID:...} // applicant : the applicant that contains {ID:...}
// these parameters are optional and may be 'string' or 'object' // these parameters are optional and may be 'string' or 'object'
var settings = $.extend({'useLocalStorage':true},options); var that = {}, priv = {};
// objectify storage and applicant
if(typeof storage === 'string')
storage = JSON.parse(options.storage);
if(typeof applicant === 'string')
applicant = JSON.parse(options.applicant);
// set init values
this['storage'] = storage;
this['applicant'] = applicant;
this['id'] = 0;
this['pubsub'] = new PubSub(settings);
this['queue'] = new JobQueue(this.pubsub,settings);
this['listener'] = new JobListener(this.queue,settings);
this['ready'] = false;
if (settings.useLocalStorage) {
this['updater'] = new ActivityUpdater(settings);
} else {
this['updater'] = null;
}
// check storage type //// Getters Setters
if (this.storage && !jioGlobalObj.storageTypeObject[this.storage.type]){ that.getID = function () {
$.error('Unknown storage type "' + this.storage.type +'"'); return priv.id;
} };
//// end Getters Setters
// start jio process //// Methods
this.start(); that.start = function () {
};
// JIO Prototype
JioCons.prototype = {
start: function () {
// Start JIO: start listening to jobs and make it ready // Start JIO: start listening to jobs and make it ready
if (this.id !== 0) return false; if (priv.id !== 0) return false;
// set a new jio id // set a new jio id
this.id = getNewQueueID(); priv.id = priv.queue.getNewQueueID();
// initializing objects // initializing objects
this.queue.init({'jioID':this.id}); priv.queue.init({'jioID':priv.id});
// start activity updater // start activity updater
if (this.updater){ if (priv.updater){
this.updater.start(this.id); priv.updater.start(priv.id);
} }
// start listening // start listening
this.listener.start(); priv.listener.start();
// is now ready // is now ready
this.ready = true; priv.ready = true;
return this.isReady(); return that.isReady();
}, };
stop: function () { that.stop = function () {
// Finish some job if possible and stop listening. // Finish some job if possible and stop listening.
// It can be restarted later // It can be restarted later
this.queue.close(); priv.queue.close();
this.listener.stop(); priv.listener.stop();
if (this.updater) { if (priv.updater) {
this.updater.stop(); priv.updater.stop();
} }
this.ready = false; priv.ready = false;
this.id = 0; priv.id = 0;
return true; return true;
}, };
kill: function () { that.kill = function () {
// kill this JIO, job listening and job operation (event if they // kill this JIO, job listening and job operation (event if they
// are on going!) // are on going!)
this.queue.close(); priv.queue.close();
this.listener.stop(); priv.listener.stop();
if (this.updater) { if (priv.updater) {
this.updater.stop(); priv.updater.stop();
} }
// TODO // TODO
this.ready = false; priv.ready = false;
return true; return true;
}, };
isReady: function () { that.isReady = function () {
// Check if Jio is ready to use. // Check if Jio is ready to use.
return this.ready; return priv.ready;
}, };
publish: function (eventname, obj) { that.publish = function (eventname, obj) {
// publish an event on this jio // publish an event on this jio
// eventname : the event name // eventname : the event name
// obj : is an object containing some parameters for example // obj : is an object containing some parameters for example
if (!this.isReady()) return ; if (!that.isReady()) return ;
return this.pubsub.publish(eventname,obj); return priv.pubsub.publish(eventname,obj);
}, };
subscribe: function (eventname, callback) { that.subscribe = function (eventname, callback) {
// subscribe to an event on this jio. We can subscribe to jio event // subscribe to an event on this jio. We can subscribe to jio event
// even if jio is not started. Returns the callback function in // even if jio is not started. Returns the callback function in
// order to unsubscribe it. // order to unsubscribe it.
// eventname : the event name. // eventname : the event name.
// callback : called after receiving event. // callback : called after receiving event.
return this.pubsub.subscribe(eventname,callback); return priv.pubsub.subscribe(eventname,callback);
}, };
unsubscribe: function (eventname,callback) { that.unsubscribe = function (eventname,callback) {
// unsubscribe callback from an event // unsubscribe callback from an event
return this.pubsub.unsubscribe(eventname,callback);
},
checkNameAvailability: function ( options ) { return priv.pubsub.unsubscribe(eventname,callback);
};
that.checkNameAvailability = function ( options ) {
// Check the user availability in the storage set in [options] // Check the user availability in the storage set in [options]
// or in the storage set at init. At the end of the job, // or in the storage set at init. At the end of the job,
// 'job_done' will be sent with this job and its 'isAvailable' // 'job_done' will be sent with this job and its 'isAvailable'
...@@ -1000,21 +981,21 @@ ...@@ -1000,21 +981,21 @@
// result.isAvailable); }}); // result.isAvailable); }});
var settings = $.extend ({ var settings = $.extend ({
'userName': this.storage.userName, 'userName': priv.storage.userName,
'storage': this.storage, 'storage': priv.storage,
'applicant': this.applicant, 'applicant': priv.applicant,
'method': 'checkNameAvailability', 'method': 'checkNameAvailability',
'callback': function () {} 'callback': function () {}
},options); },options);
// check dependencies // check dependencies
if (this.isReady() && settings.userName && if (that.isReady() && settings.userName &&
settings.storage && settings.applicant) { settings.storage && settings.applicant) {
return this.queue.createJob ( settings ); return priv.queue.createJob ( settings );
} }
return null; return null;
}, };
saveDocument: function ( options ) { that.saveDocument = function ( options ) {
// Load a document in the storage set in [options] // Load a document in the storage set in [options]
// or in the storage set at init. At the end of the job, // or in the storage set at init. At the end of the job,
// 'job_done' will be sent with this job. // 'job_done' will be sent with this job.
...@@ -1031,20 +1012,20 @@ ...@@ -1031,20 +1012,20 @@
// result.isSaved); }}); // result.isSaved); }});
var settings = $.extend({ var settings = $.extend({
'storage': this.storage, 'storage': priv.storage,
'applicant': priv.applicant,
'method':'saveDocument', 'method':'saveDocument',
'applicant': this.applicant,
'callback': function () {} 'callback': function () {}
},options); },options);
// check dependencies // check dependencies
if (this.isReady() && settings.fileName && settings.fileContent && if (that.isReady() && settings.fileName && settings.fileContent &&
settings.storage && settings.applicant) { settings.storage && settings.applicant) {
return this.queue.createJob ( settings ); return priv.queue.createJob ( settings );
} }
return null; return null;
}, },
loadDocument: function ( options ) { that.loadDocument = function ( options ) {
// Load a document in the storage set in [options] // Load a document in the storage set in [options]
// or in the storage set at init. At the end of the job, // or in the storage set at init. At the end of the job,
// 'job_done' will be sent with this job and its 'fileContent' // 'job_done' will be sent with this job and its 'fileContent'
...@@ -1063,20 +1044,20 @@ ...@@ -1063,20 +1044,20 @@
// result.doc.creationDate); }}); // result.doc.creationDate); }});
var settings = $.extend ({ var settings = $.extend ({
'storage': this.storage, 'storage': priv.storage,
'applicant': this.applicant, 'applicant': priv.applicant,
'method':'loadDocument', 'method':'loadDocument',
'callback': function(){} 'callback': function(){}
},options); },options);
// check dependencies // check dependencies
if (this.isReady() && settings.fileName && if (that.isReady() && settings.fileName &&
settings.storage && settings.applicant) { settings.storage && settings.applicant) {
return this.queue.createJob ( settings ); return priv.queue.createJob ( settings );
} }
return null; return null;
}, };
getDocumentList: function ( options ) { that.getDocumentList = function ( options ) {
// Get a document list of the user in the storage set in [options] // Get a document list of the user in the storage set in [options]
// or in the storage set at init. // or in the storage set at init.
// options.storage : the storage where to get the list (optional) // options.storage : the storage where to get the list (optional)
...@@ -1091,19 +1072,19 @@ ...@@ -1091,19 +1072,19 @@
// function (result) { alert('list: '+result.list); }}); // function (result) { alert('list: '+result.list); }});
var settings = $.extend ({ var settings = $.extend ({
'storage': this.storage, 'storage': priv.storage,
'applicant': this.applicant, 'applicant': priv.applicant,
'method':'getDocumentList', 'method':'getDocumentList',
'callback':function(){} 'callback':function(){}
},options); },options);
// check dependencies // check dependencies
if (this.isReady() && settings.storage && settings.applicant ) { if (that.isReady() && settings.storage && settings.applicant ) {
return this.queue.createJob( settings ); return priv.queue.createJob( settings );
} }
return null; return null;
}, };
removeDocument: function ( options ) { that.removeDocument = function ( options ) {
// Remove a document in the storage set in [options] // Remove a document in the storage set in [options]
// or in the storage set at init. // or in the storage set at init.
// options.storage : the storage where to remove (optional) // options.storage : the storage where to remove (optional)
...@@ -1116,31 +1097,65 @@ ...@@ -1116,31 +1097,65 @@
// jio.removeDocument({'fileName':'file','callback': // jio.removeDocument({'fileName':'file','callback':
// function (result) { alert('removed? '+result.isRemoved); }}); // function (result) { alert('removed? '+result.isRemoved); }});
var settings = $.extend ({ var settings = $.extend ({
'storage': this.storage, 'storage': priv.storage,
'applicant': this.applicant, 'applicant': priv.applicant,
'method':'removeDocument', 'method':'removeDocument',
'callback':function (){} 'callback':function (){}
},options); },options);
if (this.isReady() && settings.fileName && if (that.isReady() && settings.fileName &&
settings.storage && settings.applicant ) { settings.storage && settings.applicant ) {
return this.queue.createJob ( settings ); return priv.queue.createJob ( settings );
} }
return null; return null;
};
//// end Methods
//// Initialize
var settings = $.extend({'useLocalStorage':true},options);
// objectify storage and applicant
if(typeof storage === 'string')
storage = JSON.parse(options.storage);
if(typeof applicant === 'string')
applicant = JSON.parse(options.applicant);
// set init values
priv['storage'] = storage;
priv['applicant'] = applicant;
priv['id'] = 0;
priv['pubsub'] = new PubSub(settings);
priv['queue'] = new JobQueue(priv.pubsub,settings);
priv['listener'] = new JobListener(priv.queue,settings);
priv['ready'] = false;
if (settings.useLocalStorage) {
priv['updater'] = new ActivityUpdater(settings);
} else {
priv['updater'] = null;
}
// check storage type
if (priv.storage && !jioGlobalObj.storageTypeObject[priv.storage.type]){
$.error('Unknown storage type "' + priv.storage.type +'"');
} }
// start jio process
that.start();
//// end Initialize
return that;
}; };
// end JIO Prototype // end JIO
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
// Jio creator // Jio creator
Jio = function () { JioCreator = function () {
var that = {};
// Jio creator object // Jio creator object
// this object permit to create jio object // this object permit to create jio object
}; that.createNew = function ( storage, applicant, options ) {
Jio.prototype = {
createNew: function ( storage, applicant, options ) {
// Return a new instance of JIO // Return a new instance of JIO
// storage: the storage object or json string // storage: the storage object or json string
// applicant: the applicant object or json string // applicant: the applicant object or json string
...@@ -1152,14 +1167,14 @@ ...@@ -1152,14 +1167,14 @@
jioGlobalObj.localStorage = LocalOrCookieStorage; jioGlobalObj.localStorage = LocalOrCookieStorage;
} }
return new JioCons(storage,applicant,settings); return new JioConstructor(storage,applicant,settings);
}, };
newBaseStorage: function ( options ) { that.newBaseStorage = function ( options ) {
// Create a Jio Storage which can be used to design new storage. // Create a Jio Storage which can be used to design new storage.
return BaseStorage( options ); return BaseStorage( options );
}, };
addStorageType: function ( type, constructor ) { that.addStorageType = function ( type, constructor ) {
// Add a storage type to jio. Jio must have keys/types which are // Add a storage type to jio. Jio must have keys/types which are
// bound to a storage creation function. ex: 'local', will // bound to a storage creation function. ex: 'local', will
// create a LocalStorage (in jio.storage.js). // create a LocalStorage (in jio.storage.js).
...@@ -1172,17 +1187,18 @@ ...@@ -1172,17 +1187,18 @@
return true; return true;
} }
return false; return false;
}, };
getGlobalObject: function () { that.getGlobalObject = function () {
// Returns the global jio values // Returns the global jio values
return jioGlobalObj; return jioGlobalObj;
}, };
getConstObject: function () { that.getConstObject = function () {
// Returns a copy of the constants // Returns a copy of the constants
return $.extend({},jioConstObj); return $.extend({},jioConstObj);
} };
return that;
}; };
return new Jio(); return new JioCreator();
// end Jio Creator // end Jio Creator
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
})(); })();
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
// - dav // - dav
// - replicate // - replicate
;(function ( Jio ) { ;(function ( Jio ) {
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
// globals // globals
var jioGlobalObj = Jio.getGlobalObject(), var jioGlobalObj = Jio.getGlobalObject(),
...@@ -32,7 +32,7 @@ ...@@ -32,7 +32,7 @@
LocalStorage,DAVStorage,ReplicateStorage; LocalStorage,DAVStorage,ReplicateStorage;
// end Classes // end Classes
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
// check dependencies // check dependencies
if (!checkJioDependencies()) { return; } if (!checkJioDependencies()) { return; }
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
...@@ -50,7 +50,7 @@ ...@@ -50,7 +50,7 @@
// wait a little in order to simulate asynchronous operation // wait a little in order to simulate asynchronous operation
setTimeout(function () { setTimeout(function () {
var localStorageObject = null; var localStorageObject = null;
localStorageObject = jioGlobalObj.localStorage.getAll(); localStorageObject = jioGlobalObj.localStorage.getAll();
for (var k in localStorageObject) { for (var k in localStorageObject) {
var splitk = k.split('/'); var splitk = k.split('/');
...@@ -62,7 +62,7 @@ ...@@ -62,7 +62,7 @@
} }
return that.done(true); return that.done(true);
}, 100); }, 100);
}; // end userNameAvailable }; // end checkNameAvailability
that.saveDocument = function () { that.saveDocument = function () {
// Save a document in the local storage // Save a document in the local storage
...@@ -75,7 +75,7 @@ ...@@ -75,7 +75,7 @@
// wait a little in order to simulate asynchronous saving // wait a little in order to simulate asynchronous saving
setTimeout (function () { setTimeout (function () {
var doc = null; var doc = null;
// reading // reading
doc = jioGlobalObj.localStorage.getItem( doc = jioGlobalObj.localStorage.getItem(
'jio/local/'+that.getStorageUserName()+'/'+ 'jio/local/'+that.getStorageUserName()+'/'+
...@@ -101,21 +101,21 @@ ...@@ -101,21 +101,21 @@
return that.done(); return that.done();
}, 100); }, 100);
}; // end saveDocument }; // end saveDocument
that.loadDocument = function () { that.loadDocument = function () {
// Load a document from the storage. It returns a document object // Load a document from the storage. It returns a document object
// containing all information of the document and its content. // containing all information of the document and its content.
// this.job.fileName : the document name we want to load. // this.job.fileName : the document name we want to load.
// this.job.options.getContent: if true, also get the file content. // this.job.options.getContent: if true, also get the file content.
// document object is {'fileName':string,'fileContent':string, // document object is {'fileName':string,'fileContent':string,
// 'creationDate':date,'lastModified':date} // 'creationDate':date,'lastModified':date}
// wait a little in order to simulate asynchronous operation // wait a little in order to simulate asynchronous operation
setTimeout(function () { setTimeout(function () {
var doc = null, settings = $.extend( var doc = null, settings = $.extend(
{'getContent':true},that.cloneOptionObject()); {'getContent':true},that.cloneOptionObject());
doc = jioGlobalObj.localStorage.getItem( doc = jioGlobalObj.localStorage.getItem(
'jio/local/'+that.getStorageUserName()+'/'+ 'jio/local/'+that.getStorageUserName()+'/'+
that.getApplicantID()+'/'+that.getFileName()); that.getApplicantID()+'/'+that.getFileName());
...@@ -143,7 +143,7 @@ ...@@ -143,7 +143,7 @@
setTimeout(function () { setTimeout(function () {
var list = [], localStorageObject = null, k = 'key', var list = [], localStorageObject = null, k = 'key',
splitk = ['splitedkey'], fileObject = {}; splitk = ['splitedkey'], fileObject = {};
localStorageObject = jioGlobalObj.localStorage.getAll(); localStorageObject = jioGlobalObj.localStorage.getAll();
for (k in localStorageObject) { for (k in localStorageObject) {
splitk = k.split('/'); splitk = k.split('/');
...@@ -199,7 +199,7 @@ ...@@ -199,7 +199,7 @@
// options.password: the password // options.password: the password
// TODO this method is not working !!! // TODO this method is not working !!!
var settings = $.extend ({ var settings = $.extend ({
'success':function(){},'error':function(){}},options), 'success':function(){},'error':function(){}},options),
splitpath = ['splitedpath'], tmppath = 'temp/path'; splitpath = ['splitedpath'], tmppath = 'temp/path';
...@@ -285,7 +285,7 @@ ...@@ -285,7 +285,7 @@
} }
} ); } );
}; };
that.saveDocument = function () { that.saveDocument = function () {
// Save a document in a DAVStorage // Save a document in a DAVStorage
// this.job.storage: the storage informations. // this.job.storage: the storage informations.
...@@ -294,12 +294,12 @@ ...@@ -294,12 +294,12 @@
// this.job.applicant.ID: the applicant ID. // this.job.applicant.ID: the applicant ID.
// this.job.fileName: the document name. // this.job.fileName: the document name.
// this.job.fileContent: the document content. // this.job.fileContent: the document content.
// TODO if path of /dav/user/applic does not exists, it won't work! // TODO if path of /dav/user/applic does not exists, it won't work!
//// save on dav //// save on dav
$.ajax ( { $.ajax ( {
url: that.getStorageLocation() + '/dav/' + url: that.getStorageLocation() + '/dav/' +
that.getStorageUserName() + '/' + that.getStorageUserName() + '/' +
that.getApplicantID() + '/' + that.getApplicantID() + '/' +
that.getFileName(), that.getFileName(),
type: 'PUT', type: 'PUT',
...@@ -307,7 +307,7 @@ ...@@ -307,7 +307,7 @@
async: true, async: true,
dataType: 'text', // TODO is it necessary ? dataType: 'text', // TODO is it necessary ?
headers: {'Authorization':'Basic '+Base64.encode( headers: {'Authorization':'Basic '+Base64.encode(
that.getStorageUserName() + ':' + that.getStoragePassword())}, that.getStorageUserName()+':'+that.getStoragePassword())},
// xhrFields: {withCredentials: 'true'}, // cross domain // xhrFields: {withCredentials: 'true'}, // cross domain
success: function () { success: function () {
that.done(); that.done();
...@@ -328,7 +328,7 @@ ...@@ -328,7 +328,7 @@
// this.job.storage.userName: the user name. // this.job.storage.userName: the user name.
// this.job.storage.password: the user password. // this.job.storage.password: the user password.
// this.job.options.getContent: if true, also get the file content. // this.job.options.getContent: if true, also get the file content.
// document object is {'fileName':string,'fileContent':string, // document object is {'fileName':string,'fileContent':string,
// 'creationDate':date,'lastModified':date} // 'creationDate':date,'lastModified':date}
...@@ -359,7 +359,7 @@ ...@@ -359,7 +359,7 @@
case 404: case 404:
message = 'Document not found.'; break; message = 'Document not found.'; break;
default: default:
message = 'Cannot load "' + that.getFileName() + '".'; message = 'Cannot load "'+that.getFileName()+'".';
break; break;
} }
that.fail(message,type.status); that.fail(message,type.status);
...@@ -406,14 +406,14 @@ ...@@ -406,14 +406,14 @@
// this.job.storage.userName: the user name. // this.job.storage.userName: the user name.
// this.job.storage.password: the user password. // this.job.storage.password: the user password.
// this.job.applicant.ID: the applicant id. // this.job.applicant.ID: the applicant id.
// the list is [object,object] -> object = {'fileName':string, // the list is [object,object] -> object = {'fileName':string,
// 'lastModified':date,'creationDate':date} // 'lastModified':date,'creationDate':date}
var documentArrayList = [], file = {}, pathArray = []; var documentArrayList = [], file = {}, pathArray = [];
$.ajax ( { $.ajax ( {
url: that.getStorageLocation() + '/dav/' + url: that.getStorageLocation() + '/dav/' +
that.getStorageUserName() + '/' + that.getStorageUserName() + '/' +
that.getApplicantID() + '/', that.getApplicantID() + '/',
async: true, async: true,
...@@ -426,19 +426,22 @@ ...@@ -426,19 +426,22 @@
$("D\\:response",xmlData).each(function(i,data) { $("D\\:response",xmlData).each(function(i,data) {
if(i>0) { // exclude parent folder if(i>0) { // exclude parent folder
file = {}; file = {};
pathArray = ($($("D\\:href", pathArray = (
xmlData).get(i)).text()).split('/'); $($("D\\:href",
xmlData).get(i)).text()).split('/');
file.fileName = (pathArray[pathArray.length-1] ? file.fileName = (pathArray[pathArray.length-1] ?
pathArray[pathArray.length-1] : pathArray[pathArray.length-1] :
pathArray[pathArray.length-2]+'/'); pathArray[pathArray.length-2]+'/');
if (file.fileName === '.htaccess' || if (file.fileName === '.htaccess' ||
file.fileName === '.htpasswd') { return; } file.fileName === '.htpasswd') { return; }
file.lastModified = ( file.lastModified = (
new Date($($("lp1\\:getlastmodified", new Date(
xmlData).get(i)).text())).getTime(); $($("lp1\\:getlastmodified",
xmlData).get(i)).text())).getTime();
file.creationDate = ( file.creationDate = (
new Date($($("lp1\\:creationdate", new Date(
xmlData).get(i)).text())).getTime(); $($("lp1\\:creationdate",
xmlData).get(i)).text())).getTime();
documentArrayList.push (file); documentArrayList.push (file);
} }
}); });
...@@ -449,7 +452,7 @@ ...@@ -449,7 +452,7 @@
} }
} ); } );
}; };
that.removeDocument = function () { that.removeDocument = function () {
// Remove a document from a DAVStorage. // Remove a document from a DAVStorage.
// this.job.fileName: the document name we want to remove. // this.job.fileName: the document name we want to remove.
...@@ -495,7 +498,7 @@ ...@@ -495,7 +498,7 @@
// ReplicateStorage // ReplicateStorage
ReplicateStorage = function ( args ) { ReplicateStorage = function ( args ) {
var that = Jio.newBaseStorage( args ), priv = {}; var that = Jio.newBaseStorage( args ), priv = {};
priv.storageArray = that.getStorageArray(); priv.storageArray = that.getStorageArray();
// TODO Add a tests that check if there is no duplicate storages. // TODO Add a tests that check if there is no duplicate storages.
priv.length = priv.storageArray.length; priv.length = priv.storageArray.length;
...@@ -513,7 +516,7 @@ ...@@ -513,7 +516,7 @@
var newjob = {}, isavailable = true, i = 'id', var newjob = {}, isavailable = true, i = 'id',
res = {'status':'done'}; res = {'status':'done'};
for (i in priv.storageArray) { for (i in priv.storageArray) {
newjob = that.cloneJob(); newjob = that.cloneJob();
newjob.maxtries = priv.maxtries; newjob.maxtries = priv.maxtries;
...@@ -578,14 +581,14 @@ ...@@ -578,14 +581,14 @@
// this.job.storage.userName: the user name. // this.job.storage.userName: the user name.
// this.job.storage.password: the user password. // this.job.storage.password: the user password.
// this.job.options.getContent: if true, also get the file content. // this.job.options.getContent: if true, also get the file content.
// document object is {'fileName':string,'fileContent':string, // document object is {'fileName':string,'fileContent':string,
// 'creationDate':date,'lastModified':date} // 'creationDate':date,'lastModified':date}
// TODO // TODO
var newjob = {}, aredifferent = false, doc = {}, i = 'id', var newjob = {}, aredifferent = false, doc = {}, i = 'id',
res = {'status':'done'}; res = {'status':'done'};
for (i in priv.storageArray) { for (i in priv.storageArray) {
newjob = that.cloneJob(); newjob = that.cloneJob();
newjob.maxtries = priv.maxtries; newjob.maxtries = priv.maxtries;
...@@ -607,7 +610,7 @@ ...@@ -607,7 +610,7 @@
// previous one // previous one
aredifferent = true; aredifferent = true;
} }
if (doc.creationDate > if (doc.creationDate >
result.document.creationDate) { result.document.creationDate) {
// get older creation date // get older creation date
doc.creationDate = result.document.creationDate; doc.creationDate = result.document.creationDate;
...@@ -648,13 +651,13 @@ ...@@ -648,13 +651,13 @@
// this.job.storage.userName: the user name. // this.job.storage.userName: the user name.
// this.job.storage.password: the user password. // this.job.storage.password: the user password.
// this.job.applicant.ID: the applicant id. // this.job.applicant.ID: the applicant id.
// the list is [object,object] -> object = {'fileName':string, // the list is [object,object] -> object = {'fileName':string,
// 'lastModified':date,'creationDate':date} // 'lastModified':date,'creationDate':date}
// TODO // TODO
var newjob = {}, res = {'status':'done'}, i = 'id'; var newjob = {}, res = {'status':'done'}, i = 'id';
for (i in priv.storageArray) { for (i in priv.storageArray) {
newjob = that.cloneJob(); newjob = that.cloneJob();
newjob.maxtries = priv.maxtries; newjob.maxtries = priv.maxtries;
...@@ -686,7 +689,7 @@ ...@@ -686,7 +689,7 @@
// this.job.storage.password: the user password. // this.job.storage.password: the user password.
// this.job.applicant.ID: the applicant id. // this.job.applicant.ID: the applicant id.
// TODO // TODO
var newjob = {}, res = {'status':'done'}, i = 'key'; var newjob = {}, res = {'status':'done'}, i = 'key';
for (i in priv.storageArray) { for (i in priv.storageArray) {
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment