data.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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 <dns/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. // todo: include types and called function in the exception
  33. class TypeError : public isc::dns::Exception {
  34. public:
  35. TypeError(const char* file, size_t line, const char* what) :
  36. isc::dns::Exception(file, line, what) {}
  37. };
  38. ///
  39. /// \brief A standard Data module exception that is thrown if a parse
  40. /// error is encountered when constructing an Element from a string
  41. ///
  42. // i'd like to use Exception here but we need one that is derived from
  43. // runtime_error (as this one is directly based on external data, and
  44. // i want to add some values to any static data string that is provided)
  45. class ParseError : public std::runtime_error {
  46. public:
  47. ParseError(const std::string &err) : std::runtime_error(err) {};
  48. };
  49. ///
  50. /// \brief A standard Data module exception that is thrown if an error
  51. /// is found when decoding an Element from wire format
  52. ///
  53. class DecodeError : public std::exception {
  54. public:
  55. DecodeError(std::string m = "Wire-format data is invalid") : msg(m) {}
  56. ~DecodeError() throw() {}
  57. const char* what() const throw() { return msg.c_str(); }
  58. private:
  59. std::string msg;
  60. };
  61. ///
  62. /// \brief The \c Element class represents a piece of data, used by
  63. /// the command channel and configuration parts.
  64. ///
  65. /// An \c Element can contain simple types (int, real, string, bool and
  66. /// None), and composite types (list and string->element maps)
  67. ///
  68. /// Elements should in calling functions usually be referenced through
  69. /// an \c ElementPtr, which can be created using the factory functions
  70. /// \c Element::create() and \c Element::createFromString()
  71. ///
  72. /// Notes to developers: Element is a base class, implemented by a
  73. /// specific subclass for each type (IntElement, BoolElement, etc).
  74. /// Element does define all functions for all types, and defaults to
  75. /// raising a \c TypeError for functions that are not supported for
  76. /// the type in question.
  77. ///
  78. class Element {
  79. private:
  80. // technically the type could be omitted; is it useful?
  81. // should we remove it or replace it with a pure virtual
  82. // function getType?
  83. int type;
  84. protected:
  85. Element(int t) { type = t; }
  86. public:
  87. // any is a special type used in list specifications, specifying
  88. // that the elements can be of any type
  89. enum types { integer, real, boolean, string, list, map, any };
  90. // base class; make dtor virtual
  91. virtual ~Element() {};
  92. /// \return the type of this element
  93. int getType() { return type; };
  94. // pure virtuals, every derived class must implement these
  95. /// Returns a string representing the Element and all its
  96. /// child elements; note that this is different from stringValue(),
  97. /// which only returns the single value of a StringElement
  98. /// A MapElement will be represented as { "name1": \<value1\>, "name2", \<value2\>, etc }
  99. /// A ListElement will be represented as [ \<item1\>, \<item2\>, etc ]
  100. /// All other elements will be represented directly
  101. ///
  102. /// \return std::string containing the string representation
  103. virtual std::string str() = 0;
  104. /// Returns the wireformat for the Element and all its child
  105. /// elements.
  106. ///
  107. /// \param omit_length If this is non-zero, the item length will
  108. /// be omitted from the wire format
  109. /// \return std::string containing the element in wire format
  110. std::string toWire(int omit_length = 1);
  111. virtual void toWire(std::stringstream& out, int omit_length = 1) = 0;
  112. /// \name Type-specific getters
  113. ///
  114. ///
  115. /// \brief These functions only
  116. /// work on their corresponding Element type. For all other
  117. /// types, a TypeError is thrown.
  118. /// If you want an exception-safe getter method, use
  119. /// getValue() below
  120. //@{
  121. virtual int intValue() { dns_throw(TypeError, "intValue() called on non-integer Element"); };
  122. virtual double doubleValue() { dns_throw(TypeError, "doubleValue() called on non-double Element"); };
  123. virtual bool boolValue() { dns_throw(TypeError, "boolValue() called on non-Bool Element"); };
  124. virtual std::string stringValue() { dns_throw(TypeError, "stringValue() called on non-string Element"); };
  125. virtual const std::vector<boost::shared_ptr<Element> >& listValue() { dns_throw(TypeError, "listValue() called on non-list Element"); }; // replace with real exception or empty vector?
  126. virtual const std::map<std::string, boost::shared_ptr<Element> >& mapValue() { dns_throw(TypeError, "mapValue() called on non-map Element"); }; // replace with real exception or empty map?
  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(int& t) { return false; };
  138. virtual bool getValue(double& t) { return false; };
  139. virtual bool getValue(bool& t) { return false; };
  140. virtual bool getValue(std::string& t) { return false; };
  141. virtual bool getValue(std::vector<ElementPtr>& t) { return false; };
  142. virtual bool getValue(std::map<std::string, ElementPtr>& t) { return false; };
  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 int v) { return false; };
  153. virtual bool setValue(const double v) { return false; };
  154. virtual bool setValue(const bool t) { return false; };
  155. virtual bool setValue(const std::string& v) { return false; };
  156. virtual bool setValue(const std::vector<ElementPtr>& v) { return false; };
  157. virtual bool setValue(const std::map<std::string, ElementPtr>& v) { return false; };
  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 ElementPtr get(const int i) { dns_throw(TypeError, "get(int) called on a non-list Element"); };
  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, ElementPtr element) { dns_throw(TypeError, "set(int, element) called on a non-list Element"); };
  174. /// Adds an ElementPtr to the list
  175. /// \param element The ElementPtr to add
  176. virtual void add(ElementPtr element) { dns_throw(TypeError, "add() called on a non-list 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) { dns_throw(TypeError, "remove(int) called on a non-list Element"); };
  181. /// Returns the number of elements in the list.
  182. virtual size_t size() { dns_throw(TypeError, "size() called on a non-list Element"); };
  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 ElementPtr get(const std::string& name) { dns_throw(TypeError, "get(string) called on a non-map Element"); } ;
  193. /// Sets the ElementPtr at the given key
  194. /// \param name The key of the Element to set
  195. virtual void set(const std::string& name, ElementPtr element) { dns_throw(TypeError, "set(name, element) called on a non-map Element"); };
  196. /// Remove the ElementPtr at the given key
  197. /// \param name The key of the Element to remove
  198. virtual void remove(const std::string& name) { dns_throw(TypeError, "remove(string) called on a non-map Element"); };
  199. /// Checks if there is data at the given key
  200. /// \param name The key of the Element to remove
  201. /// \return true if there is data at the key, false if not.
  202. virtual bool contains(const std::string& name) { dns_throw(TypeError, "contains(string) called on a non-map Element"); }
  203. /// Recursively finds any data at the given identifier. The
  204. /// identifier is a /-separated list of names of nested maps, with
  205. /// the last name being the leaf that is returned.
  206. ///
  207. /// For instance, if you have a MapElement that contains another
  208. /// MapElement at the key "foo", and that second MapElement contains
  209. /// Another Element at key "bar", the identifier for that last
  210. /// element from the first is "foo/bar".
  211. ///
  212. /// \param identifier The identifier of the element to find
  213. /// \return The ElementPtr at the given identifier. Returns a
  214. /// null ElementPtr if it is not found, which can be checked with
  215. /// Element::is_null(ElementPtr e).
  216. virtual ElementPtr find(const std::string& identifier) { dns_throw(TypeError, "find(string) called on a non-map Element"); };
  217. /// See \c Element::find()
  218. /// \param identifier The identifier of the element to find
  219. /// \param t Reference to store the resulting ElementPtr, if found.
  220. /// \return true if the element was found, false if not.
  221. virtual bool find(const std::string& identifier, ElementPtr& t) { return false; };
  222. //@}
  223. /// \name Factory functions
  224. // TODO: should we move all factory functions to a different class
  225. // so as not to burden the Element base with too many functions?
  226. // and/or perhaps even to a separate header?
  227. /// \name Direct factory functions
  228. /// \brief These functions simply wrap the given data directly
  229. /// in an Element object, and return a reference to it, in the form
  230. /// of an \c ElementPtr.
  231. /// If there is a memory allocation problem, these functions will
  232. /// return a NULL ElementPtr, which can be checked with
  233. /// Element::is_null(ElementPtr ep).
  234. //@{
  235. static ElementPtr create(const int i);
  236. static ElementPtr create(const double d);
  237. static ElementPtr create(const bool b);
  238. static ElementPtr create(const std::string& s);
  239. // need both std:string and char *, since c++ will match
  240. // bool before std::string when you pass it a char *
  241. static ElementPtr create(const char *s) { return create(std::string(s)); };
  242. static ElementPtr create(const std::vector<ElementPtr>& v);
  243. static ElementPtr create(const std::map<std::string, ElementPtr>& m);
  244. //@}
  245. /// \name Compound factory functions
  246. /// \brief These functions will parse the given string representation
  247. /// of a compound element. If there is a parse error, an exception
  248. /// of the type isc::data::ParseError is thrown.
  249. //@{
  250. /// Creates an Element from the given string
  251. /// \param in The string to parse the element from
  252. /// \return An ElementPtr that contains the element(s) specified
  253. /// in the given string.
  254. static ElementPtr createFromString(const std::string& in);
  255. /// Creates an Element from the given input stream
  256. /// \param in The string to parse the element from
  257. /// \return An ElementPtr that contains the element(s) specified
  258. /// in the given input stream.
  259. static ElementPtr createFromString(std::istream& in) throw(ParseError);
  260. static ElementPtr createFromString(std::istream& in, const std::string& file_name) throw(ParseError);
  261. /// Creates an Element from the given input stream, where we keep
  262. /// track of the location in the stream for error reporting.
  263. ///
  264. /// \param in The string to parse the element from
  265. /// \param line A reference to the int where the function keeps
  266. /// track of the current line.
  267. /// \param line A reference to the int where the function keeps
  268. /// track of the current position within the current line.
  269. /// \return An ElementPtr that contains the element(s) specified
  270. /// in the given input stream.
  271. // make this one private?
  272. static ElementPtr createFromString(std::istream& in, const std::string& file, int& line, int &pos) throw(ParseError);
  273. //@}
  274. /// \name Wire format factory functions
  275. /// These function pparse the wireformat at the given stringstream
  276. /// (of the given length). If there is a parse error an exception
  277. /// of the type isc::cc::DecodeError is raised.
  278. //@{
  279. /// Creates an Element from the wire format in the given
  280. /// stringstream of the given length.
  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. /// \param s The input string
  287. /// \return ElementPtr with the data that is parsed.
  288. static ElementPtr fromWire(const std::string& s);
  289. //@}
  290. };
  291. class IntElement : public Element {
  292. int i;
  293. public:
  294. IntElement(int v) : Element(integer), i(v) { };
  295. int intValue() { return i; }
  296. bool getValue(int& t) { t = i; return true; };
  297. bool setValue(const int v) { i = v; return true; };
  298. std::string str();
  299. void toWire(std::stringstream& ss, int omit_length = 1);
  300. };
  301. class DoubleElement : public Element {
  302. double d;
  303. public:
  304. DoubleElement(double v) : Element(real), d(v) {};
  305. double doubleValue() { return d; }
  306. bool getValue(double& t) { t = d; return true; };
  307. bool setValue(const double v) { d = v; return true; };
  308. std::string str();
  309. void toWire(std::stringstream& ss, int omit_length = 1);
  310. };
  311. class BoolElement : public Element {
  312. bool b;
  313. public:
  314. BoolElement(const bool v) : Element(boolean), b(v) {};
  315. bool boolValue() { return b; }
  316. bool getValue(bool& t) { t = b; return true; };
  317. bool setValue(const bool v) { b = v; return true; };
  318. std::string str();
  319. void toWire(std::stringstream& ss, int omit_length = 1);
  320. };
  321. class StringElement : public Element {
  322. std::string s;
  323. public:
  324. StringElement(std::string v) : Element(string), s(v) {};
  325. std::string stringValue() { return s; };
  326. bool getValue(std::string& t) { t = s; return true; };
  327. bool setValue(const std::string& v) { s = v; return true; };
  328. std::string str();
  329. void toWire(std::stringstream& ss, int omit_length = 1);
  330. };
  331. class ListElement : public Element {
  332. std::vector<ElementPtr> l;
  333. public:
  334. ListElement(std::vector<ElementPtr> v) : Element(list), l(v) {};
  335. const std::vector<ElementPtr>& listValue() { return l; }
  336. bool getValue(std::vector<ElementPtr>& t) { t = l; return true; };
  337. bool setValue(const std::vector<ElementPtr>& v) { l = v; return true; };
  338. ElementPtr get(int i) { return l.at(i); };
  339. void set(size_t i, ElementPtr e) { if (i <= l.size()) {l[i] = e;} else { throw std::out_of_range("vector::_M_range_check"); } };
  340. void add(ElementPtr e) { l.push_back(e); };
  341. void remove(int i) { l.erase(l.begin() + i); };
  342. std::string str();
  343. void toWire(std::stringstream& ss, int omit_length = 1);
  344. size_t size() { return l.size(); }
  345. };
  346. class MapElement : public Element {
  347. std::map<std::string, ElementPtr> m;
  348. public:
  349. MapElement(std::map<std::string, ElementPtr> v) : Element(map), m(v) {};
  350. const std::map<std::string, ElementPtr>& mapValue() { return m; }
  351. bool getValue(std::map<std::string, ElementPtr>& t) { t = m; return true; };
  352. bool setValue(std::map<std::string, ElementPtr>& v) { m = v; return true; };
  353. ElementPtr get(const std::string& s) { return m[s]; };
  354. void set(const std::string& s, ElementPtr p) { m[s] = p; };
  355. void remove(const std::string& s) { m.erase(s); }
  356. bool contains(const std::string& s) { return m.find(s) != m.end(); }
  357. std::string str();
  358. void toWire(std::stringstream& ss, int omit_length = 1);
  359. //
  360. // Encode into the CC wire format.
  361. //
  362. void toWire(std::ostream& ss);
  363. // we should name the two finds better...
  364. // find the element at id; raises TypeError if one of the
  365. // elements at path except the one we're looking for is not a
  366. // mapelement.
  367. // returns an empty element if the item could not be found
  368. ElementPtr find(const std::string& id);
  369. // find the Element at 'id', and store the element pointer in t
  370. // returns true if found, or false if not found (either because
  371. // it doesnt exist or one of the elements in the path is not
  372. // a MapElement)
  373. bool find(const std::string& id, ElementPtr& t);
  374. };
  375. /// Checks whether the given ElementPtr is a NULL pointer
  376. /// \param p The ElementPtr to check
  377. /// \return true if it is NULL, false if not.
  378. bool isNull(ElementPtr p);
  379. } }
  380. ///
  381. /// \brief Insert the Element as a string into stream.
  382. ///
  383. /// This method converts the \c ElemetPtr into a string with
  384. /// \c Element::str() and inserts it into the
  385. /// output stream \c out.
  386. ///
  387. /// This function overloads the global operator<< to behave as described in
  388. /// ostream::operator<< but applied to \c ElementPtr objects.
  389. ///
  390. /// \param os A \c std::ostream object on which the insertion operation is
  391. /// performed.
  392. /// \param e The \c ElementPtr object to insert.
  393. /// \return A reference to the same \c std::ostream object referenced by
  394. /// parameter \c os after the insertion operation.
  395. std::ostream& operator <<(std::ostream &out, const isc::data::ElementPtr& e);
  396. #endif // _ISC_DATA_H