-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsession.js
1002 lines (871 loc) · 34.1 KB
/
session.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2003-2011 MarkLogic Corporation. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// The use of the Apache License does not indicate that this project is
// affiliated with the Apache Software Foundation.
//
//////////////////////////////////////////////////////////////////////////
// NOTE: to defeat IE6 caching, always use method=POST
// GLOBAL CONSTANTS: but IE6 doesn't support "const"
var gSessionIdCookie = "com.marklogic.cq.session-id";
var gLocalStoreSessionsKey = "com.marklogic.cq.sessions";
// GLOBAL VARIABLES
// static functions
function reportError(resp, from) {
var old = debug.isEnabled();
debug.setEnabled(true);
debug.print("session.js (reportError from " + from + "): "
+ "status = (" + resp.status + ") " + resp.statusText
+ ", response = " + resp.responseText
+ ", request.url = " + resp.request.url);
debug.setEnabled(old);
}
// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
function createUUID() {
// http://www.ietf.org/rfc/rfc4122.txt
var s = [];
var hexDigits = "0123456789ABCDEF";
for (var i = 0; i < 32; i++) {
s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
}
// bits 12-15 of the time_hi_and_version field to 0010
s[12] = "4";
// bits 6-7 of the clock_seq_hi_and_reserved to 01
s[16] = hexDigits.substr((s[16] & 0x3) | 0x8, 1);
return s.join("");
}
// SessionList class
function SessionList() {
this.cloneUrl = 'session-clone.xqy';
this.deleteUrl = 'session-delete.xqy';
this.currentSession = null;
this.setCurrentSession = function(s) {
this.currentSession = s;
};
this.refresh = function() {
if (debug.isEnabled()) {
alert("DEBUG: will refresh now");
window.location.assign( ".?debug=1");
} else {
window.location.assign( "." );
}
};
this.newSession = function() {
// start a new session and set the user cookie appropriately
debug.print("newSession: start");
// setting the session id to the string "NEW" signals
// lib-controller.xqy to build a new session.
setCookie(gSessionIdCookie, "NEW");
// refresh should show the query view
this.refresh();
};
this.resumeSession = function(sessionId) {
debug.print("resumeSession: " + sessionId);
// set cookie to the new id
setCookie(gSessionIdCookie, sessionId);
// refresh should show the query view
this.refresh();
};
this.buildNamedQueryString = function(id, name) {
return 'ID=' + id + '&NAME=' + escape(name) + (
debug.isEnabled() ? '&DEBUG=1' : '');
};
this.exportServerSession = function(id, context) {
var path = "session-export.xqy?id=" + id;
window.location.assign(path);
};
this.cloneSession = function(id, context) {
// clone the session
var name = prompt("Name of cloned session:", "new session");
debug.print("cloneSession: " + id + " to " + name);
if (! name) {
return;
}
// call session-clone
var closure = this;
var newId = null;
var opts = {
method: 'post',
// workaround, to avoid appending charset info
encoding: null,
parameters: this.buildNamedQueryString(id, name),
asynchronous: false,
onFailure: reportError,
onSuccess: function(resp) {
// refresh page to show new session
newId = resp.responseText;
}
};
var req = new Ajax.Request(this.cloneUrl, opts);
// synchronous, so we should have the response here
debug.print("cloneSession: newId = " + newId);
closure.resumeSession(newId);
};
this.deleteSession = function(id, context) {
// delete the session
debug.print("deleteSession: " + id);
if (! confirm("Are you sure you want to delete this session?")) {
return;
}
// call session-delete
var opts = {
method: 'post',
// workaround, to avoid appending charset info
encoding: null,
parameters: 'ID=' + id,
asynchronous: false,
onFailure: reportError
};
var req = new Ajax.Request(this.deleteUrl, opts);
// delete the item from the DOM
// context will be the button
var row = context.parentNode.parentNode;
if (null != row) {
Element.remove(row);
}
};
} // SessionListClass
// this class is responsible for autosaving the session state
function SessionClass(tabs, id) {
this.tabs = tabs;
this.restoreId = id;
this.sessionId = null;
// only for local sessions
this.sessionName = null;
this.localSessionList = null;
// only for remote sessions
this.etag = null;
this.buffers = this.tabs ? this.tabs.getBuffers() : null;
debug.print("SessionClass: buffers = " + this.buffers);
this.history = this.tabs ? this.tabs.getHistory() : null;
debug.print("SessionClass: history = " + this.history);
this.lastSync = null;
// enable sync if and only if we see a session id
this.syncDisabled = true;
// handle for scheduled save task
this.autosave = null;
this.renameUrl = 'session-rename.xqy';
this.updateSessionUrl = "session-update.xqy";
this.updateSessionLockUrl = "session-lock-update.xqy";
this.isSyncEnabled = function() { return ! this.syncDisabled; };
this.getId = function() { return this.sessionId; };
this.rename = function(name) {
// used for local session rename
this.sessionName = name;
this.tabs.setSessionName();
this.sync();
};
this.restore = function() {
var restore = $(this.restoreId);
var label = "SessionClass.restore: ";
if (null == restore) {
debug.print(label + "null restore from " + this.restoreId);
this.syncDisabled = true;
if (this.tabs) {
this.tabs.refresh();
}
return;
}
debug.print(label + restore + " " + restore.hasChildNodes());
// handle session id cookie
this.sessionId = restore.getAttribute('session-id');
// sessionId may be null, or empty string:
// either disables sync unless local storage is available
if (this.sessionId) {
this.syncDisabled = false;
setCookie(gSessionIdCookie, this.sessionId);
debug.print(label + "set session id cookie = " + this.sessionId);
} else {
debug.print(label + "missing session id!");
this.syncDisabled = true;
// not fatal - keep restoring whatever the server gave us
}
debug.print(label + "syncDisabled = " + this.syncDisabled);
this.restoreFromXML(restore);
};
this.restoreFromXML = function(restore) {
var label = "SessionClass.restoreFromXML: ";
var children = restore.childNodes;
if (!children) {
return;
}
debug.print(label + "children = " + children);
// store the last-updated value
this.etag = restore.getAttribute('etag');
// handle exposed tab
var activeTab = restore.getAttribute('active-tab');
var queries = null;
var query = null;
var source = null;
// first div is the buffers
var buffers = children[0];
debug.print(label + "buffers = " + buffers);
// handle rows and cols (global)
this.buffers.setRows(buffers.getAttribute('rows'));
this.buffers.setCols(buffers.getAttribute('cols'));
queries = buffers.childNodes;
debug.print(label + "queries = " + queries);
debug.print(label + "restoring buffers " + queries.length);
for (var i = 0; i < queries.length; i++) {
debug.print(label + "restoring " + i + " " + queries[i]);
query = queries[i].hasChildNodes()
? queries[i].firstChild.nodeValue
: null;
// handle content-source (per buffer)
source = queries[i].getAttribute('content-source');
debug.print(label + "restoring " + i + " source = " + source);
this.buffers.add(query, source);
}
// reactivate active buffer
var active = buffers.getAttribute('active');
debug.print(label + "buffers active = " + active);
this.buffers.activate(active);
// second div is the history
var history = children[1];
queries = history.childNodes;
debug.print(label + "restoring history " + queries.length);
// restore in reverse order
for (var i = queries.length; i > 0; i--) {
query = queries[ i - 1 ].firstChild.nodeValue;
this.history.add(query);
}
// this must happen last
this.tabs.refresh(activeTab);
};
this.restoreFromObject = function(restore) {
var label = "SessionClass.restoreFromXML: ";
debug.print(label + "restoring " + restore);
if (!restore.get) {
debug.print(label + "restoring " + Object.toJSON(restore));
}
// instead of XML, we restore from a Prototype hash object
this.sessionName = restore.get('name');
if (!this.sessionName) {
this.sessionName = "local";
}
var activeTab = restore.get('active-tab');
var activeBuffer = restore.get('active-buffer');
var rows = restore.get('rows');
var cols = restore.get('cols');
// array of hash
var buffers = restore.get('buffers');
// array of string
var history = restore.get('history');
// restore tabs, rows, and cols
this.buffers.setRows(rows);
this.buffers.setCols(cols);
// restore buffers
if (! buffers) {
debug.print(label + "null buffers!");
} else {
debug.print(label + "restoring buffers " + buffers.length);
this.buffers.clear();
var h, query, source;
for (var i=0; i < buffers.length; i++) {
h = $H(buffers[i]);
query = h.get('query');
source = h.get('source');
debug.print(label + "restoring " + i + " source = " + source);
this.buffers.add(query, source);
}
this.buffers.activate(activeBuffer);
}
if (! history) {
debug.print(label + "null history!");
} else {
debug.print(label + "restoring history " + history.length);
// restore in reverse order
this.history.clear();
var start = history.length - 1;
for (var i=start; i >= 0; i--) {
this.history.add(history[i]);
}
}
// this must happen last
if (! activeTab) {
debug.print(label + "null activeTab!");
} else {
this.tabs.refresh(activeTab);
}
};
this.sync = function() {
var label = "SessionClass.sync: ";
if (this.syncDisabled) {
debug.print(label + "disabled");
return false;
}
if (null == this.sessionId) {
debug.print(label + "no session");
return false;
}
var historyLastModified = this.history.getLastModified();
var lastLineStatus = this.buffers.getLastLineStatus();
debug.print(label + this.sessionId
+ ", etag=" + this.etag
+ ", lastmodified=" + historyLastModified
+ " ? lastsync=" + this.lastSync);
if (null != this.lastSync
&& historyLastModified <= this.lastSync
&& lastLineStatus <= this.lastSync)
{
// nothing has changed - tickle the lock anyway
this.updateLock();
return false;
}
// this is not really thread-safe - attempt at critical section...
// this seems to work ok, but we skip some syncs under duress
this.syncDisabled = true;
if (this.localSessionList) {
debug.print(label + "local store");
setCookie(gSessionIdCookie, "LOCAL");
var syncHash = new Hash();
syncHash.set('name', this.sessionName);
syncHash.set('active-tab', this.tabs.getCurrent());
syncHash.set('active-buffer', this.buffers.getActivePosition());
syncHash.set('rows', this.buffers.getRows());
syncHash.set('cols', this.buffers.getCols());
syncHash.set('buffers', this.buffers.toArray());
syncHash.set('history', this.history.toArray());
this.localSessionList.put(this.sessionId, syncHash);
// end of critical section
this.syncDisabled = false;
this.lastSync = new Date();
return true;
}
// ajax technique, for server sessions
var buffers = this.buffers.toXml();
var history = this.history.toXml();
var tabs = this.tabs.toXml();
var params = {
DEBUG: debug.isEnabled() ? true : false,
ID: this.sessionId,
BUFFERS: buffers,
HISTORY: history,
TABS: tabs
};
debug.print(label + "" + params);
// wrap current session in a closure
var session = this;
var failureHandler = function(resp) {
var old = debug.isEnabled();
debug.setEnabled(true);
debug.print("Session.sync failure:"
+ " status = (" + resp.status + ") " + resp.statusText
+ ", response = " + resp.responseText
+ ", request.url = " + resp.request.url);
debug.setEnabled(old);
// ask the user if we should fall back to local session storage.
if (!confirm("This session could not be written to server."
+ " Use browser local storage instead?")) {
alert("Changes to this session may not be saved."
+ " You may wish to copy the current query,"
+ " and refresh cq.");
return;
}
// fall back to local browser storage
session.localSessionList = new SessionListLocal();
// re-enable session sync
session.syncDisabled = false;
// rename, which will also sync the new local session
setTimeout(function() { session.rename("new local session");
}.bindAsEventListener(this),
1000 / 32);
};
var successHandler = function(resp) {
var label = "successHandler: ";
// no resp means the update was canceled by the user
if (!resp) {
debug.print(label + "empty response");
return null;
}
if (resp.status == 0) {
// actually this was an error (blank page)
return failureHandler(resp);
}
// don't overwrite the old etag unless we have a new one
var newTag = resp.getResponseHeader("etag");
debug.print(label + "old = " + session.etag + ", new = " + newTag);
if (newTag) {
session.etag = newTag;
debug.print(label + "new = " + session.etag);
}
// re-enable sync
session.syncDisabled = false;
return null;
};
var req = new Ajax.Request(this.updateSessionUrl, {
method: 'post',
parameters: params,
requestHeaders: { 'If-Match': this.etag },
// workaround, to avoid appending charset info
encoding: null,
onSuccess: successHandler,
onFailure: failureHandler
} );
// synchronous, so we should have the response now
this.lastSync = new Date();
return true;
};
this.updateLock = function() {
var label = "SessionClass.updateLock: ";
if (this.syncDisabled || null == this.sessionId) {
debug.print(label + "disabled");
return false;
}
if (this.localSessionList) {
debug.print(label + "using local store");
return false;
}
var params = {
DEBUG: debug.isEnabled() ? true : false,
ID: this.sessionId
};
debug.print(label + "" + params);
var req = new Ajax.Request(this.updateSessionLockUrl,
{
method: 'post',
parameters: params,
// workaround, to avoid appending charset info
encoding: null,
onFailure: reportError
} );
return true;
};
this.setAutoSave = function(sec) {
if (this.syncDisabled) {
debug.print("SessionClass.setAutoSave: sync is disabled");
return;
}
sec = Number(sec);
sec = (null == sec || isNaN(sec)) ? 60 : sec;
this.autosave = new PeriodicalExecuter(this.sync
.bindAsEventListener(this),
sec);
};
this.useLocal = function (sessionList) {
var label = "SessionClass.useLocal: ";
if (! sessionList || ! sessionList.store) {
debug.print(label + "null sessionList");
return;
}
// is there a local session to restore? do we want it?
var key = sessionList.length() ? sessionList.keyAt(0) : null;
var isNewLocal = (key == "NEW");
this.localSessionList = sessionList;
debug.print(label + "count = " + this.localSessionList.length()
+ ", " + isNewLocal);
if (isNewLocal || 1 > this.localSessionList.length()) {
debug.print(label + "creating new local session");
// no session, or the session is explicitly "NEW"
// keep the already-restored server session,
// but ensure that we have a session id for sync
if (isNewLocal) {
this.localSessionList.remove("NEW");
}
this.sessionId = createUUID();
this.sessionName = "new local session "
+ (1 + this.localSessionList.length());
} else {
debug.print(label + "restoring from local session " + key);
this.sessionId = key;
this.restoreFromObject($H(this.localSessionList.get(key)));
}
// activate sessions
this.syncDisabled = false;
if (isNewLocal || this.localSessionList.length() < 1) {
debug.print(label + "saving new session " + this.sessionId);
this.sync();
}
};
} // SessionClass
// SessionListLocal class
function SessionListLocal() {
this.label = "SessionListLocal.init: ";
this.store = null;
// TODO what happens when the session exceeds the storage limit?
// can we prevent data loss?
// TODO consider http://github.com/marcuswestin/store.js instead?
try {
// prohibit cookie store since it will be too small (4-kB limit)
Persist.remove('cookie');
this.store = new Persist.Store("MarkLogic cq");
} catch (ex) {
debug.print(this.label + ex.message);
debug.print(this.label + "local sessions disabled!");
}
this.sessionsList = null;
// for event callback access
var that = this;
// populate the session list
if (this.store) {
this.store.get(gLocalStoreSessionsKey,
function(ok, val) {
if (ok) {
try {
that.sessionsList = ("" + val)
.evalJSON(true);
} catch (ex) {
debug.print(label + ex.message);
alert(label + ex.message);
}
if (null == that.sessionsList) {
that.sessionsList = new Array();
}
debug.print(that.label
+ "setting sessions = "
+ that.sessionsList.length);
}
});
}
debug.print(this.label + "sessions = "
+ (this.sessionsList ? this.sessionsList.length : "null"));
// private
this.key = function(id) {
// would like to use '/', but IE objects
// so we continue in a java-like vein
return gLocalStoreSessionsKey + "." + id;
};
this.first = function() {
if (!this.sessionsList) {
return null;
}
return this.get(this.keyAt[0]);
};
this.keys = function() {
return this.sessionsList;
};
this.keyAt = function(i) {
if (!this.sessionsList) {
return null;
}
return this.sessionsList[i];
};
this.length = function() {
if (!this.sessionsList) {
return null;
}
return this.sessionsList.length;
};
this.get = function(id) {
if (!this.store) {
return null;
}
var label = "SessionListLocal.get: ";
var result = null;
this.store.get(this.key(id),
function(ok, val) {
if (ok) {
try {
result = ("" + val).evalJSON(true);
} catch (ex) {
var old = debug.isEnabled();
debug.setEnabled(true);
debug.print(label + " size=" + val.length
+ " " + ex.message);
debug.setEnabled(old);
alert(label + ex.message.substring(0, 256));
}
}
});
return result;
};
this.storeSet = function(key, value) {
var label = "SessionListLocal.storeSet: ";
// the largest danger here is that we may hit the storage limit
// TODO - try to reduce by dropping the history?
// TODO - break up session into metadata, queries, history?
// for the moment we abort the set, which leaves the old state alone
try {
this.store.set(key, value);
} catch (ex) {
var old = debug.isEnabled();
debug.setEnabled(true);
debug.print(label + ex.message);
debug.setEnabled(old);
alert(label + ex.message.substring(0, 256));
}
};
this.put = function(id, value) {
if (!this.store) {
return;
}
var label = "SessionListLocal.put: ";
var jValue = Object.toJSON(value);
debug.print(label + id);
this.queue(id);
this.storeSet(this.key(id), jValue);
};
this.queue = function(id) {
if (!this.store) {
return;
}
var label = "SessionListLocal.queue: ";
if (!this.sessionsList) {
debug.print(label + "null sessionsList");
return;
}
// re-order the sessions by most recent use
var newArray = new Array();
newArray[0] = id;
for (var i=0; i<this.sessionsList.length; i++) {
if (id != this.sessionsList[i]) {
newArray[newArray.length] = this.sessionsList[i];
}
}
debug.print(label + newArray.length + " = " + newArray[0]);
this.sessionsList = newArray;
this.storeSet(gLocalStoreSessionsKey,
Object.toJSON(this.sessionsList));
};
this.remove = function(id) {
if (!this.store) {
return;
}
var label = "SessionListLocal.remove: ";
// re-order the sessions by most recent use
var newArray = new Array();
for (var i=0; i<this.sessionsList.length; i++) {
if (id != this.sessionsList[i]) {
newArray[newArray.length] = this.sessionsList[i];
}
}
debug.print(label + newArray.length + " = " + newArray[0]);
this.sessionsList = newArray;
this.storeSet(gLocalStoreSessionsKey,
Object.toJSON(this.sessionsList));
this.store.remove(id);
};
this.clone = function(id) {
if (!this.store) {
return;
}
var session = $H(this.get(id));
session.set('name', "copy of " + session.get('name'));
this.put(createUUID(), session);
};
this.refresh = function() {
if (debug.isEnabled()) {
alert("DEBUG: will refresh now");
window.location.assign( ".?debug=1");
} else {
window.location.assign( "." );
}
};
// NB - webkit does not like functions named 'export'
this.exportLocalSession = function(id) {
if (!this.store) {
return;
}
var label = "SessionListLocal.exportLocalSession: ";
debug.print(label + "begin");
// This is all quite painful,
// but seems to be the best technique available.
// We marshall the desired session into a form,
// then submit the form to the server,
// which does nothing but twiddle some headers.
// fetch the right local session
var restore = $H(this.get(id));
// set up a form
var formId = 'SessionListLocal.exportLocalSession';
var form = $(formId);
if (!form) {
form = new Element('form', {
id: formId,
'class': 'hidden',
method: 'post',
action: "session-export-local.xqy"});
document.body.appendChild(form);
}
form.update();
// set up the UI placeholders
var ids = ['query', 'eval', 'buffer-list', 'textarea-status',
'history',
'buffer-tabs', 'buffer-tabs-0', 'buffer-tabs-1',
'buffer-tabs-accesskey-text',
'session-restore'];
ids.each(function(id) {
form.appendChild(new Element('div', {id: id})); });
// set up the UI objects
var bufferList = new QueryBufferListClass("query",
"eval",
"buffer-list",
"textarea-status");
var history = new QueryHistoryClass("history", bufferList);
var bufferTabs = new BufferTabsClass("buffer-tabs",
"buffer-accesskey-text",
bufferList,
history);
var session = new SessionClass(bufferTabs, "session-restore");
// fake the session
var sessionList = new SessionListLocal();
session.restoreFromObject(restore);
// build the XML
var xml = ("<session xmlns=\"com.marklogic.developer.cq.session\">\n"
+ bufferList.toXml()
+ history.toXml()
+ bufferTabs.toXml()
+ "</session>\n");
debug.print(label + xml);
// parameterize the form
var xmlInput = new Element('textarea', {
name: 'xml',
'xml:space': 'preserve'});
xmlInput.value = xml;
form.appendChild(xmlInput);
var idInput = new Element('input', {
name: 'id',
type: 'text',
value: id});
form.appendChild(idInput);
// submit the form
form.submit();
};
}
function sessionsOnLoad() {
var label = "sessionsOnLoad: ";
var sessionList = new SessionListLocal();
if (sessionList.length() < 0) {
return;
}
var out = $("sessions-local");
var table = new Element("table");
// IE insists on having a tbody or thead
var tbody = new Element('tbody');
table.appendChild(tbody);
if (sessionList.length() < 1) {
var row = new Element('tr');
row.appendChild(new Element('td', {
// IE is too dumb to parse class as a symbol
"class": "instruction"})
.update("No sessions found"));
tbody.appendChild(row);
} else {
for (var i=0; i<sessionList.length(); i++) {
var key = sessionList.keyAt(i);
debug.print(label + i + " " + key);
var session = $H(sessionList.get(key));
var sessionName = session.get('name');
debug.print(label + i + " " + key + " " + sessionName);
var row = document.createElement('tr');
row.appendChild(new Element('td').update(sessionName));
var cell = new Element('td');
var button;
// resume local session
button = new Element('input', {
type: 'button',
value: 'Resume' + (debug.isEnabled() ? (' ' + key) : ''),
title: 'resume this session'});
// extra function to create proper scope
button.observe('click', function(k) {
return function() {
sessionList.queue(k);
// setting the session id to "LOCAL" signals
// query.xqy and lib-controller.xqy
// to use the local information.
setCookie(gSessionIdCookie, "LOCAL");
sessionList.refresh();
};
}(key));
cell.appendChild(button);
// clone local session
button = new Element('input', {
type: 'button',
value: 'Clone' + (debug.isEnabled() ? (' ' + key) : ''),
title: 'clone this session'});
// extra function to create proper scope
button.observe('click', function(k) {
return function() {
sessionList.clone(k);
window.location.reload();
};
}(key));
cell.appendChild(button);
// export local session
button = new Element('input', {
type: 'button',
value: 'Export' + (debug.isEnabled() ? (' ' + key) : ''),
title: 'export this session'});
// extra function to create proper scope
button.observe('click', function(k) {
return function() {
sessionList.exportLocalSession(k); };
}(key));
cell.appendChild(button);
// delete local session
button = new Element('input', {
type: 'button',
value: 'Delete' + (debug.isEnabled() ? (' ' + key) : ''),
title: 'permanently delete this session'});
// extra function to create proper scope
button.observe('click', function(k) {
return function() {
if (!confirm("Are you sure you want to remove"
+ " this session?"
+ " This cannot be undone!")) {
return;
}
sessionList.remove(k);
window.location.reload();
};
}(key));
cell.appendChild(button);
row.appendChild(cell);
tbody.appendChild(row);
}
}
out.appendChild(table);
// button for new local session
button = new Element('input', {
type: 'button',
value: 'New Local Session'});
button.observe('click', function() {
// setting the session id to the string "LOCAL" signals
// query.xqy and lib-controller.xqy to use the local information.
setCookie(gSessionIdCookie, "LOCAL");
// signal that we want a new local session on refresh
sessionList.queue("NEW");
sessionList.refresh();
});
out.appendChild(button);
out.appendChild(new Element('p'));
out.appendChild(new Element('hr'));
// activate display
out.className = "";
Element.show(out);
}
function sessionImportLocal() {
var label = "sessionImportLocal: ";
debug.print(label + "begin");
// set up the UI objects
var bufferList = new QueryBufferListClass("query",
"eval",
"buffer-list",
"textarea-status");
var history = new QueryHistoryClass("history", bufferList);
var bufferTabs = new BufferTabsClass("buffer-tabs",
"buffer-accesskey-text",
bufferList,
history);
var session = new SessionClass(bufferTabs, "session-restore");
// restore from the server-supplied XML, ie from the import file
debug.print(label + "restoring");
session.restore();
// signal that we want a new local session
var sessionList = new SessionListLocal();
sessionList.queue("NEW");
session.useLocal(sessionList);
// redirect to session.xqy
window.location.assign("session.xqy");
}