Updated license
[anna.git] / include / anna / xml / XPath.hpp
1 // ANNA - Anna is Not Nothingness Anymore
2 //
3 // (c) Copyright 2005-2014 Eduardo Ramos Testillano & Francisco Ruiz Rayo
4 //
5 // https://bitbucket.org/testillano/anna
6 //
7 // Redistribution and use in source and binary forms, with or without
8 // modification, are permitted provided that the following conditions
9 // are met:
10 //
11 //     * Redistributions of source code must retain the above copyright
12 // notice, this list of conditions and the following disclaimer.
13 //     * Redistributions in binary form must reproduce the above
14 // copyright notice, this list of conditions and the following disclaimer
15 // in the documentation and/or other materials provided with the
16 // distribution.
17 //     * Neither the name of Google Inc. nor the names of its
18 // contributors may be used to endorse or promote products derived from
19 // this software without specific prior written permission.
20 //
21 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 //
33 // Authors: eduardo.ramos.testillano@gmail.com
34 //          cisco.tierra@gmail.com
35
36
37 #ifndef anna_xml_XPath_hpp
38 #define anna_xml_XPath_hpp
39
40 #include <anna/core/RuntimeException.hpp>
41 #include <anna/core/mt/Mutex.hpp>
42 #include <anna/core/util/Recycler.hpp>
43
44 #include <anna/xml/Node.hpp>
45 #include <anna/xml/Parser.hpp>
46
47 struct _xmlNode;
48 struct _xmlNodeSet;
49 struct  _xmlXPathContext;
50
51 namespace anna {
52
53 namespace xml {
54
55 /**
56    XPath es un lenguaje para encontrar información dentro de un documento XML.
57
58    \see http://www.w3schools.com/xpath/default.asp
59 */
60 class XPath : Parser {
61 public:
62   /**
63    * Modo en que recupera la información de los nodos seleccionados por la expressión XPath.
64    * \see XPath.
65    */
66   struct Mode {
67     enum _v {
68       Simple = 0x01, /**< Sólo devuelve el primer nivel de nodos que cumplen con la expressión XPath. */
69       Full = 0x02,  /**< Devuelve el árbol dependiente de los nodos que cumplen con la expressión XPath */
70       Namespace = 0x04 /**< Activa el uso de namespaces en el doc XML recibido.*/
71     };
72   };
73
74   /**
75      Constructor.
76      \param name Nombre lógico de esta instancia.
77   */
78   XPath(const char* name);
79
80   /**
81      Aplica la expresión XPath sobre el documento recibido como parámetro. Los nodos
82      del documento XML seleccionados por XPath se recogeran con los métodos
83      #node_begin, #node_end y #node.
84
85      \param document Documento XML sobre el que aplicar la expresión.
86      \param expression Expresión XPath a aplicar sobre el documento XML.
87      \param mode Una combinación de XPath::Mode::_v.
88      \warning La instancia del documento debe estar correctamente inicializada.
89      \see Document::initialize
90   */
91   void apply(const Document& document, const char* expression, const int mode = Mode::Simple) throw(RuntimeException);
92
93   /**
94    * Aplica la expresión XPath sobre el documento recibido como parámetro y devuelve
95    * \em true si hay algún nodo que cumpla la expresión o \em false en otro caso.
96    * Es mucho más rápido que el método #apply, porque no dispondremos de los nodos que
97    * cumplen la condición.
98    *
99    * \param document Documento XML al que aplicar la sentencia.
100    * \param expression Expresión XPath a aplicar.
101    * \param mode Modo de interpretación de los resultados. \em Si valor XPath::Mode::Namespace analizará el
102    * documento XML para obtener los namespaces a usar.
103    *
104    * \return \em true si algún nodo del documento que cumpla la expressión o \em false en otro caso.
105    */
106   bool match(const Document& document, const char* expression, const int mode = Mode::Simple) throw(RuntimeException);
107
108   /**
109      Aplica la expresión XPath sobre el documento recibido como parámetro y devuelve el primer
110      nodo que cumple con la expresión.
111    *
112    * \param document Documento XML al que aplicar la sentencia.
113    * \param expression Expresión XPath a aplicar.
114    * \param mode Modo de interpretación de los resultados. \em Si valor XPath::Mode::Namespace analizará el
115    * documento XML para obtener los namespaces a usar.
116    * \param emode Modo de actuar en caso de que no haya ningún nodo que cumpla la expresión.
117    *
118    * \warning Si no hay ningún nodo que cumpla la expresión devolverá una excepción.
119    */
120   const Node* find(const Document& document, const char* expression, const int mode = Mode::Full, const Exception::Mode::_v emode = Exception::Mode::Throw)
121   throw(RuntimeException);
122
123   /**
124    * Devuelve \em true si existen nodos que cumplieron la condición de #apply o \em false en otro caso.
125    * \return  \em true si existen nodos que cumplieron la condición de #apply o \em false en otro caso.
126    */
127   bool isEmpty() const throw() { return a_root->a_children.size() == 0; }
128
129   /**
130    * Devuelve el número de nodos que han sido seleccionados al invocar al método #apply.
131    * \return El número de nodos que han sido seleccionados al invocar al método #apply.
132    */
133   int size() const throw() { return a_root->a_children.size(); }
134
135   /**
136    * Devuelve el primer nodo del documento que cumple la expresión indicada al invocar al método #apply.
137    * \return El primer nodo del documento que cumple la expresión indicada al invocar al método #apply.
138    */
139   Node::const_child_iterator node_begin() const throw() { return a_root->child_begin(); }
140
141   /**
142    * Devuelve el final de la lista de nodos que cumplen la expresión indicada al invocar al método #apply.
143    * \return El final de la lista de nodos que cumplen la expresión indicada al invocar al método #apply.
144    */
145   Node::const_child_iterator node_end() const throw() { return a_root->child_end(); }
146
147   /**
148    * Devuelve la instancia del nodo apuntado por el iterador recibido como parámetro.
149    * \return la instancia del nodo apuntado por el iterador recibido como parámetro.
150    */
151   static const Node* node(Node::const_child_iterator& ii) throw() { return xml::Node::node(ii); }
152
153 private:
154   // Modo pasado al callback del apply
155   int a_mode;
156
157   // Resultado retornado por el callback del match
158   bool a_result;
159
160   typedef void(XPath::*Initialize)(_xmlXPathContext*, const Document&);
161   typedef void (XPath::*Callback)(const _xmlNodeSet*);
162
163   struct ConfigSkeleton;
164   friend struct ConfigSkeleton;
165
166   struct ConfigSkeleton {
167     Initialize initialize;
168     Callback callback;
169
170     ConfigSkeleton(Callback _callback) : initialize(NULL), callback(_callback) {;}
171   };
172
173   XPath(const XPath&);
174
175   void text(Node* node, _xmlNode* xmlNode) throw(RuntimeException);
176
177   void skeleton(const Document&, const char* expression, ConfigSkeleton&) throw(RuntimeException);
178
179   void initializeNamespaces(_xmlXPathContext*, const Document&) throw(RuntimeException);
180   void forwardNamespaces(_xmlXPathContext*, _xmlNode*) throw(RuntimeException);
181   void callbackApply(const _xmlNodeSet*);
182   void callbackMatch(const _xmlNodeSet*);
183 };
184
185 }
186 }
187
188 #endif