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;
642 context.bytargetCounter++;
643 var delay = context.bytargetTime
644 + context.bytargetCounter * context.dumpFactor;
645 if ( context.activeClients > 0 )
646 context.bytargetTimer =
654 context.bytargetCallback(bytarget);
657 context.throwError('Bytarget failed. Malformed WS resonse.',
663 // just for testing, probably shouldn't be here
664 showNext: function(page)
666 var step = page || 1;
667 this.show( ( step * this.currentNum ) + this.currentStart );
670 showPrev: function(page)
672 if (this.currentStart == 0 )
674 var step = page || 1;
675 var newStart = this.currentStart - (step * this.currentNum );
676 this.show( newStart > 0 ? newStart : 0 );
679 showPage: function(pageNum)
681 //var page = pageNum || 1;
682 this.show(pageNum * this.currentNum);
687 ********************************************************************************
688 ** AJAX HELPER CLASS ***********************************************************
689 ********************************************************************************
691 var pzHttpRequest = function ( url, errorHandler ) {
692 this.maxUrlLength = 2048;
695 this.errorHandler = errorHandler || null;
697 this.requestHeaders = {};
699 if ( window.XMLHttpRequest ) {
700 this.request = new XMLHttpRequest();
701 } else if ( window.ActiveXObject ) {
703 this.request = new ActiveXObject( 'Msxml2.XMLHTTP' );
705 this.request = new ActiveXObject( 'Microsoft.XMLHTTP' );
710 pzHttpRequest.prototype =
712 safeGet: function ( params, callback )
714 var encodedParams = this.encodeParams(params);
715 var url = this._urlAppendParams(encodedParams);
716 if (url.length >= this.maxUrlLength) {
717 this.requestHeaders["Content-Type"]
718 = "application/x-www-form-urlencoded";
719 this._send( 'POST', this.url, encodedParams, callback );
721 this._send( 'GET', url, '', callback );
725 get: function ( params, callback )
727 this._send( 'GET', this._urlAppendParams(this.encodeParams(params)),
731 post: function ( params, data, callback )
733 this._send( 'POST', this._urlAppendParams(this.encodeParams(params)),
740 this.request.open( 'GET', this.url, this.async );
741 this.request.send('');
742 if ( this.request.status == 200 )
743 return this.request.responseXML;
746 encodeParams: function (params)
750 for (var key in params) {
751 if (params[key] != null) {
752 encoded += sep + key + '=' + encodeURIComponent(params[key]);
759 _send: function ( type, url, data, callback)
762 this.callback = callback;
764 this.request.open( type, url, this.async );
765 for (var key in this.requestHeaders)
766 this.request.setRequestHeader(key, this.requestHeaders[key]);
767 this.request.onreadystatechange = function () {
768 context._handleResponse(url); /// url used ONLY for error reporting
770 this.request.send(data);
773 _urlAppendParams: function (encodedParams)
776 return this.url + "?" + encodedParams;
781 _handleResponse: function (savedUrlForErrorReporting)
783 if ( this.request.readyState == 4 ) {
784 // pick up appplication errors first
786 if (this.request.responseXML &&
787 (errNode = this.request.responseXML.documentElement)
788 && errNode.nodeName == 'error') {
789 var errMsg = errNode.getAttribute("msg");
790 var errCode = errNode.getAttribute("code");
792 if (errNode.childNodes.length)
793 errAddInfo = ': ' + errNode.childNodes[0].nodeValue;
795 var err = new Error(errMsg + errAddInfo);
798 if (this.errorHandler) {
799 this.errorHandler(err);
804 } else if (this.request.status == 200 &&
805 this.request.responseXML == null) {
806 if (this.request.responseText != null) {
808 var json = eval("(" + this.request.responseText + ")");
809 this.callback(json, "json");
811 var err = new Error("XML response is empty but no error " +
812 "for " + savedUrlForErrorReporting);
814 if (this.errorHandler) {
815 this.errorHandler(err);
820 } else if (this.request.status == 200) {
821 this.callback(this.request.responseXML);
823 var err = new Error("HTTP response not OK: "
824 + this.request.status + " - "
825 + this.request.statusText );
826 err.code = '00' + this.request.status;
827 if (this.errorHandler) {
828 this.errorHandler(err);
839 ********************************************************************************
840 ** XML HELPER FUNCTIONS ********************************************************
841 ********************************************************************************
846 if ( window.ActiveXObject) {
847 var DOMDoc = document;
849 var DOMDoc = Document.prototype;
852 DOMDoc.newXmlDoc = function ( root )
856 if (document.implementation && document.implementation.createDocument) {
857 doc = document.implementation.createDocument('', root, null);
858 } else if ( window.ActiveXObject ) {
859 doc = new ActiveXObject("MSXML2.DOMDocument");
860 doc.loadXML('<' + root + '/>');
862 throw new Error ('No XML support in this browser');
869 DOMDoc.parseXmlFromString = function ( xmlString )
873 if ( window.DOMParser ) {
874 var parser = new DOMParser();
875 doc = parser.parseFromString( xmlString, "text/xml");
876 } else if ( window.ActiveXObject ) {
877 doc = new ActiveXObject("MSXML2.DOMDocument");
878 doc.loadXML( xmlString );
880 throw new Error ("No XML parsing support in this browser.");
886 DOMDoc.transformToDoc = function (xmlDoc, xslDoc)
888 if ( window.XSLTProcessor ) {
889 var proc = new XSLTProcessor();
890 proc.importStylesheet( xslDoc );
891 return proc.transformToDocument(xmlDoc);
892 } else if ( window.ActiveXObject ) {
893 return document.parseXmlFromString(xmlDoc.transformNode(xslDoc));
895 alert( 'Unable to perform XSLT transformation in this browser' );
901 Element_removeFromDoc = function (DOM_Element)
903 DOM_Element.parentNode.removeChild(DOM_Element);
906 Element_emptyChildren = function (DOM_Element)
908 while( DOM_Element.firstChild ) {
909 DOM_Element.removeChild( DOM_Element.firstChild )
913 Element_appendTransformResult = function ( DOM_Element, xmlDoc, xslDoc )
915 if ( window.XSLTProcessor ) {
916 var proc = new XSLTProcessor();
917 proc.importStylesheet( xslDoc );
919 docFrag = proc.transformToFragment( xmlDoc, DOM_Element.ownerDocument );
920 DOM_Element.appendChild(docFrag);
921 } else if ( window.ActiveXObject ) {
922 DOM_Element.innerHTML = xmlDoc.transformNode( xslDoc );
924 alert( 'Unable to perform XSLT transformation in this browser' );
928 Element_appendTextNode = function (DOM_Element, tagName, textContent )
930 var node = DOM_Element.ownerDocument.createElement(tagName);
931 var text = DOM_Element.ownerDocument.createTextNode(textContent);
933 DOM_Element.appendChild(node);
934 node.appendChild(text);
939 Element_setTextContent = function ( DOM_Element, textContent )
941 if (typeof DOM_Element.textContent !== "undefined") {
942 DOM_Element.textContent = textContent;
943 } else if (typeof DOM_Element.innerText !== "undefined" ) {
944 DOM_Element.innerText = textContent;
946 throw new Error("Cannot set text content of the node, no such method.");
950 Element_getTextContent = function (DOM_Element)
952 if ( typeof DOM_Element.textContent != 'undefined' ) {
953 return DOM_Element.textContent;
954 } else if (typeof DOM_Element.text != 'undefined') {
955 return DOM_Element.text;
957 throw new Error("Cannot get text content of the node, no such method.");
961 Element_parseChildNodes = function (node)
964 var hasChildElems = false;
966 if (node.hasChildNodes()) {
967 var children = node.childNodes;
968 for (var i = 0; i < children.length; i++) {
969 var child = children[i];
970 if (child.nodeType == Node.ELEMENT_NODE) {
971 hasChildElems = true;
972 var nodeName = child.nodeName;
973 if (!(nodeName in parsed))
974 parsed[nodeName] = [];
975 parsed[nodeName].push(Element_parseChildNodes(child));
980 var attrs = node.attributes;
981 for (var i = 0; i < attrs.length; i++) {
982 var attrName = '@' + attrs[i].nodeName;
983 var attrValue = attrs[i].nodeValue;
984 parsed[attrName] = attrValue;
987 // if no nested elements, get text content
988 if (node.hasChildNodes() && !hasChildElems) {
989 if (node.attributes.length)
990 parsed['#text'] = node.firstChild.nodeValue;
992 parsed = node.firstChild.nodeValue;
998 /* do not remove trailing bracket */