blob: 6d305d82b34b5e3f561a99e6cf9c3f487be5f00c [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;
Jake Farrell27274222011-11-10 20:32:44 +0000257 ESCSEQ : TBytes;
258
259const
260 VERSION = 1;
261 JSON_CHAR_TABLE : array[0..$2F] of Byte
262 = (0,0,0,0, 0,0,0,0, Byte('b'),Byte('t'),Byte('n'),0, Byte('f'),Byte('r'),0,0,
263 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
264 1,1,Byte('"'),1, 1,1,1,1, 1,1,1,1, 1,1,1,1);
265
Jens Geyer21366942013-12-30 22:04:51 +0100266 ESCAPE_CHARS = '"\/btnfr';
267 ESCAPE_CHAR_VALS = '"\/'#8#9#10#12#13;
Jake Farrell27274222011-11-10 20:32:44 +0000268
269 DEF_STRING_SIZE = 16;
270
271 NAME_BOOL = 'tf';
272 NAME_BYTE = 'i8';
273 NAME_I16 = 'i16';
274 NAME_I32 = 'i32';
275 NAME_I64 = 'i64';
276 NAME_DOUBLE = 'dbl';
277 NAME_STRUCT = 'rec';
278 NAME_STRING = 'str';
279 NAME_MAP = 'map';
280 NAME_LIST = 'lst';
281 NAME_SET = 'set';
282
283 INVARIANT_CULTURE : TFormatSettings
284 = ( ThousandSeparator: ',';
285 DecimalSeparator: '.');
286
287
288
289//--- TJSONProtocolImpl ----------------------
290
291
Roger Meier333bbf32012-01-08 21:51:08 +0000292function TJSONProtocolImpl.TFactory.GetProtocol( const trans: ITransport): IProtocol;
Jake Farrell27274222011-11-10 20:32:44 +0000293begin
294 result := TJSONProtocolImpl.Create(trans);
295end;
296
297class function TJSONProtocolImpl.GetTypeNameForTypeID(typeID : TType) : string;
298begin
299 case typeID of
300 TType.Bool_: result := NAME_BOOL;
301 TType.Byte_: result := NAME_BYTE;
302 TType.I16: result := NAME_I16;
303 TType.I32: result := NAME_I32;
304 TType.I64: result := NAME_I64;
305 TType.Double_: result := NAME_DOUBLE;
306 TType.String_: result := NAME_STRING;
307 TType.Struct: result := NAME_STRUCT;
308 TType.Map: result := NAME_MAP;
309 TType.Set_: result := NAME_SET;
310 TType.List: result := NAME_LIST;
311 else
312 raise TProtocolException.Create( TProtocolException.NOT_IMPLEMENTED, 'Unrecognized type ('+IntToStr(Ord(typeID))+')');
313 end;
314end;
315
316
317class function TJSONProtocolImpl.GetTypeIDForTypeName( const name : string) : TType;
318begin
319 if name = NAME_BOOL then result := TType.Bool_
320 else if name = NAME_BYTE then result := TType.Byte_
321 else if name = NAME_I16 then result := TType.I16
322 else if name = NAME_I32 then result := TType.I32
323 else if name = NAME_I64 then result := TType.I64
324 else if name = NAME_DOUBLE then result := TType.Double_
325 else if name = NAME_STRUCT then result := TType.Struct
326 else if name = NAME_STRING then result := TType.String_
327 else if name = NAME_MAP then result := TType.Map
328 else if name = NAME_LIST then result := TType.List
329 else if name = NAME_SET then result := TType.Set_
330 else raise TProtocolException.Create( TProtocolException.NOT_IMPLEMENTED, 'Unrecognized type ('+name+')');
331end;
332
333
334constructor TJSONProtocolImpl.TJSONBaseContext.Create( const aProto : IJSONProtocol);
335begin
336 inherited Create;
Roger Meierfebe8452012-06-06 10:32:24 +0000337 FProto := Pointer(aProto);
Jake Farrell27274222011-11-10 20:32:44 +0000338end;
339
340
341procedure TJSONProtocolImpl.TJSONBaseContext.Write;
342begin
343 // nothing
344end;
345
346
347procedure TJSONProtocolImpl.TJSONBaseContext.Read;
348begin
349 // nothing
350end;
351
352
353function TJSONProtocolImpl.TJSONBaseContext.EscapeNumbers : Boolean;
354begin
355 result := FALSE;
356end;
357
358
359constructor TJSONProtocolImpl.TJSONListContext.Create( const aProto : IJSONProtocol);
360begin
361 inherited Create( aProto);
362 FFirst := TRUE;
363end;
364
365
366procedure TJSONProtocolImpl.TJSONListContext.Write;
367begin
368 if FFirst
369 then FFirst := FALSE
Roger Meierfebe8452012-06-06 10:32:24 +0000370 else IJSONProtocol(FProto).Transport.Write( COMMA);
Jake Farrell27274222011-11-10 20:32:44 +0000371end;
372
373
374procedure TJSONProtocolImpl.TJSONListContext.Read;
375begin
376 if FFirst
377 then FFirst := FALSE
Roger Meierfebe8452012-06-06 10:32:24 +0000378 else IJSONProtocol(FProto).ReadJSONSyntaxChar( COMMA[0]);
Jake Farrell27274222011-11-10 20:32:44 +0000379end;
380
381
382constructor TJSONProtocolImpl.TJSONPairContext.Create( const aProto : IJSONProtocol);
383begin
384 inherited Create( aProto);
385 FFirst := TRUE;
386 FColon := TRUE;
387end;
388
389
390procedure TJSONProtocolImpl.TJSONPairContext.Write;
391begin
392 if FFirst then begin
393 FFirst := FALSE;
394 FColon := TRUE;
395 end
396 else begin
397 if FColon
Roger Meierfebe8452012-06-06 10:32:24 +0000398 then IJSONProtocol(FProto).Transport.Write( COLON)
399 else IJSONProtocol(FProto).Transport.Write( COMMA);
Jake Farrell27274222011-11-10 20:32:44 +0000400 FColon := not FColon;
401 end;
402end;
403
404
405procedure TJSONProtocolImpl.TJSONPairContext.Read;
406begin
407 if FFirst then begin
408 FFirst := FALSE;
409 FColon := TRUE;
410 end
411 else begin
412 if FColon
Roger Meierfebe8452012-06-06 10:32:24 +0000413 then IJSONProtocol(FProto).ReadJSONSyntaxChar( COLON[0])
414 else IJSONProtocol(FProto).ReadJSONSyntaxChar( COMMA[0]);
Jake Farrell27274222011-11-10 20:32:44 +0000415 FColon := not FColon;
416 end;
417end;
418
419
420function TJSONProtocolImpl.TJSONPairContext.EscapeNumbers : Boolean;
421begin
422 result := FColon;
423end;
424
425
426constructor TJSONProtocolImpl.TLookaheadReader.Create( const aProto : IJSONProtocol);
427begin
428 inherited Create;
Roger Meierfebe8452012-06-06 10:32:24 +0000429 FProto := Pointer(aProto);
Jake Farrell27274222011-11-10 20:32:44 +0000430 FHasData := FALSE;
431end;
432
433
434function TJSONProtocolImpl.TLookaheadReader.Read : Byte;
435begin
436 if FHasData
437 then FHasData := FALSE
438 else begin
439 SetLength( FData, 1);
Roger Meierfebe8452012-06-06 10:32:24 +0000440 IJSONProtocol(FProto).Transport.ReadAll( FData, 0, 1);
Jake Farrell27274222011-11-10 20:32:44 +0000441 end;
442 result := FData[0];
443end;
444
445
446function TJSONProtocolImpl.TLookaheadReader.Peek : Byte;
447begin
448 if not FHasData then begin
449 SetLength( FData, 1);
Roger Meierfebe8452012-06-06 10:32:24 +0000450 IJSONProtocol(FProto).Transport.ReadAll( FData, 0, 1);
Jake Farrell27274222011-11-10 20:32:44 +0000451 FHasData := TRUE;
452 end;
453 result := FData[0];
454end;
455
456
Roger Meier333bbf32012-01-08 21:51:08 +0000457constructor TJSONProtocolImpl.Create( const aTrans : ITransport);
Jake Farrell27274222011-11-10 20:32:44 +0000458begin
459 inherited Create( aTrans);
460
461 // Stack of nested contexts that we may be in
462 FContextStack := TStack<TJSONBaseContext>.Create;
463
464 FContext := TJSONBaseContext.Create( Self);
465 FReader := TLookaheadReader.Create( Self);
466end;
467
468
469destructor TJSONProtocolImpl.Destroy;
470begin
471 try
Roger Meier45a37262012-01-08 21:44:44 +0000472 ResetContextStack; // free any contents
Jake Farrell27274222011-11-10 20:32:44 +0000473 FreeAndNil( FReader);
474 FreeAndNil( FContext);
475 FreeAndNil( FContextStack);
476 finally
477 inherited Destroy;
478 end;
479end;
480
481
Roger Meier45a37262012-01-08 21:44:44 +0000482procedure TJSONProtocolImpl.ResetContextStack;
483begin
484 while FContextStack.Count > 0
485 do PopContext;
486end;
487
488
Roger Meier333bbf32012-01-08 21:51:08 +0000489procedure TJSONProtocolImpl.PushContext( const aCtx : TJSONBaseContext);
Roger Meier45a37262012-01-08 21:44:44 +0000490begin
491 FContextStack.Push( FContext);
492 FContext := aCtx;
493end;
494
495
496procedure TJSONProtocolImpl.PopContext;
497begin
498 FreeAndNil(FContext);
499 FContext := FContextStack.Pop;
500end;
501
502
Jake Farrell27274222011-11-10 20:32:44 +0000503procedure TJSONProtocolImpl.ReadJSONSyntaxChar( b : Byte);
504var ch : Byte;
505begin
506 ch := FReader.Read;
507 if (ch <> b)
508 then raise TProtocolException.Create( TProtocolException.INVALID_DATA, 'Unexpected character ('+Char(ch)+')');
509end;
510
511
512class function TJSONProtocolImpl.HexVal( ch : Byte) : Byte;
513var i : Integer;
514begin
515 i := StrToIntDef( '$0'+Char(ch), -1);
516 if (0 <= i) and (i < $10)
517 then result := i
518 else raise TProtocolException.Create( TProtocolException.INVALID_DATA, 'Expected hex character ('+Char(ch)+')');
519end;
520
521
522class function TJSONProtocolImpl.HexChar( val : Byte) : Byte;
523const HEXCHARS = '0123456789ABCDEF';
524begin
525 result := Byte( PChar(HEXCHARS)[val and $0F]);
526 ASSERT( Pos( Char(result), HEXCHARS) > 0);
527end;
528
529
Roger Meier333bbf32012-01-08 21:51:08 +0000530procedure TJSONProtocolImpl.WriteJSONString( const str : string);
Jake Farrell27274222011-11-10 20:32:44 +0000531begin
532 WriteJSONString( SysUtils.TEncoding.UTF8.GetBytes( str));
533end;
534
535
536procedure TJSONProtocolImpl.WriteJSONString( const b : TBytes);
537var i : Integer;
538 tmp : TBytes;
539begin
540 FContext.Write;
541 Transport.Write( QUOTE);
542 for i := 0 to Length(b)-1 do begin
543
544 if (b[i] and $00FF) >= $30 then begin
545
546 if (b[i] = BACKSLASH[0]) then begin
547 Transport.Write( BACKSLASH);
548 Transport.Write( BACKSLASH);
549 end
550 else begin
551 Transport.Write( b, i, 1);
552 end;
553
554 end
555 else begin
556 SetLength( tmp, 2);
557 tmp[0] := JSON_CHAR_TABLE[b[i]];
558 if (tmp[0] = 1) then begin
559 Transport.Write( b, i, 1)
560 end
561 else if (tmp[0] > 1) then begin
562 Transport.Write( BACKSLASH);
563 Transport.Write( tmp, 0, 1);
564 end
565 else begin
566 Transport.Write( ESCSEQ);
567 tmp[0] := HexChar( b[i] div $10);
568 tmp[1] := HexChar( b[i]);
569 Transport.Write( tmp, 0, 2);
570 end;
571 end;
572 end;
573 Transport.Write( QUOTE);
574end;
575
576
Roger Meier333bbf32012-01-08 21:51:08 +0000577procedure TJSONProtocolImpl.WriteJSONInteger( const num : Int64);
Jake Farrell27274222011-11-10 20:32:44 +0000578var str : String;
579 escapeNum : Boolean;
580begin
581 FContext.Write;
582 str := IntToStr(num);
583
584 escapeNum := FContext.EscapeNumbers;
585 if escapeNum
586 then Transport.Write( QUOTE);
587
588 Transport.Write( SysUtils.TEncoding.UTF8.GetBytes( str));
589
590 if escapeNum
591 then Transport.Write( QUOTE);
592end;
593
594
595procedure TJSONProtocolImpl.WriteJSONDouble( const num : Double);
596var str : string;
597 special : Boolean;
598 escapeNum : Boolean;
599begin
600 FContext.Write;
601
602 str := FloatToStr( num, INVARIANT_CULTURE);
603 special := FALSE;
604
605 case UpCase(str[1]) of
606 'N' : special := TRUE; // NaN
607 'I' : special := TRUE; // Infinity
608 '-' : special := (UpCase(str[2]) = 'I'); // -Infinity
609 end;
610
611 escapeNum := special or FContext.EscapeNumbers;
612
613
614 if escapeNum
615 then Transport.Write( QUOTE);
616
617 Transport.Write( SysUtils.TEncoding.UTF8.GetBytes( str));
618
619 if escapeNum
620 then Transport.Write( QUOTE);
621end;
622
623
624procedure TJSONProtocolImpl.WriteJSONBase64( const b : TBytes);
625var str : string;
626 tmp : TBytes;
627 i : Integer;
628begin
629 FContext.Write;
630 Transport.Write( QUOTE);
631
632 // First base64-encode b, then write the resulting 8-bit chars
633 // Unfortunately, EncodeBytes() returns a string of 16-bit (wide) chars
634 // And for the sake of efficiency, we want to write everything at once
635 str := TIdEncoderMIME.EncodeBytes(b);
636 ASSERT( SizeOf(str[1]) = SizeOf(Word));
637 SetLength( tmp, Length(str));
638 for i := 1 to Length(str) do begin
639 ASSERT( Hi(Word(str[i])) = 0); // base64 consists of a well-defined set of 8-bit chars only
640 tmp[i-1] := Lo(Word(str[i])); // extract the lower byte
641 end;
642 Transport.Write( tmp); // now write all the data
643
644 Transport.Write( QUOTE);
645end;
646
647
648procedure TJSONProtocolImpl.WriteJSONObjectStart;
649begin
650 FContext.Write;
651 Transport.Write( LBRACE);
652 PushContext( TJSONPairContext.Create( Self));
653end;
654
655
656procedure TJSONProtocolImpl.WriteJSONObjectEnd;
657begin
658 PopContext;
659 Transport.Write( RBRACE);
660end;
661
662
663procedure TJSONProtocolImpl.WriteJSONArrayStart;
664begin
665 FContext.Write;
666 Transport.Write( LBRACKET);
667 PushContext( TJSONListContext.Create( Self));
668end;
669
670
671procedure TJSONProtocolImpl.WriteJSONArrayEnd;
672begin
673 PopContext;
674 Transport.Write( RBRACKET);
675end;
676
677
Roger Meier333bbf32012-01-08 21:51:08 +0000678procedure TJSONProtocolImpl.WriteMessageBegin( const aMsg : IMessage);
Jake Farrell27274222011-11-10 20:32:44 +0000679begin
Roger Meier45a37262012-01-08 21:44:44 +0000680 ResetContextStack; // THRIFT-1473
681
Jake Farrell27274222011-11-10 20:32:44 +0000682 WriteJSONArrayStart;
683 WriteJSONInteger(VERSION);
684
685 WriteJSONString( SysUtils.TEncoding.UTF8.GetBytes( aMsg.Name));
686
687 WriteJSONInteger( LongInt( aMsg.Type_));
688 WriteJSONInteger( aMsg.SeqID);
689end;
690
691procedure TJSONProtocolImpl.WriteMessageEnd;
692begin
693 WriteJSONArrayEnd;
694end;
695
696
Roger Meier333bbf32012-01-08 21:51:08 +0000697procedure TJSONProtocolImpl.WriteStructBegin( const struc: IStruct);
Jake Farrell27274222011-11-10 20:32:44 +0000698begin
699 WriteJSONObjectStart;
700end;
701
702
703procedure TJSONProtocolImpl.WriteStructEnd;
704begin
705 WriteJSONObjectEnd;
706end;
707
708
Roger Meier333bbf32012-01-08 21:51:08 +0000709procedure TJSONProtocolImpl.WriteFieldBegin( const field : IField);
Jake Farrell27274222011-11-10 20:32:44 +0000710begin
711 WriteJSONInteger(field.ID);
712 WriteJSONObjectStart;
713 WriteJSONString( GetTypeNameForTypeID(field.Type_));
714end;
715
716
717procedure TJSONProtocolImpl.WriteFieldEnd;
718begin
719 WriteJSONObjectEnd;
720end;
721
722
723procedure TJSONProtocolImpl.WriteFieldStop;
724begin
725 // nothing to do
726end;
727
Roger Meier333bbf32012-01-08 21:51:08 +0000728procedure TJSONProtocolImpl.WriteMapBegin( const map: IMap);
Jake Farrell27274222011-11-10 20:32:44 +0000729begin
730 WriteJSONArrayStart;
731 WriteJSONString( GetTypeNameForTypeID( map.KeyType));
732 WriteJSONString( GetTypeNameForTypeID( map.ValueType));
733 WriteJSONInteger( map.Count);
734 WriteJSONObjectStart;
735end;
736
737
738procedure TJSONProtocolImpl.WriteMapEnd;
739begin
740 WriteJSONObjectEnd;
741 WriteJSONArrayEnd;
742end;
743
744
Roger Meier333bbf32012-01-08 21:51:08 +0000745procedure TJSONProtocolImpl.WriteListBegin( const list: IList);
Jake Farrell27274222011-11-10 20:32:44 +0000746begin
747 WriteJSONArrayStart;
748 WriteJSONString( GetTypeNameForTypeID( list.ElementType));
749 WriteJSONInteger(list.Count);
750end;
751
752
753procedure TJSONProtocolImpl.WriteListEnd;
754begin
755 WriteJSONArrayEnd;
756end;
757
758
Roger Meier333bbf32012-01-08 21:51:08 +0000759procedure TJSONProtocolImpl.WriteSetBegin( const set_: ISet);
Jake Farrell27274222011-11-10 20:32:44 +0000760begin
761 WriteJSONArrayStart;
762 WriteJSONString( GetTypeNameForTypeID( set_.ElementType));
763 WriteJSONInteger( set_.Count);
764end;
765
766
767procedure TJSONProtocolImpl.WriteSetEnd;
768begin
769 WriteJSONArrayEnd;
770end;
771
772procedure TJSONProtocolImpl.WriteBool( b: Boolean);
773begin
774 if b
775 then WriteJSONInteger( 1)
776 else WriteJSONInteger( 0);
777end;
778
779procedure TJSONProtocolImpl.WriteByte( b: ShortInt);
780begin
781 WriteJSONInteger( b);
782end;
783
784procedure TJSONProtocolImpl.WriteI16( i16: SmallInt);
785begin
786 WriteJSONInteger( i16);
787end;
788
789procedure TJSONProtocolImpl.WriteI32( i32: Integer);
790begin
791 WriteJSONInteger( i32);
792end;
793
Roger Meier333bbf32012-01-08 21:51:08 +0000794procedure TJSONProtocolImpl.WriteI64( const i64: Int64);
Jake Farrell27274222011-11-10 20:32:44 +0000795begin
796 WriteJSONInteger(i64);
797end;
798
Roger Meier333bbf32012-01-08 21:51:08 +0000799procedure TJSONProtocolImpl.WriteDouble( const d: Double);
Jake Farrell27274222011-11-10 20:32:44 +0000800begin
801 WriteJSONDouble( d);
802end;
803
804procedure TJSONProtocolImpl.WriteString( const s: string );
805begin
806 WriteJSONString( SysUtils.TEncoding.UTF8.GetBytes( s));
807end;
808
809procedure TJSONProtocolImpl.WriteBinary( const b: TBytes);
810begin
811 WriteJSONBase64( b);
812end;
813
814
815function TJSONProtocolImpl.ReadJSONString( skipContext : Boolean) : TBytes;
816var buffer : TMemoryStream;
Jens Geyer7bb44a32014-02-07 22:24:37 +0100817 ch : Byte;
818 wch : Word;
Jake Farrell27274222011-11-10 20:32:44 +0000819 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
Jens Geyer7bb44a32014-02-07 22:24:37 +0100835 // check for escapes
836 if (ch <> ESCSEQ[0]) then begin
837 buffer.Write( ch, 1);
838 Continue;
Jake Farrell27274222011-11-10 20:32:44 +0000839 end;
Jens Geyer7bb44a32014-02-07 22:24:37 +0100840
841 // distuinguish between \uNNNN and \?
842 ch := FReader.Read;
843 if (ch <> ESCSEQ[1])
844 then begin
845 off := Pos( Char(ch), ESCAPE_CHARS);
846 if off < 1
847 then raise TProtocolException.Create( TProtocolException.INVALID_DATA, 'Expected control char');
848 ch := Byte( ESCAPE_CHAR_VALS[off]);
849 buffer.Write( ch, 1);
850 Continue;
851 end;
852
853 // it is \uXXXX
854 SetLength( tmp, 4);
855 Transport.ReadAll( tmp, 0, 4);
856 wch := (HexVal(tmp[0]) shl 12)
857 + (HexVal(tmp[1]) shl 8)
858 + (HexVal(tmp[2]) shl 4)
859 + HexVal(tmp[3]);
860 // we need to make UTF8 bytes from it, to be decoded later
861 tmp := SysUtils.TEncoding.UTF8.GetBytes(Char(wch));
862 buffer.Write( tmp[0], length(tmp));
Jake Farrell27274222011-11-10 20:32:44 +0000863 end;
864
865 SetLength( result, buffer.Size);
Jake Farrella2a9ee92011-12-15 20:50:31 +0000866 if buffer.Size > 0 then Move( buffer.Memory^, result[0], Length(result));
Jake Farrell27274222011-11-10 20:32:44 +0000867
868 finally
869 buffer.Free;
870 end;
871end;
872
873
874function TJSONProtocolImpl.IsJSONNumeric( b : Byte) : Boolean;
875const NUMCHARS = ['+','-','.','0','1','2','3','4','5','6','7','8','9','E','e'];
876begin
877 result := CharInSet( Char(b), NUMCHARS);
878end;
879
880
881function TJSONProtocolImpl.ReadJSONNumericChars : string;
882var strbld : TThriftStringBuilder;
883 ch : Byte;
884begin
885 strbld := TThriftStringBuilder.Create;
886 try
887 while TRUE do begin
888 ch := FReader.Peek;
889 if IsJSONNumeric(ch)
890 then strbld.Append( Char(FReader.Read))
891 else Break;
892 end;
893 result := strbld.ToString;
894
895 finally
896 strbld.Free;
897 end;
898end;
899
900
901function TJSONProtocolImpl.ReadJSONInteger : Int64;
902var str : string;
903begin
904 FContext.Read;
905 if FContext.EscapeNumbers
906 then ReadJSONSyntaxChar( QUOTE[0]);
907
908 str := ReadJSONNumericChars;
909
910 if FContext.EscapeNumbers
911 then ReadJSONSyntaxChar( QUOTE[0]);
912
913 try
914 result := StrToInt64(str);
915 except
916 on e:Exception do begin
917 raise TProtocolException.Create( TProtocolException.INVALID_DATA,
918 'Bad data encounted in numeric data ('+str+') ('+e.Message+')');
919 end;
920 end;
921end;
922
923
924function TJSONProtocolImpl.ReadJSONDouble : Double;
925var dub : Double;
926 str : string;
927begin
928 FContext.Read;
929
930 if FReader.Peek = QUOTE[0]
931 then begin
932 str := SysUtils.TEncoding.UTF8.GetString( ReadJSONString( TRUE));
933 dub := StrToFloat( str, INVARIANT_CULTURE);
934
935 if not FContext.EscapeNumbers()
936 and not Math.IsNaN(dub)
937 and not Math.IsInfinite(dub)
938 then begin
939 // Throw exception -- we should not be in a string in Self case
940 raise TProtocolException.Create( TProtocolException.INVALID_DATA, 'Numeric data unexpectedly quoted');
941 end;
942 result := dub;
943 Exit;
944 end;
945
946 // will throw - we should have had a quote if escapeNum == true
947 if FContext.EscapeNumbers
948 then ReadJSONSyntaxChar( QUOTE[0]);
949
950 try
951 str := ReadJSONNumericChars;
952 result := StrToFloat( str, INVARIANT_CULTURE);
953 except
954 on e:Exception
955 do raise TProtocolException.Create( TProtocolException.INVALID_DATA,
956 'Bad data encounted in numeric data ('+str+') ('+e.Message+')');
957 end;
958end;
959
960
961function TJSONProtocolImpl.ReadJSONBase64 : TBytes;
962var b : TBytes;
963 str : string;
964begin
965 b := ReadJSONString(false);
966
967 SetString( str, PAnsiChar(b), Length(b));
968 result := TIdDecoderMIME.DecodeBytes( str);
969end;
970
971
972procedure TJSONProtocolImpl.ReadJSONObjectStart;
973begin
974 FContext.Read;
975 ReadJSONSyntaxChar( LBRACE[0]);
976 PushContext( TJSONPairContext.Create( Self));
977end;
978
979
980procedure TJSONProtocolImpl.ReadJSONObjectEnd;
981begin
982 ReadJSONSyntaxChar( RBRACE[0]);
983 PopContext;
984end;
985
986
987procedure TJSONProtocolImpl.ReadJSONArrayStart;
988begin
989 FContext.Read;
990 ReadJSONSyntaxChar( LBRACKET[0]);
991 PushContext( TJSONListContext.Create( Self));
992end;
993
994
995procedure TJSONProtocolImpl.ReadJSONArrayEnd;
996begin
997 ReadJSONSyntaxChar( RBRACKET[0]);
998 PopContext;
999end;
1000
1001
1002function TJSONProtocolImpl.ReadMessageBegin: IMessage;
1003begin
Roger Meier45a37262012-01-08 21:44:44 +00001004 ResetContextStack; // THRIFT-1473
1005
Jake Farrell27274222011-11-10 20:32:44 +00001006 result := TMessageImpl.Create;
1007 ReadJSONArrayStart;
1008
1009 if ReadJSONInteger <> VERSION
1010 then raise TProtocolException.Create( TProtocolException.BAD_VERSION, 'Message contained bad version.');
1011
1012 result.Name := SysUtils.TEncoding.UTF8.GetString( ReadJSONString( FALSE));
1013 result.Type_ := TMessageType( ReadJSONInteger);
1014 result.SeqID := ReadJSONInteger;
1015end;
1016
1017
1018procedure TJSONProtocolImpl.ReadMessageEnd;
1019begin
1020 ReadJSONArrayEnd;
1021end;
1022
1023
1024function TJSONProtocolImpl.ReadStructBegin : IStruct ;
1025begin
1026 ReadJSONObjectStart;
1027 result := TStructImpl.Create('');
1028end;
1029
1030
1031procedure TJSONProtocolImpl.ReadStructEnd;
1032begin
1033 ReadJSONObjectEnd;
1034end;
1035
1036
1037function TJSONProtocolImpl.ReadFieldBegin : IField;
1038var ch : Byte;
1039 str : string;
1040begin
1041 result := TFieldImpl.Create;
1042 ch := FReader.Peek;
1043 if ch = RBRACE[0]
1044 then result.Type_ := TType.Stop
1045 else begin
1046 result.ID := ReadJSONInteger;
1047 ReadJSONObjectStart;
1048
1049 str := SysUtils.TEncoding.UTF8.GetString( ReadJSONString( FALSE));
1050 result.Type_ := GetTypeIDForTypeName( str);
1051 end;
1052end;
1053
1054
1055procedure TJSONProtocolImpl.ReadFieldEnd;
1056begin
1057 ReadJSONObjectEnd;
1058end;
1059
1060
1061function TJSONProtocolImpl.ReadMapBegin : IMap;
1062var str : string;
1063begin
1064 result := TMapImpl.Create;
1065 ReadJSONArrayStart;
1066
1067 str := SysUtils.TEncoding.UTF8.GetString( ReadJSONString(FALSE));
1068 result.KeyType := GetTypeIDForTypeName( str);
1069
1070 str := SysUtils.TEncoding.UTF8.GetString( ReadJSONString(FALSE));
1071 result.ValueType := GetTypeIDForTypeName( str);
1072
1073 result.Count := ReadJSONInteger;
1074 ReadJSONObjectStart;
1075end;
1076
1077
1078procedure TJSONProtocolImpl.ReadMapEnd;
1079begin
1080 ReadJSONObjectEnd;
1081 ReadJSONArrayEnd;
1082end;
1083
1084
1085function TJSONProtocolImpl.ReadListBegin : IList;
1086var str : string;
1087begin
1088 result := TListImpl.Create;
1089 ReadJSONArrayStart;
1090
1091 str := SysUtils.TEncoding.UTF8.GetString( ReadJSONString(FALSE));
1092 result.ElementType := GetTypeIDForTypeName( str);
1093 result.Count := ReadJSONInteger;
1094end;
1095
1096
1097procedure TJSONProtocolImpl.ReadListEnd;
1098begin
1099 ReadJSONArrayEnd;
1100end;
1101
1102
1103function TJSONProtocolImpl.ReadSetBegin : ISet;
1104var str : string;
1105begin
1106 result := TSetImpl.Create;
1107 ReadJSONArrayStart;
1108
1109 str := SysUtils.TEncoding.UTF8.GetString( ReadJSONString(FALSE));
1110 result.ElementType := GetTypeIDForTypeName( str);
1111 result.Count := ReadJSONInteger;
1112end;
1113
1114
1115procedure TJSONProtocolImpl.ReadSetEnd;
1116begin
1117 ReadJSONArrayEnd;
1118end;
1119
1120
1121function TJSONProtocolImpl.ReadBool : Boolean;
1122begin
1123 result := (ReadJSONInteger <> 0);
1124end;
1125
1126
1127function TJSONProtocolImpl.ReadByte : ShortInt;
1128begin
1129 result := ReadJSONInteger;
1130end;
1131
1132
1133function TJSONProtocolImpl.ReadI16 : SmallInt;
1134begin
1135 result := ReadJSONInteger;
1136end;
1137
1138
1139function TJSONProtocolImpl.ReadI32 : LongInt;
1140begin
1141 result := ReadJSONInteger;
1142end;
1143
1144
1145function TJSONProtocolImpl.ReadI64 : Int64;
1146begin
1147 result := ReadJSONInteger;
1148end;
1149
1150
1151function TJSONProtocolImpl.ReadDouble : Double;
1152begin
1153 result := ReadJSONDouble;
1154end;
1155
1156
1157function TJSONProtocolImpl.ReadString : string;
1158begin
1159 result := SysUtils.TEncoding.UTF8.GetString( ReadJSONString( FALSE));
1160end;
1161
1162
1163function TJSONProtocolImpl.ReadBinary : TBytes;
1164begin
1165 result := ReadJSONBase64;
1166end;
1167
1168
1169//--- init code ---
1170
1171procedure InitBytes( var b : TBytes; aData : array of Byte);
1172begin
1173 SetLength( b, Length(aData));
1174 Move( aData, b[0], Length(b));
1175end;
1176
1177initialization
1178 InitBytes( COMMA, [Byte(',')]);
1179 InitBytes( COLON, [Byte(':')]);
1180 InitBytes( LBRACE, [Byte('{')]);
1181 InitBytes( RBRACE, [Byte('}')]);
1182 InitBytes( LBRACKET, [Byte('[')]);
1183 InitBytes( RBRACKET, [Byte(']')]);
1184 InitBytes( QUOTE, [Byte('"')]);
1185 InitBytes( BACKSLASH, [Byte('\')]);
Jake Farrell27274222011-11-10 20:32:44 +00001186 InitBytes( ESCSEQ, [Byte('\'),Byte('u'),Byte('0'),Byte('0')]);
1187end.