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.initStatusOK = false;
73 this.pingStatusOK = false;
74 this.searchStatusOK = false;
77 this.currentSort = "relevance";
80 this.currentStart = 0;
83 // last full record retrieved
84 this.currRecID = null;
87 this.currQuery = null;
89 //current raw record offset
90 this.currRecOffset = null;
93 this.statTime = paramArray.stattime || 1000;
94 this.statTimer = null;
95 this.termTime = paramArray.termtime || 1000;
96 this.termTimer = null;
97 this.showTime = paramArray.showtime || 1000;
98 this.showTimer = null;
99 this.showFastCount = 4;
100 this.bytargetTime = paramArray.bytargettime || 1000;
101 this.bytargetTimer = null;
102 this.recordTime = paramArray.recordtime || 500;
103 this.recordTimer = null;
105 // counters for each command and applied delay
106 this.dumpFactor = 500;
107 this.showCounter = 0;
108 this.termCounter = 0;
109 this.statCounter = 0;
110 this.bytargetCounter = 0;
111 this.recordCounter = 0;
113 // active clients, updated by stat and show
114 // might be an issue since bytarget will poll accordingly
115 this.activeClients = 1;
117 // if in proxy mode no need to init
118 if (paramArray.usesessions != undefined) {
119 this.useSessions = paramArray.usesessions;
120 this.initStatusOK = true;
122 // else, auto init session or wait for a user init?
123 if (this.useSessions && paramArray.autoInit !== false) {
130 //error handler for async error throws
131 throwError: function (errMsg, errCode)
133 var err = new Error(errMsg);
134 if (errCode) err.code = errCode;
136 if (this.errorHandler) {
137 this.errorHandler(err);
144 // stop activity by clearing tiemouts
147 clearTimeout(this.statTimer);
148 clearTimeout(this.showTimer);
149 clearTimeout(this.termTimer);
150 clearTimeout(this.bytargetTimer);
153 // reset status variables
156 if ( this.useSessions ) {
157 this.sessionID = null;
158 this.initStatusOK = false;
159 this.pingStatusOK = false;
161 this.searchStatusOK = false;
164 if ( this.resetCallback )
165 this.resetCallback();
168 init: function ( sessionId )
172 // session id as a param
173 if ( sessionId != undefined && this.useSessions ) {
174 this.initStatusOK = true;
175 this.sessionID = sessionId;
177 // old school direct pazpar2 init
178 } else if (this.useSessions) {
180 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
182 { "command": "init" },
184 if ( data.getElementsByTagName("status")[0]
185 .childNodes[0].nodeValue == "OK" ) {
186 if ( data.getElementsByTagName("protocol")[0]
187 .childNodes[0].nodeValue
188 != context.suppProtoVer )
190 "Server's protocol not supported by the client"
192 context.initStatusOK = true;
194 data.getElementsByTagName("session")[0]
195 .childNodes[0].nodeValue;
202 if ( context.initCallback )
203 context.initCallback();
206 context.throwError('Init failed. Malformed WS resonse.',
210 // when through proxy no need to init
212 this.initStatusOK = true;
215 // no need to ping explicitly
218 // pinging only makes sense when using pazpar2 directly
219 if( !this.initStatusOK || !this.useSessions )
221 'Pz2.js: Ping not allowed (proxy mode) or session not initialized.'
224 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
226 { "command": "ping", "session": this.sessionID },
228 if ( data.getElementsByTagName("status")[0]
229 .childNodes[0].nodeValue == "OK" ) {
230 context.pingStatusOK = true;
239 context.throwError('Ping failed. Malformed WS resonse.',
244 search: function (query, num, sort, filter, showfrom, addParamsArr)
246 clearTimeout(this.statTimer);
247 clearTimeout(this.showTimer);
248 clearTimeout(this.termTimer);
249 clearTimeout(this.bytargetTimer);
251 this.showCounter = 0;
252 this.termCounter = 0;
253 this.bytargetCounter = 0;
254 this.statCounter = 0;
255 this.activeClients = 1;
258 if( !this.initStatusOK )
259 throw new Error('Pz2.js: session not initialized.');
261 if( query !== undefined )
262 this.currQuery = query;
264 throw new Error("Pz2.js: no query supplied to the search command.");
266 if ( showfrom !== undefined )
267 var start = showfrom;
273 "query": this.currQuery,
274 "session": this.sessionID
277 if (filter !== undefined)
278 searchParams["filter"] = filter;
280 // copy additional parmeters, do not overwrite
281 if (addParamsArr != undefined) {
282 for (var prop in addParamsArr) {
283 if (!searchParams.hasOwnProperty(prop))
284 searchParams[prop] = addParamsArr[prop];
289 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
293 if ( data.getElementsByTagName("status")[0]
294 .childNodes[0].nodeValue == "OK" ) {
295 context.searchStatusOK = true;
297 context.show(start, num, sort);
298 if (context.statCallback)
300 if (context.termlistCallback)
302 if (context.bytargetCallback)
306 context.throwError('Search failed. Malformed WS resonse.',
313 if( !this.initStatusOK )
314 throw new Error('Pz2.js: session not initialized.');
316 // if called explicitly takes precedence
317 clearTimeout(this.statTimer);
320 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
322 { "command": "stat", "session": this.sessionID },
324 if ( data.getElementsByTagName("stat") ) {
326 Number( data.getElementsByTagName("activeclients")[0]
327 .childNodes[0].nodeValue );
328 context.activeClients = activeClients;
330 var stat = Element_parseChildNodes(data.documentElement);
332 context.statCounter++;
333 var delay = context.statTime
334 + context.statCounter * context.dumpFactor;
336 if ( activeClients > 0 )
344 context.statCallback(stat);
347 context.throwError('Stat failed. Malformed WS resonse.',
352 show: function(start, num, sort)
354 if( !this.searchStatusOK && this.useSessions )
356 'Pz2.js: show command has to be preceded with a search command.'
359 // if called explicitly takes precedence
360 clearTimeout(this.showTimer);
362 if( sort !== undefined )
363 this.currentSort = sort;
364 if( start !== undefined )
365 this.currentStart = Number( start );
366 if( num !== undefined )
367 this.currentNum = Number( num );
370 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
374 "session": this.sessionID,
375 "start": this.currentStart,
376 "num": this.currentNum,
377 "sort": this.currentSort,
379 "type": this.showResponseType
381 function(data, type) {
383 if (type === "json") {
385 context.activeClients = Number(data.activeclients[0]);
386 show.activeclients = context.activeclients;
387 show.merged = Number(data.merged[0]);
388 show.total = Number(data.total[0]);
389 show.start = Number(data.start[0]);
390 show.num = Number(data.num[0]);
391 show.hits = data.hit;
392 } else if (data.getElementsByTagName("status")[0]
393 .childNodes[0].nodeValue == "OK") {
394 // first parse the status data send along with records
395 // this is strictly bound to the format
397 Number(data.getElementsByTagName("activeclients")[0]
398 .childNodes[0].nodeValue);
399 context.activeClients = activeClients;
401 "activeclients": activeClients,
403 Number( data.getElementsByTagName("merged")[0]
404 .childNodes[0].nodeValue ),
406 Number( data.getElementsByTagName("total")[0]
407 .childNodes[0].nodeValue ),
409 Number( data.getElementsByTagName("start")[0]
410 .childNodes[0].nodeValue ),
412 Number( data.getElementsByTagName("num")[0]
413 .childNodes[0].nodeValue ),
416 // parse all the first-level nodes for all <hit> tags
417 var hits = data.getElementsByTagName("hit");
418 for (i = 0; i < hits.length; i++)
419 show.hits[i] = Element_parseChildNodes(hits[i]);
421 context.throwError('Show failed. Malformed WS resonse.',
424 context.showCounter++;
425 var delay = context.showTime;
426 if (context.showCounter > context.showFastCount)
427 delay += context.showCounter * context.dumpFactor;
428 if ( activeClients > 0 )
429 context.showTimer = setTimeout(
435 context.showCallback(show);
439 record: function(id, offset, syntax, handler)
441 // we may call record with no previous search if in proxy mode
442 if(!this.searchStatusOK && this.useSessions)
444 'Pz2.js: record command has to be preceded with a search command.'
447 if( id !== undefined )
452 "session": this.sessionID,
456 this.currRecOffset = null;
457 if (offset != undefined) {
458 recordParams["offset"] = offset;
459 this.currRecOffset = offset;
462 if (syntax != undefined)
463 recordParams['syntax'] = syntax;
465 //overwrite default callback id needed
466 var callback = this.recordCallback;
467 var args = undefined;
468 if (handler != undefined) {
469 callback = handler['callback'];
470 args = handler['args'];
474 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
482 if (context.currRecOffset !== null) {
483 record = new Array();
484 record['xmlDoc'] = data;
485 record['offset'] = context.currRecOffset;
486 callback(record, args);
488 } else if ( recordNode =
489 data.getElementsByTagName("record")[0] ) {
490 // if stylesheet was fetched do not parse the response
491 if ( context.xslDoc ) {
492 record = new Array();
493 record['xmlDoc'] = data;
494 record['xslDoc'] = context.xslDoc;
496 recordNode.getElementsByTagName("recid")[0]
497 .firstChild.nodeValue;
500 record = Element_parseChildNodes(recordNode);
503 Number( data.getElementsByTagName("activeclients")[0]
504 .childNodes[0].nodeValue );
505 context.activeClients = activeClients;
506 context.recordCounter++;
507 var delay = context.recordTime + context.recordCounter * context.dumpFactor;
508 if ( activeClients > 0 )
509 context.recordTimer =
512 context.record(id, offset, syntax, handler);
516 callback(record, args);
519 context.throwError('Record failed. Malformed WS resonse.',
527 if( !this.searchStatusOK && this.useSessions )
529 'Pz2.js: termlist command has to be preceded with a search command.'
532 // if called explicitly takes precedence
533 clearTimeout(this.termTimer);
536 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
539 "command": "termlist",
540 "session": this.sessionID,
541 "name": this.termKeys
544 if ( data.getElementsByTagName("termlist") ) {
546 Number( data.getElementsByTagName("activeclients")[0]
547 .childNodes[0].nodeValue );
548 context.activeClients = activeClients;
549 var termList = { "activeclients": activeClients };
550 var termLists = data.getElementsByTagName("list");
552 for (i = 0; i < termLists.length; i++) {
553 var listName = termLists[i].getAttribute('name');
554 termList[listName] = new Array();
555 var terms = termLists[i].getElementsByTagName('term');
556 //for each term in the list
557 for (j = 0; j < terms.length; j++) {
560 (terms[j].getElementsByTagName("name")[0]
562 ? terms[j].getElementsByTagName("name")[0]
563 .childNodes[0].nodeValue
567 .getElementsByTagName("frequency")[0]
568 .childNodes[0].nodeValue || 'ERROR'
572 terms[j].getElementsByTagName("id");
573 if(terms[j].getElementsByTagName("id").length)
575 termIdNode[0].childNodes[0].nodeValue;
576 termList[listName][j] = term;
580 context.termCounter++;
581 var delay = context.termTime
582 + context.termCounter * context.dumpFactor;
583 if ( activeClients > 0 )
592 context.termlistCallback(termList);
595 context.throwError('Termlist failed. Malformed WS resonse.',
603 if( !this.initStatusOK && this.useSessions )
605 'Pz2.js: bytarget command has to be preceded with a search command.'
608 // no need to continue
609 if( !this.searchStatusOK )
612 // if called explicitly takes precedence
613 clearTimeout(this.bytargetTimer);
616 var request = new pzHttpRequest(this.pz2String, this.errorHandler);
618 { "command": "bytarget", "session": this.sessionID },
620 if ( data.getElementsByTagName("status")[0]
621 .childNodes[0].nodeValue == "OK" ) {
622 var targetNodes = data.getElementsByTagName("target");
623 var bytarget = new Array();
624 for ( i = 0; i < targetNodes.length; i++) {
625 bytarget[i] = new Array();
626 for( j = 0; j < targetNodes[i].childNodes.length; j++ ) {
627 if ( targetNodes[i].childNodes[j].nodeType
628 == Node.ELEMENT_NODE ) {
630 targetNodes[i].childNodes[j].nodeName;
632 targetNodes[i].childNodes[j]
633 .firstChild.nodeValue;
634 bytarget[i][nodeName] = nodeText;
639 context.bytargetCounter++;
640 var delay = context.bytargetTime
641 + context.bytargetCounter * context.dumpFactor;
642 if ( context.activeClients > 0 )
643 context.bytargetTimer =
651 context.bytargetCallback(bytarget);
654 context.throwError('Bytarget failed. Malformed WS resonse.',
660 // just for testing, probably shouldn't be here
661 showNext: function(page)
663 var step = page || 1;
664 this.show( ( step * this.currentNum ) + this.currentStart );
667 showPrev: function(page)
669 if (this.currentStart == 0 )
671 var step = page || 1;
672 var newStart = this.currentStart - (step * this.currentNum );
673 this.show( newStart > 0 ? newStart : 0 );
676 showPage: function(pageNum)
678 //var page = pageNum || 1;
679 this.show(pageNum * this.currentNum);
684 ********************************************************************************
685 ** AJAX HELPER CLASS ***********************************************************
686 ********************************************************************************
688 var pzHttpRequest = function ( url, errorHandler ) {
689 this.maxUrlLength = 2048;
692 this.errorHandler = errorHandler || null;
694 this.requestHeaders = {};
696 if ( window.XMLHttpRequest ) {
697 this.request = new XMLHttpRequest();
698 } else if ( window.ActiveXObject ) {
700 this.request = new ActiveXObject( 'Msxml2.XMLHTTP' );
702 this.request = new ActiveXObject( 'Microsoft.XMLHTTP' );
707 pzHttpRequest.prototype =
709 safeGet: function ( params, callback )
711 var encodedParams = this.encodeParams(params);
712 var url = this._urlAppendParams(encodedParams);
713 if (url.length >= this.maxUrlLength) {
714 this.requestHeaders["Content-Type"]
715 = "application/x-www-form-urlencoded";
716 this._send( 'POST', this.url, encodedParams, callback );
718 this._send( 'GET', url, '', callback );
722 get: function ( params, callback )
724 this._send( 'GET', this._urlAppendParams(this.encodeParams(params)),
728 post: function ( params, data, callback )
730 this._send( 'POST', this._urlAppendParams(this.encodeParams(params)),
737 this.request.open( 'GET', this.url, this.async );
738 this.request.send('');
739 if ( this.request.status == 200 )
740 return this.request.responseXML;
743 encodeParams: function (params)
747 for (var key in params) {
748 if (params[key] != null) {
749 encoded += sep + key + '=' + encodeURIComponent(params[key]);
756 _send: function ( type, url, data, callback)
759 this.callback = callback;
761 this.request.open( type, url, this.async );
762 for (var key in this.requestHeaders)
763 this.request.setRequestHeader(key, this.requestHeaders[key]);
764 this.request.onreadystatechange = function () {
765 context._handleResponse(url); /// url used ONLY for error reporting
767 this.request.send(data);
770 _urlAppendParams: function (encodedParams)
773 return this.url + "?" + encodedParams;
778 _handleResponse: function (savedUrlForErrorReporting)
780 if ( this.request.readyState == 4 ) {
781 // pick up appplication errors first
783 if (this.request.responseXML &&
784 (errNode = this.request.responseXML.documentElement)
785 && errNode.nodeName == 'error') {
786 var errMsg = errNode.getAttribute("msg");
787 var errCode = errNode.getAttribute("code");
789 if (errNode.childNodes.length)
790 errAddInfo = ': ' + errNode.childNodes[0].nodeValue;
792 var err = new Error(errMsg + errAddInfo);
795 if (this.errorHandler) {
796 this.errorHandler(err);
801 } else if (this.request.status == 200 &&
802 this.request.responseXML == null) {
803 if (this.request.responseText != null) {
805 var json = eval("(" + this.request.responseText + ")");
806 this.callback(json, "json");
808 var err = new Error("XML response is empty but no error " +
809 "for " + savedUrlForErrorReporting);
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;
824 if (this.errorHandler) {
825 this.errorHandler(err);
836 ********************************************************************************
837 ** XML HELPER FUNCTIONS ********************************************************
838 ********************************************************************************
843 if ( window.ActiveXObject) {
844 var DOMDoc = document;
846 var DOMDoc = Document.prototype;
849 DOMDoc.newXmlDoc = function ( root )
853 if (document.implementation && document.implementation.createDocument) {
854 doc = document.implementation.createDocument('', root, null);
855 } else if ( window.ActiveXObject ) {
856 doc = new ActiveXObject("MSXML2.DOMDocument");
857 doc.loadXML('<' + root + '/>');
859 throw new Error ('No XML support in this browser');
866 DOMDoc.parseXmlFromString = function ( xmlString )
870 if ( window.DOMParser ) {
871 var parser = new DOMParser();
872 doc = parser.parseFromString( xmlString, "text/xml");
873 } else if ( window.ActiveXObject ) {
874 doc = new ActiveXObject("MSXML2.DOMDocument");
875 doc.loadXML( xmlString );
877 throw new Error ("No XML parsing support in this browser.");
883 DOMDoc.transformToDoc = function (xmlDoc, xslDoc)
885 if ( window.XSLTProcessor ) {
886 var proc = new XSLTProcessor();
887 proc.importStylesheet( xslDoc );
888 return proc.transformToDocument(xmlDoc);
889 } else if ( window.ActiveXObject ) {
890 return document.parseXmlFromString(xmlDoc.transformNode(xslDoc));
892 alert( 'Unable to perform XSLT transformation in this browser' );
898 Element_removeFromDoc = function (DOM_Element)
900 DOM_Element.parentNode.removeChild(DOM_Element);
903 Element_emptyChildren = function (DOM_Element)
905 while( DOM_Element.firstChild ) {
906 DOM_Element.removeChild( DOM_Element.firstChild )
910 Element_appendTransformResult = function ( DOM_Element, xmlDoc, xslDoc )
912 if ( window.XSLTProcessor ) {
913 var proc = new XSLTProcessor();
914 proc.importStylesheet( xslDoc );
916 docFrag = proc.transformToFragment( xmlDoc, DOM_Element.ownerDocument );
917 DOM_Element.appendChild(docFrag);
918 } else if ( window.ActiveXObject ) {
919 DOM_Element.innerHTML = xmlDoc.transformNode( xslDoc );
921 alert( 'Unable to perform XSLT transformation in this browser' );
925 Element_appendTextNode = function (DOM_Element, tagName, textContent )
927 var node = DOM_Element.ownerDocument.createElement(tagName);
928 var text = DOM_Element.ownerDocument.createTextNode(textContent);
930 DOM_Element.appendChild(node);
931 node.appendChild(text);
936 Element_setTextContent = function ( DOM_Element, textContent )
938 if (typeof DOM_Element.textContent !== "undefined") {
939 DOM_Element.textContent = textContent;
940 } else if (typeof DOM_Element.innerText !== "undefined" ) {
941 DOM_Element.innerText = textContent;
943 throw new Error("Cannot set text content of the node, no such method.");
947 Element_getTextContent = function (DOM_Element)
949 if ( typeof DOM_Element.textContent != 'undefined' ) {
950 return DOM_Element.textContent;
951 } else if (typeof DOM_Element.text != 'undefined') {
952 return DOM_Element.text;
954 throw new Error("Cannot get text content of the node, no such method.");
958 Element_parseChildNodes = function (node)
961 var hasChildElems = false;
963 if (node.hasChildNodes()) {
964 var children = node.childNodes;
965 for (var i = 0; i < children.length; i++) {
966 var child = children[i];
967 if (child.nodeType == Node.ELEMENT_NODE) {
968 hasChildElems = true;
969 var nodeName = child.nodeName;
970 if (!(nodeName in parsed))
971 parsed[nodeName] = [];
972 parsed[nodeName].push(Element_parseChildNodes(child));
977 var attrs = node.attributes;
978 for (var i = 0; i < attrs.length; i++) {
979 var attrName = '@' + attrs[i].nodeName;
980 var attrValue = attrs[i].nodeValue;
981 parsed[attrName] = attrValue;
984 // if no nested elements, get text content
985 if (node.hasChildNodes() && !hasChildElems) {
986 if (node.attributes.length)
987 parsed['#text'] = node.firstChild.nodeValue;
989 parsed = node.firstChild.nodeValue;
995 /* do not remove trailing bracket */