blob: cce6c3cd9e5d8e15380f605005136f66ec24ba81 [file] [log] [blame]
Jake Farrell27274222011-11-10 20:32:44 +00001(*
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{$SCOPEDENUMS ON}
21
22unit Thrift.Protocol.JSON;
23
24interface
25
26uses
27 Classes,
28 SysUtils,
29 Math,
30 IdCoderMIME,
31 Generics.Collections,
32 Thrift.Transport,
33 Thrift.Protocol;
34
35type
36 IJSONProtocol = interface( IProtocol)
37 ['{F0DAFDBD-692A-4B71-9736-F5D485A2178F}']
38 // Read a byte that must match b; otherwise an exception is thrown.
39 procedure ReadJSONSyntaxChar( b : Byte);
40 end;
41
42 // JSON protocol implementation for thrift.
43 // This is a full-featured protocol supporting Write and Read.
44 // Please see the C++ class header for a detailed description of the protocol's wire format.
45 // Adapted from the C# version.
46 TJSONProtocolImpl = class( TProtocolImpl, IJSONProtocol)
47 public
48 type
49 TFactory = class( TInterfacedObject, IProtocolFactory)
50 public
Roger Meier333bbf32012-01-08 21:51:08 +000051 function GetProtocol( const trans: ITransport): IProtocol;
Jake Farrell27274222011-11-10 20:32:44 +000052 end;
53
54 private
55 class function GetTypeNameForTypeID(typeID : TType) : string;
56 class function GetTypeIDForTypeName( const name : string) : TType;
57
58 protected
59 type
60 // Base class for tracking JSON contexts that may require
61 // inserting/Reading additional JSON syntax characters.
62 // This base context does nothing.
63 TJSONBaseContext = class
64 protected
Roger Meierfebe8452012-06-06 10:32:24 +000065 FProto : Pointer; // weak IJSONProtocol;
Jake Farrell27274222011-11-10 20:32:44 +000066 public
67 constructor Create( const aProto : IJSONProtocol);
68 procedure Write; virtual;
69 procedure Read; virtual;
70 function EscapeNumbers : Boolean; virtual;
71 end;
72
73 // Context for JSON lists.
74 // Will insert/Read commas before each item except for the first one.
75 TJSONListContext = class( TJSONBaseContext)
76 private
77 FFirst : Boolean;
78 public
79 constructor Create( const aProto : IJSONProtocol);
80 procedure Write; override;
81 procedure Read; override;
82 end;
83
84 // Context for JSON records. Will insert/Read colons before the value portion of each record
85 // pair, and commas before each key except the first. In addition, will indicate that numbers
86 // in the key position need to be escaped in quotes (since JSON keys must be strings).
87 TJSONPairContext = class( TJSONBaseContext)
88 private
89 FFirst, FColon : Boolean;
90 public
91 constructor Create( const aProto : IJSONProtocol);
92 procedure Write; override;
93 procedure Read; override;
94 function EscapeNumbers : Boolean; override;
95 end;
96
97 // Holds up to one byte from the transport
98 TLookaheadReader = class
99 protected
Roger Meierfebe8452012-06-06 10:32:24 +0000100 FProto : Pointer; // weak IJSONProtocol;
Jake Farrell27274222011-11-10 20:32:44 +0000101 constructor Create( const aProto : IJSONProtocol);
102
103 private
104 FHasData : Boolean;
105 FData : TBytes;
106
107 public
108 // Return and consume the next byte to be Read, either taking it from the
109 // data buffer if present or getting it from the transport otherwise.
110 function Read : Byte;
111
112 // Return the next byte to be Read without consuming, filling the data
113 // buffer if it has not been filled alReady.
114 function Peek : Byte;
115 end;
116
117 protected
118 // Stack of nested contexts that we may be in
119 FContextStack : TStack<TJSONBaseContext>;
120
121 // Current context that we are in
122 FContext : TJSONBaseContext;
123
124 // Reader that manages a 1-byte buffer
125 FReader : TLookaheadReader;
126
127 // Push/pop a new JSON context onto/from the stack.
Roger Meier45a37262012-01-08 21:44:44 +0000128 procedure ResetContextStack;
Roger Meier333bbf32012-01-08 21:51:08 +0000129 procedure PushContext( const aCtx : TJSONBaseContext);
Jake Farrell27274222011-11-10 20:32:44 +0000130 procedure PopContext;
131
132 public
133 // TJSONProtocolImpl Constructor
Roger Meier333bbf32012-01-08 21:51:08 +0000134 constructor Create( const aTrans : ITransport);
Jake Farrell27274222011-11-10 20:32:44 +0000135 destructor Destroy; override;
136
137 protected
138 // IJSONProtocol
139 // Read a byte that must match b; otherwise an exception is thrown.
140 procedure ReadJSONSyntaxChar( b : Byte);
141
142 private
143 // Convert a byte containing a hex char ('0'-'9' or 'a'-'f') into its corresponding hex value
144 class function HexVal( ch : Byte) : Byte;
145
146 // Convert a byte containing a hex value to its corresponding hex character
147 class function HexChar( val : Byte) : Byte;
148
149 // Write the bytes in array buf as a JSON characters, escaping as needed
150 procedure WriteJSONString( const b : TBytes); overload;
Roger Meier333bbf32012-01-08 21:51:08 +0000151 procedure WriteJSONString( const str : string); overload;
Jake Farrell27274222011-11-10 20:32:44 +0000152
153 // Write out number as a JSON value. If the context dictates so, it will be
154 // wrapped in quotes to output as a JSON string.
Roger Meier333bbf32012-01-08 21:51:08 +0000155 procedure WriteJSONInteger( const num : Int64);
Jake Farrell27274222011-11-10 20:32:44 +0000156
157 // Write out a double as a JSON value. If it is NaN or infinity or if the
158 // context dictates escaping, Write out as JSON string.
159 procedure WriteJSONDouble( const num : Double);
160
161 // Write out contents of byte array b as a JSON string with base-64 encoded data
162 procedure WriteJSONBase64( const b : TBytes);
163
164 procedure WriteJSONObjectStart;
165 procedure WriteJSONObjectEnd;
166 procedure WriteJSONArrayStart;
167 procedure WriteJSONArrayEnd;
168
169 public
170 // IProtocol
Roger Meier333bbf32012-01-08 21:51:08 +0000171 procedure WriteMessageBegin( const aMsg : IMessage); override;
Jake Farrell27274222011-11-10 20:32:44 +0000172 procedure WriteMessageEnd; override;
Roger Meier333bbf32012-01-08 21:51:08 +0000173 procedure WriteStructBegin( const struc: IStruct); override;
Jake Farrell27274222011-11-10 20:32:44 +0000174 procedure WriteStructEnd; override;
Roger Meier333bbf32012-01-08 21:51:08 +0000175 procedure WriteFieldBegin( const field: IField); override;
Jake Farrell27274222011-11-10 20:32:44 +0000176 procedure WriteFieldEnd; override;
177 procedure WriteFieldStop; override;
Roger Meier333bbf32012-01-08 21:51:08 +0000178 procedure WriteMapBegin( const map: IMap); override;
Jake Farrell27274222011-11-10 20:32:44 +0000179 procedure WriteMapEnd; override;
Roger Meier333bbf32012-01-08 21:51:08 +0000180 procedure WriteListBegin( const list: IList); override;
Jake Farrell27274222011-11-10 20:32:44 +0000181 procedure WriteListEnd(); override;
Roger Meier333bbf32012-01-08 21:51:08 +0000182 procedure WriteSetBegin( const set_: ISet ); override;
Jake Farrell27274222011-11-10 20:32:44 +0000183 procedure WriteSetEnd(); override;
184 procedure WriteBool( b: Boolean); override;
185 procedure WriteByte( b: ShortInt); override;
186 procedure WriteI16( i16: SmallInt); override;
187 procedure WriteI32( i32: Integer); override;
Roger Meier333bbf32012-01-08 21:51:08 +0000188 procedure WriteI64( const i64: Int64); override;
189 procedure WriteDouble( const d: Double); override;
Jake Farrell27274222011-11-10 20:32:44 +0000190 procedure WriteString( const s: string ); override;
191 procedure WriteBinary( const b: TBytes); override;
192 //
193 function ReadMessageBegin: IMessage; override;
194 procedure ReadMessageEnd(); override;
195 function ReadStructBegin: IStruct; override;
196 procedure ReadStructEnd; override;
197 function ReadFieldBegin: IField; override;
198 procedure ReadFieldEnd(); override;
199 function ReadMapBegin: IMap; override;
200 procedure ReadMapEnd(); override;
201 function ReadListBegin: IList; override;
202 procedure ReadListEnd(); override;
203 function ReadSetBegin: ISet; override;
204 procedure ReadSetEnd(); override;
205 function ReadBool: Boolean; override;
206 function ReadByte: ShortInt; override;
207 function ReadI16: SmallInt; override;
208 function ReadI32: Integer; override;
209 function ReadI64: Int64; override;
210 function ReadDouble:Double; override;
211 function ReadString : string; override;
212 function ReadBinary: TBytes; override;
213
214
215 private
216 // Reading methods.
217
218 // Read in a JSON string, unescaping as appropriate.
219 // Skip Reading from the context if skipContext is true.
220 function ReadJSONString( skipContext : Boolean) : TBytes;
221
222 // Return true if the given byte could be a valid part of a JSON number.
223 function IsJSONNumeric( b : Byte) : Boolean;
224
225 // Read in a sequence of characters that are all valid in JSON numbers. Does
226 // not do a complete regex check to validate that this is actually a number.
227 function ReadJSONNumericChars : String;
228
229 // Read in a JSON number. If the context dictates, Read in enclosing quotes.
230 function ReadJSONInteger : Int64;
231
232 // Read in a JSON double value. Throw if the value is not wrapped in quotes
233 // when expected or if wrapped in quotes when not expected.
234 function ReadJSONDouble : Double;
235
236 // Read in a JSON string containing base-64 encoded data and decode it.
237 function ReadJSONBase64 : TBytes;
238
239 procedure ReadJSONObjectStart;
240 procedure ReadJSONObjectEnd;
241 procedure ReadJSONArrayStart;
242 procedure ReadJSONArrayEnd;
243 end;
244
245
246implementation
247
248var
249 COMMA : TBytes;
250 COLON : TBytes;
251 LBRACE : TBytes;
252 RBRACE : TBytes;
253 LBRACKET : TBytes;
254 RBRACKET : TBytes;
255 QUOTE : TBytes;
256 BACKSLASH : TBytes;
257 ZERO : TBytes;
258 ESCSEQ : TBytes;
259
260const
261 VERSION = 1;
262 JSON_CHAR_TABLE : array[0..$2F] of Byte
263 = (0,0,0,0, 0,0,0,0, Byte('b'),Byte('t'),Byte('n'),0, Byte('f'),Byte('r'),0,0,
264 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
265 1,1,Byte('"'),1, 1,1,1,1, 1,1,1,1, 1,1,1,1);
266
Jens Geyer21366942013-12-30 22:04:51 +0100267 ESCAPE_CHARS = '"\/btnfr';
268 ESCAPE_CHAR_VALS = '"\/'#8#9#10#12#13;
Jake Farrell27274222011-11-10 20:32:44 +0000269
270 DEF_STRING_SIZE = 16;
271
272 NAME_BOOL = 'tf';
273 NAME_BYTE = 'i8';
274 NAME_I16 = 'i16';
275 NAME_I32 = 'i32';
276 NAME_I64 = 'i64';
277 NAME_DOUBLE = 'dbl';
278 NAME_STRUCT = 'rec';
279 NAME_STRING = 'str';
280 NAME_MAP = 'map';
281 NAME_LIST = 'lst';
282 NAME_SET = 'set';
283
284 INVARIANT_CULTURE : TFormatSettings
285 = ( ThousandSeparator: ',';
286 DecimalSeparator: '.');
287
288
289
290//--- TJSONProtocolImpl ----------------------
291
292
Roger Meier333bbf32012-01-08 21:51:08 +0000293function TJSONProtocolImpl.TFactory.GetProtocol( const trans: ITransport): IProtocol;
Jake Farrell27274222011-11-10 20:32:44 +0000294begin
295 result := TJSONProtocolImpl.Create(trans);
296end;
297
298class function TJSONProtocolImpl.GetTypeNameForTypeID(typeID : TType) : string;
299begin
300 case typeID of
301 TType.Bool_: result := NAME_BOOL;
302 TType.Byte_: result := NAME_BYTE;
303 TType.I16: result := NAME_I16;
304 TType.I32: result := NAME_I32;
305 TType.I64: result := NAME_I64;
306 TType.Double_: result := NAME_DOUBLE;
307 TType.String_: result := NAME_STRING;
308 TType.Struct: result := NAME_STRUCT;
309 TType.Map: result := NAME_MAP;
310 TType.Set_: result := NAME_SET;
311 TType.List: result := NAME_LIST;
312 else
313 raise TProtocolException.Create( TProtocolException.NOT_IMPLEMENTED, 'Unrecognized type ('+IntToStr(Ord(typeID))+')');
314 end;
315end;
316
317
318class function TJSONProtocolImpl.GetTypeIDForTypeName( const name : string) : TType;
319begin
320 if name = NAME_BOOL then result := TType.Bool_
321 else if name = NAME_BYTE then result := TType.Byte_
322 else if name = NAME_I16 then result := TType.I16
323 else if name = NAME_I32 then result := TType.I32
324 else if name = NAME_I64 then result := TType.I64
325 else if name = NAME_DOUBLE then result := TType.Double_
326 else if name = NAME_STRUCT then result := TType.Struct
327 else if name = NAME_STRING then result := TType.String_
328 else if name = NAME_MAP then result := TType.Map
329 else if name = NAME_LIST then result := TType.List
330 else if name = NAME_SET then result := TType.Set_
331 else raise TProtocolException.Create( TProtocolException.NOT_IMPLEMENTED, 'Unrecognized type ('+name+')');
332end;
333
334
335constructor TJSONProtocolImpl.TJSONBaseContext.Create( const aProto : IJSONProtocol);
336begin
337 inherited Create;
Roger Meierfebe8452012-06-06 10:32:24 +0000338 FProto := Pointer(aProto);
Jake Farrell27274222011-11-10 20:32:44 +0000339end;
340
341
342procedure TJSONProtocolImpl.TJSONBaseContext.Write;
343begin
344 // nothing
345end;
346
347
348procedure TJSONProtocolImpl.TJSONBaseContext.Read;
349begin
350 // nothing
351end;
352
353
354function TJSONProtocolImpl.TJSONBaseContext.EscapeNumbers : Boolean;
355begin
356 result := FALSE;
357end;
358
359
360constructor TJSONProtocolImpl.TJSONListContext.Create( const aProto : IJSONProtocol);
361begin
362 inherited Create( aProto);
363 FFirst := TRUE;
364end;
365
366
367procedure TJSONProtocolImpl.TJSONListContext.Write;
368begin
369 if FFirst
370 then FFirst := FALSE
Roger Meierfebe8452012-06-06 10:32:24 +0000371 else IJSONProtocol(FProto).Transport.Write( COMMA);
Jake Farrell27274222011-11-10 20:32:44 +0000372end;
373
374
375procedure TJSONProtocolImpl.TJSONListContext.Read;
376begin
377 if FFirst
378 then FFirst := FALSE
Roger Meierfebe8452012-06-06 10:32:24 +0000379 else IJSONProtocol(FProto).ReadJSONSyntaxChar( COMMA[0]);
Jake Farrell27274222011-11-10 20:32:44 +0000380end;
381
382
383constructor TJSONProtocolImpl.TJSONPairContext.Create( const aProto : IJSONProtocol);
384begin
385 inherited Create( aProto);
386 FFirst := TRUE;
387 FColon := TRUE;
388end;
389
390
391procedure TJSONProtocolImpl.TJSONPairContext.Write;
392begin
393 if FFirst then begin
394 FFirst := FALSE;
395 FColon := TRUE;
396 end
397 else begin
398 if FColon
Roger Meierfebe8452012-06-06 10:32:24 +0000399 then IJSONProtocol(FProto).Transport.Write( COLON)
400 else IJSONProtocol(FProto).Transport.Write( COMMA);
Jake Farrell27274222011-11-10 20:32:44 +0000401 FColon := not FColon;
402 end;
403end;
404
405
406procedure TJSONProtocolImpl.TJSONPairContext.Read;
407begin
408 if FFirst then begin
409 FFirst := FALSE;
410 FColon := TRUE;
411 end
412 else begin
413 if FColon
Roger Meierfebe8452012-06-06 10:32:24 +0000414 then IJSONProtocol(FProto).ReadJSONSyntaxChar( COLON[0])
415 else IJSONProtocol(FProto).ReadJSONSyntaxChar( COMMA[0]);
Jake Farrell27274222011-11-10 20:32:44 +0000416 FColon := not FColon;
417 end;
418end;
419
420
421function TJSONProtocolImpl.TJSONPairContext.EscapeNumbers : Boolean;
422begin
423 result := FColon;
424end;
425
426
427constructor TJSONProtocolImpl.TLookaheadReader.Create( const aProto : IJSONProtocol);
428begin
429 inherited Create;
Roger Meierfebe8452012-06-06 10:32:24 +0000430 FProto := Pointer(aProto);
Jake Farrell27274222011-11-10 20:32:44 +0000431 FHasData := FALSE;
432end;
433
434
435function TJSONProtocolImpl.TLookaheadReader.Read : Byte;
436begin
437 if FHasData
438 then FHasData := FALSE
439 else begin
440 SetLength( FData, 1);
Roger Meierfebe8452012-06-06 10:32:24 +0000441 IJSONProtocol(FProto).Transport.ReadAll( FData, 0, 1);
Jake Farrell27274222011-11-10 20:32:44 +0000442 end;
443 result := FData[0];
444end;
445
446
447function TJSONProtocolImpl.TLookaheadReader.Peek : Byte;
448begin
449 if not FHasData then begin
450 SetLength( FData, 1);
Roger Meierfebe8452012-06-06 10:32:24 +0000451 IJSONProtocol(FProto).Transport.ReadAll( FData, 0, 1);
Jake Farrell27274222011-11-10 20:32:44 +0000452 FHasData := TRUE;
453 end;
454 result := FData[0];
455end;
456
457
Roger Meier333bbf32012-01-08 21:51:08 +0000458constructor TJSONProtocolImpl.Create( const aTrans : ITransport);
Jake Farrell27274222011-11-10 20:32:44 +0000459begin
460 inherited Create( aTrans);
461
462 // Stack of nested contexts that we may be in
463 FContextStack := TStack<TJSONBaseContext>.Create;
464
465 FContext := TJSONBaseContext.Create( Self);
466 FReader := TLookaheadReader.Create( Self);
467end;
468
469
470destructor TJSONProtocolImpl.Destroy;
471begin
472 try
Roger Meier45a37262012-01-08 21:44:44 +0000473 ResetContextStack; // free any contents
Jake Farrell27274222011-11-10 20:32:44 +0000474 FreeAndNil( FReader);
475 FreeAndNil( FContext);
476 FreeAndNil( FContextStack);
477 finally
478 inherited Destroy;
479 end;
480end;
481
482
Roger Meier45a37262012-01-08 21:44:44 +0000483procedure TJSONProtocolImpl.ResetContextStack;
484begin
485 while FContextStack.Count > 0
486 do PopContext;
487end;
488
489
Roger Meier333bbf32012-01-08 21:51:08 +0000490procedure TJSONProtocolImpl.PushContext( const aCtx : TJSONBaseContext);
Roger Meier45a37262012-01-08 21:44:44 +0000491begin
492 FContextStack.Push( FContext);
493 FContext := aCtx;
494end;
495
496
497procedure TJSONProtocolImpl.PopContext;
498begin
499 FreeAndNil(FContext);
500 FContext := FContextStack.Pop;
501end;
502
503
Jake Farrell27274222011-11-10 20:32:44 +0000504procedure TJSONProtocolImpl.ReadJSONSyntaxChar( b : Byte);
505var ch : Byte;
506begin
507 ch := FReader.Read;
508 if (ch <> b)
509 then raise TProtocolException.Create( TProtocolException.INVALID_DATA, 'Unexpected character ('+Char(ch)+')');
510end;
511
512
513class function TJSONProtocolImpl.HexVal( ch : Byte) : Byte;
514var i : Integer;
515begin
516 i := StrToIntDef( '$0'+Char(ch), -1);
517 if (0 <= i) and (i < $10)
518 then result := i
519 else raise TProtocolException.Create( TProtocolException.INVALID_DATA, 'Expected hex character ('+Char(ch)+')');
520end;
521
522
523class function TJSONProtocolImpl.HexChar( val : Byte) : Byte;
524const HEXCHARS = '0123456789ABCDEF';
525begin
526 result := Byte( PChar(HEXCHARS)[val and $0F]);
527 ASSERT( Pos( Char(result), HEXCHARS) > 0);
528end;
529
530
Roger Meier333bbf32012-01-08 21:51:08 +0000531procedure TJSONProtocolImpl.WriteJSONString( const str : string);
Jake Farrell27274222011-11-10 20:32:44 +0000532begin
533 WriteJSONString( SysUtils.TEncoding.UTF8.GetBytes( str));
534end;
535
536
537procedure TJSONProtocolImpl.WriteJSONString( const b : TBytes);
538var i : Integer;
539 tmp : TBytes;
540begin
541 FContext.Write;
542 Transport.Write( QUOTE);
543 for i := 0 to Length(b)-1 do begin
544
545 if (b[i] and $00FF) >= $30 then begin
546
547 if (b[i] = BACKSLASH[0]) then begin
548 Transport.Write( BACKSLASH);
549 Transport.Write( BACKSLASH);
550 end
551 else begin
552 Transport.Write( b, i, 1);
553 end;
554
555 end
556 else begin
557 SetLength( tmp, 2);
558 tmp[0] := JSON_CHAR_TABLE[b[i]];
559 if (tmp[0] = 1) then begin
560 Transport.Write( b, i, 1)
561 end
562 else if (tmp[0] > 1) then begin
563 Transport.Write( BACKSLASH);
564 Transport.Write( tmp, 0, 1);
565 end
566 else begin
567 Transport.Write( ESCSEQ);
568 tmp[0] := HexChar( b[i] div $10);
569 tmp[1] := HexChar( b[i]);
570 Transport.Write( tmp, 0, 2);
571 end;
572 end;
573 end;
574 Transport.Write( QUOTE);
575end;
576
577
Roger Meier333bbf32012-01-08 21:51:08 +0000578procedure TJSONProtocolImpl.WriteJSONInteger( const num : Int64);
Jake Farrell27274222011-11-10 20:32:44 +0000579var str : String;
580 escapeNum : Boolean;
581begin
582 FContext.Write;
583 str := IntToStr(num);
584
585 escapeNum := FContext.EscapeNumbers;
586 if escapeNum
587 then Transport.Write( QUOTE);
588
589 Transport.Write( SysUtils.TEncoding.UTF8.GetBytes( str));
590
591 if escapeNum
592 then Transport.Write( QUOTE);
593end;
594
595
596procedure TJSONProtocolImpl.WriteJSONDouble( const num : Double);
597var str : string;
598 special : Boolean;
599 escapeNum : Boolean;
600begin
601 FContext.Write;
602
603 str := FloatToStr( num, INVARIANT_CULTURE);
604 special := FALSE;
605
606 case UpCase(str[1]) of
607 'N' : special := TRUE; // NaN
608 'I' : special := TRUE; // Infinity
609 '-' : special := (UpCase(str[2]) = 'I'); // -Infinity
610 end;
611
612 escapeNum := special or FContext.EscapeNumbers;
613
614
615 if escapeNum
616 then Transport.Write( QUOTE);
617
618 Transport.Write( SysUtils.TEncoding.UTF8.GetBytes( str));
619
620 if escapeNum
621 then Transport.Write( QUOTE);
622end;
623
624
625procedure TJSONProtocolImpl.WriteJSONBase64( const b : TBytes);
626var str : string;
627 tmp : TBytes;
628 i : Integer;
629begin
630 FContext.Write;
631 Transport.Write( QUOTE);
632
633 // First base64-encode b, then write the resulting 8-bit chars
634 // Unfortunately, EncodeBytes() returns a string of 16-bit (wide) chars
635 // And for the sake of efficiency, we want to write everything at once
636 str := TIdEncoderMIME.EncodeBytes(b);
637 ASSERT( SizeOf(str[1]) = SizeOf(Word));
638 SetLength( tmp, Length(str));
639 for i := 1 to Length(str) do begin
640 ASSERT( Hi(Word(str[i])) = 0); // base64 consists of a well-defined set of 8-bit chars only
641 tmp[i-1] := Lo(Word(str[i])); // extract the lower byte
642 end;
643 Transport.Write( tmp); // now write all the data
644
645 Transport.Write( QUOTE);
646end;
647
648
649procedure TJSONProtocolImpl.WriteJSONObjectStart;
650begin
651 FContext.Write;
652 Transport.Write( LBRACE);
653 PushContext( TJSONPairContext.Create( Self));
654end;
655
656
657procedure TJSONProtocolImpl.WriteJSONObjectEnd;
658begin
659 PopContext;
660 Transport.Write( RBRACE);
661end;
662
663
664procedure TJSONProtocolImpl.WriteJSONArrayStart;
665begin
666 FContext.Write;
667 Transport.Write( LBRACKET);
668 PushContext( TJSONListContext.Create( Self));
669end;
670
671
672procedure TJSONProtocolImpl.WriteJSONArrayEnd;
673begin
674 PopContext;
675 Transport.Write( RBRACKET);
676end;
677
678
Roger Meier333bbf32012-01-08 21:51:08 +0000679procedure TJSONProtocolImpl.WriteMessageBegin( const aMsg : IMessage);
Jake Farrell27274222011-11-10 20:32:44 +0000680begin
Roger Meier45a37262012-01-08 21:44:44 +0000681 ResetContextStack; // THRIFT-1473
682
Jake Farrell27274222011-11-10 20:32:44 +0000683 WriteJSONArrayStart;
684 WriteJSONInteger(VERSION);
685
686 WriteJSONString( SysUtils.TEncoding.UTF8.GetBytes( aMsg.Name));
687
688 WriteJSONInteger( LongInt( aMsg.Type_));
689 WriteJSONInteger( aMsg.SeqID);
690end;
691
692procedure TJSONProtocolImpl.WriteMessageEnd;
693begin
694 WriteJSONArrayEnd;
695end;
696
697
Roger Meier333bbf32012-01-08 21:51:08 +0000698procedure TJSONProtocolImpl.WriteStructBegin( const struc: IStruct);
Jake Farrell27274222011-11-10 20:32:44 +0000699begin
700 WriteJSONObjectStart;
701end;
702
703
704procedure TJSONProtocolImpl.WriteStructEnd;
705begin
706 WriteJSONObjectEnd;
707end;
708
709
Roger Meier333bbf32012-01-08 21:51:08 +0000710procedure TJSONProtocolImpl.WriteFieldBegin( const field : IField);
Jake Farrell27274222011-11-10 20:32:44 +0000711begin
712 WriteJSONInteger(field.ID);
713 WriteJSONObjectStart;
714 WriteJSONString( GetTypeNameForTypeID(field.Type_));
715end;
716
717
718procedure TJSONProtocolImpl.WriteFieldEnd;
719begin
720 WriteJSONObjectEnd;
721end;
722
723
724procedure TJSONProtocolImpl.WriteFieldStop;
725begin
726 // nothing to do
727end;
728
Roger Meier333bbf32012-01-08 21:51:08 +0000729procedure TJSONProtocolImpl.WriteMapBegin( const map: IMap);
Jake Farrell27274222011-11-10 20:32:44 +0000730begin
731 WriteJSONArrayStart;
732 WriteJSONString( GetTypeNameForTypeID( map.KeyType));
733 WriteJSONString( GetTypeNameForTypeID( map.ValueType));
734 WriteJSONInteger( map.Count);
735 WriteJSONObjectStart;
736end;
737
738
739procedure TJSONProtocolImpl.WriteMapEnd;
740begin
741 WriteJSONObjectEnd;
742 WriteJSONArrayEnd;
743end;
744
745
Roger Meier333bbf32012-01-08 21:51:08 +0000746procedure TJSONProtocolImpl.WriteListBegin( const list: IList);
Jake Farrell27274222011-11-10 20:32:44 +0000747begin
748 WriteJSONArrayStart;
749 WriteJSONString( GetTypeNameForTypeID( list.ElementType));
750 WriteJSONInteger(list.Count);
751end;
752
753
754procedure TJSONProtocolImpl.WriteListEnd;
755begin
756 WriteJSONArrayEnd;
757end;
758
759
Roger Meier333bbf32012-01-08 21:51:08 +0000760procedure TJSONProtocolImpl.WriteSetBegin( const set_: ISet);
Jake Farrell27274222011-11-10 20:32:44 +0000761begin
762 WriteJSONArrayStart;
763 WriteJSONString( GetTypeNameForTypeID( set_.ElementType));
764 WriteJSONInteger( set_.Count);
765end;
766
767
768procedure TJSONProtocolImpl.WriteSetEnd;
769begin
770 WriteJSONArrayEnd;
771end;
772
773procedure TJSONProtocolImpl.WriteBool( b: Boolean);
774begin
775 if b
776 then WriteJSONInteger( 1)
777 else WriteJSONInteger( 0);
778end;
779
780procedure TJSONProtocolImpl.WriteByte( b: ShortInt);
781begin
782 WriteJSONInteger( b);
783end;
784
785procedure TJSONProtocolImpl.WriteI16( i16: SmallInt);
786begin
787 WriteJSONInteger( i16);
788end;
789
790procedure TJSONProtocolImpl.WriteI32( i32: Integer);
791begin
792 WriteJSONInteger( i32);
793end;
794
Roger Meier333bbf32012-01-08 21:51:08 +0000795procedure TJSONProtocolImpl.WriteI64( const i64: Int64);
Jake Farrell27274222011-11-10 20:32:44 +0000796begin
797 WriteJSONInteger(i64);
798end;
799
Roger Meier333bbf32012-01-08 21:51:08 +0000800procedure TJSONProtocolImpl.WriteDouble( const d: Double);
Jake Farrell27274222011-11-10 20:32:44 +0000801begin
802 WriteJSONDouble( d);
803end;
804
805procedure TJSONProtocolImpl.WriteString( const s: string );
806begin
807 WriteJSONString( SysUtils.TEncoding.UTF8.GetBytes( s));
808end;
809
810procedure TJSONProtocolImpl.WriteBinary( const b: TBytes);
811begin
812 WriteJSONBase64( b);
813end;
814
815
816function TJSONProtocolImpl.ReadJSONString( skipContext : Boolean) : TBytes;
817var buffer : TMemoryStream;
818 ch : Byte;
819 off : Integer;
820 tmp : TBytes;
821begin
822 buffer := TMemoryStream.Create;
823 try
824 if not skipContext
825 then FContext.Read;
826
827 ReadJSONSyntaxChar( QUOTE[0]);
828
829 while TRUE do begin
830 ch := FReader.Read;
831
832 if (ch = QUOTE[0])
833 then Break;
834
835 if (ch = ESCSEQ[0])
836 then begin
837 ch := FReader.Read;
838 if (ch = ESCSEQ[1])
839 then begin
840 ReadJSONSyntaxChar( ZERO[0]);
841 ReadJSONSyntaxChar( ZERO[0]);
842 SetLength( tmp, 2);
843 Transport.ReadAll( tmp, 0, 2);
844 ch := (HexVal(tmp[0]) shl 4) + HexVal(tmp[1]);
845 end
846 else begin
847 off := Pos( Char(ch), ESCAPE_CHARS);
848 if off < 1
849 then raise TProtocolException.Create( TProtocolException.INVALID_DATA, 'Expected control char');
850 ch := Byte( ESCAPE_CHAR_VALS[off]);
851 end;
852 end;
853 buffer.Write( ch, 1);
854 end;
855
856 SetLength( result, buffer.Size);
Jake Farrella2a9ee92011-12-15 20:50:31 +0000857 if buffer.Size > 0 then Move( buffer.Memory^, result[0], Length(result));
Jake Farrell27274222011-11-10 20:32:44 +0000858
859 finally
860 buffer.Free;
861 end;
862end;
863
864
865function TJSONProtocolImpl.IsJSONNumeric( b : Byte) : Boolean;
866const NUMCHARS = ['+','-','.','0','1','2','3','4','5','6','7','8','9','E','e'];
867begin
868 result := CharInSet( Char(b), NUMCHARS);
869end;
870
871
872function TJSONProtocolImpl.ReadJSONNumericChars : string;
873var strbld : TThriftStringBuilder;
874 ch : Byte;
875begin
876 strbld := TThriftStringBuilder.Create;
877 try
878 while TRUE do begin
879 ch := FReader.Peek;
880 if IsJSONNumeric(ch)
881 then strbld.Append( Char(FReader.Read))
882 else Break;
883 end;
884 result := strbld.ToString;
885
886 finally
887 strbld.Free;
888 end;
889end;
890
891
892function TJSONProtocolImpl.ReadJSONInteger : Int64;
893var str : string;
894begin
895 FContext.Read;
896 if FContext.EscapeNumbers
897 then ReadJSONSyntaxChar( QUOTE[0]);
898
899 str := ReadJSONNumericChars;
900
901 if FContext.EscapeNumbers
902 then ReadJSONSyntaxChar( QUOTE[0]);
903
904 try
905 result := StrToInt64(str);
906 except
907 on e:Exception do begin
908 raise TProtocolException.Create( TProtocolException.INVALID_DATA,
909 'Bad data encounted in numeric data ('+str+') ('+e.Message+')');
910 end;
911 end;
912end;
913
914
915function TJSONProtocolImpl.ReadJSONDouble : Double;
916var dub : Double;
917 str : string;
918begin
919 FContext.Read;
920
921 if FReader.Peek = QUOTE[0]
922 then begin
923 str := SysUtils.TEncoding.UTF8.GetString( ReadJSONString( TRUE));
924 dub := StrToFloat( str, INVARIANT_CULTURE);
925
926 if not FContext.EscapeNumbers()
927 and not Math.IsNaN(dub)
928 and not Math.IsInfinite(dub)
929 then begin
930 // Throw exception -- we should not be in a string in Self case
931 raise TProtocolException.Create( TProtocolException.INVALID_DATA, 'Numeric data unexpectedly quoted');
932 end;
933 result := dub;
934 Exit;
935 end;
936
937 // will throw - we should have had a quote if escapeNum == true
938 if FContext.EscapeNumbers
939 then ReadJSONSyntaxChar( QUOTE[0]);
940
941 try
942 str := ReadJSONNumericChars;
943 result := StrToFloat( str, INVARIANT_CULTURE);
944 except
945 on e:Exception
946 do raise TProtocolException.Create( TProtocolException.INVALID_DATA,
947 'Bad data encounted in numeric data ('+str+') ('+e.Message+')');
948 end;
949end;
950
951
952function TJSONProtocolImpl.ReadJSONBase64 : TBytes;
953var b : TBytes;
954 str : string;
955begin
956 b := ReadJSONString(false);
957
958 SetString( str, PAnsiChar(b), Length(b));
959 result := TIdDecoderMIME.DecodeBytes( str);
960end;
961
962
963procedure TJSONProtocolImpl.ReadJSONObjectStart;
964begin
965 FContext.Read;
966 ReadJSONSyntaxChar( LBRACE[0]);
967 PushContext( TJSONPairContext.Create( Self));
968end;
969
970
971procedure TJSONProtocolImpl.ReadJSONObjectEnd;
972begin
973 ReadJSONSyntaxChar( RBRACE[0]);
974 PopContext;
975end;
976
977
978procedure TJSONProtocolImpl.ReadJSONArrayStart;
979begin
980 FContext.Read;
981 ReadJSONSyntaxChar( LBRACKET[0]);
982 PushContext( TJSONListContext.Create( Self));
983end;
984
985
986procedure TJSONProtocolImpl.ReadJSONArrayEnd;
987begin
988 ReadJSONSyntaxChar( RBRACKET[0]);
989 PopContext;
990end;
991
992
993function TJSONProtocolImpl.ReadMessageBegin: IMessage;
994begin
Roger Meier45a37262012-01-08 21:44:44 +0000995 ResetContextStack; // THRIFT-1473
996
Jake Farrell27274222011-11-10 20:32:44 +0000997 result := TMessageImpl.Create;
998 ReadJSONArrayStart;
999
1000 if ReadJSONInteger <> VERSION
1001 then raise TProtocolException.Create( TProtocolException.BAD_VERSION, 'Message contained bad version.');
1002
1003 result.Name := SysUtils.TEncoding.UTF8.GetString( ReadJSONString( FALSE));
1004 result.Type_ := TMessageType( ReadJSONInteger);
1005 result.SeqID := ReadJSONInteger;
1006end;
1007
1008
1009procedure TJSONProtocolImpl.ReadMessageEnd;
1010begin
1011 ReadJSONArrayEnd;
1012end;
1013
1014
1015function TJSONProtocolImpl.ReadStructBegin : IStruct ;
1016begin
1017 ReadJSONObjectStart;
1018 result := TStructImpl.Create('');
1019end;
1020
1021
1022procedure TJSONProtocolImpl.ReadStructEnd;
1023begin
1024 ReadJSONObjectEnd;
1025end;
1026
1027
1028function TJSONProtocolImpl.ReadFieldBegin : IField;
1029var ch : Byte;
1030 str : string;
1031begin
1032 result := TFieldImpl.Create;
1033 ch := FReader.Peek;
1034 if ch = RBRACE[0]
1035 then result.Type_ := TType.Stop
1036 else begin
1037 result.ID := ReadJSONInteger;
1038 ReadJSONObjectStart;
1039
1040 str := SysUtils.TEncoding.UTF8.GetString( ReadJSONString( FALSE));
1041 result.Type_ := GetTypeIDForTypeName( str);
1042 end;
1043end;
1044
1045
1046procedure TJSONProtocolImpl.ReadFieldEnd;
1047begin
1048 ReadJSONObjectEnd;
1049end;
1050
1051
1052function TJSONProtocolImpl.ReadMapBegin : IMap;
1053var str : string;
1054begin
1055 result := TMapImpl.Create;
1056 ReadJSONArrayStart;
1057
1058 str := SysUtils.TEncoding.UTF8.GetString( ReadJSONString(FALSE));
1059 result.KeyType := GetTypeIDForTypeName( str);
1060
1061 str := SysUtils.TEncoding.UTF8.GetString( ReadJSONString(FALSE));
1062 result.ValueType := GetTypeIDForTypeName( str);
1063
1064 result.Count := ReadJSONInteger;
1065 ReadJSONObjectStart;
1066end;
1067
1068
1069procedure TJSONProtocolImpl.ReadMapEnd;
1070begin
1071 ReadJSONObjectEnd;
1072 ReadJSONArrayEnd;
1073end;
1074
1075
1076function TJSONProtocolImpl.ReadListBegin : IList;
1077var str : string;
1078begin
1079 result := TListImpl.Create;
1080 ReadJSONArrayStart;
1081
1082 str := SysUtils.TEncoding.UTF8.GetString( ReadJSONString(FALSE));
1083 result.ElementType := GetTypeIDForTypeName( str);
1084 result.Count := ReadJSONInteger;
1085end;
1086
1087
1088procedure TJSONProtocolImpl.ReadListEnd;
1089begin
1090 ReadJSONArrayEnd;
1091end;
1092
1093
1094function TJSONProtocolImpl.ReadSetBegin : ISet;
1095var str : string;
1096begin
1097 result := TSetImpl.Create;
1098 ReadJSONArrayStart;
1099
1100 str := SysUtils.TEncoding.UTF8.GetString( ReadJSONString(FALSE));
1101 result.ElementType := GetTypeIDForTypeName( str);
1102 result.Count := ReadJSONInteger;
1103end;
1104
1105
1106procedure TJSONProtocolImpl.ReadSetEnd;
1107begin
1108 ReadJSONArrayEnd;
1109end;
1110
1111
1112function TJSONProtocolImpl.ReadBool : Boolean;
1113begin
1114 result := (ReadJSONInteger <> 0);
1115end;
1116
1117
1118function TJSONProtocolImpl.ReadByte : ShortInt;
1119begin
1120 result := ReadJSONInteger;
1121end;
1122
1123
1124function TJSONProtocolImpl.ReadI16 : SmallInt;
1125begin
1126 result := ReadJSONInteger;
1127end;
1128
1129
1130function TJSONProtocolImpl.ReadI32 : LongInt;
1131begin
1132 result := ReadJSONInteger;
1133end;
1134
1135
1136function TJSONProtocolImpl.ReadI64 : Int64;
1137begin
1138 result := ReadJSONInteger;
1139end;
1140
1141
1142function TJSONProtocolImpl.ReadDouble : Double;
1143begin
1144 result := ReadJSONDouble;
1145end;
1146
1147
1148function TJSONProtocolImpl.ReadString : string;
1149begin
1150 result := SysUtils.TEncoding.UTF8.GetString( ReadJSONString( FALSE));
1151end;
1152
1153
1154function TJSONProtocolImpl.ReadBinary : TBytes;
1155begin
1156 result := ReadJSONBase64;
1157end;
1158
1159
1160//--- init code ---
1161
1162procedure InitBytes( var b : TBytes; aData : array of Byte);
1163begin
1164 SetLength( b, Length(aData));
1165 Move( aData, b[0], Length(b));
1166end;
1167
1168initialization
1169 InitBytes( COMMA, [Byte(',')]);
1170 InitBytes( COLON, [Byte(':')]);
1171 InitBytes( LBRACE, [Byte('{')]);
1172 InitBytes( RBRACE, [Byte('}')]);
1173 InitBytes( LBRACKET, [Byte('[')]);
1174 InitBytes( RBRACKET, [Byte(']')]);
1175 InitBytes( QUOTE, [Byte('"')]);
1176 InitBytes( BACKSLASH, [Byte('\')]);
1177 InitBytes( ZERO, [Byte('0')]);
1178 InitBytes( ESCSEQ, [Byte('\'),Byte('u'),Byte('0'),Byte('0')]);
1179end.