JSON.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395
  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. 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. 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. 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. 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. 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. 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. 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. if (zConstraints->hasAttribute("oneOf"))
  1066. {
  1067. JSONArray* array = Parser::getValue(zConstraints->getAttributeValue("oneOf"))->asArray();
  1068. bool ok = 0;
  1069. for (JSONValue* v : *array)
  1070. {
  1071. if (v->asString()->getString().istGleich(zValue->asString()->getString()))
  1072. {
  1073. ok = 1;
  1074. break;
  1075. }
  1076. }
  1077. array->release();
  1078. if (!ok)
  1079. {
  1080. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), 0);
  1081. }
  1082. }
  1083. }
  1084. break;
  1085. case JSONType::ARRAY:
  1086. if (!zConstraints->getName().istGleich("array"))
  1087. {
  1088. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), 0);
  1089. }
  1090. else
  1091. {
  1092. int index = 0;
  1093. for (JSON::JSONValue* value : *zValue->asArray())
  1094. {
  1095. Text p = path;
  1096. p += "[";
  1097. p += index;
  1098. p += "]";
  1099. JSONValidationResult* res = validateMultipleTypes(value, zConstraints, p);
  1100. if (!res->isValid())
  1101. {
  1102. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), res);
  1103. }
  1104. res->release();
  1105. index++;
  1106. }
  1107. }
  1108. break;
  1109. case JSONType::OBJECT:
  1110. if (!zConstraints->getName().istGleich("object"))
  1111. {
  1112. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), 0);
  1113. }
  1114. else
  1115. {
  1116. JSON::JSONObject* obj = zValue->asObject();
  1117. for (auto i = obj->getFields(); i; i++)
  1118. {
  1119. Text p = path;
  1120. p += ".";
  1121. p += i.val();
  1122. if (!zConstraints->selectChildsByAttribute("name", i.val()).exists())
  1123. {
  1124. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), new JSONUnknownValue(p, zValue->asObject()->getValue(i.val())));
  1125. }
  1126. else
  1127. {
  1128. JSONValidationResult* res = validateMultipleTypes(zValue->asObject()->zValue(i.val()), zConstraints->selectChildsByAttribute("name", i.val()).begin().val(), p);
  1129. if (!res->isValid())
  1130. {
  1131. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), res);
  1132. }
  1133. res->release();
  1134. }
  1135. }
  1136. for (XML::Element* constraint : zConstraints->selectChildren())
  1137. {
  1138. if (!zValue->asObject()->hasValue(constraint->getAttributeValue("name")))
  1139. {
  1140. Text p = path;
  1141. p += ".";
  1142. p += constraint->getAttributeValue("name");
  1143. if (constraint->getChildCount() != 1)
  1144. return new JSONTypeMissmatch(path, dynamic_cast<JSONValue*>(zValue->getThis()), dynamic_cast<XML::Element*>(zConstraints->getThis()), new JSONMissingOneOf(p, constraint->selectChildren()));
  1145. 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())));
  1146. }
  1147. }
  1148. }
  1149. break;
  1150. }
  1151. return new JSONValidValue(path, dynamic_cast<JSONValue*>(zValue->getThis()));
  1152. }
  1153. JSONValidationResult* JSONValidator::validateMultipleTypes(JSONValue* zChildValue, XML::Element* zPossibleChildConstraints, Text childPath) const
  1154. {
  1155. if (zPossibleChildConstraints->getChildCount() == 1)
  1156. return validate(zChildValue, zPossibleChildConstraints->selectChildren().begin().val(), childPath); // only one type is possible
  1157. bool hasTypeAttr = 0;
  1158. RCArray<XML::Element> possibleConstraints;
  1159. if (zPossibleChildConstraints->hasAttribute("typeSpecifiedBy"))
  1160. { // try to find the correct constraints based on the type attribute
  1161. hasTypeAttr = 1;
  1162. Text typeAttr = zPossibleChildConstraints->getAttributeValue("typeSpecifiedBy");
  1163. if (zChildValue->getType() == JSONType::OBJECT)
  1164. {
  1165. if (zChildValue->asObject()->hasValue(typeAttr))
  1166. {
  1167. JSONValue* typeV = zChildValue->asObject()->zValue(typeAttr);
  1168. for (XML::Element* constraint : zPossibleChildConstraints->selectChildsByName("object").whereChildWithAttributeExists("name", typeAttr))
  1169. {
  1170. XML::Element* typeAttrContraints = constraint->selectChildsByAttribute("name", typeAttr).begin().val();
  1171. JSONValidationResult* res = validateMultipleTypes(typeV, typeAttrContraints, childPath + "." + typeAttr);
  1172. if (res->isValid())
  1173. possibleConstraints.add(dynamic_cast<XML::Element*>(constraint->getThis()));
  1174. res->release();
  1175. }
  1176. }
  1177. }
  1178. }
  1179. if (hasTypeAttr && possibleConstraints.getEintragAnzahl() == 1)
  1180. return validate(zChildValue, possibleConstraints.begin().val(), childPath); // if the type is clear
  1181. else if (hasTypeAttr && possibleConstraints.getEintragAnzahl() > 0)
  1182. { // more then one type is possible
  1183. RCArray< JSONValidationResult> invalidResults;
  1184. for (XML::Element* constraint : possibleConstraints)
  1185. {
  1186. JSONValidationResult* res = validate(zChildValue, constraint, childPath);
  1187. invalidResults.add(res);
  1188. if (res->isValid())
  1189. return new JSONValidValue(childPath, dynamic_cast<JSONValue*>(zChildValue->getThis()));
  1190. }
  1191. return new JSONNoTypeMatching(childPath, dynamic_cast<JSONValue*>(zChildValue->getThis()), possibleConstraints, invalidResults);
  1192. }
  1193. // try all types
  1194. possibleConstraints.leeren();
  1195. RCArray< JSONValidationResult> invalidResults;
  1196. for (XML::Element* constraint : zPossibleChildConstraints->selectChildren())
  1197. {
  1198. JSONValidationResult* res = validate(zChildValue, constraint, childPath);
  1199. invalidResults.add(res);
  1200. if (res->isValid())
  1201. return new JSONValidValue(childPath, dynamic_cast<JSONValue*>(zChildValue->getThis()));
  1202. possibleConstraints.add(dynamic_cast<XML::Element*>(constraint->getThis()));
  1203. }
  1204. return new JSONNoTypeMatching(childPath, dynamic_cast<JSONValue*>(zChildValue->getThis()), possibleConstraints, invalidResults);
  1205. }
  1206. StringValidationBuilder<JSONValidator>* JSONValidator::buildForString()
  1207. {
  1208. return new StringValidationBuilder<JSONValidator>([](XML::Element& e)
  1209. {
  1210. return new JSONValidator(e.dublicate());
  1211. });
  1212. }
  1213. NumberValidationBuilder<JSONValidator>* JSONValidator::buildForNumber()
  1214. {
  1215. return new NumberValidationBuilder<JSONValidator>([](XML::Element& e)
  1216. {
  1217. return new JSONValidator(e.dublicate());
  1218. });
  1219. }
  1220. BoolValidationBuilder<JSONValidator>* JSONValidator::buildForBool()
  1221. {
  1222. return new BoolValidationBuilder<JSONValidator>([](XML::Element& e)
  1223. {
  1224. return new JSONValidator(e.dublicate());
  1225. });
  1226. }
  1227. ObjectValidationBuilder<JSONValidator>* JSONValidator::buildForObject()
  1228. {
  1229. return new ObjectValidationBuilder<JSONValidator>([](XML::Element& e)
  1230. {
  1231. return new JSONValidator(e.dublicate());
  1232. });
  1233. }
  1234. ArrayValidationBuilder<JSONValidator>* JSONValidator::buildForArray()
  1235. {
  1236. return new ArrayValidationBuilder<JSONValidator>([](XML::Element& e)
  1237. {
  1238. return new JSONValidator(e.dublicate());
  1239. });
  1240. }
  1241. #pragma endregion Content