JsonNode.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  1. #include "StdInc.h"
  2. #include "JsonNode.h"
  3. #include "HeroBonus.h"
  4. #include "Filesystem/CResourceLoader.h"
  5. const JsonNode JsonNode::nullNode;
  6. JsonNode::JsonNode(JsonType Type):
  7. type(DATA_NULL)
  8. {
  9. setType(Type);
  10. }
  11. JsonNode::JsonNode(const char *data, size_t datasize):
  12. type(DATA_NULL)
  13. {
  14. JsonParser parser(data, datasize, *this);
  15. JsonValidator validator(*this);
  16. }
  17. JsonNode::JsonNode(ResourceID && fileURI):
  18. type(DATA_NULL)
  19. {
  20. std::string filename = CResourceHandler::get()->getResourceName(fileURI);
  21. FILE * file = fopen(filename.c_str(), "rb");
  22. if (!file)
  23. {
  24. tlog1 << "Failed to open file " << filename << "\n";
  25. perror("Last system error was ");
  26. return;
  27. }
  28. fseek(file, 0, SEEK_END);
  29. size_t datasize = ftell(file);
  30. fseek(file, 0, SEEK_SET);
  31. char *input = new char[datasize];
  32. datasize = fread((void*)input, 1, datasize, file);
  33. fclose(file);
  34. JsonParser parser(input, datasize, *this);
  35. JsonValidator validator(*this);
  36. delete [] input;
  37. }
  38. JsonNode::JsonNode(const JsonNode &copy):
  39. type(DATA_NULL)
  40. {
  41. setType(copy.getType());
  42. switch(type)
  43. {
  44. break; case DATA_NULL:
  45. break; case DATA_BOOL: Bool() = copy.Bool();
  46. break; case DATA_FLOAT: Float() = copy.Float();
  47. break; case DATA_STRING: String() = copy.String();
  48. break; case DATA_VECTOR: Vector() = copy.Vector();
  49. break; case DATA_STRUCT: Struct() = copy.Struct();
  50. }
  51. }
  52. JsonNode::~JsonNode()
  53. {
  54. setType(DATA_NULL);
  55. }
  56. void JsonNode::swap(JsonNode &b)
  57. {
  58. using std::swap;
  59. swap(data, b.data);
  60. swap(type, b.type);
  61. }
  62. JsonNode & JsonNode::operator =(JsonNode node)
  63. {
  64. swap(node);
  65. return *this;
  66. }
  67. bool JsonNode::operator == (const JsonNode &other) const
  68. {
  69. if (getType() == other.getType())
  70. {
  71. switch(type)
  72. {
  73. break; case DATA_NULL: return true;
  74. break; case DATA_BOOL: return Bool() == other.Bool();
  75. break; case DATA_FLOAT: return Float() == other.Float();
  76. break; case DATA_STRING: return String() == other.String();
  77. break; case DATA_VECTOR: return Vector() == other.Vector();
  78. break; case DATA_STRUCT: return Struct() == other.Struct();
  79. }
  80. }
  81. return false;
  82. }
  83. bool JsonNode::operator != (const JsonNode &other) const
  84. {
  85. return !(*this == other);
  86. }
  87. void JsonNode::minimize(const JsonNode& schema)
  88. {
  89. JsonValidator validator(*this, schema, true);
  90. }
  91. void JsonNode::validate(const JsonNode& schema)
  92. {
  93. JsonValidator validator(*this, schema, false);
  94. }
  95. JsonNode::JsonType JsonNode::getType() const
  96. {
  97. return type;
  98. }
  99. void JsonNode::setType(JsonType Type)
  100. {
  101. if (type == Type)
  102. return;
  103. //Reset node to NULL
  104. if (Type != DATA_NULL)
  105. setType(DATA_NULL);
  106. switch (type)
  107. {
  108. break; case DATA_STRING: delete data.String;
  109. break; case DATA_VECTOR: delete data.Vector;
  110. break; case DATA_STRUCT: delete data.Struct;
  111. break; default:
  112. break;
  113. }
  114. //Set new node type
  115. type = Type;
  116. switch(type)
  117. {
  118. break; case DATA_NULL:
  119. break; case DATA_BOOL: data.Bool = false;
  120. break; case DATA_FLOAT: data.Float = 0;
  121. break; case DATA_STRING: data.String = new std::string;
  122. break; case DATA_VECTOR: data.Vector = new JsonVector;
  123. break; case DATA_STRUCT: data.Struct = new JsonMap;
  124. }
  125. }
  126. bool JsonNode::isNull() const
  127. {
  128. return type == DATA_NULL;
  129. }
  130. bool & JsonNode::Bool()
  131. {
  132. setType(DATA_BOOL);
  133. return data.Bool;
  134. }
  135. double & JsonNode::Float()
  136. {
  137. setType(DATA_FLOAT);
  138. return data.Float;
  139. }
  140. std::string & JsonNode::String()
  141. {
  142. setType(DATA_STRING);
  143. return *data.String;
  144. }
  145. JsonVector & JsonNode::Vector()
  146. {
  147. setType(DATA_VECTOR);
  148. return *data.Vector;
  149. }
  150. JsonMap & JsonNode::Struct()
  151. {
  152. setType(DATA_STRUCT);
  153. return *data.Struct;
  154. }
  155. const bool boolDefault = false;
  156. const bool & JsonNode::Bool() const
  157. {
  158. if (type == DATA_NULL)
  159. return boolDefault;
  160. assert(type == DATA_BOOL);
  161. return data.Bool;
  162. }
  163. const double floatDefault = 0;
  164. const double & JsonNode::Float() const
  165. {
  166. if (type == DATA_NULL)
  167. return floatDefault;
  168. assert(type == DATA_FLOAT);
  169. return data.Float;
  170. }
  171. const std::string stringDefault = std::string();
  172. const std::string & JsonNode::String() const
  173. {
  174. if (type == DATA_NULL)
  175. return stringDefault;
  176. assert(type == DATA_STRING);
  177. return *data.String;
  178. }
  179. const JsonVector vectorDefault = JsonVector();
  180. const JsonVector & JsonNode::Vector() const
  181. {
  182. if (type == DATA_NULL)
  183. return vectorDefault;
  184. assert(type == DATA_VECTOR);
  185. return *data.Vector;
  186. }
  187. const JsonMap mapDefault = JsonMap();
  188. const JsonMap & JsonNode::Struct() const
  189. {
  190. if (type == DATA_NULL)
  191. return mapDefault;
  192. assert(type == DATA_STRUCT);
  193. return *data.Struct;
  194. }
  195. JsonNode & JsonNode::operator[](std::string child)
  196. {
  197. return Struct()[child];
  198. }
  199. const JsonNode & JsonNode::operator[](std::string child) const
  200. {
  201. JsonMap::const_iterator it = Struct().find(child);
  202. if (it != Struct().end())
  203. return it->second;
  204. return nullNode;
  205. }
  206. ////////////////////////////////////////////////////////////////////////////////
  207. template<typename Iterator>
  208. void JsonWriter::writeContainer(Iterator begin, Iterator end)
  209. {
  210. if (begin == end)
  211. return;
  212. prefix += '\t';
  213. end--;
  214. while (begin != end)
  215. {
  216. writeEntry(begin++);
  217. out<<",\n";
  218. }
  219. writeEntry(begin);
  220. out<<"\n";
  221. prefix.resize(prefix.size()-1);
  222. }
  223. void JsonWriter::writeEntry(JsonMap::const_iterator entry)
  224. {
  225. out << prefix;
  226. writeString(entry->first);
  227. out << " : ";
  228. writeNode(entry->second);
  229. }
  230. void JsonWriter::writeEntry(JsonVector::const_iterator entry)
  231. {
  232. out << prefix;
  233. writeNode(*entry);
  234. }
  235. void JsonWriter::writeString(const std::string &string)
  236. {
  237. static const std::string escaped = "\"\\/\b\f\n\r\t";
  238. out <<'\"';
  239. size_t pos=0, start=0;
  240. for (; pos<string.size(); pos++)
  241. {
  242. size_t escapedChar = escaped.find(string[pos]);
  243. if (escapedChar != std::string::npos)
  244. {
  245. out.write(string.data()+start, pos - start);
  246. out << '\\' << escaped[escapedChar];
  247. start = pos;
  248. }
  249. }
  250. out.write(string.data()+start, pos - start);
  251. out <<'\"';
  252. }
  253. void JsonWriter::writeNode(const JsonNode &node)
  254. {
  255. switch(node.getType())
  256. {
  257. break; case JsonNode::DATA_NULL:
  258. out << "null";
  259. break; case JsonNode::DATA_BOOL:
  260. if (node.Bool())
  261. out << "true";
  262. else
  263. out << "false";
  264. break; case JsonNode::DATA_FLOAT:
  265. out << node.Float();
  266. break; case JsonNode::DATA_STRING:
  267. writeString(node.String());
  268. break; case JsonNode::DATA_VECTOR:
  269. out << "[" << "\n";
  270. writeContainer(node.Vector().begin(), node.Vector().end());
  271. out << prefix << "]";
  272. break; case JsonNode::DATA_STRUCT:
  273. out << "{" << "\n";
  274. writeContainer(node.Struct().begin(), node.Struct().end());
  275. out << prefix << "}";
  276. }
  277. }
  278. JsonWriter::JsonWriter(std::ostream &output, const JsonNode &node):
  279. out(output)
  280. {
  281. writeNode(node);
  282. }
  283. std::ostream & operator<<(std::ostream &out, const JsonNode &node)
  284. {
  285. JsonWriter(out, node);
  286. return out << "\n";
  287. }
  288. ////////////////////////////////////////////////////////////////////////////////
  289. JsonParser::JsonParser(const char * inputString, size_t stringSize, JsonNode &root):
  290. input(inputString, stringSize),
  291. lineCount(1),
  292. lineStart(0),
  293. pos(0)
  294. {
  295. extractValue(root);
  296. extractWhitespace(false);
  297. //Warn if there are any non-whitespace symbols left
  298. if (pos < input.size())
  299. error("Not all file was parsed!", true);
  300. //TODO: better way to show errors (like printing file name as well)
  301. tlog3<<errors;
  302. }
  303. bool JsonParser::extractSeparator()
  304. {
  305. if (!extractWhitespace())
  306. return false;
  307. if ( input[pos] !=':')
  308. return error("Separator expected");
  309. pos++;
  310. return true;
  311. }
  312. bool JsonParser::extractValue(JsonNode &node)
  313. {
  314. if (!extractWhitespace())
  315. return false;
  316. switch (input[pos])
  317. {
  318. case '\"': return extractString(node);
  319. case 'n' : return extractNull(node);
  320. case 't' : return extractTrue(node);
  321. case 'f' : return extractFalse(node);
  322. case '{' : return extractStruct(node);
  323. case '[' : return extractArray(node);
  324. case '-' : return extractFloat(node);
  325. default:
  326. {
  327. if (input[pos] >= '0' && input[pos] <= '9')
  328. return extractFloat(node);
  329. return error("Value expected!");
  330. }
  331. }
  332. }
  333. bool JsonParser::extractWhitespace(bool verbose)
  334. {
  335. while (true)
  336. {
  337. while (pos < input.size() && (ui8)input[pos] <= ' ')
  338. {
  339. if (input[pos] == '\n')
  340. {
  341. lineCount++;
  342. lineStart = pos+1;
  343. }
  344. pos++;
  345. }
  346. if (pos >= input.size() || input[pos] != '/')
  347. break;
  348. pos++;
  349. if (pos == input.size())
  350. break;
  351. if (input[pos] == '/')
  352. pos++;
  353. else
  354. error("Comments must consist from two slashes!", true);
  355. while (pos < input.size() && input[pos] != '\n')
  356. pos++;
  357. }
  358. if (pos >= input.size() && verbose)
  359. return error("Unexpected end of file!");
  360. return true;
  361. }
  362. bool JsonParser::extractEscaping(std::string &str)
  363. {
  364. switch(input[pos++])
  365. {
  366. break; case '\"': str += '\"';
  367. break; case '\\': str += '\\';
  368. break; case '/': str += '/';
  369. break; case '\b': str += '\b';
  370. break; case '\f': str += '\f';
  371. break; case '\n': str += '\n';
  372. break; case '\r': str += '\r';
  373. break; case '\t': str += '\t';
  374. break; default: return error("Unknown escape sequence!", true);
  375. };
  376. return true;
  377. }
  378. bool JsonParser::extractString(std::string &str)
  379. {
  380. if (input[pos] != '\"')
  381. return error("String expected!");
  382. pos++;
  383. size_t first = pos;
  384. while (pos != input.size())
  385. {
  386. if (input[pos] == '\"') // Correct end of string
  387. {
  388. str.append( &input[first], pos-first);
  389. pos++;
  390. return true;
  391. }
  392. if (input[pos] == '\\') // Escaping
  393. {
  394. str.append( &input[first], pos-first);
  395. first = pos++;
  396. if (pos == input.size())
  397. break;
  398. extractEscaping(str);
  399. }
  400. if (input[pos] == '\n') // end-of-line
  401. {
  402. str.append( &input[first], pos-first);
  403. return error("Closing quote not found!", true);
  404. }
  405. if (input[pos] < ' ') // control character
  406. {
  407. str.append( &input[first], pos-first);
  408. first = pos+1;
  409. error("Illegal character in the string!", true);
  410. }
  411. pos++;
  412. }
  413. return error("Unterminated string!");
  414. }
  415. bool JsonParser::extractString(JsonNode &node)
  416. {
  417. std::string str;
  418. if (!extractString(str))
  419. return false;
  420. node.setType(JsonNode::DATA_STRING);
  421. node.String() = str;
  422. return true;
  423. }
  424. bool JsonParser::extractLiteral(const std::string &literal)
  425. {
  426. if (literal.compare(0, literal.size(), &input[pos], literal.size()) != 0)
  427. {
  428. while (pos < input.size() && ((input[pos]>'a' && input[pos]<'z')
  429. || (input[pos]>'A' && input[pos]<'Z')))
  430. pos++;
  431. return error("Unknown literal found", true);
  432. }
  433. pos += literal.size();
  434. return true;
  435. }
  436. bool JsonParser::extractNull(JsonNode &node)
  437. {
  438. if (!extractLiteral("null"))
  439. return false;
  440. node.setType(JsonNode::DATA_NULL);
  441. return true;
  442. }
  443. bool JsonParser::extractTrue(JsonNode &node)
  444. {
  445. if (!extractLiteral("true"))
  446. return false;
  447. node.Bool() = true;
  448. return true;
  449. }
  450. bool JsonParser::extractFalse(JsonNode &node)
  451. {
  452. if (!extractLiteral("false"))
  453. return false;
  454. node.Bool() = false;
  455. return true;
  456. }
  457. bool JsonParser::extractStruct(JsonNode &node)
  458. {
  459. node.setType(JsonNode::DATA_STRUCT);
  460. pos++;
  461. if (!extractWhitespace())
  462. return false;
  463. //Empty struct found
  464. if (input[pos] == '}')
  465. {
  466. pos++;
  467. return true;
  468. }
  469. while (true)
  470. {
  471. if (!extractWhitespace())
  472. return false;
  473. std::string key;
  474. if (!extractString(key))
  475. return false;
  476. if (node.Struct().find(key) != node.Struct().end())
  477. error("Dublicated element encountered!", true);
  478. if (!extractSeparator())
  479. return false;
  480. if (!extractElement(node.Struct()[key], '}'))
  481. return false;
  482. if (input[pos] == '}')
  483. {
  484. pos++;
  485. return true;
  486. }
  487. }
  488. }
  489. bool JsonParser::extractArray(JsonNode &node)
  490. {
  491. pos++;
  492. node.setType(JsonNode::DATA_VECTOR);
  493. if (!extractWhitespace())
  494. return false;
  495. //Empty array found
  496. if (input[pos] == ']')
  497. {
  498. pos++;
  499. return true;
  500. }
  501. while (true)
  502. {
  503. //NOTE: currently 50% of time is this vector resizing.
  504. //May be useful to use list during parsing and then swap() all items to vector
  505. node.Vector().resize(node.Vector().size()+1);
  506. if (!extractElement(node.Vector().back(), ']'))
  507. return false;
  508. if (input[pos] == ']')
  509. {
  510. pos++;
  511. return true;
  512. }
  513. }
  514. }
  515. bool JsonParser::extractElement(JsonNode &node, char terminator)
  516. {
  517. if (!extractValue(node))
  518. return false;
  519. if (!extractWhitespace())
  520. return false;
  521. bool comma = (input[pos] == ',');
  522. if (comma )
  523. {
  524. pos++;
  525. if (!extractWhitespace())
  526. return false;
  527. }
  528. if (input[pos] == terminator)
  529. return true;
  530. if (!comma)
  531. error("Comma expected!", true);
  532. return true;
  533. }
  534. bool JsonParser::extractFloat(JsonNode &node)
  535. {
  536. assert(input[pos] == '-' || (input[pos] >= '0' && input[pos] <= '9'));
  537. bool negative=false;
  538. double result=0;
  539. if (input[pos] == '-')
  540. {
  541. pos++;
  542. negative = true;
  543. }
  544. if (input[pos] < '0' || input[pos] > '9')
  545. return error("Number expected!");
  546. //Extract integer part
  547. while (input[pos] >= '0' && input[pos] <= '9')
  548. {
  549. result = result*10+(input[pos]-'0');
  550. pos++;
  551. }
  552. if (input[pos] == '.')
  553. {
  554. //extract fractional part
  555. pos++;
  556. double fractMult = 0.1;
  557. if (input[pos] < '0' || input[pos] > '9')
  558. return error("Decimal part expected!");
  559. while (input[pos] >= '0' && input[pos] <= '9')
  560. {
  561. result = result + fractMult*(input[pos]-'0');
  562. fractMult /= 10;
  563. pos++;
  564. }
  565. }
  566. //TODO: exponential part
  567. if (negative)
  568. result = -result;
  569. node.setType(JsonNode::DATA_FLOAT);
  570. node.Float() = result;
  571. return true;
  572. }
  573. bool JsonParser::error(const std::string &message, bool warning)
  574. {
  575. std::ostringstream stream;
  576. std::string type(warning?" warning: ":" error: ");
  577. stream << "At line " << lineCount << ", position "<<pos-lineStart
  578. << type << message <<"\n";
  579. errors += stream.str();
  580. return warning;
  581. }
  582. static const std::map<std::string, JsonNode::JsonType> stringToType =
  583. boost::assign::map_list_of
  584. ("null", JsonNode::DATA_NULL) ("bool", JsonNode::DATA_BOOL)
  585. ("number", JsonNode::DATA_FLOAT) ("string", JsonNode::DATA_STRING)
  586. ("array", JsonNode::DATA_VECTOR) ("object", JsonNode::DATA_STRUCT);
  587. //Check current schema entry for validness and converts "type" string to JsonType
  588. bool JsonValidator::validateSchema(JsonNode::JsonType &type, const JsonNode &schema)
  589. {
  590. if (schema.isNull())
  591. return addMessage("Missing schema for current entry!");
  592. const JsonNode &nodeType = schema["type"];
  593. if (nodeType.isNull())
  594. return addMessage("Entry type is not defined in schema!");
  595. if (nodeType.getType() != JsonNode::DATA_STRING)
  596. return addMessage("Entry type must be string!");
  597. std::map<std::string, JsonNode::JsonType>::const_iterator iter = stringToType.find(nodeType.String());
  598. if (iter == stringToType.end())
  599. return addMessage("Unknown entry type found!");
  600. type = iter->second;
  601. return true;
  602. }
  603. //Replaces node with default value if needed and calls type-specific validators
  604. bool JsonValidator::validateType(JsonNode &node, const JsonNode &schema, JsonNode::JsonType type)
  605. {
  606. if (node.isNull())
  607. {
  608. const JsonNode & defaultValue = schema["default"];
  609. if (defaultValue.isNull())
  610. return addMessage("Null entry without default entry!");
  611. else
  612. node = defaultValue;
  613. }
  614. if (minimize && node == schema["default"])
  615. {
  616. node.setType(JsonNode::DATA_NULL);
  617. return false;
  618. }
  619. if (type != node.getType())
  620. {
  621. node.setType(JsonNode::DATA_NULL);
  622. return addMessage("Type mismatch!");
  623. }
  624. if (type == JsonNode::DATA_VECTOR)
  625. return validateItems(node, schema["items"]);
  626. if (type == JsonNode::DATA_STRUCT)
  627. return validateProperties(node, schema["properties"]);
  628. return true;
  629. }
  630. // Basic checks common for any nodes
  631. bool JsonValidator::validateNode(JsonNode &node, const JsonNode &schema, const std::string &name)
  632. {
  633. currentPath.push_back(name);
  634. JsonNode::JsonType type = JsonNode::DATA_NULL;
  635. if (!validateSchema(type, schema)
  636. || !validateType(node, schema, type))
  637. {
  638. node.setType(JsonNode::DATA_NULL);
  639. currentPath.pop_back();
  640. return false;
  641. }
  642. currentPath.pop_back();
  643. return true;
  644. }
  645. //Checks "items" entry from schema (type-specific check for Vector)
  646. bool JsonValidator::validateItems(JsonNode &node, const JsonNode &schema)
  647. {
  648. JsonNode::JsonType type = JsonNode::DATA_NULL;
  649. if (!validateSchema(type, schema))
  650. return false;
  651. bool result = true;
  652. BOOST_FOREACH(JsonNode &entry, node.Vector())
  653. {
  654. if (!validateType(entry, schema, type))
  655. {
  656. result = false;
  657. entry.setType(JsonNode::DATA_NULL);
  658. }
  659. }
  660. return result;
  661. }
  662. //Checks "propertries" entry from schema (type-specific check for Struct)
  663. //Function is similar to merging of two sorted lists - check every entry that present in one of the input nodes
  664. bool JsonValidator::validateProperties(JsonNode &node, const JsonNode &schema)
  665. {
  666. if (schema.isNull())
  667. return addMessage("Properties entry is missing for struct in schema");
  668. JsonMap::iterator nodeIter = node.Struct().begin();
  669. JsonMap::const_iterator schemaIter = schema.Struct().begin();
  670. while (nodeIter != node.Struct().end() && schemaIter != schema.Struct().end())
  671. {
  672. if (nodeIter->first < schemaIter->first) //No schema for entry
  673. {
  674. validateNode(nodeIter->second, JsonNode::nullNode, nodeIter->first);
  675. JsonMap::iterator toRemove = nodeIter++;
  676. node.Struct().erase(toRemove);
  677. }
  678. else
  679. if (schemaIter->first < nodeIter->first) //No entry
  680. {
  681. if (!validateNode(node[schemaIter->first], schemaIter->second, schemaIter->first))
  682. node.Struct().erase(schemaIter->first);
  683. schemaIter++;
  684. }
  685. else //both entry and schema are present
  686. {
  687. JsonMap::iterator current = nodeIter++;
  688. if (!validateNode(current->second, schemaIter->second, current->first))
  689. node.Struct().erase(current);
  690. schemaIter++;
  691. }
  692. }
  693. while (nodeIter != node.Struct().end())
  694. {
  695. validateNode(nodeIter->second, JsonNode::nullNode, nodeIter->first);
  696. JsonMap::iterator toRemove = nodeIter++;
  697. node.Struct().erase(toRemove);
  698. }
  699. while (schemaIter != schema.Struct().end())
  700. {
  701. if (!validateNode(node[schemaIter->first], schemaIter->second, schemaIter->first))
  702. node.Struct().erase(schemaIter->first);
  703. schemaIter++;
  704. }
  705. return true;
  706. }
  707. bool JsonValidator::addMessage(const std::string &message)
  708. {
  709. std::ostringstream stream;
  710. stream << "At ";
  711. BOOST_FOREACH(const std::string &path, currentPath)
  712. stream << path<<"/";
  713. stream << "\t Error: " << message <<"\n";
  714. errors += stream.str();
  715. return false;
  716. }
  717. JsonValidator::JsonValidator(JsonNode &root, bool Minimize):
  718. minimize(Minimize)
  719. {
  720. JsonNode schema;
  721. schema.swap(root["schema"]);
  722. root.Struct().erase("schema");
  723. if (!schema.isNull())
  724. {
  725. validateProperties(root, schema);
  726. }
  727. //This message is quite annoying now - most files do not have schemas. May be re-enabled later
  728. //else
  729. // addMessage("Schema not found!", true);
  730. //TODO: better way to show errors (like printing file name as well)
  731. tlog3<<errors;
  732. }
  733. JsonValidator::JsonValidator(JsonNode &root, const JsonNode &schema, bool Minimize):
  734. minimize(Minimize)
  735. {
  736. validateProperties(root, schema);
  737. if (schema.isNull())
  738. addMessage("Schema not found!");
  739. tlog3<<errors;
  740. }
  741. Bonus * ParseBonus (const JsonVector &ability_vec) //TODO: merge with AddAbility, create universal parser for all bonus properties
  742. {
  743. Bonus * b = new Bonus();
  744. std::string type = ability_vec[0].String();
  745. auto it = bonusNameMap.find(type);
  746. if (it == bonusNameMap.end())
  747. {
  748. tlog1 << "Error: invalid ability type " << type << " in creatures.txt" << std::endl;
  749. return b;
  750. }
  751. b->type = it->second;
  752. b->val = ability_vec[1].Float();
  753. b->subtype = ability_vec[2].Float();
  754. b->additionalInfo = ability_vec[3].Float();
  755. b->duration = Bonus::PERMANENT;
  756. b->turnsRemain = 0;
  757. return b;
  758. }