jsonhelpers.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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. #define REQSF_ROOT 0x0001
  21. #define REQSF_SAMPLE_DATA 0x0002
  22. #define REQSF_TRIM 0x0004
  23. #define REQSF_ESCAPEFORMATTERS 0x0008
  24. #define REQSF_EXCLUSIVE (REQSF_SAMPLE_DATA | REQSF_TRIM)
  25. class JsonHelpers
  26. {
  27. public:
  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 (int i = 0 ; i < exceptions.ordinality(); i++)
  59. {
  60. appendJSONExceptionItem(s, e->errorCode(), e->errorMessage(temp).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 const char *nextParameterTag(StringBuffer &tag, const char *path)
  206. {
  207. while (*path=='.')
  208. path++;
  209. const char *finger = strchr(path, '.');
  210. if (finger)
  211. {
  212. tag.clear().append(finger - path, path);
  213. finger++;
  214. }
  215. else
  216. tag.set(path);
  217. return finger;
  218. }
  219. static void ensureParameter(IPropertyTree *pt, StringBuffer &tag, const char *path, const char *value, const char *fullpath)
  220. {
  221. if (!tag.length())
  222. return;
  223. unsigned idx = 1;
  224. if (path && isdigit(*path))
  225. {
  226. StringBuffer pos;
  227. path = nextParameterTag(pos, path);
  228. idx = (unsigned) atoi(pos.str())+1;
  229. if (idx>25) //adf
  230. throw MakeStringException(-1, "Array items above 25 not supported in HPCC WS HTTP parameters: %s", fullpath);
  231. }
  232. if (tag.charAt(tag.length()-1)=='$')
  233. {
  234. if (path && *path)
  235. throw MakeStringException(-1, "'$' not allowed in parent node of parameter path: %s", fullpath);
  236. tag.setLength(tag.length()-1);
  237. StringArray values;
  238. values.appendList(value, "\r");
  239. ForEachItemIn(pos, values)
  240. {
  241. const char *itemValue = values.item(pos);
  242. while (*itemValue=='\n')
  243. itemValue++;
  244. pt->addProp(tag, itemValue);
  245. }
  246. return;
  247. }
  248. unsigned count = pt->getCount(tag);
  249. while (count++ < idx)
  250. pt->addPropTree(tag, createPTree(tag));
  251. StringBuffer xpath(tag);
  252. xpath.append('[').append(idx).append(']');
  253. pt = pt->queryPropTree(xpath);
  254. if (!path || !*path)
  255. {
  256. pt->setProp(NULL, value);
  257. return;
  258. }
  259. StringBuffer nextTag;
  260. path = nextParameterTag(nextTag, path);
  261. ensureParameter(pt, nextTag, path, value, fullpath);
  262. }
  263. static void ensureParameter(IPropertyTree *pt, const char *path, const char *value)
  264. {
  265. const char *fullpath = path;
  266. StringBuffer tag;
  267. path = nextParameterTag(tag, path);
  268. ensureParameter(pt, tag, path, value, fullpath);
  269. }
  270. static IPropertyTree *createPTreeFromHttpParameters(const char *name, IProperties *parameters)
  271. {
  272. Owned<IPropertyTree> pt = createPTree(name);
  273. Owned<IPropertyIterator> props = parameters->getIterator();
  274. ForEach(*props)
  275. {
  276. const char *key = props->getPropKey();
  277. const char *value = parameters->queryProp(key);
  278. ensureParameter(pt, key, value);
  279. }
  280. return pt.getClear();
  281. }
  282. };
  283. #endif // _JSONHELPERS_HPP__