data.h 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. // Copyright (C) 2010 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #ifndef ISC_DATA_H
  15. #define ISC_DATA_H 1
  16. #include <string>
  17. #include <vector>
  18. #include <map>
  19. #include <boost/shared_ptr.hpp>
  20. #include <stdexcept>
  21. #include <exceptions/exceptions.h>
  22. namespace isc { namespace data {
  23. class Element;
  24. // todo: describe the rationale behind ElementPtr?
  25. typedef boost::shared_ptr<Element> ElementPtr;
  26. typedef boost::shared_ptr<const Element> ConstElementPtr;
  27. ///
  28. /// \brief A standard Data module exception that is thrown if a function
  29. /// is called for an Element that has a wrong type (e.g. int_value on a
  30. /// ListElement)
  31. ///
  32. class TypeError : public isc::Exception {
  33. public:
  34. TypeError(const char* file, size_t line, const char* what) :
  35. isc::Exception(file, line, what) {}
  36. };
  37. ///
  38. /// \brief A standard Data module exception that is thrown if a parse
  39. /// error is encountered when constructing an Element from a string
  40. ///
  41. // i'd like to use Exception here but we need one that is derived from
  42. // runtime_error (as this one is directly based on external data, and
  43. // i want to add some values to any static data string that is provided)
  44. class JSONError : public isc::Exception {
  45. public:
  46. JSONError(const char* file, size_t line, const char* what) :
  47. isc::Exception(file, line, what) {}
  48. };
  49. ///
  50. /// \brief The \c Element class represents a piece of data, used by
  51. /// the command channel and configuration parts.
  52. ///
  53. /// An \c Element can contain simple types (int, real, string, bool and
  54. /// None), and composite types (list and string->element maps)
  55. ///
  56. /// Elements should in calling functions usually be referenced through
  57. /// an \c ElementPtr, which can be created using the factory functions
  58. /// \c Element::create() and \c Element::fromJSON()
  59. ///
  60. /// Notes to developers: Element is a base class, implemented by a
  61. /// specific subclass for each type (IntElement, BoolElement, etc).
  62. /// Element does define all functions for all types, and defaults to
  63. /// raising a \c TypeError for functions that are not supported for
  64. /// the type in question.
  65. ///
  66. class Element {
  67. private:
  68. // technically the type could be omitted; is it useful?
  69. // should we remove it or replace it with a pure virtual
  70. // function getType?
  71. int type;
  72. protected:
  73. Element(int t) { type = t; }
  74. public:
  75. // any is a special type used in list specifications, specifying
  76. // that the elements can be of any type
  77. enum types { integer, real, boolean, null, string, list, map, any };
  78. // base class; make dtor virtual
  79. virtual ~Element() {};
  80. /// \return the type of this element
  81. int getType() const { return (type); }
  82. /// Returns a string representing the Element and all its
  83. /// child elements; note that this is different from stringValue(),
  84. /// which only returns the single value of a StringElement
  85. ///
  86. /// The resulting string will contain the Element in JSON format.
  87. ///
  88. /// \return std::string containing the string representation
  89. std::string str() const;
  90. /// Returns the wireformat for the Element and all its child
  91. /// elements.
  92. ///
  93. /// \return std::string containing the element in wire format
  94. std::string toWire() const;
  95. void toWire(std::ostream& out) const;
  96. /// \name pure virtuals, every derived class must implement these
  97. /// \return true if the other ElementPtr has the same type and value
  98. virtual bool equals(const Element& other) const = 0;
  99. /// Converts the Element to JSON format and appends it to
  100. /// the given stringstream.
  101. virtual void toJSON(std::ostream& ss) const = 0;
  102. /// \name Type-specific getters
  103. ///
  104. /// \brief These functions only
  105. /// work on their corresponding Element type. For all other
  106. /// types, a TypeError is thrown.
  107. /// If you want an exception-safe getter method, use
  108. /// getValue() below
  109. //@{
  110. virtual int64_t intValue() const
  111. { isc_throw(TypeError, "intValue() called on non-integer Element"); };
  112. virtual double doubleValue() const
  113. { isc_throw(TypeError, "doubleValue() called on non-double Element"); };
  114. virtual bool boolValue() const
  115. { isc_throw(TypeError, "boolValue() called on non-Bool Element"); };
  116. virtual std::string stringValue() const
  117. { isc_throw(TypeError, "stringValue() called on non-string Element"); };
  118. virtual const std::vector<ConstElementPtr>& listValue() const {
  119. // replace with real exception or empty vector?
  120. isc_throw(TypeError, "listValue() called on non-list Element");
  121. };
  122. virtual const std::map<std::string, ConstElementPtr>& mapValue() const {
  123. // replace with real exception or empty map?
  124. isc_throw(TypeError, "mapValue() called on non-map Element");
  125. };
  126. //@}
  127. /// \name Exception-safe getters
  128. ///
  129. /// \brief The getValue() functions return false if the given reference
  130. /// is of another type than the element contains
  131. /// By default it always returns false; the derived classes
  132. /// override the function for their type, copying their
  133. /// data to the given reference and returning true
  134. ///
  135. //@{
  136. virtual bool getValue(int64_t& t) const;
  137. virtual bool getValue(double& t) const;
  138. virtual bool getValue(bool& t) const;
  139. virtual bool getValue(std::string& t) const;
  140. virtual bool getValue(std::vector<ConstElementPtr>& t) const;
  141. virtual bool getValue(std::map<std::string, ConstElementPtr>& t) const;
  142. //@}
  143. ///
  144. /// \name Exception-safe setters.
  145. ///
  146. /// \brief Return false if the Element is not
  147. /// the right type. Set the value and return true if the Elements
  148. /// is of the correct type
  149. ///
  150. /// Notes: Read notes of IntElement definition about the use of
  151. /// long long int, long int and int.
  152. //@{
  153. virtual bool setValue(const long long int v);
  154. bool setValue(const long int i) { return (setValue(static_cast<long long int>(i))); };
  155. bool setValue(const int i) { return (setValue(static_cast<long long int>(i))); };
  156. virtual bool setValue(const double v);
  157. virtual bool setValue(const bool t);
  158. virtual bool setValue(const std::string& v);
  159. virtual bool setValue(const std::vector<ConstElementPtr>& v);
  160. virtual bool setValue(const std::map<std::string, ConstElementPtr>& v);
  161. //@}
  162. // Other functions for specific subtypes
  163. /// \name ListElement functions
  164. ///
  165. /// \brief If the Element on which these functions are called are not
  166. /// an instance of ListElement, a TypeError exception is thrown.
  167. //@{
  168. /// Returns the ElementPtr at the given index. If the index is out
  169. /// of bounds, this function throws an std::out_of_range exception.
  170. /// \param i The position of the ElementPtr to return
  171. virtual ConstElementPtr get(const int i) const;
  172. /// Sets the ElementPtr at the given index. If the index is out
  173. /// of bounds, this function throws an std::out_of_range exception.
  174. /// \param i The position of the ElementPtr to set
  175. /// \param element The ElementPtr to set at the position
  176. virtual void set(const size_t i, ConstElementPtr element);
  177. /// Adds an ElementPtr to the list
  178. /// \param element The ElementPtr to add
  179. virtual void add(ConstElementPtr element);
  180. /// Removes the element at the given position. If the index is out
  181. /// of nothing happens.
  182. /// \param i The index of the element to remove.
  183. virtual void remove(const int i);
  184. /// Returns the number of elements in the list.
  185. virtual size_t size() const;
  186. //@}
  187. /// \name MapElement functions
  188. ///
  189. /// \brief If the Element on which these functions are called are not
  190. /// an instance of MapElement, a TypeError exception is thrown.
  191. //@{
  192. /// Returns the ElementPtr at the given key
  193. /// \param name The key of the Element to return
  194. /// \return The ElementPtr at the given key, or null if not present
  195. virtual ConstElementPtr get(const std::string& name) const;
  196. /// Sets the ElementPtr at the given key
  197. /// \param name The key of the Element to set
  198. /// \param element The ElementPtr to set at the given key.
  199. virtual void set(const std::string& name, ConstElementPtr element);
  200. /// Remove the ElementPtr at the given key
  201. /// \param name The key of the Element to remove
  202. virtual void remove(const std::string& name);
  203. /// Checks if there is data at the given key
  204. /// \param name The key of the Element to remove
  205. /// \return true if there is data at the key, false if not.
  206. virtual bool contains(const std::string& name) const;
  207. /// Recursively finds any data at the given identifier. The
  208. /// identifier is a /-separated list of names of nested maps, with
  209. /// the last name being the leaf that is returned.
  210. ///
  211. /// For instance, if you have a MapElement that contains another
  212. /// MapElement at the key "foo", and that second MapElement contains
  213. /// Another Element at key "bar", the identifier for that last
  214. /// element from the first is "foo/bar".
  215. ///
  216. /// \param identifier The identifier of the element to find
  217. /// \return The ElementPtr at the given identifier. Returns a
  218. /// null ElementPtr if it is not found, which can be checked with
  219. /// Element::is_null(ElementPtr e).
  220. virtual ConstElementPtr find(const std::string& identifier) const;
  221. /// See \c Element::find()
  222. /// \param identifier The identifier of the element to find
  223. /// \param t Reference to store the resulting ElementPtr, if found.
  224. /// \return true if the element was found, false if not.
  225. virtual bool find(const std::string& identifier, ConstElementPtr& t) const;
  226. //@}
  227. /// \name Factory functions
  228. // TODO: should we move all factory functions to a different class
  229. // so as not to burden the Element base with too many functions?
  230. // and/or perhaps even to a separate header?
  231. /// \name Direct factory functions
  232. /// \brief These functions simply wrap the given data directly
  233. /// in an Element object, and return a reference to it, in the form
  234. /// of an \c ElementPtr.
  235. /// These factory functions are exception-free (unless there is
  236. /// no memory available, in which case bad_alloc is raised by the
  237. /// underlying system).
  238. /// (Note that that is different from an NullElement, which
  239. /// represents an empty value, and is created with Element::create())
  240. ///
  241. /// Notes: Read notes of IntElement definition about the use of
  242. /// long long int, long int and int.
  243. //@{
  244. static ElementPtr create();
  245. static ElementPtr create(const long long int i);
  246. static ElementPtr create(const int i) { return (create(static_cast<long long int>(i))); };
  247. static ElementPtr create(const long int i) { return (create(static_cast<long long int>(i))); };
  248. static ElementPtr create(const double d);
  249. static ElementPtr create(const bool b);
  250. static ElementPtr create(const std::string& s);
  251. // need both std:string and char *, since c++ will match
  252. // bool before std::string when you pass it a char *
  253. static ElementPtr create(const char *s) { return (create(std::string(s))); }
  254. /// \brief Creates an empty ListElement type ElementPtr.
  255. static ElementPtr createList();
  256. /// \brief Creates an empty MapElement type ElementPtr.
  257. static ElementPtr createMap();
  258. //@}
  259. /// \name Compound factory functions
  260. /// \brief These functions will parse the given string (JSON)
  261. /// representation of a compound element. If there is a parse
  262. /// error, an exception of the type isc::data::JSONError is thrown.
  263. //@{
  264. /// Creates an Element from the given JSON string
  265. /// \param in The string to parse the element from
  266. /// \return An ElementPtr that contains the element(s) specified
  267. /// in the given string.
  268. static ElementPtr fromJSON(const std::string& in);
  269. /// Creates an Element from the given input stream containing JSON
  270. /// formatted data.
  271. ///
  272. /// \param in The string to parse the element from
  273. /// \return An ElementPtr that contains the element(s) specified
  274. /// in the given input stream.
  275. static ElementPtr fromJSON(std::istream& in) throw(JSONError);
  276. static ElementPtr fromJSON(std::istream& in, const std::string& file_name) throw(JSONError);
  277. /// Creates an Element from the given input stream, where we keep
  278. /// track of the location in the stream for error reporting.
  279. ///
  280. /// \param in The string to parse the element from.
  281. /// \param file The input file name.
  282. /// \param line A reference to the int where the function keeps
  283. /// track of the current line.
  284. /// \param pos A reference to the int where the function keeps
  285. /// track of the current position within the current line.
  286. /// \return An ElementPtr that contains the element(s) specified
  287. /// in the given input stream.
  288. // make this one private?
  289. static ElementPtr fromJSON(std::istream& in, const std::string& file, int& line, int &pos) throw(JSONError);
  290. //@}
  291. /// \name Type name conversion functions
  292. /// Returns the name of the given type as a string
  293. ///
  294. /// \param type The type to return the name of
  295. /// \return The name of the type, or "unknown" if the type
  296. /// is not known.
  297. static std::string typeToName(Element::types type);
  298. /// Converts the string to the corresponding type
  299. /// Throws a TypeError if the name is unknown.
  300. ///
  301. /// \param type_name The name to get the type of
  302. /// \return the corresponding type value
  303. static Element::types nameToType(const std::string& type_name);
  304. /// \name Wire format factory functions
  305. /// These function pparse the wireformat at the given stringstream
  306. /// (of the given length). If there is a parse error an exception
  307. /// of the type isc::cc::DecodeError is raised.
  308. //@{
  309. /// Creates an Element from the wire format in the given
  310. /// stringstream of the given length.
  311. /// Since the wire format is JSON, thise is the same as
  312. /// fromJSON, and could be removed.
  313. ///
  314. /// \param in The input stringstream.
  315. /// \param length The length of the wireformat data in the stream
  316. /// \return ElementPtr with the data that is parsed.
  317. static ElementPtr fromWire(std::stringstream& in, int length);
  318. /// Creates an Element from the wire format in the given string
  319. /// Since the wire format is JSON, thise is the same as
  320. /// fromJSON, and could be removed.
  321. ///
  322. /// \param s The input string
  323. /// \return ElementPtr with the data that is parsed.
  324. static ElementPtr fromWire(const std::string& s);
  325. //@}
  326. };
  327. /// Notes: IntElement type is changed to int64_t.
  328. /// Due to C++ problems on overloading and automatic type conversion,
  329. /// (C++ tries to convert integer type values and reference/pointer
  330. /// if value types do not match exactly)
  331. /// We decided the storage as int64_t,
  332. /// three (long long, long, int) override function defintions
  333. /// and cast int/long/long long to int64_t via long long.
  334. /// Therefore, call by value methods (create, setValue) have three
  335. /// (int,long,long long) definitions. Others use int64_t.
  336. ///
  337. class IntElement : public Element {
  338. int64_t i;
  339. private:
  340. public:
  341. IntElement(int64_t v) : Element(integer), i(v) { }
  342. int64_t intValue() const { return (i); }
  343. using Element::getValue;
  344. bool getValue(int64_t& t) const { t = i; return (true); }
  345. using Element::setValue;
  346. bool setValue(long long int v) { i = v; return (true); }
  347. void toJSON(std::ostream& ss) const;
  348. bool equals(const Element& other) const;
  349. };
  350. class DoubleElement : public Element {
  351. double d;
  352. public:
  353. DoubleElement(double v) : Element(real), d(v) {};
  354. double doubleValue() const { return (d); }
  355. using Element::getValue;
  356. bool getValue(double& t) const { t = d; return (true); }
  357. using Element::setValue;
  358. bool setValue(const double v) { d = v; return (true); }
  359. void toJSON(std::ostream& ss) const;
  360. bool equals(const Element& other) const;
  361. };
  362. class BoolElement : public Element {
  363. bool b;
  364. public:
  365. BoolElement(const bool v) : Element(boolean), b(v) {};
  366. bool boolValue() const { return (b); }
  367. using Element::getValue;
  368. bool getValue(bool& t) const { t = b; return (true); }
  369. using Element::setValue;
  370. bool setValue(const bool v) { b = v; return (true); }
  371. void toJSON(std::ostream& ss) const;
  372. bool equals(const Element& other) const;
  373. };
  374. class NullElement : public Element {
  375. public:
  376. NullElement() : Element(null) {};
  377. void toJSON(std::ostream& ss) const;
  378. bool equals(const Element& other) const;
  379. };
  380. class StringElement : public Element {
  381. std::string s;
  382. public:
  383. StringElement(std::string v) : Element(string), s(v) {};
  384. std::string stringValue() const { return (s); }
  385. using Element::getValue;
  386. bool getValue(std::string& t) const { t = s; return (true); }
  387. using Element::setValue;
  388. bool setValue(const std::string& v) { s = v; return (true); }
  389. void toJSON(std::ostream& ss) const;
  390. bool equals(const Element& other) const;
  391. };
  392. class ListElement : public Element {
  393. std::vector<ConstElementPtr> l;
  394. public:
  395. ListElement() : Element(list) {}
  396. const std::vector<ConstElementPtr>& listValue() const { return (l); }
  397. using Element::getValue;
  398. bool getValue(std::vector<ConstElementPtr>& t) const {
  399. t = l;
  400. return (true);
  401. }
  402. using Element::setValue;
  403. bool setValue(const std::vector<ConstElementPtr>& v) {
  404. l = v;
  405. return (true);
  406. }
  407. using Element::get;
  408. ConstElementPtr get(int i) const { return (l.at(i)); }
  409. using Element::set;
  410. void set(size_t i, ConstElementPtr e) {
  411. l.at(i) = e;
  412. }
  413. void add(ConstElementPtr e) { l.push_back(e); };
  414. using Element::remove;
  415. void remove(int i) { l.erase(l.begin() + i); };
  416. void toJSON(std::ostream& ss) const;
  417. size_t size() const { return (l.size()); }
  418. bool equals(const Element& other) const;
  419. };
  420. class MapElement : public Element {
  421. std::map<std::string, ConstElementPtr> m;
  422. public:
  423. MapElement() : Element(map) {}
  424. // TODO: should we have direct iterators instead of exposing the std::map here?
  425. const std::map<std::string, ConstElementPtr>& mapValue() const {
  426. return (m);
  427. }
  428. using Element::getValue;
  429. bool getValue(std::map<std::string, ConstElementPtr>& t) const {
  430. t = m;
  431. return (true);
  432. }
  433. using Element::setValue;
  434. bool setValue(const std::map<std::string, ConstElementPtr>& v) {
  435. m = v;
  436. return (true);
  437. }
  438. using Element::get;
  439. ConstElementPtr get(const std::string& s) const {
  440. return (contains(s) ? m.find(s)->second : ConstElementPtr());
  441. }
  442. using Element::set;
  443. void set(const std::string& key, ConstElementPtr value);
  444. using Element::remove;
  445. void remove(const std::string& s) { m.erase(s); }
  446. bool contains(const std::string& s) const {
  447. return (m.find(s) != m.end());
  448. }
  449. void toJSON(std::ostream& ss) const;
  450. // we should name the two finds better...
  451. // find the element at id; raises TypeError if one of the
  452. // elements at path except the one we're looking for is not a
  453. // mapelement.
  454. // returns an empty element if the item could not be found
  455. ConstElementPtr find(const std::string& id) const;
  456. // find the Element at 'id', and store the element pointer in t
  457. // returns true if found, or false if not found (either because
  458. // it doesn't exist or one of the elements in the path is not
  459. // a MapElement)
  460. bool find(const std::string& id, ConstElementPtr& t) const;
  461. bool equals(const Element& other) const;
  462. };
  463. /// Checks whether the given ElementPtr is a NULL pointer
  464. /// \param p The ElementPtr to check
  465. /// \return true if it is NULL, false if not.
  466. bool isNull(ConstElementPtr p);
  467. ///
  468. /// \brief Remove all values from the first ElementPtr that are
  469. /// equal in the second. Both ElementPtrs MUST be MapElements
  470. /// The use for this function is to end up with a MapElement that
  471. /// only contains new and changed values (for ModuleCCSession and
  472. /// configuration update handlers)
  473. /// Raises a TypeError if a or b are not MapElements
  474. void removeIdentical(ElementPtr a, ConstElementPtr b);
  475. /// \brief Create a new ElementPtr from the first ElementPtr, removing all
  476. /// values that are equal in the second. Both ElementPtrs MUST be MapElements.
  477. /// The returned ElementPtr will be a MapElement that only contains new and
  478. /// changed values (for ModuleCCSession and configuration update handlers).
  479. /// Raises a TypeError if a or b are not MapElements
  480. ConstElementPtr removeIdentical(ConstElementPtr a, ConstElementPtr b);
  481. /// \brief Merges the data from other into element.
  482. /// (on the first level). Both elements must be
  483. /// MapElements.
  484. /// Every string,value pair in other is copied into element
  485. /// (the ElementPtr of value is copied, this is not a new object)
  486. /// Unless the value is a NullElement, in which case the
  487. /// key is removed from element, rather than setting the value to
  488. /// the given NullElement.
  489. /// This way, we can remove values from for instance maps with
  490. /// configuration data (which would then result in reverting back
  491. /// to the default).
  492. /// Raises a TypeError if either ElementPtr is not a MapElement
  493. void merge(ElementPtr element, ConstElementPtr other);
  494. ///
  495. /// \brief Insert the Element as a string into stream.
  496. ///
  497. /// This method converts the \c ElementPtr into a string with
  498. /// \c Element::str() and inserts it into the
  499. /// output stream \c out.
  500. ///
  501. /// This function overloads the global operator<< to behave as described in
  502. /// ostream::operator<< but applied to \c ElementPtr objects.
  503. ///
  504. /// \param out A \c std::ostream object on which the insertion operation is
  505. /// performed.
  506. /// \param e The \c ElementPtr object to insert.
  507. /// \return A reference to the same \c std::ostream object referenced by
  508. /// parameter \c out after the insertion operation.
  509. std::ostream& operator<<(std::ostream& out, const Element& e);
  510. bool operator==(const Element& a, const Element& b);
  511. bool operator!=(const Element& a, const Element& b);
  512. } }
  513. #endif // ISC_DATA_H
  514. // Local Variables:
  515. // mode: c++
  516. // End: