data.h 18 KB

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