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. // $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. typedef boost::shared_ptr<const Element> ConstElementPtr;
  28. ///
  29. /// \brief A standard Data module exception that is thrown if a function
  30. /// is called for an Element that has a wrong type (e.g. int_value on a
  31. /// ListElement)
  32. ///
  33. class TypeError : public isc::Exception {
  34. public:
  35. TypeError(const char* file, size_t line, const char* what) :
  36. isc::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 JSONError : public isc::Exception {
  46. public:
  47. JSONError(const char* file, size_t line, const char* what) :
  48. isc::Exception(file, line, what) {}
  49. };
  50. ///
  51. /// \brief The \c Element class represents a piece of data, used by
  52. /// the command channel and configuration parts.
  53. ///
  54. /// An \c Element can contain simple types (int, real, string, bool and
  55. /// None), and composite types (list and string->element maps)
  56. ///
  57. /// Elements should in calling functions usually be referenced through
  58. /// an \c ElementPtr, which can be created using the factory functions
  59. /// \c Element::create() and \c Element::fromJSON()
  60. ///
  61. /// Notes to developers: Element is a base class, implemented by a
  62. /// specific subclass for each type (IntElement, BoolElement, etc).
  63. /// Element does define all functions for all types, and defaults to
  64. /// raising a \c TypeError for functions that are not supported for
  65. /// the type in question.
  66. ///
  67. class Element {
  68. private:
  69. // technically the type could be omitted; is it useful?
  70. // should we remove it or replace it with a pure virtual
  71. // function getType?
  72. int type;
  73. protected:
  74. Element(int t) { type = t; }
  75. public:
  76. // any is a special type used in list specifications, specifying
  77. // that the elements can be of any type
  78. enum types { integer, real, boolean, null, string, list, map, any };
  79. // base class; make dtor virtual
  80. virtual ~Element() {};
  81. /// \return the type of this element
  82. int getType() const { return (type); }
  83. /// Returns a string representing the Element and all its
  84. /// child elements; note that this is different from stringValue(),
  85. /// which only returns the single value of a StringElement
  86. ///
  87. /// The resulting string will contain the Element in JSON format.
  88. ///
  89. /// \return std::string containing the string representation
  90. std::string str() const;
  91. /// Returns the wireformat for the Element and all its child
  92. /// elements.
  93. ///
  94. /// \return std::string containing the element in wire format
  95. std::string toWire() const;
  96. void toWire(std::ostream& out) const;
  97. /// \name pure virtuals, every derived class must implement these
  98. /// \returns true if the other ElementPtr has the same type and
  99. /// value
  100. virtual bool equals(const Element& other) const = 0;
  101. /// Converts the Element to JSON format and appends it to
  102. /// the given stringstream.
  103. virtual void toJSON(std::ostream& ss) const = 0;
  104. /// \name Type-specific getters
  105. ///
  106. /// \brief These functions only
  107. /// work on their corresponding Element type. For all other
  108. /// types, a TypeError is thrown.
  109. /// If you want an exception-safe getter method, use
  110. /// getValue() below
  111. //@{
  112. virtual long int intValue() const
  113. { isc_throw(TypeError, "intValue() called on non-integer Element"); };
  114. virtual double doubleValue() const
  115. { isc_throw(TypeError, "doubleValue() called on non-double Element"); };
  116. virtual bool boolValue() const
  117. { isc_throw(TypeError, "boolValue() called on non-Bool Element"); };
  118. virtual std::string stringValue() const
  119. { isc_throw(TypeError, "stringValue() called on non-string Element"); };
  120. virtual const std::vector<ConstElementPtr>& listValue() const {
  121. // replace with real exception or empty vector?
  122. isc_throw(TypeError, "listValue() called on non-list Element");
  123. };
  124. virtual const std::map<std::string, ConstElementPtr>& mapValue() const {
  125. // replace with real exception or empty map?
  126. isc_throw(TypeError, "mapValue() called on non-map Element");
  127. };
  128. //@}
  129. /// \name Exception-safe getters
  130. ///
  131. /// \brief The getValue() functions return false if the given reference
  132. /// is of another type than the element contains
  133. /// By default it always returns false; the derived classes
  134. /// override the function for their type, copying their
  135. /// data to the given reference and returning true
  136. ///
  137. //@{
  138. virtual bool getValue(long int& t);
  139. virtual bool getValue(double& t);
  140. virtual bool getValue(bool& t);
  141. virtual bool getValue(std::string& t);
  142. virtual bool getValue(std::vector<ConstElementPtr>& t);
  143. virtual bool getValue(std::map<std::string, ConstElementPtr>& t);
  144. //@}
  145. ///
  146. /// \name Exception-safe setters.
  147. ///
  148. /// \brief Return false if the Element is not
  149. /// the right type. Set the value and return true if the Elements
  150. /// is of the correct type
  151. ///
  152. //@{
  153. virtual bool setValue(const long int v);
  154. virtual bool setValue(const double v);
  155. virtual bool setValue(const bool t);
  156. virtual bool setValue(const std::string& v);
  157. virtual bool setValue(const std::vector<ConstElementPtr>& v);
  158. virtual bool setValue(const std::map<std::string, ConstElementPtr>& v);
  159. //@}
  160. // Other functions for specific subtypes
  161. /// \name ListElement functions
  162. ///
  163. /// \brief If the Element on which these functions are called are not
  164. /// an instance of ListElement, a TypeError exception is thrown.
  165. //@{
  166. /// Returns the ElementPtr at the given index. If the index is out
  167. /// of bounds, this function throws an std::out_of_range exception.
  168. /// \param i The position of the ElementPtr to return
  169. virtual ConstElementPtr get(const int i) const;
  170. /// Sets the ElementPtr at the given index. If the index is out
  171. /// of bounds, this function throws an std::out_of_range exception.
  172. /// \param i The position of the ElementPtr to set
  173. /// \param element The ElementPtr to set at the position
  174. virtual void set(const size_t i, ConstElementPtr element);
  175. /// Adds an ElementPtr to the list
  176. /// \param element The ElementPtr to add
  177. virtual void add(ConstElementPtr element);
  178. /// Removes the element at the given position. If the index is out
  179. /// of nothing happens.
  180. /// \param i The index of the element to remove.
  181. virtual void remove(const int i);
  182. /// Returns the number of elements in the list.
  183. virtual size_t size() const;
  184. //@}
  185. /// \name MapElement functions
  186. ///
  187. /// \brief If the Element on which these functions are called are not
  188. /// an instance of MapElement, a TypeError exception is thrown.
  189. //@{
  190. /// Returns the ElementPtr at the given key
  191. /// \param name The key of the Element to return
  192. /// \return The ElementPtr at the given key
  193. virtual ConstElementPtr get(const std::string& name) const;
  194. /// Sets the ElementPtr at the given key
  195. /// \param name The key of the Element to set
  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 line A reference to the int where the function keeps
  275. /// track of the current line.
  276. /// \param line A reference to the int where the function keeps
  277. /// track of the current position within the current line.
  278. /// \return An ElementPtr that contains the element(s) specified
  279. /// in the given input stream.
  280. // make this one private?
  281. static ElementPtr fromJSON(std::istream& in, const std::string& file, int& line, int &pos) throw(JSONError);
  282. //@}
  283. /// \name Type name conversion functions
  284. /// Returns the name of the given type as a string
  285. ///
  286. /// \param type The type to return the name of
  287. /// \return The name of the type, or "unknown" if the type
  288. /// is not known.
  289. static std::string typeToName(Element::types type);
  290. /// Converts the string to the corresponding type
  291. /// Throws a TypeError if the name is unknown.
  292. ///
  293. /// \param type_name The name to get the type of
  294. /// \return the corresponding type value
  295. static Element::types nameToType(const std::string& type_name);
  296. /// \name Wire format factory functions
  297. /// These function pparse the wireformat at the given stringstream
  298. /// (of the given length). If there is a parse error an exception
  299. /// of the type isc::cc::DecodeError is raised.
  300. //@{
  301. /// Creates an Element from the wire format in the given
  302. /// stringstream of the given length.
  303. /// Since the wire format is JSON, thise is the same as
  304. /// fromJSON, and could be removed.
  305. ///
  306. /// \param in The input stringstream.
  307. /// \param length The length of the wireformat data in the stream
  308. /// \return ElementPtr with the data that is parsed.
  309. static ElementPtr fromWire(std::stringstream& in, int length);
  310. /// Creates an Element from the wire format in the given string
  311. /// Since the wire format is JSON, thise is the same as
  312. /// fromJSON, and could be removed.
  313. ///
  314. /// \param s The input string
  315. /// \return ElementPtr with the data that is parsed.
  316. static ElementPtr fromWire(const std::string& s);
  317. //@}
  318. };
  319. class IntElement : public Element {
  320. long int i;
  321. public:
  322. IntElement(long int v) : Element(integer), i(v) { }
  323. long int intValue() const { return (i); }
  324. using Element::getValue;
  325. bool getValue(long int& t) { t = i; return (true); }
  326. using Element::setValue;
  327. bool setValue(const long int v) { i = v; return (true); }
  328. void toJSON(std::ostream& ss) const;
  329. bool equals(const Element& other) const;
  330. };
  331. class DoubleElement : public Element {
  332. double d;
  333. public:
  334. DoubleElement(double v) : Element(real), d(v) {};
  335. double doubleValue() const { return (d); }
  336. using Element::getValue;
  337. bool getValue(double& t) { t = d; return (true); }
  338. using Element::setValue;
  339. bool setValue(const double v) { d = v; return (true); }
  340. void toJSON(std::ostream& ss) const;
  341. bool equals(const Element& other) const;
  342. };
  343. class BoolElement : public Element {
  344. bool b;
  345. public:
  346. BoolElement(const bool v) : Element(boolean), b(v) {};
  347. bool boolValue() const { return (b); }
  348. using Element::getValue;
  349. bool getValue(bool& t) { t = b; return (true); }
  350. using Element::setValue;
  351. bool setValue(const bool v) { b = v; return (true); }
  352. void toJSON(std::ostream& ss) const;
  353. bool equals(const Element& other) const;
  354. };
  355. class NullElement : public Element {
  356. public:
  357. NullElement() : Element(null) {};
  358. void toJSON(std::ostream& ss) const;
  359. bool equals(const Element& other) const;
  360. };
  361. class StringElement : public Element {
  362. std::string s;
  363. public:
  364. StringElement(std::string v) : Element(string), s(v) {};
  365. std::string stringValue() const { return (s); }
  366. using Element::getValue;
  367. bool getValue(std::string& t) { t = s; return (true); }
  368. using Element::setValue;
  369. bool setValue(const std::string& v) { s = v; return (true); }
  370. void toJSON(std::ostream& ss) const;
  371. bool equals(const Element& other) const;
  372. };
  373. class ListElement : public Element {
  374. std::vector<ConstElementPtr> l;
  375. public:
  376. ListElement() : Element(list) {}
  377. const std::vector<ConstElementPtr>& listValue() const { return (l); }
  378. using Element::getValue;
  379. bool getValue(std::vector<ConstElementPtr>& t) {
  380. t = l;
  381. return (true);
  382. }
  383. using Element::setValue;
  384. bool setValue(const std::vector<ConstElementPtr>& v) {
  385. l = v;
  386. return (true);
  387. }
  388. using Element::get;
  389. ConstElementPtr get(int i) const { return (l.at(i)); }
  390. using Element::set;
  391. void set(size_t i, ConstElementPtr e) {
  392. l.at(i) = e;
  393. }
  394. void add(ConstElementPtr e) { l.push_back(e); };
  395. using Element::remove;
  396. void remove(int i) { l.erase(l.begin() + i); };
  397. void toJSON(std::ostream& ss) const;
  398. size_t size() const { return (l.size()); }
  399. bool equals(const Element& other) const;
  400. };
  401. class MapElement : public Element {
  402. std::map<std::string, ConstElementPtr> m;
  403. public:
  404. MapElement() : Element(map) {}
  405. // TODO: should we have direct iterators instead of exposing the std::map here?
  406. const std::map<std::string, ConstElementPtr>& mapValue() const {
  407. return (m);
  408. }
  409. using Element::getValue;
  410. bool getValue(std::map<std::string, ConstElementPtr>& t) {
  411. t = m;
  412. return (true);
  413. }
  414. using Element::setValue;
  415. bool setValue(std::map<std::string, ConstElementPtr>& v) {
  416. m = v;
  417. return (true);
  418. }
  419. using Element::get;
  420. ConstElementPtr get(const std::string& s) const {
  421. return (contains(s) ? m.find(s)->second : ElementPtr());
  422. };
  423. using Element::set;
  424. void set(const std::string& key, ConstElementPtr value);
  425. using Element::remove;
  426. void remove(const std::string& s) { m.erase(s); }
  427. bool contains(const std::string& s) const {
  428. return (m.find(s) != m.end());
  429. }
  430. void toJSON(std::ostream& ss) const;
  431. // we should name the two finds better...
  432. // find the element at id; raises TypeError if one of the
  433. // elements at path except the one we're looking for is not a
  434. // mapelement.
  435. // returns an empty element if the item could not be found
  436. ConstElementPtr find(const std::string& id) const;
  437. // find the Element at 'id', and store the element pointer in t
  438. // returns true if found, or false if not found (either because
  439. // it doesnt exist or one of the elements in the path is not
  440. // a MapElement)
  441. bool find(const std::string& id, ConstElementPtr t) const;
  442. bool equals(const Element& other) const;
  443. };
  444. /// Checks whether the given ElementPtr is a NULL pointer
  445. /// \param p The ElementPtr to check
  446. /// \return true if it is NULL, false if not.
  447. bool isNull(ConstElementPtr p);
  448. ///
  449. /// \brief Remove all values from the first ElementPtr that are
  450. /// equal in the second. Both ElementPtrs MUST be MapElements
  451. /// The use for this function is to end up with a MapElement that
  452. /// only contains new and changed values (for ModuleCCSession and
  453. /// configuration update handlers)
  454. /// Raises a TypeError if a or b are not MapElements
  455. void removeIdentical(ElementPtr a, ConstElementPtr b);
  456. /// \brief Create a new ElementPtr from the first ElementPtr, removing all
  457. /// values that are equal in the second. Both ElementPtrs MUST be MapElements.
  458. /// The returned ElementPtr will be a MapElement that only contains new and
  459. /// changed values (for ModuleCCSession and configuration update handlers).
  460. /// Raises a TypeError if a or b are not MapElements
  461. ConstElementPtr removeIdentical(ConstElementPtr a, ConstElementPtr b);
  462. /// \brief Merges the data from other into element.
  463. /// (on the first level). Both elements must be
  464. /// MapElements.
  465. /// Every string,value pair in other is copied into element
  466. /// (the ElementPtr of value is copied, this is not a new object)
  467. /// Unless the value is a NullElement, in which case the
  468. /// key is removed from element, rather than setting the value to
  469. /// the given NullElement.
  470. /// This way, we can remove values from for instance maps with
  471. /// configuration data (which would then result in reverting back
  472. /// to the default).
  473. /// Raises a TypeError if either ElementPtr is not a MapElement
  474. void merge(ElementPtr element, ConstElementPtr other);
  475. ///
  476. /// \brief Insert the Element as a string into stream.
  477. ///
  478. /// This method converts the \c ElemetPtr into a string with
  479. /// \c Element::str() and inserts it into the
  480. /// output stream \c out.
  481. ///
  482. /// This function overloads the global operator<< to behave as described in
  483. /// ostream::operator<< but applied to \c ElementPtr objects.
  484. ///
  485. /// \param os A \c std::ostream object on which the insertion operation is
  486. /// performed.
  487. /// \param e The \c ElementPtr object to insert.
  488. /// \return A reference to the same \c std::ostream object referenced by
  489. /// parameter \c os after the insertion operation.
  490. std::ostream& operator<<(std::ostream& out, const Element& e);
  491. bool operator==(const Element& a, const Element& b);
  492. bool operator!=(const Element& a, const Element& b);
  493. } }
  494. #endif // _ISC_DATA_H
  495. // Local Variables:
  496. // mode: c++
  497. // End: