jsonhelpers.hpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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. class HttpParamHelpers
  27. {
  28. public:
  29. static void ensureParameter(IPropertyTree *pt, StringBuffer &tag, const char *path, const char *value, const char *fullpath)
  30. {
  31. if (!tag.length())
  32. return;
  33. unsigned idx = 1;
  34. if (path && isdigit(*path))
  35. {
  36. StringBuffer pos;
  37. path = nextParameterTag(pos, path);
  38. idx = (unsigned) atoi(pos.str())+1;
  39. if (idx>25) //adf
  40. throw MakeStringException(-1, "Array items above 25 not supported in HPCC WS HTTP parameters: %s", fullpath);
  41. }
  42. if (tag.charAt(tag.length()-1)=='$')
  43. {
  44. if (path && *path)
  45. throw MakeStringException(-1, "'$' not allowed in parent node of parameter path: %s", fullpath);
  46. tag.setLength(tag.length()-1);
  47. StringArray values;
  48. values.appendList(value, "\r");
  49. ForEachItemIn(pos, values)
  50. {
  51. const char *itemValue = values.item(pos);
  52. while (*itemValue=='\n')
  53. itemValue++;
  54. pt->addProp(tag, itemValue);
  55. }
  56. return;
  57. }
  58. unsigned count = pt->getCount(tag);
  59. while (count++ < idx)
  60. pt->addPropTree(tag, createPTree(tag));
  61. StringBuffer xpath(tag);
  62. xpath.append('[').append(idx).append(']');
  63. pt = pt->queryPropTree(xpath);
  64. if (!path || !*path)
  65. {
  66. pt->setProp(NULL, value);
  67. return;
  68. }
  69. StringBuffer nextTag;
  70. path = nextParameterTag(nextTag, path);
  71. ensureParameter(pt, nextTag, path, value, fullpath);
  72. }
  73. static void ensureParameter(IPropertyTree *pt, const char *path, const char *value)
  74. {
  75. const char *fullpath = path;
  76. StringBuffer tag;
  77. path = nextParameterTag(tag, path);
  78. ensureParameter(pt, tag, path, value, fullpath);
  79. }
  80. static IPropertyTree *createPTreeFromHttpParameters(const char *name, IProperties *parameters)
  81. {
  82. Owned<IPropertyTree> pt = createPTree(name);
  83. Owned<IPropertyIterator> props = parameters->getIterator();
  84. ForEach(*props)
  85. {
  86. const char *key = props->getPropKey();
  87. const char *value = parameters->queryProp(key);
  88. ensureParameter(pt, key, value);
  89. }
  90. return pt.getClear();
  91. }
  92. static const char *nextParameterTag(StringBuffer &tag, const char *path)
  93. {
  94. while (*path=='.')
  95. path++;
  96. const char *finger = strchr(path, '.');
  97. if (finger)
  98. {
  99. tag.clear().append(finger - path, path);
  100. finger++;
  101. }
  102. else
  103. tag.set(path);
  104. return finger;
  105. }
  106. };
  107. class JsonHelpers
  108. {
  109. public:
  110. static StringBuffer &appendJSONExceptionItem(StringBuffer &s, int code, const char *msg, const char *objname="Exceptions", const char *arrayName = "Exception")
  111. {
  112. if (objname && *objname)
  113. appendJSONName(s, objname).append('{');
  114. if (arrayName && *arrayName)
  115. appendJSONName(s, arrayName).append('[');
  116. delimitJSON(s);
  117. s.append('{');
  118. appendJSONValue(s, "Code", code);
  119. appendJSONValue(s, "Message", msg);
  120. s.append('}');
  121. if (arrayName && *arrayName)
  122. s.append(']');
  123. if (objname && *objname)
  124. s.append('}');
  125. return s;
  126. }
  127. static StringBuffer &appendJSONException(StringBuffer &s, IException *e, const char *objname="Exceptions", const char *arrayName = "Exception")
  128. {
  129. if (!e)
  130. return s;
  131. StringBuffer temp;
  132. return appendJSONExceptionItem(s, e->errorCode(), e->errorMessage(temp).str(), objname, arrayName);
  133. }
  134. static StringBuffer &appendJSONException(StringBuffer &s, IWsException *e, const char *objname="Exceptions", const char *arrayName = "Exception")
  135. {
  136. if (!e)
  137. return s;
  138. StringBuffer temp;
  139. IArrayOf<IException>& exceptions = e->getArray();
  140. for (int i = 0 ; i < exceptions.ordinality(); i++)
  141. {
  142. appendJSONExceptionItem(s, e->errorCode(), e->errorMessage(temp.clear()).str(), objname, arrayName);
  143. }
  144. return s;
  145. }
  146. static StringBuffer &appendJSONExceptions(StringBuffer &s, IMultiException *e, const char *objname="Exceptions", const char *arrayName = "Exception")
  147. {
  148. if (!e)
  149. return s;
  150. if (objname && *objname)
  151. appendJSONName(s, objname).append('{');
  152. if (arrayName && *arrayName)
  153. appendJSONName(s, arrayName).append('[');
  154. ForEachItemIn(i, *e)
  155. appendJSONException(s, &e->item(i), NULL, NULL);
  156. if (arrayName && *arrayName)
  157. s.append(']');
  158. if (objname && *objname)
  159. s.append('}');
  160. return s;
  161. }
  162. static IException *MakeJSONValueException(int code, const char *start, const char *pos, const char *tail, const char *intro="Invalid json format: ")
  163. {
  164. StringBuffer s(intro);
  165. s.append(pos-start, start).append('^').append(pos);
  166. if (tail && *tail)
  167. s.append(" - ").append(tail);
  168. return MakeStringException(code, "%s", s.str());
  169. }
  170. static inline StringBuffer &jsonNumericNext(StringBuffer &s, const char *&c, bool &allowDecimal, bool &allowExponent, const char *start)
  171. {
  172. if (isdigit(*c))
  173. s.append(*c++);
  174. else if ('.'==*c)
  175. {
  176. if (!allowDecimal || !allowExponent)
  177. throw MakeJSONValueException(-1, start, c, "Unexpected decimal");
  178. allowDecimal=false;
  179. s.append(*c++);
  180. }
  181. else if ('e'==*c || 'E'==*c)
  182. {
  183. if (!allowExponent)
  184. throw MakeJSONValueException(-1, start, c, "Unexpected exponent");
  185. allowDecimal=false;
  186. allowExponent=false;
  187. s.append(*c++);
  188. if ('-'==*c || '+'==*c)
  189. s.append(*c++);
  190. if (!isdigit(*c))
  191. throw MakeJSONValueException(-1, start, c, "Unexpected token");
  192. }
  193. else
  194. throw MakeJSONValueException(-1, start, c, "Unexpected token");
  195. return s;
  196. }
  197. static inline StringBuffer &jsonNumericStart(StringBuffer &s, const char *&c, const char *start)
  198. {
  199. if ('-'==*c)
  200. return jsonNumericStart(s.append(*c++), c, start);
  201. else if ('0'==*c)
  202. {
  203. s.append(*c++);
  204. if (*c && '.'!=*c)
  205. throw MakeJSONValueException(-1, start, c, "Unexpected token");
  206. }
  207. else if (isdigit(*c))
  208. s.append(*c++);
  209. else
  210. throw MakeJSONValueException(-1, start, c, "Unexpected token");
  211. return s;
  212. }
  213. static StringBuffer &appendJSONNumericString(StringBuffer &s, const char *value, bool allowDecimal)
  214. {
  215. if (!value || !*value)
  216. return s.append("null");
  217. bool allowExponent = allowDecimal;
  218. const char *pos = value;
  219. jsonNumericStart(s, pos, value);
  220. while (*pos)
  221. jsonNumericNext(s, pos, allowDecimal, allowExponent, value);
  222. return s;
  223. }
  224. typedef enum _JSONFieldCategory
  225. {
  226. JSONField_String,
  227. JSONField_Integer,
  228. JSONField_Real,
  229. JSONField_Boolean,
  230. JSONField_Present //true or remove
  231. } JSONField_Category;
  232. static JSONField_Category xsdTypeToJSONFieldCategory(const char *xsdtype)
  233. {
  234. //map XML Schema types used in ECL generated schemas to basic JSON formatting types
  235. if (streq(xsdtype, "integer") || streq(xsdtype, "nonNegativeInteger"))
  236. return JSONField_Integer;
  237. if (streq(xsdtype, "boolean"))
  238. return JSONField_Boolean;
  239. if (streq(xsdtype, "double"))
  240. return JSONField_Real;
  241. if (!strncmp(xsdtype, "decimal", 7)) //ecl creates derived types of the form decimal#_#
  242. return JSONField_Real;
  243. if (streq(xsdtype, "none")) //maps to an eml schema element with no type. set to true or don't add
  244. return JSONField_Present;
  245. return JSONField_String;
  246. }
  247. static void buildJsonAppendValue(IXmlType* type, StringBuffer& out, const char* tag, const char *value, unsigned flags)
  248. {
  249. JSONField_Category ct = xsdTypeToJSONFieldCategory(type->queryName());
  250. if (ct==JSONField_Present && (!value || !*value))
  251. return;
  252. if (tag && *tag)
  253. out.appendf("\"%s\": ", tag);
  254. StringBuffer sample;
  255. if ((!value || !*value) && (flags & REQSF_SAMPLE_DATA))
  256. {
  257. type->getSampleValue(sample, NULL);
  258. value = sample.str();
  259. }
  260. if (value)
  261. {
  262. switch (ct)
  263. {
  264. case JSONField_String:
  265. appendJSONValue(out, NULL, value);
  266. break;
  267. case JSONField_Integer:
  268. appendJSONNumericString(out, value, false);
  269. break;
  270. case JSONField_Real:
  271. appendJSONNumericString(out, value, true);
  272. break;
  273. case JSONField_Boolean:
  274. if (strieq(value, "default"))
  275. out.append("null");
  276. else
  277. appendJSONValue(out, NULL, strToBool(value));
  278. break;
  279. case JSONField_Present:
  280. appendJSONValue(out, NULL, true);
  281. break;
  282. }
  283. }
  284. else
  285. out.append("null");
  286. }
  287. static void buildJsonMsg(StringArray& parentTypes, IXmlType* type, StringBuffer& out, const char* tag, IPropertyTree *reqTree, unsigned flags)
  288. {
  289. assertex(type!=NULL);
  290. if (flags & REQSF_ROOT)
  291. out.append("{");
  292. const char* typeName = type->queryName();
  293. if (type->isComplexType())
  294. {
  295. if (typeName && !parentTypes.appendUniq(typeName))
  296. return; // recursive
  297. int startlen = out.length();
  298. if (tag)
  299. appendJSONName(out, tag);
  300. out.append('{');
  301. int taglen=out.length()+1;
  302. if (type->getSubType()==SubType_Complex_SimpleContent)
  303. {
  304. if (reqTree)
  305. {
  306. const char *attrval = reqTree->queryProp(NULL);
  307. out.appendf("\"%s\" ", (attrval) ? attrval : "");
  308. }
  309. else if (flags & REQSF_SAMPLE_DATA)
  310. {
  311. out.append("\"");
  312. type->queryFieldType(0)->getSampleValue(out,tag);
  313. out.append("\" ");
  314. }
  315. }
  316. else
  317. {
  318. int flds = type->getFieldCount();
  319. for (int idx=0; idx<flds; idx++)
  320. {
  321. delimitJSON(out);
  322. IPropertyTree *childtree = NULL;
  323. const char *childname = type->queryFieldName(idx);
  324. if (reqTree)
  325. childtree = reqTree->queryPropTree(childname);
  326. buildJsonMsg(parentTypes, type->queryFieldType(idx), out, childname, childtree, flags & ~REQSF_ROOT);
  327. }
  328. }
  329. if (typeName)
  330. parentTypes.pop();
  331. out.append("}");
  332. }
  333. else if (type->isArray())
  334. {
  335. if (typeName && !parentTypes.appendUniq(typeName))
  336. return; // recursive
  337. const char* itemName = type->queryFieldName(0);
  338. IXmlType* itemType = type->queryFieldType(0);
  339. if (!itemName || !itemType)
  340. throw MakeStringException(-1,"*** Invalid array definition: tag=%s, itemName=%s", tag, itemName?itemName:"NULL");
  341. int startlen = out.length();
  342. if (tag)
  343. out.appendf("\"%s\": ", tag);
  344. out.append('{');
  345. out.appendf("\"%s\": [", itemName);
  346. int taglen=out.length();
  347. if (reqTree)
  348. {
  349. Owned<IPropertyTreeIterator> items = reqTree->getElements(itemName);
  350. ForEach(*items)
  351. buildJsonMsg(parentTypes, itemType, delimitJSON(out), NULL, &items->query(), flags & ~REQSF_ROOT);
  352. }
  353. else
  354. buildJsonMsg(parentTypes, itemType, out, NULL, NULL, flags & ~REQSF_ROOT);
  355. out.append(']');
  356. if (typeName)
  357. parentTypes.pop();
  358. out.append("}");
  359. }
  360. else // simple type
  361. {
  362. const char *parmval = (reqTree) ? reqTree->queryProp(NULL) : NULL;
  363. buildJsonAppendValue(type, out, tag, parmval, flags);
  364. }
  365. if (flags & REQSF_ROOT)
  366. out.append('}');
  367. }
  368. };
  369. #endif // _JSONHELPERS_HPP__