data.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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 ParseError : public std::runtime_error {
  45. public:
  46. ParseError(const std::string &err) : std::runtime_error(err) {};
  47. };
  48. ///
  49. /// \brief A standard Data module exception that is thrown if an error
  50. /// is found when decoding an Element from wire format
  51. ///
  52. class DecodeError : public std::exception {
  53. public:
  54. DecodeError(std::string m = "Wire-format data is invalid") : msg(m) {}
  55. ~DecodeError() throw() {}
  56. const char* what() const throw() { return msg.c_str(); }
  57. private:
  58. std::string msg;
  59. };
  60. ///
  61. /// \brief The \c Element class represents a piece of data, used by
  62. /// the command channel and configuration parts.
  63. ///
  64. /// An \c Element can contain simple types (int, real, string, bool and
  65. /// None), and composite types (list and string->element maps)
  66. ///
  67. /// Elements should in calling functions usually be referenced through
  68. /// an \c ElementPtr, which can be created using the factory functions
  69. /// \c Element::create() and \c Element::createFromString()
  70. ///
  71. /// Notes to developers: Element is a base class, implemented by a
  72. /// specific subclass for each type (IntElement, BoolElement, etc).
  73. /// Element does define all functions for all types, and defaults to
  74. /// raising a \c TypeError for functions that are not supported for
  75. /// the type in question.
  76. ///
  77. class Element {
  78. private:
  79. // technically the type could be omitted; is it useful?
  80. // should we remove it or replace it with a pure virtual
  81. // function getType?
  82. int type;
  83. protected:
  84. Element(int t) { type = t; }
  85. public:
  86. // any is a special type used in list specifications, specifying
  87. // that the elements can be of any type
  88. enum types { integer, real, boolean, string, list, map, any };
  89. // base class; make dtor virtual
  90. virtual ~Element() {};
  91. /// \return the type of this element
  92. int getType() { return type; };
  93. /// \returns true if the other ElementPtr has the same type and
  94. /// value
  95. virtual bool equals(ElementPtr other) = 0;
  96. // pure virtuals, every derived class must implement these
  97. /// Returns a string representing the Element and all its
  98. /// child elements; note that this is different from stringValue(),
  99. /// which only returns the single value of a StringElement
  100. /// A MapElement will be represented as { "name1": \<value1\>, "name2", \<value2\>, etc }
  101. /// A ListElement will be represented as [ \<item1\>, \<item2\>, etc ]
  102. /// All other elements will be represented directly
  103. ///
  104. /// \return std::string containing the string representation
  105. virtual std::string str() = 0;
  106. /// Returns the wireformat for the Element and all its child
  107. /// elements.
  108. ///
  109. /// \param omit_length If this is non-zero, the item length will
  110. /// be omitted from the wire format
  111. /// \return std::string containing the element in wire format
  112. std::string toWire(int omit_length = 1);
  113. virtual void toWire(std::stringstream& out, int omit_length = 1) = 0;
  114. /// \name Type-specific getters
  115. ///
  116. ///
  117. /// \brief These functions only
  118. /// work on their corresponding Element type. For all other
  119. /// types, a TypeError is thrown.
  120. /// If you want an exception-safe getter method, use
  121. /// getValue() below
  122. //@{
  123. virtual int intValue() { isc_throw(TypeError, "intValue() called on non-integer Element"); };
  124. virtual double doubleValue() { isc_throw(TypeError, "doubleValue() called on non-double Element"); };
  125. virtual bool boolValue() { isc_throw(TypeError, "boolValue() called on non-Bool Element"); };
  126. virtual std::string stringValue() { isc_throw(TypeError, "stringValue() called on non-string Element"); };
  127. 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?
  128. 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?
  129. //@}
  130. /// \name Exception-safe getters
  131. ///
  132. /// \brief The getValue() functions return false if the given reference
  133. /// is of another type than the element contains
  134. /// By default it always returns false; the derived classes
  135. /// override the function for their type, copying their
  136. /// data to the given reference and returning true
  137. ///
  138. //@{
  139. virtual bool getValue(int& t);
  140. virtual bool getValue(double& t);
  141. virtual bool getValue(bool& t);
  142. virtual bool getValue(std::string& t);
  143. virtual bool getValue(std::vector<ElementPtr>& t);
  144. virtual bool getValue(std::map<std::string, ElementPtr>& t);
  145. //@}
  146. ///
  147. /// \name Exception-safe setters.
  148. ///
  149. /// \brief Return false if the Element is not
  150. /// the right type. Set the value and return true if the Elements
  151. /// is of the correct type
  152. ///
  153. //@{
  154. virtual bool setValue(const int v);
  155. virtual bool setValue(const double v);
  156. virtual bool setValue(const bool t);
  157. virtual bool setValue(const std::string& v);
  158. virtual bool setValue(const std::vector<ElementPtr>& v);
  159. virtual bool setValue(const std::map<std::string, ElementPtr>& v);
  160. //@}
  161. // Other functions for specific subtypes
  162. /// \name ListElement functions
  163. ///
  164. /// \brief If the Element on which these functions are called are not
  165. /// an instance of ListElement, a TypeError exception is thrown.
  166. //@{
  167. /// Returns the ElementPtr at the given index. If the index is out
  168. /// of bounds, this function throws an std::out_of_range exception.
  169. /// \param i The position of the ElementPtr to return
  170. virtual ElementPtr get(const int i);
  171. /// Sets the ElementPtr at the given index. If the index is out
  172. /// of bounds, this function throws an std::out_of_range exception.
  173. /// \param i The position of the ElementPtr to set
  174. /// \param element The ElementPtr to set at the position
  175. virtual void set(const size_t i, ElementPtr element);
  176. /// Adds an ElementPtr to the list
  177. /// \param element The ElementPtr to add
  178. virtual void add(ElementPtr element);
  179. /// Removes the element at the given position. If the index is out
  180. /// of nothing happens.
  181. /// \param i The index of the element to remove.
  182. virtual void remove(const int i);
  183. /// Returns the number of elements in the list.
  184. virtual size_t size();
  185. //@}
  186. /// \name MapElement functions
  187. ///
  188. /// \brief If the Element on which these functions are called are not
  189. /// an instance of MapElement, a TypeError exception is thrown.
  190. //@{
  191. /// Returns the ElementPtr at the given key
  192. /// \param name The key of the Element to return
  193. /// \return The ElementPtr at the given key
  194. virtual ElementPtr get(const std::string& name);
  195. /// Sets the ElementPtr at the given key
  196. /// \param name The key of the Element to set
  197. virtual void set(const std::string& name, ElementPtr element);
  198. /// Remove the ElementPtr at the given key
  199. /// \param name The key of the Element to remove
  200. virtual void remove(const std::string& name);
  201. /// Checks if there is data at the given key
  202. /// \param name The key of the Element to remove
  203. /// \return true if there is data at the key, false if not.
  204. virtual bool contains(const std::string& name);
  205. /// Recursively finds any data at the given identifier. The
  206. /// identifier is a /-separated list of names of nested maps, with
  207. /// the last name being the leaf that is returned.
  208. ///
  209. /// For instance, if you have a MapElement that contains another
  210. /// MapElement at the key "foo", and that second MapElement contains
  211. /// Another Element at key "bar", the identifier for that last
  212. /// element from the first is "foo/bar".
  213. ///
  214. /// \param identifier The identifier of the element to find
  215. /// \return The ElementPtr at the given identifier. Returns a
  216. /// null ElementPtr if it is not found, which can be checked with
  217. /// Element::is_null(ElementPtr e).
  218. virtual ElementPtr find(const std::string& identifier);
  219. /// See \c Element::find()
  220. /// \param identifier The identifier of the element to find
  221. /// \param t Reference to store the resulting ElementPtr, if found.
  222. /// \return true if the element was found, false if not.
  223. virtual bool find(const std::string& identifier, ElementPtr& t);
  224. //@}
  225. /// \name Factory functions
  226. // TODO: should we move all factory functions to a different class
  227. // so as not to burden the Element base with too many functions?
  228. // and/or perhaps even to a separate header?
  229. /// \name Direct factory functions
  230. /// \brief These functions simply wrap the given data directly
  231. /// in an Element object, and return a reference to it, in the form
  232. /// of an \c ElementPtr.
  233. /// If there is a memory allocation problem, these functions will
  234. /// return a NULL ElementPtr, which can be checked with
  235. /// Element::is_null(ElementPtr ep).
  236. //@{
  237. static ElementPtr create(const int i);
  238. static ElementPtr create(const double d);
  239. static ElementPtr create(const bool b);
  240. static ElementPtr create(const std::string& s);
  241. // need both std:string and char *, since c++ will match
  242. // bool before std::string when you pass it a char *
  243. static ElementPtr create(const char *s) { return create(std::string(s)); };
  244. static ElementPtr create(const std::vector<ElementPtr>& v);
  245. static ElementPtr create(const std::map<std::string, ElementPtr>& m);
  246. //@}
  247. /// \name Compound factory functions
  248. /// \brief These functions will parse the given string representation
  249. /// of a compound element. If there is a parse error, an exception
  250. /// of the type isc::data::ParseError is thrown.
  251. //@{
  252. /// Creates an Element from the given string
  253. /// \param in The string to parse the element from
  254. /// \return An ElementPtr that contains the element(s) specified
  255. /// in the given string.
  256. static ElementPtr createFromString(const std::string& in);
  257. /// Creates an Element from the given input stream
  258. /// \param in The string to parse the element from
  259. /// \return An ElementPtr that contains the element(s) specified
  260. /// in the given input stream.
  261. static ElementPtr createFromString(std::istream& in) throw(ParseError);
  262. static ElementPtr createFromString(std::istream& in, const std::string& file_name) throw(ParseError);
  263. /// Creates an Element from the given input stream, where we keep
  264. /// track of the location in the stream for error reporting.
  265. ///
  266. /// \param in The string to parse the element from
  267. /// \param line A reference to the int where the function keeps
  268. /// track of the current line.
  269. /// \param line A reference to the int where the function keeps
  270. /// track of the current position within the current line.
  271. /// \return An ElementPtr that contains the element(s) specified
  272. /// in the given input stream.
  273. // make this one private?
  274. static ElementPtr createFromString(std::istream& in, const std::string& file, int& line, int &pos) throw(ParseError);
  275. //@}
  276. /// \name Wire format factory functions
  277. /// These function pparse the wireformat at the given stringstream
  278. /// (of the given length). If there is a parse error an exception
  279. /// of the type isc::cc::DecodeError is raised.
  280. //@{
  281. /// Creates an Element from the wire format in the given
  282. /// stringstream of the given length.
  283. /// \param in The input stringstream.
  284. /// \param length The length of the wireformat data in the stream
  285. /// \return ElementPtr with the data that is parsed.
  286. static ElementPtr fromWire(std::stringstream& in, int length);
  287. /// Creates an Element from the wire format in the given string
  288. /// \param s The input string
  289. /// \return ElementPtr with the data that is parsed.
  290. static ElementPtr fromWire(const std::string& s);
  291. //@}
  292. };
  293. class IntElement : public Element {
  294. int i;
  295. public:
  296. IntElement(int v) : Element(integer), i(v) { };
  297. int intValue() { return i; }
  298. using Element::getValue;
  299. bool getValue(int& t) { t = i; return true; };
  300. using Element::setValue;
  301. bool setValue(const int v) { i = v; return true; };
  302. std::string str();
  303. void toWire(std::stringstream& ss, int omit_length = 1);
  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. std::string str();
  316. void toWire(std::stringstream& ss, int omit_length = 1);
  317. bool equals(ElementPtr other);
  318. };
  319. class BoolElement : public Element {
  320. bool b;
  321. public:
  322. BoolElement(const bool v) : Element(boolean), b(v) {};
  323. bool boolValue() { return b; }
  324. using Element::getValue;
  325. bool getValue(bool& t) { t = b; return true; };
  326. using Element::setValue;
  327. bool setValue(const bool v) { b = v; return true; };
  328. std::string str();
  329. void toWire(std::stringstream& ss, int omit_length = 1);
  330. bool equals(ElementPtr other);
  331. };
  332. class StringElement : public Element {
  333. std::string s;
  334. public:
  335. StringElement(std::string v) : Element(string), s(v) {};
  336. std::string stringValue() { return s; };
  337. using Element::getValue;
  338. bool getValue(std::string& t) { t = s; return true; };
  339. using Element::setValue;
  340. bool setValue(const std::string& v) { s = v; return true; };
  341. std::string str();
  342. void toWire(std::stringstream& ss, int omit_length = 1);
  343. bool equals(ElementPtr other);
  344. };
  345. class ListElement : public Element {
  346. std::vector<ElementPtr> l;
  347. public:
  348. ListElement(std::vector<ElementPtr> v) : Element(list), l(v) {};
  349. const std::vector<ElementPtr>& listValue() { return l; }
  350. using Element::getValue;
  351. bool getValue(std::vector<ElementPtr>& t) { t = l; return true; };
  352. using Element::setValue;
  353. bool setValue(const std::vector<ElementPtr>& v) { l = v; return true; };
  354. using Element::get;
  355. ElementPtr get(int i) { return l.at(i); };
  356. using Element::set;
  357. void set(size_t i, ElementPtr e) { if (i <= l.size()) {l[i] = e;} else { throw std::out_of_range("vector::_M_range_check"); } };
  358. void add(ElementPtr e) { l.push_back(e); };
  359. using Element::remove;
  360. void remove(int i) { l.erase(l.begin() + i); };
  361. std::string str();
  362. void toWire(std::stringstream& ss, int omit_length = 1);
  363. size_t size() { return l.size(); }
  364. bool equals(ElementPtr other);
  365. };
  366. class MapElement : public Element {
  367. std::map<std::string, ElementPtr> m;
  368. public:
  369. MapElement(std::map<std::string, ElementPtr> v) : Element(map), m(v) {};
  370. const std::map<std::string, ElementPtr>& mapValue() { return m; }
  371. using Element::getValue;
  372. bool getValue(std::map<std::string, ElementPtr>& t) { t = m; return true; };
  373. using Element::setValue;
  374. bool setValue(std::map<std::string, ElementPtr>& v) { m = v; return true; };
  375. using Element::get;
  376. ElementPtr get(const std::string& s) { if (contains(s)) { return m[s]; } else { return ElementPtr();} };
  377. using Element::set;
  378. void set(const std::string& s, ElementPtr p) { m[s] = p; };
  379. using Element::remove;
  380. void remove(const std::string& s) { m.erase(s); }
  381. bool contains(const std::string& s) { return m.find(s) != m.end(); }
  382. std::string str();
  383. void toWire(std::stringstream& ss, int omit_length = 1);
  384. //
  385. // Encode into the CC wire format.
  386. //
  387. void toWire(std::ostream& ss);
  388. // we should name the two finds better...
  389. // find the element at id; raises TypeError if one of the
  390. // elements at path except the one we're looking for is not a
  391. // mapelement.
  392. // returns an empty element if the item could not be found
  393. ElementPtr find(const std::string& id);
  394. // find the Element at 'id', and store the element pointer in t
  395. // returns true if found, or false if not found (either because
  396. // it doesnt exist or one of the elements in the path is not
  397. // a MapElement)
  398. bool find(const std::string& id, ElementPtr& t);
  399. bool equals(ElementPtr other);
  400. };
  401. /// Checks whether the given ElementPtr is a NULL pointer
  402. /// \param p The ElementPtr to check
  403. /// \return true if it is NULL, false if not.
  404. bool isNull(ElementPtr p);
  405. ///
  406. /// \brief Remove all values from the first ElementPtr that are
  407. /// equal in the second. Both ElementPtrs MUST be MapElements
  408. /// The use for this function is to end up with a MapElement that
  409. /// only contains new and changed values (for ModuleCCSession and
  410. /// configuration update handlers)
  411. /// Raises a TypeError if a or b are not MapElements
  412. void removeIdentical(ElementPtr a, const ElementPtr b);
  413. /// \brief Merges the data from other into element.
  414. /// (on the first level). Both elements must be
  415. /// MapElements.
  416. /// Every string,value pair in other is copied into element
  417. /// (the ElementPtr of value is copied, this is not a new object)
  418. /// Unless the value is an empty ElementPtr, in which case the
  419. /// whole key is removed from element.
  420. /// Raises a TypeError if either ElementPtr is not a MapElement
  421. void merge(ElementPtr element, const ElementPtr other);
  422. ///
  423. /// \brief Insert the Element as a string into stream.
  424. ///
  425. /// This method converts the \c ElemetPtr into a string with
  426. /// \c Element::str() and inserts it into the
  427. /// output stream \c out.
  428. ///
  429. /// This function overloads the global operator<< to behave as described in
  430. /// ostream::operator<< but applied to \c ElementPtr objects.
  431. ///
  432. /// \param os A \c std::ostream object on which the insertion operation is
  433. /// performed.
  434. /// \param e The \c ElementPtr object to insert.
  435. /// \return A reference to the same \c std::ostream object referenced by
  436. /// parameter \c os after the insertion operation.
  437. std::ostream& operator <<(std::ostream &out, const isc::data::ElementPtr& e);
  438. bool operator==(const isc::data::ElementPtr a, const isc::data::ElementPtr b);
  439. } }
  440. #endif // _ISC_DATA_H
  441. // Local Variables:
  442. // mode: c++
  443. // End: