blob: c8461625697fe85006bf3bbda1a67924aa8e165e [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);
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200313 this.send_buf = '';
314 this.recv_buf = '';
315};
316
henrique2a7dccc2014-03-07 22:16:51 +0100317Thrift.TXHRTransport.prototype = {
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200318 /**
319 * Gets the browser specific XmlHttpRequest Object.
320 * @returns {object} the browser XHR interface object
321 */
322 getXmlHttpRequestObject: function() {
323 try { return new XMLHttpRequest(); } catch (e1) { }
324 try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch (e2) { }
325 try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch (e3) { }
326
327 throw "Your browser doesn't support XHR.";
328 },
329
330 /**
henrique2a7dccc2014-03-07 22:16:51 +0100331 * Sends the current XRH request if the transport was created with a URL
332 * and the async parameter is false. If the transport was not created with
333 * a URL, or the async parameter is True and no callback is provided, or
334 * the URL is an empty string, the current send buffer is returned.
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200335 * @param {object} async - If true the current send buffer is returned.
henrique2a7dccc2014-03-07 22:16:51 +0100336 * @param {object} callback - Optional async completion callback
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200337 * @returns {undefined|string} Nothing or the current send buffer.
338 * @throws {string} If XHR fails.
339 */
henriquea2de4102014-02-07 14:12:56 +0100340 flush: function(async, callback) {
henrique2a7dccc2014-03-07 22:16:51 +0100341 var self = this;
henriquea2de4102014-02-07 14:12:56 +0100342 if ((async && !callback) || this.url === undefined || this.url === '') {
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200343 return this.send_buf;
344 }
345
346 var xreq = this.getXmlHttpRequestObject();
347
348 if (xreq.overrideMimeType) {
henriqueeec445e2015-05-04 21:37:51 +1000349 xreq.overrideMimeType('application/vnd.apache.thrift.json; charset=utf-8');
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200350 }
351
henriquea2de4102014-02-07 14:12:56 +0100352 if (callback) {
henrique2a7dccc2014-03-07 22:16:51 +0100353 //Ignore XHR callbacks until the data arrives, then call the
354 // client's callback
355 xreq.onreadystatechange =
356 (function() {
357 var clientCallback = callback;
358 return function() {
359 if (this.readyState == 4 && this.status == 200) {
360 self.setRecvBuffer(this.responseText);
361 clientCallback();
362 }
363 };
364 }());
HIRANO Satoshi84cf3632015-12-07 17:17:15 +0900365
366 // detect net::ERR_CONNECTION_REFUSED and call the callback.
367 xreq.onerror =
368 (function() {
369 var clientCallback = callback;
370 return function() {
371 clientCallback();
372 };
373 }());
374
henriquea2de4102014-02-07 14:12:56 +0100375 }
376
377 xreq.open('POST', this.url, !!async);
henriqueeec445e2015-05-04 21:37:51 +1000378
379 if (xreq.setRequestHeader) {
380 xreq.setRequestHeader('Accept', 'application/vnd.apache.thrift.json; charset=utf-8');
381 xreq.setRequestHeader('Content-Type', 'application/vnd.apache.thrift.json; charset=utf-8');
382 }
383
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200384 xreq.send(this.send_buf);
henriquea2de4102014-02-07 14:12:56 +0100385 if (async && callback) {
386 return;
387 }
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200388
389 if (xreq.readyState != 4) {
390 throw 'encountered an unknown ajax ready state: ' + xreq.readyState;
391 }
392
393 if (xreq.status != 200) {
394 throw 'encountered a unknown request status: ' + xreq.status;
395 }
396
397 this.recv_buf = xreq.responseText;
398 this.recv_buf_sz = this.recv_buf.length;
399 this.wpos = this.recv_buf.length;
400 this.rpos = 0;
401 },
402
403 /**
404 * Creates a jQuery XHR object to be used for a Thrift server call.
405 * @param {object} client - The Thrift Service client object generated by the IDL compiler.
406 * @param {object} postData - The message to send to the server.
henrique2a7dccc2014-03-07 22:16:51 +0100407 * @param {function} args - The original call arguments with the success call back at the end.
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200408 * @param {function} recv_method - The Thrift Service Client receive method for the call.
409 * @returns {object} A new jQuery XHR object.
410 * @throws {string} If the jQuery version is prior to 1.5 or if jQuery is not found.
411 */
412 jqRequest: function(client, postData, args, recv_method) {
413 if (typeof jQuery === 'undefined' ||
414 typeof jQuery.Deferred === 'undefined') {
415 throw 'Thrift.js requires jQuery 1.5+ to use asynchronous requests';
416 }
417
418 var thriftTransport = this;
419
420 var jqXHR = jQuery.ajax({
421 url: this.url,
422 data: postData,
423 type: 'POST',
424 cache: false,
henriqueeec445e2015-05-04 21:37:51 +1000425 contentType: 'application/vnd.apache.thrift.json; charset=utf-8',
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200426 dataType: 'text thrift',
427 converters: {
428 'text thrift' : function(responseData) {
429 thriftTransport.setRecvBuffer(responseData);
430 var value = recv_method.call(client);
431 return value;
432 }
433 },
434 context: client,
435 success: jQuery.makeArray(args).pop()
436 });
437
438 return jqXHR;
439 },
440
441 /**
henrique2a7dccc2014-03-07 22:16:51 +0100442 * Sets the buffer to provide the protocol when deserializing.
443 * @param {string} buf - The buffer to supply the protocol.
444 */
445 setRecvBuffer: function(buf) {
446 this.recv_buf = buf;
447 this.recv_buf_sz = this.recv_buf.length;
448 this.wpos = this.recv_buf.length;
449 this.rpos = 0;
450 },
451
452 /**
453 * Returns true if the transport is open, XHR always returns true.
454 * @readonly
455 * @returns {boolean} Always True.
456 */
457 isOpen: function() {
458 return true;
459 },
460
461 /**
462 * Opens the transport connection, with XHR this is a nop.
463 */
464 open: function() {},
465
466 /**
467 * Closes the transport connection, with XHR this is a nop.
468 */
469 close: function() {},
470
471 /**
472 * Returns the specified number of characters from the response
473 * buffer.
474 * @param {number} len - The number of characters to return.
475 * @returns {string} Characters sent by the server.
476 */
477 read: function(len) {
478 var avail = this.wpos - this.rpos;
479
480 if (avail === 0) {
481 return '';
482 }
483
484 var give = len;
485
486 if (avail < len) {
487 give = avail;
488 }
489
490 var ret = this.read_buf.substr(this.rpos, give);
491 this.rpos += give;
492
493 //clear buf when complete?
494 return ret;
495 },
496
497 /**
498 * Returns the entire response buffer.
499 * @returns {string} Characters sent by the server.
500 */
501 readAll: function() {
502 return this.recv_buf;
503 },
504
505 /**
506 * Sets the send buffer to buf.
507 * @param {string} buf - The buffer to send.
508 */
509 write: function(buf) {
510 this.send_buf = buf;
511 },
512
513 /**
514 * Returns the send buffer.
515 * @readonly
516 * @returns {string} The send buffer.
517 */
518 getSendBuffer: function() {
519 return this.send_buf;
520 }
521
522};
523
524
525/**
526 * Constructor Function for the WebSocket transport.
527 * @constructor
528 * @param {string} [url] - The URL to connect to.
529 * @classdesc The Apache Thrift Transport layer performs byte level I/O
530 * between RPC clients and servers. The JavaScript TWebSocketTransport object
531 * uses the WebSocket protocol. Target servers must implement WebSocket.
532 * (see: node.js example server_http.js).
533 * @example
534 * var transport = new Thrift.TWebSocketTransport("http://localhost:8585");
535 */
536Thrift.TWebSocketTransport = function(url) {
537 this.__reset(url);
538};
539
540Thrift.TWebSocketTransport.prototype = {
541 __reset: function(url) {
542 this.url = url; //Where to connect
543 this.socket = null; //The web socket
544 this.callbacks = []; //Pending callbacks
545 this.send_pending = []; //Buffers/Callback pairs waiting to be sent
546 this.send_buf = ''; //Outbound data, immutable until sent
547 this.recv_buf = ''; //Inbound data
548 this.rb_wpos = 0; //Network write position in receive buffer
549 this.rb_rpos = 0; //Client read position in receive buffer
550 },
551
552 /**
553 * Sends the current WS request and registers callback. The async
554 * parameter is ignored (WS flush is always async) and the callback
555 * function parameter is required.
556 * @param {object} async - Ignored.
557 * @param {object} callback - The client completion callback.
558 * @returns {undefined|string} Nothing (undefined)
559 */
560 flush: function(async, callback) {
561 var self = this;
562 if (this.isOpen()) {
563 //Send data and register a callback to invoke the client callback
564 this.socket.send(this.send_buf);
565 this.callbacks.push((function() {
566 var clientCallback = callback;
567 return function(msg) {
568 self.setRecvBuffer(msg);
569 clientCallback();
570 };
571 }()));
572 } else {
573 //Queue the send to go out __onOpen
574 this.send_pending.push({
575 buf: this.send_buf,
576 cb: callback
577 });
578 }
579 },
580
581 __onOpen: function() {
582 var self = this;
583 if (this.send_pending.length > 0) {
584 //If the user made calls before the connection was fully
585 //open, send them now
586 this.send_pending.forEach(function(elem) {
587 this.socket.send(elem.buf);
588 this.callbacks.push((function() {
589 var clientCallback = elem.cb;
590 return function(msg) {
591 self.setRecvBuffer(msg);
592 clientCallback();
593 };
594 }()));
595 });
596 this.send_pending = [];
597 }
598 },
599
600 __onClose: function(evt) {
601 this.__reset(this.url);
602 },
603
604 __onMessage: function(evt) {
605 if (this.callbacks.length) {
606 this.callbacks.shift()(evt.data);
607 }
608 },
609
610 __onError: function(evt) {
611 console.log("Thrift WebSocket Error: " + evt.toString());
612 this.socket.close();
613 },
614
615 /**
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200616 * Sets the buffer to use when receiving server responses.
617 * @param {string} buf - The buffer to receive server responses.
618 */
619 setRecvBuffer: function(buf) {
620 this.recv_buf = buf;
621 this.recv_buf_sz = this.recv_buf.length;
622 this.wpos = this.recv_buf.length;
623 this.rpos = 0;
624 },
625
626 /**
henrique2a7dccc2014-03-07 22:16:51 +0100627 * Returns true if the transport is open
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200628 * @readonly
henrique2a7dccc2014-03-07 22:16:51 +0100629 * @returns {boolean}
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200630 */
631 isOpen: function() {
henrique2a7dccc2014-03-07 22:16:51 +0100632 return this.socket && this.socket.readyState == this.socket.OPEN;
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200633 },
634
635 /**
henrique2a7dccc2014-03-07 22:16:51 +0100636 * Opens the transport connection
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200637 */
henrique2a7dccc2014-03-07 22:16:51 +0100638 open: function() {
639 //If OPEN/CONNECTING/CLOSING ignore additional opens
640 if (this.socket && this.socket.readyState != this.socket.CLOSED) {
641 return;
642 }
643 //If there is no socket or the socket is closed:
644 this.socket = new WebSocket(this.url);
645 this.socket.onopen = this.__onOpen.bind(this);
646 this.socket.onmessage = this.__onMessage.bind(this);
647 this.socket.onerror = this.__onError.bind(this);
648 this.socket.onclose = this.__onClose.bind(this);
649 },
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200650
651 /**
henrique2a7dccc2014-03-07 22:16:51 +0100652 * Closes the transport connection
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200653 */
henrique2a7dccc2014-03-07 22:16:51 +0100654 close: function() {
655 this.socket.close();
656 },
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200657
658 /**
659 * Returns the specified number of characters from the response
660 * buffer.
661 * @param {number} len - The number of characters to return.
662 * @returns {string} Characters sent by the server.
663 */
664 read: function(len) {
665 var avail = this.wpos - this.rpos;
666
667 if (avail === 0) {
668 return '';
669 }
670
671 var give = len;
672
673 if (avail < len) {
674 give = avail;
675 }
676
677 var ret = this.read_buf.substr(this.rpos, give);
678 this.rpos += give;
679
680 //clear buf when complete?
681 return ret;
682 },
683
684 /**
685 * Returns the entire response buffer.
686 * @returns {string} Characters sent by the server.
687 */
688 readAll: function() {
689 return this.recv_buf;
690 },
691
692 /**
693 * Sets the send buffer to buf.
694 * @param {string} buf - The buffer to send.
695 */
696 write: function(buf) {
697 this.send_buf = buf;
698 },
699
700 /**
701 * Returns the send buffer.
702 * @readonly
703 * @returns {string} The send buffer.
704 */
705 getSendBuffer: function() {
706 return this.send_buf;
707 }
708
709};
710
711/**
712 * Initializes a Thrift JSON protocol instance.
713 * @constructor
714 * @param {Thrift.Transport} transport - The transport to serialize to/from.
715 * @classdesc Apache Thrift Protocols perform serialization which enables cross
716 * language RPC. The Protocol type is the JavaScript browser implementation
717 * of the Apache Thrift TJSONProtocol.
718 * @example
719 * var protocol = new Thrift.Protocol(transport);
720 */
Roger Meier52744ee2014-03-12 09:38:42 +0100721Thrift.TJSONProtocol = Thrift.Protocol = function(transport) {
radekg1d305582015-01-01 20:35:01 +0100722 this.tstack = [];
723 this.tpos = [];
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200724 this.transport = transport;
725};
726
727/**
728 * Thrift IDL type Id to string mapping.
729 * @readonly
730 * @see {@link Thrift.Type}
731 */
732Thrift.Protocol.Type = {};
733Thrift.Protocol.Type[Thrift.Type.BOOL] = '"tf"';
734Thrift.Protocol.Type[Thrift.Type.BYTE] = '"i8"';
735Thrift.Protocol.Type[Thrift.Type.I16] = '"i16"';
736Thrift.Protocol.Type[Thrift.Type.I32] = '"i32"';
737Thrift.Protocol.Type[Thrift.Type.I64] = '"i64"';
738Thrift.Protocol.Type[Thrift.Type.DOUBLE] = '"dbl"';
739Thrift.Protocol.Type[Thrift.Type.STRUCT] = '"rec"';
740Thrift.Protocol.Type[Thrift.Type.STRING] = '"str"';
741Thrift.Protocol.Type[Thrift.Type.MAP] = '"map"';
742Thrift.Protocol.Type[Thrift.Type.LIST] = '"lst"';
743Thrift.Protocol.Type[Thrift.Type.SET] = '"set"';
744
745/**
746 * Thrift IDL type string to Id mapping.
747 * @readonly
748 * @see {@link Thrift.Type}
749 */
750Thrift.Protocol.RType = {};
751Thrift.Protocol.RType.tf = Thrift.Type.BOOL;
752Thrift.Protocol.RType.i8 = Thrift.Type.BYTE;
753Thrift.Protocol.RType.i16 = Thrift.Type.I16;
754Thrift.Protocol.RType.i32 = Thrift.Type.I32;
755Thrift.Protocol.RType.i64 = Thrift.Type.I64;
756Thrift.Protocol.RType.dbl = Thrift.Type.DOUBLE;
757Thrift.Protocol.RType.rec = Thrift.Type.STRUCT;
758Thrift.Protocol.RType.str = Thrift.Type.STRING;
759Thrift.Protocol.RType.map = Thrift.Type.MAP;
760Thrift.Protocol.RType.lst = Thrift.Type.LIST;
761Thrift.Protocol.RType.set = Thrift.Type.SET;
762
763/**
764 * The TJSONProtocol version number.
765 * @readonly
766 * @const {number} Version
767 * @memberof Thrift.Protocol
768 */
769 Thrift.Protocol.Version = 1;
770
771Thrift.Protocol.prototype = {
772 /**
773 * Returns the underlying transport.
774 * @readonly
775 * @returns {Thrift.Transport} The underlying transport.
776 */
777 getTransport: function() {
778 return this.transport;
779 },
780
781 /**
782 * Serializes the beginning of a Thrift RPC message.
783 * @param {string} name - The service method to call.
784 * @param {Thrift.MessageType} messageType - The type of method call.
785 * @param {number} seqid - The sequence number of this call (always 0 in Apache Thrift).
786 */
787 writeMessageBegin: function(name, messageType, seqid) {
788 this.tstack = [];
789 this.tpos = [];
790
791 this.tstack.push([Thrift.Protocol.Version, '"' +
792 name + '"', messageType, seqid]);
793 },
794
795 /**
796 * Serializes the end of a Thrift RPC message.
797 */
798 writeMessageEnd: function() {
799 var obj = this.tstack.pop();
800
801 this.wobj = this.tstack.pop();
802 this.wobj.push(obj);
803
804 this.wbuf = '[' + this.wobj.join(',') + ']';
805
806 this.transport.write(this.wbuf);
807 },
808
809
810 /**
811 * Serializes the beginning of a struct.
812 * @param {string} name - The name of the struct.
813 */
814 writeStructBegin: function(name) {
815 this.tpos.push(this.tstack.length);
816 this.tstack.push({});
817 },
818
819 /**
820 * Serializes the end of a struct.
821 */
822 writeStructEnd: function() {
823
824 var p = this.tpos.pop();
825 var struct = this.tstack[p];
826 var str = '{';
827 var first = true;
828 for (var key in struct) {
829 if (first) {
830 first = false;
831 } else {
832 str += ',';
833 }
834
835 str += key + ':' + struct[key];
836 }
837
838 str += '}';
839 this.tstack[p] = str;
840 },
841
842 /**
843 * Serializes the beginning of a struct field.
844 * @param {string} name - The name of the field.
845 * @param {Thrift.Protocol.Type} fieldType - The data type of the field.
846 * @param {number} fieldId - The field's unique identifier.
847 */
848 writeFieldBegin: function(name, fieldType, fieldId) {
849 this.tpos.push(this.tstack.length);
850 this.tstack.push({ 'fieldId': '"' +
851 fieldId + '"', 'fieldType': Thrift.Protocol.Type[fieldType]
852 });
853
854 },
855
856 /**
857 * Serializes the end of a field.
858 */
859 writeFieldEnd: function() {
860 var value = this.tstack.pop();
861 var fieldInfo = this.tstack.pop();
862
863 this.tstack[this.tstack.length - 1][fieldInfo.fieldId] = '{' +
864 fieldInfo.fieldType + ':' + value + '}';
865 this.tpos.pop();
866 },
867
868 /**
869 * Serializes the end of the set of fields for a struct.
870 */
871 writeFieldStop: function() {
872 //na
873 },
874
875 /**
876 * Serializes the beginning of a map collection.
877 * @param {Thrift.Type} keyType - The data type of the key.
878 * @param {Thrift.Type} valType - The data type of the value.
879 * @param {number} [size] - The number of elements in the map (ignored).
880 */
881 writeMapBegin: function(keyType, valType, size) {
882 this.tpos.push(this.tstack.length);
883 this.tstack.push([Thrift.Protocol.Type[keyType],
884 Thrift.Protocol.Type[valType], 0]);
885 },
886
887 /**
888 * Serializes the end of a map.
889 */
890 writeMapEnd: function() {
891 var p = this.tpos.pop();
892
893 if (p == this.tstack.length) {
894 return;
895 }
896
897 if ((this.tstack.length - p - 1) % 2 !== 0) {
898 this.tstack.push('');
899 }
900
901 var size = (this.tstack.length - p - 1) / 2;
902
903 this.tstack[p][this.tstack[p].length - 1] = size;
904
905 var map = '}';
906 var first = true;
907 while (this.tstack.length > p + 1) {
908 var v = this.tstack.pop();
909 var k = this.tstack.pop();
910 if (first) {
911 first = false;
912 } else {
913 map = ',' + map;
914 }
915
916 if (! isNaN(k)) { k = '"' + k + '"'; } //json "keys" need to be strings
917 map = k + ':' + v + map;
918 }
919 map = '{' + map;
920
921 this.tstack[p].push(map);
922 this.tstack[p] = '[' + this.tstack[p].join(',') + ']';
923 },
924
925 /**
926 * Serializes the beginning of a list collection.
927 * @param {Thrift.Type} elemType - The data type of the elements.
928 * @param {number} size - The number of elements in the list.
929 */
930 writeListBegin: function(elemType, size) {
931 this.tpos.push(this.tstack.length);
932 this.tstack.push([Thrift.Protocol.Type[elemType], size]);
933 },
934
935 /**
936 * Serializes the end of a list.
937 */
938 writeListEnd: function() {
939 var p = this.tpos.pop();
940
941 while (this.tstack.length > p + 1) {
942 var tmpVal = this.tstack[p + 1];
943 this.tstack.splice(p + 1, 1);
944 this.tstack[p].push(tmpVal);
945 }
946
947 this.tstack[p] = '[' + this.tstack[p].join(',') + ']';
948 },
949
950 /**
951 * Serializes the beginning of a set collection.
952 * @param {Thrift.Type} elemType - The data type of the elements.
953 * @param {number} size - The number of elements in the list.
954 */
955 writeSetBegin: function(elemType, size) {
956 this.tpos.push(this.tstack.length);
957 this.tstack.push([Thrift.Protocol.Type[elemType], size]);
958 },
959
960 /**
961 * Serializes the end of a set.
962 */
963 writeSetEnd: function() {
964 var p = this.tpos.pop();
965
966 while (this.tstack.length > p + 1) {
967 var tmpVal = this.tstack[p + 1];
968 this.tstack.splice(p + 1, 1);
969 this.tstack[p].push(tmpVal);
970 }
971
972 this.tstack[p] = '[' + this.tstack[p].join(',') + ']';
973 },
974
975 /** Serializes a boolean */
976 writeBool: function(value) {
977 this.tstack.push(value ? 1 : 0);
978 },
979
980 /** Serializes a number */
981 writeByte: function(i8) {
982 this.tstack.push(i8);
983 },
984
985 /** Serializes a number */
986 writeI16: function(i16) {
987 this.tstack.push(i16);
988 },
989
990 /** Serializes a number */
991 writeI32: function(i32) {
992 this.tstack.push(i32);
993 },
994
995 /** Serializes a number */
996 writeI64: function(i64) {
997 this.tstack.push(i64);
998 },
999
1000 /** Serializes a number */
1001 writeDouble: function(dbl) {
1002 this.tstack.push(dbl);
1003 },
1004
1005 /** Serializes a string */
1006 writeString: function(str) {
1007 // We do not encode uri components for wire transfer:
1008 if (str === null) {
1009 this.tstack.push(null);
1010 } else {
1011 // concat may be slower than building a byte buffer
1012 var escapedString = '';
1013 for (var i = 0; i < str.length; i++) {
1014 var ch = str.charAt(i); // a single double quote: "
1015 if (ch === '\"') {
1016 escapedString += '\\\"'; // write out as: \"
Roger Meier52744ee2014-03-12 09:38:42 +01001017 } else if (ch === '\\') { // a single backslash
1018 escapedString += '\\\\'; // write out as double backslash
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001019 } else if (ch === '\b') { // a single backspace: invisible
1020 escapedString += '\\b'; // write out as: \b"
1021 } else if (ch === '\f') { // a single formfeed: invisible
1022 escapedString += '\\f'; // write out as: \f"
1023 } else if (ch === '\n') { // a single newline: invisible
1024 escapedString += '\\n'; // write out as: \n"
1025 } else if (ch === '\r') { // a single return: invisible
1026 escapedString += '\\r'; // write out as: \r"
1027 } else if (ch === '\t') { // a single tab: invisible
1028 escapedString += '\\t'; // write out as: \t"
1029 } else {
1030 escapedString += ch; // Else it need not be escaped
1031 }
1032 }
1033 this.tstack.push('"' + escapedString + '"');
1034 }
1035 },
1036
1037 /** Serializes a string */
Nobuaki Sukegawa6defea52015-11-14 17:36:29 +09001038 writeBinary: function(binary) {
1039 var str = '';
1040 if (typeof binary == 'string') {
1041 str = binary;
1042 } else if (binary instanceof Uint8Array) {
1043 var arr = binary;
1044 for (var i = 0; i < arr.length; ++i) {
1045 str += String.fromCharCode(arr[i]);
1046 }
1047 } else {
1048 throw new TypeError('writeBinary only accepts String or Uint8Array.');
1049 }
1050 this.tstack.push('"' + btoa(str) + '"');
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001051 },
1052
1053 /**
1054 @class
1055 @name AnonReadMessageBeginReturn
1056 @property {string} fname - The name of the service method.
1057 @property {Thrift.MessageType} mtype - The type of message call.
1058 @property {number} rseqid - The sequence number of the message (0 in Thrift RPC).
1059 */
1060 /**
1061 * Deserializes the beginning of a message.
1062 * @returns {AnonReadMessageBeginReturn}
1063 */
1064 readMessageBegin: function() {
1065 this.rstack = [];
1066 this.rpos = [];
1067
Roger Meier52744ee2014-03-12 09:38:42 +01001068 if (typeof JSON !== 'undefined' && typeof JSON.parse === 'function') {
1069 this.robj = JSON.parse(this.transport.readAll());
1070 } else if (typeof jQuery !== 'undefined') {
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001071 this.robj = jQuery.parseJSON(this.transport.readAll());
1072 } else {
1073 this.robj = eval(this.transport.readAll());
1074 }
1075
1076 var r = {};
1077 var version = this.robj.shift();
1078
1079 if (version != Thrift.Protocol.Version) {
1080 throw 'Wrong thrift protocol version: ' + version;
1081 }
1082
1083 r.fname = this.robj.shift();
1084 r.mtype = this.robj.shift();
1085 r.rseqid = this.robj.shift();
1086
1087
1088 //get to the main obj
1089 this.rstack.push(this.robj.shift());
1090
1091 return r;
1092 },
1093
1094 /** Deserializes the end of a message. */
1095 readMessageEnd: function() {
1096 },
1097
1098 /**
1099 * Deserializes the beginning of a struct.
1100 * @param {string} [name] - The name of the struct (ignored)
1101 * @returns {object} - An object with an empty string fname property
1102 */
1103 readStructBegin: function(name) {
1104 var r = {};
1105 r.fname = '';
1106
1107 //incase this is an array of structs
1108 if (this.rstack[this.rstack.length - 1] instanceof Array) {
1109 this.rstack.push(this.rstack[this.rstack.length - 1].shift());
1110 }
1111
1112 return r;
1113 },
1114
1115 /** Deserializes the end of a struct. */
1116 readStructEnd: function() {
1117 if (this.rstack[this.rstack.length - 2] instanceof Array) {
1118 this.rstack.pop();
1119 }
1120 },
1121
1122 /**
1123 @class
1124 @name AnonReadFieldBeginReturn
1125 @property {string} fname - The name of the field (always '').
1126 @property {Thrift.Type} ftype - The data type of the field.
1127 @property {number} fid - The unique identifier of the field.
1128 */
1129 /**
1130 * Deserializes the beginning of a field.
1131 * @returns {AnonReadFieldBeginReturn}
1132 */
1133 readFieldBegin: function() {
1134 var r = {};
1135
1136 var fid = -1;
1137 var ftype = Thrift.Type.STOP;
1138
1139 //get a fieldId
1140 for (var f in (this.rstack[this.rstack.length - 1])) {
1141 if (f === null) {
1142 continue;
1143 }
1144
1145 fid = parseInt(f, 10);
1146 this.rpos.push(this.rstack.length);
1147
1148 var field = this.rstack[this.rstack.length - 1][fid];
1149
1150 //remove so we don't see it again
1151 delete this.rstack[this.rstack.length - 1][fid];
1152
1153 this.rstack.push(field);
1154
1155 break;
1156 }
1157
1158 if (fid != -1) {
1159
1160 //should only be 1 of these but this is the only
1161 //way to match a key
1162 for (var i in (this.rstack[this.rstack.length - 1])) {
1163 if (Thrift.Protocol.RType[i] === null) {
1164 continue;
1165 }
1166
1167 ftype = Thrift.Protocol.RType[i];
1168 this.rstack[this.rstack.length - 1] =
1169 this.rstack[this.rstack.length - 1][i];
1170 }
1171 }
1172
1173 r.fname = '';
1174 r.ftype = ftype;
1175 r.fid = fid;
1176
1177 return r;
1178 },
1179
1180 /** Deserializes the end of a field. */
1181 readFieldEnd: function() {
1182 var pos = this.rpos.pop();
1183
1184 //get back to the right place in the stack
1185 while (this.rstack.length > pos) {
1186 this.rstack.pop();
1187 }
1188
1189 },
1190
1191 /**
1192 @class
1193 @name AnonReadMapBeginReturn
1194 @property {Thrift.Type} ktype - The data type of the key.
1195 @property {Thrift.Type} vtype - The data type of the value.
1196 @property {number} size - The number of elements in the map.
1197 */
1198 /**
1199 * Deserializes the beginning of a map.
1200 * @returns {AnonReadMapBeginReturn}
1201 */
1202 readMapBegin: function() {
1203 var map = this.rstack.pop();
Liangliang He5d6378f2014-08-19 18:25:37 +08001204 var first = map.shift();
1205 if (first instanceof Array) {
1206 this.rstack.push(map);
1207 map = first;
1208 first = map.shift();
1209 }
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001210
1211 var r = {};
Liangliang He5d6378f2014-08-19 18:25:37 +08001212 r.ktype = Thrift.Protocol.RType[first];
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001213 r.vtype = Thrift.Protocol.RType[map.shift()];
1214 r.size = map.shift();
1215
1216
1217 this.rpos.push(this.rstack.length);
1218 this.rstack.push(map.shift());
1219
1220 return r;
1221 },
1222
1223 /** Deserializes the end of a map. */
1224 readMapEnd: function() {
1225 this.readFieldEnd();
1226 },
1227
1228 /**
1229 @class
1230 @name AnonReadColBeginReturn
1231 @property {Thrift.Type} etype - The data type of the element.
1232 @property {number} size - The number of elements in the collection.
1233 */
1234 /**
1235 * Deserializes the beginning of a list.
1236 * @returns {AnonReadColBeginReturn}
1237 */
1238 readListBegin: function() {
1239 var list = this.rstack[this.rstack.length - 1];
1240
1241 var r = {};
1242 r.etype = Thrift.Protocol.RType[list.shift()];
1243 r.size = list.shift();
1244
1245 this.rpos.push(this.rstack.length);
Henrique Mendonça15d90422015-06-25 22:31:41 +10001246 this.rstack.push(list.shift());
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001247
1248 return r;
1249 },
1250
1251 /** Deserializes the end of a list. */
1252 readListEnd: function() {
1253 this.readFieldEnd();
1254 },
1255
1256 /**
1257 * Deserializes the beginning of a set.
1258 * @returns {AnonReadColBeginReturn}
1259 */
1260 readSetBegin: function(elemType, size) {
1261 return this.readListBegin(elemType, size);
1262 },
1263
1264 /** Deserializes the end of a set. */
1265 readSetEnd: function() {
1266 return this.readListEnd();
1267 },
1268
1269 /** Returns an object with a value property set to
1270 * False unless the next number in the protocol buffer
Konrad Grochowski3b5dacb2014-11-24 10:55:31 +01001271 * is 1, in which case the value property is True */
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001272 readBool: function() {
1273 var r = this.readI32();
1274
1275 if (r !== null && r.value == '1') {
1276 r.value = true;
1277 } else {
1278 r.value = false;
1279 }
1280
1281 return r;
1282 },
1283
1284 /** Returns the an object with a value property set to the
1285 next value found in the protocol buffer */
1286 readByte: function() {
1287 return this.readI32();
1288 },
1289
1290 /** Returns the an object with a value property set to the
1291 next value found in the protocol buffer */
1292 readI16: 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 readI32: function(f) {
1299 if (f === undefined) {
1300 f = this.rstack[this.rstack.length - 1];
1301 }
1302
1303 var r = {};
1304
1305 if (f instanceof Array) {
1306 if (f.length === 0) {
1307 r.value = undefined;
1308 } else {
1309 r.value = f.shift();
1310 }
1311 } else if (f instanceof Object) {
1312 for (var i in f) {
1313 if (i === null) {
1314 continue;
1315 }
1316 this.rstack.push(f[i]);
1317 delete f[i];
1318
1319 r.value = i;
1320 break;
1321 }
1322 } else {
1323 r.value = f;
1324 this.rstack.pop();
1325 }
1326
1327 return r;
1328 },
1329
1330 /** Returns the an object with a value property set to the
1331 next value found in the protocol buffer */
1332 readI64: function() {
1333 return this.readI32();
1334 },
1335
1336 /** Returns the an object with a value property set to the
1337 next value found in the protocol buffer */
1338 readDouble: 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 readString: function() {
1345 var r = this.readI32();
1346 return r;
1347 },
1348
1349 /** Returns the an object with a value property set to the
1350 next value found in the protocol buffer */
1351 readBinary: function() {
Nobuaki Sukegawa6defea52015-11-14 17:36:29 +09001352 var r = this.readI32();
1353 r.value = atob(r.value);
1354 return r;
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001355 },
1356
1357 /**
Jens Geyer329d59a2014-06-19 22:11:53 +02001358 * Method to arbitrarily skip over data */
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001359 skip: function(type) {
Jens Geyer329d59a2014-06-19 22:11:53 +02001360 var ret, i;
1361 switch (type) {
1362 case Thrift.Type.STOP:
1363 return null;
1364
1365 case Thrift.Type.BOOL:
1366 return this.readBool();
1367
1368 case Thrift.Type.BYTE:
1369 return this.readByte();
1370
1371 case Thrift.Type.I16:
1372 return this.readI16();
1373
1374 case Thrift.Type.I32:
1375 return this.readI32();
1376
1377 case Thrift.Type.I64:
1378 return this.readI64();
1379
1380 case Thrift.Type.DOUBLE:
1381 return this.readDouble();
1382
1383 case Thrift.Type.STRING:
1384 return this.readString();
1385
1386 case Thrift.Type.STRUCT:
1387 this.readStructBegin();
1388 while (true) {
1389 ret = this.readFieldBegin();
1390 if (ret.ftype == Thrift.Type.STOP) {
1391 break;
1392 }
1393 this.skip(ret.ftype);
1394 this.readFieldEnd();
1395 }
1396 this.readStructEnd();
1397 return null;
1398
1399 case Thrift.Type.MAP:
1400 ret = this.readMapBegin();
1401 for (i = 0; i < ret.size; i++) {
1402 if (i > 0) {
1403 if (this.rstack.length > this.rpos[this.rpos.length - 1] + 1) {
1404 this.rstack.pop();
1405 }
1406 }
1407 this.skip(ret.ktype);
1408 this.skip(ret.vtype);
1409 }
1410 this.readMapEnd();
1411 return null;
1412
1413 case Thrift.Type.SET:
1414 ret = this.readSetBegin();
1415 for (i = 0; i < ret.size; i++) {
1416 this.skip(ret.etype);
1417 }
1418 this.readSetEnd();
1419 return null;
1420
1421 case Thrift.Type.LIST:
1422 ret = this.readListBegin();
1423 for (i = 0; i < ret.size; i++) {
1424 this.skip(ret.etype);
1425 }
1426 this.readListEnd();
1427 return null;
1428 }
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001429 }
1430};
henrique5ba91f22013-12-20 21:13:13 +01001431
1432
1433/**
1434 * Initializes a MutilplexProtocol Implementation as a Wrapper for Thrift.Protocol
1435 * @constructor
1436 */
1437Thrift.MultiplexProtocol = function (srvName, trans, strictRead, strictWrite) {
1438 Thrift.Protocol.call(this, trans, strictRead, strictWrite);
1439 this.serviceName = srvName;
1440};
1441Thrift.inherits(Thrift.MultiplexProtocol, Thrift.Protocol, 'multiplexProtocol');
1442
1443/** Override writeMessageBegin method of prototype*/
1444Thrift.MultiplexProtocol.prototype.writeMessageBegin = function (name, type, seqid) {
1445
1446 if (type === Thrift.MessageType.CALL || type === Thrift.MessageType.ONEWAY) {
1447 Thrift.Protocol.prototype.writeMessageBegin.call(this, this.serviceName + ":" + name, type, seqid);
1448 } else {
1449 Thrift.Protocol.prototype.writeMessageBegin.call(this, name, type, seqid);
1450 }
1451};
1452
1453Thrift.Multiplexer = function () {
1454 this.seqid = 0;
1455};
1456
1457/** Instantiates a multiplexed client for a specific service
1458 * @constructor
1459 * @param {String} serviceName - The transport to serialize to/from.
1460 * @param {Thrift.ServiceClient} SCl - The Service Client Class
1461 * @param {Thrift.Transport} transport - Thrift.Transport instance which provides remote host:port
1462 * @example
1463 * var mp = new Thrift.Multiplexer();
1464 * var transport = new Thrift.Transport("http://localhost:9090/foo.thrift");
1465 * var protocol = new Thrift.Protocol(transport);
1466 * var client = mp.createClient('AuthService', AuthServiceClient, transport);
1467*/
1468Thrift.Multiplexer.prototype.createClient = function (serviceName, SCl, transport) {
1469 if (SCl.Client) {
1470 SCl = SCl.Client;
1471 }
1472 var self = this;
1473 SCl.prototype.new_seqid = function () {
1474 self.seqid += 1;
1475 return self.seqid;
1476 };
1477 var client = new SCl(new Thrift.MultiplexProtocol(serviceName, transport));
1478
1479 return client;
1480};
1481
henriquea2de4102014-02-07 14:12:56 +01001482
henrique2a7dccc2014-03-07 22:16:51 +01001483
Henrique Mendonça15d90422015-06-25 22:31:41 +10001484var copyList, copyMap;
1485
1486copyList = function(lst, types) {
1487
1488 if (!lst) {return lst; }
1489
1490 var type;
1491
1492 if (types.shift === undefined) {
1493 type = types;
1494 }
1495 else {
1496 type = types[0];
1497 }
1498 var Type = type;
1499
1500 var len = lst.length, result = [], i, val;
1501 for (i = 0; i < len; i++) {
1502 val = lst[i];
1503 if (type === null) {
1504 result.push(val);
1505 }
1506 else if (type === copyMap || type === copyList) {
1507 result.push(type(val, types.slice(1)));
1508 }
1509 else {
1510 result.push(new Type(val));
1511 }
1512 }
1513 return result;
1514};
1515
1516copyMap = function(obj, types){
1517
1518 if (!obj) {return obj; }
1519
1520 var type;
1521
1522 if (types.shift === undefined) {
1523 type = types;
1524 }
1525 else {
1526 type = types[0];
1527 }
1528 var Type = type;
1529
1530 var result = {}, val;
1531 for(var prop in obj) {
1532 if(obj.hasOwnProperty(prop)) {
1533 val = obj[prop];
1534 if (type === null) {
1535 result[prop] = val;
1536 }
1537 else if (type === copyMap || type === copyList) {
1538 result[prop] = type(val, types.slice(1));
1539 }
1540 else {
1541 result[prop] = new Type(val);
1542 }
1543 }
1544 }
1545 return result;
1546};
1547
1548Thrift.copyMap = copyMap;
1549Thrift.copyList = copyList;