Bug:Fix file validation issue
[vnfsdk/refrepo.git] / vnfmarket / src / main / webapp / vnfmarket / node_modules / socket.io-client / lib / vendor / web-socket-js / web_socket.js
1 // Copyright: Hiroshi Ichikawa <http://gimite.net/en/>
2 // License: New BSD License
3 // Reference: http://dev.w3.org/html5/websockets/
4 // Reference: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol
5
6 (function() {
7   
8   if ('undefined' == typeof window || window.WebSocket) return;
9
10   var console = window.console;
11   if (!console || !console.log || !console.error) {
12     console = {log: function(){ }, error: function(){ }};
13   }
14   
15   if (!swfobject.hasFlashPlayerVersion("10.0.0")) {
16     console.error("Flash Player >= 10.0.0 is required.");
17     return;
18   }
19   if (location.protocol == "file:") {
20     console.error(
21       "WARNING: web-socket-js doesn't work in file:///... URL " +
22       "unless you set Flash Security Settings properly. " +
23       "Open the page via Web server i.e. http://...");
24   }
25
26   /**
27    * This class represents a faux web socket.
28    * @param {string} url
29    * @param {array or string} protocols
30    * @param {string} proxyHost
31    * @param {int} proxyPort
32    * @param {string} headers
33    */
34   WebSocket = function(url, protocols, proxyHost, proxyPort, headers) {
35     var self = this;
36     self.__id = WebSocket.__nextId++;
37     WebSocket.__instances[self.__id] = self;
38     self.readyState = WebSocket.CONNECTING;
39     self.bufferedAmount = 0;
40     self.__events = {};
41     if (!protocols) {
42       protocols = [];
43     } else if (typeof protocols == "string") {
44       protocols = [protocols];
45     }
46     // Uses setTimeout() to make sure __createFlash() runs after the caller sets ws.onopen etc.
47     // Otherwise, when onopen fires immediately, onopen is called before it is set.
48     setTimeout(function() {
49       WebSocket.__addTask(function() {
50         WebSocket.__flash.create(
51             self.__id, url, protocols, proxyHost || null, proxyPort || 0, headers || null);
52       });
53     }, 0);
54   };
55
56   /**
57    * Send data to the web socket.
58    * @param {string} data  The data to send to the socket.
59    * @return {boolean}  True for success, false for failure.
60    */
61   WebSocket.prototype.send = function(data) {
62     if (this.readyState == WebSocket.CONNECTING) {
63       throw "INVALID_STATE_ERR: Web Socket connection has not been established";
64     }
65     // We use encodeURIComponent() here, because FABridge doesn't work if
66     // the argument includes some characters. We don't use escape() here
67     // because of this:
68     // https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#escape_and_unescape_Functions
69     // But it looks decodeURIComponent(encodeURIComponent(s)) doesn't
70     // preserve all Unicode characters either e.g. "\uffff" in Firefox.
71     // Note by wtritch: Hopefully this will not be necessary using ExternalInterface.  Will require
72     // additional testing.
73     var result = WebSocket.__flash.send(this.__id, encodeURIComponent(data));
74     if (result < 0) { // success
75       return true;
76     } else {
77       this.bufferedAmount += result;
78       return false;
79     }
80   };
81
82   /**
83    * Close this web socket gracefully.
84    */
85   WebSocket.prototype.close = function() {
86     if (this.readyState == WebSocket.CLOSED || this.readyState == WebSocket.CLOSING) {
87       return;
88     }
89     this.readyState = WebSocket.CLOSING;
90     WebSocket.__flash.close(this.__id);
91   };
92
93   /**
94    * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
95    *
96    * @param {string} type
97    * @param {function} listener
98    * @param {boolean} useCapture
99    * @return void
100    */
101   WebSocket.prototype.addEventListener = function(type, listener, useCapture) {
102     if (!(type in this.__events)) {
103       this.__events[type] = [];
104     }
105     this.__events[type].push(listener);
106   };
107
108   /**
109    * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
110    *
111    * @param {string} type
112    * @param {function} listener
113    * @param {boolean} useCapture
114    * @return void
115    */
116   WebSocket.prototype.removeEventListener = function(type, listener, useCapture) {
117     if (!(type in this.__events)) return;
118     var events = this.__events[type];
119     for (var i = events.length - 1; i >= 0; --i) {
120       if (events[i] === listener) {
121         events.splice(i, 1);
122         break;
123       }
124     }
125   };
126
127   /**
128    * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
129    *
130    * @param {Event} event
131    * @return void
132    */
133   WebSocket.prototype.dispatchEvent = function(event) {
134     var events = this.__events[event.type] || [];
135     for (var i = 0; i < events.length; ++i) {
136       events[i](event);
137     }
138     var handler = this["on" + event.type];
139     if (handler) handler(event);
140   };
141
142   /**
143    * Handles an event from Flash.
144    * @param {Object} flashEvent
145    */
146   WebSocket.prototype.__handleEvent = function(flashEvent) {
147     if ("readyState" in flashEvent) {
148       this.readyState = flashEvent.readyState;
149     }
150     if ("protocol" in flashEvent) {
151       this.protocol = flashEvent.protocol;
152     }
153     
154     var jsEvent;
155     if (flashEvent.type == "open" || flashEvent.type == "error") {
156       jsEvent = this.__createSimpleEvent(flashEvent.type);
157     } else if (flashEvent.type == "close") {
158       // TODO implement jsEvent.wasClean
159       jsEvent = this.__createSimpleEvent("close");
160     } else if (flashEvent.type == "message") {
161       var data = decodeURIComponent(flashEvent.message);
162       jsEvent = this.__createMessageEvent("message", data);
163     } else {
164       throw "unknown event type: " + flashEvent.type;
165     }
166     
167     this.dispatchEvent(jsEvent);
168   };
169   
170   WebSocket.prototype.__createSimpleEvent = function(type) {
171     if (document.createEvent && window.Event) {
172       var event = document.createEvent("Event");
173       event.initEvent(type, false, false);
174       return event;
175     } else {
176       return {type: type, bubbles: false, cancelable: false};
177     }
178   };
179   
180   WebSocket.prototype.__createMessageEvent = function(type, data) {
181     if (document.createEvent && window.MessageEvent && !window.opera) {
182       var event = document.createEvent("MessageEvent");
183       event.initMessageEvent("message", false, false, data, null, null, window, null);
184       return event;
185     } else {
186       // IE and Opera, the latter one truncates the data parameter after any 0x00 bytes.
187       return {type: type, data: data, bubbles: false, cancelable: false};
188     }
189   };
190   
191   /**
192    * Define the WebSocket readyState enumeration.
193    */
194   WebSocket.CONNECTING = 0;
195   WebSocket.OPEN = 1;
196   WebSocket.CLOSING = 2;
197   WebSocket.CLOSED = 3;
198
199   WebSocket.__flash = null;
200   WebSocket.__instances = {};
201   WebSocket.__tasks = [];
202   WebSocket.__nextId = 0;
203   
204   /**
205    * Load a new flash security policy file.
206    * @param {string} url
207    */
208   WebSocket.loadFlashPolicyFile = function(url){
209     WebSocket.__addTask(function() {
210       WebSocket.__flash.loadManualPolicyFile(url);
211     });
212   };
213
214   /**
215    * Loads WebSocketMain.swf and creates WebSocketMain object in Flash.
216    */
217   WebSocket.__initialize = function() {
218     if (WebSocket.__flash) return;
219     
220     if (WebSocket.__swfLocation) {
221       // For backword compatibility.
222       window.WEB_SOCKET_SWF_LOCATION = WebSocket.__swfLocation;
223     }
224     if (!window.WEB_SOCKET_SWF_LOCATION) {
225       console.error("[WebSocket] set WEB_SOCKET_SWF_LOCATION to location of WebSocketMain.swf");
226       return;
227     }
228     var container = document.createElement("div");
229     container.id = "webSocketContainer";
230     // Hides Flash box. We cannot use display: none or visibility: hidden because it prevents
231     // Flash from loading at least in IE. So we move it out of the screen at (-100, -100).
232     // But this even doesn't work with Flash Lite (e.g. in Droid Incredible). So with Flash
233     // Lite, we put it at (0, 0). This shows 1x1 box visible at left-top corner but this is
234     // the best we can do as far as we know now.
235     container.style.position = "absolute";
236     if (WebSocket.__isFlashLite()) {
237       container.style.left = "0px";
238       container.style.top = "0px";
239     } else {
240       container.style.left = "-100px";
241       container.style.top = "-100px";
242     }
243     var holder = document.createElement("div");
244     holder.id = "webSocketFlash";
245     container.appendChild(holder);
246     document.body.appendChild(container);
247     // See this article for hasPriority:
248     // http://help.adobe.com/en_US/as3/mobile/WS4bebcd66a74275c36cfb8137124318eebc6-7ffd.html
249     swfobject.embedSWF(
250       WEB_SOCKET_SWF_LOCATION,
251       "webSocketFlash",
252       "1" /* width */,
253       "1" /* height */,
254       "10.0.0" /* SWF version */,
255       null,
256       null,
257       {hasPriority: true, swliveconnect : true, allowScriptAccess: "always"},
258       null,
259       function(e) {
260         if (!e.success) {
261           console.error("[WebSocket] swfobject.embedSWF failed");
262         }
263       });
264   };
265   
266   /**
267    * Called by Flash to notify JS that it's fully loaded and ready
268    * for communication.
269    */
270   WebSocket.__onFlashInitialized = function() {
271     // We need to set a timeout here to avoid round-trip calls
272     // to flash during the initialization process.
273     setTimeout(function() {
274       WebSocket.__flash = document.getElementById("webSocketFlash");
275       WebSocket.__flash.setCallerUrl(location.href);
276       WebSocket.__flash.setDebug(!!window.WEB_SOCKET_DEBUG);
277       for (var i = 0; i < WebSocket.__tasks.length; ++i) {
278         WebSocket.__tasks[i]();
279       }
280       WebSocket.__tasks = [];
281     }, 0);
282   };
283   
284   /**
285    * Called by Flash to notify WebSockets events are fired.
286    */
287   WebSocket.__onFlashEvent = function() {
288     setTimeout(function() {
289       try {
290         // Gets events using receiveEvents() instead of getting it from event object
291         // of Flash event. This is to make sure to keep message order.
292         // It seems sometimes Flash events don't arrive in the same order as they are sent.
293         var events = WebSocket.__flash.receiveEvents();
294         for (var i = 0; i < events.length; ++i) {
295           WebSocket.__instances[events[i].webSocketId].__handleEvent(events[i]);
296         }
297       } catch (e) {
298         console.error(e);
299       }
300     }, 0);
301     return true;
302   };
303   
304   // Called by Flash.
305   WebSocket.__log = function(message) {
306     console.log(decodeURIComponent(message));
307   };
308   
309   // Called by Flash.
310   WebSocket.__error = function(message) {
311     console.error(decodeURIComponent(message));
312   };
313   
314   WebSocket.__addTask = function(task) {
315     if (WebSocket.__flash) {
316       task();
317     } else {
318       WebSocket.__tasks.push(task);
319     }
320   };
321   
322   /**
323    * Test if the browser is running flash lite.
324    * @return {boolean} True if flash lite is running, false otherwise.
325    */
326   WebSocket.__isFlashLite = function() {
327     if (!window.navigator || !window.navigator.mimeTypes) {
328       return false;
329     }
330     var mimeType = window.navigator.mimeTypes["application/x-shockwave-flash"];
331     if (!mimeType || !mimeType.enabledPlugin || !mimeType.enabledPlugin.filename) {
332       return false;
333     }
334     return mimeType.enabledPlugin.filename.match(/flashlite/i) ? true : false;
335   };
336   
337   if (!window.WEB_SOCKET_DISABLE_AUTO_INITIALIZATION) {
338     if (window.addEventListener) {
339       window.addEventListener("load", function(){
340         WebSocket.__initialize();
341       }, false);
342     } else {
343       window.attachEvent("onload", function(){
344         WebSocket.__initialize();
345       });
346     }
347   }
348   
349 })();