JsonNode.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605
  1. /*
  2. * JsonNode.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "JsonNode.h"
  12. #include "ScopeGuard.h"
  13. #include "HeroBonus.h"
  14. #include "filesystem/CResourceLoader.h"
  15. #include "VCMI_Lib.h" //for identifier resolution
  16. #include "CModHandler.h"
  17. using namespace JsonDetail;
  18. class LibClasses;
  19. class CModHandler;
  20. static const JsonNode nullNode;
  21. JsonNode::JsonNode(JsonType Type):
  22. type(DATA_NULL)
  23. {
  24. setType(Type);
  25. }
  26. JsonNode::JsonNode(const char *data, size_t datasize):
  27. type(DATA_NULL)
  28. {
  29. JsonParser parser(data, datasize);
  30. *this = parser.parse("<unknown>");
  31. }
  32. JsonNode::JsonNode(ResourceID && fileURI):
  33. type(DATA_NULL)
  34. {
  35. auto file = CResourceHandler::get()->loadData(fileURI);
  36. JsonParser parser(reinterpret_cast<char*>(file.first.get()), file.second);
  37. *this = parser.parse(fileURI.getName());
  38. }
  39. JsonNode::JsonNode(const JsonNode &copy):
  40. type(DATA_NULL)
  41. {
  42. meta = copy.meta;
  43. setType(copy.getType());
  44. switch(type)
  45. {
  46. break; case DATA_NULL:
  47. break; case DATA_BOOL: Bool() = copy.Bool();
  48. break; case DATA_FLOAT: Float() = copy.Float();
  49. break; case DATA_STRING: String() = copy.String();
  50. break; case DATA_VECTOR: Vector() = copy.Vector();
  51. break; case DATA_STRUCT: Struct() = copy.Struct();
  52. }
  53. }
  54. JsonNode::~JsonNode()
  55. {
  56. setType(DATA_NULL);
  57. }
  58. void JsonNode::swap(JsonNode &b)
  59. {
  60. using std::swap;
  61. swap(meta, b.meta);
  62. swap(data, b.data);
  63. swap(type, b.type);
  64. }
  65. JsonNode & JsonNode::operator =(JsonNode node)
  66. {
  67. swap(node);
  68. return *this;
  69. }
  70. bool JsonNode::operator == (const JsonNode &other) const
  71. {
  72. if (getType() == other.getType())
  73. {
  74. switch(type)
  75. {
  76. break; case DATA_NULL: return true;
  77. break; case DATA_BOOL: return Bool() == other.Bool();
  78. break; case DATA_FLOAT: return Float() == other.Float();
  79. break; case DATA_STRING: return String() == other.String();
  80. break; case DATA_VECTOR: return Vector() == other.Vector();
  81. break; case DATA_STRUCT: return Struct() == other.Struct();
  82. }
  83. }
  84. return false;
  85. }
  86. bool JsonNode::operator != (const JsonNode &other) const
  87. {
  88. return !(*this == other);
  89. }
  90. JsonNode::JsonType JsonNode::getType() const
  91. {
  92. return type;
  93. }
  94. void JsonNode::setMeta(std::string metadata, bool recursive)
  95. {
  96. meta = metadata;
  97. if (recursive)
  98. {
  99. switch (type)
  100. {
  101. break; case DATA_VECTOR:
  102. {
  103. BOOST_FOREACH(auto & node, Vector())
  104. {
  105. node.setMeta(metadata);
  106. }
  107. }
  108. break; case DATA_STRUCT:
  109. {
  110. BOOST_FOREACH(auto & node, Struct())
  111. {
  112. node.second.setMeta(metadata);
  113. }
  114. }
  115. }
  116. }
  117. }
  118. void JsonNode::setType(JsonType Type)
  119. {
  120. if (type == Type)
  121. return;
  122. //Reset node to NULL
  123. if (Type != DATA_NULL)
  124. setType(DATA_NULL);
  125. switch (type)
  126. {
  127. break; case DATA_STRING: delete data.String;
  128. break; case DATA_VECTOR: delete data.Vector;
  129. break; case DATA_STRUCT: delete data.Struct;
  130. break; default:
  131. break;
  132. }
  133. //Set new node type
  134. type = Type;
  135. switch(type)
  136. {
  137. break; case DATA_NULL:
  138. break; case DATA_BOOL: data.Bool = false;
  139. break; case DATA_FLOAT: data.Float = 0;
  140. break; case DATA_STRING: data.String = new std::string();
  141. break; case DATA_VECTOR: data.Vector = new JsonVector();
  142. break; case DATA_STRUCT: data.Struct = new JsonMap();
  143. }
  144. }
  145. bool JsonNode::isNull() const
  146. {
  147. return type == DATA_NULL;
  148. }
  149. void JsonNode::clear()
  150. {
  151. setType(DATA_NULL);
  152. }
  153. bool & JsonNode::Bool()
  154. {
  155. setType(DATA_BOOL);
  156. return data.Bool;
  157. }
  158. double & JsonNode::Float()
  159. {
  160. setType(DATA_FLOAT);
  161. return data.Float;
  162. }
  163. std::string & JsonNode::String()
  164. {
  165. setType(DATA_STRING);
  166. return *data.String;
  167. }
  168. JsonVector & JsonNode::Vector()
  169. {
  170. setType(DATA_VECTOR);
  171. return *data.Vector;
  172. }
  173. JsonMap & JsonNode::Struct()
  174. {
  175. setType(DATA_STRUCT);
  176. return *data.Struct;
  177. }
  178. const bool boolDefault = false;
  179. const bool & JsonNode::Bool() const
  180. {
  181. if (type == DATA_NULL)
  182. return boolDefault;
  183. assert(type == DATA_BOOL);
  184. return data.Bool;
  185. }
  186. const double floatDefault = 0;
  187. const double & JsonNode::Float() const
  188. {
  189. if (type == DATA_NULL)
  190. return floatDefault;
  191. assert(type == DATA_FLOAT);
  192. return data.Float;
  193. }
  194. const std::string stringDefault = std::string();
  195. const std::string & JsonNode::String() const
  196. {
  197. if (type == DATA_NULL)
  198. return stringDefault;
  199. assert(type == DATA_STRING);
  200. return *data.String;
  201. }
  202. const JsonVector vectorDefault = JsonVector();
  203. const JsonVector & JsonNode::Vector() const
  204. {
  205. if (type == DATA_NULL)
  206. return vectorDefault;
  207. assert(type == DATA_VECTOR);
  208. return *data.Vector;
  209. }
  210. const JsonMap mapDefault = JsonMap();
  211. const JsonMap & JsonNode::Struct() const
  212. {
  213. if (type == DATA_NULL)
  214. return mapDefault;
  215. assert(type == DATA_STRUCT);
  216. return *data.Struct;
  217. }
  218. JsonNode & JsonNode::operator[](std::string child)
  219. {
  220. return Struct()[child];
  221. }
  222. const JsonNode & JsonNode::operator[](std::string child) const
  223. {
  224. JsonMap::const_iterator it = Struct().find(child);
  225. if (it != Struct().end())
  226. return it->second;
  227. return nullNode;
  228. }
  229. // to avoid duplicating const and non-const code
  230. template<typename Node>
  231. Node & resolvePointer(Node & in, const std::string & pointer)
  232. {
  233. if (pointer.empty())
  234. return in;
  235. assert(pointer[0] == '/');
  236. size_t splitPos = pointer.find('/', 1);
  237. std::string entry = pointer.substr(1, splitPos -1);
  238. std::string remainer = splitPos == std::string::npos ? "" : pointer.substr(splitPos);
  239. if (in.getType() == JsonNode::DATA_VECTOR)
  240. {
  241. if (entry.find_first_not_of("0123456789") != std::string::npos) // non-numbers in string
  242. throw std::runtime_error("Invalid Json pointer");
  243. if (entry.size() > 1 && entry[0] == '0') // leading zeros are not allowed
  244. throw std::runtime_error("Invalid Json pointer");
  245. size_t index = boost::lexical_cast<size_t>(entry);
  246. if (in.Vector().size() > index)
  247. return in.Vector()[index].resolvePointer(remainer);
  248. }
  249. return in[entry].resolvePointer(remainer);
  250. }
  251. const JsonNode & JsonNode::resolvePointer(const std::string &jsonPointer) const
  252. {
  253. return ::resolvePointer(*this, jsonPointer);
  254. }
  255. JsonNode & JsonNode::resolvePointer(const std::string &jsonPointer)
  256. {
  257. return ::resolvePointer(*this, jsonPointer);
  258. }
  259. ////////////////////////////////////////////////////////////////////////////////
  260. template<typename Iterator>
  261. void JsonWriter::writeContainer(Iterator begin, Iterator end)
  262. {
  263. if (begin == end)
  264. return;
  265. prefix += '\t';
  266. writeEntry(begin++);
  267. while (begin != end)
  268. {
  269. out<<",\n";
  270. writeEntry(begin++);
  271. }
  272. out<<"\n";
  273. prefix.resize(prefix.size()-1);
  274. }
  275. void JsonWriter::writeEntry(JsonMap::const_iterator entry)
  276. {
  277. out << prefix;
  278. writeString(entry->first);
  279. out << " : ";
  280. writeNode(entry->second);
  281. }
  282. void JsonWriter::writeEntry(JsonVector::const_iterator entry)
  283. {
  284. out << prefix;
  285. writeNode(*entry);
  286. }
  287. void JsonWriter::writeString(const std::string &string)
  288. {
  289. static const std::string escaped = "\"\\/\b\f\n\r\t";
  290. out <<'\"';
  291. size_t pos=0, start=0;
  292. for (; pos<string.size(); pos++)
  293. {
  294. size_t escapedChar = escaped.find(string[pos]);
  295. if (escapedChar != std::string::npos)
  296. {
  297. out.write(string.data()+start, pos - start);
  298. out << '\\' << escaped[escapedChar];
  299. start = pos;
  300. }
  301. }
  302. out.write(string.data()+start, pos - start);
  303. out <<'\"';
  304. }
  305. void JsonWriter::writeNode(const JsonNode &node)
  306. {
  307. switch(node.getType())
  308. {
  309. break; case JsonNode::DATA_NULL:
  310. out << "null";
  311. break; case JsonNode::DATA_BOOL:
  312. if (node.Bool())
  313. out << "true";
  314. else
  315. out << "false";
  316. break; case JsonNode::DATA_FLOAT:
  317. out << node.Float();
  318. break; case JsonNode::DATA_STRING:
  319. writeString(node.String());
  320. break; case JsonNode::DATA_VECTOR:
  321. out << "[" << "\n";
  322. writeContainer(node.Vector().begin(), node.Vector().end());
  323. out << prefix << "]";
  324. break; case JsonNode::DATA_STRUCT:
  325. out << "{" << "\n";
  326. writeContainer(node.Struct().begin(), node.Struct().end());
  327. out << prefix << "}";
  328. }
  329. }
  330. JsonWriter::JsonWriter(std::ostream &output, const JsonNode &node):
  331. out(output)
  332. {
  333. writeNode(node);
  334. }
  335. std::ostream & operator<<(std::ostream &out, const JsonNode &node)
  336. {
  337. JsonWriter(out, node);
  338. return out << "\n";
  339. }
  340. ////////////////////////////////////////////////////////////////////////////////
  341. JsonParser::JsonParser(const char * inputString, size_t stringSize):
  342. input(inputString, stringSize),
  343. lineCount(1),
  344. lineStart(0),
  345. pos(0)
  346. {
  347. }
  348. JsonNode JsonParser::parse(std::string fileName)
  349. {
  350. JsonNode root;
  351. extractValue(root);
  352. extractWhitespace(false);
  353. //Warn if there are any non-whitespace symbols left
  354. if (pos < input.size())
  355. error("Not all file was parsed!", true);
  356. if (!errors.empty())
  357. {
  358. logGlobal->warnStream()<<"File " << fileName << " is not a valid JSON file!";
  359. logGlobal->warnStream()<<errors;
  360. }
  361. return root;
  362. }
  363. bool JsonParser::extractSeparator()
  364. {
  365. if (!extractWhitespace())
  366. return false;
  367. if ( input[pos] !=':')
  368. return error("Separator expected");
  369. pos++;
  370. return true;
  371. }
  372. bool JsonParser::extractValue(JsonNode &node)
  373. {
  374. if (!extractWhitespace())
  375. return false;
  376. switch (input[pos])
  377. {
  378. case '\"': return extractString(node);
  379. case 'n' : return extractNull(node);
  380. case 't' : return extractTrue(node);
  381. case 'f' : return extractFalse(node);
  382. case '{' : return extractStruct(node);
  383. case '[' : return extractArray(node);
  384. case '-' : return extractFloat(node);
  385. default:
  386. {
  387. if (input[pos] >= '0' && input[pos] <= '9')
  388. return extractFloat(node);
  389. return error("Value expected!");
  390. }
  391. }
  392. }
  393. bool JsonParser::extractWhitespace(bool verbose)
  394. {
  395. while (true)
  396. {
  397. while (pos < input.size() && (ui8)input[pos] <= ' ')
  398. {
  399. if (input[pos] == '\n')
  400. {
  401. lineCount++;
  402. lineStart = pos+1;
  403. }
  404. pos++;
  405. }
  406. if (pos >= input.size() || input[pos] != '/')
  407. break;
  408. pos++;
  409. if (pos == input.size())
  410. break;
  411. if (input[pos] == '/')
  412. pos++;
  413. else
  414. error("Comments must consist from two slashes!", true);
  415. while (pos < input.size() && input[pos] != '\n')
  416. pos++;
  417. }
  418. if (pos >= input.size() && verbose)
  419. return error("Unexpected end of file!");
  420. return true;
  421. }
  422. bool JsonParser::extractEscaping(std::string &str)
  423. {
  424. switch(input[pos])
  425. {
  426. break; case '\"': str += '\"';
  427. break; case '\\': str += '\\';
  428. break; case '/': str += '/';
  429. break; case 'b': str += '\b';
  430. break; case 'f': str += '\f';
  431. break; case 'n': str += '\n';
  432. break; case 'r': str += '\r';
  433. break; case 't': str += '\t';
  434. break; default: return error("Unknown escape sequence!", true);
  435. };
  436. return true;
  437. }
  438. bool JsonParser::extractString(std::string &str)
  439. {
  440. if (input[pos] != '\"')
  441. return error("String expected!");
  442. pos++;
  443. size_t first = pos;
  444. while (pos != input.size())
  445. {
  446. if (input[pos] == '\"') // Correct end of string
  447. {
  448. str.append( &input[first], pos-first);
  449. pos++;
  450. return true;
  451. }
  452. if (input[pos] == '\\') // Escaping
  453. {
  454. str.append( &input[first], pos-first);
  455. pos++;
  456. if (pos == input.size())
  457. break;
  458. extractEscaping(str);
  459. first = pos + 1;
  460. }
  461. if (input[pos] == '\n') // end-of-line
  462. {
  463. str.append( &input[first], pos-first);
  464. return error("Closing quote not found!", true);
  465. }
  466. if ((unsigned char)(input[pos]) < ' ') // control character
  467. {
  468. str.append( &input[first], pos-first);
  469. first = pos+1;
  470. error("Illegal character in the string!", true);
  471. }
  472. pos++;
  473. }
  474. return error("Unterminated string!");
  475. }
  476. bool JsonParser::extractString(JsonNode &node)
  477. {
  478. std::string str;
  479. if (!extractString(str))
  480. return false;
  481. node.setType(JsonNode::DATA_STRING);
  482. node.String() = str;
  483. return true;
  484. }
  485. bool JsonParser::extractLiteral(const std::string &literal)
  486. {
  487. if (literal.compare(0, literal.size(), &input[pos], literal.size()) != 0)
  488. {
  489. while (pos < input.size() && ((input[pos]>'a' && input[pos]<'z')
  490. || (input[pos]>'A' && input[pos]<'Z')))
  491. pos++;
  492. return error("Unknown literal found", true);
  493. }
  494. pos += literal.size();
  495. return true;
  496. }
  497. bool JsonParser::extractNull(JsonNode &node)
  498. {
  499. if (!extractLiteral("null"))
  500. return false;
  501. node.clear();
  502. return true;
  503. }
  504. bool JsonParser::extractTrue(JsonNode &node)
  505. {
  506. if (!extractLiteral("true"))
  507. return false;
  508. node.Bool() = true;
  509. return true;
  510. }
  511. bool JsonParser::extractFalse(JsonNode &node)
  512. {
  513. if (!extractLiteral("false"))
  514. return false;
  515. node.Bool() = false;
  516. return true;
  517. }
  518. bool JsonParser::extractStruct(JsonNode &node)
  519. {
  520. node.setType(JsonNode::DATA_STRUCT);
  521. pos++;
  522. if (!extractWhitespace())
  523. return false;
  524. //Empty struct found
  525. if (input[pos] == '}')
  526. {
  527. pos++;
  528. return true;
  529. }
  530. while (true)
  531. {
  532. if (!extractWhitespace())
  533. return false;
  534. std::string key;
  535. if (!extractString(key))
  536. return false;
  537. if (node.Struct().find(key) != node.Struct().end())
  538. error("Dublicated element encountered!", true);
  539. if (!extractSeparator())
  540. return false;
  541. if (!extractElement(node.Struct()[key], '}'))
  542. return false;
  543. if (input[pos] == '}')
  544. {
  545. pos++;
  546. return true;
  547. }
  548. }
  549. }
  550. bool JsonParser::extractArray(JsonNode &node)
  551. {
  552. pos++;
  553. node.setType(JsonNode::DATA_VECTOR);
  554. if (!extractWhitespace())
  555. return false;
  556. //Empty array found
  557. if (input[pos] == ']')
  558. {
  559. pos++;
  560. return true;
  561. }
  562. while (true)
  563. {
  564. //NOTE: currently 50% of time is this vector resizing.
  565. //May be useful to use list during parsing and then swap() all items to vector
  566. node.Vector().resize(node.Vector().size()+1);
  567. if (!extractElement(node.Vector().back(), ']'))
  568. return false;
  569. if (input[pos] == ']')
  570. {
  571. pos++;
  572. return true;
  573. }
  574. }
  575. }
  576. bool JsonParser::extractElement(JsonNode &node, char terminator)
  577. {
  578. if (!extractValue(node))
  579. return false;
  580. if (!extractWhitespace())
  581. return false;
  582. bool comma = (input[pos] == ',');
  583. if (comma )
  584. {
  585. pos++;
  586. if (!extractWhitespace())
  587. return false;
  588. }
  589. if (input[pos] == terminator)
  590. return true;
  591. if (!comma)
  592. error("Comma expected!", true);
  593. return true;
  594. }
  595. bool JsonParser::extractFloat(JsonNode &node)
  596. {
  597. assert(input[pos] == '-' || (input[pos] >= '0' && input[pos] <= '9'));
  598. bool negative=false;
  599. double result=0;
  600. if (input[pos] == '-')
  601. {
  602. pos++;
  603. negative = true;
  604. }
  605. if (input[pos] < '0' || input[pos] > '9')
  606. return error("Number expected!");
  607. //Extract integer part
  608. while (input[pos] >= '0' && input[pos] <= '9')
  609. {
  610. result = result*10+(input[pos]-'0');
  611. pos++;
  612. }
  613. if (input[pos] == '.')
  614. {
  615. //extract fractional part
  616. pos++;
  617. double fractMult = 0.1;
  618. if (input[pos] < '0' || input[pos] > '9')
  619. return error("Decimal part expected!");
  620. while (input[pos] >= '0' && input[pos] <= '9')
  621. {
  622. result = result + fractMult*(input[pos]-'0');
  623. fractMult /= 10;
  624. pos++;
  625. }
  626. }
  627. //TODO: exponential part
  628. if (negative)
  629. result = -result;
  630. node.setType(JsonNode::DATA_FLOAT);
  631. node.Float() = result;
  632. return true;
  633. }
  634. bool JsonParser::error(const std::string &message, bool warning)
  635. {
  636. std::ostringstream stream;
  637. std::string type(warning?" warning: ":" error: ");
  638. stream << "At line " << lineCount << ", position "<<pos-lineStart
  639. << type << message <<"\n";
  640. errors += stream.str();
  641. return warning;
  642. }
  643. static const std::map<std::string, JsonNode::JsonType> stringToType =
  644. boost::assign::map_list_of
  645. ("null", JsonNode::DATA_NULL) ("boolean", JsonNode::DATA_BOOL)
  646. ("number", JsonNode::DATA_FLOAT) ("string", JsonNode::DATA_STRING)
  647. ("array", JsonNode::DATA_VECTOR) ("object", JsonNode::DATA_STRUCT);
  648. std::string JsonValidator::validateEnum(const JsonNode &node, const JsonVector &enumeration)
  649. {
  650. BOOST_FOREACH(auto & enumEntry, enumeration)
  651. {
  652. if (node == enumEntry)
  653. return "";
  654. }
  655. return fail("Key must have one of predefined values");
  656. }
  657. std::string JsonValidator::validatesSchemaList(const JsonNode &node, const JsonNode &schemas, std::string errorMsg, std::function<bool(size_t)> isValid)
  658. {
  659. if (!schemas.isNull())
  660. {
  661. std::string errors = "<tested schemas>\n";
  662. size_t result = 0;
  663. BOOST_FOREACH(auto & schema, schemas.Vector())
  664. {
  665. std::string error = validateNode(node, schema);
  666. if (error.empty())
  667. {
  668. result++;
  669. }
  670. else
  671. {
  672. errors += error;
  673. errors += "<end of schema>\n";
  674. }
  675. }
  676. if (isValid(result))
  677. {
  678. return "";
  679. }
  680. return fail(errorMsg) + errors;
  681. }
  682. return "";
  683. }
  684. std::string JsonValidator::validateNodeType(const JsonNode &node, const JsonNode &schema)
  685. {
  686. std::string errors;
  687. // data must be valid against all schemas in the list
  688. errors += validatesSchemaList(node, schema["allOf"], "Failed to pass all schemas", [&](size_t count)
  689. {
  690. return count == schema["allOf"].Vector().size();
  691. });
  692. // data must be valid against any non-zero number of schemas in the list
  693. errors += validatesSchemaList(node, schema["anyOf"], "Failed to pass any schema", [&](size_t count)
  694. {
  695. return count > 0;
  696. });
  697. // data must be valid against one and only one schema
  698. errors += validatesSchemaList(node, schema["oneOf"], "Failed to pass one and only one schema", [&](size_t count)
  699. {
  700. return count == 1;
  701. });
  702. // data must NOT be valid against schema
  703. if (!schema["not"].isNull())
  704. {
  705. if (validateNode(node, schema["not"]).empty())
  706. errors += fail("Successful validation against negative check");
  707. }
  708. return errors;
  709. }
  710. // Basic checks common for any nodes
  711. std::string JsonValidator::validateNode(const JsonNode &node, const JsonNode &schema)
  712. {
  713. std::string errors;
  714. assert(!schema.isNull()); // can this error be triggered?
  715. if (node.isNull())
  716. return ""; // node not present. consider to be "valid"
  717. if (!schema["$ref"].isNull())
  718. {
  719. std::string URI = schema["$ref"].String();
  720. //node must be validated using schema pointed by this reference and not by data here
  721. //Local reference. Turn it into more easy to handle remote ref
  722. if (boost::algorithm::starts_with(URI, "#"))
  723. URI = usedSchemas.back() + URI;
  724. return validateRoot(node, URI);
  725. }
  726. // basic schema check
  727. auto & typeNode = schema["type"];
  728. if ( !typeNode.isNull())
  729. {
  730. JsonNode::JsonType type = stringToType.find(typeNode.String())->second;
  731. if(type != node.getType())
  732. return errors + fail("Type mismatch!"); // different type. Any other checks are useless
  733. }
  734. errors += validateNodeType(node, schema);
  735. // enumeration - data must be equeal to one of items in list
  736. if (!schema["enum"].isNull())
  737. errors += validateEnum(node, schema["enum"].Vector());
  738. // try to run any type-specific checks
  739. if (node.getType() == JsonNode::DATA_VECTOR) errors += validateVector(node, schema);
  740. if (node.getType() == JsonNode::DATA_STRUCT) errors += validateStruct(node, schema);
  741. if (node.getType() == JsonNode::DATA_STRING) errors += validateString(node, schema);
  742. if (node.getType() == JsonNode::DATA_FLOAT) errors += validateNumber(node, schema);
  743. return errors;
  744. }
  745. std::string JsonValidator::validateVectorItem(const JsonVector items, const JsonNode & schema, const JsonNode & additional, size_t index)
  746. {
  747. currentPath.push_back(JsonNode());
  748. currentPath.back().Float() = index;
  749. auto onExit = vstd::makeScopeGuard([&]
  750. {
  751. currentPath.pop_back();
  752. });
  753. if (!schema.isNull())
  754. {
  755. // case 1: schema is vector. Validate items agaist corresponding items in vector
  756. if (schema.getType() == JsonNode::DATA_VECTOR)
  757. {
  758. if (schema.Vector().size() > index)
  759. return validateNode(items[index], schema.Vector()[index]);
  760. }
  761. else // case 2: schema has to be struct. Apply it to all items, completely ignore additionalItems
  762. {
  763. return validateNode(items[index], schema);
  764. }
  765. }
  766. // othervice check against schema in additional items field
  767. if (additional.getType() == JsonNode::DATA_STRUCT)
  768. return validateNode(items[index], additional);
  769. // or, additionalItems field can be bool which indicates if such items are allowed
  770. if (!additional.isNull() && additional.Bool() == false) // present and set to false - error
  771. return fail("Unknown entry found");
  772. // by default - additional items are allowed
  773. return "";
  774. }
  775. //Checks "items" entry from schema (type-specific check for Vector)
  776. std::string JsonValidator::validateVector(const JsonNode &node, const JsonNode &schema)
  777. {
  778. std::string errors;
  779. auto & vector = node.Vector();
  780. {
  781. auto & items = schema["items"];
  782. auto & additional = schema["additionalItems"];
  783. for (size_t i=0; i<vector.size(); i++)
  784. errors += validateVectorItem(vector, items, additional, i);
  785. }
  786. if (vstd::contains(schema.Struct(), "maxItems") && vector.size() > schema["maxItems"].Float())
  787. errors += fail("Too many items in the list!");
  788. if (vstd::contains(schema.Struct(), "minItems") && vector.size() < schema["minItems"].Float())
  789. errors += fail("Too few items in the list");
  790. if (schema["uniqueItems"].Bool())
  791. {
  792. for (auto itA = vector.begin(); itA != vector.end(); itA++)
  793. {
  794. auto itB = itA;
  795. while (++itB != vector.end())
  796. {
  797. if (*itA == *itB)
  798. errors += fail("List must consist from unique items");
  799. }
  800. }
  801. }
  802. return errors;
  803. }
  804. std::string JsonValidator::validateStructItem(const JsonNode &node, const JsonNode & schema, const JsonNode & additional, std::string nodeName)
  805. {
  806. currentPath.push_back(JsonNode());
  807. currentPath.back().String() = nodeName;
  808. auto onExit = vstd::makeScopeGuard([&]
  809. {
  810. currentPath.pop_back();
  811. });
  812. // there is schema specifically for this item
  813. if (!schema[nodeName].isNull())
  814. return validateNode(node, schema[nodeName]);
  815. // try generic additionalItems schema
  816. if (additional.getType() == JsonNode::DATA_STRUCT)
  817. return validateNode(node, additional);
  818. // or, additionalItems field can be bool which indicates if such items are allowed
  819. if (!additional.isNull() && additional.Bool() == false) // present and set to false - error
  820. return fail("Unknown entry found: " + nodeName);
  821. // by default - additional items are allowed
  822. return "";
  823. }
  824. //Checks "properties" entry from schema (type-specific check for Struct)
  825. std::string JsonValidator::validateStruct(const JsonNode &node, const JsonNode &schema)
  826. {
  827. std::string errors;
  828. auto & map = node.Struct();
  829. {
  830. auto & properties = schema["properties"];
  831. auto & additional = schema["additionalProperties"];
  832. BOOST_FOREACH(auto & entry, map)
  833. errors += validateStructItem(entry.second, properties, additional, entry.first);
  834. }
  835. BOOST_FOREACH(auto & required, schema["required"].Vector())
  836. {
  837. if (node[required.String()].isNull())
  838. errors += fail("Required entry " + required.String() + " is missing");
  839. }
  840. //Copy-paste from vector code. yay!
  841. if (vstd::contains(schema.Struct(), "maxProperties") && map.size() > schema["maxProperties"].Float())
  842. errors += fail("Too many items in the list!");
  843. if (vstd::contains(schema.Struct(), "minItems") && map.size() < schema["minItems"].Float())
  844. errors += fail("Too few items in the list");
  845. if (schema["uniqueItems"].Bool())
  846. {
  847. for (auto itA = map.begin(); itA != map.end(); itA++)
  848. {
  849. auto itB = itA;
  850. while (++itB != map.end())
  851. {
  852. if (itA->second == itB->second)
  853. errors += fail("List must consist from unique items");
  854. }
  855. }
  856. }
  857. // dependencies. Format is object/struct where key is the name of key in data
  858. // and value is either:
  859. // a) array of fields that must be present
  860. // b) struct with schema against which data should be valid
  861. // These checks are triggered only if key is present
  862. BOOST_FOREACH(auto & deps, schema["dependencies"].Struct())
  863. {
  864. if (vstd::contains(map, deps.first))
  865. {
  866. if (deps.second.getType() == JsonNode::DATA_VECTOR)
  867. {
  868. JsonVector depList = deps.second.Vector();
  869. BOOST_FOREACH(auto & depEntry, depList)
  870. {
  871. if (!vstd::contains(map, depEntry.String()))
  872. errors += fail("Property " + depEntry.String() + " required for " + deps.first + " is missing");
  873. }
  874. }
  875. else
  876. {
  877. if (!validateNode(node, deps.second).empty())
  878. errors += fail("Requirements for " + deps.first + " are not fulfilled");
  879. }
  880. }
  881. }
  882. // TODO: missing fields from draft v4
  883. // patternProperties
  884. return errors;
  885. }
  886. std::string JsonValidator::validateString(const JsonNode &node, const JsonNode &schema)
  887. {
  888. std::string errors;
  889. auto & string = node.String();
  890. if (vstd::contains(schema.Struct(), "maxLength") && string.size() > schema["maxLength"].Float())
  891. errors += fail("String too long");
  892. if (vstd::contains(schema.Struct(), "minLength") && string.size() < schema["minLength"].Float())
  893. errors += fail("String too short");
  894. // TODO: missing fields from draft v4
  895. // pattern
  896. return errors;
  897. }
  898. std::string JsonValidator::validateNumber(const JsonNode &node, const JsonNode &schema)
  899. {
  900. std::string errors;
  901. auto & value = node.Float();
  902. if (vstd::contains(schema.Struct(), "maximum"))
  903. {
  904. if (schema["exclusiveMaximum"].Bool())
  905. {
  906. if (value >= schema["maximum"].Float())
  907. errors += fail("Value is too large");
  908. }
  909. else
  910. {
  911. if (value > schema["maximum"].Float())
  912. errors += fail("Value is too large");
  913. }
  914. }
  915. if (vstd::contains(schema.Struct(), "minimum"))
  916. {
  917. if (schema["exclusiveMinimum"].Bool())
  918. {
  919. if (value <= schema["minimum"].Float())
  920. errors += fail("Value is too small");
  921. }
  922. else
  923. {
  924. if (value < schema["minimum"].Float())
  925. errors += fail("Value is too small");
  926. }
  927. }
  928. if (vstd::contains(schema.Struct(), "multipleOf"))
  929. {
  930. double result = value / schema["multipleOf"].Float();
  931. if (floor(result) != result)
  932. errors += ("Value is not divisible");
  933. }
  934. return errors;
  935. }
  936. //basic schema validation (like checking $schema entry).
  937. std::string JsonValidator::validateRoot(const JsonNode &node, std::string schemaName)
  938. {
  939. const JsonNode & schema = JsonUtils::getSchema(schemaName);
  940. usedSchemas.push_back(schemaName.substr(0, schemaName.find('#')));
  941. auto onExit = vstd::makeScopeGuard([&]
  942. {
  943. usedSchemas.pop_back();
  944. });
  945. if (!schema.isNull())
  946. return validateNode(node, schema);
  947. else
  948. return fail("Schema not found!");
  949. }
  950. std::string JsonValidator::fail(const std::string &message)
  951. {
  952. std::string errors;
  953. errors += "At ";
  954. if (!currentPath.empty())
  955. {
  956. BOOST_FOREACH(const JsonNode &path, currentPath)
  957. {
  958. errors += "/";
  959. if (path.getType() == JsonNode::DATA_STRING)
  960. errors += path.String();
  961. else
  962. errors += boost::lexical_cast<std::string>(static_cast<unsigned>(path.Float()));
  963. }
  964. }
  965. else
  966. errors += "<root>";
  967. errors += "\n\t Error: " + message + "\n";
  968. return errors;
  969. }
  970. bool JsonValidator::validate(const JsonNode &root, std::string schemaName, std::string name)
  971. {
  972. std::string errors = validateRoot(root, schemaName);
  973. if (!errors.empty())
  974. {
  975. logGlobal->warnStream() << "Data in " << name << " is invalid!";
  976. logGlobal->warnStream() << errors;
  977. }
  978. return errors.empty();
  979. }
  980. ///JsonUtils
  981. void JsonUtils::parseTypedBonusShort(const JsonVector& source, Bonus *dest)
  982. {
  983. dest->val = source[1].Float();
  984. resolveIdentifier(source[2],dest->subtype);
  985. dest->additionalInfo = source[3].Float();
  986. dest->duration = Bonus::PERMANENT; //TODO: handle flags (as integer)
  987. dest->turnsRemain = 0;
  988. }
  989. Bonus * JsonUtils::parseBonus (const JsonVector &ability_vec) //TODO: merge with AddAbility, create universal parser for all bonus properties
  990. {
  991. Bonus * b = new Bonus();
  992. std::string type = ability_vec[0].String();
  993. auto it = bonusNameMap.find(type);
  994. if (it == bonusNameMap.end())
  995. {
  996. logGlobal->errorStream() << "Error: invalid ability type " << type;
  997. return b;
  998. }
  999. b->type = it->second;
  1000. parseTypedBonusShort(ability_vec, b);
  1001. return b;
  1002. }
  1003. template <typename T>
  1004. const T & parseByMap(const std::map<std::string, T> & map, const JsonNode * val, std::string err)
  1005. {
  1006. static T defaultValue = T();
  1007. if (!val->isNull())
  1008. {
  1009. std::string type = val->String();
  1010. auto it = map.find(type);
  1011. if (it == map.end())
  1012. {
  1013. logGlobal->errorStream() << "Error: invalid " << err << type;
  1014. return defaultValue;
  1015. }
  1016. else
  1017. {
  1018. return it->second;
  1019. }
  1020. }
  1021. else
  1022. return defaultValue;
  1023. }
  1024. void JsonUtils::resolveIdentifier (si32 &var, const JsonNode &node, std::string name)
  1025. {
  1026. const JsonNode &value = node[name];
  1027. if (!value.isNull())
  1028. {
  1029. switch (value.getType())
  1030. {
  1031. case JsonNode::DATA_FLOAT:
  1032. var = value.Float();
  1033. break;
  1034. case JsonNode::DATA_STRING:
  1035. VLC->modh->identifiers.requestIdentifier(value, [&](si32 identifier)
  1036. {
  1037. var = identifier;
  1038. });
  1039. break;
  1040. default:
  1041. logGlobal->errorStream() << "Error! Wrong indentifier used for value of " << name;
  1042. }
  1043. }
  1044. }
  1045. void JsonUtils::resolveIdentifier (const JsonNode &node, si32 &var)
  1046. {
  1047. switch (node.getType())
  1048. {
  1049. case JsonNode::DATA_FLOAT:
  1050. var = node.Float();
  1051. break;
  1052. case JsonNode::DATA_STRING:
  1053. VLC->modh->identifiers.requestIdentifier (node, [&](si32 identifier)
  1054. {
  1055. var = identifier;
  1056. });
  1057. break;
  1058. default:
  1059. logGlobal->errorStream() << "Error! Wrong indentifier used for identifier!";
  1060. }
  1061. }
  1062. Bonus * JsonUtils::parseBonus (const JsonNode &ability)
  1063. {
  1064. Bonus * b = new Bonus();
  1065. const JsonNode *value;
  1066. std::string type = ability["type"].String();
  1067. auto it = bonusNameMap.find(type);
  1068. if (it == bonusNameMap.end())
  1069. {
  1070. logGlobal->errorStream() << "Error: invalid ability type " << type;
  1071. return b;
  1072. }
  1073. b->type = it->second;
  1074. resolveIdentifier (b->subtype, ability, "subtype");
  1075. b->val = ability["val"].Float();
  1076. value = &ability["valueType"];
  1077. if (!value->isNull())
  1078. b->valType = static_cast<Bonus::ValueType>(parseByMap(bonusValueMap, value, "value type "));
  1079. resolveIdentifier (b->additionalInfo, ability, "addInfo");
  1080. b->turnsRemain = ability["turns"].Float();
  1081. b->sid = ability["sourceID"].Float();
  1082. b->description = ability["description"].String();
  1083. value = &ability["effectRange"];
  1084. if (!value->isNull())
  1085. b->effectRange = static_cast<Bonus::LimitEffect>(parseByMap(bonusLimitEffect, value, "effect range "));
  1086. value = &ability["duration"];
  1087. if (!value->isNull())
  1088. {
  1089. switch (value->getType())
  1090. {
  1091. case JsonNode::DATA_STRING:
  1092. b->duration = parseByMap(bonusDurationMap, value, "duration type ");
  1093. break;
  1094. case JsonNode::DATA_VECTOR:
  1095. {
  1096. ui16 dur = 0;
  1097. BOOST_FOREACH (const JsonNode & d, value->Vector())
  1098. {
  1099. dur |= parseByMap(bonusDurationMap, &d, "duration type ");
  1100. }
  1101. b->duration = dur;
  1102. }
  1103. break;
  1104. default:
  1105. logGlobal->errorStream() << "Error! Wrong bonus duration format.";
  1106. }
  1107. }
  1108. value = &ability["source"];
  1109. if (!value->isNull())
  1110. b->source = static_cast<Bonus::BonusSource>(parseByMap(bonusSourceMap, value, "source type "));
  1111. value = &ability["limiters"];
  1112. if (!value->isNull())
  1113. {
  1114. BOOST_FOREACH (const JsonNode & limiter, value->Vector())
  1115. {
  1116. switch (limiter.getType())
  1117. {
  1118. case JsonNode::DATA_STRING: //pre-defined limiters
  1119. b->limiter = parseByMap(bonusLimiterMap, &limiter, "limiter type ");
  1120. break;
  1121. case JsonNode::DATA_STRUCT: //customizable limiters
  1122. {
  1123. shared_ptr<ILimiter> l;
  1124. if (limiter["type"].String() == "CREATURE_TYPE_LIMITER")
  1125. {
  1126. shared_ptr<CCreatureTypeLimiter> l2 = make_shared<CCreatureTypeLimiter>(); //TODO: How the hell resolve pointer to creature?
  1127. const JsonVector vec = limiter["parameters"].Vector();
  1128. VLC->modh->identifiers.requestIdentifier("creature", vec[0], [=](si32 creature)
  1129. {
  1130. l2->setCreature (CreatureID(creature));
  1131. });
  1132. if (vec.size() > 1)
  1133. {
  1134. l2->includeUpgrades = vec[1].Bool();
  1135. }
  1136. else
  1137. l2->includeUpgrades = false;
  1138. l = l2;
  1139. }
  1140. if (limiter["type"].String() == "HAS_ANOTHER_BONUS_LIMITER")
  1141. {
  1142. shared_ptr<HasAnotherBonusLimiter> l2 = make_shared<HasAnotherBonusLimiter>();
  1143. const JsonVector vec = limiter["parameters"].Vector();
  1144. std::string anotherBonusType = vec[0].String();
  1145. auto it = bonusNameMap.find (anotherBonusType);
  1146. if (it == bonusNameMap.end())
  1147. {
  1148. logGlobal->errorStream() << "Error: invalid ability type " << anotherBonusType;
  1149. continue;
  1150. }
  1151. l2->type = it->second;
  1152. if (vec.size() > 1 )
  1153. {
  1154. resolveIdentifier (vec[1], l2->subtype);
  1155. l2->isSubtypeRelevant = true;
  1156. }
  1157. l = l2;
  1158. }
  1159. b->addLimiter(l);
  1160. }
  1161. break;
  1162. }
  1163. }
  1164. }
  1165. value = &ability["propagator"];
  1166. if (!value->isNull())
  1167. b->propagator = parseByMap(bonusPropagatorMap, value, "propagator type ");
  1168. return b;
  1169. }
  1170. //returns first Key with value equal to given one
  1171. template<class Key, class Val>
  1172. Key reverseMapFirst(const Val & val, const std::map<Key, Val> map)
  1173. {
  1174. BOOST_FOREACH(auto it, map)
  1175. {
  1176. if(it.second == val)
  1177. {
  1178. return it.first;
  1179. }
  1180. }
  1181. assert(0);
  1182. return "";
  1183. }
  1184. void JsonUtils::unparseBonus( JsonNode &node, const Bonus * bonus )
  1185. {
  1186. node["type"].String() = reverseMapFirst<std::string, Bonus::BonusType>(bonus->type, bonusNameMap);
  1187. node["subtype"].Float() = bonus->subtype;
  1188. node["val"].Float() = bonus->val;
  1189. node["valueType"].String() = reverseMapFirst<std::string, Bonus::ValueType>(bonus->valType, bonusValueMap);
  1190. node["additionalInfo"].Float() = bonus->additionalInfo;
  1191. node["turns"].Float() = bonus->turnsRemain;
  1192. node["sourceID"].Float() = bonus->source;
  1193. node["description"].String() = bonus->description;
  1194. node["effectRange"].String() = reverseMapFirst<std::string, Bonus::LimitEffect>(bonus->effectRange, bonusLimitEffect);
  1195. node["duration"].String() = reverseMapFirst<std::string, ui16>(bonus->duration, bonusDurationMap);
  1196. node["source"].String() = reverseMapFirst<std::string, Bonus::BonusSource>(bonus->source, bonusSourceMap);
  1197. if(bonus->limiter)
  1198. {
  1199. node["limiter"].String() = reverseMapFirst<std::string, TLimiterPtr>(bonus->limiter, bonusLimiterMap);
  1200. }
  1201. if(bonus->propagator)
  1202. {
  1203. node["propagator"].String() = reverseMapFirst<std::string, TPropagatorPtr>(bonus->propagator, bonusPropagatorMap);
  1204. }
  1205. }
  1206. void minimizeNode(JsonNode & node, const JsonNode & schema)
  1207. {
  1208. if (schema["type"].String() == "object")
  1209. {
  1210. std::set<std::string> foundEntries;
  1211. BOOST_FOREACH(auto & entry, schema["required"].Vector())
  1212. {
  1213. std::string name = entry.String();
  1214. foundEntries.insert(name);
  1215. minimizeNode(node[name], schema["properties"][name]);
  1216. if (vstd::contains(node.Struct(), name) &&
  1217. node[name] == schema["properties"][name]["default"])
  1218. {
  1219. node.Struct().erase(name);
  1220. }
  1221. }
  1222. // erase all unhandled entries
  1223. for (auto it = node.Struct().begin(); it != node.Struct().end();)
  1224. {
  1225. if (!vstd::contains(foundEntries, it->first))
  1226. it = node.Struct().erase(it);
  1227. else
  1228. it++;
  1229. }
  1230. }
  1231. }
  1232. void JsonUtils::minimize(JsonNode & node, std::string schemaName)
  1233. {
  1234. minimizeNode(node, getSchema(schemaName));
  1235. }
  1236. // FIXME: except for several lines function is identical to minimizeNode. Some way to reduce duplication?
  1237. void maximizeNode(JsonNode & node, const JsonNode & schema)
  1238. {
  1239. // "required" entry can only be found in object/struct
  1240. if (schema["type"].String() == "object")
  1241. {
  1242. std::set<std::string> foundEntries;
  1243. // check all required entries that have default version
  1244. BOOST_FOREACH(auto & entry, schema["required"].Vector())
  1245. {
  1246. std::string name = entry.String();
  1247. foundEntries.insert(name);
  1248. if (node[name].isNull() &&
  1249. !schema["properties"][name]["default"].isNull())
  1250. {
  1251. node[name] = schema["properties"][name]["default"];
  1252. }
  1253. maximizeNode(node[name], schema["properties"][name]);
  1254. }
  1255. // erase all unhandled entries
  1256. for (auto it = node.Struct().begin(); it != node.Struct().end();)
  1257. {
  1258. if (!vstd::contains(foundEntries, it->first))
  1259. it = node.Struct().erase(it);
  1260. else
  1261. it++;
  1262. }
  1263. }
  1264. }
  1265. void JsonUtils::maximize(JsonNode & node, std::string schemaName)
  1266. {
  1267. maximizeNode(node, getSchema(schemaName));
  1268. }
  1269. bool JsonUtils::validate(const JsonNode &node, std::string schemaName, std::string dataName)
  1270. {
  1271. JsonValidator validator;
  1272. return validator.validate(node, schemaName, dataName);
  1273. }
  1274. const JsonNode & getSchemaByName(std::string name)
  1275. {
  1276. // cached schemas to avoid loading json data multiple times
  1277. static std::map<std::string, JsonNode> loadedSchemas;
  1278. if (vstd::contains(loadedSchemas, name))
  1279. return loadedSchemas[name];
  1280. std::string filename = "config/schemas/" + name + ".json";
  1281. if (CResourceHandler::get()->existsResource(ResourceID(filename)))
  1282. {
  1283. loadedSchemas[name] = JsonNode(ResourceID(filename));
  1284. return loadedSchemas[name];
  1285. }
  1286. logGlobal->errorStream() << "Error: missing schema with name " << name << "!";
  1287. assert(0);
  1288. return nullNode;
  1289. }
  1290. const JsonNode & JsonUtils::getSchema(std::string URI)
  1291. {
  1292. std::vector<std::string> segments;
  1293. size_t posColon = URI.find(':');
  1294. size_t posHash = URI.find('#');
  1295. assert(posColon != std::string::npos);
  1296. std::string protocolName = URI.substr(0, posColon);
  1297. std::string filename = URI.substr(posColon + 1, posHash - posColon - 1);
  1298. if (protocolName != "vcmi")
  1299. {
  1300. logGlobal->errorStream() << "Error: unsupported URI protocol for schema: " << segments[0];
  1301. return nullNode;
  1302. }
  1303. // check if json pointer if present (section after hash in string)
  1304. if (posHash == std::string::npos || posHash == URI.size() - 1)
  1305. return getSchemaByName(filename);
  1306. else
  1307. return getSchemaByName(filename).resolvePointer(URI.substr(posHash + 1));
  1308. }
  1309. void JsonUtils::merge(JsonNode & dest, JsonNode & source)
  1310. {
  1311. if (dest.getType() == JsonNode::DATA_NULL)
  1312. {
  1313. std::swap(dest, source);
  1314. return;
  1315. }
  1316. switch (source.getType())
  1317. {
  1318. case JsonNode::DATA_NULL:
  1319. {
  1320. dest.clear();
  1321. break;
  1322. }
  1323. case JsonNode::DATA_BOOL:
  1324. case JsonNode::DATA_FLOAT:
  1325. case JsonNode::DATA_STRING:
  1326. {
  1327. std::swap(dest, source);
  1328. break;
  1329. }
  1330. case JsonNode::DATA_VECTOR:
  1331. {
  1332. size_t total = std::min(source.Vector().size(), dest.Vector().size());
  1333. for (size_t i=0; i< total; i++)
  1334. merge(dest.Vector()[i], source.Vector()[i]);
  1335. if (source.Vector().size() < dest.Vector().size())
  1336. {
  1337. //reserve place and *move* data from source to dest
  1338. source.Vector().reserve(source.Vector().size() + dest.Vector().size());
  1339. std::move(source.Vector().begin(), source.Vector().end(),
  1340. std::back_inserter(dest.Vector()));
  1341. }
  1342. break;
  1343. }
  1344. case JsonNode::DATA_STRUCT:
  1345. {
  1346. //recursively merge all entries from struct
  1347. BOOST_FOREACH(auto & node, source.Struct())
  1348. merge(dest[node.first], node.second);
  1349. }
  1350. }
  1351. }
  1352. void JsonUtils::mergeCopy(JsonNode & dest, JsonNode source)
  1353. {
  1354. // uses copy created in stack to safely merge two nodes
  1355. merge(dest, source);
  1356. }
  1357. JsonNode JsonUtils::assembleFromFiles(std::vector<std::string> files)
  1358. {
  1359. JsonNode result;
  1360. BOOST_FOREACH(std::string file, files)
  1361. {
  1362. JsonNode section(ResourceID(file, EResType::TEXT));
  1363. merge(result, section);
  1364. }
  1365. return result;
  1366. }