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             element.innerHTML = ["<input type='hidden'", "id='", this.P_VIEWSTATE ,"' name='", this.P_VIEWSTATE ,"' value='" , mfInternal.appliedViewState , "' />"].join("");
213             //now we go to proper dom handling after having to deal with another ie screwup
214             try {
215                 theForm.appendChild(element.childNodes[0]);
216             } finally {
217                 element.innerHTML = "";
218             }
219         }
220     }
221     ,
222 
223     _setVSTInnerForms: function(context, elem) {
224 
225         var _Lang = this._Lang, _Dom = this._Dom;
226         elem = _Dom.byIdOrName(elem);
227 
228         var replacedForms = _Dom.findByTagName(elem, "form", false);
229         var applyVST = _Lang.hitch(this, function(elem) {
230             this._setVSTForm(context, elem);
231         });
232 
233         try {
234             _Lang.arrForEach(replacedForms, applyVST, 0, this);
235         } finally {
236             applyVST = null;
237         }
238     },
239 
240     /**
241      * processes an incoming error from the response
242      * which is hosted under the <error> tag
243      * @param request the current request
244      * @param context the contect object
245      * @param node the node in the xml hosting the error message
246      */
247     processError : function(request, context, node) {
248         /**
249          * <error>
250          *      <error-name>String</error-name>
251          *      <error-message><![CDATA[message]]></error-message>
252          * <error>
253          */
254         var errorName = node.firstChild.textContent || "",
255                 errorMessage = node.childNodes[1].firstChild.data || "";
256 
257         this.attr("impl").sendError(request, context, this.attr("impl").SERVER_ERROR, errorName, errorMessage, "myfaces._impl.xhrCore._AjaxResponse", "processError");
258     },
259 
260     /**
261      * processes an incoming xml redirect directive from the ajax response
262      * @param request the request object
263      * @param context the context
264      * @param node the node hosting the redirect data
265      */
266     processRedirect : function(request, context, node) {
267         /**
268          * <redirect url="url to redirect" />
269          */
270         var _Lang = this._Lang;
271         var redirectUrl = node.getAttribute("url");
272         if (!redirectUrl) {
273             throw this._raiseError(new Error(),_Lang.getMessage("ERR_RED_URL", null, "_AjaxResponse.processRedirect"),"processRedirect");
274         }
275         redirectUrl = _Lang.trim(redirectUrl);
276         if (redirectUrl == "") {
277             return false;
278         }
279         window.location = redirectUrl;
280         return true;
281     }
282     ,
283 
284     /**
285      * main entry point for processing the changes
286      * it deals with the <changes> node of the
287      * response
288      *
289      * @param request the xhr request object
290      * @param context the context map
291      * @param node the changes node to be processed
292      */
293     processChanges : function(request, context, node) {
294         var changes = node.childNodes;
295         var _Lang = this._Lang;
296         //note we need to trace the changes which could affect our insert update or delete
297         //se that we can realign our ViewStates afterwards
298         //the realignment must happen post change processing
299 
300         for (var i = 0; i < changes.length; i++) {
301 
302             switch (changes[i].tagName) {
303 
304                 case this.CMD_UPDATE:
305                     this.processUpdate(request, context, changes[i]);
306                     break;
307                 case this.CMD_EVAL:
308                     _Lang.globalEval(changes[i].firstChild.data);
309                     break;
310                 case this.CMD_INSERT:
311                     this.processInsert(request, context, changes[i]);
312                     break;
313                 case this.CMD_DELETE:
314                     this.processDelete(request, context, changes[i]);
315                     break;
316                 case this.CMD_ATTRIBUTES:
317                     this.processAttributes(request, context, changes[i]);
318                     break;
319                 case this.CMD_EXTENSION:
320                     break;
321                 default:
322                     throw this._raiseError(new Error(),"_AjaxResponse.processChanges: Illegal Command Issued","processChanges");
323             }
324         }
325 
326         return true;
327     }
328     ,
329 
330     /**
331      * First substep process a pending update tag
332      *
333      * @param request the xhr request object
334      * @param context the context map
335      * @param node the changes node to be processed
336      */
337     processUpdate : function(request, context, node) {
338         if (node.getAttribute('id') == this.P_VIEWSTATE) {
339             //update the submitting forms viewstate to the new value
340             // The source form has to be pulled out of the CURRENT document first because the context object
341             // may refer to an invalid document if an update of the entire body has occurred before this point.
342             var mfInternal = context._mfInternal,
343                 fuzzyFormDetection = this._Lang.hitch(this._Dom, this._Dom.fuzzyFormDetection);
344             var elemId = (mfInternal._mfSourceControlId)? mfInternal._mfSourceControlId:
345                             ((context.source)?context.source.id: null);
346 
347                     //theoretically a source of null can be given, then our form detection fails for
348                     //the source element case and hence updateviewstate is skipped for the source
349                     //form, but still render targets still can get the viewstate
350             var sourceForm = (mfInternal && mfInternal["_mfSourceFormId"] &&
351                            document.forms[mfInternal["_mfSourceFormId"]]) ?
352                            document.forms[mfInternal["_mfSourceFormId"]] : ((elemId)? fuzzyFormDetection(elemId): null);
353 
354             mfInternal.appliedViewState = node.firstChild.nodeValue;
355             //source form could not be determined either over the form identifer or the element
356             //we now skip this phase and just add everything we need for the fixup code
357 
358             if (!sourceForm) {
359                 //no source form found is not an error because
360                 //we might be able to recover one way or the other
361                 return true;
362             }
363 
364             mfInternal._updateForms.push(sourceForm.id);
365             //this._setVSTForm(sourceForm);
366         }
367         else {
368             // response may contain several blocks
369             var cDataBlock = this._Dom.concatCDATABlocks(node),
370                     resultNode = null,
371                     pushOpRes = this._Lang.hitch(this, this._pushOperationResult);
372 
373             switch (node.getAttribute('id')) {
374                 case this.P_VIEWROOT:
375 
376                     cDataBlock = cDataBlock.substring(cDataBlock.indexOf("<html"));
377 
378                     var parsedData = this._replaceHead(request, context, cDataBlock);
379 
380                     resultNode = ('undefined' != typeof parsedData && null != parsedData) ? this._replaceBody(request, context, cDataBlock, parsedData) : this._replaceBody(request, context, cDataBlock);
381                     if (resultNode) {
382                         pushOpRes(context, resultNode);
383                     }
384                     break;
385                 case this.P_VIEWHEAD:
386                     //we cannot replace the head, almost no browser allows this, some of them throw errors
387                     //others simply ignore it or replace it and destroy the dom that way!
388                     this._replaceHead(request, context, cDataBlock);
389 
390                     break;
391                 case this.P_VIEWBODY:
392                     //we assume the cdata block is our body including the tag
393                     resultNode = this._replaceBody(request, context, cDataBlock);
394                     if (resultNode) {
395                         pushOpRes(context, resultNode);
396                     }
397                     break;
398 
399                 default:
400                     resultNode = this.replaceHtmlItem(request, context, node.getAttribute('id'), cDataBlock);
401                     if (resultNode) {
402                         pushOpRes(context, resultNode);
403                     }
404                     break;
405             }
406         }
407 
408         return true;
409     }
410     ,
411 
412     _pushOperationResult: function(context, resultNode) {
413         var mfInternal = context._mfInternal;
414         var pushSubnode = this._Lang.hitch(this, function(currNode) {
415             var parentForm = this._Dom.getParent(currNode, "form");
416             //if possible we work over the ids
417             //so that elements later replaced are referenced
418             //at the latest possibility
419             if (null != parentForm) {
420                 mfInternal._updateForms.push(parentForm.id || parentForm);
421             }
422             else {
423                 mfInternal._updateElems.push(currNode.id || currNode);
424             }
425         });
426         var isArr = 'undefined' != typeof resultNode.length && 'undefined' == typeof resultNode.nodeType;
427         if (isArr && resultNode.length) {
428             for (var cnt = 0; cnt < resultNode.length; cnt++) {
429                 pushSubnode(resultNode[cnt]);
430             }
431         } else if (!isArr) {
432             pushSubnode(resultNode);
433         }
434 
435     }
436     ,
437 
438     /**
439      * replaces a current head theoretically,
440      * pratically only the scripts are evaled anew since nothing else
441      * can be changed.
442      *
443      * @param request the current request
444      * @param context the ajax context
445      * @param newData the data to be processed
446      *
447      * @return an xml representation of the page for further processing if possible
448      */
449     _replaceHead: function(request, context, newData) {
450 
451         var _Lang = this._Lang,
452                 _Dom = this._Dom,
453                 isWebkit = this._RT.browser.isWebKit,
454             //we have to work around an xml parsing bug in Webkit
455             //see https://issues.apache.org/jira/browse/MYFACES-3061
456                 doc = (!isWebkit) ? _Lang.parseXML(newData) : null,
457                 newHead = null;
458 
459         if (!isWebkit && _Lang.isXMLParseError(doc)) {
460             doc = _Lang.parseXML(newData.replace(/<!\-\-[\s\n]*<!\-\-/g, "<!--").replace(/\/\/-->[\s\n]*\/\/-->/g, "//-->"));
461         }
462 
463         if (isWebkit || _Lang.isXMLParseError(doc)) {
464             //the standard xml parser failed we retry with the stripper
465             var parser = new (this._RT.getGlobalConfig("updateParser", myfaces._impl._util._HtmlStripper))();
466             var headData = parser.parse(newData, "head");
467             //We cannot avoid it here, but we have reduced the parsing now down to the bare minimum
468             //for further processing
469             newHead = _Lang.parseXML("<head>" + headData + "</head>");
470             //last and slowest option create a new head element and let the browser
471             //do its slow job
472             if (_Lang.isXMLParseError(newHead)) {
473                 try {
474                     newHead = _Dom.createElement("head");
475                     newHead.innerHTML = headData;
476                 } catch (e) {
477                     //we give up no further fallbacks
478                     throw this._raiseError(new Error(),"Error head replacement failed reason:" + e.toString(),"_replaceHead");
479                 }
480             }
481         } else {
482             //parser worked we go on
483             newHead = doc.getElementsByTagName("head")[0];
484         }
485 
486         var oldTags = _Dom.findByTagNames(document.getElementsByTagName("head")[0], {"link": true, "style":true});
487         _Dom.runCss(newHead, true);
488         _Dom.deleteItems(oldTags);
489 
490         //var oldTags = _Dom.findByTagNames(document.getElementsByTagName("head")[0], {"script": true});
491         //_Dom.deleteScripts(oldTags);
492         _Dom.runScripts(newHead, true);
493 
494         return doc;
495     },
496 
497 
498     /**
499      * special method to handle the body dom manipulation,
500      * replacing the entire body does not work fully by simply adding a second body
501      * and by creating a range instead we have to work around that by dom creating a second
502      * body and then filling it properly!
503      *
504      * @param {Object} request our request object
505      * @param {Object} context (Map) the response context
506      * @param {String} newData the markup which replaces the old dom node!
507      * @param {Node} parsedData (optional) preparsed XML representation data of the current document
508      */
509     _replaceBody : function(request, context, newData /*varargs*/) {
510         var _RT = this._RT,
511                 _Dom = this._Dom,
512                 _Lang = this._Lang,
513 
514                 oldBody = document.getElementsByTagName("body")[0],
515                 placeHolder = document.createElement("div"),
516                 isWebkit = _RT.browser.isWebKit;
517 
518         placeHolder.id = "myfaces_bodyplaceholder";
519 
520         _Dom._removeChildNodes(oldBody);
521         oldBody.innerHTML = "";
522         oldBody.appendChild(placeHolder);
523 
524         var bodyData, doc = null, parser;
525 
526         //we have to work around an xml parsing bug in Webkit
527         //see https://issues.apache.org/jira/browse/MYFACES-3061
528         if (!isWebkit) {
529             doc = (arguments.length > 3) ? arguments[3] : _Lang.parseXML(newData);
530         }
531 
532         if (!isWebkit && _Lang.isXMLParseError(doc)) {
533             doc = _Lang.parseXML(newData.replace(/<!\-\-[\s\n]*<!\-\-/g, "<!--").replace(/\/\/-->[\s\n]*\/\/-->/g, "//-->"));
534         }
535 
536         if (isWebkit || _Lang.isXMLParseError(doc)) {
537             //the standard xml parser failed we retry with the stripper
538 
539             parser = new (_RT.getGlobalConfig("updateParser", myfaces._impl._util._HtmlStripper))();
540 
541             bodyData = parser.parse(newData, "body");
542         } else {
543             //parser worked we go on
544             var newBodyData = doc.getElementsByTagName("body")[0];
545 
546             //speedwise we serialize back into the code
547             //for code reduction, speedwise we will take a small hit
548             //there which we will clean up in the future, but for now
549             //this is ok, I guess, since replace body only is a small subcase
550             //bodyData = _Lang.serializeChilds(newBodyData);
551             var browser = _RT.browser;
552             if (!browser.isIEMobile || browser.isIEMobile >= 7) {
553                 //TODO check what is failing there
554                 for (var cnt = 0; cnt < newBodyData.attributes.length; cnt++) {
555                     var value = newBodyData.attributes[cnt].value;
556                     if (value)
557                         _Dom.setAttribute(oldBody, newBodyData.attributes[cnt].name, value);
558                 }
559             }
560         }
561         //we cannot serialize here, due to escape problems
562         //we must parse, this is somewhat unsafe but should be safe enough
563         parser = new (_RT.getGlobalConfig("updateParser", myfaces._impl._util._HtmlStripper))();
564         bodyData = parser.parse(newData, "body");
565 
566         var returnedElement = this.replaceHtmlItem(request, context, placeHolder, bodyData);
567 
568         if (returnedElement) {
569             this._pushOperationResult(context, returnedElement);
570         }
571         return returnedElement;
572     }
573     ,
574 
575     /**
576      * Replaces HTML elements through others and handle errors if the occur in the replacement part
577      *
578      * @param {Object} request (xhrRequest)
579      * @param {Object} context (Map)
580      * @param {Object} itemIdToReplace (String|Node) - ID of the element to replace
581      * @param {String} markup - the new tag
582      */
583     replaceHtmlItem : function(request, context, itemIdToReplace, markup) {
584         var _Lang = this._Lang, _Dom = this._Dom;
585 
586         var item = (!_Lang.isString(itemIdToReplace)) ? itemIdToReplace :
587                 _Dom.byIdOrName(itemIdToReplace);
588 
589         if (!item) {
590             throw this._raisError(_Lang.getMessage("ERR_ITEM_ID_NOTFOUND", null, "_AjaxResponse.replaceHtmlItem", (itemIdToReplace) ? itemIdToReplace.toString() : "undefined"));
591         }
592         return _Dom.outerHTML(item, markup);
593     },
594 
595     /**
596      * xml insert command handler
597      *
598      * @param request the ajax request element
599      * @param context the context element holding the data
600      * @param node the xml node holding the insert data
601      * @return true upon successful completion, false otherwise
602      *
603      **/
604     processInsert: function(request, context, node) {
605         /*remapping global namespaces for speed and readability reasons*/
606         var _Dom = this._Dom,
607                 _Lang = this._Lang,
608             //determine which path to go:
609                 insertData = this._parseInsertData(request, context, node);
610 
611         if (!insertData) return false;
612 
613         var opNode = _Dom.byIdOrName(insertData.opId);
614         if (!opNode) {
615             throw this._raiseError(new Error(),_Lang.getMessage("ERR_PPR_INSERTBEFID_1", null, "_AjaxResponse.processInsert", insertData.opId),"processInsert");
616         }
617 
618         //call insertBefore or insertAfter in our dom routines
619         var replacementFragment = _Dom[insertData.insertType](opNode, insertData.cDataBlock);
620         if (replacementFragment) {
621             this._pushOperationResult(context, replacementFragment);
622         }
623         return true;
624     },
625 
626     /**
627      * determines the corner data from the insert tag parsing process
628      *
629      *
630      * @param request request
631      * @param context context
632      * @param node the current node pointing to the insert tag
633      * @return false if the parsing failed, otherwise a map with follwing attributes
634      * <ul>
635      *     <li>inserType - a ponter to a constant which maps the direct function name for the insert operation </li>
636      *     <li>opId - the before or after id </li>
637      *     <li>cDataBlock - the html cdata block which needs replacement </li>
638      * </ul>
639      *
640      * TODO we have to find a mechanism to replace the direct sendError calls with a javascript exception
641      * which we then can use for cleaner error code handling
642      */
643     _parseInsertData: function(request, context, node) {
644         var _Lang = this._Lang,
645                 _Dom = this._Dom,
646                 concatCDATA = _Dom.concatCDATABlocks,
647 
648                 INSERT_TYPE_BEFORE = "insertBefore",
649                 INSERT_TYPE_AFTER = "insertAfter",
650 
651                 id = node.getAttribute("id"),
652                 beforeId = node.getAttribute("before"),
653                 afterId = node.getAttribute("after"),
654                 ret = {};
655 
656         //now we have to make a distinction between two different parsing paths
657         //due to a spec malalignment
658         //a <insert id="... beforeId|AfterId ="...
659         //b <insert><before id="..., <insert> <after id="....
660         //see https://issues.apache.org/jira/browse/MYFACES-3318
661         //simple id, case1
662         if (id && beforeId && !afterId) {
663             ret.insertType = INSERT_TYPE_BEFORE;
664             ret.opId = beforeId;
665             ret.cDataBlock = concatCDATA(node);
666 
667             //<insert id=".. afterId="..
668         } else if (id && !beforeId && afterId) {
669             ret.insertType = INSERT_TYPE_AFTER;
670             ret.opId = afterId;
671             ret.cDataBlock = concatCDATA(node);
672 
673             //<insert><before id="... <insert><after id="...
674         } else if (!id) {
675             var opType = node.childNodes[0].tagName;
676 
677             if (opType != "before" && opType != "after") {
678                 throw this._raiseError(new Error(),_Lang.getMessage("ERR_PPR_INSERTBEFID"),"_parseInsertData");
679             }
680             opType = opType.toLowerCase();
681             var beforeAfterId = node.childNodes[0].getAttribute("id");
682             ret.insertType = (opType == "before") ? INSERT_TYPE_BEFORE : INSERT_TYPE_AFTER;
683             ret.opId = beforeAfterId;
684             ret.cDataBlock = concatCDATA(node.childNodes[0]);
685         } else {
686             throw this._raiseError(new Error(),[_Lang.getMessage("ERR_PPR_IDREQ"),
687                                     "\n ",
688                                     _Lang.getMessage("ERR_PPR_INSERTBEFID")].join(""),"_parseInsertData");
689         }
690         ret.opId = _Lang.trim(ret.opId);
691         return ret;
692     },
693 
694     processDelete : function(request, context, node) {
695 
696         var _Lang = this._Lang,
697                 _Dom = this._Dom,
698                 deleteId = node.getAttribute('id');
699 
700         if (!deleteId) {
701             throw this._raiseError(new Error(),_Lang.getMessage("ERR_PPR_UNKNOWNCID", null, "_AjaxResponse.processDelete", ""),"processDelete");
702         }
703 
704         var item = _Dom.byIdOrName(deleteId);
705         if (!item) {
706             throw this._raiseError(new Error(),_Lang.getMessage("ERR_PPR_UNKNOWNCID", null, "_AjaxResponse.processDelete", deleteId),"processDelete");
707         }
708 
709         var parentForm = this._Dom.getParent(item, "form");
710         if (null != parentForm) {
711             context._mfInternal._updateForms.push(parentForm);
712         }
713         _Dom.deleteItem(item);
714 
715         return true;
716     }
717     ,
718 
719     processAttributes : function(request, context, node) {
720         //we now route into our attributes function to bypass
721         //IE quirks mode incompatibilities to the biggest possible extent
722         //most browsers just have to do a setAttributes but IE
723         //behaves as usual not like the official standard
724         //myfaces._impl._util.this._Dom.setAttribute(domNode, attribute, value;
725 
726         var _Lang = this._Lang,
727             //<attributes id="id of element"> <attribute name="attribute name" value="attribute value" />* </attributes>
728                 elemId = node.getAttribute('id');
729 
730         if (!elemId) {
731             throw this._raiseError(new Error(),"Error in attributes, id not in xml markup","processAttributes");
732         }
733         var childNodes = node.childNodes;
734 
735         if (!childNodes) {
736             return false;
737         }
738         for (var loop2 = 0; loop2 < childNodes.length; loop2++) {
739             var attributesNode = childNodes[loop2],
740                     attrName = attributesNode.getAttribute("name"),
741                     attrValue = attributesNode.getAttribute("value");
742 
743             if (!attrName) {
744                 continue;
745             }
746 
747             attrName = _Lang.trim(attrName);
748             /*no value means reset*/
749             //value can be of boolean value hence full check
750             if ('undefined' == typeof attrValue || null == attrValue) {
751                 attrValue = "";
752             }
753 
754             switch (elemId) {
755                 case this.P_VIEWROOT:
756                     throw  this._raiseError(new Error(),_Lang.getMessage("ERR_NO_VIEWROOTATTR", null, "_AjaxResponse.processAttributes"),"processAttributes");
757 
758                 case this.P_VIEWHEAD:
759                     throw  this._raiseError(new Error(),_Lang.getMessage("ERR_NO_HEADATTR", null, "_AjaxResponse.processAttributes"),"processAttributes");
760 
761                 case this.P_VIEWBODY:
762                     var element = document.getElementsByTagName("body")[0];
763                     this._Dom.setAttribute(element, attrName, attrValue);
764                     break;
765 
766                 default:
767                     this._Dom.setAttribute(document.getElementById(elemId), attrName, attrValue);
768                     break;
769             }
770         }
771         return true;
772     },
773 
774     /**
775      * internal helper which raises an error in the
776      * format we need for further processing
777      *
778      * @param message the message
779      * @param title the title of the error (optional)
780      * @param name the name of the error (optional)
781      */
782     _raiseError: function(error, message,  caller, title, name) {
783         var _Impl = this.attr("impl");
784         var finalTitle = title || _Impl.MALFORMEDXML;
785         var finalName = name || _Impl.MALFORMEDXML;
786         var finalMessage = message || "";
787 
788         return this._Lang.makeException(error, finalTitle, finalName, this._nameSpace, caller || ( (arguments.caller) ? arguments.caller.toString() : "_raiseError"), finalMessage);
789     }
790 });
791