2 ** $Id: pz2.js,v 1.70 2008-03-12 11:36:57 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;
88 //current raw record offset
89 this.currRecOffset = null;
92 this.statTime = paramArray.stattime || 1000;
93 this.statTimer = null;
94 this.termTime = paramArray.termtime || 1000;
95 this.termTimer = null;
96 this.showTime = paramArray.showtime || 1000;
97 this.showTimer = null;
98 this.showFastCount = 4;
99 this.bytargetTime = paramArray.bytargettime || 1000;
100 this.bytargetTimer = null;
102 // counters for each command and applied delay
103 this.dumpFactor = 500;
104 this.showCounter = 0;
105 this.termCounter = 0;
106 this.statCounter = 0;
107 this.bytargetCounter = 0;
109 // active clients, updated by stat and show
110 // might be an issue since bytarget will poll accordingly
111 this.activeClients = 1;
113 // if in proxy mode no need to init
114 if (paramArray.usesessions != undefined) {
115 this.useSessions = paramArray.usesessions;
116 this.initStatusOK = true;
118 // else, auto init session or wait for a user init?
119 if (this.useSessions && paramArray.autoInit !== false) {
126 //error handler for async error throws
127 throwError: function (errMsg, errCode)
129 var err = new Error(errMsg);
130 if (errCode) err.code = errCode;
132 if (this.errorHandler) {
133 this.errorHandler(err);
140 // stop activity by clearing tiemouts
143 clearTimeout(this.statTimer);
144 clearTimeout(this.showTimer);
145 clearTimeout(this.termTimer);
146 clearTimeout(this.bytargetTimer);
149 // reset status variables
152 if ( this.useSessions ) {
153 this.sessionID = null;
154 this.initStatusOK = false;
155 this.pingStatusOK = false;
157 this.searchStatusOK = false;
160 if ( this.resetCallback )
161 this.resetCallback();
164 init: function ( sessionId )
168 // session id as a param
169 if ( sessionId != undefined && this.useSessions ) {
170 this.initStatusOK = true;
171 this.sessionID = sessionId;
173 // old school direct pazpar2 init
174 } else if (this.useSessions) {
176 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
178 { "command": "init" },
180 if ( data.getElementsByTagName("status")[0]
181 .childNodes[0].nodeValue == "OK" ) {
182 if ( data.getElementsByTagName("protocol")[0]
183 .childNodes[0].nodeValue
184 != context.suppProtoVer )
186 "Server's protocol not supported by the client"
188 context.initStatusOK = true;
190 data.getElementsByTagName("session")[0]
191 .childNodes[0].nodeValue;
198 if ( context.initCallback )
199 context.initCallback();
202 context.throwError('Init failed. Malformed WS resonse.',
206 // when through proxy no need to init
208 this.initStatusOK = true;
211 // no need to ping explicitly
214 // pinging only makes sense when using pazpar2 directly
215 if( !this.initStatusOK || !this.useSessions )
217 'Pz2.js: Ping not allowed (proxy mode) or session not initialized.'
220 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
222 { "command": "ping", "session": this.sessionID },
224 if ( data.getElementsByTagName("status")[0]
225 .childNodes[0].nodeValue == "OK" ) {
226 context.pingStatusOK = true;
235 context.throwError('Ping failed. Malformed WS resonse.',
240 search: function (query, num, sort, filter, showfrom)
242 clearTimeout(this.statTimer);
243 clearTimeout(this.showTimer);
244 clearTimeout(this.termTimer);
245 clearTimeout(this.bytargetTimer);
247 this.showCounter = 0;
248 this.termCounter = 0;
249 this.bytargetCounter = 0;
250 this.statCounter = 0;
253 if( !this.initStatusOK )
254 throw new Error('Pz2.js: session not initialized.');
256 if( query !== undefined )
257 this.currQuery = query;
259 throw new Error("Pz2.js: no query supplied to the search command.");
261 if ( showfrom !== undefined )
262 var start = showfrom;
268 "query": this.currQuery,
269 "session": this.sessionID
272 if (filter !== undefined)
273 searchParams["filter"] = filter;
276 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
280 if ( data.getElementsByTagName("status")[0]
281 .childNodes[0].nodeValue == "OK" ) {
282 context.searchStatusOK = true;
284 context.show(start, num, sort);
285 if ( context.statCallback )
287 if ( context.termlistCallback )
289 if ( context.bytargetCallback )
293 context.throwError('Search failed. Malformed WS resonse.',
300 if( !this.initStatusOK )
301 throw new Error('Pz2.js: session not initialized.');
303 // if called explicitly takes precedence
304 clearTimeout(this.statTimer);
307 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
309 { "command": "stat", "session": this.sessionID },
311 if ( data.getElementsByTagName("stat") ) {
313 Number( data.getElementsByTagName("activeclients")[0]
314 .childNodes[0].nodeValue );
315 context.activeClients = activeClients;
317 "activeclients": activeClients,
319 Number( data.getElementsByTagName("hits")[0]
320 .childNodes[0].nodeValue ),
322 Number( data.getElementsByTagName("records")[0]
323 .childNodes[0].nodeValue ),
325 Number( data.getElementsByTagName("clients")[0]
326 .childNodes[0].nodeValue ),
328 Number( data.getElementsByTagName("initializing")[0]
329 .childNodes[0].nodeValue ),
331 Number( data.getElementsByTagName("searching")[0]
332 .childNodes[0].nodeValue ),
334 Number( data.getElementsByTagName("presenting")[0]
335 .childNodes[0].nodeValue ),
337 Number( data.getElementsByTagName("idle")[0]
338 .childNodes[0].nodeValue ),
340 Number( data.getElementsByTagName("failed")[0]
341 .childNodes[0].nodeValue ),
343 Number( data.getElementsByTagName("error")[0]
344 .childNodes[0].nodeValue )
347 context.statCounter++;
348 var delay = context.statTime
349 + context.statCounter * context.dumpFactor;
351 if ( activeClients > 0 )
359 context.statCallback(stat);
362 context.throwError('Stat failed. Malformed WS resonse.',
367 show: function(start, num, sort)
369 if( !this.searchStatusOK && this.useSessions )
371 'Pz2.js: show command has to be preceded with a search command.'
374 // if called explicitly takes precedence
375 clearTimeout(this.showTimer);
377 if( sort !== undefined )
378 this.currentSort = sort;
379 if( start !== undefined )
380 this.currentStart = Number( start );
381 if( num !== undefined )
382 this.currentNum = Number( num );
385 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
389 "session": this.sessionID,
390 "start": this.currentStart,
391 "num": this.currentNum,
392 "sort": this.currentSort,
396 if ( data.getElementsByTagName("status")[0]
397 .childNodes[0].nodeValue == "OK" ) {
398 // first parse the status data send along with records
399 // this is strictly bound to the format
401 Number( data.getElementsByTagName("activeclients")[0]
402 .childNodes[0].nodeValue );
403 context.activeClients = activeClients;
405 "activeclients": activeClients,
407 Number( data.getElementsByTagName("merged")[0]
408 .childNodes[0].nodeValue ),
410 Number( data.getElementsByTagName("total")[0]
411 .childNodes[0].nodeValue ),
413 Number( data.getElementsByTagName("start")[0]
414 .childNodes[0].nodeValue ),
416 Number( data.getElementsByTagName("num")[0]
417 .childNodes[0].nodeValue ),
420 // parse all the first-level nodes for all <hit> tags
421 var hits = data.getElementsByTagName("hit");
422 for (i = 0; i < hits.length; i++)
423 show.hits[i] = Element_parseChildNodes(hits[i]);
425 context.showCounter++;
426 var delay = context.showTime;
427 if (context.showCounter > context.showFastCount)
428 delay += context.showCounter * context.dumpFactor;
429 if ( activeClients > 0 )
430 context.showTimer = setTimeout(
436 context.showCallback(show);
439 context.throwError('Show failed. Malformed WS resonse.',
444 record: function(id, offset, syntax, handler)
446 // we may call record with no previous search if in proxy mode
447 if(!this.searchStatusOK && this.useSessions)
449 'Pz2.js: record command has to be preceded with a search command.'
452 if( id !== undefined )
457 "session": this.sessionID,
461 this.currRecOffset = null;
462 if (offset != undefined) {
463 recordParams["offset"] = offset;
464 this.currRecOffset = offset;
467 if (syntax != undefined)
468 recordParams['syntax'] = syntax;
470 //overwrite default callback id needed
471 var callback = this.recordCallback;
472 var args = undefined;
473 if (handler != undefined) {
474 callback = handler['callback'];
475 args = handler['args'];
479 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
487 if (context.currRecOffset !== null) {
488 record = new Array();
489 record['xmlDoc'] = data;
490 record['offset'] = context.currRecOffset;
491 callback(record, args);
493 } else if ( recordNode =
494 data.getElementsByTagName("record")[0] ) {
495 // if stylesheet was fetched do not parse the response
496 if ( context.xslDoc ) {
497 record = new Array();
498 record['xmlDoc'] = data;
499 record['xslDoc'] = context.xslDoc;
501 recordNode.getElementsByTagName("recid")[0]
502 .firstChild.nodeValue;
505 record = Element_parseChildNodes(recordNode);
507 callback(record, args);
510 context.throwError('Record failed. Malformed WS resonse.',
518 if( !this.searchStatusOK && this.useSessions )
520 'Pz2.js: termlist command has to be preceded with a search command.'
523 // if called explicitly takes precedence
524 clearTimeout(this.termTimer);
527 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
530 "command": "termlist",
531 "session": this.sessionID,
532 "name": this.termKeys
535 if ( data.getElementsByTagName("termlist") ) {
537 Number( data.getElementsByTagName("activeclients")[0]
538 .childNodes[0].nodeValue );
539 context.activeClients = activeClients;
540 var termList = { "activeclients": activeClients };
541 var termLists = data.getElementsByTagName("list");
543 for (i = 0; i < termLists.length; i++) {
544 var listName = termLists[i].getAttribute('name');
545 termList[listName] = new Array();
546 var terms = termLists[i].getElementsByTagName('term');
547 //for each term in the list
548 for (j = 0; j < terms.length; j++) {
551 (terms[j].getElementsByTagName("name")[0]
553 ? terms[j].getElementsByTagName("name")[0]
554 .childNodes[0].nodeValue
558 .getElementsByTagName("frequency")[0]
559 .childNodes[0].nodeValue || 'ERROR'
563 terms[j].getElementsByTagName("id");
564 if(terms[j].getElementsByTagName("id").length)
566 termIdNode[0].childNodes[0].nodeValue;
567 termList[listName][j] = term;
571 context.termCounter++;
572 var delay = context.termTime
573 + context.termCounter * context.dumpFactor;
574 if ( activeClients > 0 )
583 context.termlistCallback(termList);
586 context.throwError('Termlist failed. Malformed WS resonse.',
594 if( !this.initStatusOK && this.useSessions )
596 'Pz2.js: bytarget command has to be preceded with a search command.'
599 // no need to continue
600 if( !this.searchStatusOK )
603 // if called explicitly takes precedence
604 clearTimeout(this.bytargetTimer);
607 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
609 { "command": "bytarget", "session": this.sessionID },
611 if ( data.getElementsByTagName("status")[0]
612 .childNodes[0].nodeValue == "OK" ) {
613 var targetNodes = data.getElementsByTagName("target");
614 var bytarget = new Array();
615 for ( i = 0; i < targetNodes.length; i++) {
616 bytarget[i] = new Array();
617 for( j = 0; j < targetNodes[i].childNodes.length; j++ ) {
618 if ( targetNodes[i].childNodes[j].nodeType
619 == Node.ELEMENT_NODE ) {
621 targetNodes[i].childNodes[j].nodeName;
623 targetNodes[i].childNodes[j]
624 .firstChild.nodeValue;
625 bytarget[i][nodeName] = nodeText;
630 context.bytargetCounter++;
631 var delay = context.bytargetTime
632 + context.bytargetCounter * context.dumpFactor;
633 if ( context.activeClients > 0 )
634 context.bytargetTimer =
642 context.bytargetCallback(bytarget);
645 context.throwError('Bytarget failed. Malformed WS resonse.',
651 // just for testing, probably shouldn't be here
652 showNext: function(page)
654 var step = page || 1;
655 this.show( ( step * this.currentNum ) + this.currentStart );
658 showPrev: function(page)
660 if (this.currentStart == 0 )
662 var step = page || 1;
663 var newStart = this.currentStart - (step * this.currentNum );
664 this.show( newStart > 0 ? newStart : 0 );
667 showPage: function(pageNum)
669 //var page = pageNum || 1;
670 this.show(pageNum * this.currentNum);
675 ********************************************************************************
676 ** AJAX HELPER CLASS ***********************************************************
677 ********************************************************************************
679 var pzHttpRequest = function ( url, errorHandler ) {
680 this.maxUrlLength = 2048;
683 this.errorHandler = errorHandler || null;
685 this.requestHeaders = {};
687 if ( window.XMLHttpRequest ) {
688 this.request = new XMLHttpRequest();
689 } else if ( window.ActiveXObject ) {
691 this.request = new ActiveXObject( 'Msxml2.XMLHTTP' );
693 this.request = new ActiveXObject( 'Microsoft.XMLHTTP' );
698 pzHttpRequest.prototype =
700 safeGet: function ( params, callback )
702 var encodedParams = this.encodeParams(params);
703 var url = this._urlAppendParams(encodedParams);
704 if (url.length >= this.maxUrlLength) {
705 this.requestHeaders["Content-Type"]
706 = "application/x-www-form-urlencoded";
707 this._send( 'POST', this.url, encodedParams, callback );
709 this._send( 'GET', url, '', callback );
713 get: function ( params, callback )
715 this._send( 'GET', this._urlAppendParams(this.encodeParams(params)),
719 post: function ( params, data, callback )
721 this._send( 'POST', this._urlAppendParams(this.encodeParams(params)),
728 this.request.open( 'GET', this.url, this.async );
729 this.request.send('');
730 if ( this.request.status == 200 )
731 return this.request.responseXML;
734 encodeParams: function (params)
738 for (var key in params) {
739 if (params[key] != null) {
740 encoded += sep + key + '=' + encodeURIComponent(params[key]);
747 _send: function ( type, url, data, callback)
750 this.callback = callback;
752 this.request.open( type, url, this.async );
753 for (var key in this.requestHeaders)
754 this.request.setRequestHeader(key, this.requestHeaders[key]);
755 this.request.onreadystatechange = function () {
756 context._handleResponse();
758 this.request.send(data);
761 _urlAppendParams: function (encodedParams)
764 return this.url + "?" + encodedParams;
769 _handleResponse: function ()
771 if ( this.request.readyState == 4 ) {
772 // pick up pazpr2 errors first
773 if ( this.request.responseXML
774 && this.request.responseXML.documentElement.nodeName == 'error'
775 && this.request.responseXML.getElementsByTagName("error")
778 if ( this.request.responseXML.getElementsByTagName("error")[0]
781 this.request.responseXML
782 .getElementsByTagName("error")[0]
783 .childNodes[0].nodeValue;
785 this.request.responseXML.getElementsByTagName("error")[0]
786 .getAttribute("msg");
788 this.request.responseXML.getElementsByTagName("error")[0]
789 .getAttribute("code");
791 var err = new Error(errMsg + errAddInfo);
794 if (this.errorHandler) {
795 this.errorHandler(err);
800 } else if ( this.request.status == 200 ) {
801 this.callback( this.request.responseXML );
803 var err = new Error("Pz2.js: HTTP request error (AJAX). Code: "
804 + this.request.status + " Info: "
805 + this.request.statusText );
808 if (this.errorHandler) {
809 this.errorHandler(err);
820 ********************************************************************************
821 ** XML HELPER FUNCTIONS ********************************************************
822 ********************************************************************************
827 if ( window.ActiveXObject) {
828 var DOMDoc = document;
830 var DOMDoc = Document.prototype;
833 DOMDoc.newXmlDoc = function ( root )
837 if (document.implementation && document.implementation.createDocument) {
838 doc = document.implementation.createDocument('', root, null);
839 } else if ( window.ActiveXObject ) {
840 doc = new ActiveXObject("MSXML2.DOMDocument");
841 doc.loadXML('<' + root + '/>');
843 throw new Error ('No XML support in this browser');
850 DOMDoc.parseXmlFromString = function ( xmlString )
854 if ( window.DOMParser ) {
855 var parser = new DOMParser();
856 doc = parser.parseFromString( xmlString, "text/xml");
857 } else if ( window.ActiveXObject ) {
858 doc = new ActiveXObject("MSXML2.DOMDocument");
859 doc.loadXML( xmlString );
861 throw new Error ("No XML parsing support in this browser.");
867 DOMDoc.transformToDoc = function (xmlDoc, xslDoc)
869 if ( window.XSLTProcessor ) {
870 var proc = new XSLTProcessor();
871 proc.importStylesheet( xslDoc );
872 return proc.transformToDocument(xmlDoc);
873 } else if ( window.ActiveXObject ) {
874 return document.parseXmlFromString(xmlDoc.transformNode(xslDoc));
876 alert( 'Unable to perform XSLT transformation in this browser' );
882 Element_removeFromDoc = function (DOM_Element)
884 DOM_Element.parentNode.removeChild(DOM_Element);
887 Element_emptyChildren = function (DOM_Element)
889 while( DOM_Element.firstChild ) {
890 DOM_Element.removeChild( DOM_Element.firstChild )
894 Element_appendTransformResult = function ( DOM_Element, xmlDoc, xslDoc )
896 if ( window.XSLTProcessor ) {
897 var proc = new XSLTProcessor();
898 proc.importStylesheet( xslDoc );
900 docFrag = proc.transformToFragment( xmlDoc, DOM_Element.ownerDocument );
901 DOM_Element.appendChild(docFrag);
902 } else if ( window.ActiveXObject ) {
903 DOM_Element.innerHTML = xmlDoc.transformNode( xslDoc );
905 alert( 'Unable to perform XSLT transformation in this browser' );
909 Element_appendTextNode = function (DOM_Element, tagName, textContent )
911 var node = DOM_Element.ownerDocument.createElement(tagName);
912 var text = DOM_Element.ownerDocument.createTextNode(textContent);
914 DOM_Element.appendChild(node);
915 node.appendChild(text);
920 Element_setTextContent = function ( DOM_Element, textContent )
922 if (typeof DOM_Element.textContent !== "undefined") {
923 DOM_Element.textContent = textContent;
924 } else if (typeof DOM_Element.innerText !== "undefined" ) {
925 DOM_Element.innerText = textContent;
927 throw new Error("Cannot set text content of the node, no such method.");
931 Element_getTextContent = function (DOM_Element)
933 if ( typeof DOM_Element.textContent != 'undefined' ) {
934 return DOM_Element.textContent;
935 } else if (typeof DOM_Element.text != 'undefined') {
936 return DOM_Element.text;
938 throw new Error("Cannot get text content of the node, no such method.");
942 Element_parseChildNodes = function (node)
945 var hasChildElems = false;
947 if (node.hasChildNodes()) {
948 var children = node.childNodes;
949 for (var i = 0; i < children.length; i++) {
950 var child = children[i];
951 if (child.nodeType == Node.ELEMENT_NODE) {
952 hasChildElems = true;
953 var nodeName = child.nodeName;
954 if (!(nodeName in parsed))
955 parsed[nodeName] = [];
956 parsed[nodeName].push(Element_parseChildNodes(child));
961 var attrs = node.attributes;
962 for (var i = 0; i < attrs.length; i++) {
963 var attrName = '@' + attrs[i].nodeName;
964 var attrValue = attrs[i].nodeValue;
965 parsed[attrName] = attrValue;
968 // if no nested elements, get text content
969 if (node.hasChildNodes() && !hasChildElems) {
970 if (node.attributes.length)
971 parsed['textContent'] = node.firstChild.nodeValue;
973 parsed = node.firstChild.nodeValue;
979 /* do not remove trailing bracket */