DataValidator.cpp 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643
  1. #include "DataValidator.h"
  2. #include "Logging.h"
  3. #include "Regex.h"
  4. using namespace Framework;
  5. using namespace Validator;
  6. #pragma region ValidationResult
  7. ValidationResult::ValidationResult()
  8. : ReferenceCounter()
  9. {}
  10. ValidationResult::~ValidationResult() {}
  11. void ValidationResult::logInvalidInfo(std::source_location location) const
  12. {
  13. Logging::error(location) << getInvalidInfo(0).getText();
  14. }
  15. #pragma region TypeMissmatch
  16. Framework::Validator::TypeMissmatch::TypeMissmatch(Text path,
  17. AbstractElement* foundValue,
  18. XML::Element* expected,
  19. ValidationResult* reason)
  20. : ValidationResult()
  21. {
  22. this->path = path;
  23. this->foundValue = foundValue;
  24. this->expected = expected;
  25. this->reason = reason;
  26. }
  27. TypeMissmatch::~TypeMissmatch()
  28. {
  29. expected->release();
  30. if (reason) reason->release();
  31. foundValue->release();
  32. }
  33. bool TypeMissmatch::isValid() const
  34. {
  35. return 0;
  36. }
  37. Text TypeMissmatch::getInvalidInfo(int indent) const
  38. {
  39. Text ind = "";
  40. ind.fillText(' ', indent);
  41. Text error = "";
  42. error.append() << ind.getText() << "Type missmatch at path '"
  43. << path.getText() << "'. Value\n"
  44. << ind.getText() << foundValue->toString().getText() << "\n"
  45. << ind.getText() << "does not match expected type\n";
  46. if (reason)
  47. {
  48. error.append() << ind.getText() << "Reason for type mismatch:\n"
  49. << reason->getInvalidInfo(indent + 4);
  50. }
  51. else
  52. {
  53. error.append() << ind.getText() << expected->toString().getText()
  54. << "\n";
  55. }
  56. return error;
  57. }
  58. JSON::JSONValue* TypeMissmatch::getValidPart(
  59. RCArray<ValidationResult>* removedPartsValidationResults)
  60. {
  61. if (reason)
  62. {
  63. RCArray<ValidationResult> temporaryInvalidParts;
  64. JSON::JSONValue* valid = reason->getValidPart(&temporaryInvalidParts);
  65. Text* p = reason->getPath().getTeilText(path.getLength());
  66. if (foundValue->getType() == AbstractType::ARRAY)
  67. {
  68. if (!valid
  69. && (!expected->hasAttribute("removeInvalidEntries")
  70. || !expected->getAttributeValue("removeInvalidEntries")
  71. .isEqual("true")))
  72. {
  73. if (removedPartsValidationResults)
  74. {
  75. if (temporaryInvalidParts.getEntryCount() == 1)
  76. {
  77. if (reason) reason->release();
  78. reason = temporaryInvalidParts.get(0);
  79. }
  80. else
  81. {
  82. for (ValidationResult* res : temporaryInvalidParts)
  83. {
  84. if (res->isDifferent(this))
  85. {
  86. removedPartsValidationResults->add(
  87. dynamic_cast<ValidationResult*>(
  88. res->getThis()));
  89. }
  90. }
  91. }
  92. removedPartsValidationResults->add(
  93. dynamic_cast<ValidationResult*>(getThis()));
  94. }
  95. p->release();
  96. return 0;
  97. }
  98. if (p->hasAt(0, "[") && p->hasAt(p->getLength() - 1, "]"))
  99. {
  100. Text* it = p->getTeilText(1, p->getLength() - 1);
  101. int i = (int)*it;
  102. it->release();
  103. if (i >= 0 && foundValue->asAbstractArray()->getLength() > i)
  104. {
  105. if (removedPartsValidationResults)
  106. {
  107. for (ValidationResult* res : temporaryInvalidParts)
  108. {
  109. removedPartsValidationResults->add(
  110. dynamic_cast<ValidationResult*>(
  111. res->getThis()));
  112. }
  113. }
  114. JSON::JSONValue* foundValueJson
  115. = dynamic_cast<JSON::JSONValue*>(foundValue);
  116. if (foundValueJson)
  117. {
  118. JSON::JSONValue* tmp = foundValueJson->clone();
  119. if (valid)
  120. tmp->asArray()->setValue(
  121. i, dynamic_cast<JSON::JSONValue*>(valid));
  122. else
  123. tmp->asArray()->removeValue(i);
  124. ValidationResult* res = DataValidator(
  125. dynamic_cast<XML::Element*>(expected->getThis()))
  126. .validate(tmp);
  127. res->addBasePath(path);
  128. if (res->isValid())
  129. {
  130. res->release();
  131. p->release();
  132. return tmp;
  133. }
  134. else if (res->isDifferent(this) || !valid)
  135. {
  136. p->release();
  137. JSON::JSONValue* result = res->getValidPart(
  138. removedPartsValidationResults);
  139. tmp->release();
  140. res->release();
  141. return result;
  142. }
  143. tmp->release();
  144. res->release();
  145. }
  146. }
  147. }
  148. }
  149. else if (foundValue->getType() == AbstractType::OBJECT)
  150. {
  151. if (!valid
  152. && (!expected->hasAttribute("removeInvalidEntries")
  153. || !expected->getAttributeValue("removeInvalidEntries")
  154. .isEqual("true")))
  155. {
  156. if (removedPartsValidationResults)
  157. {
  158. if (temporaryInvalidParts.getEntryCount() == 1)
  159. {
  160. if (reason) reason->release();
  161. reason = temporaryInvalidParts.get(0);
  162. }
  163. else
  164. {
  165. for (ValidationResult* res : temporaryInvalidParts)
  166. {
  167. if (res->isDifferent(this))
  168. {
  169. removedPartsValidationResults->add(
  170. dynamic_cast<ValidationResult*>(
  171. res->getThis()));
  172. }
  173. }
  174. }
  175. removedPartsValidationResults->add(
  176. dynamic_cast<ValidationResult*>(getThis()));
  177. }
  178. p->release();
  179. return 0;
  180. }
  181. if (p->hasAt(0, "."))
  182. {
  183. if (removedPartsValidationResults)
  184. {
  185. for (ValidationResult* res : temporaryInvalidParts)
  186. {
  187. removedPartsValidationResults->add(
  188. dynamic_cast<ValidationResult*>(res->getThis()));
  189. }
  190. }
  191. Text* at = p->getTeilText(1);
  192. Text attr = *at;
  193. at->release();
  194. JSON::JSONValue* foundValueJson
  195. = dynamic_cast<JSON::JSONValue*>(foundValue);
  196. if (foundValueJson)
  197. {
  198. JSON::JSONValue* tmp = foundValueJson->clone();
  199. tmp->asObject()->removeValue(attr);
  200. if (valid)
  201. tmp->asObject()->addValue(
  202. attr, dynamic_cast<JSON::JSONValue*>(valid));
  203. ValidationResult* res = DataValidator(
  204. dynamic_cast<XML::Element*>(expected->getThis()))
  205. .validate(tmp);
  206. res->addBasePath(path);
  207. if (res->isValid())
  208. {
  209. res->release();
  210. p->release();
  211. return tmp;
  212. }
  213. else if (res->isDifferent(this) || !valid)
  214. {
  215. p->release();
  216. JSON::JSONValue* result
  217. = res->getValidPart(removedPartsValidationResults);
  218. tmp->release();
  219. res->release();
  220. return result;
  221. }
  222. tmp->release();
  223. res->release();
  224. }
  225. }
  226. }
  227. p->release();
  228. if (valid) valid->release();
  229. }
  230. if (removedPartsValidationResults)
  231. {
  232. removedPartsValidationResults->add(
  233. dynamic_cast<ValidationResult*>(getThis()));
  234. }
  235. return 0;
  236. }
  237. Text TypeMissmatch::getPath() const
  238. {
  239. return path;
  240. }
  241. bool TypeMissmatch::isDifferent(const ValidationResult* zResult) const
  242. {
  243. const TypeMissmatch* casted = dynamic_cast<const TypeMissmatch*>(zResult);
  244. if (casted == 0) return 1;
  245. if (!casted->getPath().isEqual(path)) return 1;
  246. return reason->isDifferent(casted->reason);
  247. }
  248. void TypeMissmatch::addBasePath(Text basePath)
  249. {
  250. path = basePath + path;
  251. if (reason) reason->addBasePath(basePath);
  252. }
  253. #pragma endregion Cotent
  254. #pragma region UnknownValue
  255. UnknownValue::UnknownValue(Text path, AbstractElement* foundValue)
  256. : ValidationResult()
  257. {
  258. this->path = path;
  259. this->foundValue = foundValue;
  260. }
  261. UnknownValue::~UnknownValue()
  262. {
  263. foundValue->release();
  264. }
  265. bool UnknownValue::isValid() const
  266. {
  267. return 0;
  268. }
  269. Text UnknownValue::getInvalidInfo(int indent) const
  270. {
  271. Text ind = "";
  272. ind.fillText(' ', indent);
  273. Text error = "";
  274. error.append() << ind.getText() << "Unknown Value at '" << path.getText()
  275. << "'. Value found:\n"
  276. << ind.getText() << foundValue->toString().getText() << "\n";
  277. return error;
  278. }
  279. JSON::JSONValue* UnknownValue::getValidPart(
  280. RCArray<ValidationResult>* removedPartsValidationResults)
  281. {
  282. if (removedPartsValidationResults)
  283. {
  284. removedPartsValidationResults->add(
  285. dynamic_cast<ValidationResult*>(getThis()));
  286. }
  287. return 0;
  288. }
  289. Text UnknownValue::getPath() const
  290. {
  291. return path;
  292. }
  293. bool UnknownValue::isDifferent(const ValidationResult* zResult) const
  294. {
  295. const UnknownValue* casted = dynamic_cast<const UnknownValue*>(zResult);
  296. if (casted == 0) return 1;
  297. if (!casted->getPath().isEqual(path)) return 1;
  298. return 0;
  299. }
  300. void UnknownValue::addBasePath(Text basePath)
  301. {
  302. path = basePath + path;
  303. }
  304. #pragma endregion Cotent
  305. #pragma region MissingValue
  306. MissingValue::MissingValue(Text path, XML::Element* expected)
  307. : ValidationResult()
  308. {
  309. this->path = path;
  310. this->expected = expected;
  311. }
  312. MissingValue::~MissingValue()
  313. {
  314. expected->release();
  315. }
  316. bool MissingValue::isValid() const
  317. {
  318. return 0;
  319. }
  320. Text MissingValue::getInvalidInfo(int indent) const
  321. {
  322. Text ind = "";
  323. ind.fillText(' ', indent);
  324. Text error = "";
  325. error.append() << ind.getText() << "Missing Value at '" << path.getText()
  326. << "'. Expected type:\n"
  327. << ind.getText() << expected->toString().getText() << "\n";
  328. return error;
  329. }
  330. JSON::JSONValue* MissingValue::getValidPart(
  331. RCArray<ValidationResult>* removedPartsValidationResults)
  332. {
  333. if (expected->hasAttribute("default"))
  334. {
  335. JSON::JSONValue* def
  336. = JSON::Parser::getValue(expected->getAttributeValue("default"));
  337. ValidationResult* res
  338. = DataValidator(dynamic_cast<XML::Element*>(expected->getThis()))
  339. .validate(def);
  340. res->addBasePath(path);
  341. if (res->isValid())
  342. {
  343. res->release();
  344. return def;
  345. }
  346. else if (res->isDifferent(this))
  347. {
  348. def->release();
  349. JSON::JSONValue* result
  350. = res->getValidPart(removedPartsValidationResults);
  351. res->release();
  352. return result;
  353. }
  354. def->release();
  355. }
  356. if (removedPartsValidationResults)
  357. {
  358. removedPartsValidationResults->add(
  359. dynamic_cast<ValidationResult*>(getThis()));
  360. }
  361. return 0;
  362. }
  363. Text MissingValue::getPath() const
  364. {
  365. return path;
  366. }
  367. bool MissingValue::isDifferent(const ValidationResult* zResult) const
  368. {
  369. const MissingValue* casted = dynamic_cast<const MissingValue*>(zResult);
  370. if (casted == 0) return 1;
  371. if (!casted->getPath().isEqual(path)) return 1;
  372. return 0;
  373. }
  374. void MissingValue::addBasePath(Text basePath)
  375. {
  376. path = basePath + path;
  377. }
  378. #pragma endregion Cotent
  379. #pragma region MissingOneOf
  380. MissingOneOf::MissingOneOf(Text path, XML::Editor expected)
  381. : ValidationResult()
  382. {
  383. this->path = path;
  384. for (XML::Element* e : expected)
  385. this->expected.add(dynamic_cast<XML::Element*>(e->getThis()));
  386. }
  387. MissingOneOf::~MissingOneOf() {}
  388. bool MissingOneOf::isValid() const
  389. {
  390. return 0;
  391. }
  392. Text MissingOneOf::getInvalidInfo(int indent) const
  393. {
  394. Text ind = "";
  395. ind.fillText(' ', indent);
  396. Text error = "";
  397. error.append() << ind.getText() << "Missing Value at '" << path.getText()
  398. << "'. The value should have one of the specified types:\n";
  399. ind += " ";
  400. for (XML::Element* e : expected)
  401. {
  402. error.append() << ind.getText() << e->toString().getText() << "\n";
  403. }
  404. return error;
  405. }
  406. JSON::JSONValue* MissingOneOf::getValidPart(
  407. RCArray<ValidationResult>* removedPartsValidationResults)
  408. {
  409. for (XML::Element* e : expected)
  410. {
  411. if (e->hasAttribute("default"))
  412. {
  413. JSON::JSONValue* defaultValue
  414. = JSON::Parser::getValue(e->getAttributeValue("default"));
  415. if (defaultValue)
  416. {
  417. JSON::JSONValue* valid
  418. = DataValidator(dynamic_cast<XML::Element*>(e->getThis()))
  419. .getValidParts(
  420. defaultValue, removedPartsValidationResults);
  421. defaultValue->release();
  422. if (valid)
  423. {
  424. return valid;
  425. }
  426. }
  427. }
  428. }
  429. if (removedPartsValidationResults)
  430. {
  431. removedPartsValidationResults->add(
  432. dynamic_cast<ValidationResult*>(getThis()));
  433. }
  434. // multiple possibilities are undecidable
  435. return 0;
  436. }
  437. Text MissingOneOf::getPath() const
  438. {
  439. return path;
  440. }
  441. bool MissingOneOf::isDifferent(const ValidationResult* zResult) const
  442. {
  443. const MissingOneOf* casted = dynamic_cast<const MissingOneOf*>(zResult);
  444. if (casted == 0) return 1;
  445. if (!casted->getPath().isEqual(path)) return 1;
  446. return 0;
  447. }
  448. void MissingOneOf::addBasePath(Text basePath)
  449. {
  450. path = basePath + path;
  451. }
  452. #pragma endregion Content
  453. #pragma region NoTypeMatching
  454. NoTypeMatching::NoTypeMatching(Text path,
  455. AbstractElement* foundValue,
  456. RCArray<XML::Element>& expected,
  457. RCArray<ValidationResult>& reasons)
  458. : ValidationResult()
  459. {
  460. this->path = path;
  461. this->foundValue = foundValue;
  462. this->expected = expected;
  463. this->reasons = reasons;
  464. }
  465. NoTypeMatching::~NoTypeMatching()
  466. {
  467. foundValue->release();
  468. }
  469. bool NoTypeMatching::isValid() const
  470. {
  471. return 0;
  472. }
  473. Text NoTypeMatching::getInvalidInfo(int indent) const
  474. {
  475. Text ind = "";
  476. ind.fillText(' ', indent);
  477. Text error = "";
  478. error.append() << ind.getText() << "Found Value at '" << path.getText()
  479. << "' did not match any of the specified types\n";
  480. Text ind2 = ind + " ";
  481. error.append() << ind.getText() << "Reasons:\n";
  482. for (ValidationResult* reason : reasons)
  483. {
  484. error += reason->getInvalidInfo(indent + 4);
  485. }
  486. return error;
  487. }
  488. JSON::JSONValue* NoTypeMatching::getValidPart(
  489. RCArray<ValidationResult>* removedPartsValidationResults)
  490. {
  491. RCArray<ValidationResult> tempErrors;
  492. for (ValidationResult* reason : reasons)
  493. {
  494. JSON::JSONValue* result = reason->getValidPart(&tempErrors);
  495. if (result)
  496. {
  497. return result;
  498. }
  499. }
  500. if (removedPartsValidationResults)
  501. {
  502. removedPartsValidationResults->add(
  503. dynamic_cast<ValidationResult*>(getThis()));
  504. reasons.clear();
  505. for (ValidationResult* error : tempErrors)
  506. {
  507. reasons.add(dynamic_cast<ValidationResult*>(error->getThis()));
  508. }
  509. }
  510. // multiple possibilities are undecidable
  511. return 0;
  512. }
  513. Text NoTypeMatching::getPath() const
  514. {
  515. return path;
  516. }
  517. bool NoTypeMatching::isDifferent(const ValidationResult* zResult) const
  518. {
  519. const NoTypeMatching* casted = dynamic_cast<const NoTypeMatching*>(zResult);
  520. if (casted == 0) return 1;
  521. if (!casted->getPath().isEqual(path)) return 1;
  522. for (int i = 0; i < reasons.getEntryCount(); i++)
  523. {
  524. if (reasons.z(i)->isDifferent(casted->reasons.z(i))) return 1;
  525. }
  526. return 0;
  527. }
  528. void NoTypeMatching::addBasePath(Text basePath)
  529. {
  530. path = basePath + path;
  531. for (ValidationResult* reason : reasons)
  532. {
  533. reason->addBasePath(basePath);
  534. }
  535. }
  536. #pragma endregion Content
  537. #pragma region ValidationPathNotFound
  538. ValidationPathNotFound::ValidationPathNotFound(
  539. Text path, AbstractElement* foundValue, Text validationPath)
  540. : ValidationResult()
  541. {
  542. this->path = path;
  543. this->foundValue = foundValue;
  544. this->validationPath = validationPath;
  545. }
  546. ValidationPathNotFound::~ValidationPathNotFound()
  547. {
  548. foundValue->release();
  549. }
  550. bool ValidationPathNotFound::isValid() const
  551. {
  552. return false;
  553. }
  554. Text ValidationPathNotFound::getInvalidInfo(int indent) const
  555. {
  556. Text result;
  557. result.append() << "Expected to validate path '" << validationPath.getText()
  558. << "' but at path '" << path.getText() << "' the value "
  559. << foundValue->toString().getText() << " was found.";
  560. return result;
  561. }
  562. JSON::JSONValue* ValidationPathNotFound::getValidPart(
  563. RCArray<ValidationResult>* zRemovedPartsValidationResults)
  564. {
  565. return 0;
  566. }
  567. Text ValidationPathNotFound::getPath() const
  568. {
  569. return path;
  570. }
  571. bool ValidationPathNotFound::isDifferent(const ValidationResult* zResult) const
  572. {
  573. const ValidationPathNotFound* other
  574. = dynamic_cast<const ValidationPathNotFound*>(zResult);
  575. if (other == 0) return 1;
  576. if (!other->path.isEqual(path)) return 1;
  577. return 0;
  578. }
  579. void ValidationPathNotFound::addBasePath(Text basePath)
  580. {
  581. path = basePath + path;
  582. }
  583. #pragma endregion Content
  584. #pragma region ValidValue
  585. ValidValue::ValidValue(Text path, AbstractElement* value)
  586. : ValidationResult()
  587. {
  588. this->path = path;
  589. this->value = value;
  590. }
  591. ValidValue::~ValidValue()
  592. {
  593. value->release();
  594. }
  595. bool ValidValue::isValid() const
  596. {
  597. return 1;
  598. }
  599. Text ValidValue::getInvalidInfo(int indent) const
  600. {
  601. return "";
  602. }
  603. JSON::JSONValue* ValidValue::getValidPart(
  604. RCArray<ValidationResult>* removedPartsValidationResults)
  605. {
  606. JSON::JSONValue* json = dynamic_cast<JSON::JSONValue*>(value);
  607. return json ? json->clone() : 0;
  608. }
  609. Text ValidValue::getPath() const
  610. {
  611. return path;
  612. }
  613. bool ValidValue::isDifferent(const ValidationResult* zResult) const
  614. {
  615. const ValidValue* casted = dynamic_cast<const ValidValue*>(zResult);
  616. if (casted == 0) return 1;
  617. if (!casted->getPath().isEqual(path)) return 1;
  618. return 0;
  619. }
  620. void ValidValue::addBasePath(Text basePath)
  621. {
  622. path = basePath + path;
  623. }
  624. #pragma endregion Content
  625. #pragma endregion Content
  626. #pragma region DataValidator
  627. DataValidator::DataValidator(XML::Element* constraints)
  628. : ReferenceCounter(),
  629. constraints(constraints),
  630. typeConstraints(new RCTrie<XML::Element>())
  631. {
  632. for (XML::Element* e :
  633. constraints->select().selectAllElements().whereAttributeExists("id"))
  634. {
  635. Framework::Text id = e->getAttributeValue("id");
  636. typeConstraints->set(
  637. id, id.getLength(), dynamic_cast<XML::Element*>(e->getThis()));
  638. }
  639. }
  640. DataValidator::DataValidator(
  641. XML::Element* constraints, RCTrie<XML::Element>* typeConstraints)
  642. : ReferenceCounter(),
  643. constraints(constraints),
  644. typeConstraints(typeConstraints)
  645. {}
  646. DataValidator::~DataValidator()
  647. {
  648. constraints->release();
  649. typeConstraints->release();
  650. }
  651. ValidationResult* DataValidator::validate(AbstractElement* zValue) const
  652. {
  653. return validate(ElementPathBuilder().build(), zValue);
  654. }
  655. ValidationResult* Framework::Validator::DataValidator::validate(
  656. ElementPath* path, AbstractElement* zValue) const
  657. {
  658. ValidationResult* result = validate(path, zValue, constraints, "");
  659. path->release();
  660. return result;
  661. }
  662. bool DataValidator::isValid(AbstractElement* zValue) const
  663. {
  664. ValidationResult* res = validate(zValue);
  665. if (res->isValid())
  666. {
  667. res->release();
  668. return 1;
  669. }
  670. res->release();
  671. return 0;
  672. }
  673. JSON::JSONValue* DataValidator::getValidParts(JSON::JSONValue* zValue,
  674. RCArray<ValidationResult>* removedPartsValidationResults) const
  675. {
  676. ValidationResult* res = validate(zValue);
  677. if (res->isValid())
  678. {
  679. res->release();
  680. return zValue->clone();
  681. }
  682. JSON::JSONValue* valid = res->getValidPart(removedPartsValidationResults);
  683. res->release();
  684. return valid;
  685. }
  686. XML::Element* DataValidator::zConstraints()
  687. {
  688. return constraints;
  689. }
  690. JSON::JSONObject* Framework::Validator::DataValidator::getJsonSchema() const
  691. {
  692. JSON::JSONObject* zDefs = new JSON::JSONObject();
  693. JSON::JSONObject* result = getJsonSchema(constraints, zDefs);
  694. if (zDefs->getFieldCount() > 0)
  695. {
  696. result->addValue("$defs", zDefs);
  697. }
  698. else
  699. {
  700. zDefs->release();
  701. }
  702. result->addValue("$schema",
  703. new JSON::JSONString("https://json-schema.org/draft-04/schema#"));
  704. return result;
  705. }
  706. void Framework::Validator::DataValidator::updateValidator(
  707. Text id, DataValidator* validator)
  708. {
  709. typeConstraints->set(id, id.getLength(), validator->constraints);
  710. validator->release();
  711. }
  712. ValidationResult* DataValidator::validate(ElementPath* pathToValidate,
  713. AbstractElement* zValue,
  714. XML::Element* zConstraints,
  715. Text path) const
  716. {
  717. if (zConstraints->getName().isEqual("oneOf"))
  718. {
  719. return validateMultipleTypes(
  720. pathToValidate, zValue, zConstraints, path);
  721. }
  722. if (zConstraints->getName().isEqual("ref"))
  723. {
  724. Text id = zConstraints->getAttributeValue("ref");
  725. XML::Element* e = typeConstraints->z(id, id.getLength());
  726. if (e)
  727. {
  728. zConstraints = e;
  729. }
  730. }
  731. switch (zValue->getType())
  732. {
  733. case AbstractType::NULL_:
  734. if (pathToValidate->isValid())
  735. {
  736. return new ValidationPathNotFound(path,
  737. dynamic_cast<AbstractElement*>(zValue->getThis()),
  738. pathToValidate->toString());
  739. }
  740. if (!zConstraints->hasAttribute("nullable")
  741. || !zConstraints->getAttributeValue("nullable").isEqual("true"))
  742. {
  743. return new TypeMissmatch(path,
  744. dynamic_cast<AbstractElement*>(zValue->getThis()),
  745. dynamic_cast<XML::Element*>(zConstraints->getThis()),
  746. 0);
  747. }
  748. break;
  749. case AbstractType::BOOLEAN:
  750. if (pathToValidate->isValid())
  751. {
  752. return new ValidationPathNotFound(path,
  753. dynamic_cast<AbstractElement*>(zValue->getThis()),
  754. pathToValidate->toString());
  755. }
  756. if (!zConstraints->getName().isEqual("bool"))
  757. {
  758. return new TypeMissmatch(path,
  759. dynamic_cast<AbstractElement*>(zValue->getThis()),
  760. dynamic_cast<XML::Element*>(zConstraints->getThis()),
  761. 0);
  762. }
  763. else if (zConstraints->hasAttribute("equals"))
  764. {
  765. if (!zConstraints->getAttributeValue("equals").isEqual("true")
  766. == !zValue->asAbstractBool()->getBool())
  767. {
  768. return new TypeMissmatch(path,
  769. dynamic_cast<AbstractElement*>(zValue->getThis()),
  770. dynamic_cast<XML::Element*>(zConstraints->getThis()),
  771. 0);
  772. }
  773. }
  774. break;
  775. case AbstractType::NUMBER:
  776. if (pathToValidate->isValid())
  777. {
  778. return new ValidationPathNotFound(path,
  779. dynamic_cast<AbstractElement*>(zValue->getThis()),
  780. pathToValidate->toString());
  781. }
  782. if (!zConstraints->getName().isEqual("number"))
  783. {
  784. return new TypeMissmatch(path,
  785. dynamic_cast<AbstractElement*>(zValue->getThis()),
  786. dynamic_cast<XML::Element*>(zConstraints->getThis()),
  787. 0);
  788. }
  789. else
  790. {
  791. double number = zValue->asAbstractNumber()->getNumber();
  792. if (zConstraints->hasAttribute("equals")
  793. && (double)zConstraints->getAttributeValue("equals") != number)
  794. {
  795. return new TypeMissmatch(path,
  796. dynamic_cast<AbstractElement*>(zValue->getThis()),
  797. dynamic_cast<XML::Element*>(zConstraints->getThis()),
  798. 0);
  799. }
  800. if (zConstraints->hasAttribute("lessOrEqual")
  801. && number
  802. > (double)zConstraints->getAttributeValue("lessOrEqual"))
  803. {
  804. return new TypeMissmatch(path,
  805. dynamic_cast<AbstractElement*>(zValue->getThis()),
  806. dynamic_cast<XML::Element*>(zConstraints->getThis()),
  807. 0);
  808. }
  809. if (zConstraints->hasAttribute("greaterOrEqual")
  810. && number < (double)zConstraints->getAttributeValue(
  811. "greaterOrEqual"))
  812. {
  813. return new TypeMissmatch(path,
  814. dynamic_cast<AbstractElement*>(zValue->getThis()),
  815. dynamic_cast<XML::Element*>(zConstraints->getThis()),
  816. 0);
  817. }
  818. if (zConstraints->hasAttribute("less")
  819. && number >= (double)zConstraints->getAttributeValue("less"))
  820. {
  821. return new TypeMissmatch(path,
  822. dynamic_cast<AbstractElement*>(zValue->getThis()),
  823. dynamic_cast<XML::Element*>(zConstraints->getThis()),
  824. 0);
  825. }
  826. if (zConstraints->hasAttribute("greater")
  827. && number <= (double)zConstraints->getAttributeValue("greater"))
  828. {
  829. return new TypeMissmatch(path,
  830. dynamic_cast<AbstractElement*>(zValue->getThis()),
  831. dynamic_cast<XML::Element*>(zConstraints->getThis()),
  832. 0);
  833. }
  834. }
  835. break;
  836. case AbstractType::STRING:
  837. if (pathToValidate->isValid())
  838. {
  839. return new ValidationPathNotFound(path,
  840. dynamic_cast<AbstractElement*>(zValue->getThis()),
  841. pathToValidate->toString());
  842. }
  843. if (!zConstraints->getName().isEqual("string"))
  844. {
  845. return new TypeMissmatch(path,
  846. dynamic_cast<AbstractElement*>(zValue->getThis()),
  847. dynamic_cast<XML::Element*>(zConstraints->getThis()),
  848. 0);
  849. }
  850. else
  851. {
  852. Text string = zValue->asAbstractString()->getString();
  853. if (zConstraints->hasAttribute("equals")
  854. && !zConstraints->getAttributeValue("equals").isEqual(string))
  855. {
  856. return new TypeMissmatch(path,
  857. dynamic_cast<AbstractElement*>(zValue->getThis()),
  858. dynamic_cast<XML::Element*>(zConstraints->getThis()),
  859. 0);
  860. }
  861. if (zConstraints->hasAttribute("contains")
  862. && !string.has(
  863. zConstraints->getAttributeValue("contains").getText()))
  864. {
  865. return new TypeMissmatch(path,
  866. dynamic_cast<AbstractElement*>(zValue->getThis()),
  867. dynamic_cast<XML::Element*>(zConstraints->getThis()),
  868. 0);
  869. }
  870. if (zConstraints->hasAttribute("startsWith")
  871. && string.positionOf(
  872. zConstraints->getAttributeValue("startsWith").getText())
  873. != 0)
  874. {
  875. return new TypeMissmatch(path,
  876. dynamic_cast<AbstractElement*>(zValue->getThis()),
  877. dynamic_cast<XML::Element*>(zConstraints->getThis()),
  878. 0);
  879. }
  880. if (zConstraints->hasAttribute("endsWith")
  881. && !string.hasAt(
  882. string.getLength()
  883. - zConstraints->getAttributeValue("endsWith")
  884. .getLength(),
  885. zConstraints->getAttributeValue("endsWith").getText()))
  886. {
  887. return new TypeMissmatch(path,
  888. dynamic_cast<AbstractElement*>(zValue->getThis()),
  889. dynamic_cast<XML::Element*>(zConstraints->getThis()),
  890. 0);
  891. }
  892. if (zConstraints->hasAttribute("oneOf"))
  893. {
  894. JSON::JSONArray* array = JSON::Parser::getValue(
  895. zConstraints->getAttributeValue("oneOf"))
  896. ->asArray();
  897. bool ok = 0;
  898. for (JSON::JSONValue* v : *array)
  899. {
  900. if (v->asString()->getString().isEqual(string))
  901. {
  902. ok = 1;
  903. break;
  904. }
  905. }
  906. array->release();
  907. if (!ok)
  908. {
  909. return new TypeMissmatch(path,
  910. dynamic_cast<AbstractElement*>(zValue->getThis()),
  911. dynamic_cast<XML::Element*>(zConstraints->getThis()),
  912. 0);
  913. }
  914. }
  915. }
  916. break;
  917. case AbstractType::ARRAY:
  918. if (!zConstraints->getName().isEqual("array"))
  919. {
  920. return new TypeMissmatch(path,
  921. dynamic_cast<AbstractElement*>(zValue->getThis()),
  922. dynamic_cast<XML::Element*>(zConstraints->getThis()),
  923. 0);
  924. }
  925. else
  926. {
  927. if (pathToValidate->isValid())
  928. {
  929. if (!pathToValidate->isArrayElement())
  930. {
  931. return new ValidationPathNotFound(path,
  932. dynamic_cast<AbstractElement*>(zValue->getThis()),
  933. pathToValidate->toString());
  934. }
  935. else
  936. {
  937. int index = pathToValidate->getArrayIndex();
  938. const AbstractArray* array = zValue->asAbstractArray();
  939. if (index >= array->getLength())
  940. {
  941. return new ValidationPathNotFound(path,
  942. dynamic_cast<AbstractElement*>(zValue->getThis()),
  943. pathToValidate->toString());
  944. }
  945. Text p = path;
  946. p += "[";
  947. p += index;
  948. p += "]";
  949. pathToValidate->next();
  950. return validateMultipleTypes(pathToValidate,
  951. array->zAbstractValue(index),
  952. zConstraints,
  953. p);
  954. }
  955. }
  956. const AbstractArray* array = zValue->asAbstractArray();
  957. if (zConstraints->hasAttribute("minSize")
  958. && (int)zConstraints->getAttributeValue("minSize")
  959. > array->getLength())
  960. {
  961. return new TypeMissmatch(path,
  962. dynamic_cast<AbstractElement*>(zValue->getThis()),
  963. dynamic_cast<XML::Element*>(zConstraints->getThis()),
  964. 0);
  965. }
  966. if (zConstraints->hasAttribute("maxSize")
  967. && (int)zConstraints->getAttributeValue("maxSize")
  968. < array->getLength())
  969. {
  970. return new TypeMissmatch(path,
  971. dynamic_cast<AbstractElement*>(zValue->getThis()),
  972. dynamic_cast<XML::Element*>(zConstraints->getThis()),
  973. 0);
  974. }
  975. for (int i = 0; i < array->getLength(); i++)
  976. {
  977. Text p = path;
  978. p += "[";
  979. p += i;
  980. p += "]";
  981. ValidationResult* res = validateMultipleTypes(
  982. pathToValidate, array->zAbstractValue(i), zConstraints, p);
  983. if (!res->isValid())
  984. {
  985. return new TypeMissmatch(path,
  986. dynamic_cast<AbstractElement*>(zValue->getThis()),
  987. dynamic_cast<XML::Element*>(zConstraints->getThis()),
  988. res);
  989. }
  990. else
  991. {
  992. res->release();
  993. }
  994. }
  995. }
  996. break;
  997. case AbstractType::OBJECT:
  998. if (!zConstraints->getName().isEqual("object"))
  999. {
  1000. return new TypeMissmatch(path,
  1001. dynamic_cast<AbstractElement*>(zValue->getThis()),
  1002. dynamic_cast<XML::Element*>(zConstraints->getThis()),
  1003. 0);
  1004. }
  1005. else
  1006. {
  1007. if (pathToValidate->isValid())
  1008. {
  1009. if (!pathToValidate->isObjectAttribute())
  1010. {
  1011. return new ValidationPathNotFound(path,
  1012. dynamic_cast<AbstractElement*>(zValue->getThis()),
  1013. pathToValidate->toString());
  1014. }
  1015. else
  1016. {
  1017. Text key = pathToValidate->getObjectAttribute();
  1018. const AbstractObject* obj = zValue->asAbstractObject();
  1019. if (!obj->hasValue(key))
  1020. {
  1021. return new ValidationPathNotFound(path,
  1022. dynamic_cast<AbstractElement*>(zValue->getThis()),
  1023. pathToValidate->toString());
  1024. }
  1025. Text p = path;
  1026. p += ".";
  1027. p += key;
  1028. if (!zConstraints->selectChildsByAttribute("name", key)
  1029. .exists())
  1030. {
  1031. if (!zConstraints
  1032. ->getAttributeValue("allowAdditionalAttributes")
  1033. .isEqual("true"))
  1034. {
  1035. return new TypeMissmatch(path,
  1036. dynamic_cast<AbstractElement*>(
  1037. zValue->getThis()),
  1038. dynamic_cast<XML::Element*>(
  1039. zConstraints->getThis()),
  1040. new UnknownValue(p,
  1041. dynamic_cast<AbstractElement*>(
  1042. obj->zAbstractValue(key)->getThis())));
  1043. }
  1044. }
  1045. else
  1046. {
  1047. XML::Editor tmp = zConstraints->selectChildsByAttribute(
  1048. "name", key);
  1049. pathToValidate->next();
  1050. return validateMultipleTypes(pathToValidate,
  1051. obj->zAbstractValue(key),
  1052. tmp.begin().val(),
  1053. p);
  1054. }
  1055. }
  1056. }
  1057. const AbstractObject* obj = zValue->asAbstractObject();
  1058. for (int i = 0; i < obj->getFieldCount(); i++)
  1059. {
  1060. Text key = obj->getFieldKey(i);
  1061. Text p = path;
  1062. p += ".";
  1063. p += key;
  1064. if (!zConstraints->selectChildsByAttribute("name", key)
  1065. .exists())
  1066. {
  1067. if (!zConstraints
  1068. ->getAttributeValue("allowAdditionalAttributes")
  1069. .isEqual("true"))
  1070. {
  1071. return new TypeMissmatch(path,
  1072. dynamic_cast<AbstractElement*>(zValue->getThis()),
  1073. dynamic_cast<XML::Element*>(
  1074. zConstraints->getThis()),
  1075. new UnknownValue(p,
  1076. dynamic_cast<AbstractElement*>(
  1077. obj->zAbstractValue(i)->getThis())));
  1078. }
  1079. }
  1080. else
  1081. {
  1082. XML::Editor tmp
  1083. = zConstraints->selectChildsByAttribute("name", key);
  1084. ValidationResult* res
  1085. = validateMultipleTypes(pathToValidate,
  1086. obj->zAbstractValue(i),
  1087. tmp.begin().val(),
  1088. p);
  1089. if (!res->isValid())
  1090. {
  1091. return new TypeMissmatch(path,
  1092. dynamic_cast<AbstractElement*>(zValue->getThis()),
  1093. dynamic_cast<XML::Element*>(
  1094. zConstraints->getThis()),
  1095. res);
  1096. }
  1097. res->release();
  1098. }
  1099. }
  1100. for (XML::Element* constraint : zConstraints->selectChildren())
  1101. {
  1102. if (!obj->hasValue(constraint->getAttributeValue("name")))
  1103. {
  1104. XML::Editor tmp = constraint->selectChildren();
  1105. bool optional = true;
  1106. std::function<void(XML::Element*)> checkOptional;
  1107. checkOptional = [&optional, &checkOptional](
  1108. XML::Element* zElement) {
  1109. if (zElement->getName().isEqual("oneOf")
  1110. && (!zElement->hasAttribute("optional")
  1111. || !zElement->getAttributeValue("optional")
  1112. .isEqual("true")))
  1113. {
  1114. XML::Editor tmp = zElement->selectChildren();
  1115. tmp.forEach(checkOptional);
  1116. }
  1117. else
  1118. {
  1119. optional &= zElement->hasAttribute("optional")
  1120. && zElement->getAttributeValue("optional")
  1121. .isEqual("true");
  1122. }
  1123. };
  1124. tmp.forEach(checkOptional);
  1125. if (!optional)
  1126. {
  1127. Text p = path;
  1128. p += ".";
  1129. p += constraint->getAttributeValue("name");
  1130. if (constraint->getChildCount() != 1)
  1131. return new TypeMissmatch(path,
  1132. dynamic_cast<AbstractElement*>(
  1133. zValue->getThis()),
  1134. dynamic_cast<XML::Element*>(
  1135. zConstraints->getThis()),
  1136. new MissingOneOf(p, tmp));
  1137. return new TypeMissmatch(path,
  1138. dynamic_cast<AbstractElement*>(zValue->getThis()),
  1139. dynamic_cast<XML::Element*>(
  1140. zConstraints->getThis()),
  1141. new MissingValue(p,
  1142. dynamic_cast<XML::Element*>(
  1143. tmp.begin()->getThis())));
  1144. }
  1145. }
  1146. }
  1147. }
  1148. break;
  1149. }
  1150. return new ValidValue(
  1151. path, dynamic_cast<AbstractElement*>(zValue->getThis()));
  1152. }
  1153. ValidationResult* DataValidator::validateMultipleTypes(
  1154. ElementPath* pathToValidate,
  1155. AbstractElement* zChildValue,
  1156. XML::Element* zPossibleChildConstraints,
  1157. Text childPath) const
  1158. {
  1159. if (zPossibleChildConstraints->getChildCount() == 1
  1160. && !zPossibleChildConstraints->hasAttribute("typeSpecifiedBy"))
  1161. {
  1162. XML::Editor children = zPossibleChildConstraints->selectChildren();
  1163. return validate(pathToValidate,
  1164. zChildValue,
  1165. children.begin().val(),
  1166. childPath); // only one type is possible
  1167. }
  1168. bool hasTypeAttr = 0;
  1169. RCArray<XML::Element> possibleConstraints;
  1170. if (zPossibleChildConstraints->hasAttribute("typeSpecifiedBy"))
  1171. { // try to find the correct constraints based on the type attribute
  1172. hasTypeAttr = 1;
  1173. Text typeAttr
  1174. = zPossibleChildConstraints->getAttributeValue("typeSpecifiedBy");
  1175. if (zChildValue->getType() == AbstractType::OBJECT)
  1176. {
  1177. const AbstractObject* obj = zChildValue->asAbstractObject();
  1178. if (obj->hasValue(typeAttr))
  1179. {
  1180. AbstractElement* typeV = obj->zAbstractValue(typeAttr);
  1181. ElementPath* tmp = ElementPathBuilder().build();
  1182. for (XML::Element* constraint :
  1183. zPossibleChildConstraints->selectChildsByName("object")
  1184. .whereChildWithAttributeExists("name", typeAttr))
  1185. {
  1186. XML::Editor nameChildren
  1187. = constraint->selectChildsByAttribute("name", typeAttr);
  1188. XML::Element* typeAttrContraints
  1189. = nameChildren.begin().val();
  1190. ValidationResult* res = validateMultipleTypes(tmp,
  1191. typeV,
  1192. typeAttrContraints,
  1193. childPath + "." + typeAttr);
  1194. if (res->isValid())
  1195. possibleConstraints.add(
  1196. dynamic_cast<XML::Element*>(constraint->getThis()));
  1197. res->release();
  1198. }
  1199. tmp->release();
  1200. }
  1201. }
  1202. }
  1203. if (hasTypeAttr && possibleConstraints.getEntryCount() == 1)
  1204. return validate(pathToValidate,
  1205. zChildValue,
  1206. possibleConstraints.begin().val(),
  1207. childPath); // if the type is clear
  1208. else if (hasTypeAttr && possibleConstraints.getEntryCount() > 0)
  1209. { // more then one type is possible
  1210. RCArray<ValidationResult> invalidResults;
  1211. int index = pathToValidate->getCurrentPathElementIndex();
  1212. for (XML::Element* constraint : possibleConstraints)
  1213. {
  1214. pathToValidate->setCurrentPathElementIndex(index);
  1215. ValidationResult* res
  1216. = validate(pathToValidate, zChildValue, constraint, childPath);
  1217. invalidResults.add(res);
  1218. if (res->isValid())
  1219. return new ValidValue(childPath,
  1220. dynamic_cast<AbstractElement*>(zChildValue->getThis()));
  1221. }
  1222. return new NoTypeMatching(childPath,
  1223. dynamic_cast<AbstractElement*>(zChildValue->getThis()),
  1224. possibleConstraints,
  1225. invalidResults);
  1226. }
  1227. // try all types
  1228. possibleConstraints.clear();
  1229. RCArray<ValidationResult> invalidResults;
  1230. int index = pathToValidate->getCurrentPathElementIndex();
  1231. for (XML::Element* constraint : zPossibleChildConstraints->selectChildren())
  1232. {
  1233. pathToValidate->setCurrentPathElementIndex(index);
  1234. ValidationResult* res
  1235. = validate(pathToValidate, zChildValue, constraint, childPath);
  1236. invalidResults.add(res);
  1237. if (res->isValid())
  1238. return new ValidValue(childPath,
  1239. dynamic_cast<AbstractElement*>(zChildValue->getThis()));
  1240. possibleConstraints.add(
  1241. dynamic_cast<XML::Element*>(constraint->getThis()));
  1242. }
  1243. pathToValidate->setCurrentPathElementIndex(index);
  1244. if (pathToValidate->isValid())
  1245. {
  1246. return new ValidationPathNotFound(childPath,
  1247. dynamic_cast<AbstractElement*>(zChildValue->getThis()),
  1248. pathToValidate->toString());
  1249. }
  1250. return new NoTypeMatching(childPath,
  1251. dynamic_cast<AbstractElement*>(zChildValue->getThis()),
  1252. possibleConstraints,
  1253. invalidResults);
  1254. }
  1255. JSON::JSONObject* Framework::Validator::DataValidator::getJsonSchema(
  1256. XML::Element* zConstraint, JSON::JSONObject* zDefs) const
  1257. {
  1258. JSON::JSONObject* result = new JSON::JSONObject();
  1259. if (zConstraint->hasAttribute("id"))
  1260. {
  1261. Text id = zConstraint->getAttributeValue("id");
  1262. id.replace(" ", "_");
  1263. if (zDefs->hasValue(id))
  1264. {
  1265. Text jsonRef = Text("#/$defs/") + id;
  1266. result->addValue("$ref", new JSON::JSONString(jsonRef));
  1267. return result;
  1268. }
  1269. zDefs->addValue(id, new JSON::JSONValue()); // avoid endless recursion
  1270. // for cyclic datastructures
  1271. }
  1272. if (zConstraint->getName().isEqual("bool"))
  1273. {
  1274. if (zConstraint->hasAttribute("equals"))
  1275. {
  1276. JSON::JSONArray* array = new JSON::JSONArray();
  1277. array->addValue(new JSON::JSONBool(
  1278. zConstraint->getAttributeValue("equals").isEqual("true")));
  1279. result->addValue("enum", array);
  1280. }
  1281. else
  1282. {
  1283. result->addValue("type", new JSON::JSONString("boolean"));
  1284. }
  1285. }
  1286. else if (zConstraint->getName().isEqual("number"))
  1287. {
  1288. if (zConstraint->hasAttribute("equals"))
  1289. {
  1290. JSON::JSONArray* array = new JSON::JSONArray();
  1291. array->addValue(new JSON::JSONNumber(
  1292. (double)zConstraint->getAttributeValue("equals")));
  1293. result->addValue("enum", array);
  1294. }
  1295. else
  1296. {
  1297. result->addValue("type", new JSON::JSONString("number"));
  1298. if (zConstraint->hasAttribute("lessOrEqual"))
  1299. {
  1300. result->addValue("maximum",
  1301. new JSON::JSONNumber(
  1302. (double)zConstraint->getAttributeValue("lessOrEqual")));
  1303. }
  1304. if (zConstraint->hasAttribute("greaterOrEqual"))
  1305. {
  1306. result->addValue("minimum",
  1307. new JSON::JSONNumber((double)zConstraint->getAttributeValue(
  1308. "greaterOrEqual")));
  1309. }
  1310. if (zConstraint->hasAttribute("less"))
  1311. {
  1312. result->addValue("maximum",
  1313. new JSON::JSONNumber(
  1314. (double)zConstraint->getAttributeValue("less")));
  1315. result->addValue("exclusiveMaximum", new JSON::JSONBool(true));
  1316. }
  1317. if (zConstraint->hasAttribute("greater"))
  1318. {
  1319. result->addValue("minimum",
  1320. new JSON::JSONNumber(
  1321. (double)zConstraint->getAttributeValue("greater")));
  1322. result->addValue("exclusiveMinimum", new JSON::JSONBool(true));
  1323. }
  1324. }
  1325. }
  1326. else if (zConstraint->getName().isEqual("string"))
  1327. {
  1328. if (zConstraint->hasAttribute("equals"))
  1329. {
  1330. JSON::JSONArray* array = new JSON::JSONArray();
  1331. array->addValue(
  1332. new JSON::JSONString(zConstraint->getAttributeValue("equals")));
  1333. result->addValue("enum", array);
  1334. }
  1335. else if (zConstraint->hasAttribute("oneOf"))
  1336. {
  1337. JSON::JSONArray* array = JSON::Parser::getValue(
  1338. zConstraint->getAttributeValue("oneOf"))
  1339. ->asArray();
  1340. result->addValue("enum", array);
  1341. }
  1342. else
  1343. {
  1344. result->addValue("type", new JSON::JSONString("string"));
  1345. if (zConstraint->hasAttribute("contains"))
  1346. {
  1347. result->addValue("pattern",
  1348. new JSON::JSONString(
  1349. Text(".*")
  1350. + Regex::quote(
  1351. zConstraint->getAttributeValue("contains"))
  1352. + ".*"));
  1353. }
  1354. if (zConstraint->hasAttribute("startsWith"))
  1355. {
  1356. result->addValue("pattern",
  1357. new JSON::JSONString(
  1358. Text("^")
  1359. + Regex::quote(
  1360. zConstraint->getAttributeValue("startsWith"))
  1361. + ".*"));
  1362. }
  1363. if (zConstraint->hasAttribute("endsWith"))
  1364. {
  1365. result->addValue("pattern",
  1366. new JSON::JSONString(
  1367. Text(".*")
  1368. + Regex::quote(
  1369. zConstraint->getAttributeValue("endsWith"))
  1370. + "$"));
  1371. }
  1372. }
  1373. }
  1374. else if (zConstraint->getName().isEqual("ref"))
  1375. {
  1376. Text id = zConstraint->getAttributeValue("ref");
  1377. XML::Element* e = typeConstraints->z(id, id.getLength());
  1378. id.replace(" ", "_");
  1379. if (!zDefs->hasValue(id))
  1380. {
  1381. JSON::JSONObject* def = getJsonSchema(e, zDefs);
  1382. if (!zDefs->hasValue(id))
  1383. {
  1384. zDefs->addValue(id, def);
  1385. }
  1386. else
  1387. {
  1388. // def was already added by a child
  1389. def->release();
  1390. }
  1391. }
  1392. Text jsonRef = Text("#/$defs/") + id;
  1393. result->addValue("$ref", new JSON::JSONString(jsonRef));
  1394. }
  1395. else if (zConstraint->getName().isEqual("object"))
  1396. {
  1397. result->addValue("type", new JSON::JSONString("object"));
  1398. result->addValue("additionalProperties",
  1399. new JSON::JSONBool(
  1400. zConstraint->getAttributeValue("allowAdditionalAttributes")
  1401. .isEqual("true")));
  1402. JSON::JSONObject* properties = new JSON::JSONObject();
  1403. JSON::JSONArray* required = new JSON::JSONArray();
  1404. for (XML::Element* e : zConstraint->selectChildren())
  1405. {
  1406. JSON::JSONObject* prop = new JSON::JSONObject();
  1407. JSON::JSONArray* oneOf = new JSON::JSONArray();
  1408. bool isRequired = true;
  1409. for (XML::Element* child : e->selectChildren())
  1410. {
  1411. oneOf->addValue(getJsonSchema(child, zDefs));
  1412. isRequired
  1413. &= !child->getAttributeValue("optional").isEqual("true")
  1414. && !child->hasAttribute("default");
  1415. }
  1416. prop->addValue("oneOf", oneOf);
  1417. properties->addValue(e->getAttributeValue("name"), prop);
  1418. if (isRequired)
  1419. {
  1420. required->addValue(
  1421. new JSON::JSONString(e->getAttributeValue("name")));
  1422. }
  1423. }
  1424. result->addValue("properties", properties);
  1425. result->addValue("required", required);
  1426. }
  1427. else if (zConstraint->getName().isEqual("array"))
  1428. {
  1429. result->addValue("type", new JSON::JSONString("array"));
  1430. JSON::JSONObject* items = new JSON::JSONObject();
  1431. JSON::JSONArray* oneOf = new JSON::JSONArray();
  1432. for (XML::Element* e : zConstraint->selectChildren())
  1433. {
  1434. oneOf->addValue(getJsonSchema(e, zDefs));
  1435. }
  1436. if (zConstraint->hasAttribute("minSize"))
  1437. {
  1438. result->addValue("minItems",
  1439. new JSON::JSONNumber(
  1440. (double)zConstraint->getAttributeValue("minSize")));
  1441. }
  1442. if (zConstraint->hasAttribute("maxSize"))
  1443. {
  1444. result->addValue("maxItems",
  1445. new JSON::JSONNumber(
  1446. (double)zConstraint->getAttributeValue("maxSize")));
  1447. }
  1448. items->addValue("oneOf", oneOf);
  1449. result->addValue("items", items);
  1450. }
  1451. else if (zConstraint->getName().isEqual("oneOf"))
  1452. {
  1453. JSON::JSONArray* oneOf = new JSON::JSONArray();
  1454. for (XML::Element* e : zConstraint->selectChildren())
  1455. {
  1456. oneOf->addValue(getJsonSchema(e, zDefs));
  1457. }
  1458. result->addValue("oneOf", oneOf);
  1459. }
  1460. if (zConstraint->hasAttribute("nullable")
  1461. && zConstraint->getAttributeValue("nullable").isEqual("true"))
  1462. {
  1463. if (!result->hasValue("type"))
  1464. {
  1465. if (result->hasValue("enum"))
  1466. {
  1467. result->zValue("enum")->asArray()->addValue(
  1468. new JSON::JSONValue());
  1469. }
  1470. else
  1471. {
  1472. JSON::JSONObject* oneOf = new JSON::JSONObject();
  1473. JSON::JSONArray* array = new JSON::JSONArray();
  1474. array->addValue(result);
  1475. JSON::JSONObject* nullType = new JSON::JSONObject();
  1476. nullType->addValue("type", new JSON::JSONString("null"));
  1477. array->addValue(nullType);
  1478. oneOf->addValue("oneOf", array);
  1479. result = oneOf;
  1480. }
  1481. }
  1482. else
  1483. {
  1484. if (result->zValue("type")->getType() == AbstractType::ARRAY)
  1485. {
  1486. result->zValue("type")->asArray()->addValue(
  1487. new JSON::JSONString("null"));
  1488. }
  1489. else
  1490. {
  1491. JSON::JSONArray* array = new JSON::JSONArray();
  1492. array->addValue(result->getValue("type"));
  1493. array->addValue(new JSON::JSONString("null"));
  1494. result->removeValue("type");
  1495. result->addValue("type", array);
  1496. }
  1497. }
  1498. }
  1499. if (zConstraint->hasAttribute("id"))
  1500. {
  1501. Text id = zConstraint->getAttributeValue("id");
  1502. id.replace(" ", "_");
  1503. zDefs->removeValue(id);
  1504. zDefs->addValue(id, result);
  1505. result = new JSON::JSONObject();
  1506. Text jsonRef = Text("#/$defs/") + id;
  1507. result->addValue("$ref", new JSON::JSONString(jsonRef));
  1508. }
  1509. return result;
  1510. }
  1511. StringValidationBuilder<DataValidator>* DataValidator::buildForString()
  1512. {
  1513. return new StringValidationBuilder<DataValidator>(
  1514. [](XML::Element& e) { return new DataValidator(e.dublicate()); });
  1515. }
  1516. NumberValidationBuilder<DataValidator>* DataValidator::buildForNumber()
  1517. {
  1518. return new NumberValidationBuilder<DataValidator>(
  1519. [](XML::Element& e) { return new DataValidator(e.dublicate()); });
  1520. }
  1521. BoolValidationBuilder<DataValidator>* DataValidator::buildForBool()
  1522. {
  1523. return new BoolValidationBuilder<DataValidator>(
  1524. [](XML::Element& e) { return new DataValidator(e.dublicate()); });
  1525. }
  1526. ObjectValidationBuilder<DataValidator>* DataValidator::buildForObject()
  1527. {
  1528. return new ObjectValidationBuilder<DataValidator>(
  1529. [](XML::Element& e) { return new DataValidator(e.dublicate()); });
  1530. }
  1531. ArrayValidationBuilder<DataValidator>* DataValidator::buildForArray()
  1532. {
  1533. return new ArrayValidationBuilder<DataValidator>(
  1534. [](XML::Element& e) { return new DataValidator(e.dublicate()); });
  1535. }
  1536. DataValidator* DataValidator::buildForReference(Text id)
  1537. {
  1538. return new DataValidator(
  1539. new XML::Element(Text("<ref ref=\"") + id + Text("\"/>")));
  1540. }
  1541. OneOfValidationBuilder<DataValidator>* DataValidator::buildForOneOf()
  1542. {
  1543. return new OneOfValidationBuilder<DataValidator>(
  1544. [](XML::Element& e) { return new DataValidator(e.dublicate()); });
  1545. }