blob: f5837816248314f49484b17ad0f68e1968e2e289 [file] [log] [blame]
Bryan Duxburyfd32d792010-09-18 20:51:25 +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
20using System;
21using System.IO;
22using System.Text;
23using System.Collections.Generic;
24
25using Thrift.Transport;
Roger Meier3da317b2011-07-28 18:35:51 +000026using System.Globalization;
Bryan Duxburyfd32d792010-09-18 20:51:25 +000027
28namespace Thrift.Protocol
29{
30 /// <summary>
31 /// JSON protocol implementation for thrift.
32 ///
33 /// This is a full-featured protocol supporting Write and Read.
34 ///
35 /// Please see the C++ class header for a detailed description of the
36 /// protocol's wire format.
37 ///
38 /// Adapted from the Java version.
39 /// </summary>
40 public class TJSONProtocol : TProtocol
41 {
42 /// <summary>
43 /// Factory for JSON protocol objects
44 /// </summary>
45 public class Factory : TProtocolFactory
46 {
47 public TProtocol GetProtocol(TTransport trans)
48 {
49 return new TJSONProtocol(trans);
50 }
51 }
52
53 private static byte[] COMMA = new byte[] { (byte)',' };
54 private static byte[] COLON = new byte[] { (byte)':' };
55 private static byte[] LBRACE = new byte[] { (byte)'{' };
56 private static byte[] RBRACE = new byte[] { (byte)'}' };
57 private static byte[] LBRACKET = new byte[] { (byte)'[' };
58 private static byte[] RBRACKET = new byte[] { (byte)']' };
59 private static byte[] QUOTE = new byte[] { (byte)'"' };
60 private static byte[] BACKSLASH = new byte[] { (byte)'\\' };
61 private static byte[] ZERO = new byte[] { (byte)'0' };
62
63 private byte[] ESCSEQ = new byte[] { (byte)'\\', (byte)'u', (byte)'0', (byte)'0' };
64
65 private const long VERSION = 1;
66 private byte[] JSON_CHAR_TABLE = {
67 0, 0, 0, 0, 0, 0, 0, 0,(byte)'b',(byte)'t',(byte)'n', 0,(byte)'f',(byte)'r', 0, 0,
68 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
69 1, 1,(byte)'"', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
70 };
71
72 private char[] ESCAPE_CHARS = "\"\\bfnrt".ToCharArray();
73
74 private byte[] ESCAPE_CHAR_VALS = {
75 (byte)'"', (byte)'\\', (byte)'\b', (byte)'\f', (byte)'\n', (byte)'\r', (byte)'\t',
76 };
77
78 private const int DEF_STRING_SIZE = 16;
79
80 private static byte[] NAME_BOOL = new byte[] { (byte)'t', (byte)'f' };
81 private static byte[] NAME_BYTE = new byte[] { (byte)'i', (byte)'8' };
82 private static byte[] NAME_I16 = new byte[] { (byte)'i', (byte)'1', (byte)'6' };
83 private static byte[] NAME_I32 = new byte[] { (byte)'i', (byte)'3', (byte)'2' };
84 private static byte[] NAME_I64 = new byte[] { (byte)'i', (byte)'6', (byte)'4' };
85 private static byte[] NAME_DOUBLE = new byte[] { (byte)'d', (byte)'b', (byte)'l' };
86 private static byte[] NAME_STRUCT = new byte[] { (byte)'r', (byte)'e', (byte)'c' };
87 private static byte[] NAME_STRING = new byte[] { (byte)'s', (byte)'t', (byte)'r' };
88 private static byte[] NAME_MAP = new byte[] { (byte)'m', (byte)'a', (byte)'p' };
89 private static byte[] NAME_LIST = new byte[] { (byte)'l', (byte)'s', (byte)'t' };
90 private static byte[] NAME_SET = new byte[] { (byte)'s', (byte)'e', (byte)'t' };
91
92 private static byte[] GetTypeNameForTypeID(TType typeID)
93 {
94 switch (typeID)
95 {
96 case TType.Bool:
97 return NAME_BOOL;
98 case TType.Byte:
99 return NAME_BYTE;
100 case TType.I16:
101 return NAME_I16;
102 case TType.I32:
103 return NAME_I32;
104 case TType.I64:
105 return NAME_I64;
106 case TType.Double:
107 return NAME_DOUBLE;
108 case TType.String:
109 return NAME_STRING;
110 case TType.Struct:
111 return NAME_STRUCT;
112 case TType.Map:
113 return NAME_MAP;
114 case TType.Set:
115 return NAME_SET;
116 case TType.List:
117 return NAME_LIST;
118 default:
119 throw new TProtocolException(TProtocolException.NOT_IMPLEMENTED,
120 "Unrecognized type");
121 }
122 }
123
124 private static TType GetTypeIDForTypeName(byte[] name)
125 {
126 TType result = TType.Stop;
127 if (name.Length > 1)
128 {
129 switch (name[0])
130 {
131 case (byte)'d':
132 result = TType.Double;
133 break;
134 case (byte)'i':
135 switch (name[1])
136 {
137 case (byte)'8':
138 result = TType.Byte;
139 break;
140 case (byte)'1':
141 result = TType.I16;
142 break;
143 case (byte)'3':
144 result = TType.I32;
145 break;
146 case (byte)'6':
147 result = TType.I64;
148 break;
149 }
150 break;
151 case (byte)'l':
152 result = TType.List;
153 break;
154 case (byte)'m':
155 result = TType.Map;
156 break;
157 case (byte)'r':
158 result = TType.Struct;
159 break;
160 case (byte)'s':
161 if (name[1] == (byte)'t')
162 {
163 result = TType.String;
164 }
165 else if (name[1] == (byte)'e')
166 {
167 result = TType.Set;
168 }
169 break;
170 case (byte)'t':
171 result = TType.Bool;
172 break;
173 }
174 }
175 if (result == TType.Stop)
176 {
177 throw new TProtocolException(TProtocolException.NOT_IMPLEMENTED,
178 "Unrecognized type");
179 }
180 return result;
181 }
182
183 ///<summary>
184 /// Base class for tracking JSON contexts that may require
185 /// inserting/Reading additional JSON syntax characters
186 /// This base context does nothing.
187 ///</summary>
188 protected class JSONBaseContext
189 {
190 protected TJSONProtocol proto;
191
192 public JSONBaseContext(TJSONProtocol proto)
193 {
194 this.proto = proto;
195 }
196
197 public virtual void Write() { }
198
199 public virtual void Read() { }
200
201 public virtual bool EscapeNumbers() { return false; }
202 }
203
204 ///<summary>
205 /// Context for JSON lists. Will insert/Read commas before each item except
206 /// for the first one
207 ///</summary>
208 protected class JSONListContext : JSONBaseContext
209 {
210 public JSONListContext(TJSONProtocol protocol)
211 : base(protocol)
212 {
213
214 }
215
216 private bool first = true;
217
218 public override void Write()
219 {
220 if (first)
221 {
222 first = false;
223 }
224 else
225 {
226 proto.trans.Write(COMMA);
227 }
228 }
229
230 public override void Read()
231 {
232 if (first)
233 {
234 first = false;
235 }
236 else
237 {
238 proto.ReadJSONSyntaxChar(COMMA);
239 }
240 }
241 }
242
243 ///<summary>
244 /// Context for JSON records. Will insert/Read colons before the value portion
245 /// of each record pair, and commas before each key except the first. In
246 /// addition, will indicate that numbers in the key position need to be
247 /// escaped in quotes (since JSON keys must be strings).
248 ///</summary>
249 protected class JSONPairContext : JSONBaseContext
250 {
251 public JSONPairContext(TJSONProtocol proto)
252 : base(proto)
253 {
254
255 }
256
257 private bool first = true;
258 private bool colon = true;
259
260 public override void Write()
261 {
262 if (first)
263 {
264 first = false;
265 colon = true;
266 }
267 else
268 {
269 proto.trans.Write(colon ? COLON : COMMA);
270 colon = !colon;
271 }
272 }
273
274 public override void Read()
275 {
276 if (first)
277 {
278 first = false;
279 colon = true;
280 }
281 else
282 {
283 proto.ReadJSONSyntaxChar(colon ? COLON : COMMA);
284 colon = !colon;
285 }
286 }
287
288 public override bool EscapeNumbers()
289 {
290 return colon;
291 }
292 }
293
294 ///<summary>
295 /// Holds up to one byte from the transport
296 ///</summary>
297 protected class LookaheadReader
298 {
299 protected TJSONProtocol proto;
300
301 public LookaheadReader(TJSONProtocol proto)
302 {
303 this.proto = proto;
304 }
305
306 private bool hasData;
307 private byte[] data = new byte[1];
308
309 ///<summary>
310 /// Return and consume the next byte to be Read, either taking it from the
311 /// data buffer if present or getting it from the transport otherwise.
312 ///</summary>
313 public byte Read()
314 {
315 if (hasData)
316 {
317 hasData = false;
318 }
319 else
320 {
321 proto.trans.ReadAll(data, 0, 1);
322 }
323 return data[0];
324 }
325
326 ///<summary>
327 /// Return the next byte to be Read without consuming, filling the data
328 /// buffer if it has not been filled alReady.
329 ///</summary>
330 public byte Peek()
331 {
332 if (!hasData)
333 {
334 proto.trans.ReadAll(data, 0, 1);
335 }
336 hasData = true;
337 return data[0];
338 }
339 }
340
341 // Default encoding
342 protected Encoding utf8Encoding = UTF8Encoding.UTF8;
343
344 // Stack of nested contexts that we may be in
345 protected Stack<JSONBaseContext> contextStack = new Stack<JSONBaseContext>();
346
347 // Current context that we are in
348 protected JSONBaseContext context;
349
350 // Reader that manages a 1-byte buffer
351 protected LookaheadReader reader;
352
353 ///<summary>
354 /// Push a new JSON context onto the stack.
355 ///</summary>
356 protected void PushContext(JSONBaseContext c)
357 {
358 contextStack.Push(context);
359 context = c;
360 }
361
362 ///<summary>
363 /// Pop the last JSON context off the stack
364 ///</summary>
365 protected void PopContext()
366 {
367 context = contextStack.Pop();
368 }
369
370 ///<summary>
371 /// TJSONProtocol Constructor
372 ///</summary>
373 public TJSONProtocol(TTransport trans)
374 : base(trans)
375 {
376 context = new JSONBaseContext(this);
377 reader = new LookaheadReader(this);
378 }
379
380 // Temporary buffer used by several methods
381 private byte[] tempBuffer = new byte[4];
382
383 ///<summary>
Roger Meiere0cac982010-12-16 13:15:49 +0000384 /// Read a byte that must match b[0]; otherwise an exception is thrown.
Bryan Duxburyfd32d792010-09-18 20:51:25 +0000385 /// Marked protected to avoid synthetic accessor in JSONListContext.Read
386 /// and JSONPairContext.Read
387 ///</summary>
388 protected void ReadJSONSyntaxChar(byte[] b)
389 {
390 byte ch = reader.Read();
391 if (ch != b[0])
392 {
393 throw new TProtocolException(TProtocolException.INVALID_DATA,
394 "Unexpected character:" + (char)ch);
395 }
396 }
397
398 ///<summary>
399 /// Convert a byte containing a hex char ('0'-'9' or 'a'-'f') into its
400 /// corresponding hex value
401 ///</summary>
402 private static byte HexVal(byte ch)
403 {
404 if ((ch >= '0') && (ch <= '9'))
405 {
406 return (byte)((char)ch - '0');
407 }
408 else if ((ch >= 'a') && (ch <= 'f'))
409 {
410 return (byte)((char)ch - 'a');
411 }
412 else
413 {
414 throw new TProtocolException(TProtocolException.INVALID_DATA,
415 "Expected hex character");
416 }
417 }
418
419 ///<summary>
420 /// Convert a byte containing a hex value to its corresponding hex character
421 ///</summary>
422 private static byte HexChar(byte val)
423 {
424 val &= 0x0F;
425 if (val < 10)
426 {
427 return (byte)((char)val + '0');
428 }
429 else
430 {
431 return (byte)((char)val + 'a');
432 }
433 }
434
435 ///<summary>
436 /// Write the bytes in array buf as a JSON characters, escaping as needed
437 ///</summary>
438 private void WriteJSONString(byte[] b)
439 {
440 context.Write();
441 trans.Write(QUOTE);
442 int len = b.Length;
443 for (int i = 0; i < len; i++)
444 {
445 if ((b[i] & 0x00FF) >= 0x30)
446 {
447 if (b[i] == BACKSLASH[0])
448 {
449 trans.Write(BACKSLASH);
450 trans.Write(BACKSLASH);
451 }
452 else
453 {
454 trans.Write(b, i, 1);
455 }
456 }
457 else
458 {
459 tempBuffer[0] = JSON_CHAR_TABLE[b[i]];
460 if (tempBuffer[0] == 1)
461 {
462 trans.Write(b, i, 1);
463 }
464 else if (tempBuffer[0] > 1)
465 {
466 trans.Write(BACKSLASH);
467 trans.Write(tempBuffer, 0, 1);
468 }
469 else
470 {
471 trans.Write(ESCSEQ);
472 tempBuffer[0] = HexChar((byte)(b[i] >> 4));
473 tempBuffer[1] = HexChar(b[i]);
474 trans.Write(tempBuffer, 0, 2);
475 }
476 }
477 }
478 trans.Write(QUOTE);
479 }
480
481 ///<summary>
482 /// Write out number as a JSON value. If the context dictates so, it will be
483 /// wrapped in quotes to output as a JSON string.
484 ///</summary>
485 private void WriteJSONInteger(long num)
486 {
487 context.Write();
488 String str = num.ToString();
489
490 bool escapeNum = context.EscapeNumbers();
491 if (escapeNum)
492 trans.Write(QUOTE);
493
494 trans.Write(utf8Encoding.GetBytes(str));
495
496 if (escapeNum)
497 trans.Write(QUOTE);
498 }
499
500 ///<summary>
501 /// Write out a double as a JSON value. If it is NaN or infinity or if the
502 /// context dictates escaping, Write out as JSON string.
503 ///</summary>
504 private void WriteJSONDouble(double num)
505 {
506 context.Write();
Roger Meier3da317b2011-07-28 18:35:51 +0000507 String str = num.ToString(CultureInfo.InvariantCulture);
Bryan Duxburyfd32d792010-09-18 20:51:25 +0000508 bool special = false;
509
510 switch (str[0])
511 {
512 case 'N': // NaN
513 case 'I': // Infinity
514 special = true;
515 break;
516 case '-':
517 if (str[1] == 'I')
518 { // -Infinity
519 special = true;
520 }
521 break;
522 }
523
524 bool escapeNum = special || context.EscapeNumbers();
525
526 if (escapeNum)
527 trans.Write(QUOTE);
528
529 trans.Write(utf8Encoding.GetBytes(str));
530
531 if (escapeNum)
532 trans.Write(QUOTE);
533 }
534 ///<summary>
535 /// Write out contents of byte array b as a JSON string with base-64 encoded
536 /// data
537 ///</summary>
538 private void WriteJSONBase64(byte[] b)
539 {
540 context.Write();
541 trans.Write(QUOTE);
542
543 int len = b.Length;
544 int off = 0;
545
546 while (len >= 3)
547 {
548 // Encode 3 bytes at a time
549 TBase64Utils.encode(b, off, 3, tempBuffer, 0);
550 trans.Write(tempBuffer, 0, 4);
551 off += 3;
552 len -= 3;
553 }
554 if (len > 0)
555 {
556 // Encode remainder
557 TBase64Utils.encode(b, off, len, tempBuffer, 0);
558 trans.Write(tempBuffer, 0, len + 1);
559 }
560
561 trans.Write(QUOTE);
562 }
563
564 private void WriteJSONObjectStart()
565 {
566 context.Write();
567 trans.Write(LBRACE);
568 PushContext(new JSONPairContext(this));
569 }
570
571 private void WriteJSONObjectEnd()
572 {
573 PopContext();
574 trans.Write(RBRACE);
575 }
576
577 private void WriteJSONArrayStart()
578 {
579 context.Write();
580 trans.Write(LBRACKET);
581 PushContext(new JSONListContext(this));
582 }
583
584 private void WriteJSONArrayEnd()
585 {
586 PopContext();
587 trans.Write(RBRACKET);
588 }
589
590 public override void WriteMessageBegin(TMessage message)
591 {
592 WriteJSONArrayStart();
593 WriteJSONInteger(VERSION);
594
595 byte[] b = utf8Encoding.GetBytes(message.Name);
596 WriteJSONString(b);
597
598 WriteJSONInteger((long)message.Type);
599 WriteJSONInteger(message.SeqID);
600 }
601
602 public override void WriteMessageEnd()
603 {
604 WriteJSONArrayEnd();
605 }
606
607 public override void WriteStructBegin(TStruct str)
608 {
609 WriteJSONObjectStart();
610 }
611
612 public override void WriteStructEnd()
613 {
614 WriteJSONObjectEnd();
615 }
616
617 public override void WriteFieldBegin(TField field)
618 {
619 WriteJSONInteger(field.ID);
620 WriteJSONObjectStart();
621 WriteJSONString(GetTypeNameForTypeID(field.Type));
622 }
623
624 public override void WriteFieldEnd()
625 {
626 WriteJSONObjectEnd();
627 }
628
629 public override void WriteFieldStop() { }
630
631 public override void WriteMapBegin(TMap map)
632 {
633 WriteJSONArrayStart();
634 WriteJSONString(GetTypeNameForTypeID(map.KeyType));
635 WriteJSONString(GetTypeNameForTypeID(map.ValueType));
636 WriteJSONInteger(map.Count);
637 WriteJSONObjectStart();
638 }
639
640 public override void WriteMapEnd()
641 {
642 WriteJSONObjectEnd();
643 WriteJSONArrayEnd();
644 }
645
646 public override void WriteListBegin(TList list)
647 {
648 WriteJSONArrayStart();
649 WriteJSONString(GetTypeNameForTypeID(list.ElementType));
650 WriteJSONInteger(list.Count);
651 }
652
653 public override void WriteListEnd()
654 {
655 WriteJSONArrayEnd();
656 }
657
658 public override void WriteSetBegin(TSet set)
659 {
660 WriteJSONArrayStart();
661 WriteJSONString(GetTypeNameForTypeID(set.ElementType));
662 WriteJSONInteger(set.Count);
663 }
664
665 public override void WriteSetEnd()
666 {
667 WriteJSONArrayEnd();
668 }
669
670 public override void WriteBool(bool b)
671 {
672 WriteJSONInteger(b ? (long)1 : (long)0);
673 }
674
Jens Geyerf509df92013-04-25 20:38:55 +0200675 public override void WriteByte(sbyte b)
Bryan Duxburyfd32d792010-09-18 20:51:25 +0000676 {
677 WriteJSONInteger((long)b);
678 }
679
680 public override void WriteI16(short i16)
681 {
682 WriteJSONInteger((long)i16);
683 }
684
685 public override void WriteI32(int i32)
686 {
687 WriteJSONInteger((long)i32);
688 }
689
690 public override void WriteI64(long i64)
691 {
692 WriteJSONInteger(i64);
693 }
694
695 public override void WriteDouble(double dub)
696 {
697 WriteJSONDouble(dub);
698 }
699
700 public override void WriteString(String str)
701 {
702 byte[] b = utf8Encoding.GetBytes(str);
703 WriteJSONString(b);
704 }
705
706 public override void WriteBinary(byte[] bin)
707 {
708 WriteJSONBase64(bin);
709 }
710
711 /**
712 * Reading methods.
713 */
714
715 ///<summary>
716 /// Read in a JSON string, unescaping as appropriate.. Skip Reading from the
717 /// context if skipContext is true.
718 ///</summary>
719 private byte[] ReadJSONString(bool skipContext)
720 {
721 MemoryStream buffer = new MemoryStream();
722
723
724 if (!skipContext)
725 {
726 context.Read();
727 }
728 ReadJSONSyntaxChar(QUOTE);
729 while (true)
730 {
731 byte ch = reader.Read();
732 if (ch == QUOTE[0])
733 {
734 break;
735 }
736 if (ch == ESCSEQ[0])
737 {
738 ch = reader.Read();
739 if (ch == ESCSEQ[1])
740 {
741 ReadJSONSyntaxChar(ZERO);
742 ReadJSONSyntaxChar(ZERO);
743 trans.ReadAll(tempBuffer, 0, 2);
744 ch = (byte)((HexVal((byte)tempBuffer[0]) << 4) + HexVal(tempBuffer[1]));
745 }
746 else
747 {
Jake Farrell83693532011-04-14 14:30:25 +0000748 int off = Array.IndexOf(ESCAPE_CHARS, (char)ch);
Bryan Duxburyfd32d792010-09-18 20:51:25 +0000749 if (off == -1)
750 {
751 throw new TProtocolException(TProtocolException.INVALID_DATA,
752 "Expected control char");
753 }
754 ch = ESCAPE_CHAR_VALS[off];
755 }
756 }
757 buffer.Write(new byte[] { (byte)ch }, 0, 1);
758 }
759 return buffer.ToArray();
760 }
761
762 ///<summary>
763 /// Return true if the given byte could be a valid part of a JSON number.
764 ///</summary>
765 private bool IsJSONNumeric(byte b)
766 {
767 switch (b)
768 {
769 case (byte)'+':
770 case (byte)'-':
771 case (byte)'.':
772 case (byte)'0':
773 case (byte)'1':
774 case (byte)'2':
775 case (byte)'3':
776 case (byte)'4':
777 case (byte)'5':
778 case (byte)'6':
779 case (byte)'7':
780 case (byte)'8':
781 case (byte)'9':
782 case (byte)'E':
783 case (byte)'e':
784 return true;
785 }
786 return false;
787 }
788
789 ///<summary>
790 /// Read in a sequence of characters that are all valid in JSON numbers. Does
791 /// not do a complete regex check to validate that this is actually a number.
792 ////</summary>
793 private String ReadJSONNumericChars()
794 {
795 StringBuilder strbld = new StringBuilder();
796 while (true)
797 {
798 byte ch = reader.Peek();
799 if (!IsJSONNumeric(ch))
800 {
801 break;
802 }
803 strbld.Append((char)reader.Read());
804 }
805 return strbld.ToString();
806 }
807
808 ///<summary>
809 /// Read in a JSON number. If the context dictates, Read in enclosing quotes.
810 ///</summary>
811 private long ReadJSONInteger()
812 {
813 context.Read();
814 if (context.EscapeNumbers())
815 {
816 ReadJSONSyntaxChar(QUOTE);
817 }
818 String str = ReadJSONNumericChars();
819 if (context.EscapeNumbers())
820 {
821 ReadJSONSyntaxChar(QUOTE);
822 }
823 try
824 {
825 return Int64.Parse(str);
826 }
827 catch (FormatException)
828 {
829 throw new TProtocolException(TProtocolException.INVALID_DATA,
830 "Bad data encounted in numeric data");
831 }
832 }
833
834 ///<summary>
835 /// Read in a JSON double value. Throw if the value is not wrapped in quotes
836 /// when expected or if wrapped in quotes when not expected.
837 ///</summary>
838 private double ReadJSONDouble()
839 {
840 context.Read();
841 if (reader.Peek() == QUOTE[0])
842 {
843 byte[] arr = ReadJSONString(true);
Roger Meier284a9b52011-12-08 13:39:56 +0000844 double dub = Double.Parse(utf8Encoding.GetString(arr,0,arr.Length), CultureInfo.InvariantCulture);
Bryan Duxburyfd32d792010-09-18 20:51:25 +0000845
846 if (!context.EscapeNumbers() && !Double.IsNaN(dub) &&
847 !Double.IsInfinity(dub))
848 {
849 // Throw exception -- we should not be in a string in this case
850 throw new TProtocolException(TProtocolException.INVALID_DATA,
851 "Numeric data unexpectedly quoted");
852 }
853 return dub;
854 }
855 else
856 {
857 if (context.EscapeNumbers())
858 {
859 // This will throw - we should have had a quote if escapeNum == true
860 ReadJSONSyntaxChar(QUOTE);
861 }
862 try
863 {
864 return Double.Parse(ReadJSONNumericChars());
865 }
866 catch (FormatException)
867 {
868 throw new TProtocolException(TProtocolException.INVALID_DATA,
869 "Bad data encounted in numeric data");
870 }
871 }
872 }
873
874 //<summary>
875 /// Read in a JSON string containing base-64 encoded data and decode it.
876 ///</summary>
877 private byte[] ReadJSONBase64()
878 {
879 byte[] b = ReadJSONString(false);
880 int len = b.Length;
881 int off = 0;
882 int size = 0;
883 while (len >= 4)
884 {
885 // Decode 4 bytes at a time
886 TBase64Utils.decode(b, off, 4, b, size); // NB: decoded in place
887 off += 4;
888 len -= 4;
889 size += 3;
890 }
891 // Don't decode if we hit the end or got a single leftover byte (invalid
892 // base64 but legal for skip of regular string type)
893 if (len > 1)
894 {
895 // Decode remainder
896 TBase64Utils.decode(b, off, len, b, size); // NB: decoded in place
897 size += len - 1;
898 }
899 // Sadly we must copy the byte[] (any way around this?)
900 byte[] result = new byte[size];
901 Array.Copy(b, 0, result, 0, size);
902 return result;
903 }
904
905 private void ReadJSONObjectStart()
906 {
907 context.Read();
908 ReadJSONSyntaxChar(LBRACE);
909 PushContext(new JSONPairContext(this));
910 }
911
912 private void ReadJSONObjectEnd()
913 {
914 ReadJSONSyntaxChar(RBRACE);
915 PopContext();
916 }
917
918 private void ReadJSONArrayStart()
919 {
920 context.Read();
921 ReadJSONSyntaxChar(LBRACKET);
922 PushContext(new JSONListContext(this));
923 }
924
925 private void ReadJSONArrayEnd()
926 {
927 ReadJSONSyntaxChar(RBRACKET);
928 PopContext();
929 }
930
931 public override TMessage ReadMessageBegin()
932 {
933 TMessage message = new TMessage();
934 ReadJSONArrayStart();
935 if (ReadJSONInteger() != VERSION)
936 {
937 throw new TProtocolException(TProtocolException.BAD_VERSION,
938 "Message contained bad version.");
939 }
940
Roger Meier284a9b52011-12-08 13:39:56 +0000941 var buf = ReadJSONString(false);
942 message.Name = utf8Encoding.GetString(buf,0,buf.Length);
Bryan Duxburyfd32d792010-09-18 20:51:25 +0000943 message.Type = (TMessageType)ReadJSONInteger();
944 message.SeqID = (int)ReadJSONInteger();
945 return message;
946 }
947
948 public override void ReadMessageEnd()
949 {
950 ReadJSONArrayEnd();
951 }
952
953 public override TStruct ReadStructBegin()
954 {
955 ReadJSONObjectStart();
956 return new TStruct();
957 }
958
959 public override void ReadStructEnd()
960 {
961 ReadJSONObjectEnd();
962 }
963
964 public override TField ReadFieldBegin()
965 {
966 TField field = new TField();
967 byte ch = reader.Peek();
968 if (ch == RBRACE[0])
969 {
970 field.Type = TType.Stop;
971 }
972 else
973 {
974 field.ID = (short)ReadJSONInteger();
975 ReadJSONObjectStart();
976 field.Type = GetTypeIDForTypeName(ReadJSONString(false));
977 }
978 return field;
979 }
980
981 public override void ReadFieldEnd()
982 {
983 ReadJSONObjectEnd();
984 }
985
986 public override TMap ReadMapBegin()
987 {
988 TMap map = new TMap();
989 ReadJSONArrayStart();
990 map.KeyType = GetTypeIDForTypeName(ReadJSONString(false));
991 map.ValueType = GetTypeIDForTypeName(ReadJSONString(false));
992 map.Count = (int)ReadJSONInteger();
993 ReadJSONObjectStart();
994 return map;
995 }
996
997 public override void ReadMapEnd()
998 {
999 ReadJSONObjectEnd();
1000 ReadJSONArrayEnd();
1001 }
1002
1003 public override TList ReadListBegin()
1004 {
1005 TList list = new TList();
1006 ReadJSONArrayStart();
1007 list.ElementType = GetTypeIDForTypeName(ReadJSONString(false));
1008 list.Count = (int)ReadJSONInteger();
1009 return list;
1010 }
1011
1012 public override void ReadListEnd()
1013 {
1014 ReadJSONArrayEnd();
1015 }
1016
1017 public override TSet ReadSetBegin()
1018 {
1019 TSet set = new TSet();
1020 ReadJSONArrayStart();
1021 set.ElementType = GetTypeIDForTypeName(ReadJSONString(false));
1022 set.Count = (int)ReadJSONInteger();
1023 return set;
1024 }
1025
1026 public override void ReadSetEnd()
1027 {
1028 ReadJSONArrayEnd();
1029 }
1030
1031 public override bool ReadBool()
1032 {
1033 return (ReadJSONInteger() == 0 ? false : true);
1034 }
1035
Jens Geyerf509df92013-04-25 20:38:55 +02001036 public override sbyte ReadByte()
Bryan Duxburyfd32d792010-09-18 20:51:25 +00001037 {
Jens Geyerf509df92013-04-25 20:38:55 +02001038 return (sbyte)ReadJSONInteger();
Bryan Duxburyfd32d792010-09-18 20:51:25 +00001039 }
1040
1041 public override short ReadI16()
1042 {
1043 return (short)ReadJSONInteger();
1044 }
1045
1046 public override int ReadI32()
1047 {
1048 return (int)ReadJSONInteger();
1049 }
1050
1051 public override long ReadI64()
1052 {
1053 return (long)ReadJSONInteger();
1054 }
1055
1056 public override double ReadDouble()
1057 {
1058 return ReadJSONDouble();
1059 }
1060
1061 public override String ReadString()
1062 {
Roger Meier284a9b52011-12-08 13:39:56 +00001063 var buf = ReadJSONString(false);
1064 return utf8Encoding.GetString(buf,0,buf.Length);
Bryan Duxburyfd32d792010-09-18 20:51:25 +00001065 }
1066
1067 public override byte[] ReadBinary()
1068 {
1069 return ReadJSONBase64();
1070 }
1071
1072 }
1073}