blob: 3ea57c8d9ce7ed20f9ae16eafcfd4a586c5ea8ed [file] [log] [blame]
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20/*jshint evil:true*/
21
22/**
23 * The Thrift namespace houses the Apache Thrift JavaScript library
24 * elements providing JavaScript bindings for the Apache Thrift RPC
henrique2a7dccc2014-03-07 22:16:51 +010025 * system. End users will typically only directly make use of the
26 * Transport (TXHRTransport/TWebSocketTransport) and Protocol
27 * (TJSONPRotocol/TBinaryProtocol) constructors.
28 *
29 * Object methods beginning with a __ (e.g. __onOpen()) are internal
30 * and should not be called outside of the object's own methods.
31 *
32 * This library creates one global object: Thrift
33 * Code in this library must never create additional global identifiers,
34 * all features must be scoped within the Thrift namespace.
Henrique Mendonça095ddb72013-09-20 19:38:03 +020035 * @namespace
36 * @example
37 * var transport = new Thrift.Transport("http://localhost:8585");
38 * var protocol = new Thrift.Protocol(transport);
39 * var client = new MyThriftSvcClient(protocol);
40 * var result = client.MyMethod();
41 */
42var Thrift = {
43 /**
44 * Thrift JavaScript library version.
45 * @readonly
46 * @const {string} Version
47 * @memberof Thrift
48 */
49 Version: '1.0.0-dev',
50
51 /**
52 * Thrift IDL type string to Id mapping.
53 * @readonly
54 * @property {number} STOP - End of a set of fields.
55 * @property {number} VOID - No value (only legal for return types).
56 * @property {number} BOOL - True/False integer.
57 * @property {number} BYTE - Signed 8 bit integer.
58 * @property {number} I08 - Signed 8 bit integer.
59 * @property {number} DOUBLE - 64 bit IEEE 854 floating point.
60 * @property {number} I16 - Signed 16 bit integer.
61 * @property {number} I32 - Signed 32 bit integer.
62 * @property {number} I64 - Signed 64 bit integer.
63 * @property {number} STRING - Array of bytes representing a string of characters.
64 * @property {number} UTF7 - Array of bytes representing a string of UTF7 encoded characters.
65 * @property {number} STRUCT - A multifield type.
66 * @property {number} MAP - A collection type (map/associative-array/dictionary).
67 * @property {number} SET - A collection type (unordered and without repeated values).
68 * @property {number} LIST - A collection type (unordered).
69 * @property {number} UTF8 - Array of bytes representing a string of UTF8 encoded characters.
70 * @property {number} UTF16 - Array of bytes representing a string of UTF16 encoded characters.
71 */
72 Type: {
73 'STOP' : 0,
74 'VOID' : 1,
75 'BOOL' : 2,
76 'BYTE' : 3,
77 'I08' : 3,
78 'DOUBLE' : 4,
79 'I16' : 6,
80 'I32' : 8,
81 'I64' : 10,
82 'STRING' : 11,
83 'UTF7' : 11,
84 'STRUCT' : 12,
85 'MAP' : 13,
86 'SET' : 14,
87 'LIST' : 15,
88 'UTF8' : 16,
89 'UTF16' : 17
90 },
91
92 /**
93 * Thrift RPC message type string to Id mapping.
94 * @readonly
95 * @property {number} CALL - RPC call sent from client to server.
96 * @property {number} REPLY - RPC call normal response from server to client.
97 * @property {number} EXCEPTION - RPC call exception response from server to client.
98 * @property {number} ONEWAY - Oneway RPC call from client to server with no response.
99 */
100 MessageType: {
101 'CALL' : 1,
102 'REPLY' : 2,
103 'EXCEPTION' : 3,
104 'ONEWAY' : 4
105 },
106
107 /**
108 * Utility function returning the count of an object's own properties.
109 * @param {object} obj - Object to test.
110 * @returns {number} number of object's own properties
111 */
112 objectLength: function(obj) {
113 var length = 0;
114 for (var k in obj) {
115 if (obj.hasOwnProperty(k)) {
116 length++;
117 }
118 }
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200119 return length;
120 },
121
122 /**
123 * Utility function to establish prototype inheritance.
124 * @see {@link http://javascript.crockford.com/prototypal.html|Prototypal Inheritance}
125 * @param {function} constructor - Contstructor function to set as derived.
126 * @param {function} superConstructor - Contstructor function to set as base.
127 * @param {string} [name] - Type name to set as name property in derived prototype.
128 */
129 inherits: function(constructor, superConstructor, name) {
130 function F() {}
131 F.prototype = superConstructor.prototype;
132 constructor.prototype = new F();
133 constructor.prototype.name = name || "";
134 }
135};
136
137/**
138 * Initializes a Thrift TException instance.
139 * @constructor
140 * @augments Error
141 * @param {string} message - The TException message (distinct from the Error message).
142 * @classdesc TException is the base class for all Thrift exceptions types.
143 */
144Thrift.TException = function(message) {
145 this.message = message;
146};
147Thrift.inherits(Thrift.TException, Error, 'TException');
148
149/**
150 * Returns the message set on the exception.
151 * @readonly
152 * @returns {string} exception message
153 */
154Thrift.TException.prototype.getMessage = function() {
155 return this.message;
156};
157
158/**
159 * Thrift Application Exception type string to Id mapping.
160 * @readonly
161 * @property {number} UNKNOWN - Unknown/undefined.
162 * @property {number} UNKNOWN_METHOD - Client attempted to call a method unknown to the server.
163 * @property {number} INVALID_MESSAGE_TYPE - Client passed an unknown/unsupported MessageType.
164 * @property {number} WRONG_METHOD_NAME - Unused.
165 * @property {number} BAD_SEQUENCE_ID - Unused in Thrift RPC, used to flag proprietary sequence number errors.
166 * @property {number} MISSING_RESULT - Raised by a server processor if a handler fails to supply the required return result.
167 * @property {number} INTERNAL_ERROR - Something bad happened.
168 * @property {number} PROTOCOL_ERROR - The protocol layer failed to serialize or deserialize data.
169 * @property {number} INVALID_TRANSFORM - Unused.
170 * @property {number} INVALID_PROTOCOL - The protocol (or version) is not supported.
171 * @property {number} UNSUPPORTED_CLIENT_TYPE - Unused.
172 */
173Thrift.TApplicationExceptionType = {
174 'UNKNOWN' : 0,
175 'UNKNOWN_METHOD' : 1,
176 'INVALID_MESSAGE_TYPE' : 2,
177 'WRONG_METHOD_NAME' : 3,
178 'BAD_SEQUENCE_ID' : 4,
179 'MISSING_RESULT' : 5,
180 'INTERNAL_ERROR' : 6,
181 'PROTOCOL_ERROR' : 7,
182 'INVALID_TRANSFORM' : 8,
183 'INVALID_PROTOCOL' : 9,
184 'UNSUPPORTED_CLIENT_TYPE' : 10
185};
186
187/**
188 * Initializes a Thrift TApplicationException instance.
189 * @constructor
190 * @augments Thrift.TException
191 * @param {string} message - The TApplicationException message (distinct from the Error message).
192 * @param {Thrift.TApplicationExceptionType} [code] - The TApplicationExceptionType code.
193 * @classdesc TApplicationException is the exception class used to propagate exceptions from an RPC server back to a calling client.
194*/
195Thrift.TApplicationException = function(message, code) {
196 this.message = message;
197 this.code = typeof code === "number" ? code : 0;
198};
199Thrift.inherits(Thrift.TApplicationException, Thrift.TException, 'TApplicationException');
200
201/**
202 * Read a TApplicationException from the supplied protocol.
203 * @param {object} input - The input protocol to read from.
204 */
205Thrift.TApplicationException.prototype.read = function(input) {
206 while (1) {
207 var ret = input.readFieldBegin();
208
209 if (ret.ftype == Thrift.Type.STOP) {
210 break;
211 }
212
213 var fid = ret.fid;
214
215 switch (fid) {
216 case 1:
217 if (ret.ftype == Thrift.Type.STRING) {
218 ret = input.readString();
219 this.message = ret.value;
220 } else {
221 ret = input.skip(ret.ftype);
222 }
223 break;
224 case 2:
225 if (ret.ftype == Thrift.Type.I32) {
226 ret = input.readI32();
227 this.code = ret.value;
228 } else {
229 ret = input.skip(ret.ftype);
230 }
231 break;
232 default:
233 ret = input.skip(ret.ftype);
234 break;
235 }
236
237 input.readFieldEnd();
238 }
239
240 input.readStructEnd();
241};
242
243/**
244 * Wite a TApplicationException to the supplied protocol.
245 * @param {object} output - The output protocol to write to.
246 */
247Thrift.TApplicationException.prototype.write = function(output) {
248 output.writeStructBegin('TApplicationException');
249
250 if (this.message) {
251 output.writeFieldBegin('message', Thrift.Type.STRING, 1);
252 output.writeString(this.getMessage());
253 output.writeFieldEnd();
254 }
255
256 if (this.code) {
257 output.writeFieldBegin('type', Thrift.Type.I32, 2);
258 output.writeI32(this.code);
259 output.writeFieldEnd();
260 }
261
262 output.writeFieldStop();
263 output.writeStructEnd();
264};
265
266/**
267 * Returns the application exception code set on the exception.
268 * @readonly
269 * @returns {Thrift.TApplicationExceptionType} exception code
270 */
271Thrift.TApplicationException.prototype.getCode = function() {
272 return this.code;
273};
274
Liyin Tangf5399b22016-03-05 14:54:53 -0800275Thrift.TProtocolExceptionType = {
276 UNKNOWN: 0,
277 INVALID_DATA: 1,
278 NEGATIVE_SIZE: 2,
279 SIZE_LIMIT: 3,
280 BAD_VERSION: 4,
281 NOT_IMPLEMENTED: 5,
282 DEPTH_LIMIT: 6
283};
284
285Thrift.TProtocolException = function TProtocolException(type, message) {
286 Error.call(this);
287 Error.captureStackTrace(this, this.constructor);
288 this.name = this.constructor.name;
289 this.type = type;
290 this.message = message;
291};
292Thrift.inherits(Thrift.TProtocolException, Thrift.TException, 'TProtocolException');
293
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200294/**
henrique2a7dccc2014-03-07 22:16:51 +0100295 * Constructor Function for the XHR transport.
296 * If you do not specify a url then you must handle XHR operations on
297 * your own. This type can also be constructed using the Transport alias
298 * for backward compatibility.
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200299 * @constructor
300 * @param {string} [url] - The URL to connect to.
henrique2a7dccc2014-03-07 22:16:51 +0100301 * @classdesc The Apache Thrift Transport layer performs byte level I/O
302 * between RPC clients and servers. The JavaScript TXHRTransport object
303 * uses Http[s]/XHR. Target servers must implement the http[s] transport
304 * (see: node.js example server_http.js).
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200305 * @example
henrique2a7dccc2014-03-07 22:16:51 +0100306 * var transport = new Thrift.TXHRTransport("http://localhost:8585");
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200307 */
Roger Meier52744ee2014-03-12 09:38:42 +0100308Thrift.Transport = Thrift.TXHRTransport = function(url, options) {
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200309 this.url = url;
310 this.wpos = 0;
311 this.rpos = 0;
Roger Meier52744ee2014-03-12 09:38:42 +0100312 this.useCORS = (options && options.useCORS);
Randy Abernethy3ca89e62016-04-13 06:24:57 -0700313 this.customHeaders = options ? (options.customHeaders ? options.customHeaders : {}): {};
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200314 this.send_buf = '';
315 this.recv_buf = '';
316};
317
henrique2a7dccc2014-03-07 22:16:51 +0100318Thrift.TXHRTransport.prototype = {
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200319 /**
320 * Gets the browser specific XmlHttpRequest Object.
321 * @returns {object} the browser XHR interface object
322 */
323 getXmlHttpRequestObject: function() {
324 try { return new XMLHttpRequest(); } catch (e1) { }
325 try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch (e2) { }
326 try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch (e3) { }
327
328 throw "Your browser doesn't support XHR.";
329 },
330
331 /**
henrique2a7dccc2014-03-07 22:16:51 +0100332 * Sends the current XRH request if the transport was created with a URL
333 * and the async parameter is false. If the transport was not created with
334 * a URL, or the async parameter is True and no callback is provided, or
335 * the URL is an empty string, the current send buffer is returned.
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200336 * @param {object} async - If true the current send buffer is returned.
henrique2a7dccc2014-03-07 22:16:51 +0100337 * @param {object} callback - Optional async completion callback
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200338 * @returns {undefined|string} Nothing or the current send buffer.
339 * @throws {string} If XHR fails.
340 */
henriquea2de4102014-02-07 14:12:56 +0100341 flush: function(async, callback) {
henrique2a7dccc2014-03-07 22:16:51 +0100342 var self = this;
henriquea2de4102014-02-07 14:12:56 +0100343 if ((async && !callback) || this.url === undefined || this.url === '') {
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200344 return this.send_buf;
345 }
346
347 var xreq = this.getXmlHttpRequestObject();
348
349 if (xreq.overrideMimeType) {
henriqueeec445e2015-05-04 21:37:51 +1000350 xreq.overrideMimeType('application/vnd.apache.thrift.json; charset=utf-8');
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200351 }
352
henriquea2de4102014-02-07 14:12:56 +0100353 if (callback) {
henrique2a7dccc2014-03-07 22:16:51 +0100354 //Ignore XHR callbacks until the data arrives, then call the
355 // client's callback
356 xreq.onreadystatechange =
357 (function() {
358 var clientCallback = callback;
359 return function() {
360 if (this.readyState == 4 && this.status == 200) {
361 self.setRecvBuffer(this.responseText);
362 clientCallback();
363 }
364 };
365 }());
HIRANO Satoshi84cf3632015-12-07 17:17:15 +0900366
367 // detect net::ERR_CONNECTION_REFUSED and call the callback.
368 xreq.onerror =
369 (function() {
370 var clientCallback = callback;
371 return function() {
372 clientCallback();
373 };
374 }());
375
henriquea2de4102014-02-07 14:12:56 +0100376 }
377
378 xreq.open('POST', this.url, !!async);
henriqueeec445e2015-05-04 21:37:51 +1000379
Randy Abernethy3ca89e62016-04-13 06:24:57 -0700380 // add custom headers
381 Object.keys(self.customHeaders).forEach(function(prop) {
382 xreq.setRequestHeader(prop, self.customHeaders[prop]);
383 });
384
henriqueeec445e2015-05-04 21:37:51 +1000385 if (xreq.setRequestHeader) {
386 xreq.setRequestHeader('Accept', 'application/vnd.apache.thrift.json; charset=utf-8');
387 xreq.setRequestHeader('Content-Type', 'application/vnd.apache.thrift.json; charset=utf-8');
388 }
389
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200390 xreq.send(this.send_buf);
henriquea2de4102014-02-07 14:12:56 +0100391 if (async && callback) {
392 return;
393 }
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200394
395 if (xreq.readyState != 4) {
396 throw 'encountered an unknown ajax ready state: ' + xreq.readyState;
397 }
398
399 if (xreq.status != 200) {
400 throw 'encountered a unknown request status: ' + xreq.status;
401 }
402
403 this.recv_buf = xreq.responseText;
404 this.recv_buf_sz = this.recv_buf.length;
405 this.wpos = this.recv_buf.length;
406 this.rpos = 0;
407 },
408
409 /**
410 * Creates a jQuery XHR object to be used for a Thrift server call.
411 * @param {object} client - The Thrift Service client object generated by the IDL compiler.
412 * @param {object} postData - The message to send to the server.
henrique2a7dccc2014-03-07 22:16:51 +0100413 * @param {function} args - The original call arguments with the success call back at the end.
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200414 * @param {function} recv_method - The Thrift Service Client receive method for the call.
415 * @returns {object} A new jQuery XHR object.
416 * @throws {string} If the jQuery version is prior to 1.5 or if jQuery is not found.
417 */
418 jqRequest: function(client, postData, args, recv_method) {
419 if (typeof jQuery === 'undefined' ||
420 typeof jQuery.Deferred === 'undefined') {
421 throw 'Thrift.js requires jQuery 1.5+ to use asynchronous requests';
422 }
423
424 var thriftTransport = this;
425
426 var jqXHR = jQuery.ajax({
427 url: this.url,
428 data: postData,
429 type: 'POST',
430 cache: false,
henriqueeec445e2015-05-04 21:37:51 +1000431 contentType: 'application/vnd.apache.thrift.json; charset=utf-8',
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200432 dataType: 'text thrift',
433 converters: {
434 'text thrift' : function(responseData) {
435 thriftTransport.setRecvBuffer(responseData);
436 var value = recv_method.call(client);
437 return value;
438 }
439 },
440 context: client,
441 success: jQuery.makeArray(args).pop()
442 });
443
444 return jqXHR;
445 },
446
447 /**
henrique2a7dccc2014-03-07 22:16:51 +0100448 * Sets the buffer to provide the protocol when deserializing.
449 * @param {string} buf - The buffer to supply the protocol.
450 */
451 setRecvBuffer: function(buf) {
452 this.recv_buf = buf;
453 this.recv_buf_sz = this.recv_buf.length;
454 this.wpos = this.recv_buf.length;
455 this.rpos = 0;
456 },
457
458 /**
459 * Returns true if the transport is open, XHR always returns true.
460 * @readonly
461 * @returns {boolean} Always True.
462 */
463 isOpen: function() {
464 return true;
465 },
466
467 /**
468 * Opens the transport connection, with XHR this is a nop.
469 */
470 open: function() {},
471
472 /**
473 * Closes the transport connection, with XHR this is a nop.
474 */
475 close: function() {},
476
477 /**
478 * Returns the specified number of characters from the response
479 * buffer.
480 * @param {number} len - The number of characters to return.
481 * @returns {string} Characters sent by the server.
482 */
483 read: function(len) {
484 var avail = this.wpos - this.rpos;
485
486 if (avail === 0) {
487 return '';
488 }
489
490 var give = len;
491
492 if (avail < len) {
493 give = avail;
494 }
495
496 var ret = this.read_buf.substr(this.rpos, give);
497 this.rpos += give;
498
499 //clear buf when complete?
500 return ret;
501 },
502
503 /**
504 * Returns the entire response buffer.
505 * @returns {string} Characters sent by the server.
506 */
507 readAll: function() {
508 return this.recv_buf;
509 },
510
511 /**
512 * Sets the send buffer to buf.
513 * @param {string} buf - The buffer to send.
514 */
515 write: function(buf) {
516 this.send_buf = buf;
517 },
518
519 /**
520 * Returns the send buffer.
521 * @readonly
522 * @returns {string} The send buffer.
523 */
524 getSendBuffer: function() {
525 return this.send_buf;
526 }
527
528};
529
530
531/**
532 * Constructor Function for the WebSocket transport.
533 * @constructor
534 * @param {string} [url] - The URL to connect to.
535 * @classdesc The Apache Thrift Transport layer performs byte level I/O
536 * between RPC clients and servers. The JavaScript TWebSocketTransport object
537 * uses the WebSocket protocol. Target servers must implement WebSocket.
538 * (see: node.js example server_http.js).
539 * @example
540 * var transport = new Thrift.TWebSocketTransport("http://localhost:8585");
541 */
542Thrift.TWebSocketTransport = function(url) {
543 this.__reset(url);
544};
545
546Thrift.TWebSocketTransport.prototype = {
547 __reset: function(url) {
548 this.url = url; //Where to connect
549 this.socket = null; //The web socket
550 this.callbacks = []; //Pending callbacks
551 this.send_pending = []; //Buffers/Callback pairs waiting to be sent
552 this.send_buf = ''; //Outbound data, immutable until sent
553 this.recv_buf = ''; //Inbound data
554 this.rb_wpos = 0; //Network write position in receive buffer
555 this.rb_rpos = 0; //Client read position in receive buffer
556 },
557
558 /**
559 * Sends the current WS request and registers callback. The async
560 * parameter is ignored (WS flush is always async) and the callback
561 * function parameter is required.
562 * @param {object} async - Ignored.
563 * @param {object} callback - The client completion callback.
564 * @returns {undefined|string} Nothing (undefined)
565 */
566 flush: function(async, callback) {
567 var self = this;
568 if (this.isOpen()) {
569 //Send data and register a callback to invoke the client callback
570 this.socket.send(this.send_buf);
571 this.callbacks.push((function() {
572 var clientCallback = callback;
573 return function(msg) {
574 self.setRecvBuffer(msg);
575 clientCallback();
576 };
577 }()));
578 } else {
579 //Queue the send to go out __onOpen
580 this.send_pending.push({
581 buf: this.send_buf,
582 cb: callback
583 });
584 }
585 },
586
587 __onOpen: function() {
588 var self = this;
589 if (this.send_pending.length > 0) {
590 //If the user made calls before the connection was fully
591 //open, send them now
592 this.send_pending.forEach(function(elem) {
593 this.socket.send(elem.buf);
594 this.callbacks.push((function() {
595 var clientCallback = elem.cb;
596 return function(msg) {
597 self.setRecvBuffer(msg);
598 clientCallback();
599 };
600 }()));
601 });
602 this.send_pending = [];
603 }
604 },
605
606 __onClose: function(evt) {
607 this.__reset(this.url);
608 },
609
610 __onMessage: function(evt) {
611 if (this.callbacks.length) {
612 this.callbacks.shift()(evt.data);
613 }
614 },
615
616 __onError: function(evt) {
617 console.log("Thrift WebSocket Error: " + evt.toString());
618 this.socket.close();
619 },
620
621 /**
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200622 * Sets the buffer to use when receiving server responses.
623 * @param {string} buf - The buffer to receive server responses.
624 */
625 setRecvBuffer: function(buf) {
626 this.recv_buf = buf;
627 this.recv_buf_sz = this.recv_buf.length;
628 this.wpos = this.recv_buf.length;
629 this.rpos = 0;
630 },
631
632 /**
henrique2a7dccc2014-03-07 22:16:51 +0100633 * Returns true if the transport is open
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200634 * @readonly
henrique2a7dccc2014-03-07 22:16:51 +0100635 * @returns {boolean}
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200636 */
637 isOpen: function() {
henrique2a7dccc2014-03-07 22:16:51 +0100638 return this.socket && this.socket.readyState == this.socket.OPEN;
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200639 },
640
641 /**
henrique2a7dccc2014-03-07 22:16:51 +0100642 * Opens the transport connection
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200643 */
henrique2a7dccc2014-03-07 22:16:51 +0100644 open: function() {
645 //If OPEN/CONNECTING/CLOSING ignore additional opens
646 if (this.socket && this.socket.readyState != this.socket.CLOSED) {
647 return;
648 }
649 //If there is no socket or the socket is closed:
650 this.socket = new WebSocket(this.url);
651 this.socket.onopen = this.__onOpen.bind(this);
652 this.socket.onmessage = this.__onMessage.bind(this);
653 this.socket.onerror = this.__onError.bind(this);
654 this.socket.onclose = this.__onClose.bind(this);
655 },
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200656
657 /**
henrique2a7dccc2014-03-07 22:16:51 +0100658 * Closes the transport connection
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200659 */
henrique2a7dccc2014-03-07 22:16:51 +0100660 close: function() {
661 this.socket.close();
662 },
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200663
664 /**
665 * Returns the specified number of characters from the response
666 * buffer.
667 * @param {number} len - The number of characters to return.
668 * @returns {string} Characters sent by the server.
669 */
670 read: function(len) {
671 var avail = this.wpos - this.rpos;
672
673 if (avail === 0) {
674 return '';
675 }
676
677 var give = len;
678
679 if (avail < len) {
680 give = avail;
681 }
682
683 var ret = this.read_buf.substr(this.rpos, give);
684 this.rpos += give;
685
686 //clear buf when complete?
687 return ret;
688 },
689
690 /**
691 * Returns the entire response buffer.
692 * @returns {string} Characters sent by the server.
693 */
694 readAll: function() {
695 return this.recv_buf;
696 },
697
698 /**
699 * Sets the send buffer to buf.
700 * @param {string} buf - The buffer to send.
701 */
702 write: function(buf) {
703 this.send_buf = buf;
704 },
705
706 /**
707 * Returns the send buffer.
708 * @readonly
709 * @returns {string} The send buffer.
710 */
711 getSendBuffer: function() {
712 return this.send_buf;
713 }
714
715};
716
717/**
718 * Initializes a Thrift JSON protocol instance.
719 * @constructor
720 * @param {Thrift.Transport} transport - The transport to serialize to/from.
721 * @classdesc Apache Thrift Protocols perform serialization which enables cross
722 * language RPC. The Protocol type is the JavaScript browser implementation
723 * of the Apache Thrift TJSONProtocol.
724 * @example
725 * var protocol = new Thrift.Protocol(transport);
726 */
Roger Meier52744ee2014-03-12 09:38:42 +0100727Thrift.TJSONProtocol = Thrift.Protocol = function(transport) {
radekg1d305582015-01-01 20:35:01 +0100728 this.tstack = [];
729 this.tpos = [];
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200730 this.transport = transport;
731};
732
733/**
734 * Thrift IDL type Id to string mapping.
735 * @readonly
736 * @see {@link Thrift.Type}
737 */
738Thrift.Protocol.Type = {};
739Thrift.Protocol.Type[Thrift.Type.BOOL] = '"tf"';
740Thrift.Protocol.Type[Thrift.Type.BYTE] = '"i8"';
741Thrift.Protocol.Type[Thrift.Type.I16] = '"i16"';
742Thrift.Protocol.Type[Thrift.Type.I32] = '"i32"';
743Thrift.Protocol.Type[Thrift.Type.I64] = '"i64"';
744Thrift.Protocol.Type[Thrift.Type.DOUBLE] = '"dbl"';
745Thrift.Protocol.Type[Thrift.Type.STRUCT] = '"rec"';
746Thrift.Protocol.Type[Thrift.Type.STRING] = '"str"';
747Thrift.Protocol.Type[Thrift.Type.MAP] = '"map"';
748Thrift.Protocol.Type[Thrift.Type.LIST] = '"lst"';
749Thrift.Protocol.Type[Thrift.Type.SET] = '"set"';
750
751/**
752 * Thrift IDL type string to Id mapping.
753 * @readonly
754 * @see {@link Thrift.Type}
755 */
756Thrift.Protocol.RType = {};
757Thrift.Protocol.RType.tf = Thrift.Type.BOOL;
758Thrift.Protocol.RType.i8 = Thrift.Type.BYTE;
759Thrift.Protocol.RType.i16 = Thrift.Type.I16;
760Thrift.Protocol.RType.i32 = Thrift.Type.I32;
761Thrift.Protocol.RType.i64 = Thrift.Type.I64;
762Thrift.Protocol.RType.dbl = Thrift.Type.DOUBLE;
763Thrift.Protocol.RType.rec = Thrift.Type.STRUCT;
764Thrift.Protocol.RType.str = Thrift.Type.STRING;
765Thrift.Protocol.RType.map = Thrift.Type.MAP;
766Thrift.Protocol.RType.lst = Thrift.Type.LIST;
767Thrift.Protocol.RType.set = Thrift.Type.SET;
768
769/**
770 * The TJSONProtocol version number.
771 * @readonly
772 * @const {number} Version
773 * @memberof Thrift.Protocol
774 */
775 Thrift.Protocol.Version = 1;
776
777Thrift.Protocol.prototype = {
778 /**
779 * Returns the underlying transport.
780 * @readonly
781 * @returns {Thrift.Transport} The underlying transport.
782 */
783 getTransport: function() {
784 return this.transport;
785 },
786
787 /**
788 * Serializes the beginning of a Thrift RPC message.
789 * @param {string} name - The service method to call.
790 * @param {Thrift.MessageType} messageType - The type of method call.
791 * @param {number} seqid - The sequence number of this call (always 0 in Apache Thrift).
792 */
793 writeMessageBegin: function(name, messageType, seqid) {
794 this.tstack = [];
795 this.tpos = [];
796
797 this.tstack.push([Thrift.Protocol.Version, '"' +
798 name + '"', messageType, seqid]);
799 },
800
801 /**
802 * Serializes the end of a Thrift RPC message.
803 */
804 writeMessageEnd: function() {
805 var obj = this.tstack.pop();
806
807 this.wobj = this.tstack.pop();
808 this.wobj.push(obj);
809
810 this.wbuf = '[' + this.wobj.join(',') + ']';
811
812 this.transport.write(this.wbuf);
813 },
814
815
816 /**
817 * Serializes the beginning of a struct.
818 * @param {string} name - The name of the struct.
819 */
820 writeStructBegin: function(name) {
821 this.tpos.push(this.tstack.length);
822 this.tstack.push({});
823 },
824
825 /**
826 * Serializes the end of a struct.
827 */
828 writeStructEnd: function() {
829
830 var p = this.tpos.pop();
831 var struct = this.tstack[p];
832 var str = '{';
833 var first = true;
834 for (var key in struct) {
835 if (first) {
836 first = false;
837 } else {
838 str += ',';
839 }
840
841 str += key + ':' + struct[key];
842 }
843
844 str += '}';
845 this.tstack[p] = str;
846 },
847
848 /**
849 * Serializes the beginning of a struct field.
850 * @param {string} name - The name of the field.
851 * @param {Thrift.Protocol.Type} fieldType - The data type of the field.
852 * @param {number} fieldId - The field's unique identifier.
853 */
854 writeFieldBegin: function(name, fieldType, fieldId) {
855 this.tpos.push(this.tstack.length);
856 this.tstack.push({ 'fieldId': '"' +
857 fieldId + '"', 'fieldType': Thrift.Protocol.Type[fieldType]
858 });
859
860 },
861
862 /**
863 * Serializes the end of a field.
864 */
865 writeFieldEnd: function() {
866 var value = this.tstack.pop();
867 var fieldInfo = this.tstack.pop();
868
869 this.tstack[this.tstack.length - 1][fieldInfo.fieldId] = '{' +
870 fieldInfo.fieldType + ':' + value + '}';
871 this.tpos.pop();
872 },
873
874 /**
875 * Serializes the end of the set of fields for a struct.
876 */
877 writeFieldStop: function() {
878 //na
879 },
880
881 /**
882 * Serializes the beginning of a map collection.
883 * @param {Thrift.Type} keyType - The data type of the key.
884 * @param {Thrift.Type} valType - The data type of the value.
885 * @param {number} [size] - The number of elements in the map (ignored).
886 */
887 writeMapBegin: function(keyType, valType, size) {
888 this.tpos.push(this.tstack.length);
889 this.tstack.push([Thrift.Protocol.Type[keyType],
890 Thrift.Protocol.Type[valType], 0]);
891 },
892
893 /**
894 * Serializes the end of a map.
895 */
896 writeMapEnd: function() {
897 var p = this.tpos.pop();
898
899 if (p == this.tstack.length) {
900 return;
901 }
902
903 if ((this.tstack.length - p - 1) % 2 !== 0) {
904 this.tstack.push('');
905 }
906
907 var size = (this.tstack.length - p - 1) / 2;
908
909 this.tstack[p][this.tstack[p].length - 1] = size;
910
911 var map = '}';
912 var first = true;
913 while (this.tstack.length > p + 1) {
914 var v = this.tstack.pop();
915 var k = this.tstack.pop();
916 if (first) {
917 first = false;
918 } else {
919 map = ',' + map;
920 }
921
922 if (! isNaN(k)) { k = '"' + k + '"'; } //json "keys" need to be strings
923 map = k + ':' + v + map;
924 }
925 map = '{' + map;
926
927 this.tstack[p].push(map);
928 this.tstack[p] = '[' + this.tstack[p].join(',') + ']';
929 },
930
931 /**
932 * Serializes the beginning of a list collection.
933 * @param {Thrift.Type} elemType - The data type of the elements.
934 * @param {number} size - The number of elements in the list.
935 */
936 writeListBegin: function(elemType, size) {
937 this.tpos.push(this.tstack.length);
938 this.tstack.push([Thrift.Protocol.Type[elemType], size]);
939 },
940
941 /**
942 * Serializes the end of a list.
943 */
944 writeListEnd: function() {
945 var p = this.tpos.pop();
946
947 while (this.tstack.length > p + 1) {
948 var tmpVal = this.tstack[p + 1];
949 this.tstack.splice(p + 1, 1);
950 this.tstack[p].push(tmpVal);
951 }
952
953 this.tstack[p] = '[' + this.tstack[p].join(',') + ']';
954 },
955
956 /**
957 * Serializes the beginning of a set collection.
958 * @param {Thrift.Type} elemType - The data type of the elements.
959 * @param {number} size - The number of elements in the list.
960 */
961 writeSetBegin: function(elemType, size) {
962 this.tpos.push(this.tstack.length);
963 this.tstack.push([Thrift.Protocol.Type[elemType], size]);
964 },
965
966 /**
967 * Serializes the end of a set.
968 */
969 writeSetEnd: function() {
970 var p = this.tpos.pop();
971
972 while (this.tstack.length > p + 1) {
973 var tmpVal = this.tstack[p + 1];
974 this.tstack.splice(p + 1, 1);
975 this.tstack[p].push(tmpVal);
976 }
977
978 this.tstack[p] = '[' + this.tstack[p].join(',') + ']';
979 },
980
981 /** Serializes a boolean */
982 writeBool: function(value) {
983 this.tstack.push(value ? 1 : 0);
984 },
985
986 /** Serializes a number */
987 writeByte: function(i8) {
988 this.tstack.push(i8);
989 },
990
991 /** Serializes a number */
992 writeI16: function(i16) {
993 this.tstack.push(i16);
994 },
995
996 /** Serializes a number */
997 writeI32: function(i32) {
998 this.tstack.push(i32);
999 },
1000
1001 /** Serializes a number */
1002 writeI64: function(i64) {
1003 this.tstack.push(i64);
1004 },
1005
1006 /** Serializes a number */
1007 writeDouble: function(dbl) {
1008 this.tstack.push(dbl);
1009 },
1010
1011 /** Serializes a string */
1012 writeString: function(str) {
1013 // We do not encode uri components for wire transfer:
1014 if (str === null) {
1015 this.tstack.push(null);
1016 } else {
1017 // concat may be slower than building a byte buffer
1018 var escapedString = '';
1019 for (var i = 0; i < str.length; i++) {
1020 var ch = str.charAt(i); // a single double quote: "
1021 if (ch === '\"') {
1022 escapedString += '\\\"'; // write out as: \"
Roger Meier52744ee2014-03-12 09:38:42 +01001023 } else if (ch === '\\') { // a single backslash
1024 escapedString += '\\\\'; // write out as double backslash
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001025 } else if (ch === '\b') { // a single backspace: invisible
1026 escapedString += '\\b'; // write out as: \b"
1027 } else if (ch === '\f') { // a single formfeed: invisible
1028 escapedString += '\\f'; // write out as: \f"
1029 } else if (ch === '\n') { // a single newline: invisible
1030 escapedString += '\\n'; // write out as: \n"
1031 } else if (ch === '\r') { // a single return: invisible
1032 escapedString += '\\r'; // write out as: \r"
1033 } else if (ch === '\t') { // a single tab: invisible
1034 escapedString += '\\t'; // write out as: \t"
1035 } else {
1036 escapedString += ch; // Else it need not be escaped
1037 }
1038 }
1039 this.tstack.push('"' + escapedString + '"');
1040 }
1041 },
1042
1043 /** Serializes a string */
Nobuaki Sukegawa6defea52015-11-14 17:36:29 +09001044 writeBinary: function(binary) {
1045 var str = '';
1046 if (typeof binary == 'string') {
1047 str = binary;
1048 } else if (binary instanceof Uint8Array) {
1049 var arr = binary;
1050 for (var i = 0; i < arr.length; ++i) {
1051 str += String.fromCharCode(arr[i]);
1052 }
1053 } else {
1054 throw new TypeError('writeBinary only accepts String or Uint8Array.');
1055 }
1056 this.tstack.push('"' + btoa(str) + '"');
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001057 },
1058
1059 /**
1060 @class
1061 @name AnonReadMessageBeginReturn
1062 @property {string} fname - The name of the service method.
1063 @property {Thrift.MessageType} mtype - The type of message call.
1064 @property {number} rseqid - The sequence number of the message (0 in Thrift RPC).
1065 */
1066 /**
1067 * Deserializes the beginning of a message.
1068 * @returns {AnonReadMessageBeginReturn}
1069 */
1070 readMessageBegin: function() {
1071 this.rstack = [];
1072 this.rpos = [];
1073
Roger Meier52744ee2014-03-12 09:38:42 +01001074 if (typeof JSON !== 'undefined' && typeof JSON.parse === 'function') {
1075 this.robj = JSON.parse(this.transport.readAll());
1076 } else if (typeof jQuery !== 'undefined') {
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001077 this.robj = jQuery.parseJSON(this.transport.readAll());
1078 } else {
1079 this.robj = eval(this.transport.readAll());
1080 }
1081
1082 var r = {};
1083 var version = this.robj.shift();
1084
1085 if (version != Thrift.Protocol.Version) {
1086 throw 'Wrong thrift protocol version: ' + version;
1087 }
1088
1089 r.fname = this.robj.shift();
1090 r.mtype = this.robj.shift();
1091 r.rseqid = this.robj.shift();
1092
1093
1094 //get to the main obj
1095 this.rstack.push(this.robj.shift());
1096
1097 return r;
1098 },
1099
1100 /** Deserializes the end of a message. */
1101 readMessageEnd: function() {
1102 },
1103
1104 /**
1105 * Deserializes the beginning of a struct.
1106 * @param {string} [name] - The name of the struct (ignored)
1107 * @returns {object} - An object with an empty string fname property
1108 */
1109 readStructBegin: function(name) {
1110 var r = {};
1111 r.fname = '';
1112
1113 //incase this is an array of structs
1114 if (this.rstack[this.rstack.length - 1] instanceof Array) {
1115 this.rstack.push(this.rstack[this.rstack.length - 1].shift());
1116 }
1117
1118 return r;
1119 },
1120
1121 /** Deserializes the end of a struct. */
1122 readStructEnd: function() {
1123 if (this.rstack[this.rstack.length - 2] instanceof Array) {
1124 this.rstack.pop();
1125 }
1126 },
1127
1128 /**
1129 @class
1130 @name AnonReadFieldBeginReturn
1131 @property {string} fname - The name of the field (always '').
1132 @property {Thrift.Type} ftype - The data type of the field.
1133 @property {number} fid - The unique identifier of the field.
1134 */
1135 /**
1136 * Deserializes the beginning of a field.
1137 * @returns {AnonReadFieldBeginReturn}
1138 */
1139 readFieldBegin: function() {
1140 var r = {};
1141
1142 var fid = -1;
1143 var ftype = Thrift.Type.STOP;
1144
1145 //get a fieldId
1146 for (var f in (this.rstack[this.rstack.length - 1])) {
1147 if (f === null) {
1148 continue;
1149 }
1150
1151 fid = parseInt(f, 10);
1152 this.rpos.push(this.rstack.length);
1153
1154 var field = this.rstack[this.rstack.length - 1][fid];
1155
1156 //remove so we don't see it again
1157 delete this.rstack[this.rstack.length - 1][fid];
1158
1159 this.rstack.push(field);
1160
1161 break;
1162 }
1163
1164 if (fid != -1) {
1165
1166 //should only be 1 of these but this is the only
1167 //way to match a key
1168 for (var i in (this.rstack[this.rstack.length - 1])) {
1169 if (Thrift.Protocol.RType[i] === null) {
1170 continue;
1171 }
1172
1173 ftype = Thrift.Protocol.RType[i];
1174 this.rstack[this.rstack.length - 1] =
1175 this.rstack[this.rstack.length - 1][i];
1176 }
1177 }
1178
1179 r.fname = '';
1180 r.ftype = ftype;
1181 r.fid = fid;
1182
1183 return r;
1184 },
1185
1186 /** Deserializes the end of a field. */
1187 readFieldEnd: function() {
1188 var pos = this.rpos.pop();
1189
1190 //get back to the right place in the stack
1191 while (this.rstack.length > pos) {
1192 this.rstack.pop();
1193 }
1194
1195 },
1196
1197 /**
1198 @class
1199 @name AnonReadMapBeginReturn
1200 @property {Thrift.Type} ktype - The data type of the key.
1201 @property {Thrift.Type} vtype - The data type of the value.
1202 @property {number} size - The number of elements in the map.
1203 */
1204 /**
1205 * Deserializes the beginning of a map.
1206 * @returns {AnonReadMapBeginReturn}
1207 */
1208 readMapBegin: function() {
1209 var map = this.rstack.pop();
Liangliang He5d6378f2014-08-19 18:25:37 +08001210 var first = map.shift();
1211 if (first instanceof Array) {
1212 this.rstack.push(map);
1213 map = first;
1214 first = map.shift();
1215 }
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001216
1217 var r = {};
Liangliang He5d6378f2014-08-19 18:25:37 +08001218 r.ktype = Thrift.Protocol.RType[first];
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001219 r.vtype = Thrift.Protocol.RType[map.shift()];
1220 r.size = map.shift();
1221
1222
1223 this.rpos.push(this.rstack.length);
1224 this.rstack.push(map.shift());
1225
1226 return r;
1227 },
1228
1229 /** Deserializes the end of a map. */
1230 readMapEnd: function() {
1231 this.readFieldEnd();
1232 },
1233
1234 /**
1235 @class
1236 @name AnonReadColBeginReturn
1237 @property {Thrift.Type} etype - The data type of the element.
1238 @property {number} size - The number of elements in the collection.
1239 */
1240 /**
1241 * Deserializes the beginning of a list.
1242 * @returns {AnonReadColBeginReturn}
1243 */
1244 readListBegin: function() {
1245 var list = this.rstack[this.rstack.length - 1];
1246
1247 var r = {};
1248 r.etype = Thrift.Protocol.RType[list.shift()];
1249 r.size = list.shift();
1250
1251 this.rpos.push(this.rstack.length);
Henrique Mendonça15d90422015-06-25 22:31:41 +10001252 this.rstack.push(list.shift());
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001253
1254 return r;
1255 },
1256
1257 /** Deserializes the end of a list. */
1258 readListEnd: function() {
1259 this.readFieldEnd();
1260 },
1261
1262 /**
1263 * Deserializes the beginning of a set.
1264 * @returns {AnonReadColBeginReturn}
1265 */
1266 readSetBegin: function(elemType, size) {
1267 return this.readListBegin(elemType, size);
1268 },
1269
1270 /** Deserializes the end of a set. */
1271 readSetEnd: function() {
1272 return this.readListEnd();
1273 },
1274
1275 /** Returns an object with a value property set to
1276 * False unless the next number in the protocol buffer
Konrad Grochowski3b5dacb2014-11-24 10:55:31 +01001277 * is 1, in which case the value property is True */
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001278 readBool: function() {
1279 var r = this.readI32();
1280
1281 if (r !== null && r.value == '1') {
1282 r.value = true;
1283 } else {
1284 r.value = false;
1285 }
1286
1287 return r;
1288 },
1289
1290 /** Returns the an object with a value property set to the
1291 next value found in the protocol buffer */
1292 readByte: function() {
1293 return this.readI32();
1294 },
1295
1296 /** Returns the an object with a value property set to the
1297 next value found in the protocol buffer */
1298 readI16: function() {
1299 return this.readI32();
1300 },
1301
1302 /** Returns the an object with a value property set to the
1303 next value found in the protocol buffer */
1304 readI32: function(f) {
1305 if (f === undefined) {
1306 f = this.rstack[this.rstack.length - 1];
1307 }
1308
1309 var r = {};
1310
1311 if (f instanceof Array) {
1312 if (f.length === 0) {
1313 r.value = undefined;
1314 } else {
1315 r.value = f.shift();
1316 }
1317 } else if (f instanceof Object) {
1318 for (var i in f) {
1319 if (i === null) {
1320 continue;
1321 }
1322 this.rstack.push(f[i]);
1323 delete f[i];
1324
1325 r.value = i;
1326 break;
1327 }
1328 } else {
1329 r.value = f;
1330 this.rstack.pop();
1331 }
1332
1333 return r;
1334 },
1335
1336 /** Returns the an object with a value property set to the
1337 next value found in the protocol buffer */
1338 readI64: function() {
1339 return this.readI32();
1340 },
1341
1342 /** Returns the an object with a value property set to the
1343 next value found in the protocol buffer */
1344 readDouble: function() {
1345 return this.readI32();
1346 },
1347
1348 /** Returns the an object with a value property set to the
1349 next value found in the protocol buffer */
1350 readString: function() {
1351 var r = this.readI32();
1352 return r;
1353 },
1354
1355 /** Returns the an object with a value property set to the
1356 next value found in the protocol buffer */
1357 readBinary: function() {
Nobuaki Sukegawa6defea52015-11-14 17:36:29 +09001358 var r = this.readI32();
1359 r.value = atob(r.value);
1360 return r;
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001361 },
1362
1363 /**
Jens Geyer329d59a2014-06-19 22:11:53 +02001364 * Method to arbitrarily skip over data */
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001365 skip: function(type) {
Jens Geyer329d59a2014-06-19 22:11:53 +02001366 var ret, i;
1367 switch (type) {
1368 case Thrift.Type.STOP:
1369 return null;
1370
1371 case Thrift.Type.BOOL:
1372 return this.readBool();
1373
1374 case Thrift.Type.BYTE:
1375 return this.readByte();
1376
1377 case Thrift.Type.I16:
1378 return this.readI16();
1379
1380 case Thrift.Type.I32:
1381 return this.readI32();
1382
1383 case Thrift.Type.I64:
1384 return this.readI64();
1385
1386 case Thrift.Type.DOUBLE:
1387 return this.readDouble();
1388
1389 case Thrift.Type.STRING:
1390 return this.readString();
1391
1392 case Thrift.Type.STRUCT:
1393 this.readStructBegin();
1394 while (true) {
1395 ret = this.readFieldBegin();
1396 if (ret.ftype == Thrift.Type.STOP) {
1397 break;
1398 }
1399 this.skip(ret.ftype);
1400 this.readFieldEnd();
1401 }
1402 this.readStructEnd();
1403 return null;
1404
1405 case Thrift.Type.MAP:
1406 ret = this.readMapBegin();
1407 for (i = 0; i < ret.size; i++) {
1408 if (i > 0) {
1409 if (this.rstack.length > this.rpos[this.rpos.length - 1] + 1) {
1410 this.rstack.pop();
1411 }
1412 }
1413 this.skip(ret.ktype);
1414 this.skip(ret.vtype);
1415 }
1416 this.readMapEnd();
1417 return null;
1418
1419 case Thrift.Type.SET:
1420 ret = this.readSetBegin();
1421 for (i = 0; i < ret.size; i++) {
1422 this.skip(ret.etype);
1423 }
1424 this.readSetEnd();
1425 return null;
1426
1427 case Thrift.Type.LIST:
1428 ret = this.readListBegin();
1429 for (i = 0; i < ret.size; i++) {
1430 this.skip(ret.etype);
1431 }
1432 this.readListEnd();
1433 return null;
1434 }
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001435 }
1436};
henrique5ba91f22013-12-20 21:13:13 +01001437
1438
1439/**
1440 * Initializes a MutilplexProtocol Implementation as a Wrapper for Thrift.Protocol
1441 * @constructor
1442 */
1443Thrift.MultiplexProtocol = function (srvName, trans, strictRead, strictWrite) {
1444 Thrift.Protocol.call(this, trans, strictRead, strictWrite);
1445 this.serviceName = srvName;
1446};
1447Thrift.inherits(Thrift.MultiplexProtocol, Thrift.Protocol, 'multiplexProtocol');
1448
1449/** Override writeMessageBegin method of prototype*/
1450Thrift.MultiplexProtocol.prototype.writeMessageBegin = function (name, type, seqid) {
1451
1452 if (type === Thrift.MessageType.CALL || type === Thrift.MessageType.ONEWAY) {
1453 Thrift.Protocol.prototype.writeMessageBegin.call(this, this.serviceName + ":" + name, type, seqid);
1454 } else {
1455 Thrift.Protocol.prototype.writeMessageBegin.call(this, name, type, seqid);
1456 }
1457};
1458
1459Thrift.Multiplexer = function () {
1460 this.seqid = 0;
1461};
1462
1463/** Instantiates a multiplexed client for a specific service
1464 * @constructor
1465 * @param {String} serviceName - The transport to serialize to/from.
1466 * @param {Thrift.ServiceClient} SCl - The Service Client Class
1467 * @param {Thrift.Transport} transport - Thrift.Transport instance which provides remote host:port
1468 * @example
1469 * var mp = new Thrift.Multiplexer();
1470 * var transport = new Thrift.Transport("http://localhost:9090/foo.thrift");
1471 * var protocol = new Thrift.Protocol(transport);
1472 * var client = mp.createClient('AuthService', AuthServiceClient, transport);
1473*/
1474Thrift.Multiplexer.prototype.createClient = function (serviceName, SCl, transport) {
1475 if (SCl.Client) {
1476 SCl = SCl.Client;
1477 }
1478 var self = this;
1479 SCl.prototype.new_seqid = function () {
1480 self.seqid += 1;
1481 return self.seqid;
1482 };
1483 var client = new SCl(new Thrift.MultiplexProtocol(serviceName, transport));
1484
1485 return client;
1486};
1487
henriquea2de4102014-02-07 14:12:56 +01001488
henrique2a7dccc2014-03-07 22:16:51 +01001489
Henrique Mendonça15d90422015-06-25 22:31:41 +10001490var copyList, copyMap;
1491
1492copyList = function(lst, types) {
1493
1494 if (!lst) {return lst; }
1495
1496 var type;
1497
1498 if (types.shift === undefined) {
1499 type = types;
1500 }
1501 else {
1502 type = types[0];
1503 }
1504 var Type = type;
1505
1506 var len = lst.length, result = [], i, val;
1507 for (i = 0; i < len; i++) {
1508 val = lst[i];
1509 if (type === null) {
1510 result.push(val);
1511 }
1512 else if (type === copyMap || type === copyList) {
1513 result.push(type(val, types.slice(1)));
1514 }
1515 else {
1516 result.push(new Type(val));
1517 }
1518 }
1519 return result;
1520};
1521
1522copyMap = function(obj, types){
1523
1524 if (!obj) {return obj; }
1525
1526 var type;
1527
1528 if (types.shift === undefined) {
1529 type = types;
1530 }
1531 else {
1532 type = types[0];
1533 }
1534 var Type = type;
1535
1536 var result = {}, val;
1537 for(var prop in obj) {
1538 if(obj.hasOwnProperty(prop)) {
1539 val = obj[prop];
1540 if (type === null) {
1541 result[prop] = val;
1542 }
1543 else if (type === copyMap || type === copyList) {
1544 result[prop] = type(val, types.slice(1));
1545 }
1546 else {
1547 result[prop] = new Type(val);
1548 }
1549 }
1550 }
1551 return result;
1552};
1553
1554Thrift.copyMap = copyMap;
1555Thrift.copyList = copyList;