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;
101 this.recordTime = paramArray.recordtime || 500;
102 this.recordTimer = null;
104 // counters for each command and applied delay
105 this.dumpFactor = 500;
106 this.showCounter = 0;
107 this.termCounter = 0;
108 this.statCounter = 0;
109 this.bytargetCounter = 0;
110 this.recordCounter = 0;
112 // active clients, updated by stat and show
113 // might be an issue since bytarget will poll accordingly
114 this.activeClients = 1;
116 // if in proxy mode no need to init
117 if (paramArray.usesessions != undefined) {
118 this.useSessions = paramArray.usesessions;
119 this.initStatusOK = true;
121 // else, auto init session or wait for a user init?
122 if (this.useSessions && paramArray.autoInit !== false) {
129 //error handler for async error throws
130 throwError: function (errMsg, errCode)
132 var err = new Error(errMsg);
133 if (errCode) err.code = errCode;
135 if (this.errorHandler) {
136 this.errorHandler(err);
143 // stop activity by clearing tiemouts
146 clearTimeout(this.statTimer);
147 clearTimeout(this.showTimer);
148 clearTimeout(this.termTimer);
149 clearTimeout(this.bytargetTimer);
152 // reset status variables
155 if ( this.useSessions ) {
156 this.sessionID = null;
157 this.initStatusOK = false;
158 this.pingStatusOK = false;
160 this.searchStatusOK = false;
163 if ( this.resetCallback )
164 this.resetCallback();
167 init: function ( sessionId )
171 // session id as a param
172 if ( sessionId != undefined && this.useSessions ) {
173 this.initStatusOK = true;
174 this.sessionID = sessionId;
176 // old school direct pazpar2 init
177 } else if (this.useSessions) {
179 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
181 { "command": "init" },
183 if ( data.getElementsByTagName("status")[0]
184 .childNodes[0].nodeValue == "OK" ) {
185 if ( data.getElementsByTagName("protocol")[0]
186 .childNodes[0].nodeValue
187 != context.suppProtoVer )
189 "Server's protocol not supported by the client"
191 context.initStatusOK = true;
193 data.getElementsByTagName("session")[0]
194 .childNodes[0].nodeValue;
201 if ( context.initCallback )
202 context.initCallback();
205 context.throwError('Init failed. Malformed WS resonse.',
209 // when through proxy no need to init
211 this.initStatusOK = true;
214 // no need to ping explicitly
217 // pinging only makes sense when using pazpar2 directly
218 if( !this.initStatusOK || !this.useSessions )
220 'Pz2.js: Ping not allowed (proxy mode) or session not initialized.'
223 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
225 { "command": "ping", "session": this.sessionID },
227 if ( data.getElementsByTagName("status")[0]
228 .childNodes[0].nodeValue == "OK" ) {
229 context.pingStatusOK = true;
238 context.throwError('Ping failed. Malformed WS resonse.',
243 search: function (query, num, sort, filter, showfrom, addParamsArr)
245 clearTimeout(this.statTimer);
246 clearTimeout(this.showTimer);
247 clearTimeout(this.termTimer);
248 clearTimeout(this.bytargetTimer);
250 this.showCounter = 0;
251 this.termCounter = 0;
252 this.bytargetCounter = 0;
253 this.statCounter = 0;
254 this.activeClients = 1;
257 if( !this.initStatusOK )
258 throw new Error('Pz2.js: session not initialized.');
260 if( query !== undefined )
261 this.currQuery = query;
263 throw new Error("Pz2.js: no query supplied to the search command.");
265 if ( showfrom !== undefined )
266 var start = showfrom;
272 "query": this.currQuery,
273 "session": this.sessionID
276 if (filter !== undefined)
277 searchParams["filter"] = filter;
279 // copy additional parmeters, do not overwrite
280 if (addParamsArr != undefined) {
281 for (var prop in addParamsArr) {
282 if (!searchParams.hasOwnProperty(prop))
283 searchParams[prop] = addParamsArr[prop];
288 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
292 if ( data.getElementsByTagName("status")[0]
293 .childNodes[0].nodeValue == "OK" ) {
294 context.searchStatusOK = true;
296 context.show(start, num, sort);
297 if ( context.statCallback )
299 if ( context.termlistCallback )
301 if ( context.bytargetCallback )
305 context.throwError('Search failed. Malformed WS resonse.',
312 if( !this.initStatusOK )
313 throw new Error('Pz2.js: session not initialized.');
315 // if called explicitly takes precedence
316 clearTimeout(this.statTimer);
319 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
321 { "command": "stat", "session": this.sessionID },
323 if ( data.getElementsByTagName("stat") ) {
325 Number( data.getElementsByTagName("activeclients")[0]
326 .childNodes[0].nodeValue );
327 context.activeClients = activeClients;
329 var stat = Element_parseChildNodes(data.documentElement);
331 context.statCounter++;
332 var delay = context.statTime
333 + context.statCounter * context.dumpFactor;
335 if ( activeClients > 0 )
343 context.statCallback(stat);
346 context.throwError('Stat failed. Malformed WS resonse.',
351 show: function(start, num, sort)
353 if( !this.searchStatusOK && this.useSessions )
355 'Pz2.js: show command has to be preceded with a search command.'
358 // if called explicitly takes precedence
359 clearTimeout(this.showTimer);
361 if( sort !== undefined )
362 this.currentSort = sort;
363 if( start !== undefined )
364 this.currentStart = Number( start );
365 if( num !== undefined )
366 this.currentNum = Number( num );
369 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
373 "session": this.sessionID,
374 "start": this.currentStart,
375 "num": this.currentNum,
376 "sort": this.currentSort,
380 if ( data.getElementsByTagName("status")[0]
381 .childNodes[0].nodeValue == "OK" ) {
382 // first parse the status data send along with records
383 // this is strictly bound to the format
385 Number( data.getElementsByTagName("activeclients")[0]
386 .childNodes[0].nodeValue );
387 context.activeClients = activeClients;
389 "activeclients": activeClients,
391 Number( data.getElementsByTagName("merged")[0]
392 .childNodes[0].nodeValue ),
394 Number( data.getElementsByTagName("total")[0]
395 .childNodes[0].nodeValue ),
397 Number( data.getElementsByTagName("start")[0]
398 .childNodes[0].nodeValue ),
400 Number( data.getElementsByTagName("num")[0]
401 .childNodes[0].nodeValue ),
404 // parse all the first-level nodes for all <hit> tags
405 var hits = data.getElementsByTagName("hit");
406 for (i = 0; i < hits.length; i++)
407 show.hits[i] = Element_parseChildNodes(hits[i]);
409 context.showCounter++;
410 var delay = context.showTime;
411 if (context.showCounter > context.showFastCount)
412 delay += context.showCounter * context.dumpFactor;
413 if ( activeClients > 0 )
414 context.showTimer = setTimeout(
420 context.showCallback(show);
423 context.throwError('Show failed. Malformed WS resonse.',
428 record: function(id, offset, syntax, handler)
430 // we may call record with no previous search if in proxy mode
431 if(!this.searchStatusOK && this.useSessions)
433 'Pz2.js: record command has to be preceded with a search command.'
436 if( id !== undefined )
441 "session": this.sessionID,
445 this.currRecOffset = null;
446 if (offset != undefined) {
447 recordParams["offset"] = offset;
448 this.currRecOffset = offset;
451 if (syntax != undefined)
452 recordParams['syntax'] = syntax;
454 //overwrite default callback id needed
455 var callback = this.recordCallback;
456 var args = undefined;
457 if (handler != undefined) {
458 callback = handler['callback'];
459 args = handler['args'];
463 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
471 if (context.currRecOffset !== null) {
472 record = new Array();
473 record['xmlDoc'] = data;
474 record['offset'] = context.currRecOffset;
475 callback(record, args);
477 } else if ( recordNode =
478 data.getElementsByTagName("record")[0] ) {
479 // if stylesheet was fetched do not parse the response
480 if ( context.xslDoc ) {
481 record = new Array();
482 record['xmlDoc'] = data;
483 record['xslDoc'] = context.xslDoc;
485 recordNode.getElementsByTagName("recid")[0]
486 .firstChild.nodeValue;
489 record = Element_parseChildNodes(recordNode);
492 Number( data.getElementsByTagName("activeclients")[0]
493 .childNodes[0].nodeValue );
494 context.activeClients = activeClients;
495 context.recordCounter++;
496 var delay = context.recordTime + context.recordCounter * context.dumpFactor;
497 if ( activeClients > 0 )
498 context.recordTimer =
501 context.record(id, offset, syntax, handler);
505 callback(record, args);
508 context.throwError('Record failed. Malformed WS resonse.',
516 if( !this.searchStatusOK && this.useSessions )
518 'Pz2.js: termlist command has to be preceded with a search command.'
521 // if called explicitly takes precedence
522 clearTimeout(this.termTimer);
525 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
528 "command": "termlist",
529 "session": this.sessionID,
530 "name": this.termKeys
533 if ( data.getElementsByTagName("termlist") ) {
535 Number( data.getElementsByTagName("activeclients")[0]
536 .childNodes[0].nodeValue );
537 context.activeClients = activeClients;
538 var termList = { "activeclients": activeClients };
539 var termLists = data.getElementsByTagName("list");
541 for (i = 0; i < termLists.length; i++) {
542 var listName = termLists[i].getAttribute('name');
543 termList[listName] = new Array();
544 var terms = termLists[i].getElementsByTagName('term');
545 //for each term in the list
546 for (j = 0; j < terms.length; j++) {
549 (terms[j].getElementsByTagName("name")[0]
551 ? terms[j].getElementsByTagName("name")[0]
552 .childNodes[0].nodeValue
556 .getElementsByTagName("frequency")[0]
557 .childNodes[0].nodeValue || 'ERROR'
561 terms[j].getElementsByTagName("id");
562 if(terms[j].getElementsByTagName("id").length)
564 termIdNode[0].childNodes[0].nodeValue;
565 termList[listName][j] = term;
569 context.termCounter++;
570 var delay = context.termTime
571 + context.termCounter * context.dumpFactor;
572 if ( activeClients > 0 )
581 context.termlistCallback(termList);
584 context.throwError('Termlist failed. Malformed WS resonse.',
592 if( !this.initStatusOK && this.useSessions )
594 'Pz2.js: bytarget command has to be preceded with a search command.'
597 // no need to continue
598 if( !this.searchStatusOK )
601 // if called explicitly takes precedence
602 clearTimeout(this.bytargetTimer);
605 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
607 { "command": "bytarget", "session": this.sessionID },
609 if ( data.getElementsByTagName("status")[0]
610 .childNodes[0].nodeValue == "OK" ) {
611 var targetNodes = data.getElementsByTagName("target");
612 var bytarget = new Array();
613 for ( i = 0; i < targetNodes.length; i++) {
614 bytarget[i] = new Array();
615 for( j = 0; j < targetNodes[i].childNodes.length; j++ ) {
616 if ( targetNodes[i].childNodes[j].nodeType
617 == Node.ELEMENT_NODE ) {
619 targetNodes[i].childNodes[j].nodeName;
621 targetNodes[i].childNodes[j]
622 .firstChild.nodeValue;
623 bytarget[i][nodeName] = nodeText;
628 context.bytargetCounter++;
629 var delay = context.bytargetTime
630 + context.bytargetCounter * context.dumpFactor;
631 if ( context.activeClients > 0 )
632 context.bytargetTimer =
640 context.bytargetCallback(bytarget);
643 context.throwError('Bytarget failed. Malformed WS resonse.',
649 // just for testing, probably shouldn't be here
650 showNext: function(page)
652 var step = page || 1;
653 this.show( ( step * this.currentNum ) + this.currentStart );
656 showPrev: function(page)
658 if (this.currentStart == 0 )
660 var step = page || 1;
661 var newStart = this.currentStart - (step * this.currentNum );
662 this.show( newStart > 0 ? newStart : 0 );
665 showPage: function(pageNum)
667 //var page = pageNum || 1;
668 this.show(pageNum * this.currentNum);
673 ********************************************************************************
674 ** AJAX HELPER CLASS ***********************************************************
675 ********************************************************************************
677 var pzHttpRequest = function ( url, errorHandler ) {
678 this.maxUrlLength = 2048;
681 this.errorHandler = errorHandler || null;
683 this.requestHeaders = {};
685 if ( window.XMLHttpRequest ) {
686 this.request = new XMLHttpRequest();
687 } else if ( window.ActiveXObject ) {
689 this.request = new ActiveXObject( 'Msxml2.XMLHTTP' );
691 this.request = new ActiveXObject( 'Microsoft.XMLHTTP' );
696 pzHttpRequest.prototype =
698 safeGet: function ( params, callback )
700 var encodedParams = this.encodeParams(params);
701 var url = this._urlAppendParams(encodedParams);
702 if (url.length >= this.maxUrlLength) {
703 this.requestHeaders["Content-Type"]
704 = "application/x-www-form-urlencoded";
705 this._send( 'POST', this.url, encodedParams, callback );
707 this._send( 'GET', url, '', callback );
711 get: function ( params, callback )
713 this._send( 'GET', this._urlAppendParams(this.encodeParams(params)),
717 post: function ( params, data, callback )
719 this._send( 'POST', this._urlAppendParams(this.encodeParams(params)),
726 this.request.open( 'GET', this.url, this.async );
727 this.request.send('');
728 if ( this.request.status == 200 )
729 return this.request.responseXML;
732 encodeParams: function (params)
736 for (var key in params) {
737 if (params[key] != null) {
738 encoded += sep + key + '=' + encodeURIComponent(params[key]);
745 _send: function ( type, url, data, callback)
748 this.callback = callback;
750 this.request.open( type, url, this.async );
751 for (var key in this.requestHeaders)
752 this.request.setRequestHeader(key, this.requestHeaders[key]);
753 this.request.onreadystatechange = function () {
754 context._handleResponse();
756 this.request.send(data);
759 _urlAppendParams: function (encodedParams)
762 return this.url + "?" + encodedParams;
767 _handleResponse: function ()
769 if ( this.request.readyState == 4 ) {
770 // pick up appplication errors first
772 if (this.request.responseXML &&
773 (errNode = this.request.responseXML.documentElement)
774 && errNode.nodeName == 'error') {
775 var errMsg = errNode.getAttribute("msg");
776 var errCode = errNode.getAttribute("code");
778 if (errNode.childNodes.length)
779 errAddInfo = ': ' + errNode.childNodes[0].nodeValue;
781 var err = new Error(errMsg + errAddInfo);
784 if (this.errorHandler) {
785 this.errorHandler(err);
790 } else if (this.request.status == 200) {
791 this.callback(this.request.responseXML);
793 var err = new Error("HTTP response not OK: "
794 + this.request.status + " - "
795 + this.request.statusText );
796 err.code = '00' + this.request.status;
798 if (this.errorHandler) {
799 this.errorHandler(err);
810 ********************************************************************************
811 ** XML HELPER FUNCTIONS ********************************************************
812 ********************************************************************************
817 if ( window.ActiveXObject) {
818 var DOMDoc = document;
820 var DOMDoc = Document.prototype;
823 DOMDoc.newXmlDoc = function ( root )
827 if (document.implementation && document.implementation.createDocument) {
828 doc = document.implementation.createDocument('', root, null);
829 } else if ( window.ActiveXObject ) {
830 doc = new ActiveXObject("MSXML2.DOMDocument");
831 doc.loadXML('<' + root + '/>');
833 throw new Error ('No XML support in this browser');
840 DOMDoc.parseXmlFromString = function ( xmlString )
844 if ( window.DOMParser ) {
845 var parser = new DOMParser();
846 doc = parser.parseFromString( xmlString, "text/xml");
847 } else if ( window.ActiveXObject ) {
848 doc = new ActiveXObject("MSXML2.DOMDocument");
849 doc.loadXML( xmlString );
851 throw new Error ("No XML parsing support in this browser.");
857 DOMDoc.transformToDoc = function (xmlDoc, xslDoc)
859 if ( window.XSLTProcessor ) {
860 var proc = new XSLTProcessor();
861 proc.importStylesheet( xslDoc );
862 return proc.transformToDocument(xmlDoc);
863 } else if ( window.ActiveXObject ) {
864 return document.parseXmlFromString(xmlDoc.transformNode(xslDoc));
866 alert( 'Unable to perform XSLT transformation in this browser' );
872 Element_removeFromDoc = function (DOM_Element)
874 DOM_Element.parentNode.removeChild(DOM_Element);
877 Element_emptyChildren = function (DOM_Element)
879 while( DOM_Element.firstChild ) {
880 DOM_Element.removeChild( DOM_Element.firstChild )
884 Element_appendTransformResult = function ( DOM_Element, xmlDoc, xslDoc )
886 if ( window.XSLTProcessor ) {
887 var proc = new XSLTProcessor();
888 proc.importStylesheet( xslDoc );
890 docFrag = proc.transformToFragment( xmlDoc, DOM_Element.ownerDocument );
891 DOM_Element.appendChild(docFrag);
892 } else if ( window.ActiveXObject ) {
893 DOM_Element.innerHTML = xmlDoc.transformNode( xslDoc );
895 alert( 'Unable to perform XSLT transformation in this browser' );
899 Element_appendTextNode = function (DOM_Element, tagName, textContent )
901 var node = DOM_Element.ownerDocument.createElement(tagName);
902 var text = DOM_Element.ownerDocument.createTextNode(textContent);
904 DOM_Element.appendChild(node);
905 node.appendChild(text);
910 Element_setTextContent = function ( DOM_Element, textContent )
912 if (typeof DOM_Element.textContent !== "undefined") {
913 DOM_Element.textContent = textContent;
914 } else if (typeof DOM_Element.innerText !== "undefined" ) {
915 DOM_Element.innerText = textContent;
917 throw new Error("Cannot set text content of the node, no such method.");
921 Element_getTextContent = function (DOM_Element)
923 if ( typeof DOM_Element.textContent != 'undefined' ) {
924 return DOM_Element.textContent;
925 } else if (typeof DOM_Element.text != 'undefined') {
926 return DOM_Element.text;
928 throw new Error("Cannot get text content of the node, no such method.");
932 Element_parseChildNodes = function (node)
935 var hasChildElems = false;
937 if (node.hasChildNodes()) {
938 var children = node.childNodes;
939 for (var i = 0; i < children.length; i++) {
940 var child = children[i];
941 if (child.nodeType == Node.ELEMENT_NODE) {
942 hasChildElems = true;
943 var nodeName = child.nodeName;
944 if (!(nodeName in parsed))
945 parsed[nodeName] = [];
946 parsed[nodeName].push(Element_parseChildNodes(child));
951 var attrs = node.attributes;
952 for (var i = 0; i < attrs.length; i++) {
953 var attrName = '@' + attrs[i].nodeName;
954 var attrValue = attrs[i].nodeValue;
955 parsed[attrName] = attrValue;
958 // if no nested elements, get text content
959 if (node.hasChildNodes() && !hasChildElems) {
960 if (node.attributes.length)
961 parsed['textContent'] = node.firstChild.nodeValue;
963 parsed = node.firstChild.nodeValue;
969 /* do not remove trailing bracket */