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