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;
51 this.showResponseType = paramArray.showResponseType || "xml";
54 this.initCallback = paramArray.oninit || null;
55 this.statCallback = paramArray.onstat || null;
56 this.showCallback = paramArray.onshow || null;
57 this.termlistCallback = paramArray.onterm || null;
58 this.recordCallback = paramArray.onrecord || null;
59 this.bytargetCallback = paramArray.onbytarget || null;
60 this.resetCallback = paramArray.onreset || null;
63 this.termKeys = paramArray.termlist || "subject";
65 // some configurational stuff
66 this.keepAlive = 50000;
68 if ( paramArray.keepAlive < this.keepAlive )
69 this.keepAlive = paramArray.keepAlive;
71 this.sessionID = null;
72 this.serviceId = paramArray.serviceId || null;
73 this.initStatusOK = false;
74 this.pingStatusOK = false;
75 this.searchStatusOK = false;
78 this.currentSort = "relevance";
81 this.currentStart = 0;
84 // last full record retrieved
85 this.currRecID = null;
88 this.currQuery = null;
90 //current raw record offset
91 this.currRecOffset = null;
94 this.statTime = paramArray.stattime || 1000;
95 this.statTimer = null;
96 this.termTime = paramArray.termtime || 1000;
97 this.termTimer = null;
98 this.showTime = paramArray.showtime || 1000;
99 this.showTimer = null;
100 this.showFastCount = 4;
101 this.bytargetTime = paramArray.bytargettime || 1000;
102 this.bytargetTimer = null;
103 this.recordTime = paramArray.recordtime || 500;
104 this.recordTimer = null;
106 // counters for each command and applied delay
107 this.dumpFactor = 500;
108 this.showCounter = 0;
109 this.termCounter = 0;
110 this.statCounter = 0;
111 this.bytargetCounter = 0;
112 this.recordCounter = 0;
114 // active clients, updated by stat and show
115 // might be an issue since bytarget will poll accordingly
116 this.activeClients = 1;
118 // if in proxy mode no need to init
119 if (paramArray.usesessions != undefined) {
120 this.useSessions = paramArray.usesessions;
121 this.initStatusOK = true;
123 // else, auto init session or wait for a user init?
124 if (this.useSessions && paramArray.autoInit !== false) {
125 this.init(this.sessionId, this.serviceId);
131 //error handler for async error throws
132 throwError: function (errMsg, errCode)
134 var err = new Error(errMsg);
135 if (errCode) err.code = errCode;
137 if (this.errorHandler) {
138 this.errorHandler(err);
145 // stop activity by clearing tiemouts
148 clearTimeout(this.statTimer);
149 clearTimeout(this.showTimer);
150 clearTimeout(this.termTimer);
151 clearTimeout(this.bytargetTimer);
154 // reset status variables
157 if ( this.useSessions ) {
158 this.sessionID = null;
159 this.initStatusOK = false;
160 this.pingStatusOK = false;
162 this.searchStatusOK = false;
165 if ( this.resetCallback )
166 this.resetCallback();
169 init: function (sessionId, serviceId)
173 // session id as a param
174 if (sessionId && this.useSessions ) {
175 this.initStatusOK = true;
176 this.sessionID = sessionId;
178 // old school direct pazpar2 init
179 } else if (this.useSessions) {
181 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
182 var opts = {'command' : 'init'};
183 if (serviceId) opts.service = serviceId;
187 if ( data.getElementsByTagName("status")[0]
188 .childNodes[0].nodeValue == "OK" ) {
189 if ( data.getElementsByTagName("protocol")[0]
190 .childNodes[0].nodeValue
191 != context.suppProtoVer )
193 "Server's protocol not supported by the client"
195 context.initStatusOK = true;
197 data.getElementsByTagName("session")[0]
198 .childNodes[0].nodeValue;
205 if ( context.initCallback )
206 context.initCallback();
209 context.throwError('Init failed. Malformed WS resonse.',
213 // when through proxy no need to init
215 this.initStatusOK = true;
218 // no need to ping explicitly
221 // pinging only makes sense when using pazpar2 directly
222 if( !this.initStatusOK || !this.useSessions )
224 'Pz2.js: Ping not allowed (proxy mode) or session not initialized.'
227 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
229 { "command": "ping", "session": this.sessionID },
231 if ( data.getElementsByTagName("status")[0]
232 .childNodes[0].nodeValue == "OK" ) {
233 context.pingStatusOK = true;
242 context.throwError('Ping failed. Malformed WS resonse.',
247 search: function (query, num, sort, filter, showfrom, addParamsArr)
249 clearTimeout(this.statTimer);
250 clearTimeout(this.showTimer);
251 clearTimeout(this.termTimer);
252 clearTimeout(this.bytargetTimer);
254 this.showCounter = 0;
255 this.termCounter = 0;
256 this.bytargetCounter = 0;
257 this.statCounter = 0;
258 this.activeClients = 1;
261 if( !this.initStatusOK )
262 throw new Error('Pz2.js: session not initialized.');
264 if( query !== undefined )
265 this.currQuery = query;
267 throw new Error("Pz2.js: no query supplied to the search command.");
269 if ( showfrom !== undefined )
270 var start = showfrom;
276 "query": this.currQuery,
277 "session": this.sessionID
280 if (filter !== undefined)
281 searchParams["filter"] = filter;
283 // copy additional parmeters, do not overwrite
284 if (addParamsArr != undefined) {
285 for (var prop in addParamsArr) {
286 if (!searchParams.hasOwnProperty(prop))
287 searchParams[prop] = addParamsArr[prop];
292 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
296 if ( data.getElementsByTagName("status")[0]
297 .childNodes[0].nodeValue == "OK" ) {
298 context.searchStatusOK = true;
300 context.show(start, num, sort);
301 if (context.statCallback)
303 if (context.termlistCallback)
305 if (context.bytargetCallback)
309 context.throwError('Search failed. Malformed WS resonse.',
316 if( !this.initStatusOK )
317 throw new Error('Pz2.js: session not initialized.');
319 // if called explicitly takes precedence
320 clearTimeout(this.statTimer);
323 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
325 { "command": "stat", "session": this.sessionID },
327 if ( data.getElementsByTagName("stat") ) {
329 Number( data.getElementsByTagName("activeclients")[0]
330 .childNodes[0].nodeValue );
331 context.activeClients = activeClients;
333 var stat = Element_parseChildNodes(data.documentElement);
335 context.statCounter++;
336 var delay = context.statTime
337 + context.statCounter * context.dumpFactor;
339 if ( activeClients > 0 )
347 context.statCallback(stat);
350 context.throwError('Stat failed. Malformed WS resonse.',
355 show: function(start, num, sort)
357 if( !this.searchStatusOK && this.useSessions )
359 'Pz2.js: show command has to be preceded with a search command.'
362 // if called explicitly takes precedence
363 clearTimeout(this.showTimer);
365 if( sort !== undefined )
366 this.currentSort = sort;
367 if( start !== undefined )
368 this.currentStart = Number( start );
369 if( num !== undefined )
370 this.currentNum = Number( num );
373 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
377 "session": this.sessionID,
378 "start": this.currentStart,
379 "num": this.currentNum,
380 "sort": this.currentSort,
382 "type": this.showResponseType
384 function(data, type) {
386 var activeClients = 0;
387 if (type === "json") {
389 activeClients = Number(data.activeclients[0]);
390 show.activeclients = activeClients;
391 show.merged = Number(data.merged[0]);
392 show.total = Number(data.total[0]);
393 show.start = Number(data.start[0]);
394 show.num = Number(data.num[0]);
395 show.hits = data.hit;
396 } else 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);
404 "activeclients": activeClients,
406 Number( data.getElementsByTagName("merged")[0]
407 .childNodes[0].nodeValue ),
409 Number( data.getElementsByTagName("total")[0]
410 .childNodes[0].nodeValue ),
412 Number( data.getElementsByTagName("start")[0]
413 .childNodes[0].nodeValue ),
415 Number( data.getElementsByTagName("num")[0]
416 .childNodes[0].nodeValue ),
419 // parse all the first-level nodes for all <hit> tags
420 var hits = data.getElementsByTagName("hit");
421 for (i = 0; i < hits.length; i++)
422 show.hits[i] = Element_parseChildNodes(hits[i]);
424 context.throwError('Show failed. Malformed WS resonse.',
427 context.activeClients = activeClients;
428 context.showCounter++;
429 var delay = context.showTime;
430 if (context.showCounter > context.showFastCount)
431 delay += context.showCounter * context.dumpFactor;
432 if ( activeClients > 0 )
433 context.showTimer = setTimeout(
438 context.showCallback(show);
442 record: function(id, offset, syntax, handler)
444 // we may call record with no previous search if in proxy mode
445 if(!this.searchStatusOK && this.useSessions)
447 'Pz2.js: record command has to be preceded with a search command.'
450 if( id !== undefined )
455 "session": this.sessionID,
459 this.currRecOffset = null;
460 if (offset != undefined) {
461 recordParams["offset"] = offset;
462 this.currRecOffset = offset;
465 if (syntax != undefined)
466 recordParams['syntax'] = syntax;
468 //overwrite default callback id needed
469 var callback = this.recordCallback;
470 var args = undefined;
471 if (handler != undefined) {
472 callback = handler['callback'];
473 args = handler['args'];
477 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
485 if (context.currRecOffset !== null) {
486 record = new Array();
487 record['xmlDoc'] = data;
488 record['offset'] = context.currRecOffset;
489 callback(record, args);
491 } else if ( recordNode =
492 data.getElementsByTagName("record")[0] ) {
493 // if stylesheet was fetched do not parse the response
494 if ( context.xslDoc ) {
495 record = new Array();
496 record['xmlDoc'] = data;
497 record['xslDoc'] = context.xslDoc;
499 recordNode.getElementsByTagName("recid")[0]
500 .firstChild.nodeValue;
503 record = Element_parseChildNodes(recordNode);
506 Number( data.getElementsByTagName("activeclients")[0]
507 .childNodes[0].nodeValue );
508 context.activeClients = activeClients;
509 context.recordCounter++;
510 var delay = context.recordTime + context.recordCounter * context.dumpFactor;
511 if ( activeClients > 0 )
512 context.recordTimer =
515 context.record(id, offset, syntax, handler);
519 callback(record, args);
522 context.throwError('Record failed. Malformed WS resonse.',
530 if( !this.searchStatusOK && this.useSessions )
532 'Pz2.js: termlist command has to be preceded with a search command.'
535 // if called explicitly takes precedence
536 clearTimeout(this.termTimer);
539 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
542 "command": "termlist",
543 "session": this.sessionID,
544 "name": this.termKeys
547 if ( data.getElementsByTagName("termlist") ) {
549 Number( data.getElementsByTagName("activeclients")[0]
550 .childNodes[0].nodeValue );
551 context.activeClients = activeClients;
552 var termList = { "activeclients": activeClients };
553 var termLists = data.getElementsByTagName("list");
555 for (i = 0; i < termLists.length; i++) {
556 var listName = termLists[i].getAttribute('name');
557 termList[listName] = new Array();
558 var terms = termLists[i].getElementsByTagName('term');
559 //for each term in the list
560 for (j = 0; j < terms.length; j++) {
563 (terms[j].getElementsByTagName("name")[0]
565 ? terms[j].getElementsByTagName("name")[0]
566 .childNodes[0].nodeValue
570 .getElementsByTagName("frequency")[0]
571 .childNodes[0].nodeValue || 'ERROR'
575 terms[j].getElementsByTagName("id");
576 if(terms[j].getElementsByTagName("id").length)
578 termIdNode[0].childNodes[0].nodeValue;
579 termList[listName][j] = term;
583 context.termCounter++;
584 var delay = context.termTime
585 + context.termCounter * context.dumpFactor;
586 if ( activeClients > 0 )
595 context.termlistCallback(termList);
598 context.throwError('Termlist failed. Malformed WS resonse.',
606 if( !this.initStatusOK && this.useSessions )
608 'Pz2.js: bytarget command has to be preceded with a search command.'
611 // no need to continue
612 if( !this.searchStatusOK )
615 // if called explicitly takes precedence
616 clearTimeout(this.bytargetTimer);
619 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
621 { "command": "bytarget", "session": this.sessionID },
623 if ( data.getElementsByTagName("status")[0]
624 .childNodes[0].nodeValue == "OK" ) {
625 var targetNodes = data.getElementsByTagName("target");
626 var bytarget = new Array();
627 for ( i = 0; i < targetNodes.length; i++) {
628 bytarget[i] = new Array();
629 for( j = 0; j < targetNodes[i].childNodes.length; j++ ) {
630 if ( targetNodes[i].childNodes[j].nodeType
631 == Node.ELEMENT_NODE ) {
633 targetNodes[i].childNodes[j].nodeName;
635 targetNodes[i].childNodes[j]
636 .firstChild.nodeValue;
637 bytarget[i][nodeName] = nodeText;
640 if (bytarget[i]["state"]=="Client_Disconnected") {
641 bytarget[i]["hits"] = "Error";
642 } else if (bytarget[i]["state"]=="Client_Error") {
643 bytarget[i]["hits"] = "Error";
644 } else if (bytarget[i]["state"]=="Client_Working") {
645 bytarget[i]["hits"] = "...";
649 context.bytargetCounter++;
650 var delay = context.bytargetTime
651 + context.bytargetCounter * context.dumpFactor;
652 if ( context.activeClients > 0 )
653 context.bytargetTimer =
661 context.bytargetCallback(bytarget);
664 context.throwError('Bytarget failed. Malformed WS resonse.',
670 // just for testing, probably shouldn't be here
671 showNext: function(page)
673 var step = page || 1;
674 this.show( ( step * this.currentNum ) + this.currentStart );
677 showPrev: function(page)
679 if (this.currentStart == 0 )
681 var step = page || 1;
682 var newStart = this.currentStart - (step * this.currentNum );
683 this.show( newStart > 0 ? newStart : 0 );
686 showPage: function(pageNum)
688 //var page = pageNum || 1;
689 this.show(pageNum * this.currentNum);
694 ********************************************************************************
695 ** AJAX HELPER CLASS ***********************************************************
696 ********************************************************************************
698 var pzHttpRequest = function ( url, errorHandler ) {
699 this.maxUrlLength = 2048;
702 this.errorHandler = errorHandler || null;
704 this.requestHeaders = {};
706 if ( window.XMLHttpRequest ) {
707 this.request = new XMLHttpRequest();
708 } else if ( window.ActiveXObject ) {
710 this.request = new ActiveXObject( 'Msxml2.XMLHTTP' );
712 this.request = new ActiveXObject( 'Microsoft.XMLHTTP' );
718 pzHttpRequest.prototype =
720 safeGet: function ( params, callback )
722 var encodedParams = this.encodeParams(params);
723 var url = this._urlAppendParams(encodedParams);
724 if (url.length >= this.maxUrlLength) {
725 this.requestHeaders["Content-Type"]
726 = "application/x-www-form-urlencoded";
727 this._send( 'POST', this.url, encodedParams, callback );
729 this._send( 'GET', url, '', callback );
733 get: function ( params, callback )
735 this._send( 'GET', this._urlAppendParams(this.encodeParams(params)),
739 post: function ( params, data, callback )
741 this._send( 'POST', this._urlAppendParams(this.encodeParams(params)),
748 this.request.open( 'GET', this.url, this.async );
749 this.request.send('');
750 if ( this.request.status == 200 )
751 return this.request.responseXML;
754 encodeParams: function (params)
758 for (var key in params) {
759 if (params[key] != null) {
760 encoded += sep + key + '=' + encodeURIComponent(params[key]);
767 _send: function ( type, url, data, callback)
770 this.callback = callback;
772 this.request.open( type, url, this.async );
773 for (var key in this.requestHeaders)
774 this.request.setRequestHeader(key, this.requestHeaders[key]);
775 this.request.onreadystatechange = function () {
776 context._handleResponse(url); /// url used ONLY for error reporting
778 this.request.send(data);
781 _urlAppendParams: function (encodedParams)
784 return this.url + "?" + encodedParams;
789 _handleResponse: function (savedUrlForErrorReporting)
791 if ( this.request.readyState == 4 ) {
792 // pick up appplication errors first
794 if (this.request.responseXML &&
795 (errNode = this.request.responseXML.documentElement)
796 && errNode.nodeName == 'error') {
797 var errMsg = errNode.getAttribute("msg");
798 var errCode = errNode.getAttribute("code");
800 if (errNode.childNodes.length)
801 errAddInfo = ': ' + errNode.childNodes[0].nodeValue;
803 var err = new Error(errMsg + errAddInfo);
806 if (this.errorHandler) {
807 this.errorHandler(err);
812 } else if (this.request.status == 200 &&
813 this.request.responseXML == null) {
814 if (this.request.responseText != null) {
818 var text = this.request.responseText;
819 if (typeof window.JSON == "undefined")
820 json = eval("(" + text + ")");
823 json = JSON.parse(text);
826 // Safari: eval will fail as well. Considering trying JSON2 (non-native implementation) instead
827 /* DEBUG only works in mk2-mobile
828 if (document.getElementById("log"))
829 document.getElementById("log").innerHTML = "" + e + " " + length + ": " + text;
832 json = eval("(" + text + ")");
835 /* DEBUG only works in mk2-mobile
836 if (document.getElementById("log"))
837 document.getElementById("log").innerHTML = "" + e + " " + length + ": " + text;
842 this.callback(json, "json");
844 var err = new Error("XML response is empty but no error " +
845 "for " + savedUrlForErrorReporting);
847 if (this.errorHandler) {
848 this.errorHandler(err);
853 } else if (this.request.status == 200) {
854 this.callback(this.request.responseXML);
856 var err = new Error("HTTP response not OK: "
857 + this.request.status + " - "
858 + this.request.statusText );
859 err.code = '00' + this.request.status;
860 if (this.errorHandler) {
861 this.errorHandler(err);
872 ********************************************************************************
873 ** XML HELPER FUNCTIONS ********************************************************
874 ********************************************************************************
879 if ( window.ActiveXObject) {
880 var DOMDoc = document;
882 var DOMDoc = Document.prototype;
885 DOMDoc.newXmlDoc = function ( root )
889 if (document.implementation && document.implementation.createDocument) {
890 doc = document.implementation.createDocument('', root, null);
891 } else if ( window.ActiveXObject ) {
892 doc = new ActiveXObject("MSXML2.DOMDocument");
893 doc.loadXML('<' + root + '/>');
895 throw new Error ('No XML support in this browser');
902 DOMDoc.parseXmlFromString = function ( xmlString )
906 if ( window.DOMParser ) {
907 var parser = new DOMParser();
908 doc = parser.parseFromString( xmlString, "text/xml");
909 } else if ( window.ActiveXObject ) {
910 doc = new ActiveXObject("MSXML2.DOMDocument");
911 doc.loadXML( xmlString );
913 throw new Error ("No XML parsing support in this browser.");
919 DOMDoc.transformToDoc = function (xmlDoc, xslDoc)
921 if ( window.XSLTProcessor ) {
922 var proc = new XSLTProcessor();
923 proc.importStylesheet( xslDoc );
924 return proc.transformToDocument(xmlDoc);
925 } else if ( window.ActiveXObject ) {
926 return document.parseXmlFromString(xmlDoc.transformNode(xslDoc));
928 alert( 'Unable to perform XSLT transformation in this browser' );
934 Element_removeFromDoc = function (DOM_Element)
936 DOM_Element.parentNode.removeChild(DOM_Element);
939 Element_emptyChildren = function (DOM_Element)
941 while( DOM_Element.firstChild ) {
942 DOM_Element.removeChild( DOM_Element.firstChild )
946 Element_appendTransformResult = function ( DOM_Element, xmlDoc, xslDoc )
948 if ( window.XSLTProcessor ) {
949 var proc = new XSLTProcessor();
950 proc.importStylesheet( xslDoc );
952 docFrag = proc.transformToFragment( xmlDoc, DOM_Element.ownerDocument );
953 DOM_Element.appendChild(docFrag);
954 } else if ( window.ActiveXObject ) {
955 DOM_Element.innerHTML = xmlDoc.transformNode( xslDoc );
957 alert( 'Unable to perform XSLT transformation in this browser' );
961 Element_appendTextNode = function (DOM_Element, tagName, textContent )
963 var node = DOM_Element.ownerDocument.createElement(tagName);
964 var text = DOM_Element.ownerDocument.createTextNode(textContent);
966 DOM_Element.appendChild(node);
967 node.appendChild(text);
972 Element_setTextContent = function ( DOM_Element, textContent )
974 if (typeof DOM_Element.textContent !== "undefined") {
975 DOM_Element.textContent = textContent;
976 } else if (typeof DOM_Element.innerText !== "undefined" ) {
977 DOM_Element.innerText = textContent;
979 throw new Error("Cannot set text content of the node, no such method.");
983 Element_getTextContent = function (DOM_Element)
985 if ( typeof DOM_Element.textContent != 'undefined' ) {
986 return DOM_Element.textContent;
987 } else if (typeof DOM_Element.text != 'undefined') {
988 return DOM_Element.text;
990 throw new Error("Cannot get text content of the node, no such method.");
994 Element_parseChildNodes = function (node)
997 var hasChildElems = false;
999 if (node.hasChildNodes()) {
1000 var children = node.childNodes;
1001 for (var i = 0; i < children.length; i++) {
1002 var child = children[i];
1003 if (child.nodeType == Node.ELEMENT_NODE) {
1004 hasChildElems = true;
1005 var nodeName = child.nodeName;
1006 if (!(nodeName in parsed))
1007 parsed[nodeName] = [];
1008 parsed[nodeName].push(Element_parseChildNodes(child));
1013 var attrs = node.attributes;
1014 for (var i = 0; i < attrs.length; i++) {
1015 var attrName = '@' + attrs[i].nodeName;
1016 var attrValue = attrs[i].nodeValue;
1017 parsed[attrName] = attrValue;
1020 // if no nested elements, get text content
1021 if (node.hasChildNodes() && !hasChildElems) {
1022 if (node.attributes.length)
1023 parsed['#text'] = node.firstChild.nodeValue;
1025 parsed = node.firstChild.nodeValue;
1031 /* do not remove trailing bracket */