JSON.cpp 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393
  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. i = 0;
  405. esc = 0;
  406. strO = 0;
  407. for (; str[i]; i++)
  408. {
  409. switch (str[i])
  410. {
  411. case '\\':
  412. if (strO)
  413. esc = !esc;
  414. else
  415. esc = 0;
  416. ret.append(str[i]);
  417. break;
  418. case '"':
  419. if (!esc)
  420. strO = !strO;
  421. esc = 0;
  422. ret.append(str[i]);
  423. break;
  424. case ' ':
  425. case '\n':
  426. case '\t':
  427. case '\r':
  428. if (strO)
  429. ret.append(str[i]);
  430. esc = 0;
  431. break;
  432. default:
  433. ret.append(str[i]);
  434. esc = 0;
  435. break;
  436. }
  437. }
  438. return ret;
  439. }
  440. JSONValue* Parser::getValue(const char* str)
  441. {
  442. Text string = Parser::removeWhitespace(str);
  443. if (string.istGleich("true"))
  444. return new JSONBool(1);
  445. if (string.istGleich("false"))
  446. return new JSONBool(0);
  447. if (string.getText()[0] == '"')
  448. {
  449. string.remove(0, 1);
  450. string.remove(string.getLength() - 1, string.getLength());
  451. return new JSONString(string);
  452. }
  453. if (string.getText()[0] == '[')
  454. return new JSONArray(string);
  455. if (string.getText()[0] == '{')
  456. return new JSONObject(string);
  457. if (Text((int)string).istGleich(string.getText()))
  458. return new JSONNumber((double)string);
  459. if (string.anzahlVon('.') == 1)
  460. {
  461. bool isNumber = 1;
  462. for (const char* c = (*string.getText() == '-') ? string.getText() + 1 : string.getText(); *c; c++)
  463. isNumber &= (*c >= '0' && *c <= '9') || *c == '.';
  464. if (isNumber)
  465. return new JSONNumber((double)string);
  466. }
  467. return new JSONValue();
  468. }
  469. int Parser::findFieldEndInObject(const char* str)
  470. {
  471. int i = 0;
  472. bool esc = 0;
  473. bool strO = 0;
  474. int objOc = 0;
  475. int arrayOc = 0;
  476. for (; str[i]; i++)
  477. {
  478. switch (str[i])
  479. {
  480. case '\\':
  481. if (strO)
  482. esc = !esc;
  483. else
  484. esc = 0;
  485. break;
  486. case '"':
  487. if (!esc)
  488. strO = !strO;
  489. esc = 0;
  490. break;
  491. case '[':
  492. if (!strO)
  493. arrayOc++;
  494. esc = 0;
  495. break;
  496. case ']':
  497. if (!strO)
  498. arrayOc--;
  499. esc = 0;
  500. break;
  501. case '{':
  502. if (!strO)
  503. objOc++;
  504. esc = 0;
  505. break;
  506. case '}':
  507. if (!strO)
  508. objOc--;
  509. esc = 0;
  510. break;
  511. case ':':
  512. if (!strO && objOc == 0 && arrayOc == 0)
  513. return i;
  514. esc = 0;
  515. break;
  516. default:
  517. esc = 0;
  518. break;
  519. }
  520. }
  521. return i;
  522. }
  523. int Parser::findValueEndInObject(const char* str)
  524. {
  525. int i = 0;
  526. bool esc = 0;
  527. bool strO = 0;
  528. int objOc = 0;
  529. int arrayOc = 0;
  530. for (; str[i]; i++)
  531. {
  532. switch (str[i])
  533. {
  534. case '\\':
  535. if (strO)
  536. esc = !esc;
  537. else
  538. esc = 0;
  539. break;
  540. case '"':
  541. if (!esc)
  542. strO = !strO;
  543. esc = 0;
  544. break;
  545. case '[':
  546. if (!strO)
  547. arrayOc++;
  548. esc = 0;
  549. break;
  550. case ']':
  551. if (!strO)
  552. arrayOc--;
  553. esc = 0;
  554. break;
  555. case '{':
  556. if (!strO)
  557. objOc++;
  558. esc = 0;
  559. break;
  560. case '}':
  561. if (!strO)
  562. objOc--;
  563. esc = 0;
  564. break;
  565. case ',':
  566. if (!strO && objOc == 0 && arrayOc == 0)
  567. return i;
  568. esc = 0;
  569. break;
  570. default:
  571. esc = 0;
  572. break;
  573. }
  574. }
  575. return i;
  576. }
  577. #pragma endregion Content
  578. using namespace Validator;
  579. #pragma region JSONValidationResult
  580. JSONValidationResult::JSONValidationResult()
  581. : ReferenceCounter()
  582. {}
  583. JSONValidationResult::~JSONValidationResult() {}
  584. #pragma region JSONTypeMissmatch
  585. JSONTypeMissmatch::JSONTypeMissmatch(Text path, JSONValue* foundValue, XML::Element* expected, JSONValidationResult* reason)
  586. : JSONValidationResult()
  587. {
  588. this->path = path;
  589. this->foundValue = foundValue;
  590. this->expected = expected;
  591. this->reason = reason;
  592. }
  593. JSONTypeMissmatch::~JSONTypeMissmatch()
  594. {
  595. foundValue->release();
  596. expected->release();
  597. if (reason)
  598. reason->release();
  599. }
  600. bool JSONTypeMissmatch::isValid() const
  601. {
  602. return 0;
  603. }
  604. void JSONTypeMissmatch::printInvalidInfo(int indent) const
  605. {
  606. Text ind = "";
  607. ind.fillText(' ', indent);
  608. 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";
  609. if (reason)
  610. {
  611. std::cout << ind.getText() << "Reason for type mismatch:\n";
  612. reason->printInvalidInfo(indent + 4);
  613. }
  614. }
  615. JSONValue* JSONTypeMissmatch::getValidPart() const
  616. {
  617. if (reason)
  618. {
  619. JSONValue* valid = reason->getValidPart();
  620. Text* p = reason->getPath().getTeilText(path.getLength());
  621. if (foundValue->getType() == JSONType::ARRAY)
  622. {
  623. if (!valid && (!expected->hasAttribute("removeInvalidEntries") || !expected->getAttributeValue("removeInvalidEntries").istGleich("true")))
  624. {
  625. p->release();
  626. return 0;
  627. }
  628. if (p->hatAt(0, "[") && p->hatAt(p->getLength() - 1, "]"))
  629. {
  630. Text* it = p->getTeilText(1, p->getLength() - 1);
  631. int i = (int)*it;
  632. it->release();
  633. if (i >= 0 && foundValue->asArray()->getLength() > i)
  634. {
  635. JSONValue* tmp = foundValue->clone();
  636. if (valid)
  637. tmp->asArray()->setValue(i, valid);
  638. else
  639. tmp->asArray()->removeValue(i);
  640. JSONValidationResult* res = JSONValidator(dynamic_cast<XML::Element*>(expected->getThis())).validate(tmp);
  641. if (res->isValid())
  642. {
  643. res->release();
  644. p->release();
  645. return tmp;
  646. }
  647. else if (res->isDifferent(this, path) || !valid)
  648. {
  649. p->release();
  650. tmp->release();
  651. JSONValue* result = res->getValidPart();
  652. res->release();
  653. return result;
  654. }
  655. tmp->release();
  656. res->release();
  657. }
  658. }
  659. }
  660. else if (foundValue->getType() == JSONType::OBJECT)
  661. {
  662. if (!valid && (!expected->hasAttribute("removeInvalidEntries") || !expected->getAttributeValue("removeInvalidEntries").istGleich("true")))
  663. {
  664. p->release();
  665. return 0;
  666. }
  667. if (p->hatAt(0, "."))
  668. {
  669. Text* at = p->getTeilText(1);
  670. Text attr = *at;
  671. at->release();
  672. JSONValue* tmp = foundValue->clone();
  673. tmp->asObject()->removeValue(attr);
  674. if (valid)
  675. tmp->asObject()->addValue(attr, valid);
  676. JSONValidationResult* res = JSONValidator(dynamic_cast<XML::Element*>(expected->getThis())).validate(tmp);
  677. if (res->isValid())
  678. {
  679. res->release();
  680. p->release();
  681. return tmp;
  682. }
  683. else if (res->isDifferent(this, path) || !valid)
  684. {
  685. p->release();
  686. tmp->release();
  687. JSONValue* result = res->getValidPart();
  688. res->release();
  689. return result;
  690. }
  691. tmp->release();
  692. res->release();
  693. }
  694. }
  695. p->release();
  696. if (valid)
  697. valid->release();
  698. }
  699. return 0;
  700. }
  701. Text JSONTypeMissmatch::getPath() const
  702. {
  703. return path;
  704. }
  705. bool JSONTypeMissmatch::isDifferent(const JSONValidationResult* zResult, Text additionalPath) const
  706. {
  707. const JSONTypeMissmatch* casted = dynamic_cast<const JSONTypeMissmatch*>(zResult);
  708. if (casted == 0)
  709. return 1;
  710. if (!casted->getPath().istGleich(additionalPath + path))
  711. return 1;
  712. return reason->isDifferent(casted->reason, path);
  713. }
  714. #pragma endregion Content
  715. #pragma region JSONUnknownValue
  716. JSONUnknownValue::JSONUnknownValue(Text path, JSONValue* foundValue)
  717. : JSONValidationResult()
  718. {
  719. this->path = path;
  720. this->foundValue = foundValue;
  721. }
  722. JSONUnknownValue::~JSONUnknownValue()
  723. {
  724. foundValue->release();
  725. }
  726. bool JSONUnknownValue::isValid() const
  727. {
  728. return 0;
  729. }
  730. void JSONUnknownValue::printInvalidInfo(int indent) const
  731. {
  732. Text ind = "";
  733. ind.fillText(' ', indent);
  734. std::cout << ind.getText() << "Unknown Value at '" << path.getText() << "'. Value found:\n" << ind.getText() << foundValue->toString().getText() << "\n";
  735. }
  736. JSONValue* JSONUnknownValue::getValidPart() const
  737. {
  738. return 0;
  739. }
  740. Text JSONUnknownValue::getPath() const
  741. {
  742. return path;
  743. }
  744. bool JSONUnknownValue::isDifferent(const JSONValidationResult* zResult, Text additionalPath) const
  745. {
  746. const JSONUnknownValue* casted = dynamic_cast<const JSONUnknownValue*>(zResult);
  747. if (casted == 0)
  748. return 1;
  749. if (!casted->getPath().istGleich(additionalPath + path))
  750. return 1;
  751. return 0;
  752. }
  753. #pragma endregion Content
  754. #pragma region JSONMissingValue
  755. JSONMissingValue::JSONMissingValue(Text path, XML::Element* expected)
  756. : JSONValidationResult()
  757. {
  758. this->path = path;
  759. this->expected = expected;
  760. }
  761. JSONMissingValue::~JSONMissingValue()
  762. {
  763. expected->release();
  764. }
  765. bool JSONMissingValue::isValid() const
  766. {
  767. return 0;
  768. }
  769. void JSONMissingValue::printInvalidInfo(int indent) const
  770. {
  771. Text ind = "";
  772. ind.fillText(' ', indent);
  773. std::cout << ind.getText() << "Missing Value at '" << path.getText() << "'. Expected type:\n" << ind.getText() << expected->toString().getText() << "\n";
  774. }
  775. JSONValue* JSONMissingValue::getValidPart() const
  776. {
  777. if (expected->hasAttribute("default"))
  778. {
  779. JSONValue* def = Parser::getValue(expected->getAttributeValue("default"));
  780. JSONValidationResult* res = JSONValidator(dynamic_cast<XML::Element*>(expected->getThis())).validate(def);
  781. if (res->isValid())
  782. {
  783. res->release();
  784. return def;
  785. }
  786. else if (res->isDifferent(this, path))
  787. {
  788. def->release();
  789. JSONValue* result = res->getValidPart();
  790. res->release();
  791. return result;
  792. }
  793. def->release();
  794. }
  795. return 0;
  796. }
  797. Text JSONMissingValue::getPath() const
  798. {
  799. return path;
  800. }
  801. bool JSONMissingValue::isDifferent(const JSONValidationResult* zResult, Text additionalPath) const
  802. {
  803. const JSONMissingValue* casted = dynamic_cast<const JSONMissingValue*>(zResult);
  804. if (casted == 0)
  805. return 1;
  806. if (!casted->getPath().istGleich(additionalPath + path))
  807. return 1;
  808. return 0;
  809. }
  810. #pragma endregion Content
  811. #pragma region JSONMissingOneOf
  812. JSONMissingOneOf::JSONMissingOneOf(Text path, XML::Editor expected)
  813. : JSONValidationResult()
  814. {
  815. this->path = path;
  816. for (XML::Element* e : expected)
  817. this->expected.add(dynamic_cast<XML::Element*>(e->getThis()));
  818. }
  819. JSONMissingOneOf::~JSONMissingOneOf()
  820. {}
  821. bool JSONMissingOneOf::isValid() const
  822. {
  823. return 0;
  824. }
  825. void JSONMissingOneOf::printInvalidInfo(int indent) const
  826. {
  827. Text ind = "";
  828. ind.fillText(' ', indent);
  829. std::cout << ind.getText() << "Missing Value at '" << path.getText() << "'. The value should have one of the following types:\n";
  830. ind += " ";
  831. for (XML::Element* e : expected)
  832. {
  833. std::cout << ind.getText() << e->toString().getText() << "\n";
  834. }
  835. }
  836. JSONValue* JSONMissingOneOf::getValidPart() const
  837. {
  838. // multiple possibilities are undecidable
  839. return 0;
  840. }
  841. Text JSONMissingOneOf::getPath() const
  842. {
  843. return path;
  844. }
  845. bool JSONMissingOneOf::isDifferent(const JSONValidationResult* zResult, Text additionalPath) const
  846. {
  847. const JSONMissingOneOf* casted = dynamic_cast<const JSONMissingOneOf*>(zResult);
  848. if (casted == 0)
  849. return 1;
  850. if (!casted->getPath().istGleich(additionalPath + path))
  851. return 1;
  852. return 0;
  853. }
  854. #pragma endregion Content
  855. #pragma region JSONNoTypeMatching
  856. JSONNoTypeMatching::JSONNoTypeMatching(Text path, JSONValue* foundValue, RCArray<XML::Element>& expected, RCArray<JSONValidationResult>& reasons)
  857. : JSONValidationResult()
  858. {
  859. this->path = path;
  860. this->foundValue = foundValue;
  861. this->expected = expected;
  862. this->reasons = reasons;
  863. }
  864. JSONNoTypeMatching::~JSONNoTypeMatching()
  865. {
  866. foundValue->release();
  867. }
  868. bool JSONNoTypeMatching::isValid() const
  869. {
  870. return 0;
  871. }
  872. void JSONNoTypeMatching::printInvalidInfo(int indent) const
  873. {
  874. Text ind = "";
  875. ind.fillText(' ', indent);
  876. std::cout << ind.getText() << "Found Value at '" << path.getText() << "' did not match any of the given possible types:\n";
  877. Text ind2 = ind + " ";
  878. for (XML::Element* element : expected)
  879. {
  880. std::cout << ind2.getText() << element->toString().getText() << "\n";
  881. }
  882. std::cout << ind.getText() << "Reasons:\n";
  883. for (JSONValidationResult* reason : reasons)
  884. {
  885. reason->printInvalidInfo(indent + 4);
  886. }
  887. }
  888. JSONValue* JSONNoTypeMatching::getValidPart() const
  889. {
  890. // multiple possibilities are undecidable
  891. return 0;
  892. }
  893. Text JSONNoTypeMatching::getPath() const
  894. {
  895. return path;
  896. }
  897. bool JSONNoTypeMatching::isDifferent(const JSONValidationResult* zResult, Text additionalPath) const
  898. {
  899. const JSONNoTypeMatching* casted = dynamic_cast<const JSONNoTypeMatching*>(zResult);
  900. if (casted == 0)
  901. return 1;
  902. if (!casted->getPath().istGleich(additionalPath + path))
  903. return 1;
  904. for (int i = 0; i < reasons.getEintragAnzahl(); i++)
  905. {
  906. if (reasons.z(i)->isDifferent(casted->reasons.z(i), additionalPath))
  907. return 1;
  908. }
  909. return 0;
  910. }
  911. #pragma endregion Content
  912. #pragma region JSONValidValue
  913. JSONValidValue::JSONValidValue(Text path, JSONValue* value)
  914. : JSONValidationResult()
  915. {
  916. this->path = path;
  917. this->value = value;
  918. }
  919. JSONValidValue::~JSONValidValue()
  920. {
  921. value->release();
  922. }
  923. bool JSONValidValue::isValid() const
  924. {
  925. return 1;
  926. }
  927. void JSONValidValue::printInvalidInfo(int indent) const
  928. {}
  929. JSONValue* JSONValidValue::getValidPart() const
  930. {
  931. return value->clone();
  932. }
  933. Text JSONValidValue::getPath() const
  934. {
  935. return path;
  936. }
  937. bool JSONValidValue::isDifferent(const JSONValidationResult* zResult, Text additionalPath) const
  938. {
  939. const JSONValidValue* casted = dynamic_cast<const JSONValidValue*>(zResult);
  940. if (casted == 0)
  941. return 1;
  942. if (!casted->getPath().istGleich(additionalPath + path))
  943. return 1;
  944. return 0;
  945. }
  946. #pragma endregion Content
  947. #pragma endregion Content
  948. #pragma region JSONValidator
  949. JSONValidator::JSONValidator(XML::Element* constraints)
  950. : ReferenceCounter(),
  951. constraints(constraints)
  952. {}
  953. JSONValidator::~JSONValidator()
  954. {
  955. constraints->release();
  956. }
  957. JSONValidationResult* JSONValidator::validate(JSONValue* zValue) const
  958. {
  959. return validate(zValue, constraints, "");
  960. }
  961. bool JSONValidator::isValid(JSONValue* zValue) const
  962. {
  963. JSONValidationResult* res = validate(zValue);
  964. if (res->isValid())
  965. {
  966. res->release();
  967. return 1;
  968. }
  969. res->release();
  970. return 0;
  971. }
  972. JSONValue* JSONValidator::getValidParts(JSONValue* zValue) const
  973. {
  974. JSONValidationResult* res = validate(zValue);
  975. if (res->isValid())
  976. {
  977. res->release();
  978. return zValue->clone();
  979. }
  980. JSONValue* valid = res->getValidPart();
  981. res->release();
  982. return valid;
  983. }
  984. XML::Element* JSONValidator::zConstraints()
  985. {
  986. return constraints;
  987. }
  988. JSONValidationResult* JSONValidator::validate(JSONValue* zValue, XML::Element* zConstraints, Text path) const
  989. {
  990. switch (zValue->getType())
  991. {
  992. case JSONType::NULL_:
  993. if (!zConstraints->hasAttribute("nullable") || !zConstraints->getAttributeValue("nullable").istGleich("true"))
  994. {
  995. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), 0);
  996. }
  997. break;
  998. case JSONType::BOOLEAN:
  999. if (!zConstraints->getName().istGleich("bool"))
  1000. {
  1001. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), 0);
  1002. }
  1003. else if (zConstraints->hasAttribute("equals"))
  1004. {
  1005. if (!zConstraints->getAttributeValue("equals").istGleich("true") == !zValue->asBool()->getBool())
  1006. {
  1007. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), 0);
  1008. }
  1009. }
  1010. break;
  1011. case JSONType::NUMBER:
  1012. if (!zConstraints->getName().istGleich("number"))
  1013. {
  1014. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), 0);
  1015. }
  1016. else
  1017. {
  1018. if (zConstraints->hasAttribute("equals") && (double)zConstraints->getAttributeValue("equals") != zValue->asNumber()->getNumber())
  1019. {
  1020. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), 0);
  1021. }
  1022. if (zConstraints->hasAttribute("lessOrEqual") && zValue->asNumber()->getNumber() > (double)zConstraints->getAttributeValue("lessOrEqual"))
  1023. {
  1024. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), 0);
  1025. }
  1026. if (zConstraints->hasAttribute("greaterOrEqual") && zValue->asNumber()->getNumber() < (double)zConstraints->getAttributeValue("greaterOrEqual"))
  1027. {
  1028. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), 0);
  1029. }
  1030. if (zConstraints->hasAttribute("less") && zValue->asNumber()->getNumber() >= (double)zConstraints->getAttributeValue("less"))
  1031. {
  1032. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), 0);
  1033. }
  1034. if (zConstraints->hasAttribute("greater") && zValue->asNumber()->getNumber() <= (double)zConstraints->getAttributeValue("greater"))
  1035. {
  1036. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), 0);
  1037. }
  1038. }
  1039. break;
  1040. case JSONType::STRING:
  1041. if (!zConstraints->getName().istGleich("string"))
  1042. {
  1043. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), 0);
  1044. }
  1045. else
  1046. {
  1047. if (zConstraints->hasAttribute("equals") && !zConstraints->getAttributeValue("equals").istGleich(zValue->asString()->getString()))
  1048. {
  1049. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), 0);
  1050. }
  1051. if (zConstraints->hasAttribute("contains") && zValue->asString()->getString().hat(zConstraints->getAttributeValue("contains").getText()))
  1052. {
  1053. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), 0);
  1054. }
  1055. if (zConstraints->hasAttribute("startsWith") && zValue->asString()->getString().positionVon(zConstraints->getAttributeValue("startsWith").getText()) == 0)
  1056. {
  1057. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), 0);
  1058. }
  1059. if (zConstraints->hasAttribute("endsWith") && zValue->asString()->getString().positionVon(zConstraints->getAttributeValue("endsWith").getText()) == zValue->asString()->getString().getLength() - zConstraints->getAttributeValue("endsWith").getLength())
  1060. {
  1061. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), 0);
  1062. }
  1063. if (zConstraints->hasAttribute("oneOf"))
  1064. {
  1065. JSONArray* array = Parser::getValue(zConstraints->getAttributeValue("oneOf"))->asArray();
  1066. bool ok = 0;
  1067. for (JSONValue* v : *array)
  1068. {
  1069. if (v->asString()->getString().istGleich(zValue->asString()->getString()))
  1070. {
  1071. ok = 1;
  1072. break;
  1073. }
  1074. }
  1075. array->release();
  1076. if (!ok)
  1077. {
  1078. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), 0);
  1079. }
  1080. }
  1081. }
  1082. break;
  1083. case JSONType::ARRAY:
  1084. if (!zConstraints->getName().istGleich("array"))
  1085. {
  1086. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), 0);
  1087. }
  1088. else
  1089. {
  1090. int index = 0;
  1091. for (JSON::JSONValue* value : *zValue->asArray())
  1092. {
  1093. Text p = path;
  1094. p += "[";
  1095. p += index;
  1096. p += "]";
  1097. JSONValidationResult* res = validateMultipleTypes(value, zConstraints, p);
  1098. if (!res->isValid())
  1099. {
  1100. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), res);
  1101. }
  1102. res->release();
  1103. index++;
  1104. }
  1105. }
  1106. break;
  1107. case JSONType::OBJECT:
  1108. if (!zConstraints->getName().istGleich("object"))
  1109. {
  1110. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), 0);
  1111. }
  1112. else
  1113. {
  1114. JSON::JSONObject* obj = zValue->asObject();
  1115. for (auto i = obj->getFields(); i; i++)
  1116. {
  1117. Text p = path;
  1118. p += ".";
  1119. p += i.val();
  1120. if (!zConstraints->selectChildsByAttribute("name", i.val()).exists())
  1121. {
  1122. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), new JSONUnknownValue(p, zValue->asObject()->getValue(i.val())));
  1123. }
  1124. else
  1125. {
  1126. JSONValidationResult* res = validateMultipleTypes(zValue->asObject()->zValue(i.val()), zConstraints->selectChildsByAttribute("name", i.val()).begin().val(), p);
  1127. if (!res->isValid())
  1128. {
  1129. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), res);
  1130. }
  1131. res->release();
  1132. }
  1133. }
  1134. for (XML::Element* constraint : zConstraints->selectChildren())
  1135. {
  1136. if (!zValue->asObject()->hasValue(constraint->getAttributeValue("name")))
  1137. {
  1138. Text p = path;
  1139. p += ".";
  1140. p += constraint->getAttributeValue("name");
  1141. if (constraint->getChildCount() != 1)
  1142. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), new JSONMissingOneOf(p, constraint->selectChildren()));
  1143. 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())));
  1144. }
  1145. }
  1146. }
  1147. break;
  1148. }
  1149. return new JSONValidValue(path, dynamic_cast<JSONValue*>(zValue->getThis()));
  1150. }
  1151. JSONValidationResult* JSONValidator::validateMultipleTypes(JSONValue* zChildValue, XML::Element* zPossibleChildConstraints, Text childPath) const
  1152. {
  1153. if (zPossibleChildConstraints->getChildCount() == 1)
  1154. return validate(zChildValue, zPossibleChildConstraints->selectChildren().begin().val(), childPath); // only one type is possible
  1155. bool hasTypeAttr = 0;
  1156. RCArray<XML::Element> possibleConstraints;
  1157. if (zPossibleChildConstraints->hasAttribute("typeSpecifiedBy"))
  1158. { // try to find the correct constraints based on the type attribute
  1159. hasTypeAttr = 1;
  1160. Text typeAttr = zPossibleChildConstraints->getAttributeValue("typeSpecifiedBy");
  1161. if (zChildValue->getType() == JSONType::OBJECT)
  1162. {
  1163. if (zChildValue->asObject()->hasValue(typeAttr))
  1164. {
  1165. JSONValue* typeV = zChildValue->asObject()->zValue(typeAttr);
  1166. for (XML::Element* constraint : zPossibleChildConstraints->selectChildsByName("object").whereChildWithAttributeExists("name", typeAttr))
  1167. {
  1168. XML::Element* typeAttrContraints = constraint->selectChildsByAttribute("name", typeAttr).begin().val();
  1169. JSONValidationResult* res = validateMultipleTypes(typeV, typeAttrContraints, childPath + "." + typeAttr);
  1170. if (res->isValid())
  1171. possibleConstraints.add(dynamic_cast<XML::Element*>(constraint->getThis()));
  1172. res->release();
  1173. }
  1174. }
  1175. }
  1176. }
  1177. if (hasTypeAttr && possibleConstraints.getEintragAnzahl() == 1)
  1178. return validate(zChildValue, possibleConstraints.begin().val(), childPath); // if the type is clear
  1179. else if (hasTypeAttr && possibleConstraints.getEintragAnzahl() > 0)
  1180. { // more then one type is possible
  1181. RCArray< JSONValidationResult> invalidResults;
  1182. for (XML::Element* constraint : possibleConstraints)
  1183. {
  1184. JSONValidationResult* res = validate(zChildValue, constraint, childPath);
  1185. invalidResults.add(res);
  1186. if (res->isValid())
  1187. return new JSONValidValue(childPath, dynamic_cast<JSONValue*>(zChildValue->getThis()));
  1188. }
  1189. return new JSONNoTypeMatching(childPath, dynamic_cast<JSONValue*>(zChildValue->getThis()), possibleConstraints, invalidResults);
  1190. }
  1191. // try all types
  1192. possibleConstraints.leeren();
  1193. RCArray< JSONValidationResult> invalidResults;
  1194. for (XML::Element* constraint : zPossibleChildConstraints->selectChildren())
  1195. {
  1196. JSONValidationResult* res = validate(zChildValue, constraint, childPath);
  1197. invalidResults.add(res);
  1198. if (res->isValid())
  1199. return new JSONValidValue(childPath, dynamic_cast<JSONValue*>(zChildValue->getThis()));
  1200. possibleConstraints.add(dynamic_cast<XML::Element*>(constraint->getThis()));
  1201. }
  1202. return new JSONNoTypeMatching(childPath, dynamic_cast<JSONValue*>(zChildValue->getThis()), possibleConstraints, invalidResults);
  1203. }
  1204. StringValidationBuilder<JSONValidator>* JSONValidator::buildForString()
  1205. {
  1206. return new StringValidationBuilder<JSONValidator>([](XML::Element& e)
  1207. {
  1208. return new JSONValidator(e.dublicate());
  1209. });
  1210. }
  1211. NumberValidationBuilder<JSONValidator>* JSONValidator::buildForNumber()
  1212. {
  1213. return new NumberValidationBuilder<JSONValidator>([](XML::Element& e)
  1214. {
  1215. return new JSONValidator(e.dublicate());
  1216. });
  1217. }
  1218. BoolValidationBuilder<JSONValidator>* JSONValidator::buildForBool()
  1219. {
  1220. return new BoolValidationBuilder<JSONValidator>([](XML::Element& e)
  1221. {
  1222. return new JSONValidator(e.dublicate());
  1223. });
  1224. }
  1225. ObjectValidationBuilder<JSONValidator>* JSONValidator::buildForObject()
  1226. {
  1227. return new ObjectValidationBuilder<JSONValidator>([](XML::Element& e)
  1228. {
  1229. return new JSONValidator(e.dublicate());
  1230. });
  1231. }
  1232. ArrayValidationBuilder<JSONValidator>* JSONValidator::buildForArray()
  1233. {
  1234. return new ArrayValidationBuilder<JSONValidator>([](XML::Element& e)
  1235. {
  1236. return new JSONValidator(e.dublicate());
  1237. });
  1238. }
  1239. #pragma endregion Content