data.h 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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. /// \returns true if the other ElementPtr has the same type and
  98. /// value
  99. virtual bool equals(const Element& other) const = 0;
  100. /// Converts the Element to JSON format and appends it to
  101. /// the given stringstream.
  102. virtual void toJSON(std::ostream& ss) const = 0;
  103. /// \name Type-specific getters
  104. ///
  105. /// \brief These functions only
  106. /// work on their corresponding Element type. For all other
  107. /// types, a TypeError is thrown.
  108. /// If you want an exception-safe getter method, use
  109. /// getValue() below
  110. //@{
  111. virtual long int intValue() const
  112. { isc_throw(TypeError, "intValue() called on non-integer Element"); };
  113. virtual double doubleValue() const
  114. { isc_throw(TypeError, "doubleValue() called on non-double Element"); };
  115. virtual bool boolValue() const
  116. { isc_throw(TypeError, "boolValue() called on non-Bool Element"); };
  117. virtual std::string stringValue() const
  118. { isc_throw(TypeError, "stringValue() called on non-string Element"); };
  119. virtual const std::vector<ConstElementPtr>& listValue() const {
  120. // replace with real exception or empty vector?
  121. isc_throw(TypeError, "listValue() called on non-list Element");
  122. };
  123. virtual const std::map<std::string, ConstElementPtr>& mapValue() const {
  124. // replace with real exception or empty map?
  125. isc_throw(TypeError, "mapValue() called on non-map Element");
  126. };
  127. //@}
  128. /// \name Exception-safe getters
  129. ///
  130. /// \brief The getValue() functions return false if the given reference
  131. /// is of another type than the element contains
  132. /// By default it always returns false; the derived classes
  133. /// override the function for their type, copying their
  134. /// data to the given reference and returning true
  135. ///
  136. //@{
  137. virtual bool getValue(long int& t) const;
  138. virtual bool getValue(double& t) const;
  139. virtual bool getValue(bool& t) const;
  140. virtual bool getValue(std::string& t) const;
  141. virtual bool getValue(std::vector<ConstElementPtr>& t) const;
  142. virtual bool getValue(std::map<std::string, ConstElementPtr>& t) const;
  143. //@}
  144. ///
  145. /// \name Exception-safe setters.
  146. ///
  147. /// \brief Return false if the Element is not
  148. /// the right type. Set the value and return true if the Elements
  149. /// is of the correct type
  150. ///
  151. //@{
  152. virtual bool setValue(const long int v);
  153. virtual bool setValue(const double v);
  154. virtual bool setValue(const bool t);
  155. virtual bool setValue(const std::string& v);
  156. virtual bool setValue(const std::vector<ConstElementPtr>& v);
  157. virtual bool setValue(const std::map<std::string, ConstElementPtr>& v);
  158. //@}
  159. // Other functions for specific subtypes
  160. /// \name ListElement functions
  161. ///
  162. /// \brief If the Element on which these functions are called are not
  163. /// an instance of ListElement, a TypeError exception is thrown.
  164. //@{
  165. /// Returns the ElementPtr at the given index. If the index is out
  166. /// of bounds, this function throws an std::out_of_range exception.
  167. /// \param i The position of the ElementPtr to return
  168. virtual ConstElementPtr get(const int i) const;
  169. /// Sets the ElementPtr at the given index. If the index is out
  170. /// of bounds, this function throws an std::out_of_range exception.
  171. /// \param i The position of the ElementPtr to set
  172. /// \param element The ElementPtr to set at the position
  173. virtual void set(const size_t i, ConstElementPtr element);
  174. /// Adds an ElementPtr to the list
  175. /// \param element The ElementPtr to add
  176. virtual void add(ConstElementPtr element);
  177. /// Removes the element at the given position. If the index is out
  178. /// of nothing happens.
  179. /// \param i The index of the element to remove.
  180. virtual void remove(const int i);
  181. /// Returns the number of elements in the list.
  182. virtual size_t size() const;
  183. //@}
  184. /// \name MapElement functions
  185. ///
  186. /// \brief If the Element on which these functions are called are not
  187. /// an instance of MapElement, a TypeError exception is thrown.
  188. //@{
  189. /// Returns the ElementPtr at the given key
  190. /// \param name The key of the Element to return
  191. /// \return The ElementPtr at the given key
  192. virtual ConstElementPtr get(const std::string& name) const;
  193. /// Sets the ElementPtr at the given key
  194. /// \param name The key of the Element to set
  195. /// \param element The ElementPtr to set at the given key.
  196. virtual void set(const std::string& name, ConstElementPtr element);
  197. /// Remove the ElementPtr at the given key
  198. /// \param name The key of the Element to remove
  199. virtual void remove(const std::string& name);
  200. /// Checks if there is data at the given key
  201. /// \param name The key of the Element to remove
  202. /// \return true if there is data at the key, false if not.
  203. virtual bool contains(const std::string& name) const;
  204. /// Recursively finds any data at the given identifier. The
  205. /// identifier is a /-separated list of names of nested maps, with
  206. /// the last name being the leaf that is returned.
  207. ///
  208. /// For instance, if you have a MapElement that contains another
  209. /// MapElement at the key "foo", and that second MapElement contains
  210. /// Another Element at key "bar", the identifier for that last
  211. /// element from the first is "foo/bar".
  212. ///
  213. /// \param identifier The identifier of the element to find
  214. /// \return The ElementPtr at the given identifier. Returns a
  215. /// null ElementPtr if it is not found, which can be checked with
  216. /// Element::is_null(ElementPtr e).
  217. virtual ConstElementPtr find(const std::string& identifier) const;
  218. /// See \c Element::find()
  219. /// \param identifier The identifier of the element to find
  220. /// \param t Reference to store the resulting ElementPtr, if found.
  221. /// \return true if the element was found, false if not.
  222. virtual bool find(const std::string& identifier, ConstElementPtr& t) const;
  223. //@}
  224. /// \name Factory functions
  225. // TODO: should we move all factory functions to a different class
  226. // so as not to burden the Element base with too many functions?
  227. // and/or perhaps even to a separate header?
  228. /// \name Direct factory functions
  229. /// \brief These functions simply wrap the given data directly
  230. /// in an Element object, and return a reference to it, in the form
  231. /// of an \c ElementPtr.
  232. /// These factory functions are exception-free (unless there is
  233. /// no memory available, in which case bad_alloc is raised by the
  234. /// underlying system).
  235. /// (Note that that is different from an NullElement, which
  236. /// represents an empty value, and is created with Element::create())
  237. //@{
  238. static ElementPtr create();
  239. static ElementPtr create(const long int i);
  240. static ElementPtr create(const int i) { return (create(static_cast<long int>(i))); };
  241. static ElementPtr create(const double d);
  242. static ElementPtr create(const bool b);
  243. static ElementPtr create(const std::string& s);
  244. // need both std:string and char *, since c++ will match
  245. // bool before std::string when you pass it a char *
  246. static ElementPtr create(const char *s) { return (create(std::string(s))); }
  247. /// \brief Creates an empty ListElement type ElementPtr.
  248. static ElementPtr createList();
  249. /// \brief Creates an empty MapElement type ElementPtr.
  250. static ElementPtr createMap();
  251. //@}
  252. /// \name Compound factory functions
  253. /// \brief These functions will parse the given string (JSON)
  254. /// representation of a compound element. If there is a parse
  255. /// error, an exception of the type isc::data::JSONError is thrown.
  256. //@{
  257. /// Creates an Element from the given JSON string
  258. /// \param in The string to parse the element from
  259. /// \return An ElementPtr that contains the element(s) specified
  260. /// in the given string.
  261. static ElementPtr fromJSON(const std::string& in);
  262. /// Creates an Element from the given input stream containing JSON
  263. /// formatted data.
  264. ///
  265. /// \param in The string to parse the element from
  266. /// \return An ElementPtr that contains the element(s) specified
  267. /// in the given input stream.
  268. static ElementPtr fromJSON(std::istream& in) throw(JSONError);
  269. static ElementPtr fromJSON(std::istream& in, const std::string& file_name) throw(JSONError);
  270. /// Creates an Element from the given input stream, where we keep
  271. /// track of the location in the stream for error reporting.
  272. ///
  273. /// \param in The string to parse the element from.
  274. /// \param file The input file name.
  275. /// \param line A reference to the int where the function keeps
  276. /// track of the current line.
  277. /// \param pos A reference to the int where the function keeps
  278. /// track of the current position within the current line.
  279. /// \return An ElementPtr that contains the element(s) specified
  280. /// in the given input stream.
  281. // make this one private?
  282. static ElementPtr fromJSON(std::istream& in, const std::string& file, int& line, int &pos) throw(JSONError);
  283. //@}
  284. /// \name Type name conversion functions
  285. /// Returns the name of the given type as a string
  286. ///
  287. /// \param type The type to return the name of
  288. /// \return The name of the type, or "unknown" if the type
  289. /// is not known.
  290. static std::string typeToName(Element::types type);
  291. /// Converts the string to the corresponding type
  292. /// Throws a TypeError if the name is unknown.
  293. ///
  294. /// \param type_name The name to get the type of
  295. /// \return the corresponding type value
  296. static Element::types nameToType(const std::string& type_name);
  297. /// \name Wire format factory functions
  298. /// These function pparse the wireformat at the given stringstream
  299. /// (of the given length). If there is a parse error an exception
  300. /// of the type isc::cc::DecodeError is raised.
  301. //@{
  302. /// Creates an Element from the wire format in the given
  303. /// stringstream of the given length.
  304. /// Since the wire format is JSON, thise is the same as
  305. /// fromJSON, and could be removed.
  306. ///
  307. /// \param in The input stringstream.
  308. /// \param length The length of the wireformat data in the stream
  309. /// \return ElementPtr with the data that is parsed.
  310. static ElementPtr fromWire(std::stringstream& in, int length);
  311. /// Creates an Element from the wire format in the given string
  312. /// Since the wire format is JSON, thise is the same as
  313. /// fromJSON, and could be removed.
  314. ///
  315. /// \param s The input string
  316. /// \return ElementPtr with the data that is parsed.
  317. static ElementPtr fromWire(const std::string& s);
  318. //@}
  319. };
  320. class IntElement : public Element {
  321. long int i;
  322. public:
  323. IntElement(long int v) : Element(integer), i(v) { }
  324. long int intValue() const { return (i); }
  325. using Element::getValue;
  326. bool getValue(long int& t) const { t = i; return (true); }
  327. using Element::setValue;
  328. bool setValue(const long int v) { i = v; return (true); }
  329. void toJSON(std::ostream& ss) const;
  330. bool equals(const Element& other) const;
  331. };
  332. class DoubleElement : public Element {
  333. double d;
  334. public:
  335. DoubleElement(double v) : Element(real), d(v) {};
  336. double doubleValue() const { return (d); }
  337. using Element::getValue;
  338. bool getValue(double& t) const { t = d; return (true); }
  339. using Element::setValue;
  340. bool setValue(const double v) { d = v; return (true); }
  341. void toJSON(std::ostream& ss) const;
  342. bool equals(const Element& other) const;
  343. };
  344. class BoolElement : public Element {
  345. bool b;
  346. public:
  347. BoolElement(const bool v) : Element(boolean), b(v) {};
  348. bool boolValue() const { return (b); }
  349. using Element::getValue;
  350. bool getValue(bool& t) const { t = b; return (true); }
  351. using Element::setValue;
  352. bool setValue(const bool v) { b = v; return (true); }
  353. void toJSON(std::ostream& ss) const;
  354. bool equals(const Element& other) const;
  355. };
  356. class NullElement : public Element {
  357. public:
  358. NullElement() : Element(null) {};
  359. void toJSON(std::ostream& ss) const;
  360. bool equals(const Element& other) const;
  361. };
  362. class StringElement : public Element {
  363. std::string s;
  364. public:
  365. StringElement(std::string v) : Element(string), s(v) {};
  366. std::string stringValue() const { return (s); }
  367. using Element::getValue;
  368. bool getValue(std::string& t) const { t = s; return (true); }
  369. using Element::setValue;
  370. bool setValue(const std::string& v) { s = v; return (true); }
  371. void toJSON(std::ostream& ss) const;
  372. bool equals(const Element& other) const;
  373. };
  374. class ListElement : public Element {
  375. std::vector<ConstElementPtr> l;
  376. public:
  377. ListElement() : Element(list) {}
  378. const std::vector<ConstElementPtr>& listValue() const { return (l); }
  379. using Element::getValue;
  380. bool getValue(std::vector<ConstElementPtr>& t) const {
  381. t = l;
  382. return (true);
  383. }
  384. using Element::setValue;
  385. bool setValue(const std::vector<ConstElementPtr>& v) {
  386. l = v;
  387. return (true);
  388. }
  389. using Element::get;
  390. ConstElementPtr get(int i) const { return (l.at(i)); }
  391. using Element::set;
  392. void set(size_t i, ConstElementPtr e) {
  393. l.at(i) = e;
  394. }
  395. void add(ConstElementPtr e) { l.push_back(e); };
  396. using Element::remove;
  397. void remove(int i) { l.erase(l.begin() + i); };
  398. void toJSON(std::ostream& ss) const;
  399. size_t size() const { return (l.size()); }
  400. bool equals(const Element& other) const;
  401. };
  402. class MapElement : public Element {
  403. std::map<std::string, ConstElementPtr> m;
  404. public:
  405. MapElement() : Element(map) {}
  406. // TODO: should we have direct iterators instead of exposing the std::map here?
  407. const std::map<std::string, ConstElementPtr>& mapValue() const {
  408. return (m);
  409. }
  410. using Element::getValue;
  411. bool getValue(std::map<std::string, ConstElementPtr>& t) const {
  412. t = m;
  413. return (true);
  414. }
  415. using Element::setValue;
  416. bool setValue(const std::map<std::string, ConstElementPtr>& v) {
  417. m = v;
  418. return (true);
  419. }
  420. using Element::get;
  421. ConstElementPtr get(const std::string& s) const {
  422. return (contains(s) ? m.find(s)->second : ConstElementPtr());
  423. }
  424. using Element::set;
  425. void set(const std::string& key, ConstElementPtr value);
  426. using Element::remove;
  427. void remove(const std::string& s) { m.erase(s); }
  428. bool contains(const std::string& s) const {
  429. return (m.find(s) != m.end());
  430. }
  431. void toJSON(std::ostream& ss) const;
  432. // we should name the two finds better...
  433. // find the element at id; raises TypeError if one of the
  434. // elements at path except the one we're looking for is not a
  435. // mapelement.
  436. // returns an empty element if the item could not be found
  437. ConstElementPtr find(const std::string& id) const;
  438. // find the Element at 'id', and store the element pointer in t
  439. // returns true if found, or false if not found (either because
  440. // it doesnt exist or one of the elements in the path is not
  441. // a MapElement)
  442. bool find(const std::string& id, ConstElementPtr& t) const;
  443. bool equals(const Element& other) const;
  444. };
  445. /// Checks whether the given ElementPtr is a NULL pointer
  446. /// \param p The ElementPtr to check
  447. /// \return true if it is NULL, false if not.
  448. bool isNull(ConstElementPtr p);
  449. ///
  450. /// \brief Remove all values from the first ElementPtr that are
  451. /// equal in the second. Both ElementPtrs MUST be MapElements
  452. /// The use for this function is to end up with a MapElement that
  453. /// only contains new and changed values (for ModuleCCSession and
  454. /// configuration update handlers)
  455. /// Raises a TypeError if a or b are not MapElements
  456. void removeIdentical(ElementPtr a, ConstElementPtr b);
  457. /// \brief Create a new ElementPtr from the first ElementPtr, removing all
  458. /// values that are equal in the second. Both ElementPtrs MUST be MapElements.
  459. /// The returned ElementPtr will be a MapElement that only contains new and
  460. /// changed values (for ModuleCCSession and configuration update handlers).
  461. /// Raises a TypeError if a or b are not MapElements
  462. ConstElementPtr removeIdentical(ConstElementPtr a, ConstElementPtr b);
  463. /// \brief Merges the data from other into element.
  464. /// (on the first level). Both elements must be
  465. /// MapElements.
  466. /// Every string,value pair in other is copied into element
  467. /// (the ElementPtr of value is copied, this is not a new object)
  468. /// Unless the value is a NullElement, in which case the
  469. /// key is removed from element, rather than setting the value to
  470. /// the given NullElement.
  471. /// This way, we can remove values from for instance maps with
  472. /// configuration data (which would then result in reverting back
  473. /// to the default).
  474. /// Raises a TypeError if either ElementPtr is not a MapElement
  475. void merge(ElementPtr element, ConstElementPtr other);
  476. ///
  477. /// \brief Insert the Element as a string into stream.
  478. ///
  479. /// This method converts the \c ElementPtr into a string with
  480. /// \c Element::str() and inserts it into the
  481. /// output stream \c out.
  482. ///
  483. /// This function overloads the global operator<< to behave as described in
  484. /// ostream::operator<< but applied to \c ElementPtr objects.
  485. ///
  486. /// \param out A \c std::ostream object on which the insertion operation is
  487. /// performed.
  488. /// \param e The \c ElementPtr object to insert.
  489. /// \return A reference to the same \c std::ostream object referenced by
  490. /// parameter \c out after the insertion operation.
  491. std::ostream& operator<<(std::ostream& out, const Element& e);
  492. bool operator==(const Element& a, const Element& b);
  493. bool operator!=(const Element& a, const Element& b);
  494. } }
  495. #endif // ISC_DATA_H
  496. // Local Variables:
  497. // mode: c++
  498. // End: