First commit
[anna.git] / include / anna / dbos / AutoObject.hpp
1 // ANNA - Anna is Not 'N' 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_dbos_AutoObject_hpp
38 #define anna_dbos_AutoObject_hpp
39
40 #include <anna/dbos/Object.hpp>
41
42 namespace anna {
43
44 namespace dbos {
45
46
47 /**
48    Facilita el uso de los punteros a objectos obtenidos a partir de los datos guardados en un medio fisico.
49
50    La idea de esta clase es que el constructor y el destructor de esta clase cooperan para reservar y/o
51    liberar correctamente la instancia de T asociada a esta instancia.
52
53    \param T Clase que vamos a gestionar.
54
55    En el siguiente ejemplo podemos ver la forma habitual de trabajar con un objeto persistente tiene
56    el incoveniente de que tenemos que tener en cuenta cada una de las situaciones en las que la
57    referencia obtenida mediante el metodo \em instantiate debe ser liberada.
58
59    \code
60    void Application::getServerSocketsData (vector <SocketData>& serverSocketsData) const
61       throw (RuntimeException)
62    {
63       LOGMETHOD (TraceMethod ("anna::Application", "getServerSocketsData", ANNA_FILE_LOCATION));
64
65       Facility* facility (NULL);
66       FacilityLoader facilityLoader;
67
68       try {
69          facility = Facility::instantiate (facilityLoader.setKey (a_thisFacility));   // (1)
70          LOGDEBUG (Logger::write (Logger::Debug, facility->asString (), ANNA_FILE_LOCATION));
71
72          getSocketsData (getThisHostName (), facility->getName (), a_thisCell, a_thisInstance, serverSocketsData);
73
74          Facility::release (facility);
75       }
76       catch (dbos::DatabaseException& edbos) {
77          Facility::release (facility);
78          throw RuntimeException (edbos.getText (), ANNA_FILE_LOCATION);
79       }
80       catch (RuntimeException&) {   // Tenemos que capturar esta excepcion para liberar el recurso.
81          Facility::release (facility);
82          throw;
83       }
84    }
85    \endcode
86
87    Como podemos ver a continuacion el siguiente metodo es mucho mas sencillo y aporta la gran ventaja de que
88    el sistema trabaja por nosotros para liberar correctamente los recursos.
89
90    \code
91    void Application::getServerSocketsData (vector <SocketData>& serverSocketsData) const
92       throw (RuntimeException)
93    {
94       LOGMETHOD (TraceMethod ("anna::Application", "getServerSocketsData", ANNA_FILE_LOCATION));
95
96       AutoObject <Facility> facility;
97       FacilityLoader facilityLoader;
98
99       try {
100          facility = Facility::instantiate (facilityLoader.setKey (a_thisFacility));   // (1)
101
102          LOGDEBUG (Logger::write (Logger::Debug, facility->asString (), ANNA_FILE_LOCATION));
103
104          getSocketsData (getThisHostName (), facility->getName (), a_thisCell, a_thisInstance, serverSocketsData);
105       }
106       catch (dbos::DatabaseException& edbos) {
107          throw RuntimeException (edbos.getText (), ANNA_FILE_LOCATION);
108       }
109    }
110    \endcode
111 */
112 template <typename T> class AutoObject {
113 public:
114   /**
115      Constructor.
116      \param t Instancia del objeto asociado a esta instancia.
117      \warning La instancia deberia haber sido obtenida mediate la invocacion a \em T::instantiate de la
118      clase persistente.
119   */
120   explicit AutoObject(T* t) : a_t(t) {;}
121
122   /**
123      Constructor.
124   */
125   AutoObject() : a_t(NULL) {;}
126
127   /**
128      Destructor. Invoca al metodo \em T::release
129   */
130   ~AutoObject() { if(a_t != NULL) T::release(a_t); }
131
132   /**
133      Operador ->
134      Permite invocar a metodos de la clase T.
135      \return La instancia de la clase T asociada a esta instancia.
136   */
137   T* operator -> () const throw() { return a_t; }
138
139   /**
140      Operador copia.
141      \param t Referencia al objeto que vamos a tratar.
142      \return La instancia de la clase T asociada a esta instancia.
143   */
144   T* operator = (T* t) throw() {
145     if(a_t != t) {
146       T::release(a_t);
147       a_t = t;
148     }
149
150     return a_t;
151   }
152
153   /**
154      Operador copia.
155      \param other Referencia al objeto que vamos a tratar.
156      \return La instancia de la clase T asociada a esta instancia.
157   */
158   T* operator = (const AutoObject <T>& other) throw(RuntimeException) {
159     return (this != &other)  ? (*this = T::duplicate(other.a_t)) : a_t;
160   }
161
162   /**
163      Operador de conversion.
164      \return La instancia de la clase T asociada a esta instancia.
165   */
166   operator T*() const throw() { return a_t; }
167
168 private:
169   T* a_t;
170 };
171
172
173 }
174 }
175
176
177
178 #endif
179
180