data.h 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  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. /// Return true if there are no elements in the list.
  187. virtual bool empty() const;
  188. //@}
  189. /// \name MapElement functions
  190. ///
  191. /// \brief If the Element on which these functions are called are not
  192. /// an instance of MapElement, a TypeError exception is thrown.
  193. //@{
  194. /// Returns the ElementPtr at the given key
  195. /// \param name The key of the Element to return
  196. /// \return The ElementPtr at the given key, or null if not present
  197. virtual ConstElementPtr get(const std::string& name) const;
  198. /// Sets the ElementPtr at the given key
  199. /// \param name The key of the Element to set
  200. /// \param element The ElementPtr to set at the given key.
  201. virtual void set(const std::string& name, ConstElementPtr element);
  202. /// Remove the ElementPtr at the given key
  203. /// \param name The key of the Element to remove
  204. virtual void remove(const std::string& name);
  205. /// Checks if there is data at the given key
  206. /// \param name The key of the Element to remove
  207. /// \return true if there is data at the key, false if not.
  208. virtual bool contains(const std::string& name) const;
  209. /// Recursively finds any data at the given identifier. The
  210. /// identifier is a /-separated list of names of nested maps, with
  211. /// the last name being the leaf that is returned.
  212. ///
  213. /// For instance, if you have a MapElement that contains another
  214. /// MapElement at the key "foo", and that second MapElement contains
  215. /// Another Element at key "bar", the identifier for that last
  216. /// element from the first is "foo/bar".
  217. ///
  218. /// \param identifier The identifier of the element to find
  219. /// \return The ElementPtr at the given identifier. Returns a
  220. /// null ElementPtr if it is not found, which can be checked with
  221. /// Element::is_null(ElementPtr e).
  222. virtual ConstElementPtr find(const std::string& identifier) const;
  223. /// See \c Element::find()
  224. /// \param identifier The identifier of the element to find
  225. /// \param t Reference to store the resulting ElementPtr, if found.
  226. /// \return true if the element was found, false if not.
  227. virtual bool find(const std::string& identifier, ConstElementPtr& t) const;
  228. //@}
  229. /// \name Factory functions
  230. // TODO: should we move all factory functions to a different class
  231. // so as not to burden the Element base with too many functions?
  232. // and/or perhaps even to a separate header?
  233. /// \name Direct factory functions
  234. /// \brief These functions simply wrap the given data directly
  235. /// in an Element object, and return a reference to it, in the form
  236. /// of an \c ElementPtr.
  237. /// These factory functions are exception-free (unless there is
  238. /// no memory available, in which case bad_alloc is raised by the
  239. /// underlying system).
  240. /// (Note that that is different from an NullElement, which
  241. /// represents an empty value, and is created with Element::create())
  242. ///
  243. /// Notes: Read notes of IntElement definition about the use of
  244. /// long long int, long int and int.
  245. //@{
  246. static ElementPtr create();
  247. static ElementPtr create(const long long int i);
  248. static ElementPtr create(const int i) { return (create(static_cast<long long int>(i))); };
  249. static ElementPtr create(const long int i) { return (create(static_cast<long long int>(i))); };
  250. static ElementPtr create(const double d);
  251. static ElementPtr create(const bool b);
  252. static ElementPtr create(const std::string& s);
  253. // need both std:string and char *, since c++ will match
  254. // bool before std::string when you pass it a char *
  255. static ElementPtr create(const char *s) { return (create(std::string(s))); }
  256. /// \brief Creates an empty ListElement type ElementPtr.
  257. static ElementPtr createList();
  258. /// \brief Creates an empty MapElement type ElementPtr.
  259. static ElementPtr createMap();
  260. //@}
  261. /// \name Compound factory functions
  262. /// \brief These functions will parse the given string (JSON)
  263. /// representation of a compound element. If there is a parse
  264. /// error, an exception of the type isc::data::JSONError is thrown.
  265. //@{
  266. /// Creates an Element from the given JSON string
  267. /// \param in The string to parse the element from
  268. /// \return An ElementPtr that contains the element(s) specified
  269. /// in the given string.
  270. static ElementPtr fromJSON(const std::string& in);
  271. /// Creates an Element from the given input stream containing JSON
  272. /// formatted data.
  273. ///
  274. /// \param in The string to parse the element from
  275. /// \return An ElementPtr that contains the element(s) specified
  276. /// in the given input stream.
  277. static ElementPtr fromJSON(std::istream& in) throw(JSONError);
  278. static ElementPtr fromJSON(std::istream& in, const std::string& file_name) throw(JSONError);
  279. /// Creates an Element from the given input stream, where we keep
  280. /// track of the location in the stream for error reporting.
  281. ///
  282. /// \param in The string to parse the element from.
  283. /// \param file The input file name.
  284. /// \param line A reference to the int where the function keeps
  285. /// track of the current line.
  286. /// \param pos A reference to the int where the function keeps
  287. /// track of the current position within the current line.
  288. /// \return An ElementPtr that contains the element(s) specified
  289. /// in the given input stream.
  290. // make this one private?
  291. static ElementPtr fromJSON(std::istream& in, const std::string& file, int& line, int &pos) throw(JSONError);
  292. //@}
  293. /// \name Type name conversion functions
  294. /// Returns the name of the given type as a string
  295. ///
  296. /// \param type The type to return the name of
  297. /// \return The name of the type, or "unknown" if the type
  298. /// is not known.
  299. static std::string typeToName(Element::types type);
  300. /// Converts the string to the corresponding type
  301. /// Throws a TypeError if the name is unknown.
  302. ///
  303. /// \param type_name The name to get the type of
  304. /// \return the corresponding type value
  305. static Element::types nameToType(const std::string& type_name);
  306. /// \name Wire format factory functions
  307. /// These function pparse the wireformat at the given stringstream
  308. /// (of the given length). If there is a parse error an exception
  309. /// of the type isc::cc::DecodeError is raised.
  310. //@{
  311. /// Creates an Element from the wire format in the given
  312. /// stringstream of the given length.
  313. /// Since the wire format is JSON, thise is the same as
  314. /// fromJSON, and could be removed.
  315. ///
  316. /// \param in The input stringstream.
  317. /// \param length The length of the wireformat data in the stream
  318. /// \return ElementPtr with the data that is parsed.
  319. static ElementPtr fromWire(std::stringstream& in, int length);
  320. /// Creates an Element from the wire format in the given string
  321. /// Since the wire format is JSON, thise is the same as
  322. /// fromJSON, and could be removed.
  323. ///
  324. /// \param s The input string
  325. /// \return ElementPtr with the data that is parsed.
  326. static ElementPtr fromWire(const std::string& s);
  327. //@}
  328. };
  329. /// Notes: IntElement type is changed to int64_t.
  330. /// Due to C++ problems on overloading and automatic type conversion,
  331. /// (C++ tries to convert integer type values and reference/pointer
  332. /// if value types do not match exactly)
  333. /// We decided the storage as int64_t,
  334. /// three (long long, long, int) override function defintions
  335. /// and cast int/long/long long to int64_t via long long.
  336. /// Therefore, call by value methods (create, setValue) have three
  337. /// (int,long,long long) definitions. Others use int64_t.
  338. ///
  339. class IntElement : public Element {
  340. int64_t i;
  341. private:
  342. public:
  343. IntElement(int64_t v) : Element(integer), i(v) { }
  344. int64_t intValue() const { return (i); }
  345. using Element::getValue;
  346. bool getValue(int64_t& t) const { t = i; return (true); }
  347. using Element::setValue;
  348. bool setValue(long long int v) { i = v; return (true); }
  349. void toJSON(std::ostream& ss) const;
  350. bool equals(const Element& other) const;
  351. };
  352. class DoubleElement : public Element {
  353. double d;
  354. public:
  355. DoubleElement(double v) : Element(real), d(v) {};
  356. double doubleValue() const { return (d); }
  357. using Element::getValue;
  358. bool getValue(double& t) const { t = d; return (true); }
  359. using Element::setValue;
  360. bool setValue(const double v) { d = v; return (true); }
  361. void toJSON(std::ostream& ss) const;
  362. bool equals(const Element& other) const;
  363. };
  364. class BoolElement : public Element {
  365. bool b;
  366. public:
  367. BoolElement(const bool v) : Element(boolean), b(v) {};
  368. bool boolValue() const { return (b); }
  369. using Element::getValue;
  370. bool getValue(bool& t) const { t = b; return (true); }
  371. using Element::setValue;
  372. bool setValue(const bool v) { b = v; return (true); }
  373. void toJSON(std::ostream& ss) const;
  374. bool equals(const Element& other) const;
  375. };
  376. class NullElement : public Element {
  377. public:
  378. NullElement() : Element(null) {};
  379. void toJSON(std::ostream& ss) const;
  380. bool equals(const Element& other) const;
  381. };
  382. class StringElement : public Element {
  383. std::string s;
  384. public:
  385. StringElement(std::string v) : Element(string), s(v) {};
  386. std::string stringValue() const { return (s); }
  387. using Element::getValue;
  388. bool getValue(std::string& t) const { t = s; return (true); }
  389. using Element::setValue;
  390. bool setValue(const std::string& v) { s = v; return (true); }
  391. void toJSON(std::ostream& ss) const;
  392. bool equals(const Element& other) const;
  393. };
  394. class ListElement : public Element {
  395. std::vector<ConstElementPtr> l;
  396. public:
  397. ListElement() : Element(list) {}
  398. const std::vector<ConstElementPtr>& listValue() const { return (l); }
  399. using Element::getValue;
  400. bool getValue(std::vector<ConstElementPtr>& t) const {
  401. t = l;
  402. return (true);
  403. }
  404. using Element::setValue;
  405. bool setValue(const std::vector<ConstElementPtr>& v) {
  406. l = v;
  407. return (true);
  408. }
  409. using Element::get;
  410. ConstElementPtr get(int i) const { return (l.at(i)); }
  411. using Element::set;
  412. void set(size_t i, ConstElementPtr e) {
  413. l.at(i) = e;
  414. }
  415. void add(ConstElementPtr e) { l.push_back(e); };
  416. using Element::remove;
  417. void remove(int i) { l.erase(l.begin() + i); };
  418. void toJSON(std::ostream& ss) const;
  419. size_t size() const { return (l.size()); }
  420. bool empty() const { return (l.empty()); }
  421. bool equals(const Element& other) const;
  422. };
  423. class MapElement : public Element {
  424. std::map<std::string, ConstElementPtr> m;
  425. public:
  426. MapElement() : Element(map) {}
  427. // TODO: should we have direct iterators instead of exposing the std::map here?
  428. const std::map<std::string, ConstElementPtr>& mapValue() const {
  429. return (m);
  430. }
  431. using Element::getValue;
  432. bool getValue(std::map<std::string, ConstElementPtr>& t) const {
  433. t = m;
  434. return (true);
  435. }
  436. using Element::setValue;
  437. bool setValue(const std::map<std::string, ConstElementPtr>& v) {
  438. m = v;
  439. return (true);
  440. }
  441. using Element::get;
  442. ConstElementPtr get(const std::string& s) const {
  443. return (contains(s) ? m.find(s)->second : ConstElementPtr());
  444. }
  445. using Element::set;
  446. void set(const std::string& key, ConstElementPtr value);
  447. using Element::remove;
  448. void remove(const std::string& s) { m.erase(s); }
  449. bool contains(const std::string& s) const {
  450. return (m.find(s) != m.end());
  451. }
  452. void toJSON(std::ostream& ss) const;
  453. // we should name the two finds better...
  454. // find the element at id; raises TypeError if one of the
  455. // elements at path except the one we're looking for is not a
  456. // mapelement.
  457. // returns an empty element if the item could not be found
  458. ConstElementPtr find(const std::string& id) const;
  459. // find the Element at 'id', and store the element pointer in t
  460. // returns true if found, or false if not found (either because
  461. // it doesn't exist or one of the elements in the path is not
  462. // a MapElement)
  463. bool find(const std::string& id, ConstElementPtr& t) const;
  464. bool equals(const Element& other) const;
  465. };
  466. /// Checks whether the given ElementPtr is a NULL pointer
  467. /// \param p The ElementPtr to check
  468. /// \return true if it is NULL, false if not.
  469. bool isNull(ConstElementPtr p);
  470. ///
  471. /// \brief Remove all values from the first ElementPtr that are
  472. /// equal in the second. Both ElementPtrs MUST be MapElements
  473. /// The use for this function is to end up with a MapElement that
  474. /// only contains new and changed values (for ModuleCCSession and
  475. /// configuration update handlers)
  476. /// Raises a TypeError if a or b are not MapElements
  477. void removeIdentical(ElementPtr a, ConstElementPtr b);
  478. /// \brief Create a new ElementPtr from the first ElementPtr, removing all
  479. /// values that are equal in the second. Both ElementPtrs MUST be MapElements.
  480. /// The returned ElementPtr will be a MapElement that only contains new and
  481. /// changed values (for ModuleCCSession and configuration update handlers).
  482. /// Raises a TypeError if a or b are not MapElements
  483. ConstElementPtr removeIdentical(ConstElementPtr a, ConstElementPtr b);
  484. /// \brief Merges the data from other into element.
  485. /// (on the first level). Both elements must be
  486. /// MapElements.
  487. /// Every string,value pair in other is copied into element
  488. /// (the ElementPtr of value is copied, this is not a new object)
  489. /// Unless the value is a NullElement, in which case the
  490. /// key is removed from element, rather than setting the value to
  491. /// the given NullElement.
  492. /// This way, we can remove values from for instance maps with
  493. /// configuration data (which would then result in reverting back
  494. /// to the default).
  495. /// Raises a TypeError if either ElementPtr is not a MapElement
  496. void merge(ElementPtr element, ConstElementPtr other);
  497. ///
  498. /// \brief Insert the Element as a string into stream.
  499. ///
  500. /// This method converts the \c ElementPtr into a string with
  501. /// \c Element::str() and inserts it into the
  502. /// output stream \c out.
  503. ///
  504. /// This function overloads the global operator<< to behave as described in
  505. /// ostream::operator<< but applied to \c ElementPtr objects.
  506. ///
  507. /// \param out A \c std::ostream object on which the insertion operation is
  508. /// performed.
  509. /// \param e The \c ElementPtr object to insert.
  510. /// \return A reference to the same \c std::ostream object referenced by
  511. /// parameter \c out after the insertion operation.
  512. std::ostream& operator<<(std::ostream& out, const Element& e);
  513. bool operator==(const Element& a, const Element& b);
  514. bool operator!=(const Element& a, const Element& b);
  515. } }
  516. #endif // ISC_DATA_H
  517. // Local Variables:
  518. // mode: c++
  519. // End: