jsonhelpers.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2014 HPCC Systems.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. // jsonhelpers.hpp:
  14. //
  15. //////////////////////////////////////////////////////////////////////
  16. #pragma warning( disable : 4786)
  17. #ifndef _JSONHELPERS_HPP__
  18. #define _JSONHELPERS_HPP__
  19. #include "jliball.hpp"
  20. #include "wsexcept.hpp"
  21. #define REQSF_ROOT 0x0001
  22. #define REQSF_SAMPLE_DATA 0x0002
  23. #define REQSF_TRIM 0x0004
  24. #define REQSF_ESCAPEFORMATTERS 0x0008
  25. #define REQSF_EXCLUSIVE (REQSF_SAMPLE_DATA | REQSF_TRIM)
  26. namespace JsonHelpers
  27. {
  28. static StringBuffer &appendJSONExceptionItem(StringBuffer &s, int code, const char *msg, const char *objname="Exceptions", const char *arrayName = "Exception")
  29. {
  30. if (objname && *objname)
  31. appendJSONName(s, objname).append('{');
  32. if (arrayName && *arrayName)
  33. appendJSONName(s, arrayName).append('[');
  34. delimitJSON(s);
  35. s.append('{');
  36. appendJSONValue(s, "Code", code);
  37. appendJSONValue(s, "Message", msg);
  38. s.append('}');
  39. if (arrayName && *arrayName)
  40. s.append(']');
  41. if (objname && *objname)
  42. s.append('}');
  43. return s;
  44. }
  45. static StringBuffer &appendJSONException(StringBuffer &s, IException *e, const char *objname="Exceptions", const char *arrayName = "Exception")
  46. {
  47. if (!e)
  48. return s;
  49. StringBuffer temp;
  50. return appendJSONExceptionItem(s, e->errorCode(), e->errorMessage(temp).str(), objname, arrayName);
  51. }
  52. static StringBuffer &appendJSONException(StringBuffer &s, IWsException *e, const char *objname="Exceptions", const char *arrayName = "Exception")
  53. {
  54. if (!e)
  55. return s;
  56. StringBuffer temp;
  57. IArrayOf<IException>& exceptions = e->getArray();
  58. for (unsigned i = 0 ; i < exceptions.ordinality(); i++)
  59. {
  60. appendJSONExceptionItem(s, e->errorCode(), e->errorMessage(temp.clear()).str(), objname, arrayName);
  61. }
  62. return s;
  63. }
  64. static StringBuffer &appendJSONExceptions(StringBuffer &s, IMultiException *e, const char *objname="Exceptions", const char *arrayName = "Exception")
  65. {
  66. if (!e)
  67. return s;
  68. if (objname && *objname)
  69. appendJSONName(s, objname).append('{');
  70. if (arrayName && *arrayName)
  71. appendJSONName(s, arrayName).append('[');
  72. ForEachItemIn(i, *e)
  73. appendJSONException(s, &e->item(i), NULL, NULL);
  74. if (arrayName && *arrayName)
  75. s.append(']');
  76. if (objname && *objname)
  77. s.append('}');
  78. return s;
  79. }
  80. static IException *MakeJSONValueException(int code, const char *start, const char *pos, const char *tail, const char *intro="Invalid json format: ")
  81. {
  82. StringBuffer s(intro);
  83. s.append(pos-start, start).append('^').append(pos);
  84. if (tail && *tail)
  85. s.append(" - ").append(tail);
  86. return MakeStringException(code, "%s", s.str());
  87. }
  88. static inline StringBuffer &jsonNumericNext(StringBuffer &s, const char *&c, bool &allowDecimal, bool &allowExponent, const char *start)
  89. {
  90. if (isdigit(*c))
  91. s.append(*c++);
  92. else if ('.'==*c)
  93. {
  94. if (!allowDecimal || !allowExponent)
  95. throw MakeJSONValueException(-1, start, c, "Unexpected decimal");
  96. allowDecimal=false;
  97. s.append(*c++);
  98. }
  99. else if ('e'==*c || 'E'==*c)
  100. {
  101. if (!allowExponent)
  102. throw MakeJSONValueException(-1, start, c, "Unexpected exponent");
  103. allowDecimal=false;
  104. allowExponent=false;
  105. s.append(*c++);
  106. if ('-'==*c || '+'==*c)
  107. s.append(*c++);
  108. if (!isdigit(*c))
  109. throw MakeJSONValueException(-1, start, c, "Unexpected token");
  110. }
  111. else
  112. throw MakeJSONValueException(-1, start, c, "Unexpected token");
  113. return s;
  114. }
  115. static inline StringBuffer &jsonNumericStart(StringBuffer &s, const char *&c, const char *start)
  116. {
  117. if ('-'==*c)
  118. return jsonNumericStart(s.append(*c++), c, start);
  119. else if ('0'==*c)
  120. {
  121. s.append(*c++);
  122. if (*c && '.'!=*c)
  123. throw MakeJSONValueException(-1, start, c, "Unexpected token");
  124. }
  125. else if (isdigit(*c))
  126. s.append(*c++);
  127. else
  128. throw MakeJSONValueException(-1, start, c, "Unexpected token");
  129. return s;
  130. }
  131. static StringBuffer &appendJSONNumericString(StringBuffer &s, const char *value, bool allowDecimal)
  132. {
  133. if (!value || !*value)
  134. return s.append("null");
  135. bool allowExponent = allowDecimal;
  136. const char *pos = value;
  137. jsonNumericStart(s, pos, value);
  138. while (*pos)
  139. jsonNumericNext(s, pos, allowDecimal, allowExponent, value);
  140. return s;
  141. }
  142. typedef enum _JSONFieldCategory
  143. {
  144. JSONField_String,
  145. JSONField_Integer,
  146. JSONField_Real,
  147. JSONField_Boolean,
  148. JSONField_Present //true or remove
  149. } JSONField_Category;
  150. static JSONField_Category xsdTypeToJSONFieldCategory(const char *xsdtype)
  151. {
  152. //map XML Schema types used in ECL generated schemas to basic JSON formatting types
  153. if (streq(xsdtype, "integer") || streq(xsdtype, "nonNegativeInteger"))
  154. return JSONField_Integer;
  155. if (streq(xsdtype, "boolean"))
  156. return JSONField_Boolean;
  157. if (streq(xsdtype, "double"))
  158. return JSONField_Real;
  159. if (!strncmp(xsdtype, "decimal", 7)) //ecl creates derived types of the form decimal#_#
  160. return JSONField_Real;
  161. if (streq(xsdtype, "none")) //maps to an eml schema element with no type. set to true or don't add
  162. return JSONField_Present;
  163. return JSONField_String;
  164. }
  165. static void buildJsonAppendValue(IXmlType* type, StringBuffer& out, const char* tag, const char *value, unsigned flags)
  166. {
  167. JSONField_Category ct = xsdTypeToJSONFieldCategory(type->queryName());
  168. if (ct==JSONField_Present && (!value || !*value))
  169. return;
  170. if (tag && *tag)
  171. out.appendf("\"%s\": ", tag);
  172. StringBuffer sample;
  173. if ((!value || !*value) && (flags & REQSF_SAMPLE_DATA))
  174. {
  175. type->getSampleValue(sample, NULL);
  176. value = sample.str();
  177. }
  178. if (value)
  179. {
  180. switch (ct)
  181. {
  182. case JSONField_String:
  183. appendJSONValue(out, NULL, value);
  184. break;
  185. case JSONField_Integer:
  186. appendJSONNumericString(out, value, false);
  187. break;
  188. case JSONField_Real:
  189. appendJSONNumericString(out, value, true);
  190. break;
  191. case JSONField_Boolean:
  192. if (strieq(value, "default"))
  193. out.append("null");
  194. else
  195. appendJSONValue(out, NULL, strToBool(value));
  196. break;
  197. case JSONField_Present:
  198. appendJSONValue(out, NULL, true);
  199. break;
  200. }
  201. }
  202. else
  203. out.append("null");
  204. }
  205. static void buildJsonMsg(StringArray& parentTypes, IXmlType* type, StringBuffer& out, const char* tag, IPropertyTree *reqTree, unsigned flags)
  206. {
  207. assertex(type!=NULL);
  208. if (flags & REQSF_ROOT)
  209. out.append("{");
  210. const char* typeName = type->queryName();
  211. if (type->isComplexType())
  212. {
  213. if (typeName && !parentTypes.appendUniq(typeName))
  214. return; // recursive
  215. int startlen = out.length();
  216. if (tag)
  217. appendJSONName(out, tag);
  218. out.append('{');
  219. int taglen=out.length()+1;
  220. if (type->getSubType()==SubType_Complex_SimpleContent)
  221. {
  222. if (reqTree)
  223. {
  224. const char *attrval = reqTree->queryProp(NULL);
  225. out.appendf("\"%s\" ", (attrval) ? attrval : "");
  226. }
  227. else if (flags & REQSF_SAMPLE_DATA)
  228. {
  229. out.append("\"");
  230. type->queryFieldType(0)->getSampleValue(out,tag);
  231. out.append("\" ");
  232. }
  233. }
  234. else
  235. {
  236. int flds = type->getFieldCount();
  237. for (int idx=0; idx<flds; idx++)
  238. {
  239. delimitJSON(out);
  240. IPropertyTree *childtree = NULL;
  241. const char *childname = type->queryFieldName(idx);
  242. if (reqTree)
  243. childtree = reqTree->queryPropTree(childname);
  244. buildJsonMsg(parentTypes, type->queryFieldType(idx), out, childname, childtree, flags & ~REQSF_ROOT);
  245. }
  246. }
  247. if (typeName)
  248. parentTypes.pop();
  249. out.append("}");
  250. }
  251. else if (type->isArray())
  252. {
  253. if (typeName && !parentTypes.appendUniq(typeName))
  254. return; // recursive
  255. const char* itemName = type->queryFieldName(0);
  256. IXmlType* itemType = type->queryFieldType(0);
  257. if (!itemName || !itemType)
  258. throw MakeStringException(-1,"*** Invalid array definition: tag=%s, itemName=%s", tag, itemName?itemName:"NULL");
  259. int startlen = out.length();
  260. if (tag)
  261. out.appendf("\"%s\": ", tag);
  262. out.append('{');
  263. out.appendf("\"%s\": [", itemName);
  264. int taglen=out.length();
  265. if (reqTree)
  266. {
  267. Owned<IPropertyTreeIterator> items = reqTree->getElements(itemName);
  268. ForEach(*items)
  269. buildJsonMsg(parentTypes, itemType, delimitJSON(out), NULL, &items->query(), flags & ~REQSF_ROOT);
  270. }
  271. else
  272. buildJsonMsg(parentTypes, itemType, out, NULL, NULL, flags & ~REQSF_ROOT);
  273. out.append(']');
  274. if (typeName)
  275. parentTypes.pop();
  276. out.append("}");
  277. }
  278. else // simple type
  279. {
  280. const char *parmval = (reqTree) ? reqTree->queryProp(NULL) : NULL;
  281. buildJsonAppendValue(type, out, tag, parmval, flags);
  282. }
  283. if (flags & REQSF_ROOT)
  284. out.append('}');
  285. }
  286. };
  287. #endif // _JSONHELPERS_HPP__