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  * An implementation of an xhr request object
 19  * with partial page submit functionality, and jsf
 20  * ppr request and timeout handling capabilities
 21  *
 22  * Author: Werner Punz (latest modification by $Author: ganeshpuri $)
 23  * Version: $Revision: 1.4 $ $Date: 2009/05/31 09:16:44 $
 24  */
 25 
 26 /**
 27  * @class
 28  * @name _AjaxRequest
 29  * @memberOf myfaces._impl.xhrCore
 30  * @extends myfaces._impl.core.Object
 31  */
 32 _MF_CLS(_PFX_XHR + "_AjaxRequest", _MF_OBJECT, /** @lends myfaces._impl.xhrCore._AjaxRequest.prototype */ {
 33 
 34     _contentType: "application/x-www-form-urlencoded",
 35     /** source element issuing the request */
 36     _source: null,
 37     /** context passed down from the caller */
 38     _context:null,
 39     /** source form issuing the request */
 40     _sourceForm: null,
 41     /** passthrough parameters */
 42     _passThrough: null,
 43 
 44     /** queue control */
 45     _timeout: null,
 46     /** enqueuing delay */
 47     //_delay:null,
 48     /** queue size */
 49     _queueSize:-1,
 50 
 51     /**
 52      back reference to the xhr queue,
 53      only set if the object really is queued
 54      */
 55     _xhrQueue: null,
 56 
 57     /** pps an array of identifiers which should be part of the submit, the form is ignored */
 58     _partialIdsArray : null,
 59 
 60     /** xhr object, internal param */
 61     _xhr: null,
 62 
 63     /** predefined method */
 64     _ajaxType:"POST",
 65 
 66     //CONSTANTS
 67     ENCODED_URL:"javax.faces.encodedURL",
 68     /*
 69      * constants used internally
 70      */
 71     _CONTENT_TYPE:"Content-Type",
 72     _HEAD_FACES_REQ:"Faces-Request",
 73     _VAL_AJAX: "partial/ajax",
 74     _XHR_CONST: myfaces._impl.xhrCore.engine.XhrConst,
 75 
 76     // _exception: null,
 77     // _requestParameters: null,
 78     /**
 79      * Constructor
 80      * <p />
 81      * note there is a load of common properties
 82      * inherited by the base class which define the corner
 83      * parameters and the general internal behavior
 84      * like _onError etc...
 85      * @param {Object} args an arguments map which an override any of the given protected
 86      * instance variables, by a simple name value pair combination
 87      */
 88     constructor_: function(args) {
 89 
 90         try {
 91             this._callSuper("constructor_", args);
 92 
 93             this._initDefaultFinalizableFields();
 94             delete this._resettableContent["_xhrQueue"];
 95 
 96             this.applyArgs(args);
 97 
 98             /*namespace remapping for readability*/
 99             //we fetch in the standard arguments
100             //and apply them to our protected attributes
101             //we do not gc the entry hence it is not defined on top
102             var xhrCore = myfaces._impl.xhrCore;
103             this._AJAXUTIL = xhrCore._AjaxUtils;
104 
105         } catch (e) {
106             //_onError
107             this._stdErrorHandler(this._xhr, this._context, e);
108         }
109     },
110 
111     /**
112      * Sends an Ajax request
113      */
114     send : function() {
115 
116         var _Lang = this._Lang;
117 
118         try {
119 
120             var scopeThis = _Lang.hitch(this, function(functionName) {
121                 return _Lang.hitch(this, this[functionName]);
122             });
123             this._xhr = _Lang.mixMaps(this._getTransport(), {
124                 onprogress: scopeThis("onprogress"),
125                 ontimeout:  scopeThis("ontimeout"),
126                 onloadend:  scopeThis("ondone"),
127                 onload:     scopeThis("onsuccess"),
128                 onerror:    scopeThis("onerror")
129 
130             }, true);
131             var xhr = this._xhr,
132                     sourceForm = this._sourceForm,
133                     targetURL = (typeof sourceForm.elements[this.ENCODED_URL] == 'undefined') ?
134                             sourceForm.action :
135                             sourceForm.elements[this.ENCODED_URL].value,
136                     formData = this.getFormData();
137 
138             for (var key in this._passThrough) {
139                 if(!this._passThrough.hasOwnProperty(key)) continue;
140                 formData.append(key, this._passThrough[key]);
141             }
142 
143             xhr.open(this._ajaxType, targetURL +
144                     ((this._ajaxType == "GET") ? "?" + this._formDataToURI(formData) : "")
145                     , true);
146 
147             xhr.timeout = this._timeout || 0;
148 
149             var contentType = this._contentType+"; charset=utf-8";
150 
151             xhr.setRequestHeader(this._CONTENT_TYPE, contentType);
152             xhr.setRequestHeader(this._HEAD_FACES_REQ, this._VAL_AJAX);
153 
154             this._sendEvent("BEGIN");
155             //Check if it is a custom form data object
156             //if yes we use makefinal for the final handling
157             if (formData && formData.makeFinal) {
158                 formData = formData.makeFinal()
159             }
160             xhr.send((this._ajaxType != "GET") ? formData : null);
161 
162         } catch (e) {
163             //_onError//_onError
164             e = (e._mfInternal)? e: this._Lang.makeException(new Error(), "sendError","sendError", this._nameSpace, "send", e.message);
165             this._stdErrorHandler(this._xhr, this._context, e);
166         }
167     },
168 
169 
170     ondone: function() {
171         this._requestDone();
172     },
173 
174 
175     onsuccess: function(/*evt*/) {
176 
177         var context = this._context;
178         var xhr = this._xhr;
179         try {
180             this._sendEvent("COMPLETE");
181             //now we have to reroute into our official api
182             //because users might want to decorate it, we will split it apart afterwards
183 
184             context._mfInternal = context._mfInternal || {};
185             jsf.ajax.response((xhr.getXHRObject) ? xhr.getXHRObject() : xhr, context);
186 
187 
188 
189         } catch (e) {
190             this._stdErrorHandler(this._xhr, this._context, e);
191         }
192     },
193 
194     onerror: function(/*evt*/) {
195         //TODO improve the error code detection here regarding server errors etc...
196         //and push it into our general error handling subframework
197         var context = this._context;
198         var xhr = this._xhr;
199         var _Lang = this._Lang;
200 
201         var errorText = "";
202         this._sendEvent("COMPLETE");
203         try {
204             var UNKNOWN = _Lang.getMessage("UNKNOWN");
205             //status can be 0 and statusText can be ""
206             var status = ('undefined' != xhr.status  && null != xhr.status)? xhr.status : UNKNOWN;
207             var statusText = ('undefined' != xhr.statusText  && null != xhr.statusText)? xhr.statusText : UNKNOWN;
208             errorText = _Lang.getMessage("ERR_REQU_FAILED", null,status,statusText);
209 
210         } catch (e) {
211             errorText = _Lang.getMessage("ERR_REQ_FAILED_UNKNOWN", null);
212         } finally {
213             var _Impl = this.attr("impl");
214             _Impl.sendError(xhr, context, _Impl.HTTPERROR,
215                     _Impl.HTTPERROR, errorText,"","myfaces._impl.xhrCore._AjaxRequest","onerror");
216         }
217         //_onError
218     },
219 
220     onprogress: function(/*evt*/) {
221         //do nothing for now
222     },
223 
224     ontimeout: function(/*evt*/) {
225         try {
226             //we issue an event not an error here before killing the xhr process
227             this._sendEvent("TIMEOUT_EVENT");
228             //timeout done we process the next in the queue
229         } finally {
230             this._requestDone();
231         }
232     },
233 
234     _formDataToURI: function(formData) {
235         if (formData && formData.makeFinal) {
236             formData = formData.makeFinal()
237         }
238         return formData;
239     },
240 
241     _getTransport: function() {
242 
243         var xhr = this._RT.getXHRObject();
244         //the current xhr level2 timeout w3c spec is not implemented by the browsers yet
245         //we have to do a fallback to our custom routines
246 
247         //Chrome fails in the current builds, on our loadend, we disable the xhr
248         //level2 optimisations for now
249         //if (('undefined' == typeof this._timeout || null == this._timeout) && _Rt.getXHRLvl() >= 2) {
250         //no timeout we can skip the emulation layer
251         //    return xhr;
252         //}
253         return new myfaces._impl.xhrCore.engine.Xhr1({xhrObject: xhr});
254     },
255 
256 
257 
258     //----------------- backported from the base request --------------------------------
259     //non abstract ones
260     /**
261      * Spec. 13.3.1
262      * Collect and encode input elements.
263      * Additionally the hidden element javax.faces.ViewState
264      *
265      *
266      * @return  an element of formDataWrapper
267      * which keeps the final Send Representation of the
268      */
269     getFormData : function() {
270         var _AJAXUTIL = this._AJAXUTIL, myfacesOptions = this._context.myfaces;
271         return this._Lang.createFormDataDecorator(jsf.getViewState(this._sourceForm));
272     },
273 
274     /**
275      * Client error handlers which also in the long run route into our error queue
276      * but also are able to deliver more meaningful messages
277      * note, in case of an error all subsequent xhr requests are dropped
278      * to get a clean state on things
279      *
280      * @param request the xhr request object
281      * @param context the context holding all values for further processing
282      * @param exception the embedded exception
283      */
284     _stdErrorHandler: function(request, context, exception) {
285         var xhrQueue = this._xhrQueue;
286         try {
287              this.attr("impl").stdErrorHandler(request, context, exception);
288         } finally {
289             if (xhrQueue) {
290                 xhrQueue.cleanup();
291             }
292         }
293     },
294 
295     _sendEvent: function(evtType) {
296         var _Impl = this.attr("impl");
297         _Impl.sendEvent(this._xhr, this._context, _Impl[evtType]);
298     },
299 
300     _requestDone: function() {
301         var queue = this._xhrQueue;
302         if (queue) {
303             queue.processQueue();
304         }
305         //ie6 helper cleanup
306         delete this._context.source;
307         this._finalize();
308     },
309 
310     //cleanup
311     _finalize: function() {
312         if (this._xhr.readyState == this._XHR_CONST.READY_STATE_DONE) {
313             this._callSuper("_finalize");
314         }
315     }
316 });
317 
318