1 /* 2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. 3 * 4 * Copyright 1997-2012 Sun Microsystems, Inc. All rights reserved. 5 * 6 * The contents of this file are subject to the terms of either the GNU 7 * General Public License Version 2 only ("GPL") or the Common Development 8 * and Distribution License("CDDL") (collectively, the "License"). You 9 * may not use this file except in compliance with the License. You can obtain 10 * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html 11 * or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific 12 * language governing permissions and limitations under the License. 13 * 14 * When distributing the software, include this License Header Notice in each 15 * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt. 16 * Sun designates this particular file as subject to the "Classpath" exception 17 * as provided by Sun in the GPL Version 2 section of the License file that 18 * accompanied this code. If applicable, add the following below the License 19 * Header, with the fields enclosed by brackets [] replaced by your own 20 * identifying information: "Portions Copyrighted [year] 21 * [name of copyright owner]" 22 * 23 * Contributor(s): 24 * 25 * If you wish your version of this file to be governed by only the CDDL or 26 * only the GPL Version 2, indicate your decision by adding "[Contributor] 27 * elects to include this software in this distribution under the [CDDL or GPL 28 * Version 2] license." If you don't indicate a single choice of license, a 29 * recipient has the option to distribute your version of this file under 30 * either the CDDL, the GPL Version 2 or to extend the choice of license to 31 * its licensees as provided above. However, if you add GPL Version 2 code 32 * and therefore, elected the GPL Version 2 license, then the option applies 33 * only if the new code is made subject to such option by the copyright 34 * holder. 35 * 36 * 37 * This file incorporates work covered by the following copyright and 38 * permission notices: 39 * 40 * Copyright 2004 The Apache Software Foundation 41 * Copyright 2004-2008 Emmanouil Batsis, mailto: mbatsis at users full stop sourceforge full stop net 42 * 43 * Licensed under the Apache License, Version 2.0 (the "License"); 44 * you may not use this file except in compliance with the License. 45 * You may obtain a copy of the License at 46 * 47 * http://www.apache.org/licenses/LICENSE-2.0 48 * 49 * Unless required by applicable law or agreed to in writing, software 50 * distributed under the License is distributed on an "AS IS" BASIS, 51 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 52 * See the License for the specific language governing permissions and 53 * limitations under the License. 54 */ 55 56 /** 57 @project JSF JavaScript Library 58 @version 2.2 59 @description This is the standard implementation of the JSF JavaScript Library. 60 */ 61 62 /** 63 * Register with OpenAjax 64 */ 65 if (typeof OpenAjax !== "undefined" && 66 typeof OpenAjax.hub.registerLibrary !== "undefined") { 67 OpenAjax.hub.registerLibrary("jsf", "www.sun.com", "2.2", null); 68 } 69 70 // Detect if this is already loaded, and if loaded, if it's a higher version 71 if (!((jsf && jsf.specversion && jsf.specversion >= 20000 ) && 72 (jsf.implversion && jsf.implversion >= 3))) { 73 74 /** 75 * <span class="changed_modified_2_2">The top level global namespace 76 * for JavaServer Faces functionality.</span> 77 78 * @name jsf 79 * @namespace 80 */ 81 var jsf = {}; 82 83 /** 84 85 * <span class="changed_modified_2_2">The namespace for Ajax 86 * functionality.</span> 87 88 * @name jsf.ajax 89 * @namespace 90 * @exec 91 */ 92 jsf.ajax = function() { 93 94 var eventListeners = []; 95 var errorListeners = []; 96 97 var delayHandler = null; 98 /** 99 * Determine if the current browser is part of Microsoft's failed attempt at 100 * standards modification. 101 * @ignore 102 */ 103 var isIE = function isIE() { 104 if (typeof isIECache !== "undefined") { 105 return isIECache; 106 } 107 isIECache = 108 document.all && window.ActiveXObject && 109 navigator.userAgent.toLowerCase().indexOf("msie") > -1 && 110 navigator.userAgent.toLowerCase().indexOf("opera") == -1; 111 return isIECache; 112 }; 113 var isIECache; 114 115 /** 116 * Determine if loading scripts into the page executes the script. 117 * This is instead of doing a complicated browser detection algorithm. Some do, some don't. 118 * @returns {boolean} does including a script in the dom execute it? 119 * @ignore 120 */ 121 var isAutoExec = function isAutoExec() { 122 try { 123 if (typeof isAutoExecCache !== "undefined") { 124 return isAutoExecCache; 125 } 126 var autoExecTestString = "<script>var mojarra = mojarra || {};mojarra.autoExecTest = true;</script>"; 127 var tempElement = document.createElement('span'); 128 tempElement.innerHTML = autoExecTestString; 129 var body = document.getElementsByTagName('body')[0]; 130 var tempNode = body.appendChild(tempElement); 131 if (mojarra && mojarra.autoExecTest) { 132 isAutoExecCache = true; 133 delete mojarra.autoExecTest; 134 } else { 135 isAutoExecCache = false; 136 } 137 deleteNode(tempNode); 138 return isAutoExecCache; 139 } catch (ex) { 140 // OK, that didn't work, we'll have to make an assumption 141 if (typeof isAutoExecCache === "undefined") { 142 isAutoExecCache = false; 143 } 144 return isAutoExecCache; 145 } 146 }; 147 var isAutoExecCache; 148 149 /** 150 * @ignore 151 */ 152 var getTransport = function getTransport() { 153 var methods = [ 154 function() { 155 return new XMLHttpRequest(); 156 }, 157 function() { 158 return new ActiveXObject('Msxml2.XMLHTTP'); 159 }, 160 function() { 161 return new ActiveXObject('Microsoft.XMLHTTP'); 162 } 163 ]; 164 165 var returnVal; 166 for (var i = 0, len = methods.length; i < len; i++) { 167 try { 168 returnVal = methods[i](); 169 } catch(e) { 170 continue; 171 } 172 return returnVal; 173 } 174 throw new Error('Could not create an XHR object.'); 175 }; 176 177 /** 178 * Find instance of passed String via getElementById 179 * @ignore 180 */ 181 var $ = function $() { 182 var results = [], element; 183 for (var i = 0; i < arguments.length; i++) { 184 element = arguments[i]; 185 if (typeof element == 'string') { 186 element = document.getElementById(element); 187 } 188 results.push(element); 189 } 190 return results.length > 1 ? results : results[0]; 191 }; 192 193 /** 194 * Get the form element which encloses the supplied element. 195 * @param element - element to act against in search 196 * @returns form element representing enclosing form, or first form if none found. 197 * @ignore 198 */ 199 var getForm = function getForm(element) { 200 if (element) { 201 var form = $(element); 202 while (form) { 203 204 if (form.nodeName && (form.nodeName.toLowerCase() == 'form')) { 205 return form; 206 } 207 if (form.form) { 208 return form.form; 209 } 210 if (form.parentNode) { 211 form = form.parentNode; 212 } else { 213 form = null; 214 } 215 } 216 return document.forms[0]; 217 } 218 return null; 219 }; 220 221 /** 222 * Check if a value exists in an array 223 * @ignore 224 */ 225 var isInArray = function isInArray(array, value) { 226 for (var i = 0; i < array.length; i++) { 227 if (array[i] === value) { 228 return true; 229 } 230 } 231 return false; 232 }; 233 234 235 /** 236 * Evaluate JavaScript code in a global context. 237 * @param src JavaScript code to evaluate 238 * @ignore 239 */ 240 var globalEval = function globalEval(src) { 241 if (window.execScript) { 242 window.execScript(src); 243 return; 244 } 245 // We have to wrap the call in an anon function because of a firefox bug, where this is incorrectly set 246 // We need to explicitly call window.eval because of a Chrome peculiarity 247 var fn = function() { 248 window.eval.call(window,src); 249 }; 250 fn(); 251 }; 252 253 /** 254 * Get all scripts from supplied string, return them as an array for later processing. 255 * @param str 256 * @returns {array} of script text 257 * @ignore 258 */ 259 var stripScripts = function stripScripts(str) { 260 // Regex to find all scripts in a string 261 var findscripts = /<script[^>]*>([\S\s]*?)<\/script>/igm; 262 // Regex to find one script, to isolate it's content [2] and attributes [1] 263 var findscript = /<script([^>]*)>([\S\s]*?)<\/script>/im; 264 // Regex to remove leading cruft 265 var stripStart = /^\s*(<!--)*\s*(\/\/)*\s*(\/\*)*\s*(<!\[CDATA\[)*/; 266 // Regex to find src attribute 267 var findsrc = /src="([\S]*?)"/im; 268 var initialnodes = []; 269 var scripts = []; 270 initialnodes = str.match(findscripts); 271 while (!!initialnodes && initialnodes.length > 0) { 272 var scriptStr = []; 273 scriptStr = initialnodes.shift().match(findscript); 274 var src = []; 275 // check if src specified 276 src = scriptStr[1].match(findsrc); 277 var script; 278 if ( !!src && src[1]) { 279 // if this is a file, load it 280 var url = src[1]; 281 // if this is another copy of jsf.js, don't load it 282 // it's never necessary, and can make debugging difficult 283 if (/\/javax.faces.resource\/jsf.js\?ln=javax\.faces/.test(url)) { 284 script = false; 285 } else { 286 script = loadScript(url); 287 } 288 } else if (!!scriptStr && scriptStr[2]){ 289 // else get content of tag, without leading CDATA and such 290 script = scriptStr[2].replace(stripStart,""); 291 } else { 292 script = false; 293 } 294 if (!!script) { 295 scripts.push(script); 296 } 297 } 298 return scripts; 299 }; 300 301 /** 302 * Load a script via a url, use synchronous XHR request. This is liable to be slow, 303 * but it's probably the only correct way. 304 * @param url the url to load 305 * @ignore 306 */ 307 var loadScript = function loadScript(url) { 308 var xhr = getTransport(); 309 if (xhr === null) { 310 return ""; 311 } 312 313 xhr.open("GET", url, false); 314 xhr.setRequestHeader("Content-Type", "application/x-javascript"); 315 xhr.send(null); 316 317 // PENDING graceful error handling 318 if (xhr.readyState == 4 && xhr.status == 200) { 319 return xhr.responseText; 320 } 321 322 return ""; 323 }; 324 325 /** 326 * Run an array of scripts text 327 * @param scripts array of script nodes 328 * @ignore 329 */ 330 var runScripts = function runScripts(scripts) { 331 if (!scripts || scripts.length === 0) { 332 return; 333 } 334 335 var head = document.getElementsByTagName('head')[0] || document.documentElement; 336 while (scripts.length) { 337 // create script node 338 var scriptNode = document.createElement('script'); 339 scriptNode.type = 'text/javascript'; 340 scriptNode.text = scripts.shift(); // add the code to the script node 341 head.appendChild(scriptNode); // add it to the page 342 head.removeChild(scriptNode); // then remove it 343 } 344 }; 345 346 /** 347 * Replace DOM element with a new tagname and supplied innerHTML 348 * @param element element to replace 349 * @param tempTagName new tag name to replace with 350 * @param src string new content for element 351 * @ignore 352 */ 353 var elementReplaceStr = function elementReplaceStr(element, tempTagName, src) { 354 355 var temp = document.createElement(tempTagName); 356 if (element.id) { 357 temp.id = element.id; 358 } 359 360 // Creating a head element isn't allowed in IE, and faulty in most browsers, 361 // so it is not allowed 362 if (element.nodeName.toLowerCase() === "head") { 363 throw new Error("Attempted to replace a head element - this is not allowed."); 364 } else { 365 var scripts = []; 366 if (isAutoExec()) { 367 temp.innerHTML = src; 368 } else { 369 // Get scripts from text 370 scripts = stripScripts(src); 371 // Remove scripts from text 372 src = src.replace(/<script[^>]*>([\S\s]*?)<\/script>/igm,""); 373 temp.innerHTML = src; 374 } 375 } 376 377 replaceNode(temp, element); 378 runScripts(scripts); 379 380 }; 381 382 /** 383 * Get a string with the concatenated values of all string nodes under the given node 384 * @param oNode the given DOM node 385 * @param deep boolean - whether to recursively scan the children nodes of the given node for text as well. Default is <code>false</code> 386 * @ignore 387 * Note: This code originally from Sarissa: http://dev.abiss.gr/sarissa 388 * It has been modified to fit into the overall codebase 389 */ 390 var getText = function getText(oNode, deep) { 391 var Node = {ELEMENT_NODE: 1, ATTRIBUTE_NODE: 2, TEXT_NODE: 3, CDATA_SECTION_NODE: 4, 392 ENTITY_REFERENCE_NODE: 5, ENTITY_NODE: 6, PROCESSING_INSTRUCTION_NODE: 7, 393 COMMENT_NODE: 8, DOCUMENT_NODE: 9, DOCUMENT_TYPE_NODE: 10, 394 DOCUMENT_FRAGMENT_NODE: 11, NOTATION_NODE: 12}; 395 396 var s = ""; 397 var nodes = oNode.childNodes; 398 for (var i = 0; i < nodes.length; i++) { 399 var node = nodes[i]; 400 var nodeType = node.nodeType; 401 if (nodeType == Node.TEXT_NODE || nodeType == Node.CDATA_SECTION_NODE) { 402 s += node.data; 403 } else if (deep === true && (nodeType == Node.ELEMENT_NODE || 404 nodeType == Node.DOCUMENT_NODE || 405 nodeType == Node.DOCUMENT_FRAGMENT_NODE)) { 406 s += getText(node, true); 407 } 408 } 409 return s; 410 }; 411 412 var PARSED_OK = "Document contains no parsing errors"; 413 var PARSED_EMPTY = "Document is empty"; 414 var PARSED_UNKNOWN_ERROR = "Not well-formed or other error"; 415 var getParseErrorText; 416 if (isIE()) { 417 /** 418 * Note: This code orginally from Sarissa: http://dev.abiss.gr/sarissa 419 * @ignore 420 */ 421 getParseErrorText = function (oDoc) { 422 var parseErrorText = PARSED_OK; 423 if (oDoc && oDoc.parseError && oDoc.parseError.errorCode && oDoc.parseError.errorCode !== 0) { 424 parseErrorText = "XML Parsing Error: " + oDoc.parseError.reason + 425 "\nLocation: " + oDoc.parseError.url + 426 "\nLine Number " + oDoc.parseError.line + ", Column " + 427 oDoc.parseError.linepos + 428 ":\n" + oDoc.parseError.srcText + 429 "\n"; 430 for (var i = 0; i < oDoc.parseError.linepos; i++) { 431 parseErrorText += "-"; 432 } 433 parseErrorText += "^\n"; 434 } 435 else if (oDoc.documentElement === null) { 436 parseErrorText = PARSED_EMPTY; 437 } 438 return parseErrorText; 439 }; 440 } else { // (non-IE) 441 442 /** 443 * <p>Returns a human readable description of the parsing error. Useful 444 * for debugging. Tip: append the returned error string in a <pre> 445 * element if you want to render it.</p> 446 * @param oDoc The target DOM document 447 * @returns {String} The parsing error description of the target Document in 448 * human readable form (preformated text) 449 * @ignore 450 * Note: This code orginally from Sarissa: http://dev.abiss.gr/sarissa 451 */ 452 getParseErrorText = function (oDoc) { 453 var parseErrorText = PARSED_OK; 454 if ((!oDoc) || (!oDoc.documentElement)) { 455 parseErrorText = PARSED_EMPTY; 456 } else if (oDoc.documentElement.tagName == "parsererror") { 457 parseErrorText = oDoc.documentElement.firstChild.data; 458 parseErrorText += "\n" + oDoc.documentElement.firstChild.nextSibling.firstChild.data; 459 } else if (oDoc.getElementsByTagName("parsererror").length > 0) { 460 var parsererror = oDoc.getElementsByTagName("parsererror")[0]; 461 parseErrorText = getText(parsererror, true) + "\n"; 462 } else if (oDoc.parseError && oDoc.parseError.errorCode !== 0) { 463 parseErrorText = PARSED_UNKNOWN_ERROR; 464 } 465 return parseErrorText; 466 }; 467 } 468 469 if ((typeof(document.importNode) == "undefined") && isIE()) { 470 try { 471 /** 472 * Implementation of importNode for the context window document in IE. 473 * If <code>oNode</code> is a TextNode, <code>bChildren</code> is ignored. 474 * @param oNode the Node to import 475 * @param bChildren whether to include the children of oNode 476 * @returns the imported node for further use 477 * @ignore 478 * Note: This code orginally from Sarissa: http://dev.abiss.gr/sarissa 479 */ 480 document.importNode = function(oNode, bChildren) { 481 var tmp; 482 if (oNode.nodeName == '#text') { 483 return document.createTextNode(oNode.data); 484 } 485 else { 486 if (oNode.nodeName == "tbody" || oNode.nodeName == "tr") { 487 tmp = document.createElement("table"); 488 } 489 else if (oNode.nodeName == "td") { 490 tmp = document.createElement("tr"); 491 } 492 else if (oNode.nodeName == "option") { 493 tmp = document.createElement("select"); 494 } 495 else { 496 tmp = document.createElement("div"); 497 } 498 if (bChildren) { 499 tmp.innerHTML = oNode.xml ? oNode.xml : oNode.outerHTML; 500 } else { 501 tmp.innerHTML = oNode.xml ? oNode.cloneNode(false).xml : oNode.cloneNode(false).outerHTML; 502 } 503 return tmp.getElementsByTagName("*")[0]; 504 } 505 }; 506 } catch(e) { 507 } 508 } 509 // Setup Node type constants for those browsers that don't have them (IE) 510 var Node = {ELEMENT_NODE: 1, ATTRIBUTE_NODE: 2, TEXT_NODE: 3, CDATA_SECTION_NODE: 4, 511 ENTITY_REFERENCE_NODE: 5, ENTITY_NODE: 6, PROCESSING_INSTRUCTION_NODE: 7, 512 COMMENT_NODE: 8, DOCUMENT_NODE: 9, DOCUMENT_TYPE_NODE: 10, 513 DOCUMENT_FRAGMENT_NODE: 11, NOTATION_NODE: 12}; 514 515 // PENDING - add support for removing handlers added via DOM 2 methods 516 /** 517 * Delete all events attached to a node 518 * @param node 519 * @ignore 520 */ 521 var clearEvents = function clearEvents(node) { 522 if (!node) { 523 return; 524 } 525 526 // don't do anything for text and comment nodes - unnecessary 527 if (node.nodeType == Node.TEXT_NODE || node.nodeType == Node.COMMENT_NODE) { 528 return; 529 } 530 531 var events = ['abort', 'blur', 'change', 'error', 'focus', 'load', 'reset', 'resize', 'scroll', 'select', 'submit', 'unload', 532 'keydown', 'keypress', 'keyup', 'click', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'dblclick' ]; 533 try { 534 for (var e in events) { 535 if (events.hasOwnProperty(e)) { 536 node[e] = null; 537 } 538 } 539 } catch (ex) { 540 // it's OK if it fails, at least we tried 541 } 542 }; 543 544 /** 545 * Determine if this current browser is IE9 or greater 546 * @param node 547 * @ignore 548 */ 549 var isIE9Plus = function isIE9Plus() { 550 return typeof XDomainRequest !== "undefined" && typeof window.msPerformance !== "undefined"; 551 } 552 553 554 /** 555 * Deletes node 556 * @param node 557 * @ignore 558 */ 559 var deleteNode = function deleteNode(node) { 560 if (!node) { 561 return; 562 } 563 if (!node.parentNode) { 564 // if there's no parent, there's nothing to do 565 return; 566 } 567 if (!isIE() || (isIE() && isIE9Plus())) { 568 // nothing special required 569 node.parentNode.removeChild(node); 570 return; 571 } 572 // The rest of this code is specialcasing for IE 573 if (node.nodeName.toLowerCase() === "body") { 574 // special case for removing body under IE. 575 deleteChildren(node); 576 try { 577 node.outerHTML = ''; 578 } catch (ex) { 579 // fails under some circumstances, but not in RI 580 // supplied responses. If we've gotten here, it's 581 // fairly safe to leave a lingering body tag rather than 582 // fail outright 583 } 584 return; 585 } 586 var temp = node.ownerDocument.createElement('div'); 587 var parent = node.parentNode; 588 temp.appendChild(parent.removeChild(node)); 589 // Now clean up the temporary element 590 try { 591 temp.outerHTML = ''; //prevent leak in IE 592 } catch (ex) { 593 // at least we tried. Fails in some circumstances, 594 // but not in RI supplied responses. Better to leave a lingering 595 // temporary div than to fail outright. 596 } 597 }; 598 599 /** 600 * Deletes all children of a node 601 * @param node 602 * @ignore 603 */ 604 var deleteChildren = function deleteChildren(node) { 605 if (!node) { 606 return; 607 } 608 for (var x = node.childNodes.length - 1; x >= 0; x--) { //delete all of node's children 609 var childNode = node.childNodes[x]; 610 deleteNode(childNode); 611 } 612 }; 613 614 /** 615 * <p> Copies the childNodes of nodeFrom to nodeTo</p> 616 * 617 * @param nodeFrom the Node to copy the childNodes from 618 * @param nodeTo the Node to copy the childNodes to 619 * @ignore 620 * Note: This code originally from Sarissa: http://dev.abiss.gr/sarissa 621 * It has been modified to fit into the overall codebase 622 */ 623 var copyChildNodes = function copyChildNodes(nodeFrom, nodeTo) { 624 625 if ((!nodeFrom) || (!nodeTo)) { 626 throw "Both source and destination nodes must be provided"; 627 } 628 629 deleteChildren(nodeTo); 630 var nodes = nodeFrom.childNodes; 631 // if within the same doc, just move, else copy and delete 632 if (nodeFrom.ownerDocument == nodeTo.ownerDocument) { 633 while (nodeFrom.firstChild) { 634 nodeTo.appendChild(nodeFrom.firstChild); 635 } 636 } else { 637 var ownerDoc = nodeTo.nodeType == Node.DOCUMENT_NODE ? nodeTo : nodeTo.ownerDocument; 638 var i; 639 if (typeof(ownerDoc.importNode) != "undefined") { 640 for (i = 0; i < nodes.length; i++) { 641 nodeTo.appendChild(ownerDoc.importNode(nodes[i], true)); 642 } 643 } else { 644 for (i = 0; i < nodes.length; i++) { 645 nodeTo.appendChild(nodes[i].cloneNode(true)); 646 } 647 } 648 } 649 }; 650 651 652 /** 653 * Replace one node with another. Necessary for handling IE memory leak. 654 * @param node 655 * @param newNode 656 * @ignore 657 */ 658 var replaceNode = function replaceNode(newNode, node) { 659 if(isIE()){ 660 node.parentNode.insertBefore(newNode, node); 661 deleteNode(node); 662 } else { 663 node.parentNode.replaceChild(newNode, node); 664 } 665 }; 666 667 668 /** 669 * copy all attributes from one element to another - except id 670 * @param target element to copy attributes to 671 * @param source element to copy attributes from 672 * @ignore 673 */ 674 var cloneAttributes = function cloneAttributes(target, source) { 675 676 // enumerate core element attributes - without 'dir' as special case 677 var coreElementAttributes = ['className', 'title', 'lang', 'xml:lang']; 678 679 // Enumerate additional input element attributes 680 var inputElementAttributes = 681 [ 'name', 'value', 'checked', 'disabled', 'readOnly', 682 'size', 'maxLength', 'src', 'alt', 'useMap', 'isMap', 683 'tabIndex', 'accessKey', 'accept', 'type' 684 ]; 685 686 // Enumerate all the names of the event listeners 687 var listenerNames = 688 [ 'onclick', 'ondblclick', 'onmousedown', 'onmousemove', 'onmouseout', 689 'onmouseover', 'onmouseup', 'onkeydown', 'onkeypress', 'onkeyup', 690 'onhelp', 'onblur', 'onfocus', 'onchange', 'onload', 'onunload', 'onabort', 691 'onreset', 'onselect', 'onsubmit' 692 ]; 693 694 var iIndex, iLength; // for loop variables 695 var attributeName; // name of the attribute to set 696 var newValue, oldValue; // attribute values in each element 697 698 // First, copy over core attributes 699 for (iIndex = 0,iLength = coreElementAttributes.length; iIndex < iLength; iIndex++) { 700 attributeName = coreElementAttributes[iIndex]; 701 newValue = source.getAttribute(attributeName); 702 oldValue = target.getAttribute(attributeName); 703 if (oldValue != newValue) { 704 target[attributeName] = newValue; 705 } 706 } 707 708 // Next, if it's an input, copy those over 709 if (target.nodeName.toLowerCase() === 'input') { 710 for (iIndex = 0,iLength = inputElementAttributes.length; iIndex < iLength; iIndex++) { 711 attributeName = inputElementAttributes[iIndex]; 712 newValue = source.getAttribute(attributeName); 713 oldValue = target.getAttribute(attributeName); 714 if (oldValue != newValue) { 715 target[attributeName] = newValue; 716 } 717 } 718 } 719 //'style' attribute special case 720 var newStyle = source.getAttribute('style'); 721 var oldStyle = target.getAttribute('style'); 722 if (newStyle != oldStyle) { 723 if (isIE()) { 724 target.style.setAttribute('cssText', newStyle, 0); 725 } else { 726 target.setAttribute('style',newStyle); 727 } 728 } 729 for (var lIndex = 0, lLength = listenerNames.length; lIndex < lLength; lIndex++) { 730 var name = listenerNames[lIndex]; 731 target[name] = source[name] ? source[name] : null; 732 if (source[name]) { 733 source[name] = null; 734 } 735 } 736 // Special case for 'dir' attribute 737 if (!isIE() && source.dir != target.dir) { 738 target.dir = source.dir ? source.dir : null; 739 } 740 }; 741 742 /** 743 * Replace an element from one document into another 744 * @param newElement new element to put in document 745 * @param origElement original element to replace 746 * @ignore 747 */ 748 var elementReplace = function elementReplace(newElement, origElement) { 749 copyChildNodes(newElement, origElement); 750 // sadly, we have to reparse all over again 751 // to reregister the event handlers and styles 752 // PENDING do some performance tests on large pages 753 origElement.innerHTML = origElement.innerHTML; 754 755 try { 756 cloneAttributes(origElement, newElement); 757 } catch (ex) { 758 // if in dev mode, report an error, else try to limp onward 759 if (jsf.getProjectStage() == "Development") { 760 throw new Error("Error updating attributes"); 761 } 762 } 763 deleteNode(newElement); 764 765 }; 766 767 /** 768 * Create a new document, then select the body element within it 769 * @param docStr Stringified version of document to create 770 * @return element the body element 771 * @ignore 772 */ 773 var getBodyElement = function getBodyElement(docStr) { 774 775 var doc; // intermediate document we'll create 776 var body; // Body element to return 777 778 if (typeof DOMParser !== "undefined") { // FF, S, Chrome 779 doc = (new DOMParser()).parseFromString(docStr, "text/xml"); 780 } else if (typeof ActiveXObject !== "undefined") { // IE 781 doc = new ActiveXObject("MSXML2.DOMDocument"); 782 doc.loadXML(docStr); 783 } else { 784 throw new Error("You don't seem to be running a supported browser"); 785 } 786 787 if (getParseErrorText(doc) !== PARSED_OK) { 788 throw new Error(getParseErrorText(doc)); 789 } 790 791 body = doc.getElementsByTagName("body")[0]; 792 793 if (!body) { 794 throw new Error("Can't find body tag in returned document."); 795 } 796 797 return body; 798 }; 799 800 /** 801 * Do update. 802 * @param element element to update 803 * @param context context of request 804 * @ignore 805 */ 806 var doUpdate = function doUpdate(element, context, partialResponseId) { 807 var id, content, markup, state, windowId; 808 var stateForm, windowIdForm; 809 var scripts = []; // temp holding value for array of script nodes 810 811 id = element.getAttribute('id'); 812 var viewStateRegex = new RegExp("javax.faces.ViewState" + 813 jsf.separatorchar + ".*$"); 814 var windowIdRegex = new RegExp("^.*" + jsf.separatorchar + 815 "javax.faces.WindowId" + 816 jsf.separatorchar + ".*$"); 817 if (id.match(viewStateRegex)) { 818 819 state = element.firstChild; 820 821 // Now set the view state from the server into the DOM 822 // but only for the form that submitted the request. 823 824 stateForm = document.getElementById(context.formid); 825 if (!stateForm || !stateForm.elements) { 826 // if the form went away for some reason, or it lacks elements 827 // we're going to just return silently. 828 return; 829 } 830 var field = stateForm.elements["javax.faces.ViewState"]; 831 if (typeof field == 'undefined') { 832 field = document.createElement("input"); 833 field.type = "hidden"; 834 field.name = "javax.faces.ViewState"; 835 stateForm.appendChild(field); 836 } 837 field.value = state.nodeValue; 838 839 // Now set the view state from the server into the DOM 840 // for any form that is a render target. 841 842 if (typeof context.render !== 'undefined' && context.render !== null) { 843 var temp = context.render.split(' '); 844 for (var i = 0; i < temp.length; i++) { 845 if (temp.hasOwnProperty(i)) { 846 // See if the element is a form and 847 // the form is not the one that caused the submission.. 848 var f = document.forms[temp[i]]; 849 if (typeof f !== 'undefined' && f !== null && f.id !== context.formid) { 850 field = f.elements["javax.faces.ViewState"]; 851 if (typeof field === 'undefined') { 852 field = document.createElement("input"); 853 field.type = "hidden"; 854 field.name = "javax.faces.ViewState"; 855 f.appendChild(field); 856 } 857 field.value = state.nodeValue; 858 } 859 } 860 } 861 } 862 return; 863 } else if (id.match(windowIdRegex)) { 864 865 windowId = element.firstChild; 866 867 // Now set the windowId from the server into the DOM 868 // but only for the form that submitted the request. 869 870 windowIdForm = document.getElementById(context.formid); 871 if (!windowIdForm || !windowIdForm.elements) { 872 // if the form went away for some reason, or it lacks elements 873 // we're going to just return silently. 874 return; 875 } 876 var field = windowIdForm.elements["javax.faces.WindowId"]; 877 if (typeof field == 'undefined') { 878 field = document.createElement("input"); 879 field.type = "hidden"; 880 field.name = "javax.faces.WindowId"; 881 windowIdForm.appendChild(field); 882 } 883 field.value = windowId.nodeValue; 884 885 // Now set the windowId from the server into the DOM 886 // for any form that is a render target. 887 888 if (typeof context.render !== 'undefined' && context.render !== null) { 889 var temp = context.render.split(' '); 890 for (var i = 0; i < temp.length; i++) { 891 if (temp.hasOwnProperty(i)) { 892 // See if the element is a form and 893 // the form is not the one that caused the submission.. 894 var f = document.forms[temp[i]]; 895 if (typeof f !== 'undefined' && f !== null && f.id !== context.formid) { 896 field = f.elements["javax.faces.WindowId"]; 897 if (typeof field === 'undefined') { 898 field = document.createElement("input"); 899 field.type = "hidden"; 900 field.name = "javax.faces.WindowId"; 901 f.appendChild(field); 902 } 903 field.value = windowId.nodeValue; 904 } 905 } 906 } 907 } 908 return; 909 } 910 911 // join the CDATA sections in the markup 912 markup = ''; 913 for (var j = 0; j < element.childNodes.length; j++) { 914 content = element.childNodes[j]; 915 markup += content.nodeValue; 916 } 917 918 var src = markup; 919 920 // If our special render all markup is present.. 921 if (id === "javax.faces.ViewRoot" || id === "javax.faces.ViewBody") { 922 var bodyStartEx = new RegExp("< *body[^>]*>", "gi"); 923 var bodyEndEx = new RegExp("< */ *body[^>]*>", "gi"); 924 var newsrc; 925 926 var docBody = document.getElementsByTagName("body")[0]; 927 var bodyStart = bodyStartEx.exec(src); 928 929 if (bodyStart !== null) { // replace body tag 930 // First, try with XML manipulation 931 try { 932 // Get scripts from text 933 scripts = stripScripts(src); 934 // Remove scripts from text 935 newsrc = src.replace(/<script[^>]*>([\S\s]*?)<\/script>/igm, ""); 936 elementReplace(getBodyElement(newsrc), docBody); 937 runScripts(scripts); 938 } catch (e) { 939 // OK, replacing the body didn't work with XML - fall back to quirks mode insert 940 var srcBody, bodyEnd; 941 // if src contains </body> 942 bodyEnd = bodyEndEx.exec(src); 943 if (bodyEnd !== null) { 944 srcBody = src.substring(bodyStartEx.lastIndex, 945 bodyEnd.index); 946 } else { // can't find the </body> tag, punt 947 srcBody = src.substring(bodyStartEx.lastIndex); 948 } 949 // replace body contents with innerHTML - note, script handling happens within function 950 elementReplaceStr(docBody, "body", srcBody); 951 952 } 953 954 } else { // replace body contents with innerHTML - note, script handling happens within function 955 elementReplaceStr(docBody, "body", src); 956 } 957 } else if (id === "javax.faces.ViewHead") { 958 throw new Error("javax.faces.ViewHead not supported - browsers cannot reliably replace the head's contents"); 959 } else { 960 var d = $(id); 961 if (!d) { 962 throw new Error("During update: " + id + " not found"); 963 } 964 var parent = d.parentNode; 965 // Trim space padding before assigning to innerHTML 966 var html = src.replace(/^\s+/g, '').replace(/\s+$/g, ''); 967 var parserElement = document.createElement('div'); 968 var tag = d.nodeName.toLowerCase(); 969 var tableElements = ['td', 'th', 'tr', 'tbody', 'thead', 'tfoot']; 970 var isInTable = false; 971 for (var tei = 0, tel = tableElements.length; tei < tel; tei++) { 972 if (tableElements[tei] == tag) { 973 isInTable = true; 974 break; 975 } 976 } 977 if (isInTable) { 978 979 if (isAutoExec()) { 980 // Create html 981 parserElement.innerHTML = '<table>' + html + '</table>'; 982 } else { 983 // Get the scripts from the text 984 scripts = stripScripts(html); 985 // Remove scripts from text 986 html = html.replace(/<script[^>]*>([\S\s]*?)<\/script>/igm,""); 987 parserElement.innerHTML = '<table>' + html + '</table>'; 988 } 989 var newElement = parserElement.firstChild; 990 //some browsers will also create intermediary elements such as table>tbody>tr>td 991 while ((null !== newElement) && (id !== newElement.id)) { 992 newElement = newElement.firstChild; 993 } 994 parent.replaceChild(newElement, d); 995 runScripts(scripts); 996 } else if (d.nodeName.toLowerCase() === 'input') { 997 // special case handling for 'input' elements 998 // in order to not lose focus when updating, 999 // input elements need to be added in place. 1000 parserElement = document.createElement('div'); 1001 parserElement.innerHTML = html; 1002 newElement = parserElement.firstChild; 1003 1004 cloneAttributes(d, newElement); 1005 deleteNode(parserElement); 1006 } else if (html.length > 0) { 1007 if (isAutoExec()) { 1008 // Create html 1009 parserElement.innerHTML = html; 1010 } else { 1011 // Get the scripts from the text 1012 scripts = stripScripts(html); 1013 // Remove scripts from text 1014 html = html.replace(/<script[^>]*>([\S\s]*?)<\/script>/igm,""); 1015 parserElement.innerHTML = html; 1016 } 1017 replaceNode(parserElement.firstChild, d); 1018 deleteNode(parserElement); 1019 runScripts(scripts); 1020 } 1021 } 1022 }; 1023 1024 /** 1025 * Delete a node specified by the element. 1026 * @param element 1027 * @ignore 1028 */ 1029 var doDelete = function doDelete(element) { 1030 var id = element.getAttribute('id'); 1031 var target = $(id); 1032 deleteNode(target); 1033 }; 1034 1035 /** 1036 * Insert a node specified by the element. 1037 * @param element 1038 * @ignore 1039 */ 1040 var doInsert = function doInsert(element) { 1041 var tablePattern = new RegExp("<\\s*(td|th|tr|tbody|thead|tfoot)", "i"); 1042 var scripts = []; 1043 var target = $(element.firstChild.getAttribute('id')); 1044 var parent = target.parentNode; 1045 var html = element.firstChild.firstChild.nodeValue; 1046 var isInTable = tablePattern.test(html); 1047 1048 if (!isAutoExec()) { 1049 // Get the scripts from the text 1050 scripts = stripScripts(html); 1051 // Remove scripts from text 1052 html = html.replace(/<script[^>]*>([\S\s]*?)<\/script>/igm,""); 1053 } 1054 var tempElement = document.createElement('div'); 1055 var newElement = null; 1056 if (isInTable) { 1057 tempElement.innerHTML = '<table>' + html + '</table>'; 1058 newElement = tempElement.firstChild; 1059 //some browsers will also create intermediary elements such as table>tbody>tr>td 1060 //test for presence of id on the new element since we do not have it directly 1061 while ((null !== newElement) && ("" == newElement.id)) { 1062 newElement = newElement.firstChild; 1063 } 1064 } else { 1065 tempElement.innerHTML = html; 1066 newElement = tempElement.firstChild; 1067 } 1068 1069 if (element.firstChild.nodeName === 'after') { 1070 // Get the next in the list, to insert before 1071 target = target.nextSibling; 1072 } // otherwise, this is a 'before' element 1073 if (!!tempElement.innerHTML) { // check if only scripts were inserted - if so, do nothing here 1074 parent.insertBefore(newElement, target); 1075 } 1076 runScripts(scripts); 1077 deleteNode(tempElement); 1078 }; 1079 1080 /** 1081 * Modify attributes of given element id. 1082 * @param element 1083 * @ignore 1084 */ 1085 var doAttributes = function doAttributes(element) { 1086 1087 // Get id of element we'll act against 1088 var id = element.getAttribute('id'); 1089 1090 var target = $(id); 1091 1092 if (!target) { 1093 throw new Error("The specified id: " + id + " was not found in the page."); 1094 } 1095 1096 // There can be multiple attributes modified. Loop through the list. 1097 var nodes = element.childNodes; 1098 for (var i = 0; i < nodes.length; i++) { 1099 var name = nodes[i].getAttribute('name'); 1100 var value = nodes[i].getAttribute('value'); 1101 if (!isIE()) { 1102 target.setAttribute(name, value); 1103 } else { // if it's IE, then quite a bit more work is required 1104 if (name === 'class') { 1105 name = 'className'; 1106 target.setAttribute(name, value, 0); 1107 } else if (name === "for") { 1108 name = 'htmlFor'; 1109 target.setAttribute(name, value, 0); 1110 } else if (name === 'style') { 1111 target.style.setAttribute('cssText', value, 0); 1112 } else if (name.substring(0, 2) === 'on') { 1113 var fn = function(value) { 1114 return function() { 1115 window.execScript(value); 1116 }; 1117 }(value); 1118 target.setAttribute(name, fn, 0); 1119 } else if (name === 'dir') { 1120 if (jsf.getProjectStage() == 'Development') { 1121 throw new Error("Cannot set 'dir' attribute in IE"); 1122 } 1123 } else { 1124 target.setAttribute(name, value, 0); 1125 } 1126 } 1127 } 1128 }; 1129 1130 /** 1131 * Eval the CDATA of the element. 1132 * @param element to eval 1133 * @ignore 1134 */ 1135 var doEval = function doEval(element) { 1136 var evalText = element.firstChild.nodeValue; 1137 globalEval(evalText); 1138 }; 1139 1140 /** 1141 * Ajax Request Queue 1142 * @ignore 1143 */ 1144 var Queue = new function Queue() { 1145 1146 // Create the internal queue 1147 var queue = []; 1148 1149 1150 // the amount of space at the front of the queue, initialised to zero 1151 var queueSpace = 0; 1152 1153 /** Returns the size of this Queue. The size of a Queue is equal to the number 1154 * of elements that have been enqueued minus the number of elements that have 1155 * been dequeued. 1156 * @ignore 1157 */ 1158 this.getSize = function getSize() { 1159 return queue.length - queueSpace; 1160 }; 1161 1162 /** Returns true if this Queue is empty, and false otherwise. A Queue is empty 1163 * if the number of elements that have been enqueued equals the number of 1164 * elements that have been dequeued. 1165 * @ignore 1166 */ 1167 this.isEmpty = function isEmpty() { 1168 return (queue.length === 0); 1169 }; 1170 1171 /** Enqueues the specified element in this Queue. 1172 * 1173 * @param element - the element to enqueue 1174 * @ignore 1175 */ 1176 this.enqueue = function enqueue(element) { 1177 // Queue the request 1178 queue.push(element); 1179 }; 1180 1181 1182 /** Dequeues an element from this Queue. The oldest element in this Queue is 1183 * removed and returned. If this Queue is empty then undefined is returned. 1184 * 1185 * @returns Object The element that was removed from the queue. 1186 * @ignore 1187 */ 1188 this.dequeue = function dequeue() { 1189 // initialise the element to return to be undefined 1190 var element = undefined; 1191 1192 // check whether the queue is empty 1193 if (queue.length) { 1194 // fetch the oldest element in the queue 1195 element = queue[queueSpace]; 1196 1197 // update the amount of space and check whether a shift should occur 1198 if (++queueSpace * 2 >= queue.length) { 1199 // set the queue equal to the non-empty portion of the queue 1200 queue = queue.slice(queueSpace); 1201 // reset the amount of space at the front of the queue 1202 queueSpace = 0; 1203 } 1204 } 1205 // return the removed element 1206 try { 1207 return element; 1208 } finally { 1209 element = null; // IE 6 leak prevention 1210 } 1211 }; 1212 1213 /** Returns the oldest element in this Queue. If this Queue is empty then 1214 * undefined is returned. This function returns the same value as the dequeue 1215 * function, but does not remove the returned element from this Queue. 1216 * @ignore 1217 */ 1218 this.getOldestElement = function getOldestElement() { 1219 // initialise the element to return to be undefined 1220 var element = undefined; 1221 1222 // if the queue is not element then fetch the oldest element in the queue 1223 if (queue.length) { 1224 element = queue[queueSpace]; 1225 } 1226 // return the oldest element 1227 try { 1228 return element; 1229 } finally { 1230 element = null; //IE 6 leak prevention 1231 } 1232 }; 1233 }(); 1234 1235 1236 /** 1237 * AjaxEngine handles Ajax implementation details. 1238 * @ignore 1239 */ 1240 var AjaxEngine = function AjaxEngine() { 1241 1242 var req = {}; // Request Object 1243 req.url = null; // Request URL 1244 req.context = {}; // Context of request and response 1245 req.context.sourceid = null; // Source of this request 1246 req.context.onerror = null; // Error handler for request 1247 req.context.onevent = null; // Event handler for request 1248 req.context.formid = null; // Form that's the context for this request 1249 req.xmlReq = null; // XMLHttpRequest Object 1250 req.async = true; // Default - Asynchronous 1251 req.parameters = {}; // Parameters For GET or POST 1252 req.queryString = null; // Encoded Data For GET or POST 1253 req.method = null; // GET or POST 1254 req.status = null; // Response Status Code From Server 1255 req.fromQueue = false; // Indicates if the request was taken off the queue 1256 // before being sent. This prevents the request from 1257 // entering the queue redundantly. 1258 1259 req.que = Queue; 1260 1261 // Get an XMLHttpRequest Handle 1262 req.xmlReq = getTransport(); 1263 if (req.xmlReq === null) { 1264 return null; 1265 } 1266 1267 function noop() {} 1268 1269 // Set up request/response state callbacks 1270 /** 1271 * @ignore 1272 */ 1273 req.xmlReq.onreadystatechange = function() { 1274 if (req.xmlReq.readyState === 4) { 1275 req.onComplete(); 1276 // next two lines prevent closure/ciruclar reference leaks 1277 // of XHR instances in IE 1278 req.xmlReq.onreadystatechange = noop; 1279 req.xmlReq = null; 1280 } 1281 }; 1282 1283 /** 1284 * This function is called when the request/response interaction 1285 * is complete. If the return status code is successfull, 1286 * dequeue all requests from the queue that have completed. If a 1287 * request has been found on the queue that has not been sent, 1288 * send the request. 1289 * @ignore 1290 */ 1291 req.onComplete = function onComplete() { 1292 if (req.xmlReq.status && (req.xmlReq.status >= 200 && req.xmlReq.status < 300)) { 1293 sendEvent(req.xmlReq, req.context, "complete"); 1294 jsf.ajax.response(req.xmlReq, req.context); 1295 } else { 1296 sendEvent(req.xmlReq, req.context, "complete"); 1297 sendError(req.xmlReq, req.context, "httpError"); 1298 } 1299 1300 // Regardless of whether the request completed successfully (or not), 1301 // dequeue requests that have been completed (readyState 4) and send 1302 // requests that ready to be sent (readyState 0). 1303 1304 var nextReq = req.que.getOldestElement(); 1305 if (nextReq === null || typeof nextReq === 'undefined') { 1306 return; 1307 } 1308 while ((typeof nextReq.xmlReq !== 'undefined' && nextReq.xmlReq !== null) && 1309 nextReq.xmlReq.readyState === 4) { 1310 req.que.dequeue(); 1311 nextReq = req.que.getOldestElement(); 1312 if (nextReq === null || typeof nextReq === 'undefined') { 1313 break; 1314 } 1315 } 1316 if (nextReq === null || typeof nextReq === 'undefined') { 1317 return; 1318 } 1319 if ((typeof nextReq.xmlReq !== 'undefined' && nextReq.xmlReq !== null) && 1320 nextReq.xmlReq.readyState === 0) { 1321 nextReq.fromQueue = true; 1322 nextReq.sendRequest(); 1323 } 1324 }; 1325 1326 /** 1327 * Utility method that accepts additional arguments for the AjaxEngine. 1328 * If an argument is passed in that matches an AjaxEngine property, the 1329 * argument value becomes the value of the AjaxEngine property. 1330 * Arguments that don't match AjaxEngine properties are added as 1331 * request parameters. 1332 * @ignore 1333 */ 1334 req.setupArguments = function(args) { 1335 for (var i in args) { 1336 if (args.hasOwnProperty(i)) { 1337 if (typeof req[i] === 'undefined') { 1338 req.parameters[i] = args[i]; 1339 } else { 1340 req[i] = args[i]; 1341 } 1342 } 1343 } 1344 }; 1345 1346 /** 1347 * This function does final encoding of parameters, determines the request method 1348 * (GET or POST) and sends the request using the specified url. 1349 * @ignore 1350 */ 1351 req.sendRequest = function() { 1352 if (req.xmlReq !== null) { 1353 // if there is already a request on the queue waiting to be processed.. 1354 // just queue this request 1355 if (!req.que.isEmpty()) { 1356 if (!req.fromQueue) { 1357 req.que.enqueue(req); 1358 return; 1359 } 1360 } 1361 // If the queue is empty, queue up this request and send 1362 if (!req.fromQueue) { 1363 req.que.enqueue(req); 1364 } 1365 // Some logic to get the real request URL 1366 if (req.generateUniqueUrl && req.method == "GET") { 1367 req.parameters["AjaxRequestUniqueId"] = new Date().getTime() + "" + req.requestIndex; 1368 } 1369 var content = null; // For POST requests, to hold query string 1370 for (var i in req.parameters) { 1371 if (req.parameters.hasOwnProperty(i)) { 1372 if (req.queryString.length > 0) { 1373 req.queryString += "&"; 1374 } 1375 req.queryString += encodeURIComponent(i) + "=" + encodeURIComponent(req.parameters[i]); 1376 } 1377 } 1378 if (req.method === "GET") { 1379 if (req.queryString.length > 0) { 1380 req.url += ((req.url.indexOf("?") > -1) ? "&" : "?") + req.queryString; 1381 } 1382 } 1383 req.xmlReq.open(req.method, req.url, req.async); 1384 // note that we are including the charset=UTF-8 as part of the content type (even 1385 // if encodeURIComponent encodes as UTF-8), because with some 1386 // browsers it will not be set in the request. Some server implementations need to 1387 // determine the character encoding from the request header content type. 1388 if (req.method === "POST") { 1389 if (typeof req.xmlReq.setRequestHeader !== 'undefined') { 1390 req.xmlReq.setRequestHeader('Faces-Request', 'partial/ajax'); 1391 req.xmlReq.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;charset=UTF-8'); 1392 } 1393 content = req.queryString; 1394 } 1395 // note that async == false is not a supported feature. We may change it in ways 1396 // that break existing programs at any time, with no warning. 1397 if(!req.async) { 1398 req.xmlReq.onreadystatechange = null; // no need for readystate change listening 1399 } 1400 sendEvent(req.xmlReq, req.context, "begin"); 1401 req.xmlReq.send(content); 1402 if(!req.async){ 1403 req.onComplete(); 1404 } 1405 } 1406 }; 1407 1408 return req; 1409 }; 1410 1411 /** 1412 * Error handling callback. 1413 * Assumes that the request has completed. 1414 * @ignore 1415 */ 1416 var sendError = function sendError(request, context, status, description, serverErrorName, serverErrorMessage) { 1417 1418 // Possible errornames: 1419 // httpError 1420 // emptyResponse 1421 // serverError 1422 // malformedXML 1423 1424 var sent = false; 1425 var data = {}; // data payload for function 1426 data.type = "error"; 1427 data.status = status; 1428 data.source = context.sourceid; 1429 data.responseCode = request.status; 1430 data.responseXML = request.responseXML; 1431 data.responseText = request.responseText; 1432 1433 // ensure data source is the dom element and not the ID 1434 // per 14.4.1 of the 2.0 specification. 1435 if (typeof data.source === 'string') { 1436 data.source = document.getElementById(data.source); 1437 } 1438 1439 if (description) { 1440 data.description = description; 1441 } else if (status == "httpError") { 1442 if (data.responseCode === 0) { 1443 data.description = "The Http Transport returned a 0 status code. This is usually the result of mixing ajax and full requests. This is usually undesired, for both performance and data integrity reasons."; 1444 } else { 1445 data.description = "There was an error communicating with the server, status: " + data.responseCode; 1446 } 1447 } else if (status == "serverError") { 1448 data.description = serverErrorMessage; 1449 } else if (status == "emptyResponse") { 1450 data.description = "An empty response was received from the server. Check server error logs."; 1451 } else if (status == "malformedXML") { 1452 if (getParseErrorText(data.responseXML) !== PARSED_OK) { 1453 data.description = getParseErrorText(data.responseXML); 1454 } else { 1455 data.description = "An invalid XML response was received from the server."; 1456 } 1457 } 1458 1459 if (status == "serverError") { 1460 data.errorName = serverErrorName; 1461 data.errorMessage = serverErrorMessage; 1462 } 1463 1464 // If we have a registered callback, send the error to it. 1465 if (context.onerror) { 1466 context.onerror.call(null, data); 1467 sent = true; 1468 } 1469 1470 for (var i in errorListeners) { 1471 if (errorListeners.hasOwnProperty(i)) { 1472 errorListeners[i].call(null, data); 1473 sent = true; 1474 } 1475 } 1476 1477 if (!sent && jsf.getProjectStage() === "Development") { 1478 if (status == "serverError") { 1479 alert("serverError: " + serverErrorName + " " + serverErrorMessage); 1480 } else { 1481 alert(status + ": " + data.description); 1482 } 1483 } 1484 }; 1485 1486 /** 1487 * Event handling callback. 1488 * Request is assumed to have completed, except in the case of event = 'begin'. 1489 * @ignore 1490 */ 1491 var sendEvent = function sendEvent(request, context, status) { 1492 1493 var data = {}; 1494 data.type = "event"; 1495 data.status = status; 1496 data.source = context.sourceid; 1497 // ensure data source is the dom element and not the ID 1498 // per 14.4.1 of the 2.0 specification. 1499 if (typeof data.source === 'string') { 1500 data.source = document.getElementById(data.source); 1501 } 1502 if (status !== 'begin') { 1503 data.responseCode = request.status; 1504 data.responseXML = request.responseXML; 1505 data.responseText = request.responseText; 1506 } 1507 1508 if (context.onevent) { 1509 context.onevent.call(null, data); 1510 } 1511 1512 for (var i in eventListeners) { 1513 if (eventListeners.hasOwnProperty(i)) { 1514 eventListeners[i].call(null, data); 1515 } 1516 } 1517 }; 1518 1519 // Use module pattern to return the functions we actually expose 1520 return { 1521 /** 1522 * Register a callback for error handling. 1523 * <p><b>Usage:</b></p> 1524 * <pre><code> 1525 * jsf.ajax.addOnError(handleError); 1526 * ... 1527 * var handleError = function handleError(data) { 1528 * ... 1529 * } 1530 * </pre></code> 1531 * <p><b>Implementation Requirements:</b></p> 1532 * This function must accept a reference to an existing JavaScript function. 1533 * The JavaScript function reference must be added to a list of callbacks, making it possible 1534 * to register more than one callback by invoking <code>jsf.ajax.addOnError</code> 1535 * more than once. This function must throw an error if the <code>callback</code> 1536 * argument is not a function. 1537 * 1538 * @member jsf.ajax 1539 * @param callback a reference to a function to call on an error 1540 */ 1541 addOnError: function addOnError(callback) { 1542 if (typeof callback === 'function') { 1543 errorListeners[errorListeners.length] = callback; 1544 } else { 1545 throw new Error("jsf.ajax.addOnError: Added a callback that was not a function."); 1546 } 1547 }, 1548 /** 1549 * Register a callback for event handling. 1550 * <p><b>Usage:</b></p> 1551 * <pre><code> 1552 * jsf.ajax.addOnEvent(statusUpdate); 1553 * ... 1554 * var statusUpdate = function statusUpdate(data) { 1555 * ... 1556 * } 1557 * </pre></code> 1558 * <p><b>Implementation Requirements:</b></p> 1559 * This function must accept a reference to an existing JavaScript function. 1560 * The JavaScript function reference must be added to a list of callbacks, making it possible 1561 * to register more than one callback by invoking <code>jsf.ajax.addOnEvent</code> 1562 * more than once. This function must throw an error if the <code>callback</code> 1563 * argument is not a function. 1564 * 1565 * @member jsf.ajax 1566 * @param callback a reference to a function to call on an event 1567 */ 1568 addOnEvent: function addOnEvent(callback) { 1569 if (typeof callback === 'function') { 1570 eventListeners[eventListeners.length] = callback; 1571 } else { 1572 throw new Error("jsf.ajax.addOnEvent: Added a callback that was not a function"); 1573 } 1574 }, 1575 /** 1576 1577 * <p><span class="changed_modified_2_2">Send</span> an 1578 * asynchronous Ajax req uest to the server. 1579 1580 * <p><b>Usage:</b></p> 1581 * <pre><code> 1582 * Example showing all optional arguments: 1583 * 1584 * <commandButton id="button1" value="submit" 1585 * onclick="jsf.ajax.request(this,event, 1586 * {execute:'button1',render:'status',onevent: handleEvent,onerror: handleError});return false;"/> 1587 * </commandButton/> 1588 * </pre></code> 1589 * <p><b>Implementation Requirements:</b></p> 1590 * This function must: 1591 * <ul> 1592 * <li>Be used within the context of a <code>form</code>.</li> 1593 * <li>Capture the element that triggered this Ajax request 1594 * (from the <code>source</code> argument, also known as the 1595 * <code>source</code> element.</li> 1596 * <li>If the <code>source</code> element is <code>null</code> or 1597 * <code>undefined</code> throw an error.</li> 1598 * <li>If the <code>source</code> argument is not a <code>string</code> or 1599 * DOM element object, throw an error.</li> 1600 * <li>If the <code>source</code> argument is a <code>string</code>, find the 1601 * DOM element for that <code>string</code> identifier. 1602 * <li>If the DOM element could not be determined, throw an error.</li> 1603 * <li>If the <code>onerror</code> and <code>onevent</code> arguments are set, 1604 * they must be functions, or throw an error. 1605 * <li>Determine the <code>source</code> element's <code>form</code> 1606 * element.</li> 1607 * <li>Get the <code>form</code> view state by calling 1608 * {@link jsf.getViewState} passing the 1609 * <code>form</code> element as the argument.</li> 1610 * <li>Collect post data arguments for the Ajax request. 1611 * <ul> 1612 * <li>The following name/value pairs are required post data arguments: 1613 * <table border="1"> 1614 * <tr> 1615 * <th>name</th> 1616 * <th>value</th> 1617 * </tr> 1618 * <tr> 1619 * <td><code>javax.faces.ViewState</code></td> 1620 * <td><code>Contents of javax.faces.ViewState hidden field. This is included when 1621 * {@link jsf.getViewState} is used.</code></td> 1622 * </tr> 1623 * <tr> 1624 * <td><code>javax.faces.partial.ajax</code></td> 1625 * <td><code>true</code></td> 1626 * </tr> 1627 * <tr> 1628 * <td><code>javax.faces.source</code></td> 1629 * <td><code>The identifier of the element that triggered this request.</code></td> 1630 * </tr> 1631 * </table> 1632 * </li> 1633 * </ul> 1634 * </li> 1635 * <li>Collect optional post data arguments for the Ajax request. 1636 * <ul> 1637 * <li>Determine additional arguments (if any) from the <code>options</code> 1638 * argument. If <code>options.execute</code> exists: 1639 * <ul> 1640 * <li>If the keyword <code>@none</code> is present, do not create and send 1641 * the post data argument <code>javax.faces.partial.execute</code>.</li> 1642 * <li>If the keyword <code>@all</code> is present, create the post data argument with 1643 * the name <code>javax.faces.partial.execute</code> and the value <code>@all</code>.</li> 1644 * <li>Otherwise, there are specific identifiers that need to be sent. Create the post 1645 * data argument with the name <code>javax.faces.partial.execute</code> and the value as a 1646 * space delimited <code>string</code> of client identifiers.</li> 1647 * </ul> 1648 * </li> 1649 * <li>If <code>options.execute</code> does not exist, create the post data argument with the 1650 * name <code>javax.faces.partial.execute</code> and the value as the identifier of the 1651 * element that caused this request.</li> 1652 * <li>If <code>options.render</code> exists: 1653 * <ul> 1654 * <li>If the keyword <code>@none</code> is present, do not create and send 1655 * the post data argument <code>javax.faces.partial.render</code>.</li> 1656 * <li>If the keyword <code>@all</code> is present, create the post data argument with 1657 * the name <code>javax.faces.partial.render</code> and the value <code>@all</code>.</li> 1658 * <li>Otherwise, there are specific identifiers that need to be sent. Create the post 1659 * data argument with the name <code>javax.faces.partial.render</code> and the value as a 1660 * space delimited <code>string</code> of client identifiers.</li> 1661 * </ul> 1662 * <li>If <code>options.render</code> does not exist do not create and send the 1663 * post data argument <code>javax.faces.partial.render</code>.</li> 1664 1665 * <li class="changed_added_2_2">If 1666 * <code>options.render</code> exists let it be the value 1667 * <em>delay</em>, for this discussion. If 1668 * <code>options.render</code> does not exist let 1669 * <em>delay</em> be 300. If less than <em>delay</em> 1670 * milliseconds elapses between calls to <em>request()</em> 1671 * only the most recent one is sent and all other requests 1672 * are discarded. The default value of this option is 300. 1673 * If the value of <em>delay</em> is the literal string 1674 * <code>'none'</code> without the quotes, no delay is 1675 * used. </li> 1676 1677 * <li>Determine additional arguments (if any) from the <code>event</code> 1678 * argument. The following name/value pairs may be used from the 1679 * <code>event</code> object: 1680 * <ul> 1681 * <li><code>target</code> - the ID of the element that triggered the event.</li> 1682 * <li><code>captured</code> - the ID of the element that captured the event.</li> 1683 * <li><code>type</code> - the type of event (ex: onkeypress)</li> 1684 * <li><code>alt</code> - <code>true</code> if ALT key was pressed.</li> 1685 * <li><code>ctrl</code> - <code>true</code> if CTRL key was pressed.</li> 1686 * <li><code>shift</code> - <code>true</code> if SHIFT key was pressed. </li> 1687 * <li><code>meta</code> - <code>true</code> if META key was pressed. </li> 1688 * <li><code>right</code> - <code>true</code> if right mouse button 1689 * was pressed. </li> 1690 * <li><code>left</code> - <code>true</code> if left mouse button 1691 * was pressed. </li> 1692 * <li><code>keycode</code> - the key code. 1693 * </ul> 1694 * </li> 1695 * </ul> 1696 * </li> 1697 * <li>Encode the set of post data arguments.</li> 1698 * <li>Join the encoded view state with the encoded set of post data arguments 1699 * to form the <code>query string</code> that will be sent to the server.</li> 1700 * <li>Create a request <code>context</code> object and set the properties: 1701 * <ul><li><code>source</code> (the source DOM element for this request)</li> 1702 * <li><code>onerror</code> (the error handler for this request)</li> 1703 * <li><code>onevent</code> (the event handler for this request)</li></ul> 1704 * The request context will be used during error/event handling.</li> 1705 * <li>Send a <code>begin</code> event following the procedure as outlined 1706 * in the Chapter 13 "Sending Events" section of the spec prose document <a 1707 * href="../../javadocs/overview-summary.html#prose_document">linked in the 1708 * overview summary</a></li> 1709 * <li>Set the request header with the name: <code>Faces-Request</code> and the 1710 * value: <code>partial/ajax</code>.</li> 1711 * <li>Determine the <code>posting URL</code> as follows: If the hidden field 1712 * <code>javax.faces.encodedURL</code> is present in the submitting form, use its 1713 * value as the <code>posting URL</code>. Otherwise, use the <code>action</code> 1714 * property of the <code>form</code> element as the <code>URL</code>.</li> 1715 * <li>Send the request as an <code>asynchronous POST</code> using the 1716 * <code>posting URL</code> that was determined in the previous step.</li> 1717 * </ul> 1718 * Form serialization should occur just before the request is sent to minimize 1719 * the amount of time between the creation of the serialized form data and the 1720 * sending of the serialized form data (in the case of long requests in the queue). 1721 * Before the request is sent it must be put into a queue to ensure requests 1722 * are sent in the same order as when they were initiated. The request callback function 1723 * must examine the queue and determine the next request to be sent. The behavior of the 1724 * request callback function must be as follows: 1725 * <ul> 1726 * <li>If the request completed successfully invoke {@link jsf.ajax.response} 1727 * passing the <code>request</code> object.</li> 1728 * <li>If the request did not complete successfully, notify the client.</li> 1729 * <li>Regardless of the outcome of the request (success or error) every request in the 1730 * queue must be handled. Examine the status of each request in the queue starting from 1731 * the request that has been in the queue the longest. If the status of the request is 1732 * <code>complete</code> (readyState 4), dequeue the request (remove it from the queue). 1733 * If the request has not been sent (readyState 0), send the request. Requests that are 1734 * taken off the queue and sent should not be put back on the queue.</li> 1735 * </ul> 1736 * 1737 * </p> 1738 * 1739 * @param source The DOM element that triggered this Ajax request, or an id string of the 1740 * element to use as the triggering element. 1741 * @param event The DOM event that triggered this Ajax request. The 1742 * <code>event</code> argument is optional. 1743 * @param options The set of available options that can be sent as 1744 * request parameters to control client and/or server side 1745 * request processing. Acceptable name/value pair options are: 1746 * <table border="1"> 1747 * <tr> 1748 * <th>name</th> 1749 * <th>value</th> 1750 * </tr> 1751 * <tr> 1752 * <td><code>execute</code></td> 1753 * <td><code>space seperated list of client identifiers</code></td> 1754 * </tr> 1755 * <tr> 1756 * <td><code>render</code></td> 1757 * <td><code>space seperated list of client identifiers</code></td> 1758 * </tr> 1759 * <tr> 1760 * <td><code>onevent</code></td> 1761 * <td><code>function to callback for event</code></td> 1762 * </tr> 1763 * <tr> 1764 * <td><code>onerror</code></td> 1765 * <td><code>function to callback for error</code></td> 1766 * </tr> 1767 * <tr> 1768 * <td><code>params</code></td> 1769 * <td><code>object containing parameters to include in the request</code></td> 1770 * </tr> 1771 1772 * <tr class="changed_added_2_2"> 1773 1774 * <td><code>delay</code></td> 1775 1776 * <td><code>If less than <em>delay</em> milliseconds 1777 * elapses between calls to <em>request()</em> only the most 1778 * recent one is sent and all other requests are 1779 * discarded. The default value of this option is 1780 * 300.</code> If the value of <em>delay</em> is the literal string 1781 * <code>'none'</code> without the quotes, no delay is 1782 * used. </td> 1783 1784 * </tr> 1785 1786 * </table> 1787 * The <code>options</code> argument is optional. 1788 * @member jsf.ajax 1789 * @function jsf.ajax.request 1790 * @throws Error if first required argument <code>element</code> is not specified 1791 */ 1792 request: function request(source, event, options) { 1793 1794 var element, form; // Element variables 1795 var all, none; 1796 1797 if (typeof source === 'undefined' || source === null) { 1798 throw new Error("jsf.ajax.request: source not set"); 1799 } 1800 if(delayHandler) { 1801 clearTimeout(delayHandler); 1802 delayHandler = null; 1803 } 1804 1805 // set up the element based on source 1806 if (typeof source === 'string') { 1807 element = document.getElementById(source); 1808 } else if (typeof source === 'object') { 1809 element = source; 1810 } else { 1811 throw new Error("jsf.request: source must be object or string"); 1812 } 1813 // attempt to handle case of name unset 1814 // this might be true in a badly written composite component 1815 if (!element.name) { 1816 element.name = element.id; 1817 } 1818 1819 if (typeof(options) === 'undefined' || options === null) { 1820 options = {}; 1821 } 1822 1823 // Error handler for this request 1824 var onerror = false; 1825 1826 if (options.onerror && typeof options.onerror === 'function') { 1827 onerror = options.onerror; 1828 } else if (options.onerror && typeof options.onerror !== 'function') { 1829 throw new Error("jsf.ajax.request: Added an onerror callback that was not a function"); 1830 } 1831 1832 // Event handler for this request 1833 var onevent = false; 1834 1835 if (options.onevent && typeof options.onevent === 'function') { 1836 onevent = options.onevent; 1837 } else if (options.onevent && typeof options.onevent !== 'function') { 1838 throw new Error("jsf.ajax.request: Added an onevent callback that was not a function"); 1839 } 1840 1841 form = getForm(element); 1842 if (!form) { 1843 throw new Error("jsf.ajax.request: Method must be called within a form"); 1844 } 1845 var viewState = jsf.getViewState(form); 1846 1847 // Set up additional arguments to be used in the request.. 1848 // Make sure "javax.faces.source" is set up. 1849 // If there were "execute" ids specified, make sure we 1850 // include the identifier of the source element in the 1851 // "execute" list. If there were no "execute" ids 1852 // specified, determine the default. 1853 1854 var args = {}; 1855 1856 args["javax.faces.source"] = element.id; 1857 1858 if (event && !!event.type) { 1859 args["javax.faces.partial.event"] = event.type; 1860 } 1861 1862 // If we have 'execute' identifiers: 1863 // Handle any keywords that may be present. 1864 // If @none present anywhere, do not send the 1865 // "javax.faces.partial.execute" parameter. 1866 // The 'execute' and 'render' lists must be space 1867 // delimited. 1868 1869 if (options.execute) { 1870 none = options.execute.search(/@none/); 1871 if (none < 0) { 1872 all = options.execute.search(/@all/); 1873 if (all < 0) { 1874 options.execute = options.execute.replace("@this", element.id); 1875 options.execute = options.execute.replace("@form", form.id); 1876 var temp = options.execute.split(' '); 1877 if (!isInArray(temp, element.name)) { 1878 options.execute = element.name + " " + options.execute; 1879 } 1880 } else { 1881 options.execute = "@all"; 1882 } 1883 args["javax.faces.partial.execute"] = options.execute; 1884 } 1885 } else { 1886 options.execute = element.name + " " + element.id; 1887 args["javax.faces.partial.execute"] = options.execute; 1888 } 1889 1890 if (options.render) { 1891 none = options.render.search(/@none/); 1892 if (none < 0) { 1893 all = options.render.search(/@all/); 1894 if (all < 0) { 1895 options.render = options.render.replace("@this", element.id); 1896 options.render = options.render.replace("@form", form.id); 1897 } else { 1898 options.render = "@all"; 1899 } 1900 args["javax.faces.partial.render"] = options.render; 1901 } 1902 } 1903 var defaultDelayValue = 300; 1904 var explicitlyDoNotDelay = (typeof options.delay == 'string') && 1905 (options.delay.toLowerCase() == 'none'); 1906 var delayValue; 1907 if (typeof options.delay == 'undefined') { 1908 delayValue = defaultDelayValue; 1909 } else if (typeof options.delay == 'number') { 1910 delayValue = options.delay; 1911 } else if (!explicitlyDoNotDelay) { 1912 throw new Error('invalid value for delay option: ' + options.delay); 1913 } 1914 1915 // remove non-passthrough options 1916 delete options.execute; 1917 delete options.render; 1918 delete options.onerror; 1919 delete options.onevent; 1920 delete options.delay; 1921 1922 // copy all other options to args 1923 for (var property in options) { 1924 if (options.hasOwnProperty(property)) { 1925 args[property] = options[property]; 1926 } 1927 } 1928 1929 args["javax.faces.partial.ajax"] = "true"; 1930 args["method"] = "POST"; 1931 1932 // Determine the posting url 1933 1934 var encodedUrlField = form.elements["javax.faces.encodedURL"]; 1935 if (typeof encodedUrlField == 'undefined') { 1936 args["url"] = form.action; 1937 } else { 1938 args["url"] = encodedUrlField.value; 1939 } 1940 var sendRequest = function() { 1941 var ajaxEngine = new AjaxEngine(); 1942 ajaxEngine.setupArguments(args); 1943 ajaxEngine.queryString = viewState; 1944 ajaxEngine.context.onevent = onevent; 1945 ajaxEngine.context.onerror = onerror; 1946 ajaxEngine.context.sourceid = element.id; 1947 ajaxEngine.context.formid = form.id; 1948 ajaxEngine.context.render = args["javax.faces.partial.render"]; 1949 ajaxEngine.sendRequest(); 1950 1951 // null out element variables to protect against IE memory leak 1952 element = null; 1953 form = null; 1954 sendRequest = null; 1955 }; 1956 1957 if (explicitlyDoNotDelay) { 1958 sendRequest(); 1959 } else { 1960 delayHandler = setTimeout(sendRequest, delayValue); 1961 } 1962 1963 }, 1964 /** 1965 * <p><span class="changed_modified_2_2">Receive</span> an Ajax response 1966 * from the server. 1967 * <p><b>Usage:</b></p> 1968 * <pre><code> 1969 * jsf.ajax.response(request, context); 1970 * </pre></code> 1971 * <p><b>Implementation Requirements:</b></p> 1972 * This function must evaluate the markup returned in the 1973 * <code>request.responseXML</code> object and perform the following action: 1974 * <ul> 1975 * <p>If there is no XML response returned, signal an <code>emptyResponse</code> 1976 * error. If the XML response does not follow the format as outlined 1977 * in Appendix A of the spec prose document <a 1978 * href="../../javadocs/overview-summary.html#prose_document">linked in the 1979 * overview summary</a> signal a <code>malformedError</code> error. Refer to 1980 * section "Signaling Errors" in Chapter 13 of the spec prose document <a 1981 * href="../../javadocs/overview-summary.html#prose_document">linked in the 1982 * overview summary</a>.</p> 1983 * <p>If the response was successfully processed, send a <code>success</code> 1984 * event as outlined in Chapter 13 "Sending Events" section of the spec prose 1985 * document <a 1986 * href="../../javadocs/overview-summary.html#prose_document">linked in the 1987 * overview summary</a>.</p> 1988 * <p><i>Update Element Processing</i></p> 1989 * The <code>update</code> element is used to update a single DOM element. The 1990 * "id" attribute of the <code>update</code> element refers to the DOM element that 1991 * will be updated. The contents of the <code>CDATA</code> section is the data that 1992 * will be used when updating the contents of the DOM element as specified by the 1993 * <code><update></code> element identifier. 1994 * <li>If an <code>update</code> element is found in the response 1995 * with the identifier <code>javax.faces.ViewRoot</code>: 1996 * <pre><code><update id="javax.faces.ViewRoot"> 1997 * <![CDATA[...]]> 1998 * </update></code></pre> 1999 * Update the entire DOM replacing the appropriate <code>head</code> and/or 2000 * <code>body</code> sections with the content from the response.</li> 2001 2002 * <li class="changed_modified_2_2">If an 2003 * <code>update</code> element is found in the response with 2004 * an identifier containing 2005 * <code>javax.faces.ViewState</code>: 2006 2007 * <pre><code><update id="<VIEW_ROOT_CONTAINER_CLIENT_ID><SEP>javax.faces.ViewState<SEP><UNIQUE_PER_VIEW_NUMBER>"> 2008 * <![CDATA[...]]> 2009 * </update></code></pre> 2010 2011 * locate and update the submitting form's 2012 * <code>javax.faces.ViewState</code> value with the 2013 * <code>CDATA</code> contents from the response. 2014 * <SEP>: is the currently configured 2015 * <code>UINamingContainer.getSeparatorChar()</code>. 2016 * <VIEW_ROOT_CONTAINER_CLIENT_ID> is the return from 2017 * <code>UIViewRoot.getContainerClientId()</code> on the 2018 * view from whence this state originated. 2019 * <UNIQUE_PER_VIEW_NUMBER> is a number that must be 2020 * unique within this view, but must not be included in the 2021 * view state. This requirement is simply to satisfy XML 2022 * correctness in parity with what is done in the 2023 * corresponding non-partial JSF view. Locate and update 2024 * the <code>javax.faces.ViewState</code> value for all 2025 * forms specified in the <code>render</code> target 2026 * list.</li> 2027 2028 * <li class="changed_added_2_2">If an 2029 * <code>update</code> element is found in the response with 2030 * an identifier containing 2031 * <code>javax.faces.WindowId</code>: 2032 2033 * <pre><code><update id="<VIEW_ROOT_CONTAINER_CLIENT_ID><SEP>javax.faces.WindowId<SEP><UNIQUE_PER_VIEW_NUMBER>"> 2034 * <![CDATA[...]]> 2035 * </update></code></pre> 2036 2037 * locate and update the submitting form's 2038 * <code>javax.faces.WindowId</code> value with the 2039 * <code>CDATA</code> contents from the response. 2040 * <SEP>: is the currently configured 2041 * <code>UINamingContainer.getSeparatorChar()</code>. 2042 * <VIEW_ROOT_CONTAINER_CLIENT_ID> is the return from 2043 * <code>UIViewRoot.getContainerClientId()</code> on the 2044 * view from whence this state originated. 2045 * <UNIQUE_PER_VIEW_NUMBER> is a number that must be 2046 * unique within this view, but must not be included in the 2047 * view state. This requirement is simply to satisfy XML 2048 * correctness in parity with what is done in the 2049 * corresponding non-partial JSF view. Locate and update 2050 * the <code>javax.faces.WindowId</code> value for all 2051 * forms specified in the <code>render</code> target 2052 * list.</li> 2053 2054 2055 * <li>If an <code>update</code> element is found in the response with the identifier 2056 * <code>javax.faces.ViewHead</code>: 2057 * <pre><code><update id="javax.faces.ViewHead"> 2058 * <![CDATA[...]]> 2059 * </update></code></pre> 2060 * update the document's <code>head</code> section with the <code>CDATA</code> 2061 * contents from the response.</li> 2062 * <li>If an <code>update</code> element is found in the response with the identifier 2063 * <code>javax.faces.ViewBody</code>: 2064 * <pre><code><update id="javax.faces.ViewBody"> 2065 * <![CDATA[...]]> 2066 * </update></code></pre> 2067 * update the document's <code>body</code> section with the <code>CDATA</code> 2068 * contents from the response.</li> 2069 * <li>For any other <code><update></code> element: 2070 * <pre><code><update id="update id"> 2071 * <![CDATA[...]]> 2072 * </update></code></pre> 2073 * Find the DOM element with the identifier that matches the 2074 * <code><update></code> element identifier, and replace its contents with 2075 * the <code><update></code> element's <code>CDATA</code> contents.</li> 2076 * </li> 2077 * <p><i>Insert Element Processing</i></p> 2078 * <li>If an <code><insert></code> element is found in the response with the 2079 * attribute <code>before</code>: 2080 * <pre><code><insert id="insert id" before="before id"> 2081 * <![CDATA[...]]> 2082 * </insert></code></pre> 2083 * <ul> 2084 * <li>Extract this <code><insert></code> element's <code>CDATA</code> contents 2085 * from the response.</li> 2086 * <li>Find the DOM element whose identifier matches <code>before id</code> and insert 2087 * the <code><insert></code> element's <code>CDATA</code> content before 2088 * the DOM element in the document.</li> 2089 * </ul> 2090 * </li> 2091 * <li>If an <code><insert></code> element is found in the response with the 2092 * attribute <code>after</code>: 2093 * <pre><code><insert id="insert id" after="after id"> 2094 * <![CDATA[...]]> 2095 * </insert></code></pre> 2096 * <ul> 2097 * <li>Extract this <code><insert></code> element's <code>CDATA</code> contents 2098 * from the response.</li> 2099 * <li>Find the DOM element whose identifier matches <code>after id</code> and insert 2100 * the <code><insert></code> element's <code>CDATA</code> content after 2101 * the DOM element in the document.</li> 2102 * </ul> 2103 * </li> 2104 * <p><i>Delete Element Processing</i></p> 2105 * <li>If a <code><delete></code> element is found in the response: 2106 * <pre><code><delete id="delete id"/></code></pre> 2107 * Find the DOM element whose identifier matches <code>delete id</code> and remove it 2108 * from the DOM.</li> 2109 * <p><i>Element Attribute Update Processing</i></p> 2110 * <li>If an <code><attributes></code> element is found in the response: 2111 * <pre><code><attributes id="id of element with attribute"> 2112 * <attribute name="attribute name" value="attribute value"> 2113 * ... 2114 * </attributes></code></pre> 2115 * <ul> 2116 * <li>Find the DOM element that matches the <code><attributes></code> identifier.</li> 2117 * <li>For each nested <code><attribute></code> element in <code><attribute></code>, 2118 * update the DOM element attribute value (whose name matches <code>attribute name</code>), 2119 * with <code>attribute value</code>.</li> 2120 * </ul> 2121 * </li> 2122 * <p><i>JavaScript Processing</i></p> 2123 * <li>If an <code><eval></code> element is found in the response: 2124 * <pre><code><eval> 2125 * <![CDATA[...JavaScript...]]> 2126 * </eval></code></pre> 2127 * <ul> 2128 * <li>Extract this <code><eval></code> element's <code>CDATA</code> contents 2129 * from the response and execute it as if it were JavaScript code.</li> 2130 * </ul> 2131 * </li> 2132 * <p><i>Redirect Processing</i></p> 2133 * <li>If a <code><redirect></code> element is found in the response: 2134 * <pre><code><redirect url="redirect url"/></code></pre> 2135 * Cause a redirect to the url <code>redirect url</code>.</li> 2136 * <p><i>Error Processing</i></p> 2137 * <li>If an <code><error></code> element is found in the response: 2138 * <pre><code><error> 2139 * <error-name>..fully qualified class name string...<error-name> 2140 * <error-message><![CDATA[...]]><error-message> 2141 * </error></code></pre> 2142 * Extract this <code><error></code> element's <code>error-name</code> contents 2143 * and the <code>error-message</code> contents. Signal a <code>serverError</code> passing 2144 * the <code>errorName</code> and <code>errorMessage</code>. Refer to 2145 * section "Signaling Errors" in Chapter 13 of the spec prose document <a 2146 * href="../../javadocs/overview-summary.html#prose_document">linked in the 2147 * overview summary</a>.</li> 2148 * <p><i>Extensions</i></p> 2149 * <li>The <code><extensions></code> element provides a way for framework 2150 * implementations to provide their own information.</li> 2151 * <p><li>The implementation must check if <script> elements in the response can 2152 * be automatically run, as some browsers support this feature and some do not. 2153 * If they can not be run, then scripts should be extracted from the response and 2154 * run separately.</li></p> 2155 * </ul> 2156 * 2157 * </p> 2158 * 2159 * @param request The <code>XMLHttpRequest</code> instance that 2160 * contains the status code and response message from the server. 2161 * 2162 * @param context An object containing the request context, including the following properties: 2163 * the source element, per call onerror callback function, and per call onevent callback function. 2164 * 2165 * @throws Error if request contains no data 2166 * 2167 * @function jsf.ajax.response 2168 */ 2169 response: function response(request, context) { 2170 if (!request) { 2171 throw new Error("jsf.ajax.response: Request parameter is unset"); 2172 } 2173 2174 // ensure context source is the dom element and not the ID 2175 // per 14.4.1 of the 2.0 specification. We're doing it here 2176 // *before* any errors or events are propagated becasue the 2177 // DOM element may be removed after the update has been processed. 2178 if (typeof context.sourceid === 'string') { 2179 context.sourceid = document.getElementById(context.sourceid); 2180 } 2181 2182 var xml = request.responseXML; 2183 if (xml === null) { 2184 sendError(request, context, "emptyResponse"); 2185 return; 2186 } 2187 2188 if (getParseErrorText(xml) !== PARSED_OK) { 2189 sendError(request, context, "malformedXML"); 2190 return; 2191 } 2192 2193 var partialResponse = xml.getElementsByTagName("partial-response")[0]; 2194 var partialResponseId = partialResponse.getAttribute("id"); 2195 var responseType = partialResponse.firstChild; 2196 2197 if (responseType.nodeName === "error") { // it's an error 2198 var errorName = responseType.firstChild.firstChild.nodeValue; 2199 var errorMessage = responseType.firstChild.nextSibling.firstChild.nodeValue; 2200 sendError(request, context, "serverError", null, errorName, errorMessage); 2201 sendEvent(request, context, "success"); 2202 return; 2203 } 2204 2205 2206 if (responseType.nodeName === "redirect") { 2207 window.location = responseType.getAttribute("url"); 2208 return; 2209 } 2210 2211 2212 if (responseType.nodeName !== "changes") { 2213 sendError(request, context, "malformedXML", "Top level node must be one of: changes, redirect, error, received: " + responseType.nodeName + " instead."); 2214 return; 2215 } 2216 2217 2218 var changes = responseType.childNodes; 2219 2220 try { 2221 for (var i = 0; i < changes.length; i++) { 2222 switch (changes[i].nodeName) { 2223 case "update": 2224 doUpdate(changes[i], context, partialResponseId); 2225 break; 2226 case "delete": 2227 doDelete(changes[i]); 2228 break; 2229 case "insert": 2230 doInsert(changes[i]); 2231 break; 2232 case "attributes": 2233 doAttributes(changes[i]); 2234 break; 2235 case "eval": 2236 doEval(changes[i]); 2237 break; 2238 case "extension": 2239 // no action 2240 break; 2241 default: 2242 sendError(request, context, "malformedXML", "Changes allowed are: update, delete, insert, attributes, eval, extension. Received " + changes[i].nodeName + " instead."); 2243 return; 2244 } 2245 } 2246 } catch (ex) { 2247 sendError(request, context, "malformedXML", ex.message); 2248 return; 2249 } 2250 sendEvent(request, context, "success"); 2251 2252 } 2253 }; 2254 }(); 2255 2256 /** 2257 * 2258 * <p>Return the value of <code>Application.getProjectStage()</code> for 2259 * the currently running application instance. Calling this method must 2260 * not cause any network transaction to happen to the server.</p> 2261 * <p><b>Usage:</b></p> 2262 * <pre><code> 2263 * var stage = jsf.getProjectStage(); 2264 * if (stage === ProjectStage.Development) { 2265 * ... 2266 * } else if stage === ProjectStage.Production) { 2267 * ... 2268 * } 2269 * </code></pre> 2270 * 2271 * @returns String <code>String</code> representing the current state of the 2272 * running application in a typical product development lifecycle. Refer 2273 * to <code>javax.faces.application.Application.getProjectStage</code> and 2274 * <code>javax.faces.application.ProjectStage</code>. 2275 * @function jsf.getProjectStage 2276 */ 2277 jsf.getProjectStage = function() { 2278 // First, return cached value if available 2279 if (typeof mojarra !== 'undefined' && typeof mojarra.projectStageCache !== 'undefined') { 2280 return mojarra.projectStageCache; 2281 } 2282 var scripts = document.getElementsByTagName("script"); // nodelist of scripts 2283 var script; // jsf.js script 2284 var s = 0; // incremental variable for for loop 2285 var stage; // temp value for stage 2286 var match; // temp value for match 2287 while (s < scripts.length) { 2288 if (typeof scripts[s].src === 'string' && scripts[s].src.match('\/javax\.faces\.resource\/jsf\.js\?.*ln=javax\.faces')) { 2289 script = scripts[s].src; 2290 break; 2291 } 2292 s++; 2293 } 2294 if (typeof script == "string") { 2295 match = script.match("stage=(.*)"); 2296 if (match) { 2297 stage = match[1]; 2298 } 2299 } 2300 if (typeof stage === 'undefined' || !stage) { 2301 stage = "Production"; 2302 } 2303 2304 mojarra = mojarra || {}; 2305 mojarra.projectStageCache = stage; 2306 2307 return mojarra.projectStageCache; 2308 }; 2309 2310 2311 /** 2312 * <p>Collect and encode state for input controls associated 2313 * with the specified <code>form</code> element. This will include 2314 * all input controls of type <code>hidden</code>.</p> 2315 * <p><b>Usage:</b></p> 2316 * <pre><code> 2317 * var state = jsf.getViewState(form); 2318 * </pre></code> 2319 * 2320 * @param form The <code>form</code> element whose contained 2321 * <code>input</code> controls will be collected and encoded. 2322 * Only successful controls will be collected and encoded in 2323 * accordance with: <a href="http://www.w3.org/TR/html401/interact/forms.html#h-17.13.2"> 2324 * Section 17.13.2 of the HTML Specification</a>. 2325 * 2326 * @returns String The encoded state for the specified form's input controls. 2327 * @function jsf.getViewState 2328 */ 2329 jsf.getViewState = function(form) { 2330 if (!form) { 2331 throw new Error("jsf.getViewState: form must be set"); 2332 } 2333 var els = form.elements; 2334 var len = els.length; 2335 // create an array which we'll use to hold all the intermediate strings 2336 // this bypasses a problem in IE when repeatedly concatenating very 2337 // large strings - we'll perform the concatenation once at the end 2338 var qString = []; 2339 var addField = function(name, value) { 2340 var tmpStr = ""; 2341 if (qString.length > 0) { 2342 tmpStr = "&"; 2343 } 2344 tmpStr += encodeURIComponent(name) + "=" + encodeURIComponent(value); 2345 qString.push(tmpStr); 2346 }; 2347 for (var i = 0; i < len; i++) { 2348 var el = els[i]; 2349 if (!el.disabled) { 2350 switch (el.type) { 2351 case 'text': 2352 case 'password': 2353 case 'hidden': 2354 case 'textarea': 2355 addField(el.name, el.value); 2356 break; 2357 case 'select-one': 2358 if (el.selectedIndex >= 0) { 2359 addField(el.name, el.options[el.selectedIndex].value); 2360 } 2361 break; 2362 case 'select-multiple': 2363 for (var j = 0; j < el.options.length; j++) { 2364 if (el.options[j].selected) { 2365 addField(el.name, el.options[j].value); 2366 } 2367 } 2368 break; 2369 case 'checkbox': 2370 case 'radio': 2371 if (el.checked) { 2372 addField(el.name, el.value || 'on'); 2373 } 2374 break; 2375 } 2376 } 2377 } 2378 // concatenate the array 2379 return qString.join(""); 2380 }; 2381 2382 /** 2383 * <p class="changed_added_2_2">Return the windowId of the window 2384 * in which the argument form is rendered.</p> 2385 2386 * <p>PENDING: edburns implement URL mode.</p> 2387 2388 * @param {optional String|DomNode} node. Determine the nature of 2389 * the argument. If not present, search for the windowId within 2390 * <code>document.forms</code>. If present and the value is a 2391 * string, assume the string is a DOM id and get the element with 2392 * that id and start the search from there. If present and the 2393 * value is a DOM element, start the search from there. 2394 2395 * @returns String The windowId of the current window, or null 2396 * if the windowId cannot be determined. 2397 2398 * @throws an error if more than one unique WindowId is found. 2399 2400 * @function jsf.getViewState 2401 */ 2402 jsf.getWindowId = function(node) { 2403 var FORM = "form"; 2404 var WIN_ID = "javax.faces.WindowId"; 2405 2406 var fetchWindowIdFromForms = function (forms) { 2407 var result_idx = {}; 2408 var result; 2409 var foundCnt = 0; 2410 for (var cnt = forms.length - 1; cnt >= 0; cnt--) { 2411 var UDEF = 'undefined'; 2412 var currentForm = forms[cnt]; 2413 var windowId = currentForm[WIN_ID] && currentForm[WIN_ID].value; 2414 if (UDEF != typeof windowId) { 2415 if (foundCnt > 0 && UDEF == typeof result_idx[windowId]) throw Error("Multiple different windowIds found in document"); 2416 result = windowId; 2417 result_idx[windowId] = true; 2418 foundCnt++; 2419 } 2420 } 2421 return result; 2422 } 2423 2424 var getChildForms = function (currentElement) { 2425 //Special condition no element we return document forms 2426 //as search parameter, ideal would be to 2427 //have the viewroot here but the frameworks 2428 //can deal with that themselves by using 2429 //the viewroot as currentElement 2430 if (!currentElement) { 2431 return document.forms; 2432 } 2433 2434 var targetArr = []; 2435 if (!currentElement.tagName) return []; 2436 else if (currentElement.tagName.toLowerCase() == FORM) { 2437 targetArr.push(currentElement); 2438 return targetArr; 2439 } 2440 2441 //if query selectors are supported we can take 2442 //a non recursive shortcut 2443 if (currentElement.querySelectorAll) { 2444 return currentElement.querySelectorAll(FORM); 2445 } 2446 2447 //old recursive way, due to flakeyness of querySelectorAll 2448 for (var cnt = currentElement.childNodes.length - 1; cnt >= 0; cnt--) { 2449 var currentChild = currentElement.childNodes[cnt]; 2450 targetArr = targetArr.concat(getChildForms(currentChild, FORM)); 2451 } 2452 return targetArr; 2453 } 2454 2455 var fetchWindowIdFromURL = function () { 2456 var href = window.location.href; 2457 var windowId = "windowId"; 2458 var regex = new RegExp("[\\?&]" + windowId + "=([^\\;]*)"); 2459 var results = regex.exec(href); 2460 //initial trial over the url and a regexp 2461 if (results != null) return results[1]; 2462 return null; 2463 } 2464 2465 //byId ($) 2466 var finalNode = (node && (typeof node == "string" || node instanceof String)) ? 2467 document.getElementById(node) : (node || null); 2468 2469 var forms = getChildForms(finalNode); 2470 var result = fetchWindowIdFromForms(forms); 2471 return (null != result) ? result : fetchWindowIdFromURL(); 2472 2473 2474 }; 2475 2476 2477 /** 2478 * The namespace for JavaServer Faces JavaScript utilities. 2479 * @name jsf.util 2480 * @namespace 2481 */ 2482 jsf.util = {}; 2483 2484 /** 2485 * <p>A varargs function that invokes an arbitrary number of scripts. 2486 * If any script in the chain returns false, the chain is short-circuited 2487 * and subsequent scripts are not invoked. Any number of scripts may 2488 * specified after the <code>event</code> argument.</p> 2489 * 2490 * @param source The DOM element that triggered this Ajax request, or an 2491 * id string of the element to use as the triggering element. 2492 * @param event The DOM event that triggered this Ajax request. The 2493 * <code>event</code> argument is optional. 2494 * 2495 * @returns boolean <code>false</code> if any scripts in the chain return <code>false</code>, 2496 * otherwise returns <code>true</code> 2497 * 2498 * @function jsf.util.chain 2499 */ 2500 jsf.util.chain = function(source, event) { 2501 2502 if (arguments.length < 3) { 2503 return true; 2504 } 2505 2506 // RELEASE_PENDING rogerk - shouldn't this be getElementById instead of null 2507 var thisArg = (typeof source === 'object') ? source : null; 2508 2509 // Call back any scripts that were passed in 2510 for (var i = 2; i < arguments.length; i++) { 2511 2512 var f = new Function("event", arguments[i]); 2513 var returnValue = f.call(thisArg, event); 2514 2515 if (returnValue === false) { 2516 return false; 2517 } 2518 } 2519 return true; 2520 2521 }; 2522 2523 /** 2524 * <p class="changed_added_2_2">The result of calling 2525 * <code>UINamingContainer.getNamingContainerSeparatorChar().</code></p> 2526 */ 2527 jsf.separatorchar = '#{facesContext.namingContainerSeparatorChar}'; 2528 2529 /** 2530 * <p>An integer specifying the specification version that this file implements. 2531 * It's format is: rightmost two digits, bug release number, next two digits, 2532 * minor release number, leftmost digits, major release number. 2533 * This number may only be incremented by a new release of the specification.</p> 2534 */ 2535 jsf.specversion = 22000; 2536 2537 /** 2538 * <p>An integer specifying the implementation version that this file implements. 2539 * It's a monotonically increasing number, reset with every increment of 2540 * <code>jsf.specversion</code> 2541 * This number is implementation dependent.</p> 2542 */ 2543 jsf.implversion = 3; 2544 2545 2546 } //end if version detection block 2547