2 ** $Id: pz2.js,v 1.64 2007-10-31 10:29:01 jakub Exp $
3 ** pz2.js - pazpar2's javascript client library.
6 //since explorer is flawed
8 window.Node = new Object();
10 Node.ATTRIBUTE_NODE = 2;
12 Node.CDATA_SECTION_NODE = 4;
13 Node.ENTITY_REFERENCE_NODE = 5;
15 Node.PROCESSING_INSTRUCTION_NODE = 7;
16 Node.COMMENT_NODE = 8;
17 Node.DOCUMENT_NODE = 9;
18 Node.DOCUMENT_TYPE_NODE = 10;
19 Node.DOCUMENT_FRAGMENT_NODE = 11;
20 Node.NOTATION_NODE = 12;
23 // prevent execution of more than once
24 if(typeof window.pz2 == "undefined") {
25 window.undefined = window.undefined;
27 var pz2 = function ( paramArray )
30 // at least one callback required
32 throw new Error("Pz2.js: Array with parameters has to be suplied.");
34 //supported pazpar2's protocol version
35 this.suppProtoVer = '1';
36 if (typeof paramArray.pazpar2path != "undefined")
37 this.pz2String = paramArray.pazpar2path;
39 this.pz2String = "/pazpar2/search.pz2";
40 this.useSessions = true;
42 this.stylesheet = paramArray.detailstylesheet || null;
43 //load stylesheet if required in async mode
44 if( this.stylesheet ) {
46 var request = new pzHttpRequest( this.stylesheet );
47 request.get( {}, function ( doc ) { context.xslDoc = doc; } );
50 this.errorHandler = paramArray.errorhandler || null;
53 this.initCallback = paramArray.oninit || null;
54 this.statCallback = paramArray.onstat || null;
55 this.showCallback = paramArray.onshow || null;
56 this.termlistCallback = paramArray.onterm || null;
57 this.recordCallback = paramArray.onrecord || null;
58 this.bytargetCallback = paramArray.onbytarget || null;
59 this.resetCallback = paramArray.onreset || null;
62 this.termKeys = paramArray.termlist || "subject";
64 // some configurational stuff
65 this.keepAlive = 50000;
67 if ( paramArray.keepAlive < this.keepAlive )
68 this.keepAlive = paramArray.keepAlive;
70 this.sessionID = null;
71 this.initStatusOK = false;
72 this.pingStatusOK = false;
73 this.searchStatusOK = false;
76 this.currentSort = "relevance";
79 this.currentStart = 0;
82 // last full record retrieved
83 this.currRecID = null;
86 this.currQuery = null;
89 this.statTime = paramArray.stattime || 1000;
90 this.statTimer = null;
91 this.termTime = paramArray.termtime || 1000;
92 this.termTimer = null;
93 this.showTime = paramArray.showtime || 1000;
94 this.showTimer = null;
95 this.showFastCount = 4;
96 this.bytargetTime = paramArray.bytargettime || 1000;
97 this.bytargetTimer = null;
99 // counters for each command and applied delay
100 this.dumpFactor = 500;
101 this.showCounter = 0;
102 this.termCounter = 0;
103 this.statCounter = 0;
104 this.bytargetCounter = 0;
106 // active clients, updated by stat and show
107 // might be an issue since bytarget will poll accordingly
108 this.activeClients = 1;
110 // if in proxy mode no need to init
111 if (paramArray.usesessions != undefined) {
112 this.useSessions = paramArray.usesessions;
113 this.initStatusOK = true;
115 // else, auto init session or wait for a user init?
116 if (this.useSessions && paramArray.autoInit !== false) {
123 //error handler for async error throws
124 throwError: function (errMsg, errCode)
126 var err = new Error(errMsg);
127 if (errCode) err.code = errCode;
129 if (this.errorHandler) {
130 this.errorHandler(err);
137 // stop activity by clearing tiemouts
140 clearTimeout(this.statTimer);
141 clearTimeout(this.showTimer);
142 clearTimeout(this.termTimer);
143 clearTimeout(this.bytargetTimer);
146 // reset status variables
149 if ( this.useSessions ) {
150 this.sessionID = null;
151 this.initStatusOK = false;
152 this.pingStatusOK = false;
154 this.searchStatusOK = false;
157 if ( this.resetCallback )
158 this.resetCallback();
161 init: function ( sessionId )
165 // session id as a param
166 if ( sessionId != undefined && this.useSessions ) {
167 this.initStatusOK = true;
168 this.sessionID = sessionId;
170 // old school direct pazpar2 init
171 } else if (this.useSessions) {
173 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
175 { "command": "init" },
177 if ( data.getElementsByTagName("status")[0]
178 .childNodes[0].nodeValue == "OK" ) {
179 if ( data.getElementsByTagName("protocol")[0]
180 .childNodes[0].nodeValue
181 != context.suppProtoVer )
183 "Server's protocol not supported by the client"
185 context.initStatusOK = true;
187 data.getElementsByTagName("session")[0]
188 .childNodes[0].nodeValue;
195 if ( context.initCallback )
196 context.initCallback();
199 context.throwError('Init failed. Malformed WS resonse.',
203 // when through proxy no need to init
205 this.initStatusOK = true;
208 // no need to ping explicitly
211 // pinging only makes sense when using pazpar2 directly
212 if( !this.initStatusOK || !this.useSessions )
214 'Pz2.js: Ping not allowed (proxy mode) or session not initialized.'
217 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
219 { "command": "ping", "session": this.sessionID },
221 if ( data.getElementsByTagName("status")[0]
222 .childNodes[0].nodeValue == "OK" ) {
223 context.pingStatusOK = true;
232 context.throwError('Ping failed. Malformed WS resonse.',
237 search: function (query, num, sort, filter, showfrom)
239 clearTimeout(this.statTimer);
240 clearTimeout(this.showTimer);
241 clearTimeout(this.termTimer);
242 clearTimeout(this.bytargetTimer);
244 this.showCounter = 0;
245 this.termCounter = 0;
246 this.bytargetCounter = 0;
247 this.statCounter = 0;
250 if( !this.initStatusOK )
251 throw new Error('Pz2.js: session not initialized.');
253 if( query !== undefined )
254 this.currQuery = query;
256 throw new Error("Pz2.js: no query supplied to the search command.");
258 if ( showfrom !== undefined )
259 var start = showfrom;
265 "query": this.currQuery,
266 "session": this.sessionID
269 if (filter !== undefined)
270 searchParams["filter"] = filter;
273 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
277 if ( data.getElementsByTagName("status")[0]
278 .childNodes[0].nodeValue == "OK" ) {
279 context.searchStatusOK = true;
281 context.show(start, num, sort);
282 if ( context.statCallback )
284 if ( context.termlistCallback )
286 if ( context.bytargetCallback )
290 context.throwError('Search failed. Malformed WS resonse.',
297 if( !this.initStatusOK )
298 throw new Error('Pz2.js: session not initialized.');
300 // if called explicitly takes precedence
301 clearTimeout(this.statTimer);
304 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
306 { "command": "stat", "session": this.sessionID },
308 if ( data.getElementsByTagName("stat") ) {
310 Number( data.getElementsByTagName("activeclients")[0]
311 .childNodes[0].nodeValue );
312 context.activeClients = activeClients;
314 "activeclients": activeClients,
316 Number( data.getElementsByTagName("hits")[0]
317 .childNodes[0].nodeValue ),
319 Number( data.getElementsByTagName("records")[0]
320 .childNodes[0].nodeValue ),
322 Number( data.getElementsByTagName("clients")[0]
323 .childNodes[0].nodeValue ),
325 Number( data.getElementsByTagName("initializing")[0]
326 .childNodes[0].nodeValue ),
328 Number( data.getElementsByTagName("searching")[0]
329 .childNodes[0].nodeValue ),
331 Number( data.getElementsByTagName("presenting")[0]
332 .childNodes[0].nodeValue ),
334 Number( data.getElementsByTagName("idle")[0]
335 .childNodes[0].nodeValue ),
337 Number( data.getElementsByTagName("failed")[0]
338 .childNodes[0].nodeValue ),
340 Number( data.getElementsByTagName("error")[0]
341 .childNodes[0].nodeValue )
344 context.statCounter++;
345 var delay = context.statTime
346 + context.statCounter * context.dumpFactor;
348 if ( activeClients > 0 )
356 context.statCallback(stat);
359 context.throwError('Stat failed. Malformed WS resonse.',
364 show: function(start, num, sort)
366 if( !this.searchStatusOK && this.useSessions )
368 'Pz2.js: show command has to be preceded with a search command.'
371 // if called explicitly takes precedence
372 clearTimeout(this.showTimer);
374 if( sort !== undefined )
375 this.currentSort = sort;
376 if( start !== undefined )
377 this.currentStart = Number( start );
378 if( num !== undefined )
379 this.currentNum = Number( num );
382 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
386 "session": this.sessionID,
387 "start": this.currentStart,
388 "num": this.currentNum,
389 "sort": this.currentSort,
393 if ( data.getElementsByTagName("status")[0]
394 .childNodes[0].nodeValue == "OK" ) {
395 // first parse the status data send along with records
396 // this is strictly bound to the format
398 Number( data.getElementsByTagName("activeclients")[0]
399 .childNodes[0].nodeValue );
400 context.activeClients = activeClients;
402 "activeclients": activeClients,
404 Number( data.getElementsByTagName("merged")[0]
405 .childNodes[0].nodeValue ),
407 Number( data.getElementsByTagName("total")[0]
408 .childNodes[0].nodeValue ),
410 Number( data.getElementsByTagName("start")[0]
411 .childNodes[0].nodeValue ),
413 Number( data.getElementsByTagName("num")[0]
414 .childNodes[0].nodeValue ),
417 // parse all the first-level nodes for all <hit> tags
418 var hits = data.getElementsByTagName("hit");
419 var hit = new Array();
420 for (i = 0; i < hits.length; i++) {
421 show.hits[i] = new Array();
422 show.hits[i]['location'] = new Array();
424 for ( j = 0; j < hits[i].childNodes.length; j++) {
425 if ( hits[i].childNodes[j].nodeType
426 == Node.ELEMENT_NODE ) {
427 if (hits[i].childNodes[j].nodeName
429 var locNode = hits[i].childNodes[j];
430 var id = locNode.getAttribute('id');
431 show.hits[i]['location'][locCount] = {
432 "id": locNode.getAttribute("id"),
433 "name": locNode.getAttribute("name")
439 hits[i].childNodes[j].nodeName;
440 var nodeText = 'ERROR'
441 if ( hits[i].childNodes[j].firstChild )
443 hits[i].childNodes[j]
444 .firstChild.nodeValue;
445 show.hits[i][nodeName] = nodeText;
450 context.showCounter++;
451 var delay = context.showTime;
452 if (context.showCounter > context.showFastCount)
453 delay += context.showCounter * context.dumpFactor;
454 if ( activeClients > 0 )
455 context.showTimer = setTimeout(
461 context.showCallback(show);
464 context.throwError('Show failed. Malformed WS resonse.',
469 record: function(id, offset, params)
471 // we may call record with no previous search if in proxy mode
472 if( !this.searchStatusOK && this.useSessions)
474 'Pz2.js: record command has to be preceded with a search command.'
476 if ( params == undefined )
479 if ( params.callback != undefined ) {
480 callback = params.callback;
482 callback = this.recordCallback;
486 if ( params['handle'] == undefined )
489 handle = params['handle'];
491 if( id !== undefined )
495 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
497 var recordParams = { "command": "record",
498 "session": this.sessionID,
499 "id": this.currRecID };
501 if (offset !== undefined) {
502 recordParams["offset"] = offset;
505 if (params.syntax != undefined) {
506 recordParams['syntax'] = params.syntax;
509 this.currRecOffset = offset;
515 var record = new Array();
516 record['xmlDoc'] = data;
517 if (context.currRecOffset !== undefined) {
518 record['offset'] = context.currRecOffset;
519 callback(record, handle);
520 } else if ( recordNode =
521 data.getElementsByTagName("record")[0] ) {
522 // if stylesheet was fetched do not parse the response
523 if ( context.xslDoc ) {
525 recordNode.getElementsByTagName("recid")[0]
526 .firstChild.nodeValue;
530 for ( i = 0; i < recordNode.childNodes.length; i++) {
531 if ( recordNode.childNodes[i].nodeType
533 && recordNode.childNodes[i].nodeName
536 recordNode.childNodes[i].nodeName;
538 recordNode.childNodes[i]
539 .firstChild.nodeValue;
540 record[nodeName] = nodeText;
543 // the location might be empty!!
545 recordNode.getElementsByTagName("location");
546 record["location"] = new Array();
547 for ( i = 0; i < locationNodes.length; i++ ) {
548 record["location"][i] = {
549 "id": locationNodes[i].getAttribute("id"),
550 "name": locationNodes[i].getAttribute("name")
554 j < locationNodes[i].childNodes.length;
556 if ( locationNodes[i].childNodes[j].nodeType
557 == Node.ELEMENT_NODE ) {
559 locationNodes[i].childNodes[j].nodeName;
561 if (locationNodes[i].childNodes[j]
564 locationNodes[i].childNodes[j]
565 .firstChild.nodeValue;
566 record["location"][i][nodeName] = nodeText;
572 callback(record, handle);
575 context.throwError('Record failed. Malformed WS resonse.',
583 if( !this.searchStatusOK && this.useSessions )
585 'Pz2.js: termlist command has to be preceded with a search command.'
588 // if called explicitly takes precedence
589 clearTimeout(this.termTimer);
592 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
595 "command": "termlist",
596 "session": this.sessionID,
597 "name": this.termKeys
600 if ( data.getElementsByTagName("termlist") ) {
602 Number( data.getElementsByTagName("activeclients")[0]
603 .childNodes[0].nodeValue );
604 context.activeClients = activeClients;
605 var termList = { "activeclients": activeClients };
606 var termLists = data.getElementsByTagName("list");
608 for (i = 0; i < termLists.length; i++) {
609 var listName = termLists[i].getAttribute('name');
610 termList[listName] = new Array();
611 var terms = termLists[i].getElementsByTagName('term');
612 //for each term in the list
613 for (j = 0; j < terms.length; j++) {
616 (terms[j].getElementsByTagName("name")[0]
618 ? terms[j].getElementsByTagName("name")[0]
619 .childNodes[0].nodeValue
623 .getElementsByTagName("frequency")[0]
624 .childNodes[0].nodeValue || 'ERROR'
628 terms[j].getElementsByTagName("id");
629 if(terms[j].getElementsByTagName("id").length)
631 termIdNode[0].childNodes[0].nodeValue;
632 termList[listName][j] = term;
636 context.termCounter++;
637 var delay = context.termTime
638 + context.termCounter * context.dumpFactor;
639 if ( activeClients > 0 )
648 context.termlistCallback(termList);
651 context.throwError('Termlist failed. Malformed WS resonse.',
659 if( !this.initStatusOK && this.useSessions )
661 'Pz2.js: bytarget command has to be preceded with a search command.'
664 // no need to continue
665 if( !this.searchStatusOK )
668 // if called explicitly takes precedence
669 clearTimeout(this.bytargetTimer);
672 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
674 { "command": "bytarget", "session": this.sessionID },
676 if ( data.getElementsByTagName("status")[0]
677 .childNodes[0].nodeValue == "OK" ) {
678 var targetNodes = data.getElementsByTagName("target");
679 var bytarget = new Array();
680 for ( i = 0; i < targetNodes.length; i++) {
681 bytarget[i] = new Array();
682 for( j = 0; j < targetNodes[i].childNodes.length; j++ ) {
683 if ( targetNodes[i].childNodes[j].nodeType
684 == Node.ELEMENT_NODE ) {
686 targetNodes[i].childNodes[j].nodeName;
688 targetNodes[i].childNodes[j]
689 .firstChild.nodeValue;
690 bytarget[i][nodeName] = nodeText;
695 context.bytargetCounter++;
696 var delay = context.bytargetTime
697 + context.bytargetCounter * context.dumpFactor;
698 if ( context.activeClients > 0 )
699 context.bytargetTimer =
707 context.bytargetCallback(bytarget);
710 context.throwError('Bytarget failed. Malformed WS resonse.',
716 // just for testing, probably shouldn't be here
717 showNext: function(page)
719 var step = page || 1;
720 this.show( ( step * this.currentNum ) + this.currentStart );
723 showPrev: function(page)
725 if (this.currentStart == 0 )
727 var step = page || 1;
728 var newStart = this.currentStart - (step * this.currentNum );
729 this.show( newStart > 0 ? newStart : 0 );
732 showPage: function(pageNum)
734 //var page = pageNum || 1;
735 this.show(pageNum * this.currentNum);
740 ********************************************************************************
741 ** AJAX HELPER CLASS ***********************************************************
742 ********************************************************************************
744 var pzHttpRequest = function ( url, errorHandler ) {
747 this.errorHandler = errorHandler || null;
750 if ( window.XMLHttpRequest ) {
751 this.request = new XMLHttpRequest();
752 } else if ( window.ActiveXObject ) {
754 this.request = new ActiveXObject( 'Msxml2.XMLHTTP' );
756 this.request = new ActiveXObject( 'Microsoft.XMLHTTP' );
761 pzHttpRequest.prototype =
763 get: function ( params, callback )
765 this._send( 'GET', params, '', callback );
768 post: function ( params, data, callback )
770 this._send( 'POST', params, data, callback );
776 this.request.open( 'GET', this.url, this.async );
777 this.request.send('');
778 if ( this.request.status == 200 )
779 return this.request.responseXML;
782 _send: function ( type, params, data, callback )
784 this.callback = callback;
787 this.request.open( type, this._urlAppendParams(params), this.async );
788 this.request.onreadystatechange = function () {
789 context._handleResponse();
791 this.request.send(data);
794 _urlAppendParams: function (params)
796 var getUrl = this.url;
800 for (var key in el) {
801 if (el[key] != null) {
802 getUrl += sep + key + '=' + encodeURIComponent(el[key]);
809 _handleResponse: function ()
811 if ( this.request.readyState == 4 ) {
812 // pick up pazpr2 errors first
813 if ( this.request.responseXML
814 && this.request.responseXML.documentElement.nodeName == 'error'
815 && this.request.responseXML.getElementsByTagName("error")
818 if ( this.request.responseXML.getElementsByTagName("error")[0]
821 this.request.responseXML
822 .getElementsByTagName("error")[0]
823 .childNodes[0].nodeValue;
825 this.request.responseXML.getElementsByTagName("error")[0]
826 .getAttribute("msg");
828 this.request.responseXML.getElementsByTagName("error")[0]
829 .getAttribute("code");
831 var err = new Error(errMsg + errAddInfo);
834 if (this.errorHandler) {
835 this.errorHandler(err);
840 } else if ( this.request.status == 200 ) {
841 this.callback( this.request.responseXML );
843 var err = new Error("Pz2.js: HTTP request error (AJAX). Code: "
844 + this.request.status + " Info: "
845 + this.request.statusText );
848 if (this.errorHandler) {
849 this.errorHandler(err);
860 ********************************************************************************
861 ** XML HELPER FUNCTIONS ********************************************************
862 ********************************************************************************
867 if ( window.ActiveXObject) {
868 var DOMDoc = document;
870 var DOMDoc = Document.prototype;
873 DOMDoc.newXmlDoc = function ( root )
877 if (document.implementation && document.implementation.createDocument) {
878 doc = document.implementation.createDocument('', root, null);
879 } else if ( window.ActiveXObject ) {
880 doc = new ActiveXObject("MSXML2.DOMDocument");
881 doc.loadXML('<' + root + '/>');
883 throw new Error ('No XML support in this browser');
890 DOMDoc.parseXmlFromString = function ( xmlString )
894 if ( window.DOMParser ) {
895 var parser = new DOMParser();
896 doc = parser.parseFromString( xmlString, "text/xml");
897 } else if ( window.ActiveXObject ) {
898 doc = new ActiveXObject("MSXML2.DOMDocument");
899 doc.loadXML( xmlString );
901 throw new Error ("No XML parsing support in this browser.");
907 DOMDoc.transformToDoc = function (xmlDoc, xslDoc)
909 if ( window.XSLTProcessor ) {
910 var proc = new XSLTProcessor();
911 proc.importStylesheet( xslDoc );
912 return proc.transformToDocument(xmlDoc);
913 } else if ( window.ActiveXObject ) {
914 return document.parseXmlFromString(xmlDoc.transformNode(xslDoc));
916 alert( 'Unable to perform XSLT transformation in this browser' );
922 Element_removeFromDoc = function (DOM_Element)
924 DOM_Element.parentNode.removeChild(DOM_Element);
927 Element_emptyChildren = function (DOM_Element)
929 while( DOM_Element.firstChild ) {
930 DOM_Element.removeChild( DOM_Element.firstChild )
934 Element_appendTransformResult = function ( DOM_Element, xmlDoc, xslDoc )
936 if ( window.XSLTProcessor ) {
937 var proc = new XSLTProcessor();
938 proc.importStylesheet( xslDoc );
940 docFrag = proc.transformToFragment( xmlDoc, DOM_Element.ownerDocument );
941 DOM_Element.appendChild(docFrag);
942 } else if ( window.ActiveXObject ) {
943 DOM_Element.innerHTML = xmlDoc.transformNode( xslDoc );
945 alert( 'Unable to perform XSLT transformation in this browser' );
949 Element_appendTextNode = function (DOM_Element, tagName, textContent )
951 var node = DOM_Element.ownerDocument.createElement(tagName);
952 var text = DOM_Element.ownerDocument.createTextNode(textContent);
954 DOM_Element.appendChild(node);
955 node.appendChild(text);
960 Element_setTextContent = function ( DOM_Element, textContent )
962 if (typeof DOM_Element.textContent !== "undefined") {
963 DOM_Element.textContent = textContent;
964 } else if (typeof DOM_Element.innerText !== "undefined" ) {
965 DOM_Element.innerText = textContent;
967 throw new Error("Cannot set text content of the node, no such method.");
971 Element_getTextContent = function (DOM_Element)
973 if ( typeof DOM_Element.textContent != 'undefined' ) {
974 return DOM_Element.textContent;
975 } else if (typeof DOM_Element.text != 'undefined') {
976 return DOM_Element.text;
978 throw new Error("Cannot get text content of the node, no such method.");
982 /* do not remove trailing bracket */