JSON.cpp 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378
  1. #include "JSON.h"
  2. #include "Datei.h"
  3. using namespace Framework;
  4. using namespace JSON;
  5. #pragma region JSONValue
  6. JSONValue::JSONValue()
  7. : ReferenceCounter()
  8. {
  9. this->type = JSONType::NULL_;
  10. }
  11. JSONValue::~JSONValue()
  12. {}
  13. JSONValue::JSONValue(JSONType type)
  14. : ReferenceCounter()
  15. {
  16. this->type = type;
  17. }
  18. JSONType JSONValue::getType() const
  19. {
  20. return type;
  21. }
  22. Text JSONValue::toString() const
  23. {
  24. return Text("null");
  25. }
  26. JSONValue* JSONValue::clone() const
  27. {
  28. return new JSONValue();
  29. }
  30. JSONBool* JSONValue::asBool() const
  31. {
  32. return (JSONBool*)this;
  33. }
  34. JSONNumber* JSONValue::asNumber() const
  35. {
  36. return (JSONNumber*)this;
  37. }
  38. JSONString* JSONValue::asString() const
  39. {
  40. return (JSONString*)this;
  41. }
  42. JSONArray* JSONValue::asArray() const
  43. {
  44. return (JSONArray*)this;
  45. }
  46. JSONObject* JSONValue::asObject() const
  47. {
  48. return (JSONObject*)this;
  49. }
  50. #pragma endregion Content
  51. #pragma region JSONBool
  52. JSONBool::JSONBool(bool b)
  53. : JSONValue(JSONType::BOOLEAN)
  54. {
  55. this->b = b;
  56. }
  57. bool JSONBool::getBool() const
  58. {
  59. return b;
  60. }
  61. Text JSONBool::toString() const
  62. {
  63. if (b)
  64. return Text("true");
  65. else
  66. return Text("false");
  67. }
  68. JSONValue* JSONBool::clone() const
  69. {
  70. return new JSONBool(b);
  71. }
  72. #pragma endregion Content
  73. #pragma region JSONNumber
  74. JSONNumber::JSONNumber(double num)
  75. : JSONValue(JSONType::NUMBER)
  76. {
  77. number = num;
  78. }
  79. double JSONNumber::getNumber() const
  80. {
  81. return number;
  82. }
  83. Text JSONNumber::toString() const
  84. {
  85. return Text(number);
  86. }
  87. JSONValue* JSONNumber::clone() const
  88. {
  89. return new JSONNumber(number);
  90. }
  91. #pragma endregion Content
  92. #pragma region JSONString
  93. JSONString::JSONString(Text string)
  94. : JSONValue(JSONType::STRING)
  95. {
  96. this->string = string;
  97. string.ersetzen("\\\"", "\"");
  98. }
  99. Text JSONString::getString() const
  100. {
  101. return string;
  102. }
  103. Text JSONString::toString() const
  104. {
  105. Text esc = string;
  106. esc.ersetzen("\"", "\\\"");
  107. return Text(Text("\"") += esc.getText()) += "\"";
  108. }
  109. JSONValue* JSONString::clone() const
  110. {
  111. return new JSONString(string);
  112. }
  113. #pragma endregion Content
  114. #pragma region JSONArray
  115. JSONArray::JSONArray()
  116. : JSONValue(JSONType::ARRAY)
  117. {
  118. array = new RCArray< JSONValue >();
  119. }
  120. JSONArray::JSONArray(Text string)
  121. : JSONValue(JSONType::ARRAY)
  122. {
  123. array = new RCArray< JSONValue >();
  124. string = Parser::removeWhitespace(string);
  125. if (string.getText()[0] == '[' && string.getText()[string.getLength() - 1] == ']')
  126. {
  127. string.remove(0, 1);
  128. string.remove(string.getLength() - 1, string.getLength());
  129. while (string.getLength())
  130. {
  131. int end = Parser::findObjectEndInArray(string);
  132. Text* objStr = string.getTeilText(0, end);
  133. string.remove(0, end + 1);
  134. array->add(Parser::getValue(*objStr));
  135. objStr->release();
  136. }
  137. }
  138. }
  139. JSONArray::JSONArray(const JSONArray& arr)
  140. : JSONValue(JSONType::ARRAY)
  141. {
  142. array = dynamic_cast<RCArray<JSONValue> *>(arr.array->getThis());
  143. }
  144. JSONArray::~JSONArray()
  145. {
  146. array->release();
  147. }
  148. JSONArray& JSONArray::operator=(const JSONArray& arr)
  149. {
  150. array->release();
  151. array = dynamic_cast<RCArray<JSONValue> *>(arr.array->getThis());
  152. return *this;
  153. }
  154. void JSONArray::addValue(JSONValue* value)
  155. {
  156. array->add(value);
  157. }
  158. void JSONArray::setValue(int i, JSONValue* value)
  159. {
  160. array->set(value, i);
  161. }
  162. void JSONArray::removeValue(int i)
  163. {
  164. array->remove(i);
  165. }
  166. JSONValue* JSONArray::getValue(int i) const
  167. {
  168. return array->get(i);
  169. }
  170. JSONValue* JSONArray::zValue(int i) const
  171. {
  172. return array->z(i);
  173. }
  174. int JSONArray::getLength() const
  175. {
  176. return array->getEintragAnzahl();
  177. }
  178. bool JSONArray::isValueOfType(int i, JSONType type) const
  179. {
  180. return i >= 0 && i < array->getEintragAnzahl() && array->z(i)->getType() == type;
  181. }
  182. Iterator< JSONValue* > JSONArray::begin() const
  183. {
  184. return array->begin();
  185. }
  186. Iterator< JSONValue* > JSONArray::end() const
  187. {
  188. return array->end();
  189. }
  190. Text JSONArray::toString() const
  191. {
  192. Text str = "[";
  193. for (auto i = array->begin(); i; i++)
  194. {
  195. str += i->toString();
  196. if (i.hasNext())
  197. str += ",";
  198. }
  199. str += "]";
  200. return str;
  201. }
  202. JSONValue* JSONArray::clone() const
  203. {
  204. return new JSONArray(toString());
  205. }
  206. #pragma endregion Content
  207. #pragma region JSONObject
  208. JSONObject::JSONObject()
  209. : JSONValue(JSONType::OBJECT)
  210. {
  211. fields = new Array< Text >();
  212. values = new RCArray< JSONValue >();
  213. }
  214. JSONObject::JSONObject(Text string)
  215. : JSONValue(JSONType::OBJECT)
  216. {
  217. fields = new Array< Text >();
  218. values = new RCArray< JSONValue >();
  219. string = Parser::removeWhitespace(string);
  220. if (string.getText()[0] == '{' && string.getText()[string.getLength() - 1] == '}')
  221. {
  222. string.remove(0, 1);
  223. string.remove(string.getLength() - 1, string.getLength());
  224. while (string.getLength())
  225. {
  226. int endField = Parser::findFieldEndInObject(string);
  227. Text* fieldName = string.getTeilText(0, endField);
  228. string.remove(0, endField + 1);
  229. fieldName->remove(0, 1);
  230. fieldName->remove(fieldName->getLength() - 1, fieldName->getLength());
  231. int endValue = Parser::findValueEndInObject(string);
  232. Text* value = string.getTeilText(0, endValue);
  233. string.remove(0, endValue + 1);
  234. fields->add(Text(fieldName->getText()));
  235. values->add(Parser::getValue(*value));
  236. fieldName->release();
  237. value->release();
  238. }
  239. }
  240. }
  241. JSONObject::JSONObject(const JSONObject& obj)
  242. : JSONValue(JSONType::OBJECT)
  243. {
  244. fields = dynamic_cast<Array<Text> *>(obj.fields->getThis());
  245. values = dynamic_cast<RCArray<JSONValue> *>(obj.values->getThis());
  246. }
  247. JSONObject::~JSONObject()
  248. {
  249. fields->release();
  250. values->release();
  251. }
  252. JSONObject& JSONObject::operator=(const JSONObject& obj)
  253. {
  254. fields->release();
  255. values->release();
  256. fields = dynamic_cast<Array<Text> *>(obj.fields->getThis());
  257. values = dynamic_cast<RCArray<JSONValue> *>(obj.values->getThis());
  258. return *this;
  259. }
  260. bool JSONObject::addValue(Text field, JSONValue* value)
  261. {
  262. if (hasValue(field))
  263. return 0;
  264. fields->add(field);
  265. values->add(value);
  266. return 1;
  267. }
  268. bool JSONObject::removeValue(Text field)
  269. {
  270. for (int i = 0; i < fields->getEintragAnzahl(); i++)
  271. {
  272. if (fields->get(i).istGleich(field))
  273. {
  274. fields->remove(i);
  275. values->remove(i);
  276. return 1;
  277. }
  278. }
  279. return 0;
  280. }
  281. bool JSONObject::hasValue(Text field)
  282. {
  283. for (int i = 0; i < fields->getEintragAnzahl(); i++)
  284. {
  285. if (fields->get(i).istGleich(field))
  286. return 1;
  287. }
  288. return 0;
  289. }
  290. JSONValue* JSONObject::getValue(Text field)
  291. {
  292. for (int i = 0; i < fields->getEintragAnzahl(); i++)
  293. {
  294. if (fields->get(i).istGleich(field))
  295. return values->get(i);
  296. }
  297. return 0;
  298. }
  299. JSONValue* JSONObject::zValue(Text field)
  300. {
  301. for (int i = 0; i < fields->getEintragAnzahl(); i++)
  302. {
  303. if (fields->get(i).istGleich(field))
  304. return values->z(i);
  305. }
  306. return 0;
  307. }
  308. Iterator< Text > JSONObject::getFields()
  309. {
  310. return fields->begin();
  311. }
  312. Iterator< JSONValue* > JSONObject::getValues()
  313. {
  314. return values->begin();
  315. }
  316. int JSONObject::getFieldCount() const
  317. {
  318. return fields->getEintragAnzahl();
  319. }
  320. bool JSONObject::isValueOfType(Text field, JSONType type) const
  321. {
  322. for (int i = 0; i < fields->getEintragAnzahl(); i++)
  323. {
  324. if (fields->get(i).istGleich(field))
  325. return values->z(i)->getType() == type;
  326. }
  327. return 0;
  328. }
  329. Text JSONObject::toString() const
  330. {
  331. Text str = "{";
  332. Iterator< Text > k = fields->begin();
  333. for (auto v = values->begin(); k && v; k++, v++)
  334. {
  335. str += "\"";
  336. str += k._.getText();
  337. str += "\":";
  338. str += v->toString().getText();
  339. if (v.hasNext())
  340. str += ",";
  341. }
  342. str += "}";
  343. return str;
  344. }
  345. JSONValue* JSONObject::clone() const
  346. {
  347. return new JSONObject(toString());
  348. }
  349. #pragma endregion Content
  350. JSONValue* JSON::loadJSONFromFile(Text path)
  351. {
  352. Datei d;
  353. d.setDatei(path);
  354. d.open(Datei::Style::lesen);
  355. int size = (int)d.getSize();
  356. char* buffer = new char[size + 1];
  357. buffer[size] = 0;
  358. d.lese(buffer, size);
  359. d.close();
  360. JSONValue* result = Parser::getValue(buffer);
  361. delete[] buffer;
  362. return result;
  363. }
  364. #pragma region Parser
  365. int Parser::findObjectEndInArray(const char* str)
  366. {
  367. return findValueEndInObject(str);
  368. }
  369. Text Parser::removeWhitespace(const char* str)
  370. {
  371. int wsc = 0;
  372. int i = 0;
  373. bool esc = 0;
  374. bool strO = 0;
  375. for (; str[i]; i++)
  376. {
  377. switch (str[i])
  378. {
  379. case '\\':
  380. if (strO)
  381. esc = !esc;
  382. else
  383. esc = 0;
  384. break;
  385. case '"':
  386. if (!esc)
  387. strO = !strO;
  388. esc = 0;
  389. break;
  390. case ' ':
  391. case '\n':
  392. case '\t':
  393. case '\r':
  394. if (!strO)
  395. wsc++;
  396. esc = 0;
  397. break;
  398. default:
  399. esc = 0;
  400. break;
  401. }
  402. }
  403. Text ret;
  404. ret.fillText(' ', i - wsc);
  405. i = 0;
  406. esc = 0;
  407. strO = 0;
  408. int index = 0;
  409. for (; str[i]; i++)
  410. {
  411. switch (str[i])
  412. {
  413. case '\\':
  414. if (strO)
  415. esc = !esc;
  416. else
  417. esc = 0;
  418. ret.getText()[index++] = str[i];
  419. break;
  420. case '"':
  421. if (!esc)
  422. strO = !strO;
  423. esc = 0;
  424. ret.getText()[index++] = str[i];
  425. break;
  426. case ' ':
  427. case '\n':
  428. case '\t':
  429. case '\r':
  430. if (strO)
  431. ret.getText()[index++] = str[i];
  432. esc = 0;
  433. break;
  434. default:
  435. ret.getText()[index++] = str[i];
  436. esc = 0;
  437. break;
  438. }
  439. }
  440. return ret;
  441. }
  442. JSONValue* Parser::getValue(const char* str)
  443. {
  444. Text string = Parser::removeWhitespace(str);
  445. if (string.istGleich("true"))
  446. return new JSONBool(1);
  447. if (string.istGleich("false"))
  448. return new JSONBool(0);
  449. if (string.getText()[0] == '"')
  450. {
  451. string.remove(0, 1);
  452. string.remove(string.getLength() - 1, string.getLength());
  453. return new JSONString(string);
  454. }
  455. if (string.getText()[0] == '[')
  456. return new JSONArray(string);
  457. if (string.getText()[0] == '{')
  458. return new JSONObject(string);
  459. if (Text((int)string).istGleich(string.getText()))
  460. return new JSONNumber(string);
  461. if (string.anzahlVon('.') == 1)
  462. {
  463. bool isNumber = 1;
  464. for (char* c = (*string.getText() == '-') ? string.getText() + 1 : string.getText(); *c; c++)
  465. isNumber &= (*c >= '0' && *c <= '9') || *c == '.';
  466. if (isNumber)
  467. return new JSONNumber(string);
  468. }
  469. return new JSONValue();
  470. }
  471. int Parser::findFieldEndInObject(const char* str)
  472. {
  473. int i = 0;
  474. bool esc = 0;
  475. bool strO = 0;
  476. int objOc = 0;
  477. int arrayOc = 0;
  478. for (; str[i]; i++)
  479. {
  480. switch (str[i])
  481. {
  482. case '\\':
  483. if (strO)
  484. esc = !esc;
  485. else
  486. esc = 0;
  487. break;
  488. case '"':
  489. if (!esc)
  490. strO = !strO;
  491. esc = 0;
  492. break;
  493. case '[':
  494. if (!strO)
  495. arrayOc++;
  496. esc = 0;
  497. break;
  498. case ']':
  499. if (!strO)
  500. arrayOc--;
  501. esc = 0;
  502. break;
  503. case '{':
  504. if (!strO)
  505. objOc++;
  506. esc = 0;
  507. break;
  508. case '}':
  509. if (!strO)
  510. objOc--;
  511. esc = 0;
  512. break;
  513. case ':':
  514. if (!strO && objOc == 0 && arrayOc == 0)
  515. return i;
  516. esc = 0;
  517. break;
  518. default:
  519. esc = 0;
  520. break;
  521. }
  522. }
  523. return i;
  524. }
  525. int Parser::findValueEndInObject(const char* str)
  526. {
  527. int i = 0;
  528. bool esc = 0;
  529. bool strO = 0;
  530. int objOc = 0;
  531. int arrayOc = 0;
  532. for (; str[i]; i++)
  533. {
  534. switch (str[i])
  535. {
  536. case '\\':
  537. if (strO)
  538. esc = !esc;
  539. else
  540. esc = 0;
  541. break;
  542. case '"':
  543. if (!esc)
  544. strO = !strO;
  545. esc = 0;
  546. break;
  547. case '[':
  548. if (!strO)
  549. arrayOc++;
  550. esc = 0;
  551. break;
  552. case ']':
  553. if (!strO)
  554. arrayOc--;
  555. esc = 0;
  556. break;
  557. case '{':
  558. if (!strO)
  559. objOc++;
  560. esc = 0;
  561. break;
  562. case '}':
  563. if (!strO)
  564. objOc--;
  565. esc = 0;
  566. break;
  567. case ',':
  568. if (!strO && objOc == 0 && arrayOc == 0)
  569. return i;
  570. esc = 0;
  571. break;
  572. default:
  573. esc = 0;
  574. break;
  575. }
  576. }
  577. return i;
  578. }
  579. #pragma endregion Content
  580. using namespace Validator;
  581. #pragma region JSONValidationResult
  582. JSONValidationResult::JSONValidationResult()
  583. : ReferenceCounter()
  584. {}
  585. JSONValidationResult::~JSONValidationResult() {}
  586. #pragma region JSONTypeMissmatch
  587. JSONTypeMissmatch::JSONTypeMissmatch(Text path, JSONValue* foundValue, XML::Element* expected, JSONValidationResult* reason)
  588. : JSONValidationResult()
  589. {
  590. this->path = path;
  591. this->foundValue = foundValue;
  592. this->expected = expected;
  593. this->reason = reason;
  594. }
  595. JSONTypeMissmatch::~JSONTypeMissmatch()
  596. {
  597. foundValue->release();
  598. expected->release();
  599. if (reason)
  600. reason->release();
  601. }
  602. bool JSONTypeMissmatch::isValid() const
  603. {
  604. return 0;
  605. }
  606. void JSONTypeMissmatch::printInvalidInfo(int indent) const
  607. {
  608. Text ind = "";
  609. ind.fillText(' ', indent);
  610. std::cout << ind.getText() << "Type missmatch at path '" << path.getText() << "'. JSON Value\n" << ind.getText() << foundValue->toString().getText() << "\n" << ind.getText() << "does not match type\n" << ind.getText() << expected->toString().getText() << "\n";
  611. if (reason)
  612. {
  613. std::cout << ind.getText() << "Reason for type mismatch:\n";
  614. reason->printInvalidInfo(indent + 4);
  615. }
  616. }
  617. JSONValue* JSONTypeMissmatch::getValidPart() const
  618. {
  619. if (reason)
  620. {
  621. JSONValue* valid = reason->getValidPart();
  622. Text* p = reason->getPath().getTeilText(path.getLength());
  623. if (foundValue->getType() == JSONType::ARRAY)
  624. {
  625. if (!valid && (!expected->hasAttribute("removeInvalidEntries") || !expected->getAttributeValue("removeInvalidEntries").istGleich("true")))
  626. {
  627. p->release();
  628. return 0;
  629. }
  630. if (p->hatAt(0, "[") && p->hatAt(p->getLength() - 1, "]"))
  631. {
  632. Text* it = p->getTeilText(1, p->getLength() - 1);
  633. int i = *it;
  634. it->release();
  635. if (i >= 0 && foundValue->asArray()->getLength() > i)
  636. {
  637. JSONValue* tmp = foundValue->clone();
  638. if (valid)
  639. tmp->asArray()->setValue(i, valid);
  640. else
  641. tmp->asArray()->removeValue(i);
  642. JSONValidationResult* res = JSONValidator(dynamic_cast<XML::Element*>(expected->getThis())).validate(tmp);
  643. if (res->isValid())
  644. {
  645. res->release();
  646. p->release();
  647. return tmp;
  648. }
  649. else if (res->isDifferent(this, path) || !valid)
  650. {
  651. p->release();
  652. tmp->release();
  653. JSONValue* result = res->getValidPart();
  654. res->release();
  655. return result;
  656. }
  657. tmp->release();
  658. res->release();
  659. }
  660. }
  661. }
  662. else if (foundValue->getType() == JSONType::OBJECT)
  663. {
  664. if (!valid && (!expected->hasAttribute("removeInvalidEntries") || !expected->getAttributeValue("removeInvalidEntries").istGleich("true")))
  665. {
  666. p->release();
  667. return 0;
  668. }
  669. if (p->hatAt(0, "."))
  670. {
  671. Text* at = p->getTeilText(1);
  672. Text attr = *at;
  673. at->release();
  674. JSONValue* tmp = foundValue->clone();
  675. tmp->asObject()->removeValue(attr);
  676. if (valid)
  677. tmp->asObject()->addValue(attr, valid);
  678. JSONValidationResult* res = JSONValidator(dynamic_cast<XML::Element*>(expected->getThis())).validate(tmp);
  679. if (res->isValid())
  680. {
  681. res->release();
  682. p->release();
  683. return tmp;
  684. }
  685. else if (res->isDifferent(this, path) || !valid)
  686. {
  687. p->release();
  688. tmp->release();
  689. JSONValue* result = res->getValidPart();
  690. res->release();
  691. return result;
  692. }
  693. tmp->release();
  694. res->release();
  695. }
  696. }
  697. p->release();
  698. if (valid)
  699. valid->release();
  700. }
  701. return 0;
  702. }
  703. Text JSONTypeMissmatch::getPath() const
  704. {
  705. return path;
  706. }
  707. bool JSONTypeMissmatch::isDifferent(const JSONValidationResult* zResult, Text additionalPath) const
  708. {
  709. const JSONTypeMissmatch* casted = dynamic_cast<const JSONTypeMissmatch*>(zResult);
  710. if (casted == 0)
  711. return 1;
  712. if (!casted->getPath().istGleich(additionalPath + path))
  713. return 1;
  714. return reason->isDifferent(casted->reason, path);
  715. }
  716. #pragma endregion Content
  717. #pragma region JSONUnknownValue
  718. JSONUnknownValue::JSONUnknownValue(Text path, JSONValue* foundValue)
  719. : JSONValidationResult()
  720. {
  721. this->path = path;
  722. this->foundValue = foundValue;
  723. }
  724. JSONUnknownValue::~JSONUnknownValue()
  725. {
  726. foundValue->release();
  727. }
  728. bool JSONUnknownValue::isValid() const
  729. {
  730. return 0;
  731. }
  732. void JSONUnknownValue::printInvalidInfo(int indent) const
  733. {
  734. Text ind = "";
  735. ind.fillText(' ', indent);
  736. std::cout << ind.getText() << "Unknown Value at '" << path.getText() << "'. Value found:\n" << ind.getText() << foundValue->toString().getText() << "\n";
  737. }
  738. JSONValue* JSONUnknownValue::getValidPart() const
  739. {
  740. return 0;
  741. }
  742. Text JSONUnknownValue::getPath() const
  743. {
  744. return path;
  745. }
  746. bool JSONUnknownValue::isDifferent(const JSONValidationResult* zResult, Text additionalPath) const
  747. {
  748. const JSONUnknownValue* casted = dynamic_cast<const JSONUnknownValue*>(zResult);
  749. if (casted == 0)
  750. return 1;
  751. if (!casted->getPath().istGleich(additionalPath + path))
  752. return 1;
  753. return 0;
  754. }
  755. #pragma endregion Content
  756. #pragma region JSONMissingValue
  757. JSONMissingValue::JSONMissingValue(Text path, XML::Element* expected)
  758. : JSONValidationResult()
  759. {
  760. this->path = path;
  761. this->expected = expected;
  762. }
  763. JSONMissingValue::~JSONMissingValue()
  764. {
  765. expected->release();
  766. }
  767. bool JSONMissingValue::isValid() const
  768. {
  769. return 0;
  770. }
  771. void JSONMissingValue::printInvalidInfo(int indent) const
  772. {
  773. Text ind = "";
  774. ind.fillText(' ', indent);
  775. std::cout << ind.getText() << "Missing Value at '" << path.getText() << "'. Expected type:\n" << ind.getText() << expected->toString().getText() << "\n";
  776. }
  777. JSONValue* JSONMissingValue::getValidPart() const
  778. {
  779. if (expected->hasAttribute("default"))
  780. {
  781. JSONValue* def = Parser::getValue(expected->getAttributeValue("default"));
  782. JSONValidationResult* res = JSONValidator(dynamic_cast<XML::Element*>(expected->getThis())).validate(def);
  783. if (res->isValid())
  784. {
  785. res->release();
  786. return def;
  787. }
  788. else if (res->isDifferent(this, path))
  789. {
  790. def->release();
  791. JSONValue* result = res->getValidPart();
  792. res->release();
  793. return result;
  794. }
  795. def->release();
  796. }
  797. return 0;
  798. }
  799. Text JSONMissingValue::getPath() const
  800. {
  801. return path;
  802. }
  803. bool JSONMissingValue::isDifferent(const JSONValidationResult* zResult, Text additionalPath) const
  804. {
  805. const JSONMissingValue* casted = dynamic_cast<const JSONMissingValue*>(zResult);
  806. if (casted == 0)
  807. return 1;
  808. if (!casted->getPath().istGleich(additionalPath + path))
  809. return 1;
  810. return 0;
  811. }
  812. #pragma endregion Content
  813. #pragma region JSONMissingOneOf
  814. JSONMissingOneOf::JSONMissingOneOf(Text path, XML::Editor expected)
  815. : JSONValidationResult()
  816. {
  817. this->path = path;
  818. for (XML::Element* e : expected)
  819. this->expected.add(dynamic_cast<XML::Element*>(e->getThis()));
  820. }
  821. JSONMissingOneOf::~JSONMissingOneOf()
  822. {}
  823. bool JSONMissingOneOf::isValid() const
  824. {
  825. return 0;
  826. }
  827. void JSONMissingOneOf::printInvalidInfo(int indent) const
  828. {
  829. Text ind = "";
  830. ind.fillText(' ', indent);
  831. std::cout << ind.getText() << "Missing Value at '" << path.getText() << "'. The value should have one of the following types:\n";
  832. ind += " ";
  833. for (XML::Element* e : expected)
  834. {
  835. std::cout << ind.getText() << e->toString().getText() << "\n";
  836. }
  837. }
  838. JSONValue* JSONMissingOneOf::getValidPart() const
  839. {
  840. // multiple possibilities are undecidable
  841. return 0;
  842. }
  843. Text JSONMissingOneOf::getPath() const
  844. {
  845. return path;
  846. }
  847. bool JSONMissingOneOf::isDifferent(const JSONValidationResult* zResult, Text additionalPath) const
  848. {
  849. const JSONMissingOneOf* casted = dynamic_cast<const JSONMissingOneOf*>(zResult);
  850. if (casted == 0)
  851. return 1;
  852. if (!casted->getPath().istGleich(additionalPath + path))
  853. return 1;
  854. return 0;
  855. }
  856. #pragma endregion Content
  857. #pragma region JSONNoTypeMatching
  858. JSONNoTypeMatching::JSONNoTypeMatching(Text path, JSONValue* foundValue, RCArray<XML::Element>& expected, RCArray<JSONValidationResult>& reasons)
  859. : JSONValidationResult()
  860. {
  861. this->path = path;
  862. this->foundValue = foundValue;
  863. this->expected = expected;
  864. this->reasons = reasons;
  865. }
  866. JSONNoTypeMatching::~JSONNoTypeMatching()
  867. {
  868. foundValue->release();
  869. }
  870. bool JSONNoTypeMatching::isValid() const
  871. {
  872. return 0;
  873. }
  874. void JSONNoTypeMatching::printInvalidInfo(int indent) const
  875. {
  876. Text ind = "";
  877. ind.fillText(' ', indent);
  878. std::cout << ind.getText() << "Found Value at '" << path.getText() << "' did not match any of the given possible types:\n";
  879. Text ind2 = ind + " ";
  880. for (XML::Element* element : expected)
  881. {
  882. std::cout << ind2.getText() << element->toString().getText() << "\n";
  883. }
  884. std::cout << ind.getText() << "Reasons:\n";
  885. for (JSONValidationResult* reason : reasons)
  886. {
  887. reason->printInvalidInfo(indent + 4);
  888. }
  889. }
  890. JSONValue* JSONNoTypeMatching::getValidPart() const
  891. {
  892. // multiple possibilities are undecidable
  893. return 0;
  894. }
  895. Text JSONNoTypeMatching::getPath() const
  896. {
  897. return path;
  898. }
  899. bool JSONNoTypeMatching::isDifferent(const JSONValidationResult* zResult, Text additionalPath) const
  900. {
  901. const JSONNoTypeMatching* casted = dynamic_cast<const JSONNoTypeMatching*>(zResult);
  902. if (casted == 0)
  903. return 1;
  904. if (!casted->getPath().istGleich(additionalPath + path))
  905. return 1;
  906. for (int i = 0; i < reasons.getEintragAnzahl(); i++)
  907. {
  908. if (reasons.z(i)->isDifferent(casted->reasons.z(i), additionalPath))
  909. return 1;
  910. }
  911. return 0;
  912. }
  913. #pragma endregion Content
  914. #pragma region JSONValidValue
  915. JSONValidValue::JSONValidValue(Text path, JSONValue* value)
  916. : JSONValidationResult()
  917. {
  918. this->path = path;
  919. this->value = value;
  920. }
  921. JSONValidValue::~JSONValidValue()
  922. {
  923. value->release();
  924. }
  925. bool JSONValidValue::isValid() const
  926. {
  927. return 1;
  928. }
  929. void JSONValidValue::printInvalidInfo(int indent) const
  930. {}
  931. JSONValue* JSONValidValue::getValidPart() const
  932. {
  933. return value->clone();
  934. }
  935. Text JSONValidValue::getPath() const
  936. {
  937. return path;
  938. }
  939. bool JSONValidValue::isDifferent(const JSONValidationResult* zResult, Text additionalPath) const
  940. {
  941. const JSONValidValue* casted = dynamic_cast<const JSONValidValue*>(zResult);
  942. if (casted == 0)
  943. return 1;
  944. if (!casted->getPath().istGleich(additionalPath + path))
  945. return 1;
  946. return 0;
  947. }
  948. #pragma endregion Content
  949. #pragma endregion Content
  950. #pragma region JSONValidator
  951. JSONValidator::JSONValidator(XML::Element* constraints)
  952. : ReferenceCounter(),
  953. constraints(constraints)
  954. {}
  955. JSONValidator::~JSONValidator()
  956. {
  957. constraints->release();
  958. }
  959. JSONValidationResult* JSONValidator::validate(JSONValue* zValue) const
  960. {
  961. return validate(zValue, constraints, "");
  962. }
  963. bool JSONValidator::isValid(JSONValue* zValue) const
  964. {
  965. JSONValidationResult* res = validate(zValue);
  966. if (res->isValid())
  967. {
  968. res->release();
  969. return 1;
  970. }
  971. res->release();
  972. return 0;
  973. }
  974. JSONValue* JSONValidator::getValidParts(JSONValue* zValue) const
  975. {
  976. JSONValidationResult* res = validate(zValue);
  977. if (res->isValid())
  978. {
  979. res->release();
  980. return zValue->clone();
  981. }
  982. JSONValue* valid = res->getValidPart();
  983. res->release();
  984. return valid;
  985. }
  986. XML::Element* JSONValidator::zConstraints()
  987. {
  988. return constraints;
  989. }
  990. JSONValidationResult* JSONValidator::validate(JSONValue* zValue, XML::Element* zConstraints, Text path) const
  991. {
  992. switch (zValue->getType())
  993. {
  994. case JSONType::NULL_:
  995. if (!zConstraints->hasAttribute("nullable") || !zConstraints->getAttributeValue("nullable").istGleich("true"))
  996. {
  997. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), 0);
  998. }
  999. break;
  1000. case JSONType::BOOLEAN:
  1001. if (!zConstraints->getName().istGleich("bool"))
  1002. {
  1003. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), 0);
  1004. }
  1005. else if (zConstraints->hasAttribute("equals"))
  1006. {
  1007. if (!zConstraints->getAttributeValue("equals").istGleich("true") == !zValue->asBool()->getBool())
  1008. {
  1009. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), 0);
  1010. }
  1011. }
  1012. break;
  1013. case JSONType::NUMBER:
  1014. if (!zConstraints->getName().istGleich("number"))
  1015. {
  1016. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), 0);
  1017. }
  1018. else
  1019. {
  1020. if (zConstraints->hasAttribute("equals") && (double)zConstraints->getAttributeValue("equals") != zValue->asNumber()->getNumber())
  1021. {
  1022. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), 0);
  1023. }
  1024. else if (zConstraints->hasAttribute("lessOrEqual") && zValue->asNumber()->getNumber() > (double)zConstraints->getAttributeValue("lessOrEqual"))
  1025. {
  1026. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), 0);
  1027. }
  1028. else if (zConstraints->hasAttribute("greaterOrEqual") && zValue->asNumber()->getNumber() < (double)zConstraints->getAttributeValue("greaterOrEqual"))
  1029. {
  1030. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), 0);
  1031. }
  1032. else if (zConstraints->hasAttribute("less") && zValue->asNumber()->getNumber() >= (double)zConstraints->getAttributeValue("less"))
  1033. {
  1034. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), 0);
  1035. }
  1036. else if (zConstraints->hasAttribute("greater") && zValue->asNumber()->getNumber() <= (double)zConstraints->getAttributeValue("greater"))
  1037. {
  1038. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), 0);
  1039. }
  1040. }
  1041. break;
  1042. case JSONType::STRING:
  1043. if (!zConstraints->getName().istGleich("string"))
  1044. {
  1045. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), 0);
  1046. }
  1047. else
  1048. {
  1049. if (zConstraints->hasAttribute("equals") && !zConstraints->getAttributeValue("equals").istGleich(zValue->asString()->getString()))
  1050. {
  1051. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), 0);
  1052. }
  1053. else if (zConstraints->hasAttribute("contains") && zValue->asString()->getString().hat(zConstraints->getAttributeValue("contains").getText()))
  1054. {
  1055. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), 0);
  1056. }
  1057. else if (zConstraints->hasAttribute("startsWith") && zValue->asString()->getString().positionVon(zConstraints->getAttributeValue("startsWith").getText()) == 0)
  1058. {
  1059. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), 0);
  1060. }
  1061. else if (zConstraints->hasAttribute("endsWith") && zValue->asString()->getString().positionVon(zConstraints->getAttributeValue("endsWith").getText()) == zValue->asString()->getString().getLength() - zConstraints->getAttributeValue("endsWith").getLength())
  1062. {
  1063. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), 0);
  1064. }
  1065. }
  1066. break;
  1067. case JSONType::ARRAY:
  1068. if (!zConstraints->getName().istGleich("array"))
  1069. {
  1070. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), 0);
  1071. }
  1072. else
  1073. {
  1074. int index = 0;
  1075. for (JSON::JSONValue* value : *zValue->asArray())
  1076. {
  1077. Text p = path;
  1078. p += "[";
  1079. p += index;
  1080. p += "]";
  1081. JSONValidationResult* res = validateMultipleTypes(value, zConstraints, p);
  1082. if (!res->isValid())
  1083. {
  1084. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), res);
  1085. }
  1086. res->release();
  1087. index++;
  1088. }
  1089. }
  1090. break;
  1091. case JSONType::OBJECT:
  1092. if (!zConstraints->getName().istGleich("object"))
  1093. {
  1094. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), 0);
  1095. }
  1096. else
  1097. {
  1098. JSON::JSONObject* obj = zValue->asObject();
  1099. for (auto i = obj->getFields(); i; i++)
  1100. {
  1101. Text p = path;
  1102. p += ".";
  1103. p += i.val();
  1104. if (!zConstraints->selectChildsByAttribute("name", i.val()).exists())
  1105. {
  1106. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), new JSONUnknownValue(p, zValue->asObject()->getValue(i.val())));
  1107. }
  1108. else
  1109. {
  1110. bool isValueValid = 0;
  1111. JSONValidationResult* res = validateMultipleTypes(zValue->asObject()->zValue(i.val()), zConstraints->selectChildsByAttribute("name", i.val()).begin().val(), p);
  1112. if (!res->isValid())
  1113. {
  1114. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), res);
  1115. }
  1116. res->release();
  1117. }
  1118. }
  1119. for (XML::Element* constraint : zConstraints->selectChildren())
  1120. {
  1121. if (!zValue->asObject()->hasValue(constraint->getAttributeValue("name")))
  1122. {
  1123. Text p = path;
  1124. p += ".";
  1125. p += constraint->getAttributeValue("name");
  1126. if (constraint->getChildCount() != 1)
  1127. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), new JSONMissingOneOf(p, constraint->selectChildren()));
  1128. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), new JSONMissingValue(p, dynamic_cast<XML::Element*>(constraint->selectChildren().begin().val()->getThis())));
  1129. }
  1130. }
  1131. }
  1132. break;
  1133. }
  1134. return new JSONValidValue(path, dynamic_cast<JSONValue*>(zValue->getThis()));
  1135. }
  1136. JSONValidationResult* JSONValidator::validateMultipleTypes(JSONValue* zChildValue, XML::Element* zPossibleChildConstraints, Text childPath) const
  1137. {
  1138. if (zPossibleChildConstraints->getChildCount() == 1)
  1139. return validate(zChildValue, zPossibleChildConstraints->selectChildren().begin().val(), childPath); // only one type is possible
  1140. bool hasTypeAttr = 0;
  1141. RCArray<XML::Element> possibleConstraints;
  1142. if (zPossibleChildConstraints->hasAttribute("typeSpecifiedBy"))
  1143. { // try to find the correct constraints based on the type attribute
  1144. hasTypeAttr = 1;
  1145. Text typeAttr = zPossibleChildConstraints->getAttributeValue("typeSpecifiedBy");
  1146. if (zChildValue->getType() == JSONType::OBJECT)
  1147. {
  1148. if (zChildValue->asObject()->hasValue(typeAttr))
  1149. {
  1150. JSONValue* typeV = zChildValue->asObject()->zValue(typeAttr);
  1151. for (XML::Element* constraint : zPossibleChildConstraints->selectChildsByName("object").whereChildWithAttributeExists("name", typeAttr))
  1152. {
  1153. XML::Element* typeAttrContraints = constraint->selectChildsByAttribute("name", typeAttr).begin().val();
  1154. JSONValidationResult* res = validateMultipleTypes(typeV, typeAttrContraints, childPath + "." + typeAttr);
  1155. if (res->isValid())
  1156. possibleConstraints.add(dynamic_cast<XML::Element*>(constraint->getThis()));
  1157. res->release();
  1158. }
  1159. }
  1160. }
  1161. }
  1162. if (hasTypeAttr && possibleConstraints.getEintragAnzahl() == 1)
  1163. return validate(zChildValue, possibleConstraints.begin().val(), childPath); // if the type is clear
  1164. else if (hasTypeAttr && possibleConstraints.getEintragAnzahl() > 0)
  1165. { // more then one type is possible
  1166. RCArray< JSONValidationResult> invalidResults;
  1167. for (XML::Element* constraint : possibleConstraints)
  1168. {
  1169. JSONValidationResult* res = validate(zChildValue, constraint, childPath);
  1170. invalidResults.add(res);
  1171. if (res->isValid())
  1172. return new JSONValidValue(childPath, dynamic_cast<JSONValue*>(zChildValue->getThis()));
  1173. }
  1174. return new JSONNoTypeMatching(childPath, dynamic_cast<JSONValue*>(zChildValue->getThis()), possibleConstraints, invalidResults);
  1175. }
  1176. // try all types
  1177. possibleConstraints.leeren();
  1178. RCArray< JSONValidationResult> invalidResults;
  1179. for (XML::Element* constraint : zPossibleChildConstraints->selectChildren())
  1180. {
  1181. JSONValidationResult* res = validate(zChildValue, constraint, childPath);
  1182. invalidResults.add(res);
  1183. if (res->isValid())
  1184. return new JSONValidValue(childPath, dynamic_cast<JSONValue*>(zChildValue->getThis()));
  1185. possibleConstraints.add(dynamic_cast<XML::Element*>(constraint->getThis()));
  1186. }
  1187. return new JSONNoTypeMatching(childPath, dynamic_cast<JSONValue*>(zChildValue->getThis()), possibleConstraints, invalidResults);
  1188. }
  1189. StringValidationBuilder<JSONValidator>* JSONValidator::buildForString()
  1190. {
  1191. return new StringValidationBuilder<JSONValidator>([](XML::Element& e)
  1192. {
  1193. return new JSONValidator(e.dublicate());
  1194. });
  1195. }
  1196. NumberValidationBuilder<JSONValidator>* JSONValidator::buildForNumber()
  1197. {
  1198. return new NumberValidationBuilder<JSONValidator>([](XML::Element& e)
  1199. {
  1200. return new JSONValidator(e.dublicate());
  1201. });
  1202. }
  1203. BoolValidationBuilder<JSONValidator>* JSONValidator::buildForBool()
  1204. {
  1205. return new BoolValidationBuilder<JSONValidator>([](XML::Element& e)
  1206. {
  1207. return new JSONValidator(e.dublicate());
  1208. });
  1209. }
  1210. ObjectValidationBuilder<JSONValidator>* JSONValidator::buildForObject()
  1211. {
  1212. return new ObjectValidationBuilder<JSONValidator>([](XML::Element& e)
  1213. {
  1214. return new JSONValidator(e.dublicate());
  1215. });
  1216. }
  1217. ArrayValidationBuilder<JSONValidator>* JSONValidator::buildForArray()
  1218. {
  1219. return new ArrayValidationBuilder<JSONValidator>([](XML::Element& e)
  1220. {
  1221. return new JSONValidator(e.dublicate());
  1222. });
  1223. }
  1224. #pragma endregion Content