1 /* Licensed to the Apache Software Foundation (ASF) under one or more
  2  * contributor license agreements.  See the NOTICE file distributed with
  3  * this work for additional information regarding copyright ownership.
  4  * The ASF licenses this file to you under the Apache License, Version 2.0
  5  * (the "License"); you may not use this file except in compliance with
  6  * the License.  You may obtain a copy of the License at
  7  *
  8  *      http://www.apache.org/licenses/LICENSE-2.0
  9  *
 10  * Unless required by applicable law or agreed to in writing, software
 11  * distributed under the License is distributed on an "AS IS" BASIS,
 12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13  * See the License for the specific language governing permissions and
 14  * limitations under the License.
 15  */
 16 
 17 /**
 18  * @class
 19  * @name _AjaxResponse
 20  * @memberOf myfaces._impl.xhrCore
 21  * @extends myfaces._impl.core.Object
 22  * @description
 23  * This singleton is responsible for handling the standardized xml ajax response
 24  * Note: since the semantic processing can be handled about 90% in a functional
 25  * style we make this class stateless. Every state information is stored
 26  * temporarily in the context.
 27  *
 28  * The singleton approach also improves performance
 29  * due to less object gc compared to the old instance approach.
 30  *
 31  */
 32 _MF_SINGLTN(_PFX_XHR + "_AjaxResponse", _MF_OBJECT, /** @lends myfaces._impl.xhrCore._AjaxResponse.prototype */ {
 33 
 34     /*partial response types*/
 35     RESP_PARTIAL : "partial-response",
 36     RESP_TYPE_ERROR : "error",
 37     RESP_TYPE_REDIRECT : "redirect",
 38     RESP_TYPE_CHANGES : "changes",
 39 
 40     /*partial commands*/
 41     CMD_CHANGES : "changes",
 42     CMD_UPDATE : "update",
 43     CMD_DELETE : "delete",
 44     CMD_INSERT : "insert",
 45     CMD_EVAL : "eval",
 46     CMD_ERROR : "error",
 47     CMD_ATTRIBUTES : "attributes",
 48     CMD_EXTENSION : "extension",
 49     CMD_REDIRECT : "redirect",
 50 
 51     /*other constants*/
 52     P_VIEWSTATE: "javax.faces.ViewState",
 53     P_VIEWROOT: "javax.faces.ViewRoot",
 54     P_VIEWHEAD: "javax.faces.ViewHead",
 55     P_VIEWBODY: "javax.faces.ViewBody",
 56 
 57 
 58     /**
 59      * uses response to start Html element replacement
 60      *
 61      * @param {Object} request (xhrRequest) - xhr request object
 62      * @param {Object} context (Map) - AJAX context
 63      *
 64      * A special handling has to be added to the update cycle
 65      * according to the JSDoc specs if the CDATA block contains html tags the outer rim must be stripped
 66      * if the CDATA block contains a head section the document head must be replaced
 67      * and if the CDATA block contains a body section the document body must be replaced!
 68      *
 69      */
 70     processResponse : function(request, context) {
 71         //mfinternal handling, note, the mfinternal is only optional
 72         //according to the spec
 73         context._mfInternal =  context._mfInternal || {};
 74         var mfInternal = context._mfInternal;
 75 
 76         //the temporary data is hosted here
 77         mfInternal._updateElems = [];
 78         mfInternal._updateForms = [];
 79         mfInternal.appliedViewState = null;
 80 
 81         try {
 82             var _Impl = this.attr("impl"), _Lang = this._Lang;
 83             // TODO:
 84             // Solution from
 85             // http://www.codingforums.com/archive/index.php/t-47018.html
 86             // to solve IE error 1072896658 when a Java server sends iso88591
 87             // istead of ISO-8859-1
 88 
 89             if (!request || !_Lang.exists(request, "responseXML")) {
 90                 throw this.makeException(new Error(), _Impl.EMPTY_RESPONSE, _Impl.EMPTY_RESPONSE, this._nameSpace, "processResponse", "");
 91             }
 92             //check for a parseError under certain browsers
 93 
 94             var xmlContent = request.responseXML;
 95             //ie6+ keeps the parsing response under xmlContent.parserError
 96             //while the rest of the world keeps it as element under the first node
 97             var xmlErr = _Lang.fetchXMLErrorMessage(request.responseText || request.response, xmlContent)
 98             if (xmlErr) {
 99                 throw this._raiseError(new Error(),xmlErr.errorMessage+"\n"+xmlErr.sourceText+"\n"+xmlErr.visualError+"\n", "processResponse");
100             }
101             var partials = xmlContent.childNodes[0];
102             if ('undefined' == typeof partials || partials == null) {
103                 throw this._raiseError(new Error(),"No child nodes for response", "processResponse");
104 
105             } else {
106                 if (partials.tagName != this.RESP_PARTIAL) {
107                     // IE 8 sees XML Header as first sibling ...
108                     partials = partials.nextSibling;
109                     if (!partials || partials.tagName != this.RESP_PARTIAL) {
110                         throw this._raiseError(new Error(), "Partial response not set","processResponse");
111                     }
112                 }
113             }
114 
115             var childNodesLength = partials.childNodes.length;
116 
117             for (var loop = 0; loop < childNodesLength; loop++) {
118                 var childNode = partials.childNodes[loop];
119                 var tagName = childNode.tagName;
120                 /**
121                  * <eval>
122                  *      <![CDATA[javascript]]>
123                  * </eval>
124                  */
125 
126                 //this ought to be enough for eval
127                 //however the run scripts still makes sense
128                 //in the update and insert area for components
129                 //which do not use the response writer properly
130                 //we might add this one as custom option in update and
131                 //insert!
132                 if (tagName == this.CMD_ERROR) {
133                     this.processError(request, context, childNode);
134                 } else if (tagName == this.CMD_REDIRECT) {
135                     this.processRedirect(request, context, childNode);
136                 } else if (tagName == this.CMD_CHANGES) {
137                     this.processChanges(request, context, childNode);
138                 }
139             }
140 
141             //fixup missing viewStates due to spec deficiencies
142             this.fixViewStates(context);
143 
144             //spec jsdoc, the success event must be sent from response
145             _Impl.sendEvent(request, context, _Impl["SUCCESS"]);
146 
147         } finally {
148             delete mfInternal._updateElems;
149             delete mfInternal._updateForms;
150             delete mfInternal.appliedViewState;
151         }
152     },
153 
154     /**
155      * fixes the viewstates in the current page
156      *
157      * @param context
158      */
159     fixViewStates : function(context) {
160         var _Lang = this._Lang;
161         var mfInternal = context._mfInternal;
162 
163         if (null == mfInternal.appliedViewState) {
164             return;
165         }
166 
167         //if we set our no portlet env we safely can update all forms with
168         //the new viewstate
169         if (this._RT.getLocalOrGlobalConfig(context, "no_portlet_env", false)) {
170             for (var cnt = document.forms.length - 1; cnt >= 0; cnt --) {
171                 this._setVSTForm(context, document.forms[cnt]);
172             }
173             return;
174         }
175 
176         // Now update the forms that were not replaced but forced to be updated, because contains child ajax tags
177         // we should only update forms with view state hidden field. If by some reason, the form was set to be
178         // updated but the form was replaced, it does not have hidden view state, so later in changeTrace processing the
179         // view state is updated.
180 
181         //set the viewstates of all outer forms parents of our updated elements
182         var _T = this;
183         _Lang.arrForEach(mfInternal._updateForms, function(elem) {
184             _T._setVSTForm(context, elem);
185         }, 0, this);
186 
187         //set the viewstate of all forms within our updated elements
188         _Lang.arrForEach(mfInternal._updateElems, function(elem) {
189             _T._setVSTInnerForms(context, elem);
190         }, 0, this);
191     }
192     ,
193 
194     /**
195      * sets the viewstate element in a given form
196      *
197      * @param theForm the form to which the element has to be set to
198      * @param context the current request context
199      */
200     _setVSTForm: function(context, theForm) {
201         theForm = this._Lang.byId(theForm);
202         var mfInternal = context._mfInternal;
203 
204         if (!theForm) return;
205 
206         var viewStateField = (theForm.elements) ? theForm.elements[this.P_VIEWSTATE] : null;//this._Dom.findFormElement(elem, this.P_VIEWSTATE);
207 
208         if (viewStateField) {
209             this._Dom.setAttribute(viewStateField, "value", mfInternal.appliedViewState);
210         } else if (!viewStateField) {
211             var element = this._Dom.getDummyPlaceHolder();
212             //spec error, two elements with the same id should not be there, TODO recheck the space if the name does not suffice alone
213             element.innerHTML = ["<input type='hidden'", "id='", this.P_VIEWSTATE ,"' name='", this.P_VIEWSTATE ,"' value='" , mfInternal.appliedViewState , "' />"].join("");
214             //now we go to proper dom handling after having to deal with another ie screwup
215             try {
216                 theForm.appendChild(element.childNodes[0]);
217             } finally {
218                 element.innerHTML = "";
219             }
220         }
221     }
222     ,
223 
224     _setVSTInnerForms: function(context, elem) {
225 
226         var _Lang = this._Lang, _Dom = this._Dom;
227         elem = _Dom.byIdOrName(elem);
228 
229         var replacedForms = _Dom.findByTagName(elem, "form", false);
230         var applyVST = _Lang.hitch(this, function(elem) {
231             this._setVSTForm(context, elem);
232         });
233 
234         try {
235             _Lang.arrForEach(replacedForms, applyVST, 0, this);
236         } finally {
237             applyVST = null;
238         }
239     },
240 
241     /**
242      * processes an incoming error from the response
243      * which is hosted under the <error> tag
244      * @param request the current request
245      * @param context the contect object
246      * @param node the node in the xml hosting the error message
247      */
248     processError : function(request, context, node) {
249         /**
250          * <error>
251          *      <error-name>String</error-name>
252          *      <error-message><![CDATA[message]]></error-message>
253          * <error>
254          */
255         var errorName = node.firstChild.textContent || "",
256                 errorMessage = node.childNodes[1].firstChild.data || "";
257 
258         this.attr("impl").sendError(request, context, this.attr("impl").SERVER_ERROR, errorName, errorMessage, "myfaces._impl.xhrCore._AjaxResponse", "processError");
259     },
260 
261     /**
262      * processes an incoming xml redirect directive from the ajax response
263      * @param request the request object
264      * @param context the context
265      * @param node the node hosting the redirect data
266      */
267     processRedirect : function(request, context, node) {
268         /**
269          * <redirect url="url to redirect" />
270          */
271         var _Lang = this._Lang;
272         var redirectUrl = node.getAttribute("url");
273         if (!redirectUrl) {
274             throw this._raiseError(new Error(),_Lang.getMessage("ERR_RED_URL", null, "_AjaxResponse.processRedirect"),"processRedirect");
275         }
276         redirectUrl = _Lang.trim(redirectUrl);
277         if (redirectUrl == "") {
278             return false;
279         }
280         window.location = redirectUrl;
281         return true;
282     }
283     ,
284 
285     /**
286      * main entry point for processing the changes
287      * it deals with the <changes> node of the
288      * response
289      *
290      * @param request the xhr request object
291      * @param context the context map
292      * @param node the changes node to be processed
293      */
294     processChanges : function(request, context, node) {
295         var changes = node.childNodes;
296         var _Lang = this._Lang;
297         //note we need to trace the changes which could affect our insert update or delete
298         //se that we can realign our ViewStates afterwards
299         //the realignment must happen post change processing
300 
301         for (var i = 0; i < changes.length; i++) {
302 
303             switch (changes[i].tagName) {
304 
305                 case this.CMD_UPDATE:
306                     this.processUpdate(request, context, changes[i]);
307                     break;
308                 case this.CMD_EVAL:
309                     _Lang.globalEval(changes[i].firstChild.data);
310                     break;
311                 case this.CMD_INSERT:
312                     this.processInsert(request, context, changes[i]);
313                     break;
314                 case this.CMD_DELETE:
315                     this.processDelete(request, context, changes[i]);
316                     break;
317                 case this.CMD_ATTRIBUTES:
318                     this.processAttributes(request, context, changes[i]);
319                     break;
320                 case this.CMD_EXTENSION:
321                     break;
322                 default:
323                     throw this._raiseError(new Error(),"_AjaxResponse.processChanges: Illegal Command Issued","processChanges");
324             }
325         }
326 
327         return true;
328     }
329     ,
330 
331     /**
332      * First sub-step process a pending update tag
333      *
334      * @param request the xhr request object
335      * @param context the context map
336      * @param node the changes node to be processed
337      */
338     processUpdate : function(request, context, node) {
339         if (node.getAttribute('id') == this.P_VIEWSTATE) {
340             //update the submitting forms viewstate to the new value
341             // The source form has to be pulled out of the CURRENT document first because the context object
342             // may refer to an invalid document if an update of the entire body has occurred before this point.
343             var mfInternal = context._mfInternal,
344                 fuzzyFormDetection = this._Lang.hitch(this._Dom, this._Dom.fuzzyFormDetection);
345             var elemId = (mfInternal._mfSourceControlId)? mfInternal._mfSourceControlId:
346                             ((context.source)?context.source.id: null);
347 
348                     //theoretically a source of null can be given, then our form detection fails for
349                     //the source element case and hence updateviewstate is skipped for the source
350                     //form, but still render targets still can get the viewstate
351             var sourceForm = (mfInternal && mfInternal["_mfSourceFormId"] &&
352                            document.forms[mfInternal["_mfSourceFormId"]]) ?
353                            document.forms[mfInternal["_mfSourceFormId"]] : ((elemId)? fuzzyFormDetection(elemId): null);
354 
355             mfInternal.appliedViewState = node.firstChild.nodeValue;
356             //source form could not be determined either over the form identifer or the element
357             //we now skip this phase and just add everything we need for the fixup code
358 
359             if (!sourceForm) {
360                 //no source form found is not an error because
361                 //we might be able to recover one way or the other
362                 return true;
363             }
364 
365             mfInternal._updateForms.push(sourceForm.id);
366             //this._setVSTForm(sourceForm);
367         }
368         else {
369             // response may contain several blocks
370             var cDataBlock = this._Dom.concatCDATABlocks(node),
371                     resultNode = null,
372                     pushOpRes = this._Lang.hitch(this, this._pushOperationResult);
373 
374             switch (node.getAttribute('id')) {
375                 case this.P_VIEWROOT:
376 
377                     cDataBlock = cDataBlock.substring(cDataBlock.indexOf("<html"));
378 
379                     var parsedData = this._replaceHead(request, context, cDataBlock);
380 
381                     resultNode = ('undefined' != typeof parsedData && null != parsedData) ? this._replaceBody(request, context, cDataBlock, parsedData) : this._replaceBody(request, context, cDataBlock);
382                     if (resultNode) {
383                         pushOpRes(context, resultNode);
384                     }
385                     break;
386                 case this.P_VIEWHEAD:
387                     //we cannot replace the head, almost no browser allows this, some of them throw errors
388                     //others simply ignore it or replace it and destroy the dom that way!
389                     this._replaceHead(request, context, cDataBlock);
390 
391                     break;
392                 case this.P_VIEWBODY:
393                     //we assume the cdata block is our body including the tag
394                     resultNode = this._replaceBody(request, context, cDataBlock);
395                     if (resultNode) {
396                         pushOpRes(context, resultNode);
397                     }
398                     break;
399 
400                 default:
401                     resultNode = this.replaceHtmlItem(request, context, node.getAttribute('id'), cDataBlock);
402                     if (resultNode) {
403                         pushOpRes(context, resultNode);
404                     }
405                     break;
406             }
407         }
408 
409         return true;
410     }
411     ,
412 
413     _pushOperationResult: function(context, resultNode) {
414         var mfInternal = context._mfInternal;
415         var pushSubnode = this._Lang.hitch(this, function(currNode) {
416             var parentForm = this._Dom.getParent(currNode, "form");
417             //if possible we work over the ids
418             //so that elements later replaced are referenced
419             //at the latest possibility
420             if (null != parentForm) {
421                 mfInternal._updateForms.push(parentForm.id || parentForm);
422             }
423             else {
424                 mfInternal._updateElems.push(currNode.id || currNode);
425             }
426         });
427         var isArr = 'undefined' != typeof resultNode.length && 'undefined' == typeof resultNode.nodeType;
428         if (isArr && resultNode.length) {
429             for (var cnt = 0; cnt < resultNode.length; cnt++) {
430                 pushSubnode(resultNode[cnt]);
431             }
432         } else if (!isArr) {
433             pushSubnode(resultNode);
434         }
435 
436     }
437     ,
438 
439     /**
440      * replaces a current head theoretically,
441      * pratically only the scripts are evaled anew since nothing else
442      * can be changed.
443      *
444      * @param request the current request
445      * @param context the ajax context
446      * @param newData the data to be processed
447      *
448      * @return an xml representation of the page for further processing if possible
449      */
450     _replaceHead: function(request, context, newData) {
451 
452         var _Lang = this._Lang,
453                 _Dom = this._Dom,
454                 isWebkit = this._RT.browser.isWebKit,
455             //we have to work around an xml parsing bug in Webkit
456             //see https://issues.apache.org/jira/browse/MYFACES-3061
457                 doc = (!isWebkit) ? _Lang.parseXML(newData) : null,
458                 newHead = null;
459 
460         if (!isWebkit && _Lang.isXMLParseError(doc)) {
461             doc = _Lang.parseXML(newData.replace(/<!\-\-[\s\n]*<!\-\-/g, "<!--").replace(/\/\/-->[\s\n]*\/\/-->/g, "//-->"));
462         }
463 
464         if (isWebkit || _Lang.isXMLParseError(doc)) {
465             //the standard xml parser failed we retry with the stripper
466             var parser = new (this._RT.getGlobalConfig("updateParser", myfaces._impl._util._HtmlStripper))();
467             var headData = parser.parse(newData, "head");
468             //We cannot avoid it here, but we have reduced the parsing now down to the bare minimum
469             //for further processing
470             newHead = _Lang.parseXML("<head>" + headData + "</head>");
471             //last and slowest option create a new head element and let the browser
472             //do its slow job
473             if (_Lang.isXMLParseError(newHead)) {
474                 try {
475                     newHead = _Dom.createElement("head");
476                     newHead.innerHTML = headData;
477                 } catch (e) {
478                     //we give up no further fallbacks
479                     throw this._raiseError(new Error(),"Error head replacement failed reason:" + e.toString(),"_replaceHead");
480                 }
481             }
482         } else {
483             //parser worked we go on
484             newHead = doc.getElementsByTagName("head")[0];
485         }
486 
487         var oldTags = _Dom.findByTagNames(document.getElementsByTagName("head")[0], {"link": true, "style":true});
488         _Dom.runCss(newHead, true);
489         _Dom.deleteItems(oldTags);
490 
491         //var oldTags = _Dom.findByTagNames(document.getElementsByTagName("head")[0], {"script": true});
492         //_Dom.deleteScripts(oldTags);
493         _Dom.runScripts(newHead, true);
494 
495         return doc;
496     },
497 
498 
499     /**
500      * special method to handle the body dom manipulation,
501      * replacing the entire body does not work fully by simply adding a second body
502      * and by creating a range instead we have to work around that by dom creating a second
503      * body and then filling it properly!
504      *
505      * @param {Object} request our request object
506      * @param {Object} context (Map) the response context
507      * @param {String} newData the markup which replaces the old dom node!
508      * @param {Node} parsedData (optional) preparsed XML representation data of the current document
509      */
510     _replaceBody : function(request, context, newData /*varargs*/) {
511         var _RT = this._RT,
512                 _Dom = this._Dom,
513                 _Lang = this._Lang,
514 
515                 oldBody = document.getElementsByTagName("body")[0],
516                 placeHolder = document.createElement("div"),
517                 isWebkit = _RT.browser.isWebKit;
518 
519         placeHolder.id = "myfaces_bodyplaceholder";
520 
521         _Dom._removeChildNodes(oldBody);
522         oldBody.innerHTML = "";
523         oldBody.appendChild(placeHolder);
524 
525         var bodyData, doc = null, parser;
526 
527         //we have to work around an xml parsing bug in Webkit
528         //see https://issues.apache.org/jira/browse/MYFACES-3061
529         if (!isWebkit) {
530             doc = (arguments.length > 3) ? arguments[3] : _Lang.parseXML(newData);
531         }
532 
533         if (!isWebkit && _Lang.isXMLParseError(doc)) {
534             doc = _Lang.parseXML(newData.replace(/<!\-\-[\s\n]*<!\-\-/g, "<!--").replace(/\/\/-->[\s\n]*\/\/-->/g, "//-->"));
535         }
536 
537         if (isWebkit || _Lang.isXMLParseError(doc)) {
538             //the standard xml parser failed we retry with the stripper
539 
540             parser = new (_RT.getGlobalConfig("updateParser", myfaces._impl._util._HtmlStripper))();
541 
542             bodyData = parser.parse(newData, "body");
543         } else {
544             //parser worked we go on
545             var newBodyData = doc.getElementsByTagName("body")[0];
546 
547             //speedwise we serialize back into the code
548             //for code reduction, speedwise we will take a small hit
549             //there which we will clean up in the future, but for now
550             //this is ok, I guess, since replace body only is a small subcase
551             //bodyData = _Lang.serializeChilds(newBodyData);
552             var browser = _RT.browser;
553             if (!browser.isIEMobile || browser.isIEMobile >= 7) {
554                 //TODO check what is failing there
555                 for (var cnt = 0; cnt < newBodyData.attributes.length; cnt++) {
556                     var value = newBodyData.attributes[cnt].value;
557                     if (value)
558                         _Dom.setAttribute(oldBody, newBodyData.attributes[cnt].name, value);
559                 }
560             }
561         }
562         //we cannot serialize here, due to escape problems
563         //we must parse, this is somewhat unsafe but should be safe enough
564         parser = new (_RT.getGlobalConfig("updateParser", myfaces._impl._util._HtmlStripper))();
565         bodyData = parser.parse(newData, "body");
566 
567         var returnedElement = this.replaceHtmlItem(request, context, placeHolder, bodyData);
568 
569         if (returnedElement) {
570             this._pushOperationResult(context, returnedElement);
571         }
572         return returnedElement;
573     }
574     ,
575 
576     /**
577      * Replaces HTML elements through others and handle errors if the occur in the replacement part
578      *
579      * @param {Object} request (xhrRequest)
580      * @param {Object} context (Map)
581      * @param {Object} itemIdToReplace (String|Node) - ID of the element to replace
582      * @param {String} markup - the new tag
583      */
584     replaceHtmlItem : function(request, context, itemIdToReplace, markup) {
585         var _Lang = this._Lang, _Dom = this._Dom;
586 
587         var item = (!_Lang.isString(itemIdToReplace)) ? itemIdToReplace :
588                 _Dom.byIdOrName(itemIdToReplace);
589 
590         if (!item) {
591             throw this._raiseError(_Lang.getMessage("ERR_ITEM_ID_NOTFOUND", null, "_AjaxResponse.replaceHtmlItem", (itemIdToReplace) ? itemIdToReplace.toString() : "undefined"));
592         }
593         return _Dom.outerHTML(item, markup);
594     },
595 
596     /**
597      * xml insert command handler
598      *
599      * @param request the ajax request element
600      * @param context the context element holding the data
601      * @param node the xml node holding the insert data
602      * @return true upon successful completion, false otherwise
603      *
604      **/
605     processInsert: function(request, context, node) {
606         /*remapping global namespaces for speed and readability reasons*/
607         var _Dom = this._Dom,
608                 _Lang = this._Lang,
609             //determine which path to go:
610                 insertData = this._parseInsertData(request, context, node);
611 
612         if (!insertData) return false;
613 
614         var opNode = _Dom.byIdOrName(insertData.opId);
615         if (!opNode) {
616             throw this._raiseError(new Error(),_Lang.getMessage("ERR_PPR_INSERTBEFID_1", null, "_AjaxResponse.processInsert", insertData.opId),"processInsert");
617         }
618 
619         //call insertBefore or insertAfter in our dom routines
620         var replacementFragment = _Dom[insertData.insertType](opNode, insertData.cDataBlock);
621         if (replacementFragment) {
622             this._pushOperationResult(context, replacementFragment);
623         }
624         return true;
625     },
626 
627     /**
628      * determines the corner data from the insert tag parsing process
629      *
630      *
631      * @param request request
632      * @param context context
633      * @param node the current node pointing to the insert tag
634      * @return false if the parsing failed, otherwise a map with follwing attributes
635      * <ul>
636      *     <li>inserType - a ponter to a constant which maps the direct function name for the insert operation </li>
637      *     <li>opId - the before or after id </li>
638      *     <li>cDataBlock - the html cdata block which needs replacement </li>
639      * </ul>
640      *
641      * TODO we have to find a mechanism to replace the direct sendError calls with a javascript exception
642      * which we then can use for cleaner error code handling
643      */
644     _parseInsertData: function(request, context, node) {
645         var _Lang = this._Lang,
646                 _Dom = this._Dom,
647                 concatCDATA = _Dom.concatCDATABlocks,
648 
649                 INSERT_TYPE_BEFORE = "insertBefore",
650                 INSERT_TYPE_AFTER = "insertAfter",
651 
652                 id = node.getAttribute("id"),
653                 beforeId = node.getAttribute("before"),
654                 afterId = node.getAttribute("after"),
655                 ret = {};
656 
657         //now we have to make a distinction between two different parsing paths
658         //due to a spec malalignment
659         //a <insert id="... beforeId|AfterId ="...
660         //b <insert><before id="..., <insert> <after id="....
661         //see https://issues.apache.org/jira/browse/MYFACES-3318
662         //simple id, case1
663         if (id && beforeId && !afterId) {
664             ret.insertType = INSERT_TYPE_BEFORE;
665             ret.opId = beforeId;
666             ret.cDataBlock = concatCDATA(node);
667 
668             //<insert id=".. afterId="..
669         } else if (id && !beforeId && afterId) {
670             ret.insertType = INSERT_TYPE_AFTER;
671             ret.opId = afterId;
672             ret.cDataBlock = concatCDATA(node);
673 
674             //<insert><before id="... <insert><after id="...
675         } else if (!id) {
676             var opType = node.childNodes[0].tagName;
677 
678             if (opType != "before" && opType != "after") {
679                 throw this._raiseError(new Error(),_Lang.getMessage("ERR_PPR_INSERTBEFID"),"_parseInsertData");
680             }
681             opType = opType.toLowerCase();
682             var beforeAfterId = node.childNodes[0].getAttribute("id");
683             ret.insertType = (opType == "before") ? INSERT_TYPE_BEFORE : INSERT_TYPE_AFTER;
684             ret.opId = beforeAfterId;
685             ret.cDataBlock = concatCDATA(node.childNodes[0]);
686         } else {
687             throw this._raiseError(new Error(),[_Lang.getMessage("ERR_PPR_IDREQ"),
688                                     "\n ",
689                                     _Lang.getMessage("ERR_PPR_INSERTBEFID")].join(""),"_parseInsertData");
690         }
691         ret.opId = _Lang.trim(ret.opId);
692         return ret;
693     },
694 
695     processDelete : function(request, context, node) {
696 
697         var _Lang = this._Lang,
698                 _Dom = this._Dom,
699                 deleteId = node.getAttribute('id');
700 
701         if (!deleteId) {
702             throw this._raiseError(new Error(),_Lang.getMessage("ERR_PPR_UNKNOWNCID", null, "_AjaxResponse.processDelete", ""),"processDelete");
703         }
704 
705         var item = _Dom.byIdOrName(deleteId);
706         if (!item) {
707             throw this._raiseError(new Error(),_Lang.getMessage("ERR_PPR_UNKNOWNCID", null, "_AjaxResponse.processDelete", deleteId),"processDelete");
708         }
709 
710         var parentForm = this._Dom.getParent(item, "form");
711         if (null != parentForm) {
712             context._mfInternal._updateForms.push(parentForm);
713         }
714         _Dom.deleteItem(item);
715 
716         return true;
717     }
718     ,
719 
720     processAttributes : function(request, context, node) {
721         //we now route into our attributes function to bypass
722         //IE quirks mode incompatibilities to the biggest possible extent
723         //most browsers just have to do a setAttributes but IE
724         //behaves as usual not like the official standard
725         //myfaces._impl._util.this._Dom.setAttribute(domNode, attribute, value;
726 
727         var _Lang = this._Lang,
728             //<attributes id="id of element"> <attribute name="attribute name" value="attribute value" />* </attributes>
729                 elemId = node.getAttribute('id');
730 
731         if (!elemId) {
732             throw this._raiseError(new Error(),"Error in attributes, id not in xml markup","processAttributes");
733         }
734         var childNodes = node.childNodes;
735 
736         if (!childNodes) {
737             return false;
738         }
739         for (var loop2 = 0; loop2 < childNodes.length; loop2++) {
740             var attributesNode = childNodes[loop2],
741                     attrName = attributesNode.getAttribute("name"),
742                     attrValue = attributesNode.getAttribute("value");
743 
744             if (!attrName) {
745                 continue;
746             }
747 
748             attrName = _Lang.trim(attrName);
749             /*no value means reset*/
750             //value can be of boolean value hence full check
751             if ('undefined' == typeof attrValue || null == attrValue) {
752                 attrValue = "";
753             }
754 
755             switch (elemId) {
756                 case this.P_VIEWROOT:
757                     throw  this._raiseError(new Error(),_Lang.getMessage("ERR_NO_VIEWROOTATTR", null, "_AjaxResponse.processAttributes"),"processAttributes");
758 
759                 case this.P_VIEWHEAD:
760                     throw  this._raiseError(new Error(),_Lang.getMessage("ERR_NO_HEADATTR", null, "_AjaxResponse.processAttributes"),"processAttributes");
761 
762                 case this.P_VIEWBODY:
763                     var element = document.getElementsByTagName("body")[0];
764                     this._Dom.setAttribute(element, attrName, attrValue);
765                     break;
766 
767                 default:
768                     this._Dom.setAttribute(document.getElementById(elemId), attrName, attrValue);
769                     break;
770             }
771         }
772         return true;
773     },
774 
775     /**
776      * internal helper which raises an error in the
777      * format we need for further processing
778      *
779      * @param message the message
780      * @param title the title of the error (optional)
781      * @param name the name of the error (optional)
782      */
783     _raiseError: function(error, message,  caller, title, name) {
784         var _Impl = this.attr("impl");
785         var finalTitle = title || _Impl.MALFORMEDXML;
786         var finalName = name || _Impl.MALFORMEDXML;
787         var finalMessage = message || "";
788 
789         return this._Lang.makeException(error, finalTitle, finalName, this._nameSpace, caller || ( (arguments.caller) ? arguments.caller.toString() : "_raiseError"), finalMessage);
790     }
791 });
792