5.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
5.2 +++ b/examples/Common/Dictionary/Resources/scripts/sarissa.js Fri Sep 09 17:33:19 2005 +0000
5.3 @@ -0,0 +1,616 @@
5.4 +/**
5.5 + * ====================================================================
5.6 + * About
5.7 + * ====================================================================
5.8 + * Sarissa cross browser XML library
5.9 + * @version 0.9.6
5.10 + * @author: Manos Batsis, mailto: mbatsis at users full stop sourceforge full stop net
5.11 + *
5.12 + * Sarissa is an ECMAScript library acting as a cross-browser wrapper for native XML APIs.
5.13 + * The library supports Gecko based browsers like Mozilla and Firefox,
5.14 + * Internet Explorer (5.5+ with MSXML3.0+) and, last but not least, KHTML based browsers like
5.15 + * Konqueror and Safari.
5.16 + *
5.17 + * ====================================================================
5.18 + * Licence
5.19 + * ====================================================================
5.20 + * This program is free software; you can redistribute it and/or modify
5.21 + * it under the terms of the GNU General Public License version 2 or
5.22 + * the GNU Lesser General Public License version 2.1 as published by
5.23 + * the Free Software Foundation (your choice of the two).
5.24 + *
5.25 + * This program is distributed in the hope that it will be useful,
5.26 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
5.27 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
5.28 + * GNU General Public License or GNU Lesser General Public License for more details.
5.29 + *
5.30 + * You should have received a copy of the GNU General Public License
5.31 + * or GNU Lesser General Public License along with this program; if not,
5.32 + * write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
5.33 + * or visit http://www.gnu.org
5.34 + *
5.35 + */
5.36 +/**
5.37 + * <p>Sarissa is a utility class. Provides static methods for DOMDocument and
5.38 + * XMLHTTP objects, DOM Node serializatrion to XML strings and other goodies.</p>
5.39 + * @constructor
5.40 + */
5.41 +function Sarissa(){};
5.42 +/** @private */
5.43 +Sarissa.PARSED_OK = "Document contains no parsing errors";
5.44 +/**
5.45 + * Tells you whether transformNode and transformNodeToObject are available. This functionality
5.46 + * is contained in sarissa_ieemu_xslt.js and is deprecated. If you want to control XSLT transformations
5.47 + * use the XSLTProcessor
5.48 + * @deprecated
5.49 + * @type boolean
5.50 + */
5.51 +Sarissa.IS_ENABLED_TRANSFORM_NODE = false;
5.52 +/**
5.53 + * tells you whether XMLHttpRequest (or equivalent) is available
5.54 + * @type boolean
5.55 + */
5.56 +Sarissa.IS_ENABLED_XMLHTTP = false;
5.57 +/**
5.58 + * tells you whether selectNodes/selectSingleNode is available
5.59 + * @type boolean
5.60 + */
5.61 +Sarissa.IS_ENABLED_SELECT_NODES = false;
5.62 +var _sarissa_iNsCounter = 0;
5.63 +var _SARISSA_IEPREFIX4XSLPARAM = "";
5.64 +var _SARISSA_HAS_DOM_IMPLEMENTATION = document.implementation && true;
5.65 +var _SARISSA_HAS_DOM_CREATE_DOCUMENT = _SARISSA_HAS_DOM_IMPLEMENTATION && document.implementation.createDocument;
5.66 +var _SARISSA_HAS_DOM_FEATURE = _SARISSA_HAS_DOM_IMPLEMENTATION && document.implementation.hasFeature;
5.67 +var _SARISSA_IS_MOZ = _SARISSA_HAS_DOM_CREATE_DOCUMENT && _SARISSA_HAS_DOM_FEATURE;
5.68 +var _SARISSA_IS_SAFARI = navigator.userAgent.toLowerCase().indexOf("applewebkit") != -1;
5.69 +var _SARISSA_IS_IE = document.all && window.ActiveXObject && navigator.userAgent.toLowerCase().indexOf("msie") > -1 && navigator.userAgent.toLowerCase().indexOf("opera") == -1;
5.70 +
5.71 +if(!window.Node || !window.Node.ELEMENT_NODE){
5.72 + var Node = {ELEMENT_NODE: 1, ATTRIBUTE_NODE: 2, TEXT_NODE: 3, CDATA_SECTION_NODE: 4, ENTITY_REFERENCE_NODE: 5, ENTITY_NODE: 6, PROCESSING_INSTRUCTION_NODE: 7, COMMENT_NODE: 8, DOCUMENT_NODE: 9, DOCUMENT_TYPE_NODE: 10, DOCUMENT_FRAGMENT_NODE: 11, NOTATION_NODE: 12};
5.73 +};
5.74 +
5.75 +// IE initialization
5.76 +if(_SARISSA_IS_IE){
5.77 + // for XSLT parameter names, prefix needed by IE
5.78 + _SARISSA_IEPREFIX4XSLPARAM = "xsl:";
5.79 + // used to store the most recent ProgID available out of the above
5.80 + var _SARISSA_DOM_PROGID = "";
5.81 + var _SARISSA_XMLHTTP_PROGID = "";
5.82 + /**
5.83 + * Called when the Sarissa_xx.js file is parsed, to pick most recent
5.84 + * ProgIDs for IE, then gets destroyed.
5.85 + * @param idList an array of MSXML PROGIDs from which the most recent will be picked for a given object
5.86 + * @param enabledList an array of arrays where each array has two items; the index of the PROGID for which a certain feature is enabled
5.87 + */
5.88 + pickRecentProgID = function (idList, enabledList){
5.89 + // found progID flag
5.90 + var bFound = false;
5.91 + for(var i=0; i < idList.length && !bFound; i++){
5.92 + try{
5.93 + var oDoc = new ActiveXObject(idList[i]);
5.94 + o2Store = idList[i];
5.95 + bFound = true;
5.96 + for(var j=0;j<enabledList.length;j++)
5.97 + if(i <= enabledList[j][1])
5.98 + Sarissa["IS_ENABLED_"+enabledList[j][0]] = true;
5.99 + }catch (objException){
5.100 + // trap; try next progID
5.101 + };
5.102 + };
5.103 + if (!bFound)
5.104 + throw "Could not retreive a valid progID of Class: " + idList[idList.length-1]+". (original exception: "+e+")";
5.105 + idList = null;
5.106 + return o2Store;
5.107 + };
5.108 + // pick best available MSXML progIDs
5.109 + _SARISSA_DOM_PROGID = pickRecentProgID(["Msxml2.DOMDocument.5.0", "Msxml2.DOMDocument.4.0", "Msxml2.DOMDocument.3.0", "MSXML2.DOMDocument", "MSXML.DOMDocument", "Microsoft.XMLDOM"], [["SELECT_NODES", 2],["TRANSFORM_NODE", 2]]);
5.110 + _SARISSA_XMLHTTP_PROGID = pickRecentProgID(["Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"], [["XMLHTTP", 4]]);
5.111 + _SARISSA_THREADEDDOM_PROGID = pickRecentProgID(["Msxml2.FreeThreadedDOMDocument.5.0", "MSXML2.FreeThreadedDOMDocument.4.0", "MSXML2.FreeThreadedDOMDocument.3.0"]);
5.112 + _SARISSA_XSLTEMPLATE_PROGID = pickRecentProgID(["Msxml2.XSLTemplate.5.0", "Msxml2.XSLTemplate.4.0", "MSXML2.XSLTemplate.3.0"], [["XSLTPROC", 2]]);
5.113 + // we dont need this anymore
5.114 + pickRecentProgID = null;
5.115 + //============================================
5.116 + // Factory methods (IE)
5.117 + //============================================
5.118 + // see non-IE version
5.119 + Sarissa.getDomDocument = function(sUri, sName){
5.120 + var oDoc = new ActiveXObject(_SARISSA_DOM_PROGID);
5.121 + // if a root tag name was provided, we need to load it in the DOM
5.122 + // object
5.123 + if (sName){
5.124 + // if needed, create an artifical namespace prefix the way Moz
5.125 + // does
5.126 + if (sUri){
5.127 + oDoc.loadXML("<a" + _sarissa_iNsCounter + ":" + sName + " xmlns:a" + _sarissa_iNsCounter + "=\"" + sUri + "\" />");
5.128 + // don't use the same prefix again
5.129 + ++_sarissa_iNsCounter;
5.130 + }
5.131 + else
5.132 + oDoc.loadXML("<" + sName + "/>");
5.133 + };
5.134 + return oDoc;
5.135 + };
5.136 + // see non-IE version
5.137 + Sarissa.getParseErrorText = function (oDoc) {
5.138 + var parseErrorText = Sarissa.PARSED_OK;
5.139 + if(oDoc.parseError != 0){
5.140 + parseErrorText = "XML Parsing Error: " + oDoc.parseError.reason +
5.141 + "\nLocation: " + oDoc.parseError.url +
5.142 + "\nLine Number " + oDoc.parseError.line + ", Column " +
5.143 + oDoc.parseError.linepos +
5.144 + ":\n" + oDoc.parseError.srcText +
5.145 + "\n";
5.146 + for(var i = 0; i < oDoc.parseError.linepos;i++){
5.147 + parseErrorText += "-";
5.148 + };
5.149 + parseErrorText += "^\n";
5.150 + };
5.151 + return parseErrorText;
5.152 + };
5.153 + // see non-IE version
5.154 + Sarissa.setXpathNamespaces = function(oDoc, sNsSet) {
5.155 + oDoc.setProperty("SelectionLanguage", "XPath");
5.156 + oDoc.setProperty("SelectionNamespaces", sNsSet);
5.157 + };
5.158 + /**
5.159 + * Basic implementation of Mozilla's XSLTProcessor for IE.
5.160 + * Reuses the same XSLT stylesheet for multiple transforms
5.161 + * @constructor
5.162 + */
5.163 + XSLTProcessor = function(){
5.164 + this.template = new ActiveXObject(_SARISSA_XSLTEMPLATE_PROGID);
5.165 + this.processor = null;
5.166 + };
5.167 + /**
5.168 + * Impoprts the given XSLT DOM and compiles it to a reusable transform
5.169 + * @argument xslDoc The XSLT DOMDocument to import
5.170 + */
5.171 + XSLTProcessor.prototype.importStylesheet = function(xslDoc){
5.172 + // convert stylesheet to free threaded
5.173 + var converted = new ActiveXObject(_SARISSA_THREADEDDOM_PROGID);
5.174 + converted.loadXML(xslDoc.xml);
5.175 + this.template.stylesheet = converted;
5.176 + this.processor = this.template.createProcessor();
5.177 + // (re)set default param values
5.178 + this.paramsSet = new Array();
5.179 + };
5.180 + /**
5.181 + * Transform the given XML DOM
5.182 + * @argument sourceDoc The XML DOMDocument to transform
5.183 + * @return The transformation result as a DOM Document
5.184 + */
5.185 + XSLTProcessor.prototype.transformToDocument = function(sourceDoc){
5.186 + this.processor.input = sourceDoc;
5.187 + var outDoc = new ActiveXObject(_SARISSA_DOM_PROGID);
5.188 + this.processor.output = outDoc;
5.189 + this.processor.transform();
5.190 + return outDoc;
5.191 + };
5.192 + /**
5.193 + * Not sure if this works in IE. Maybe this will allow non-well-formed
5.194 + * transformation results (i.e. with no single root element)
5.195 + * @argument sourceDoc The XML DOMDocument to transform
5.196 + * @return The transformation result as a DOM Fragment
5.197 + */
5.198 + XSLTProcessor.prototype.transformToFragment = function(sourceDoc, ownerDocument){
5.199 + return this.transformToDocument(sourceDoc);
5.200 + };
5.201 + /**
5.202 + * Set global XSLT parameter of the imported stylesheet
5.203 + * @argument nsURI The parameter namespace URI
5.204 + * @argument name The parameter base name
5.205 + * @argument value The new parameter value
5.206 + */
5.207 + XSLTProcessor.prototype.setParameter = function(nsURI, name, value){
5.208 + /* nsURI is optional but cannot be null */
5.209 + if(nsURI){
5.210 + this.processor.addParameter(name, value, nsURI);
5.211 + }else{
5.212 + this.processor.addParameter(name, value);
5.213 + };
5.214 + /* update updated params for getParameter */
5.215 + if(!this.paramsSet[""+nsURI]){
5.216 + this.paramsSet[""+nsURI] = new Array();
5.217 + };
5.218 + this.paramsSet[""+nsURI][name] = value;
5.219 + };
5.220 + /**
5.221 + * Gets a parameter if previously set by setParameter. Returns null
5.222 + * otherwise
5.223 + * @argument name The parameter base name
5.224 + * @argument value The new parameter value
5.225 + * @return The parameter value if reviously set by setParameter, null otherwise
5.226 + */
5.227 + XSLTProcessor.prototype.getParameter = function(nsURI, name){
5.228 + if(this.paramsSet[""+nsURI] && this.paramsSet[""+nsURI][name])
5.229 + return this.paramsSet[""+nsURI][name];
5.230 + else
5.231 + return null;
5.232 + };
5.233 +}
5.234 +else{ /* end IE initialization, try to deal with real browsers now ;-) */
5.235 + if(_SARISSA_HAS_DOM_CREATE_DOCUMENT){
5.236 + if(window.XMLDocument){
5.237 + /**
5.238 + * <p>Emulate IE's onreadystatechange attribute</p>
5.239 + */
5.240 + XMLDocument.prototype.onreadystatechange = null;
5.241 + /**
5.242 + * <p>Emulates IE's readyState property, which always gives an integer from 0 to 4:</p>
5.243 + * <ul><li>1 == LOADING,</li>
5.244 + * <li>2 == LOADED,</li>
5.245 + * <li>3 == INTERACTIVE,</li>
5.246 + * <li>4 == COMPLETED</li></ul>
5.247 + */
5.248 + XMLDocument.prototype.readyState = 0;
5.249 + /**
5.250 + * <p>Emulate IE's parseError attribute</p>
5.251 + */
5.252 + XMLDocument.prototype.parseError = 0;
5.253 +
5.254 + // NOTE: setting async to false will only work with documents
5.255 + // called over HTTP (meaning a server), not the local file system,
5.256 + // unless you are using Moz 1.4+.
5.257 + // BTW the try>catch block is for 1.4; I haven't found a way to check if
5.258 + // the property is implemented without
5.259 + // causing an error and I dont want to use user agent stuff for that...
5.260 + var _SARISSA_SYNC_NON_IMPLEMENTED = false;
5.261 + try{
5.262 + /**
5.263 + * <p>Emulates IE's async property for Moz versions prior to 1.4.
5.264 + * It controls whether loading of remote XML files works
5.265 + * synchronously or asynchronously.</p>
5.266 + */
5.267 + XMLDocument.prototype.async = true;
5.268 + _SARISSA_SYNC_NON_IMPLEMENTED = true;
5.269 + }catch(e){/* trap */};
5.270 + /**
5.271 + * <p>Keeps a handle to the original load() method. Internal use and only
5.272 + * if Mozilla version is lower than 1.4</p>
5.273 + * @private
5.274 + */
5.275 + XMLDocument.prototype._sarissa_load = XMLDocument.prototype.load;
5.276 +
5.277 + /**
5.278 + * <p>Overrides the original load method to provide synchronous loading for
5.279 + * Mozilla versions prior to 1.4, using an XMLHttpRequest object (if
5.280 + * async is set to false)</p>
5.281 + * @returns the DOM Object as it was before the load() call (may be empty)
5.282 + */
5.283 + XMLDocument.prototype.load = function(sURI) {
5.284 + var oDoc = document.implementation.createDocument("", "", null);
5.285 + Sarissa.copyChildNodes(this, oDoc);
5.286 + this.parseError = 0;
5.287 + Sarissa.__setReadyState__(this, 1);
5.288 + try {
5.289 + if(this.async == false && _SARISSA_SYNC_NON_IMPLEMENTED) {
5.290 + var tmp = new XMLHttpRequest();
5.291 + tmp.open("GET", sURI, false);
5.292 + tmp.send(null);
5.293 + Sarissa.__setReadyState__(this, 2);
5.294 + Sarissa.copyChildNodes(tmp.responseXML, this);
5.295 + Sarissa.__setReadyState__(this, 3);
5.296 + }
5.297 + else {
5.298 + this._sarissa_load(sURI);
5.299 + };
5.300 + }
5.301 + catch (objException) {
5.302 + this.parseError = -1;
5.303 + }
5.304 + finally {
5.305 + if(this.async == false){
5.306 + Sarissa.__handleLoad__(this);
5.307 + };
5.308 + };
5.309 + return oDoc;
5.310 + };
5.311 + };//if(window.XMLDocument)
5.312 +
5.313 + /**
5.314 + * <p>Ensures the document was loaded correctly, otherwise sets the
5.315 + * parseError to -1 to indicate something went wrong. Internal use</p>
5.316 + * @private
5.317 + */
5.318 + Sarissa.__handleLoad__ = function(oDoc){
5.319 + if (!oDoc.documentElement || oDoc.documentElement.tagName == "parsererror")
5.320 + oDoc.parseError = -1;
5.321 + Sarissa.__setReadyState__(oDoc, 4);
5.322 + };
5.323 +
5.324 + /**
5.325 + * <p>Attached by an event handler to the load event. Internal use.</p>
5.326 + * @private
5.327 + */
5.328 + _sarissa_XMLDocument_onload = function(){
5.329 + Sarissa.__handleLoad__(this);
5.330 + };
5.331 +
5.332 + /**
5.333 + * <p>Sets the readyState property of the given DOM Document object.
5.334 + * Internal use.</p>
5.335 + * @private
5.336 + * @argument oDoc the DOM Document object to fire the
5.337 + * readystatechange event
5.338 + * @argument iReadyState the number to change the readystate property to
5.339 + */
5.340 + Sarissa.__setReadyState__ = function(oDoc, iReadyState){
5.341 + oDoc.readyState = iReadyState;
5.342 + if (oDoc.onreadystatechange != null && typeof oDoc.onreadystatechange == "function")
5.343 + oDoc.onreadystatechange();
5.344 + };
5.345 + /**
5.346 + * <p>Factory method to obtain a new DOM Document object</p>
5.347 + * @argument sUri the namespace of the root node (if any)
5.348 + * @argument sUri the local name of the root node (if any)
5.349 + * @returns a new DOM Document
5.350 + */
5.351 + Sarissa.getDomDocument = function(sUri, sName){
5.352 + var oDoc = document.implementation.createDocument(sUri?sUri:"", sName?sName:"", null);
5.353 + oDoc.addEventListener("load", _sarissa_XMLDocument_onload, false);
5.354 + return oDoc;
5.355 + };
5.356 + };//if(_SARISSA_HAS_DOM_CREATE_DOCUMENT)
5.357 +};
5.358 +//==========================================
5.359 +// Common stuff
5.360 +//==========================================
5.361 +if(!window.DOMParser){
5.362 + /**
5.363 + * DOMParser is a utility class, used to construct DOMDocuments from XML strings
5.364 + * @constructor
5.365 + */
5.366 + DOMParser = function() {
5.367 + };
5.368 + /**
5.369 + * Construct a new DOM Document from the given XMLstring
5.370 + * @param sXml the given XML string
5.371 + * @param contentType the content type of the document the given string represents (one of text/xml, application/xml, application/xhtml+xml).
5.372 + * @return a new DOM Document from the given XML string
5.373 + */
5.374 + DOMParser.prototype.parseFromString = function(sXml, contentType){
5.375 + var doc = Sarissa.getDomDocument();
5.376 + doc.loadXML(sXml);
5.377 + return doc;
5.378 + };
5.379 +
5.380 +};
5.381 +
5.382 +if(window.XMLHttpRequest){
5.383 + Sarissa.IS_ENABLED_XMLHTTP = true;
5.384 +}
5.385 +else if(_SARISSA_IS_IE){
5.386 + /**
5.387 + * Emulate XMLHttpRequest
5.388 + * @constructor
5.389 + */
5.390 + XMLHttpRequest = function() {
5.391 + return new ActiveXObject(_SARISSA_XMLHTTP_PROGID);
5.392 + };
5.393 + Sarissa.IS_ENABLED_XMLHTTP = true;
5.394 +};
5.395 +
5.396 +if(!window.document.importNode && _SARISSA_IS_IE){
5.397 + try{
5.398 + /**
5.399 + * Implements importNode for the current window document in IE using innerHTML.
5.400 + * Testing showed that DOM was multiple times slower than innerHTML for this,
5.401 + * sorry folks. If you encounter trouble (who knows what IE does behind innerHTML)
5.402 + * please gimme a call.
5.403 + * @param oNode the Node to import
5.404 + * @param bChildren whether to include the children of oNode
5.405 + * @returns the imported node for further use
5.406 + */
5.407 + window.document.importNode = function(oNode, bChildren){
5.408 + var importNode = document.createElement("div");
5.409 + if(bChildren)
5.410 + importNode.innerHTML = Sarissa.serialize(oNode);
5.411 + else
5.412 + importNode.innerHTML = Sarissa.serialize(oNode.cloneNode(false));
5.413 + return importNode.firstChild;
5.414 + };
5.415 + }catch(e){};
5.416 +};
5.417 +if(!Sarissa.getParseErrorText){
5.418 + /**
5.419 + * <p>Returns a human readable description of the parsing error. Usefull
5.420 + * for debugging. Tip: append the returned error string in a <pre>
5.421 + * element if you want to render it.</p>
5.422 + * <p>Many thanks to Christian Stocker for the initial patch.</p>
5.423 + * @argument oDoc The target DOM document
5.424 + * @returns The parsing error description of the target Document in
5.425 + * human readable form (preformated text)
5.426 + */
5.427 + Sarissa.getParseErrorText = function (oDoc){
5.428 + var parseErrorText = Sarissa.PARSED_OK;
5.429 + if(oDoc.parseError != 0){
5.430 + /*moz*/
5.431 + if(oDoc.documentElement.tagName == "parsererror"){
5.432 + parseErrorText = oDoc.documentElement.firstChild.data;
5.433 + parseErrorText += "\n" + oDoc.documentElement.firstChild.nextSibling.firstChild.data;
5.434 + }/*konq*/
5.435 + else if(oDoc.documentElement.tagName == "html"){
5.436 + parseErrorText = Sarissa.getText(oDoc.documentElement.getElementsByTagName("h1")[0], false) + "\n";
5.437 + parseErrorText += Sarissa.getText(oDoc.documentElement.getElementsByTagName("body")[0], false) + "\n";
5.438 + parseErrorText += Sarissa.getText(oDoc.documentElement.getElementsByTagName("pre")[0], false);
5.439 + };
5.440 + };
5.441 + return parseErrorText;
5.442 + };
5.443 +};
5.444 +Sarissa.getText = function(oNode, deep){
5.445 + var s = "";
5.446 + var nodes = oNode.childNodes;
5.447 + for(var i=0; i < nodes.length; i++){
5.448 + var node = nodes[i];
5.449 + var nodeType = node.nodeType;
5.450 + if(nodeType == Node.TEXT_NODE || nodeType == Node.CDATA_SECTION_NODE){
5.451 + s += node.data;
5.452 + }
5.453 + else if(deep == true
5.454 + && (nodeType == Node.ELEMENT_NODE
5.455 + || nodeType == Node.DOCUMENT_NODE
5.456 + || nodeType == Node.DOCUMENT_FRAGMENT_NODE)){
5.457 + s += Sarissa.getText(node, true);
5.458 + };
5.459 + };
5.460 + return s;
5.461 +};
5.462 +if(window.XMLSerializer){
5.463 + /**
5.464 + * <p>Factory method to obtain the serialization of a DOM Node</p>
5.465 + * @returns the serialized Node as an XML string
5.466 + */
5.467 + Sarissa.serialize = function(oDoc){
5.468 + return (new XMLSerializer()).serializeToString(oDoc);
5.469 + };
5.470 +}else{
5.471 + if((Sarissa.getDomDocument("","foo", null)).xml){
5.472 + // see non-IE version
5.473 + Sarissa.serialize = function(oDoc) {
5.474 + // TODO: check for HTML document and return innerHTML instead
5.475 + return oDoc.xml;
5.476 + };
5.477 + /**
5.478 + * Utility class to serialize DOM Node objects to XML strings
5.479 + * @constructor
5.480 + */
5.481 + XMLSerializer = function(){};
5.482 + /**
5.483 + * Serialize the given DOM Node to an XML string
5.484 + * @param oNode the DOM Node to serialize
5.485 + */
5.486 + XMLSerializer.prototype.serializeToString = function(oNode) {
5.487 + return oNode.xml;
5.488 + };
5.489 + };
5.490 +};
5.491 +
5.492 +/**
5.493 + * strips tags from a markup string
5.494 + */
5.495 +Sarissa.stripTags = function (s) {
5.496 + return s.replace(/<[^>]+>/g,"");
5.497 +};
5.498 +/**
5.499 + * <p>Deletes all child nodes of the given node</p>
5.500 + * @argument oNode the Node to empty
5.501 + */
5.502 +Sarissa.clearChildNodes = function(oNode) {
5.503 + while(oNode.hasChildNodes()){
5.504 + oNode.removeChild(oNode.firstChild);
5.505 + };
5.506 +};
5.507 +/**
5.508 + * <p> Copies the childNodes of nodeFrom to nodeTo</p>
5.509 + * <p> <b>Note:</b> The second object's original content is deleted before
5.510 + * the copy operation, unless you supply a true third parameter</p>
5.511 + * @argument nodeFrom the Node to copy the childNodes from
5.512 + * @argument nodeTo the Node to copy the childNodes to
5.513 + * @argument bPreserveExisting whether to preserve the original content of nodeTo, default is false
5.514 + */
5.515 +Sarissa.copyChildNodes = function(nodeFrom, nodeTo, bPreserveExisting) {
5.516 + if(!bPreserveExisting){
5.517 + Sarissa.clearChildNodes(nodeTo);
5.518 + };
5.519 + var ownerDoc = nodeTo.nodeType == Node.DOCUMENT_NODE ? nodeTo : nodeTo.ownerDocument;
5.520 + var nodes = nodeFrom.childNodes;
5.521 + if(ownerDoc.importNode && (!_SARISSA_IS_IE)) {
5.522 + for(var i=0;i < nodes.length;i++) {
5.523 + nodeTo.appendChild(ownerDoc.importNode(nodes[i], true));
5.524 + };
5.525 + }
5.526 + else{
5.527 + for(var i=0;i < nodes.length;i++) {
5.528 + nodeTo.appendChild(nodes[i].cloneNode(true));
5.529 + };
5.530 + };
5.531 +};
5.532 +
5.533 +/**
5.534 + * <p> Moves the childNodes of nodeFrom to nodeTo</p>
5.535 + * <p> <b>Note:</b> The second object's original content is deleted before
5.536 + * the move operation, unless you supply a true third parameter</p>
5.537 + * @argument nodeFrom the Node to copy the childNodes from
5.538 + * @argument nodeTo the Node to copy the childNodes to
5.539 + * @argument bPreserveExisting whether to preserve the original content of nodeTo, default is false
5.540 + */
5.541 +Sarissa.moveChildNodes = function(nodeFrom, nodeTo, bPreserveExisting) {
5.542 + if(!bPreserveExisting){
5.543 + Sarissa.clearChildNodes(nodeTo);
5.544 + };
5.545 +
5.546 + var nodes = nodeFrom.childNodes;
5.547 + // if within the same doc, just move, else copy and delete
5.548 + if(nodeFrom.ownerDocument == nodeTo.ownerDocument){
5.549 + nodeTo.appendChild(nodes[i]);
5.550 + }else{
5.551 + var ownerDoc = nodeTo.nodeType == Node.DOCUMENT_NODE ? nodeTo : nodeTo.ownerDocument;
5.552 + if(ownerDoc.importNode && (!_SARISSA_IS_IE)) {
5.553 + for(var i=0;i < nodes.length;i++) {
5.554 + nodeTo.appendChild(ownerDoc.importNode(nodes[i], true));
5.555 + };
5.556 + }
5.557 + else{
5.558 + for(var i=0;i < nodes.length;i++) {
5.559 + nodeTo.appendChild(nodes[i].cloneNode(true));
5.560 + };
5.561 + };
5.562 + Sarissa.clearChildNodes(nodeFrom);
5.563 + };
5.564 +
5.565 +};
5.566 +
5.567 +/**
5.568 + * <p>Serialize any object to an XML string. All properties are serialized using the property name
5.569 + * as the XML element name. Array elements are rendered as <code>array-item</code> elements,
5.570 + * using their index/key as the value of the <code>key</code> attribute.</p>
5.571 + * @argument anyObject the object to serialize
5.572 + * @argument objectName a name for that object
5.573 + * @return the XML serializationj of the given object as a string
5.574 + */
5.575 +Sarissa.xmlize = function(anyObject, objectName, indentSpace){
5.576 + indentSpace = indentSpace?indentSpace:'';
5.577 + var s = indentSpace + '<' + objectName + '>';
5.578 + var isLeaf = false;
5.579 + if(!(anyObject instanceof Object) || anyObject instanceof Number || anyObject instanceof String
5.580 + || anyObject instanceof Boolean || anyObject instanceof Date){
5.581 + s += Sarissa.escape(""+anyObject);
5.582 + isLeaf = true;
5.583 + }else{
5.584 + s += "\n";
5.585 + var itemKey = '';
5.586 + var isArrayItem = anyObject instanceof Array;
5.587 + for(var name in anyObject){
5.588 + s += Sarissa.xmlize(anyObject[name], (isArrayItem?"array-item key=\""+name+"\"":name), indentSpace + " ");
5.589 + };
5.590 + s += indentSpace;
5.591 + };
5.592 + return s += (objectName.indexOf(' ')!=-1?"</array-item>\n":"</" + objectName + ">\n");
5.593 +};
5.594 +
5.595 +/**
5.596 + * Escape the given string chacters that correspond to the five predefined XML entities
5.597 + * @param sXml the string to escape
5.598 + */
5.599 +Sarissa.escape = function(sXml){
5.600 + return sXml.replace(/&/g, "&")
5.601 + .replace(/</g, "<")
5.602 + .replace(/>/g, ">")
5.603 + .replace(/"/g, """)
5.604 + .replace(/'/g, "'");
5.605 +};
5.606 +
5.607 +/**
5.608 + * Unescape the given string. This turns the occurences of the predefined XML
5.609 + * entities to become the characters they represent correspond to the five predefined XML entities
5.610 + * @param sXml the string to unescape
5.611 + */
5.612 +Sarissa.unescape = function(sXml){
5.613 + return sXml.replace(/'/g,"'")
5.614 + .replace(/"/g,"\"")
5.615 + .replace(/>/g,">")
5.616 + .replace(/</g,"<")
5.617 + .replace(/&/g,"&");
5.618 +};
5.619 +// EOF
7.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
7.2 +++ b/examples/Common/Dictionary/__init__.py Fri Sep 09 17:33:19 2005 +0000
7.3 @@ -0,0 +1,148 @@
7.4 +#!/usr/bin/env python
7.5 +
7.6 +"A dictionary example application."
7.7 +
7.8 +import WebStack.Generic
7.9 +import XSLForms.Resources
7.10 +import XSLForms.Utils
7.11 +import os
7.12 +
7.13 +# Site map imports.
7.14 +
7.15 +from WebStack.Resources.ResourceMap import MapResource
7.16 +from WebStack.Resources.Static import DirectoryResource
7.17 +
7.18 +# Resource classes.
7.19 +
7.20 +class DictionaryResource(XSLForms.Resources.XSLFormsResource):
7.21 +
7.22 + "A simple resource providing dictionary lookup."
7.23 +
7.24 + resource_dir = os.path.join(os.path.split(__file__)[0], "Resources")
7.25 + encoding = "utf-8"
7.26 + template_resources = {
7.27 + "words" : ("words_template.xhtml", "words_output.xsl")
7.28 + }
7.29 + in_page_resources = {
7.30 + "entry" : ("words_output_entry.xsl", "entry-node")
7.31 + }
7.32 +
7.33 + def __init__(self, dict):
7.34 +
7.35 + "Initialise the resource with the given 'dict'."
7.36 +
7.37 + self.dict = dict
7.38 +
7.39 + def respond_to_form(self, trans, form):
7.40 +
7.41 + """
7.42 + Respond to a request having the given transaction 'trans' and the given
7.43 + 'form' information.
7.44 + """
7.45 +
7.46 + in_page_resource = self.get_in_page_resource(trans)
7.47 + parameters = form.get_parameters()
7.48 + documents = form.get_documents()
7.49 +
7.50 + # Ensure the presence of a document.
7.51 +
7.52 + if documents.has_key("words"):
7.53 + words = documents["words"]
7.54 + else:
7.55 + words = form.new_instance("words")
7.56 +
7.57 + # Add and remove elements according to the selectors found.
7.58 +
7.59 + selectors = form.get_selectors()
7.60 + XSLForms.Utils.remove_elements(selectors.get("remove"))
7.61 + XSLForms.Utils.add_elements(selectors.get("add"), "entry")
7.62 +
7.63 + # Ensure all entries have a matches element.
7.64 + # Ensure all matches elements have at least one choice.
7.65 + # Copy selected matches to their corresponding text field.
7.66 +
7.67 + for entry in words.xpath("words/entry"):
7.68 + matches_list = entry.xpath("matches")
7.69 + if len(matches_list) == 0:
7.70 + matches = words.createElement("matches")
7.71 + entry.appendChild(matches)
7.72 + else:
7.73 + matches = matches_list[0]
7.74 +
7.75 + if len(entry.xpath("matches/match-enum")) == 0:
7.76 + match_enum = words.createElement("match-enum")
7.77 + match_enum.setAttribute("word", "")
7.78 + matches.appendChild(match_enum)
7.79 +
7.80 + if matches.hasAttribute("word"):
7.81 + word = matches.getAttribute("word")
7.82 + if word != "":
7.83 + entry.setAttribute("word", word)
7.84 +
7.85 + # Find requested search locations.
7.86 +
7.87 + if selectors.has_key("search"):
7.88 + entries = selectors["search"]
7.89 + elif in_page_resource == "entry":
7.90 + entries = words.xpath("words/entry")
7.91 + else:
7.92 + entries = []
7.93 +
7.94 + # Transform, adding dictionary information.
7.95 +
7.96 + for entry in entries:
7.97 + word = entry.getAttribute("word")
7.98 + if word != "":
7.99 + matches = entry.xpath("matches")[0]
7.100 + for found_word in self.dict.find(word):
7.101 + match_enum = words.createElement("match-enum")
7.102 + match_enum.setAttribute("word", found_word)
7.103 + matches.appendChild(match_enum)
7.104 +
7.105 + # Start the response.
7.106 +
7.107 + trans.set_content_type(WebStack.Generic.ContentType("application/xhtml+xml", self.encoding))
7.108 +
7.109 + # Define the stylesheet parameters.
7.110 +
7.111 + stylesheet_parameters = {}
7.112 +
7.113 + # Ensure that an output stylesheet exists.
7.114 +
7.115 + if in_page_resource in self.in_page_resources.keys():
7.116 + trans_xsl = self.prepare_fragment("words", in_page_resource)
7.117 + element_path = parameters.get("element-path", [""])[0]
7.118 + stylesheet_parameters["element-path"] = element_path
7.119 + else:
7.120 + trans_xsl = self.prepare_output("words")
7.121 +
7.122 + # Complete the response.
7.123 +
7.124 + self.send_output(trans, [trans_xsl], words, stylesheet_parameters)
7.125 +
7.126 +# Site map initialisation.
7.127 +
7.128 +def get_site(dict):
7.129 +
7.130 + """
7.131 + Return a simple Web site resource using the given 'dict' - a dictionary
7.132 + employed by the application.
7.133 + """
7.134 +
7.135 + # Get the main resource and the directory used by the application.
7.136 +
7.137 + dictionary_resource = DictionaryResource(dict)
7.138 + directory = dictionary_resource.resource_dir
7.139 +
7.140 + # Make a simple Web site.
7.141 +
7.142 + resource = MapResource({
7.143 + # Static resources:
7.144 + "scripts" : DirectoryResource(os.path.join(directory, "scripts"), {"js" : "text/javascript"}),
7.145 + # Main page and in-page resources:
7.146 + None : dictionary_resource
7.147 + })
7.148 +
7.149 + return resource
7.150 +
7.151 +# vim: tabstop=4 expandtab shiftwidth=4