data.h 19 KB

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