-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathencoder.js
More file actions
587 lines (506 loc) · 13.3 KB
/
encoder.js
File metadata and controls
587 lines (506 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
/**!
* hessian.js - lib/encoder.js
* Copyright(c) 2014
* MIT Licensed
*
* Authors:
* dead_horse <dead_horse@qq.com> (http://deadhorse.me)
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
*/
'use strict';
var ByteBuffer = require('byte');
var debug = require('debug')('hessian:v1:encoder');
var utils = require('../utils');
var javaObject = require('../object');
var is = require('is-type-of');
var SUPPORT_ES6_MAP = typeof Map === 'function' && typeof Map.prototype.forEach === 'function';
function Encoder(options) {
options = options || {};
//array of buffer
this.byteBuffer = new ByteBuffer({
size: options.size
});
this.objects = [];
}
var proto = Encoder.prototype;
proto._assertType = function (method, expectType, val, desc) {
var valType = typeof val;
if (!is[expectType](val)) {
var msg = 'hessian ' + method +
' expect input type is `' + expectType + '`, but got `' + valType + '`' + ' : ' + JSON.stringify(val) + ' ' + (desc || '');
throw new TypeError(msg);
}
};
/**
* get the encode buffer
* @return {Buffer}
*/
proto.get = function () {
return this.byteBuffer.array();
};
/**
* clean the buf
*/
proto.reset = proto.clean = function () {
this.byteBuffer.reset();
this.objects = [];
return this;
};
/**
* encode null
* : N
*/
proto.writeNull = function () {
this.byteBuffer.putChar('N');
return this;
};
/**
* encode bool
* : T
* : F
*/
proto.writeBool = function (val) {
this.byteBuffer.putChar(val ? 'T' : 'F');
return this;
};
/**
* encode int
* : I 0x00 0x00 0x00 0x10
*/
proto.writeInt = function (val) {
this._assertType('writeInt', 'int32', val);
this.byteBuffer
.putChar('I')
.putInt(val);
return this;
};
/**
* encode long
* warning: we won't check if the long value is out of bound, be careful!
* : L 0x00 0x00 0x00 0x00 0x10 0x32 0x33 0x12
*/
proto.writeLong = function (val) {
this.byteBuffer
.putChar('L')
.putLong(val);
return this;
};
/**
* encode double
* : D 0x00 0x00 0x00 0x00 0x10 0x32 0x33 0x12
*/
proto.writeDouble = function (val) {
this._assertType('writeDouble', 'number', val);
this.byteBuffer
.putChar('D')
.putDouble(val);
return this;
};
/**
* encode date
* 1.0: http://hessian.caucho.com/doc/hessian-1.0-spec.xtp#date
* : d 0x00 0x00 0x00 0x00 0x10 0x32 0x33 0x12
*/
proto.writeDate = function (milliEpoch) {
if (milliEpoch instanceof Date) {
milliEpoch = milliEpoch.getTime();
}
this._assertType('writeDate', 'number', milliEpoch);
this.byteBuffer
.putChar('d')
.putLong(milliEpoch);
return this;
};
/**
* encode buffer
* : b 0x80 0x00 [...]
* B 0x00 0x03 [0x01 0x02 0x03]
*/
proto.writeBytes = function (buf) {
this._assertType('writeBytes', 'buffer', buf);
var offset = 0;
while (buf.length - offset > utils.MAX_BYTE_TRUNK_SIZE) {
this.byteBuffer
.putChar('b')
.putUInt16(utils.MAX_BYTE_TRUNK_SIZE)
.put(buf.slice(offset, offset + utils.MAX_BYTE_TRUNK_SIZE));
offset += utils.MAX_BYTE_TRUNK_SIZE;
}
this.byteBuffer
.putChar('B')
.putUInt16(buf.length - offset)
.put(buf.slice(offset));
return this;
};
/**
* encode string
* : s 0x80 0x00 [...]
* S 0x00 0x03 [0x01 0x02 0x03]
*/
proto.writeString = function (str) {
this._assertType('writeString', 'string', str);
var offset = 0;
var length = str.length;
var strOffset = 0;
while (length > 0x8000) {
var sublen = 0x8000;
// chunk can't end in high surrogate
var tail = str.charCodeAt(strOffset + sublen - 1);
if (0xd800 <= tail && tail <= 0xdbff) {
debug('writeString got tail: 0x%s', tail.toString(16));
sublen--;
}
this.byteBuffer
.put(0x73) // 's'
.putUInt16(sublen)
.putRawString(str.slice(strOffset, strOffset + sublen));
length -= sublen;
strOffset += sublen;
debug('writeString strOffset: %s, length: %s, sublen: %s', strOffset, length, sublen);
}
debug('writeString left length: %s', length);
this.byteBuffer
.put(0x53) // 'S'
.putUInt16(length)
.putRawString(str.slice(strOffset));
return this;
};
var _typecache = {};
/**
* encode type
* v1.0
* ```
* type ::= 0x74(t) type-string-length(putUInt16) type-string(putRawString)
* ```
*/
proto.writeType = function (type) {
type = type || '';
if (_typecache[type]) {
this.byteBuffer.put(_typecache[type]);
return this;
}
var start = this.byteBuffer.position();
this.byteBuffer
.put(0x74)
.putUInt16(type.length)
.putRawString(type);
var end = this.byteBuffer.position();
_typecache[type] = this.byteBuffer.copy(start, end);
return this;
};
/**
* encode ref
* v1.0
* ```
* ref ::= R(0x52) int(putInt)
* ```
*/
proto.writeRef = function (refId) {
this.byteBuffer
.putChar('R')
.putInt(refId);
return this;
};
proto._checkRef = function (obj) {
var refIndex = this.objects.indexOf(obj);
if (refIndex >= 0) {
// already have this object
// just write ref
debug('writeObject with a refIndex: %d', refIndex);
this.writeRef(refIndex);
return true;
}
// a new comming object
this.objects.push(obj);
return false;
};
/**
* A sparse array
*
* @param {Object} obj simple obj
* @return {this}
*/
proto._writeHashMap = function (obj) {
debug('_writeHashMap() %j, fields: %j', obj);
// Real code in java impl:
// http://grepcode.com/file/repo1.maven.org/maven2/com.caucho/hessian/3.1.3/com/caucho/hessian/io/Hessian2Output.java#Hessian2Output.writeMapBegin%28java.lang.String%29
// M(0x4d) type(writeType) (<key> <value>) z(0x7a)
this.byteBuffer.put(0x4d);
// hashmap's type is null
this.writeType('');
if (SUPPORT_ES6_MAP && obj instanceof Map) {
obj.forEach(function (value, key) {
this.write(key);
this.write(value);
}, this);
} else {
// hash map must sort keys
var keys = Object.keys(obj).sort();
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
this.writeString(k);
this.write(obj[k]);
}
}
this.byteBuffer.put(0x7a);
return this;
};
// M(0x4d) type(writeType) (<key> <value>) z(0x7a)
proto._writeObject = function (obj) {
this._assertType('writeObject / writeMap', 'object', obj.$, obj.$class);
this.byteBuffer.put(0x4d);
this.writeType(obj.$class);
var val = obj.$;
var keys = Object.keys(val);
for (var i = 0, len = keys.length; i < len; i++) {
var key = keys[i];
this.writeString(key);
this.write(val[key]);
}
this.byteBuffer.put(0x7a);
return this;
};
/**
* encode object
* support circular
* support all kind of java object
* : {a: 1}
* : {$class: 'java.lang.Map', $: {a: 1}}
*/
proto.writeObject = function (obj) {
if (is.nullOrUndefined(obj) ||
// : { a: { '$class': 'xxx', '$': null } }
(is.string(obj.$class) && is.nullOrUndefined(obj.$))) {
debug('writeObject with a null');
return this.writeNull();
}
this._assertType('writeObject / writeMap', 'object', obj);
if (this._checkRef(obj)) {
// if is ref, will write by _checkRef
return this;
}
var className = '';
var realObj;
if (!obj.$class || !obj.$) {
// : {a: 1}
realObj = obj;
} else {
// : {$class: 'java.util.HashMap', $: {a: 1}}
className = obj.$class === javaObject.DEFAULT_CLASSNAME.map || obj.$class === javaObject.DEFAULT_CLASSNAME.iMap ? '' : obj.$class;
realObj = obj.$;
}
if (!className) {
return this._writeHashMap(realObj);
}
debug('writeObject with complex object, className: %s', className);
return this._writeObject(obj);
};
proto.writeMap = proto.writeObject;
proto._writeListBegin = function (length, type) {
this.byteBuffer.putChar('V');
if (type) {
this.writeType(type);
}
this.byteBuffer.put(0x6c); // 'l'
this.byteBuffer.putInt(length);
return true;
};
/**
* encode array
*
* v1.0
* ```
* list ::= V(x56) [type(writeType)] l(0x6c) long-length(putInt) values 'z'
* ```
*
* v2.0
* ```
* list ::= V(x56) type(writeType) n(0x6e) short-length(put) values 'z'
* ::= V(x56) type(writeType) l(0x6c) long-length(putInt) values 'z'
* ::= v(x76) ref(writeInt) fix-length(writeInt) values
* ```
*
* An ordered list, like an array.
* The two list productions are a fixed-length list and a variable length list.
* Both lists have a type.
* The type string may be an arbitrary UTF-8 string understood by the service.
*
* fixed length list:
* Hessian 2.0 allows a compact form of the list for successive lists of
* the same type where the length is known beforehand.
* The type and length are encoded by integers,
* where the type is a reference to an earlier specified type.
*
* @param {Array} arr
* @return {this}
*/
proto.writeArray = function (arr) {
if (this._checkRef(arr)) {
// if is ref, will write by _checkRef
return this;
}
var isSimpleArray = is.array(arr);
var className = ''; // empty string meaning: `javaObject.DEFAULT_CLASSNAME.list`
var realArray = arr;
if (!isSimpleArray) {
if (is.object(arr) && is.nullOrUndefined(arr.$)) {
return this.writeNull();
}
var isComplexArray = is.object(arr) &&
is.string(arr.$class) && is.array(arr.$);
if (!isComplexArray) {
throw new TypeError('hessian writeArray input type invalid');
}
debug('write array with a complex array with className: %s', className);
className = arr.$class === javaObject.DEFAULT_CLASSNAME.list ? '' : arr.$class;
realArray = arr.$;
}
var hasEnd = this._writeListBegin(realArray.length, className);
for (var i = 0; i < realArray.length; i++) {
this.write(realArray[i]);
}
if (hasEnd) {
this.byteBuffer.putChar('z');
}
return this;
};
proto.writeList = proto.writeArray;
/**
* write any type
* @param {Object|Number|String|Boolean|Array} val
* : 1 => int
* : 1.1 => double
* :
*/
proto.write = function (val) {
var type = typeof val;
if (is.nullOrUndefined(val) || is.NaN(val)) {
return this.writeNull();
}
switch (type) {
case 'string':
return this.writeString(val);
case 'boolean':
return this.writeBool(val);
case 'number':
// must check long value first
if (is.long(val)) {
debug('write number %d as long', val);
return this.writeLong(val);
}
if (is.int(val)) {
debug('write number %d as int', val);
return this.writeInt(val);
}
// double
debug('write number %d as double', val);
return this.writeDouble(val);
}
if (is.long(val) || is.Long(val)) {
debug('write long: high: %s, low: %s', val.high, val.low);
return this.writeLong(val);
}
if (is.date(val)) {
debug('write Date: %s', val);
return this.writeDate(val);
}
if (is.buffer(val)) {
debug('write Buffer with a length of %d', val.length);
return this.writeBytes(val);
}
if (is.array(val)) {
debug('write simple array with a length of %d', val.length);
return this.writeArray(val);
}
// Object
// {a: 1, b: 'test'}
// {a: 0, b: null}
if (!is.string(val.$class) || !utils.hasOwnProperty(val, '$')) {
debug('write simple object');
return this.writeObject(val);
}
if (is.array(val.$)) {
debug('detect val.$ is array');
return this.writeArray(val);
}
var method = utils.getSerializer(val.$class);
debug('write detect %s use serializer %s', val.$class, method);
// {$class: 'long', $: 123}
if (method !== 'writeObject' && method !== 'writeArray') {
if (is.nullOrUndefined(val.$)) {
return this.writeNull();
}
return this[method](val.$);
}
// java.lang.Object
if (utils.isJavaObject(val.$class)) {
if (is.date(val.$) || !is.object(val.$)) {
return this.write(val.$);
}
}
// {$class: 'java.util.Map', $: {a: 1}}
return this[method](val);
};
/**
* encode fault
* @param {fault} The defined fields are code, message, and detail. code is one of a short list of strings defined below. message is a user-readable message. detail is an object representing the exception. In Java, detail will be a serialized exception.
* @return {this}
*/
proto._writeFault = function(fault) {
this._assertType('writeFault', 'object', fault);
this._assertType('writeFault', 'string', fault.message);
var code = fault.code || 'ServiceException';
this.byteBuffer.putChar('f');
this.writeString('code');
this.writeString(code);
this.writeString('message');
this.writeString(fault.message);
if (fault.detail) {
this.writeString('detail');
this.writeObject(fault.detail);
}
return this;
};
proto._writeHeader = function(header) {
this._assertType('writeHeader', 'object', header);
this.byteBuffer.putChar('H');
if (SUPPORT_ES6_MAP && header instanceof Map) {
header.forEach(function (value, key) {
this.write(key);
this.write(value);
}, this);
} else {
var keys = Object.keys(header).sort();
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
this.writeString(k);
this.write(header[k]);
}
}
this.byteBuffer.putChar('z');
return this;
};
/**
* encode reply
* v1.0
* ```
* valid-reply ::= r x01 x00 header* object z
* fault-reply ::= r x01 x00 header* fault z
* ```
* @param {reply}
* @return {this}
*/
proto.writeReply = function(reply) {
this.byteBuffer.putChar('r').put(0x01).put(0x00);
if (reply.header) {
this._writeHeader(reply.header);
}
if (reply.fault) {
this._writeFault(reply.fault);
}else {
this.write(reply.value);
}
this.byteBuffer.putChar('z');
return this;
};
module.exports = Encoder;