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;
256 if( !this.initStatusOK )
257 throw new Error('Pz2.js: session not initialized.');
259 if( query !== undefined )
260 this.currQuery = query;
262 throw new Error("Pz2.js: no query supplied to the search command.");
264 if ( showfrom !== undefined )
265 var start = showfrom;
271 "query": this.currQuery,
272 "session": this.sessionID
275 if (filter !== undefined)
276 searchParams["filter"] = filter;
278 // copy additional parmeters, do not overwrite
279 if (addParamsArr != undefined) {
280 for (var prop in addParamsArr) {
281 if (!searchParams.hasOwnProperty(prop))
282 searchParams[prop] = addParamsArr[prop];
287 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
291 if ( data.getElementsByTagName("status")[0]
292 .childNodes[0].nodeValue == "OK" ) {
293 context.searchStatusOK = true;
295 context.show(start, num, sort);
296 if ( context.statCallback )
298 if ( context.termlistCallback )
300 if ( context.bytargetCallback )
304 context.throwError('Search failed. Malformed WS resonse.',
311 if( !this.initStatusOK )
312 throw new Error('Pz2.js: session not initialized.');
314 // if called explicitly takes precedence
315 clearTimeout(this.statTimer);
318 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
320 { "command": "stat", "session": this.sessionID },
322 if ( data.getElementsByTagName("stat") ) {
324 Number( data.getElementsByTagName("activeclients")[0]
325 .childNodes[0].nodeValue );
326 context.activeClients = activeClients;
328 "activeclients": activeClients,
330 Number( data.getElementsByTagName("hits")[0]
331 .childNodes[0].nodeValue ),
333 Number( data.getElementsByTagName("records")[0]
334 .childNodes[0].nodeValue ),
336 Number( data.getElementsByTagName("clients")[0]
337 .childNodes[0].nodeValue ),
339 Number( data.getElementsByTagName("initializing")[0]
340 .childNodes[0].nodeValue ),
342 Number( data.getElementsByTagName("searching")[0]
343 .childNodes[0].nodeValue ),
345 Number( data.getElementsByTagName("presenting")[0]
346 .childNodes[0].nodeValue ),
348 Number( data.getElementsByTagName("idle")[0]
349 .childNodes[0].nodeValue ),
351 Number( data.getElementsByTagName("failed")[0]
352 .childNodes[0].nodeValue ),
354 Number( data.getElementsByTagName("error")[0]
355 .childNodes[0].nodeValue )
358 context.statCounter++;
359 var delay = context.statTime
360 + context.statCounter * context.dumpFactor;
362 if ( activeClients > 0 )
370 context.statCallback(stat);
373 context.throwError('Stat failed. Malformed WS resonse.',
378 show: function(start, num, sort)
380 if( !this.searchStatusOK && this.useSessions )
382 'Pz2.js: show command has to be preceded with a search command.'
385 // if called explicitly takes precedence
386 clearTimeout(this.showTimer);
388 if( sort !== undefined )
389 this.currentSort = sort;
390 if( start !== undefined )
391 this.currentStart = Number( start );
392 if( num !== undefined )
393 this.currentNum = Number( num );
396 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
400 "session": this.sessionID,
401 "start": this.currentStart,
402 "num": this.currentNum,
403 "sort": this.currentSort,
407 if ( data.getElementsByTagName("status")[0]
408 .childNodes[0].nodeValue == "OK" ) {
409 // first parse the status data send along with records
410 // this is strictly bound to the format
412 Number( data.getElementsByTagName("activeclients")[0]
413 .childNodes[0].nodeValue );
414 context.activeClients = activeClients;
416 "activeclients": activeClients,
418 Number( data.getElementsByTagName("merged")[0]
419 .childNodes[0].nodeValue ),
421 Number( data.getElementsByTagName("total")[0]
422 .childNodes[0].nodeValue ),
424 Number( data.getElementsByTagName("start")[0]
425 .childNodes[0].nodeValue ),
427 Number( data.getElementsByTagName("num")[0]
428 .childNodes[0].nodeValue ),
431 // parse all the first-level nodes for all <hit> tags
432 var hits = data.getElementsByTagName("hit");
433 for (i = 0; i < hits.length; i++)
434 show.hits[i] = Element_parseChildNodes(hits[i]);
436 context.showCounter++;
437 var delay = context.showTime;
438 if (context.showCounter > context.showFastCount)
439 delay += context.showCounter * context.dumpFactor;
440 if ( activeClients > 0 )
441 context.showTimer = setTimeout(
447 context.showCallback(show);
450 context.throwError('Show failed. Malformed WS resonse.',
455 record: function(id, offset, syntax, handler)
457 // we may call record with no previous search if in proxy mode
458 if(!this.searchStatusOK && this.useSessions)
460 'Pz2.js: record command has to be preceded with a search command.'
463 if( id !== undefined )
468 "session": this.sessionID,
472 this.currRecOffset = null;
473 if (offset != undefined) {
474 recordParams["offset"] = offset;
475 this.currRecOffset = offset;
478 if (syntax != undefined)
479 recordParams['syntax'] = syntax;
481 //overwrite default callback id needed
482 var callback = this.recordCallback;
483 var args = undefined;
484 if (handler != undefined) {
485 callback = handler['callback'];
486 args = handler['args'];
490 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
498 if (context.currRecOffset !== null) {
499 record = new Array();
500 record['xmlDoc'] = data;
501 record['offset'] = context.currRecOffset;
502 callback(record, args);
504 } else if ( recordNode =
505 data.getElementsByTagName("record")[0] ) {
506 // if stylesheet was fetched do not parse the response
507 if ( context.xslDoc ) {
508 record = new Array();
509 record['xmlDoc'] = data;
510 record['xslDoc'] = context.xslDoc;
512 recordNode.getElementsByTagName("recid")[0]
513 .firstChild.nodeValue;
516 record = Element_parseChildNodes(recordNode);
519 Number( data.getElementsByTagName("activeclients")[0]
520 .childNodes[0].nodeValue );
521 context.activeClients = activeClients;
522 context.recordCounter++;
523 var delay = context.recordTime + context.recordCounter * context.dumpFactor;
524 if ( activeClients > 0 )
525 context.recordTimer =
528 context.record(id, offset, syntax, handler);
532 callback(record, args);
535 context.throwError('Record failed. Malformed WS resonse.',
543 if( !this.searchStatusOK && this.useSessions )
545 'Pz2.js: termlist command has to be preceded with a search command.'
548 // if called explicitly takes precedence
549 clearTimeout(this.termTimer);
552 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
555 "command": "termlist",
556 "session": this.sessionID,
557 "name": this.termKeys
560 if ( data.getElementsByTagName("termlist") ) {
562 Number( data.getElementsByTagName("activeclients")[0]
563 .childNodes[0].nodeValue );
564 context.activeClients = activeClients;
565 var termList = { "activeclients": activeClients };
566 var termLists = data.getElementsByTagName("list");
568 for (i = 0; i < termLists.length; i++) {
569 var listName = termLists[i].getAttribute('name');
570 termList[listName] = new Array();
571 var terms = termLists[i].getElementsByTagName('term');
572 //for each term in the list
573 for (j = 0; j < terms.length; j++) {
576 (terms[j].getElementsByTagName("name")[0]
578 ? terms[j].getElementsByTagName("name")[0]
579 .childNodes[0].nodeValue
583 .getElementsByTagName("frequency")[0]
584 .childNodes[0].nodeValue || 'ERROR'
588 terms[j].getElementsByTagName("id");
589 if(terms[j].getElementsByTagName("id").length)
591 termIdNode[0].childNodes[0].nodeValue;
592 termList[listName][j] = term;
596 context.termCounter++;
597 var delay = context.termTime
598 + context.termCounter * context.dumpFactor;
599 if ( activeClients > 0 )
608 context.termlistCallback(termList);
611 context.throwError('Termlist failed. Malformed WS resonse.',
619 if( !this.initStatusOK && this.useSessions )
621 'Pz2.js: bytarget command has to be preceded with a search command.'
624 // no need to continue
625 if( !this.searchStatusOK )
628 // if called explicitly takes precedence
629 clearTimeout(this.bytargetTimer);
632 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
634 { "command": "bytarget", "session": this.sessionID },
636 if ( data.getElementsByTagName("status")[0]
637 .childNodes[0].nodeValue == "OK" ) {
638 var targetNodes = data.getElementsByTagName("target");
639 var bytarget = new Array();
640 for ( i = 0; i < targetNodes.length; i++) {
641 bytarget[i] = new Array();
642 for( j = 0; j < targetNodes[i].childNodes.length; j++ ) {
643 if ( targetNodes[i].childNodes[j].nodeType
644 == Node.ELEMENT_NODE ) {
646 targetNodes[i].childNodes[j].nodeName;
648 targetNodes[i].childNodes[j]
649 .firstChild.nodeValue;
650 bytarget[i][nodeName] = nodeText;
655 context.bytargetCounter++;
656 var delay = context.bytargetTime
657 + context.bytargetCounter * context.dumpFactor;
658 if ( context.activeClients > 0 )
659 context.bytargetTimer =
667 context.bytargetCallback(bytarget);
670 context.throwError('Bytarget failed. Malformed WS resonse.',
676 // just for testing, probably shouldn't be here
677 showNext: function(page)
679 var step = page || 1;
680 this.show( ( step * this.currentNum ) + this.currentStart );
683 showPrev: function(page)
685 if (this.currentStart == 0 )
687 var step = page || 1;
688 var newStart = this.currentStart - (step * this.currentNum );
689 this.show( newStart > 0 ? newStart : 0 );
692 showPage: function(pageNum)
694 //var page = pageNum || 1;
695 this.show(pageNum * this.currentNum);
700 ********************************************************************************
701 ** AJAX HELPER CLASS ***********************************************************
702 ********************************************************************************
704 var pzHttpRequest = function ( url, errorHandler ) {
705 this.maxUrlLength = 2048;
708 this.errorHandler = errorHandler || null;
710 this.requestHeaders = {};
712 if ( window.XMLHttpRequest ) {
713 this.request = new XMLHttpRequest();
714 } else if ( window.ActiveXObject ) {
716 this.request = new ActiveXObject( 'Msxml2.XMLHTTP' );
718 this.request = new ActiveXObject( 'Microsoft.XMLHTTP' );
723 pzHttpRequest.prototype =
725 safeGet: function ( params, callback )
727 var encodedParams = this.encodeParams(params);
728 var url = this._urlAppendParams(encodedParams);
729 if (url.length >= this.maxUrlLength) {
730 this.requestHeaders["Content-Type"]
731 = "application/x-www-form-urlencoded";
732 this._send( 'POST', this.url, encodedParams, callback );
734 this._send( 'GET', url, '', callback );
738 get: function ( params, callback )
740 this._send( 'GET', this._urlAppendParams(this.encodeParams(params)),
744 post: function ( params, data, callback )
746 this._send( 'POST', this._urlAppendParams(this.encodeParams(params)),
753 this.request.open( 'GET', this.url, this.async );
754 this.request.send('');
755 if ( this.request.status == 200 )
756 return this.request.responseXML;
759 encodeParams: function (params)
763 for (var key in params) {
764 if (params[key] != null) {
765 encoded += sep + key + '=' + encodeURIComponent(params[key]);
772 _send: function ( type, url, data, callback)
775 this.callback = callback;
777 this.request.open( type, url, this.async );
778 for (var key in this.requestHeaders)
779 this.request.setRequestHeader(key, this.requestHeaders[key]);
780 this.request.onreadystatechange = function () {
781 context._handleResponse();
783 this.request.send(data);
786 _urlAppendParams: function (encodedParams)
789 return this.url + "?" + encodedParams;
794 _handleResponse: function ()
796 if ( this.request.readyState == 4 ) {
797 // pick up appplication errors first
799 if (this.request.responseXML &&
800 (errNode = this.request.responseXML.documentElement)
801 && errNode.nodeName == 'error') {
802 var errMsg = errNode.getAttribute("msg");
803 var errCode = errNode.getAttribute("code");
805 if (errNode.childNodes.length)
806 errAddInfo = ': ' + errNode.childNodes[0].nodeValue;
808 var err = new Error(errMsg + errAddInfo);
811 if (this.errorHandler) {
812 this.errorHandler(err);
817 } else if (this.request.status == 200) {
818 this.callback(this.request.responseXML);
820 var err = new Error("HTTP response not OK: "
821 + this.request.status + " - "
822 + this.request.statusText );
823 err.code = '00' + this.request.status;
825 if (this.errorHandler) {
826 this.errorHandler(err);
837 ********************************************************************************
838 ** XML HELPER FUNCTIONS ********************************************************
839 ********************************************************************************
844 if ( window.ActiveXObject) {
845 var DOMDoc = document;
847 var DOMDoc = Document.prototype;
850 DOMDoc.newXmlDoc = function ( root )
854 if (document.implementation && document.implementation.createDocument) {
855 doc = document.implementation.createDocument('', root, null);
856 } else if ( window.ActiveXObject ) {
857 doc = new ActiveXObject("MSXML2.DOMDocument");
858 doc.loadXML('<' + root + '/>');
860 throw new Error ('No XML support in this browser');
867 DOMDoc.parseXmlFromString = function ( xmlString )
871 if ( window.DOMParser ) {
872 var parser = new DOMParser();
873 doc = parser.parseFromString( xmlString, "text/xml");
874 } else if ( window.ActiveXObject ) {
875 doc = new ActiveXObject("MSXML2.DOMDocument");
876 doc.loadXML( xmlString );
878 throw new Error ("No XML parsing support in this browser.");
884 DOMDoc.transformToDoc = function (xmlDoc, xslDoc)
886 if ( window.XSLTProcessor ) {
887 var proc = new XSLTProcessor();
888 proc.importStylesheet( xslDoc );
889 return proc.transformToDocument(xmlDoc);
890 } else if ( window.ActiveXObject ) {
891 return document.parseXmlFromString(xmlDoc.transformNode(xslDoc));
893 alert( 'Unable to perform XSLT transformation in this browser' );
899 Element_removeFromDoc = function (DOM_Element)
901 DOM_Element.parentNode.removeChild(DOM_Element);
904 Element_emptyChildren = function (DOM_Element)
906 while( DOM_Element.firstChild ) {
907 DOM_Element.removeChild( DOM_Element.firstChild )
911 Element_appendTransformResult = function ( DOM_Element, xmlDoc, xslDoc )
913 if ( window.XSLTProcessor ) {
914 var proc = new XSLTProcessor();
915 proc.importStylesheet( xslDoc );
917 docFrag = proc.transformToFragment( xmlDoc, DOM_Element.ownerDocument );
918 DOM_Element.appendChild(docFrag);
919 } else if ( window.ActiveXObject ) {
920 DOM_Element.innerHTML = xmlDoc.transformNode( xslDoc );
922 alert( 'Unable to perform XSLT transformation in this browser' );
926 Element_appendTextNode = function (DOM_Element, tagName, textContent )
928 var node = DOM_Element.ownerDocument.createElement(tagName);
929 var text = DOM_Element.ownerDocument.createTextNode(textContent);
931 DOM_Element.appendChild(node);
932 node.appendChild(text);
937 Element_setTextContent = function ( DOM_Element, textContent )
939 if (typeof DOM_Element.textContent !== "undefined") {
940 DOM_Element.textContent = textContent;
941 } else if (typeof DOM_Element.innerText !== "undefined" ) {
942 DOM_Element.innerText = textContent;
944 throw new Error("Cannot set text content of the node, no such method.");
948 Element_getTextContent = function (DOM_Element)
950 if ( typeof DOM_Element.textContent != 'undefined' ) {
951 return DOM_Element.textContent;
952 } else if (typeof DOM_Element.text != 'undefined') {
953 return DOM_Element.text;
955 throw new Error("Cannot get text content of the node, no such method.");
959 Element_parseChildNodes = function (node)
962 var hasChildElems = false;
964 if (node.hasChildNodes()) {
965 var children = node.childNodes;
966 for (var i = 0; i < children.length; i++) {
967 var child = children[i];
968 if (child.nodeType == Node.ELEMENT_NODE) {
969 hasChildElems = true;
970 var nodeName = child.nodeName;
971 if (!(nodeName in parsed))
972 parsed[nodeName] = [];
973 parsed[nodeName].push(Element_parseChildNodes(child));
978 var attrs = node.attributes;
979 for (var i = 0; i < attrs.length; i++) {
980 var attrName = '@' + attrs[i].nodeName;
981 var attrValue = attrs[i].nodeValue;
982 parsed[attrName] = attrValue;
985 // if no nested elements, get text content
986 if (node.hasChildNodes() && !hasChildElems) {
987 if (node.attributes.length)
988 parsed['textContent'] = node.firstChild.nodeValue;
990 parsed = node.firstChild.nodeValue;
996 /* do not remove trailing bracket */