Commit a4b6f558 authored by Tristan Cavelier's avatar Tristan Cavelier Committed by Sebastien Robin

Redesigning pseudo classes inheritance.

Add tests.
parent 39836f9f
...@@ -4,6 +4,7 @@ ...@@ -4,6 +4,7 @@
// - dummyallok // - dummyallok
// - dummyallfail // - dummyallfail
// - dummyallnotfound // - dummyallnotfound
// - dummyall3tries
;(function ( Jio ) { ;(function ( Jio ) {
// check dependencies // check dependencies
...@@ -15,47 +16,39 @@ ...@@ -15,47 +16,39 @@
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
// globals // globals
var jioGlobalObj = Jio.getGlobalObject(); var jioGlobalObj = Jio.getGlobalObject(),
// end globals // end globals
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
// Dummy Storage 1 : all ok // Dummy Storage 1 : all ok
var DummyStorageAllOk = function ( args ) { DummyStorageAllOk = function ( args ) {
this.job = args.job; var that = Jio.newBaseStorage( args );
}; that.checkNameAvailability = function () {
DummyStorageAllOk.prototype = {
checkNameAvailability: function () {
// The [job.userName] IS available. // The [job.userName] IS available.
var t = this;
// wait a little in order to simulate asynchronous operation // wait a little in order to simulate asynchronous operation
setTimeout(function () { setTimeout(function () {
t.done(true); that.done(true);
}, 100); }, 100);
}, // end userNameAvailable }; // end userNameAvailable
saveDocument: function () { that.saveDocument = function () {
// Tells us that the document is saved. // Tells us that the document is saved.
var t = this;
// wait a little in order to simulate asynchronous saving // wait a little in order to simulate asynchronous saving
setTimeout (function () { setTimeout (function () {
t.done(); that.done();
}, 100); }, 100);
}, // end saveDocument }; // end saveDocument
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}
var t = this;
// wait a little in order to simulate asynchronous operation // wait a little in order to simulate asynchronous operation
setTimeout(function () { setTimeout(function () {
var doc = { var doc = {
...@@ -63,19 +56,17 @@ ...@@ -63,19 +56,17 @@
'fileName': 'file', 'fileName': 'file',
'creationDate': 10000, 'creationDate': 10000,
'lastModified': 15000}; 'lastModified': 15000};
t.done(doc); that.done(doc);
}, 100); }, 100);
}, // end loadDocument }; // end loadDocument
getDocumentList: function () { that.getDocumentList = function () {
// It returns a document array containing all the user documents // It returns a document array containing all the user documents
// informations, but not their content. // informations, but not their content.
// 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 t = this;
setTimeout(function () { setTimeout(function () {
var list = [ var list = [
{'fileName':'file', {'fileName':'file',
...@@ -85,257 +76,215 @@ ...@@ -85,257 +76,215 @@
'creationDate':20000, 'creationDate':20000,
'lastModified':25000 'lastModified':25000
}]; }];
t.done(list); that.done(list);
}, 100); }, 100);
}, // end getDocumentList }; // end getDocumentList
removeDocument: function () { that.removeDocument = function () {
// Remove a document from the storage. // Remove a document from the storage.
var t = this;
setTimeout (function () { setTimeout (function () {
t.done(); that.done();
}, 100); }, 100);
} };
}; return that;
},
// add key to storageObjectType of global jio
Jio.addStorageType('dummyallok', function (options) {
return new DummyStorageAllOk(options);
});
// end Dummy Storage All Ok // end Dummy Storage All Ok
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
// Dummy Storage 2 : all fail // Dummy Storage 2 : all fail
var DummyStorageAllFail = function ( args ) { DummyStorageAllFail = function ( args ) {
this.job = args.job; var that = Jio.newBaseStorage( args );
};
DummyStorageAllFail.prototype = { that.checkNameAvailability = function () {
checkNameAvailability: function () {
// Fails to check [job.userName]. // Fails to check [job.userName].
var t = this;
// wait a little in order to simulate asynchronous operation // wait a little in order to simulate asynchronous operation
setTimeout(function () { setTimeout(function () {
t.fail('Cannot check name availability.',0); that.fail('Cannot check name availability.',0);
}, 100); }, 100);
}, // end userNameAvailable }; // end userNameAvailable
saveDocument: function () { that.saveDocument = function () {
// Tells us that the document is not saved. // Tells us that the document is not saved.
var t = this;
// wait a little in order to simulate asynchronous saving // wait a little in order to simulate asynchronous saving
setTimeout (function () { setTimeout (function () {
t.fail('Unable to save document.',0); that.fail('Unable to save document.',0);
}, 100); }, 100);
}, // end saveDocument }; // end saveDocument
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}
var t = this;
// wait a little in order to simulate asynchronous operation // wait a little in order to simulate asynchronous operation
setTimeout(function () { setTimeout(function () {
t.fail('Unable to load document.',0); that.fail('Unable to load document.',0);
}, 100); }, 100);
}, // end loadDocument }; // end loadDocument
getDocumentList: function () { that.getDocumentList = function () {
// It returns nothing. // It returns nothing.
// 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 t = this;
setTimeout(function () { setTimeout(function () {
t.fail('Cannot get document list.',0); that.fail('Cannot get document list.',0);
}, 100); }, 100);
}, // end getDocumentList }; // end getDocumentList
removeDocument: function ( job, jobendcallback ) { that.removeDocument = function () {
// Remove a document from the storage. // Remove a document from the storage.
// returns {'status':string,'message':string,'isRemoved':boolean} // returns {'status':string,'message':string,'isRemoved':boolean}
// in the jobendcallback arguments. // in the jobendcallback arguments.
var t = this;
setTimeout (function () { setTimeout (function () {
t.fail('Unable to remove anything.',0); that.fail('Unable to remove anything.',0);
}, 100); }, 100);
} };
}; return that;
},
// add key to storageObjectType of global jio
Jio.addStorageType('dummyallfail', function (options) {
return new DummyStorageAllFail(options);
});
// end Dummy Storage All Fail // end Dummy Storage All Fail
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
// Dummy Storage 3 : all not found // Dummy Storage 3 : all not found
var DummyStorageAllNotFound = function ( args ) { DummyStorageAllNotFound = function ( args ) {
this.job = args.job; var that = Jio.newBaseStorage( args );
};
DummyStorageAllNotFound.prototype = { that.checkNameAvailability = function () {
checkNameAvailability: function () {
// [job.userName] not found, so the name is available. // [job.userName] not found, so the name is available.
var t = this;
// wait a little in order to simulate asynchronous operation // wait a little in order to simulate asynchronous operation
setTimeout(function () { setTimeout(function () {
t.done(true); that.done(true);
}, 100); }, 100);
}, // end userNameAvailable }; // end userNameAvailable
saveDocument: function () { that.saveDocument = function () {
// Document does not exists yet, create it. // Document does not exists yet, create it.
var t = this;
// wait a little in order to simulate asynchronous saving // wait a little in order to simulate asynchronous saving
setTimeout (function () { setTimeout (function () {
t.done(); that.done();
}, 100); }, 100);
}, // end saveDocument }; // end saveDocument
loadDocument: function ( job, jobendcallback ) { 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}
var t = this;
// wait a little in order to simulate asynchronous operation // wait a little in order to simulate asynchronous operation
setTimeout(function () { setTimeout(function () {
t.fail('Document not found.',404); that.fail('Document not found.',404);
}, 100); }, 100);
}, // end loadDocument }; // end loadDocument
getDocumentList: function ( job, jobendcallback) { that.getDocumentList = function () {
// It returns nothing. // It returns nothing.
// 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 t = this;
setTimeout(function () { setTimeout(function () {
t.fail('User collection not found.',404); that.fail('User collection not found.',404);
}, 100); }, 100);
}, // end getDocumentList }; // end getDocumentList
removeDocument: function ( job, jobendcallback ) { that.removeDocument = function () {
// Remove a document from the storage. // Remove a document from the storage.
// returns {'status':string,'message':string,'isRemoved':boolean} // returns {'status':string,'message':string,'isRemoved':boolean}
// in the jobendcallback arguments. // in the jobendcallback arguments.
var t = this;
setTimeout (function () { setTimeout (function () {
t.done(); that.done();
}, 100); }, 100);
} };
}; return that;
},
// add key to storageObjectType of global jio
Jio.addStorageType('dummyallnotfound', function (options) {
return new DummyStorageAllNotFound(options);
});
// end Dummy Storage All Not Found // end Dummy Storage All Not Found
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
// Dummy Storage 4 : all 3 tries // Dummy Storage 4 : all 3 tries
var DummyStorageAll3Tries = function ( args ) { DummyStorageAll3Tries = function ( args ) {
this.job = args.job; var that = Jio.newBaseStorage( args ), priv = {};
};
DummyStorageAllNotFound.prototype = { priv.doJob = function (ifokreturn) {
checkNameAvailability: function () {
// [job.userName] not found, so the name is available.
var t = this;
// wait a little in order to simulate asynchronous operation // wait a little in order to simulate asynchronous operation
setTimeout(function () { setTimeout(function () {
t.done(true); priv.Try3OKElseFail (that.cloneJob().tries,ifokreturn);
}, 100); }, 100);
}, // end userNameAvailable };
priv.Try3OKElseFail = function (tries,ifokreturn) {
saveDocument: function () { if ( tries === 3 ) {
// Document does not exists yet, create it. return that.done(ifokreturn);
}
var t = this; if ( tries < 3 ) {
return that.fail('' + (3 - tries) + ' tries left.');
// wait a little in order to simulate asynchronous saving }
setTimeout (function () { if ( tries > 3 ) {
t.done(); return that.fail('Too much tries.');
}, 100); }
}, // end saveDocument };
loadDocument: function () { that.checkNameAvailability = function () {
// Returns a document object containing nothing. priv.doJob (true);
}; // end userNameAvailable
// document object is {'fileName':string,'fileContent':string,
// 'creationDate':date,'lastModified':date} that.saveDocument = function () {
priv.doJob ();
var t = this; }; // end saveDocument
// wait a little in order to simulate asynchronous operation that.loadDocument = function () {
setTimeout(function () { priv.doJob ({
t.fail('Document not found.',404); 'fileContent': 'content2',
}, 100); 'fileName': 'file',
}, // end loadDocument 'creationDate': 11000,
'lastModified': 17000
getDocumentList: function () { });
// It returns nothing. }; // end loadDocument
// the list is [object,object] -> object = {'fileName':string, that.getDocumentList = function () {
// 'lastModified':date,'creationDate':date} priv.doJob([{'fileName':'file',
'creationDate':10000,
var t = this; 'lastModified':15000},
{'fileName':'memo',
setTimeout(function () { 'creationDate':20000,
t.fail('User collection not found.',404); 'lastModified':25000}
}, 100); ]);
}, // end getDocumentList }; // end getDocumentList
removeDocument: function () { that.removeDocument = function () {
// Remove a document from the storage. priv.doJob();
}; // end removeDocument
// returns {'status':string,'message':string,'isRemoved':boolean}
// in the jobendcallback arguments. return that;
var t = this;
setTimeout (function () {
t.done();
}, 100);
}
}; };
// end Dummy Storage All 3 Tries
////////////////////////////////////////////////////////////////////////////
// add key to storageObjectType of global jio // add key to storageObjectType of global jio
Jio.addStorageType('dummyallok', function (options) {
return DummyStorageAllOk(options);
});
Jio.addStorageType('dummyallfail', function (options) {
return DummyStorageAllFail(options);
});
Jio.addStorageType('dummyallnotfound', function (options) {
return DummyStorageAllNotFound(options);
});
Jio.addStorageType('dummyall3tries', function (options) { Jio.addStorageType('dummyall3tries', function (options) {
return new DummyStorageAll3Tries(options); return DummyStorageAll3Tries(options);
}); });
// end Dummy Storage All 3 Tries
////////////////////////////////////////////////////////////////////////////
})( JIO ); })( JIO );
...@@ -142,12 +142,16 @@ test ('Simple Job Elimination', function () { ...@@ -142,12 +142,16 @@ test ('Simple Job Elimination', function () {
id = o.jio.id; id = o.jio.id;
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');
}); });
...@@ -214,22 +218,20 @@ test ('Simple Job Waiting', function () { ...@@ -214,22 +218,20 @@ 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.
var o = {}, clock = this.sandbox.useFakeTimers(), id = 0; var o = {}, clock = this.sandbox.useFakeTimers(), id = 0;
o.f1 = this.spy(); o.f = function (result) {
o.jio = JIO.createNew({'type':'dummyallfail','userName':'dummy'}, o.res = (result.status === 'done');
};
this.spy(o,'f');
o.jio = JIO.createNew({'type':'dummyall3tries','userName':'dummy'},
{'ID':'jiotests'}); {'ID':'jiotests'});
id = o.jio.id;
o.jio.saveDocument({'fileName':'file','fileContent':'content', o.jio.saveDocument({'fileName':'file','fileContent':'content',
'callback':o.f1,'maxtries':2}); 'callback':o.f,'maxtries':3});
clock.tick(400); clock.tick(100000);
o.tmp = LocalOrCookieStorage.getItem('jio/jobObject/'+id)['1']; ok(o.f.calledOnce,'callback called once.');
ok(o.tmp.status === 'wait' && o.tmp.waitingFor && o.tmp.waitingFor.time, ok(o.res,'job done.');
'is waiting for time');
clock.tick(1500);
o.tmp = LocalOrCookieStorage.getItem('jio/jobObject/'+id)['1'];
ok(o.tmp.status === 'fail','it restores itself after time');
console.log (localStorage);
o.jio.stop(); o.jio.stop();
}); });
...@@ -631,11 +633,12 @@ test ('Check name availability', function () { ...@@ -631,11 +633,12 @@ test ('Check name availability', function () {
deepEqual (result.isAvailable,value,message)}; deepEqual (result.isAvailable,value,message)};
t.spy(o,'f'); t.spy(o,'f');
o.jio.checkNameAvailability({'userName':'Dummy','callback':o.f, o.jio.checkNameAvailability({'userName':'Dummy','callback':o.f,
'maxtries':1}); 'maxtries':o.maxtries});
clock.tick(1000); clock.tick(300000);
if (!o.f.calledOnce) if (!o.f.calledOnce)
ok(false,'no respose / too much results'); ok(false,'no respose / too much results');
}; };
o.maxtries = 1;
// DummyStorageAllOK,OK // DummyStorageAllOK,OK
o.jio = JIO.createNew({'type':'replicate','storageArray':[ o.jio = JIO.createNew({'type':'replicate','storageArray':[
{'type':'dummyallok','userName':'1'}, {'type':'dummyallok','userName':'1'},
...@@ -664,24 +667,112 @@ test ('Check name availability', function () { ...@@ -664,24 +667,112 @@ test ('Check name availability', function () {
{'ID':'jiotests'}); {'ID':'jiotests'});
mytest('DummyStoragesAllFail,Fail : name not available',false); mytest('DummyStoragesAllFail,Fail : name not available',false);
o.jio.stop(); o.jio.stop();
// DummyStorageAllOK,3Tries
o.maxtries = 3 ;
o.jio = JIO.createNew({'type':'replicate','storageArray':[
{'type':'dummyallok','userName':'1'},
{'type':'dummyall3tries','userName':'2'}]},
{'ID':'jiotests'});
mytest('DummyStoragesAllOK,3Tries : name available',true);
o.jio.stop();
// DummyStorageAll{3tries,{3tries,3tries},3tries}
o.maxtries = 3 ;
o.jio = JIO.createNew({'type':'replicate','storageArray':[
{'type':'dummyall3tries','userName':'1'},
{'type':'replicate','storageArray':[
{'type':'dummyall3tries','userName':'2'},
{'type':'dummyall3tries','userName':'3'}]},
{'type':'dummyall3tries','userName':'4'}]},
{'ID':'jiotests'});
mytest('DummyStorageAll{3tries,{3tries,3tries},3tries} : name available',true);
o.jio.stop();
}); });
// test ('Document load', function () { test ('Document load', function () {
// // Test if DavStorage can load documents. // Test if ReplicateStorage can load several documents.
// var o = {}; var clock = this.sandbox.useFakeTimers(); var t = this; var o = {}; var clock = this.sandbox.useFakeTimers(); var t = this;
// var mytest = function (message,doc) { var mytest = function (message,doc) {
// o.f = function (result) { o.f = function (result) {
// deepEqual (result.document,doc,message);}; deepEqual (result.document,doc,message);};
// t.spy(o,'f'); t.spy(o,'f');
// o.jio.loadDocument({'fileName':'file','callback':o.f}); o.jio.loadDocument({'fileName':'file','callback':o.f});
// clock.tick(1000); clock.tick(100000);
// server.respond(); 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':'replicate','userName':'Dummy','storageArray':[
// o.jio = JIO.createNew({'type':'replicate','userName':'Dummy'}, {'type':'dummyallok','userName':'1'},
// {'ID':'jiotests'}); {'type':'dummyallok','userName':'2'}]},
{'ID':'jiotests'});
mytest('DummyStorageAllOK,OK: load same file',{
'fileName':'file','fileContent':'content',
'lastModified':15000,
'creationDate':10000});
o.jio.stop();
o.jio=JIO.createNew({'type':'replicate','userName':'Dummy','storageArray':[
{'type':'dummyallok','userName':'1'},
{'type':'dummyall3tries','userName':'2'}]},
{'ID':'jiotests'});
mytest('DummyStorageAllOK,3tries: load 2 different files',{
'fileName':'file','fileContent':'content2',
'lastModified':17000,
'creationDate':10000});
// o.jio.stop(); o.jio.stop();
// }); });
test ('Document save', function () {
// Test if ReplicateStorage can save several documents.
var o = {}, clock = this.sandbox.useFakeTimers(), t = this,
mytest = function (message,value) {
o.f = function (result) {
deepEqual (result.isSaved,value,message);};
t.spy(o,'f');
o.jio.saveDocument({'fileName':'file','fileContent':'content',
'callback':o.f,'maxtries':3});
clock.tick(500);
if (!o.f.calledOnce)
ok(false, 'no response / too much results');
};
o.jio=JIO.createNew({'type':'replicate','userName':'Dummy','storageArray':[
{'type':'dummyallok','userName':'1'},
{'type':'dummyallok','userName':'2'}]},
{'ID':'jiotests'});
mytest('DummyStorageAllOK,OK: save a file.',true);
o.jio.stop();
});
test ('Get Document List', function () {
// Test if ReplicateStorage can save several documents.
var o = {}, clock = this.sandbox.useFakeTimers(), t = this,
mytest = function (message,value) {
o.f = function (result) {
var objectifyDocumentArray = function (array) {
var obj = {}, k;
for (k in array) {obj[array[k].fileName] = array[k];}
return obj;
};
deepEqual (objectifyDocumentArray(result.list),
objectifyDocumentArray(value),'getting list');
};
t.spy(o,'f');
o.jio.saveDocument({'fileName':'file','fileContent':'content',
'callback':o.f,'maxtries':3});
clock.tick(100000);
if (!o.f.calledOnce)
ok(false, 'no response / too much results');
};
o.jio=JIO.createNew({'type':'replicate','userName':'Dummy','storageArray':[
{'type':'dummyallok','userName':'1'},
{'type':'dummyall3tries','userName':'2'}]},
{'ID':'jiotests'});
o.doc1 = {'fileName':'memo','fileContent':'test',
'lastModified':15000,'creationDate':10000};
o.doc1 = {'fileName':'memo','fileContent':'test',
'lastModified':25000,'creationDate':20000};
mytest('DummyStorageAllOK,3tries: get document list .',[o.doc1,o.doc2]);
o.jio.stop();
});
...@@ -121,9 +121,10 @@ ...@@ -121,9 +121,10 @@
}, },
'canEliminate':function (job1,job2) { 'canEliminate':function (job1,job2) {
if (job1.status !== 'ongoing' && if (job1.status !== 'ongoing' &&
job2.method === 'removeDocument' && (job1.method === 'removeDocument' &&
(job1.method === 'removeDocument' || job2.method === 'saveDocument' ||
job1.method === 'saveDocument')) { job1.method === 'saveDocument' &&
job2.method === 'removeDocument')) {
return true; return true;
} }
return false; return false;
...@@ -364,15 +365,11 @@ ...@@ -364,15 +365,11 @@
} }
if (jioGlobalObj.jobManagingMethod.canEliminate( if (jioGlobalObj.jobManagingMethod.canEliminate(
this.jobObject[id],job)) { this.jobObject[id],job)) {
console.log ('Elimitated: ' +
JSON.stringify (this.jobObject[id]));
res.elimArray.push(id); res.elimArray.push(id);
continue; continue;
} }
if (jioGlobalObj.jobManagingMethod.canReplace( if (jioGlobalObj.jobManagingMethod.canReplace(
this.jobObject[id],job)) { this.jobObject[id],job)) {
console.log ('Replaced: ' +
JSON.stringify (this.jobObject[id]));
basestorage = new BaseStorage( basestorage = new BaseStorage(
{'queue':this,'job':this.jobObject[id]}); {'queue':this,'job':this.jobObject[id]});
basestorage.replace(job); basestorage.replace(job);
...@@ -381,16 +378,11 @@ ...@@ -381,16 +378,11 @@
} }
if (jioGlobalObj.jobManagingMethod.cannotAccept( if (jioGlobalObj.jobManagingMethod.cannotAccept(
this.jobObject[id],job)) { this.jobObject[id],job)) {
console.log ('Not accepted: ' + JSON.stringify (job) + '\nby: ' +
JSON.stringify (this.jobObject[id]));
// Job not accepted // Job not accepted
return false; return false;
} }
if (jioGlobalObj.jobManagingMethod.mustWait( if (jioGlobalObj.jobManagingMethod.mustWait(
this.jobObject[id],job)) { this.jobObject[id],job)) {
console.log ('Waited: ' +
JSON.stringify (this.jobObject[id]) +
'\nby : ' + JSON.stringify (job));
res.waitArray.push(id); res.waitArray.push(id);
continue; continue;
} }
...@@ -422,10 +414,10 @@ ...@@ -422,10 +414,10 @@
} }
// set job id // set job id
job.id = this.jobid; job.id = this.jobid;
job.tries = 0;
this.jobid ++; this.jobid ++;
// save the new job into the queue // save the new job into the queue
this.jobObject[job.id] = job; this.jobObject[job.id] = job;
console.log ('new one: ' + JSON.stringify (job));
} }
// save into localStorage // save into localStorage
this.copyJobQueueToLocalStorage(); this.copyJobQueueToLocalStorage();
...@@ -506,7 +498,7 @@ ...@@ -506,7 +498,7 @@
if (this.jobObject[i].waitingFor.time > Date.now()) { if (this.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;
} }
} }
// else wait nothing // else wait nothing
if (ok) { if (ok) {
...@@ -691,127 +683,188 @@ ...@@ -691,127 +683,188 @@
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.
this.job = options.job; var that = {}, priv = {};
this.callback = options.job.callback;
this.queue = options.queue; //// Private attributes
this.res = {'status':'done','message':''}; priv.job = options.job;
}; priv.callback = options.job.callback;
BaseStorage.prototype = { priv.queue = options.queue;
createStorageObject: function ( options ) { priv.res = {'status':'done','message':''};
// Create a storage thanks to storages types set //// end Private attributes
// with 'addStorageType'.
//// Private Methods
if (!jioGlobalObj.storageTypeObject[ options.job.storage.type ]) priv.fail_checkNameAvailability = function () {
return null; // error! priv.res.isAvailable = false;
return jioGlobalObj.storageTypeObject[ },
options.job.storage.type ](options); priv.done_checkNameAvailability = function ( isavailable ) {
priv.res.message = priv.job.userName + ' is ' +
(isavailable?'':'not ') + 'available.';
priv.res.isAvailable = isavailable;
},
priv.fail_loadDocument = function () {
priv.res.document = {};
},
priv.done_loadDocument = function ( returneddocument ) {
priv.res.message = 'Document loaded.';
priv.res.document = returneddocument;
}, },
retryLater: function () { priv.fail_saveDocument = function () {
priv.res.isSaved = false;
},
priv.done_saveDocument = function () {
priv.res.message = 'Document saved.';
priv.res.isSaved = true;
},
priv.fail_getDocumentList = function () {
priv.res.list = [];
},
priv.done_getDocumentList = function ( documentlist ) {
priv.res.message = 'Document list received.';
priv.res.list = documentlist;
},
priv.fail_removeDocument = function () {
priv.res.isRemoved = false;
},
priv.done_removeDocument = function () {
priv.res.message = 'Document removed.';
priv.res.isRemoved = true;
};
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.
this.job.status = 'wait'; priv.job.status = 'wait';
this.job.waitingFor = {'time':Date.now() + priv.job.waitingFor = {'time':Date.now() +
(this.job.tries*this.job.tries*1000)}; (priv.job.tries*priv.job.tries*1000)};
}, };
eliminate: function () { //// end Private Methods
this.job.maxtries = 0;
this.fail('Job Stopped!',0); //// Getters Setters
}, that.cloneJob = function () {
replace: function ( newjob ) { return $.extend({},priv.job);
};
that.getUserName = function () {
return priv.job.userName || '';
};
that.getApplicantID = function () {
return priv.job.applicant.ID || '';
};
that.getStorageUserName = function () {
return priv.job.storage.userName || '';
};
that.getStoragePassword = function () {
return priv.job.storage.password || '';
};
that.getStorageLocation = function () {
return priv.job.storage.location || '';
};
that.getStorageArray = function () {
return priv.job.storage.storageArray || [];
};
that.getFileName = function () {
return priv.job.fileName || '';
};
that.getFileContent = function () {
return priv.job.fileContent || '';
};
that.cloneOptionObject = function () {
return $.extend({},priv.job.options);
};
that.getMaxTries = function () {
return priv.job.maxtries;
};
that.getTries = function () {
return priv.job.tries || 0;
};
that.setMaxTries = function (maxtries) {
priv.job.maxtries = maxtries;
};
//// end Getters Setters
//// Public Methods
that.addJob = function ( newjob ) {
return priv.queue.createJob ( newjob );
};
that.eliminate = function () {
// Stop and remove a job !
priv.job.maxtries = 1;
priv.job.tries = 1;
that.fail('Job Stopped!',0);
};
that.replace = function ( newjob ) {
// It replace the current job by the new one. // It replace the current job by the new one.
// Replacing only the date // Replacing only the date
this.job.tries = 0; priv.job.tries = 0;
this.job.date = newjob.date; priv.job.date = newjob.date;
this.job.callback = newjob.callback; priv.job.callback = newjob.callback;
this.res.status = 'fail'; priv.res.status = 'fail';
this.res.message = 'Job Stopped!'; priv.res.message = 'Job Stopped!';
this.res.errno = 0; priv.res.errno = 0;
this['fail_'+this.job.method](); priv['fail_'+priv.job.method]();
this.callback(this.res); priv.callback(priv.res);
}, };
fail: function ( message, errno ) { that.fail = function ( message, errno ) {
// Called when a job has failed. // Called when a job has failed.
// It will retry the job from a certain moment or it will return // It will retry the job from a certain moment or it will return
// a failure. // a failure.
this.res.status = 'fail'; priv.res.status = 'fail';
this.res.message = message; priv.res.message = message;
this.res.errno = errno; priv.res.errno = errno;
if (this.job.maxtries && this.job.tries < this.job.maxtries) { if (!priv.job.maxtries ||
this.retryLater(); priv.job.tries < priv.job.maxtries) {
priv.retryLater();
} else { } else {
this.job.status = 'fail'; priv.job.status = 'fail';
this['fail_'+this.job.method](); priv['fail_'+priv.job.method]();
this.queue.ended(this.job); priv.queue.ended(priv.job);
this.callback(this.res); priv.callback(priv.res);
} }
}, };
done: function ( retvalue ) { that.done = function ( retvalue ) {
// Called when a job has terminated successfully. // Called when a job has terminated successfully.
// It will return the return value by the calling the callback // It will return the return value by the calling the callback
// function. // function.
this.job.status = 'done'; priv.job.status = 'done';
this['done_'+this.job.method]( retvalue ); priv['done_'+priv.job.method]( retvalue );
this.queue.ended(this.job); priv.queue.ended(priv.job);
this.callback(this.res); priv.callback(priv.res);
}, };
execute: function () { that.execute = function () {
// Execute the good function from the good storage. // Execute the good function from the good storage.
var t = this, stor = null;
if (!this.job.tries) { priv.job.tries = that.getTries() + 1;
this.job.tries = 0;
if ( !jioGlobalObj.storageTypeObject[ priv.job.storage.type ] ) {
return null;
} }
this.job.tries ++; return jioGlobalObj.storageTypeObject[ priv.job.storage.type ]({
stor = this.createStorageObject ( 'job':priv.job,'queue':priv.queue})[priv.job.method]();
{'job':this.job,'queue':this.queue} };
); // These methods must be redefined!
stor.done = function (retval) { t.done(retval); }; that.checkNameAvailability = function () {
stor.fail = function (mess,errno) { t.fail(mess,errno); }; that.fail('This method must be redefined!',0);
stor[this.job.method](); };
}, that.loadDocument = function () {
fail_checkNameAvailability: function () { that.fail('This method must be redefined!',0);
this.res.isAvailable = false; };
}, that.saveDocument = function () {
done_checkNameAvailability: function ( isavailable ) { that.fail('This method must be redefined!',0);
this.res.message = this.job.userName + ' is ' + };
(isavailable?'':'not ') + 'available.'; that.getDocumentList = function () {
this.res.isAvailable = isavailable; that.fail('This method must be redefined!',0);
}, };
fail_saveDocument: function () { that.removeDocument = function () {
this.res.isSaved = false; that.fail('This method must be redefined!',0);
}, };
done_saveDocument: function () { //// end Public Methods
this.res.message = 'Document saved.'; return that;
this.res.isSaved = true;
},
fail_loadDocument: function () {
this.res.document = {};
},
done_loadDocument: function ( returneddocument ) {
this.res.message = 'Document loaded.';
this.res.document = returneddocument;
},
fail_getDocumentList: function () {
this.res.list = [];
},
done_getDocumentList: function ( documentlist ) {
this.res.message = 'Document list received.';
this.res.list = documentlist;
},
fail_removeDocument: function () {
this.res.isRemoved = false;
},
done_removeDocument: function () {
this.res.message = 'Document removed.';
this.res.isRemoved = true;
}
}; };
// end BaseStorage // end BaseStorage
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
...@@ -848,9 +901,9 @@ ...@@ -848,9 +901,9 @@
} }
// check storage type // check storage type
if (this.storage) if (this.storage && !jioGlobalObj.storageTypeObject[this.storage.type]){
if (!jioGlobalObj.storageTypeObject[this.storage.type]) $.error('Unknown storage type "' + this.storage.type +'"');
$.error('Unknown storage type "' + this.storage.type +'"'); }
// start jio process // start jio process
this.start(); this.start();
...@@ -1091,6 +1144,7 @@ ...@@ -1091,6 +1144,7 @@
// 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
// options.useLocalStorage: if true, save job queue on localStorage. // options.useLocalStorage: if true, save job queue on localStorage.
var settings = $.extend({'useLocalStorage':true},options); var settings = $.extend({'useLocalStorage':true},options);
if (jioGlobalObj.localStorage===null) { if (jioGlobalObj.localStorage===null) {
...@@ -1099,8 +1153,10 @@ ...@@ -1099,8 +1153,10 @@
return new JioCons(storage,applicant,settings); return new JioCons(storage,applicant,settings);
}, },
getStoragePrototype: function () { newBaseStorage: function ( options ) {
return new BaseStorage(); // Create a Jio Storage which can be used to design new storage.
return BaseStorage( options );
}, },
addStorageType: function ( type, constructor ) { 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
......
...@@ -35,39 +35,36 @@ ...@@ -35,39 +35,36 @@
// check dependencies // check dependencies
if (!checkJioDependencies()) { return; } if (!checkJioDependencies()) { return; }
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
// Local Storage // Local Storage
LocalStorage = function ( args ) { LocalStorage = function ( args ) {
// LocalStorage constructor // LocalStorage constructor
this.job = args.job; var that = Jio.newBaseStorage( args ), priv = {};
};
LocalStorage.prototype = { that.checkNameAvailability = function () {
checkNameAvailability: function () {
// checks the availability of the [job.userName]. // checks the availability of the [job.userName].
// if the name already exists, it is not available. // if the name already exists, it is not available.
// this.job.userName: the name we want to check. // this.job.userName: the name we want to check.
var t = this, localStor = null,
k = 'key', splitk = ['splitedkey'];
// wait a little in order to simulate asynchronous operation // wait a little in order to simulate asynchronous operation
setTimeout(function () { setTimeout(function () {
localStor = jioGlobalObj.localStorage.getAll(); var localStorageObject = null, k = 'key', splitk = ['splitedkey'];
for (k in localStor) {
localStorageObject = jioGlobalObj.localStorage.getAll();
for (k in localStorageObject) {
splitk = k.split('/'); splitk = k.split('/');
if (splitk[0] === 'jio' && if (splitk[0] === 'jio' &&
splitk[1] === 'local' && splitk[1] === 'local' &&
splitk[2] === t.job.userName) { splitk[2] === that.getUserName()) {
return t.done(false); return that.done(false);
} }
} }
return t.done(true); return that.done(true);
}, 100); }, 100);
}, // end userNameAvailable }; // end userNameAvailable
saveDocument: function () { that.saveDocument = function () {
// Save a document in the local storage // Save a document in the local storage
// this.job.fileName: the document name. // this.job.fileName: the document name.
// this.job.fileContent: the document content. // this.job.fileContent: the document content.
...@@ -75,36 +72,37 @@ ...@@ -75,36 +72,37 @@
// this.job.storage.userName: the user name // this.job.storage.userName: the user name
// this.job.applicant.ID: the applicant id. // this.job.applicant.ID: the applicant id.
var t = this, doc = null;
// 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;
// reading // reading
doc = jioGlobalObj.localStorage.getItem( doc = jioGlobalObj.localStorage.getItem(
'jio/local/'+t.job.storage.userName+'/'+ 'jio/local/'+that.getStorageUserName()+'/'+
t.job.applicant.ID+'/'+ that.getApplicantID()+'/'+
t.job.fileName); that.getFileName());
if (!doc) { if (!doc) {
// create document // create document
doc = { doc = {
'fileName': t.job.fileName, 'fileName': that.getFileName(),
'fileContent': t.job.fileContent, 'fileContent': that.getFileContent(),
'creationDate': Date.now(), 'creationDate': Date.now(),
'lastModified': Date.now() 'lastModified': Date.now()
} }
} else { } else {
// overwriting // overwriting
doc.lastModified = Date.now(); doc.lastModified = Date.now();
doc.fileContent = t.job.fileContent; doc.fileContent = that.getFileContent();
} }
jioGlobalObj.localStorage.setItem( jioGlobalObj.localStorage.setItem(
'jio/local/'+t.job.storage.userName+'/'+ 'jio/local/'+that.getStorageUserName()+'/'+
t.job.applicant.ID+'/'+ that.getApplicantID()+'/'+
t.job.fileName, doc); that.getFileName(), doc);
return t.done(); return that.done();
}, 100); }, 100);
}, // end saveDocument }; // end saveDocument
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.
...@@ -113,29 +111,28 @@ ...@@ -113,29 +111,28 @@
// document object is {'fileName':string,'fileContent':string, // document object is {'fileName':string,'fileContent':string,
// 'creationDate':date,'lastModified':date} // 'creationDate':date,'lastModified':date}
var t = this, doc = null, settings = $.extend(
{'getContent':true},this.job.options);
// 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(
{'getContent':true},that.cloneOptionObject());
doc = jioGlobalObj.localStorage.getItem( doc = jioGlobalObj.localStorage.getItem(
'jio/local/'+t.job.storage.userName+'/'+ 'jio/local/'+that.getStorageUserName()+'/'+
t.job.applicant.ID+'/'+t.job.fileName); that.getApplicantID()+'/'+that.getFileName());
if (!doc) { if (!doc) {
t.fail('Document not found.',404); that.fail('Document not found.',404);
} else { } else {
if (!settings.getContent) { if (!settings.getContent) {
delete doc.fileContent; delete doc.fileContent;
} }
t.done(doc); that.done(doc);
} }
}, 100); }, 100);
}, // end loadDocument }; // end loadDocument
getDocumentList: function () { that.getDocumentList = function () {
// Get a document list from the storage. It returns a document // Get a document list from the storage. It returns a document
// array containing all the user documents informations, but not // array containing all the user documents informations.
// their content.
// this.job.storage: the storage informations. // this.job.storage: the storage informations.
// this.job.storage.userName: the userName. // this.job.storage.userName: the userName.
// this.job.storage.applicant.ID: the applicant ID. // this.job.storage.applicant.ID: the applicant ID.
...@@ -143,45 +140,45 @@ ...@@ -143,45 +140,45 @@
// 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 t = this, list = [], localStor = null, k = 'key',
splitk = ['splitedkey'];
setTimeout(function () { setTimeout(function () {
localStor = jioGlobalObj.localStorage.getAll(); var list = [], localStor = null, k = 'key',
for (k in localStor) { splitk = ['splitedkey'];
localStorageObject = jioGlobalObj.localStorage.getAll();
for (k in localStorageObject) {
splitk = k.split('/'); splitk = k.split('/');
if (splitk[0] === 'jio' && if (splitk[0] === 'jio' &&
splitk[1] === 'local' && splitk[1] === 'local' &&
splitk[2] === t.job.storage.userName && splitk[2] === that.getStorageUserName() &&
splitk[3] === t.job.applicant.ID) { splitk[3] === that.getApplicantID()) {
fileObject = JSON.parse(localStor[k]); fileObject = JSON.parse(localStorageObject[k]);
list.push ({ list.push ({
'fileName':fileObject.fileName, 'fileName':fileObject.fileName,
'creationDate':fileObject.creationDate, 'creationDate':fileObject.creationDate,
'lastModified':fileObject.lastModified}); 'lastModified':fileObject.lastModified});
} }
} }
t.done(list); that.done(list);
}, 100); }, 100);
}, // end getDocumentList }; // end getDocumentList
removeDocument: function () { that.removeDocument = function () {
// Remove a document from the storage. // Remove a document from the storage.
// this.job.storage.userName: the userName. // this.job.storage.userName: the userName.
// 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.
var t = this;
setTimeout (function () { setTimeout (function () {
// deleting // deleting
jioGlobalObj.localStorage.deleteItem( jioGlobalObj.localStorage.deleteItem(
'jio/local/'+ 'jio/local/'+
t.job.storage.userName+'/'+t.job.applicant.ID+ that.getStorageUserName()+'/'+
'/'+t.job.fileName); that.getApplicantID()+'/'+
return t.done(); that.getFileName());
return that.done();
}, 100); }, 100);
} };
return that;
}, },
// end Local Storage // end Local Storage
...@@ -190,10 +187,9 @@ ...@@ -190,10 +187,9 @@
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
// DAVStorage // DAVStorage
DAVStorage = function ( args ) { DAVStorage = function ( args ) {
this.job = args.job; var that = Jio.newBaseStorage( args );
};
DAVStorage.prototype = { that.mkcol = function ( options ) {
mkcol: function ( options ) {
// create folders in dav storage, synchronously // create folders in dav storage, synchronously
// options : contains mkcol list // options : contains mkcol list
// options.location : the davstorage locations // options.location : the davstorage locations
...@@ -206,13 +202,13 @@ ...@@ -206,13 +202,13 @@
var settings = $.extend ({ var settings = $.extend ({
'success':function(){},'error':function(){}},options), 'success':function(){},'error':function(){}},options),
splitpath = ['splitedpath'], tmppath = 'temp/path', t = this; splitpath = ['splitedpath'], tmppath = 'temp/path';
// if pathstep is not defined, then split the settings.path // if pathstep is not defined, then split the settings.path
// and do mkcol recursively // and do mkcol recursively
if (!settings.pathsteps) { if (!settings.pathsteps) {
settings.pathsteps = 1; settings.pathsteps = 1;
this.mkcol(settings); that.mkcol(settings);
} else { } else {
splitpath = settings.path.split('/'); splitpath = settings.path.split('/');
// // check if the path is terminated by '/' // // check if the path is terminated by '/'
...@@ -237,7 +233,7 @@ ...@@ -237,7 +233,7 @@
// xhrFields: {withCredentials: 'true'}, // cross domain // xhrFields: {withCredentials: 'true'}, // cross domain
success: function () { success: function () {
// done // done
t.mkcol(settings); that.mkcol(settings);
}, },
error: function (type) { error: function (type) {
alert(JSON.stringify(type)); alert(JSON.stringify(type));
...@@ -253,8 +249,9 @@ ...@@ -253,8 +249,9 @@
} }
} ); } );
} }
}, };
checkNameAvailability: function () {
that.checkNameAvailability = function () {
// checks the availability of the [job.userName]. // checks the availability of the [job.userName].
// if the name already exists, it is not available. // if the name already exists, it is not available.
// this.job.storage: the storage informations. // this.job.storage: the storage informations.
...@@ -263,33 +260,33 @@ ...@@ -263,33 +260,33 @@
// 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.
var t = this;
$.ajax ( { $.ajax ( {
url: t.job.storage.location + '/dav/' + t.job.userName + '/', url: that.getStorageLocation() + '/dav/' +
that.getStorageUserName() + '/',
async: true, async: true,
type: 'PROPFIND', type: 'PROPFIND',
dataType: 'xml', dataType: 'xml',
headers: {'Authorization': 'Basic '+Base64.encode( headers: {'Authorization': 'Basic '+Base64.encode(
t.job.storage.userName + ':' + that.getStorageUserName() + ':' +
t.job.storage.password ), Depth: '1'}, that.getStoragePassword() ), Depth: '1'},
success: function (xmlData) { success: function (xmlData) {
t.done(false); that.done(false);
}, },
error: function (type) { error: function (type) {
switch(type.status){ switch(type.status){
case 404: case 404:
t.done(true); that.done(true);
break; break;
default: default:
t.fail('Cannot check if ' + t.job.userName + that.fail('Cannot check if ' + that.getUserName() +
' is available.',type.status); ' is available.',type.status);
break; break;
} }
} }
} ); } );
}, };
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.
// this.job.storage.userName: the user name. // this.job.storage.userName: the user name.
...@@ -298,32 +295,31 @@ ...@@ -298,32 +295,31 @@
// this.job.fileName: the document name. // this.job.fileName: the document name.
// this.job.fileContent: the document content. // this.job.fileContent: the document content.
var t = this;
// 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: t.job.storage.location + '/dav/' + url: that.getStorageLocation() + '/dav/' +
t.job.storage.userName + '/' + that.getStorageUserName() + '/' +
t.job.applicant.ID + '/' + that.getApplicantID() + '/' +
t.job.fileName, that.getFileName(),
type: 'PUT', type: 'PUT',
data: t.job.fileContent, data: that.getFileContent(),
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(
t.job.storage.userName + ':' + t.job.storage.password )}, that.getStorageUserName() + ':' + that.getStoragePassword())},
// xhrFields: {withCredentials: 'true'}, // cross domain // xhrFields: {withCredentials: 'true'}, // cross domain
success: function () { success: function () {
t.done(); that.done();
}, },
error: function (type) { error: function (type) {
t.fail('Cannot save document.',type.status); that.fail('Cannot save document.',type.status);
} }
} ); } );
//// end saving on dav //// end saving on dav
}, };
loadDocument: function () {
that.loadDocument = function () {
// Load a document from a DAVStorage. It returns a document object // Load a document from a DAVStorage. 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.
...@@ -336,26 +332,26 @@ ...@@ -336,26 +332,26 @@
// document object is {'fileName':string,'fileContent':string, // document object is {'fileName':string,'fileContent':string,
// 'creationDate':date,'lastModified':date} // 'creationDate':date,'lastModified':date}
var t = this, doc = {}, var doc = {},
settings = $.extend({'getContent':true},this.job.options), settings = $.extend({'getContent':true},that.cloneOptionObject()),
// TODO check if job's features are good // TODO check if job's features are good
getContent = function () { getContent = function () {
$.ajax ( { $.ajax ( {
url: t.job.storage.location + '/dav/' + url: that.getStorageLocation() + '/dav/' +
t.job.storage.userName + '/' + that.getStorageUserName() + '/' +
t.job.applicant.ID + '/' + that.getApplicantID() + '/' +
t.job.fileName, that.getFileName(),
type: "GET", type: "GET",
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(
t.job.storage.userName + ':' + that.getStorageUserName() + ':' +
t.job.storage.password )}, that.getStoragePassword() )},
// xhrFields: {withCredentials: 'true'}, // cross domain // xhrFields: {withCredentials: 'true'}, // cross domain
success: function (content) { success: function (content) {
doc.fileContent = content; doc.fileContent = content;
t.done(doc); that.done(doc);
}, },
error: function (type) { error: function (type) {
var message; var message;
...@@ -363,25 +359,25 @@ ...@@ -363,25 +359,25 @@
case 404: case 404:
message = 'Document not found.'; break; message = 'Document not found.'; break;
default: default:
message = 'Cannot load "' + job.fileName + '".'; message = 'Cannot load "' + that.getFileName() + '".';
break; break;
} }
t.fail(message,type.status); that.fail(message,type.status);
} }
} ); } );
} };
// Get properties // Get properties
$.ajax ( { $.ajax ( {
url: t.job.storage.location + '/dav/' + url: that.getStorageLocation() + '/dav/' +
t.job.storage.userName + '/' + that.getStorageUserName() + '/' +
t.job.applicant.ID + '/' + that.getApplicantID() + '/' +
t.job.fileName, that.getFileName(),
type: "PROPFIND", type: "PROPFIND",
async: true, async: true,
dataType: 'xml', dataType: 'xml',
headers: {'Authorization':'Basic '+Base64.encode( headers: {'Authorization':'Basic '+Base64.encode(
t.job.storage.userName + ':' + that.getStorageUserName() + ':' +
t.job.storage.password )}, that.getStoragePassword() )},
success: function (xmlData) { success: function (xmlData) {
doc.lastModified = ( doc.lastModified = (
new Date($($("lp1\\:getlastmodified", new Date($($("lp1\\:getlastmodified",
...@@ -389,22 +385,22 @@ ...@@ -389,22 +385,22 @@
doc.creationDate = ( doc.creationDate = (
new Date($($("lp1\\:creationdate", new Date($($("lp1\\:creationdate",
xmlData).get(0)).text())).getTime(); xmlData).get(0)).text())).getTime();
doc.fileName = t.job.fileName; doc.fileName = that.getFileName();
if (settings.getContent) { if (settings.getContent) {
getContent(); getContent();
} else { } else {
t.done(doc); that.done(doc);
} }
}, },
error: function (type) { error: function (type) {
t.fail('Cannot get document informations.',type.status); that.fail('Cannot get document informations.',type.status);
} }
} ); } );
}, };
getDocumentList: function () {
that.getDocumentList = function () {
// Get a document list from a DAVStorage. It returns a document // Get a document list from a DAVStorage. It returns a document
// array containing all the user documents informations, but their // array containing all the user documents informations.
// content.
// this.job.storage: the storage informations. // this.job.storage: the storage informations.
// this.job.storage.location: the dav storage location. // this.job.storage.location: the dav storage location.
// this.job.storage.userName: the user name. // this.job.storage.userName: the user name.
...@@ -414,17 +410,18 @@ ...@@ -414,17 +410,18 @@
// 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 t = this, documentArrayList = [], file = {}, pathArray = []; var documentArrayList = [], file = {}, pathArray = [];
$.ajax ( { $.ajax ( {
url: t.job.storage.location + '/dav/' + url: that.getStorageLocation() + '/dav/' +
t.job.storage.userName + '/' + t.job.applicant.ID + '/', that.getStorageUserName() + '/' +
that.getApplicantID() + '/',
async: true, async: true,
type: 'PROPFIND', type: 'PROPFIND',
dataType: 'xml', dataType: 'xml',
headers: {'Authorization': 'Basic '+Base64.encode( headers: {'Authorization': 'Basic '+Base64.encode(
t.job.storage.userName + ':' + that.getStorageUserName() + ':' +
t.job.storage.password ), Depth: '1'}, that.getStoragePassword() ), Depth: '1'},
success: function (xmlData) { success: function (xmlData) {
$("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
...@@ -445,14 +442,15 @@ ...@@ -445,14 +442,15 @@
documentArrayList.push (file); documentArrayList.push (file);
} }
}); });
t.done(documentArrayList); that.done(documentArrayList);
}, },
error: function (type) { error: function (type) {
t.fail('Cannot get list.',type.status); that.fail('Cannot get list.',type.status);
} }
} ); } );
}, };
removeDocument: function ( job, jobendcallback ) {
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.
// this.job.storage: the storage informations. // this.job.storage: the storage informations.
...@@ -461,34 +459,34 @@ ...@@ -461,34 +459,34 @@
// 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.
var t = this;
$.ajax ( { $.ajax ( {
url: t.job.storage.location + '/dav/' + url: that.getStorageLocation() + '/dav/' +
t.job.storage.userName + '/' + that.getStorageUserName() + '/' +
t.job.applicant.ID + '/' + that.getApplicantID() + '/' +
t.job.fileName, that.getFileName(),
type: "DELETE", type: "DELETE",
async: true, async: true,
headers: {'Authorization':'Basic '+Base64.encode( headers: {'Authorization':'Basic '+Base64.encode(
t.job.storage.userName + ':' + that.getStorageUserName() + ':' +
t.job.storage.password )}, that.getStoragePassword() )},
// xhrFields: {withCredentials: 'true'}, // cross domain // xhrFields: {withCredentials: 'true'}, // cross domain
success: function () { success: function () {
t.done(); that.done();
}, },
error: function (type) { error: function (type) {
switch (type.status) { switch (type.status) {
case 404: case 404:
t.done(); that.done();
break; break;
default: default:
t.fail('Cannot remove "' + t.job.fileName + '".',type.status); that.fail('Cannot remove "' + that.getFileName()
+ '".',type.status);
break; break;
} }
} }
} ); } );
} };
return that;
}, },
// end DAVStorage // end DAVStorage
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
...@@ -496,67 +494,227 @@ ...@@ -496,67 +494,227 @@
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
// ReplicateStorage // ReplicateStorage
ReplicateStorage = function ( args ) { ReplicateStorage = function ( args ) {
var that = Jio.newBaseStorage( args ), priv = {};
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.
this.queue = args.queue; priv.length = priv.storageArray.length;
this.job = args.job; priv.returnsValuesArray = [];
this.id = null; priv.maxtries = that.getMaxTries();
this.length = args.job.storage.storageArray.length;
this.returnsValuesArray = []; that.setMaxTries (1);
};
ReplicateStorage.prototype = { that.checkNameAvailability = function () {
checkNameAvailability: function () {
// Checks the availability of the [job.userName]. // Checks the availability of the [job.userName].
// if the name already exists in a storage, it is not available. // if the name already exists in a storage, it is not available.
// this.job.userName: the name we want to check. // this.job.userName: the name we want to check.
// this.job.storage.storageArray: An Array of storages. // this.job.storage.storageArray: An Array of storages.
// TODO
var t = this, newjob = {}, isavailable = true, var newjob = {}, isavailable = true,
res = {'status':'done'}, i = 'ind'; res = {'status':'done'}, i = 'ind';
for (i in t.job.storage.storageArray) { for (i in priv.storageArray) {
newjob = $.extend({},t.job); newjob = that.cloneJob();
newjob.storage = t.job.storage.storageArray[i]; newjob.maxtries = priv.maxtries;
newjob.storage = priv.storageArray[i];
newjob.callback = function (result) { newjob.callback = function (result) {
t.returnsValuesArray.push(result); priv.returnsValuesArray.push(result);
if (result.status === 'fail') { if (result.status === 'fail') {
res.status = 'fail'; res.status = 'fail';
} }
if (!result.isAvailable) { isavailable = false; } if (!result.isAvailable) { isavailable = false; }
if (t.returnsValuesArray.length === t.length) { if (priv.returnsValuesArray.length === priv.length) {
// if this is the last callback // if this is the last callback
t.done(isavailable); that.done(isavailable);
} }
}; };
this.queue.createJob ( newjob ) ; that.addJob ( newjob ) ;
} }
}, };
saveDocument: function () { that.saveDocument = function () {
// Save a single document in several storages. // Save a single document in several storages.
// If a storage failed to save the document, it modify the job in // If a storage failed to save the document.
// in order to invoke it sometime later. // this.job.storage: the storage informations.
// job: the job object // this.job.storage.userName: the user name.
// job.options: the save options object // this.job.storage.password: the user password.
// job.options.overwrite: true -> overwrite // this.job.applicant.ID: the applicant ID.
// job.options.force: true -> save even if jobdate < existingdate // this.job.fileName: the document name.
// or overwrite: false // this.job.fileContent: the document content.
// jobendcallback: the function called at the end of the job.
// returns {'status':string,'message':string,'isSaved':boolean,
// 'resultArray':Array} in the jobendcallback arguments.
// TODO // TODO
},
loadDocument: function () { var newjob = {},
res = {'status':'done'}, i = 'ind';
for (i in priv.storageArray) {
newjob = that.cloneJob();
newjob.maxtries = priv.maxtries;
newjob.storage = priv.storageArray[i];
newjob.callback = function (result) {
priv.returnsValuesArray.push(result);
if (result.status === 'fail') {
res.status = 'fail';
}
if (priv.returnsValuesArray.length === priv.length) {
// if this is the last callback
if (res.status === 'fail') {
that.fail('Unable to save all files.',0);
} else {
that.done();
}
}
};
that.addJob ( newjob ) ;
}
};
that.loadDocument = function () {
// Load a document from several storages. It returns a document
// object containing all information of the document and its
// content. TODO will popup a window which will help us to choose
// the good file if the files are different.
// this.job.fileName: the document name we want to load.
// this.job.storage: the storage informations.
// this.job.storage.location: the dav storage location.
// this.job.storage.userName: the user name.
// this.job.storage.password: the user password.
// this.job.options.getContent: if true, also get the file content.
// document object is {'fileName':string,'fileContent':string,
// 'creationDate':date,'lastModified':date}
// TODO // TODO
},
getDocumentList: function () { var newjob = {}, aredifferent = false, doc = {},
res = {'status':'done'}, i = 'ind';
doc.fileName = that.getFileName();
for (i in priv.storageArray) {
newjob = that.cloneJob();
newjob.maxtries = priv.maxtries;
newjob.storage = priv.storageArray[i];
newjob.callback = function (result) {
priv.returnsValuesArray.push(result);
if (result.status === 'fail') {
res.status = 'fail';
} else {
// check if the file are different
if (!doc.fileContent && !doc.creationDate &&
!doc.lastModified) {
// if it is the first document loaded
doc = $.extend({},result.document);
} else {
if (doc.fileContent !==
result.document.fileContent) {
// if the document is different from the
// previous one
aredifferent = true;
}
if (doc.creationDate >
result.document.creationDate) {
// get older creation date
doc.creationDate = result.document.creationDate;
}
if (doc.lastModified <
result.document.lastModified) {
// get newer last modified
doc.fileContent = result.document.fileContent;
doc.lastModified = result.document.lastModified;
}
}
}
if (priv.returnsValuesArray.length === priv.length) {
// if this is the last callback
if (res.status === 'fail') {
that.fail('Unable to load all files.',0);
} else {
if (!aredifferent) {
that.done(doc);
} else {
// TODO the files are different! Give options
// to know what do we do now!
// console.warn ('The files are different.');
that.done(doc);
}
}
}
};
that.addJob ( newjob ) ;
}
};
that.getDocumentList = function () {
// Get a document list from several storages. It returns a document
// array containing all the user documents informations.
// this.job.storage: the storage informations.
// this.job.storage.location: the dav storage location.
// this.job.storage.userName: the user name.
// this.job.storage.password: the user password.
// this.job.applicant.ID: the applicant id.
// the list is [object,object] -> object = {'fileName':string,
// 'lastModified':date,'creationDate':date}
// TODO // TODO
},
removeDocument: function () { var newjob = {},
res = {'status':'done'}, i = 'ind';
for (i in priv.storageArray) {
newjob = that.cloneJob();
newjob.maxtries = priv.maxtries;
newjob.storage = priv.storageArray[i];
newjob.callback = function (result) {
priv.returnsValuesArray.push(result);
if (result.status === 'fail') {
res.status = 'fail';
}
if (priv.returnsValuesArray.length === priv.length) {
// if this is the last callback
if (res.status === 'fail') {
that.fail('Unable retrieve all lists.',0);
} else {
that.done(result.list);
}
}
};
that.addJob ( newjob ) ;
}
};
that.removeDocument = function () {
// Remove a document from several storages.
// this.job.fileName: the document name we want to remove.
// this.job.storage: the storage informations.
// this.job.storage.location: the dav storage location.
// this.job.storage.userName: the user name.
// this.job.storage.password: the user password.
// this.job.applicant.ID: the applicant id.
// TODO // TODO
}
var newjob = {},
res = {'status':'done'}, i = 'ind';
for (i in priv.storageArray) {
newjob = that.cloneJob();
newjob.maxtries = priv.maxtries;
newjob.storage = priv.storageArray[i];
newjob.callback = function (result) {
priv.returnsValuesArray.push(result);
if (result.status === 'fail') {
res.status = 'fail';
}
if (priv.returnsValuesArray.length === priv.length) {
// if this is the last callback
if (res.status === 'fail') {
that.fail('Unable remove all files.',0);
} else {
that.done();
}
}
};
that.addJob ( newjob ) ;
} };
return that;
}; };
// end ReplicateStorage // end ReplicateStorage
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
...@@ -564,15 +722,11 @@ ...@@ -564,15 +722,11 @@
Jio.addStorageType('local', function (options) { Jio.addStorageType('local', function (options) {
return new LocalStorage(options); return new LocalStorage(options);
}); });
// add key to storageObject
Jio.addStorageType('dav', function (options) { Jio.addStorageType('dav', function (options) {
return new DAVStorage(options); return new DAVStorage(options);
}); });
// add key to storageObject
Jio.addStorageType('replicate', function (options) { Jio.addStorageType('replicate', function (options) {
return new ReplicateStorage(options); return new ReplicateStorage(options);
}); });
})( JIO ); })( JIO );
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