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>
...@@ -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');
...@@ -140,19 +140,15 @@ test ('Simple Job Elimination', function () { ...@@ -140,19 +140,15 @@ 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');
}); });
...@@ -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);
...@@ -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);
......
...@@ -195,26 +195,6 @@ ...@@ -195,26 +195,6 @@
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
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
...@@ -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
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
...@@ -284,105 +264,115 @@ ...@@ -284,105 +264,115 @@
// 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; var that = {}, priv = {};
this.publisher = publisher;
this.jobid = 1;
this.jioID = 0;
this.jobObjectName = '';
this.jobObject = {};
// reset all jobs' status to initial
this.resetAll();
};
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;
} }
...@@ -397,55 +387,55 @@ ...@@ -397,55 +387,55 @@
// 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; priv.interval = 200;
this.id = null; priv.id = null;
this.queue = queue; 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 (!this.id) { if (!priv.id) {
this.id = setInterval (function () { priv.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;
// start the updater //// end private vars
var t = this; //// methods
that.start = function (id) {
// start the updater
if (!this.id) { if (!priv.id) {
this.touch(id); that.touch(id);
this.id = setInterval (function () { priv.id = setInterval (function () {
t.touch(id); that.touch(id);
},this.interval); },priv.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
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
...@@ -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
if (this.storage && !jioGlobalObj.storageTypeObject[this.storage.type]){
$.error('Unknown storage type "' + this.storage.type +'"');
}
// start jio process //// Getters Setters
this.start(); that.getID = function () {
return priv.id;
}; };
// JIO Prototype //// end Getters Setters
JioCons.prototype = {
start: function () { //// Methods
that.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); return priv.pubsub.unsubscribe(eventname,callback);
}, };
checkNameAvailability: function ( options ) { 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)
...@@ -1118,29 +1099,63 @@ ...@@ -1118,29 +1099,63 @@
// 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 new Jio(); return that;
};
return new JioCreator();
// end Jio Creator // end Jio Creator
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
})(); })();
...@@ -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
...@@ -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();
...@@ -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);
...@@ -426,7 +426,8 @@ ...@@ -426,7 +426,8 @@
$("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 = (
$($("D\\:href",
xmlData).get(i)).text()).split('/'); 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] :
...@@ -434,10 +435,12 @@ ...@@ -434,10 +435,12 @@
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(
$($("lp1\\:getlastmodified",
xmlData).get(i)).text())).getTime(); xmlData).get(i)).text())).getTime();
file.creationDate = ( file.creationDate = (
new Date($($("lp1\\:creationdate", new Date(
$($("lp1\\:creationdate",
xmlData).get(i)).text())).getTime(); xmlData).get(i)).text())).getTime();
documentArrayList.push (file); documentArrayList.push (file);
} }
......
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