First commit
[anna.git] / example / http / xmlRServer / main.cpp
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 /*
38   Ejemplo de programa servidor. Atiende peticiones aritmeticas, el protocolo de transporte sera HTTP
39   ver http::Transport y el contenido del mensaje sera el resutaldo de un comm::Codec con los
40   (x, y, op) -> El resultado sera estos tres componente mas result.
41
42   Para poder probar el sistema de congestion se puede indicar un numero de milisegundos de
43   retardo aplicados a cada contestacion.
44   
45   Los clientes pueden ser: http_kclient.p http_client.p
46 */
47 #include <iostream>
48
49 #include <anna/core/core.hpp>
50
51 #include <anna/xml/Node.hpp>
52 #include <anna/xml/Attribute.hpp>
53 #include <anna/xml/DocumentMemory.hpp>
54
55 #include <anna/comm/comm.hpp>
56
57 #include <anna/http/Request.hpp>
58 #include <anna/http/Response.hpp>
59 #include <anna/http/Handler.hpp>
60 #include <anna/http/Transport.hpp>
61 #include <anna/http/functions.hpp>
62
63
64 #include <anna/test/Communicator.hpp>
65
66
67 using namespace std;
68
69 class MyHandler : public http::Handler {
70 public:
71    MyHandler () : http::Handler ("http_rserver::MyHandler")
72    {
73       anna_memset (a_xmlAttributes, 0, sizeof (a_xmlAttributes));      
74    }
75    ~MyHandler () {
76    }
77
78    static const char* className () throw () { return "http_rserver::ReceiverFactory"; }
79
80 private:
81    struct Attribute { enum _v { ValueOne, ValueTwo, Operator, Result, Time, Max }; };
82    
83    test::Communicator* a_communicator;
84    xml::DocumentMemory a_xmlRequest;
85    xml::Node* a_xmlResponse;
86    xml::Attribute* a_xmlAttributes [Attribute::Max];
87    
88    void initialize () throw (RuntimeException);
89    void evRequest (ClientSocket&, const http::Request& request) throw (RuntimeException);
90    void evResponse (ClientSocket&, const http::Response&) throw (RuntimeException) {;}
91 };
92
93 class WIMS20ArithmeticServer : public comm::Application {
94 public:
95    WIMS20ArithmeticServer ();
96       
97 private:
98    test::Communicator a_communicator;
99    ReceiverFactoryImpl <MyHandler> a_receiverFactory;
100    comm::ServerSocket* a_serverSocket;
101
102    void initialize () throw (RuntimeException);
103    void run () throw (RuntimeException);
104    xml::Node* asXML (xml::Node* app) const throw ();
105 };
106
107 using namespace std;
108 using namespace anna::comm;
109
110 int main (int argc, const char** argv)
111 {
112    CommandLine& commandLine (CommandLine::instantiate ());
113    WIMS20ArithmeticServer app;
114
115    http::functions::initialize ();
116
117    srand (time (NULL));
118
119    try {
120       commandLine.initialize (argv, argc);
121       commandLine.verify ();
122
123       Logger::setLevel (Logger::Debug); 
124       Logger::initialize ("http_server", new anna::TraceWriter ("file.trace", 4048000));
125  
126       app.start ();
127    }
128    catch (Exception& ex) {
129       cout << ex.asString () << endl;
130    }
131    
132    return 0;
133 }
134
135 WIMS20ArithmeticServer::WIMS20ArithmeticServer () : 
136    Application ("http_rserver", "Servidor WIMS20 de operaciones aritmeticas (iRS)", "1.0") 
137 {
138    CommandLine& commandLine (CommandLine::instantiate ());
139       
140    commandLine.add ("p", CommandLine::Argument::Mandatory, "Puerto en el que atender peticiones");
141    commandLine.add ("a", CommandLine::Argument::Mandatory, "Direccin IP en la que atender");
142    commandLine.add ("d", CommandLine::Argument::Mandatory, "Retardo aplicado a la contestacion");
143    commandLine.add ("r", CommandLine::Argument::Optional, "Indicador de reuso de direccion", false);
144    commandLine.add ("limit", CommandLine::Argument::Mandatory, "% de ocupacion que permitimos");
145    commandLine.add ("n", CommandLine::Argument::Optional, "Numero de mensajes a servir", true);
146    commandLine.add ("trace", CommandLine::Argument::Optional, "Nivel de trazas (debug,warning, error,...)");
147    commandLine.add ("timeout", CommandLine::Argument::Optional, "Timeout (ms) del cliente sin enviar peticiones");
148    commandLine.add ("quota", CommandLine::Argument::Optional, "Numero de bytes aceptados antes de cerrar el socket");
149 }
150
151 void WIMS20ArithmeticServer::initialize () 
152    throw (RuntimeException)
153 {
154    CommandLine& cl (CommandLine::instantiate ());
155
156    int port = cl.getIntegerValue ("p");
157    const comm::Device* device = Network::instantiate ().find (Device::asAddress (cl.getValue ("a")));
158
159    comm::TransportFactory* ttff = &http::Transport::getFactory ();
160
161    if (cl.exists ("quota") == true) 
162       ttff->setOverQuotaSize (cl.getIntegerValue ("quota"));
163
164    a_serverSocket = new ServerSocket (INetAddress (device, port), cl.exists ("r"), ttff);
165    a_serverSocket->setReceiverFactory (a_receiverFactory);
166 }
167
168 void WIMS20ArithmeticServer::run ()
169    throw (RuntimeException)
170 {
171    CommandLine& cl (CommandLine::instantiate ());
172
173    a_communicator.attach (a_serverSocket);
174    a_communicator.setDelay ((Millisecond)cl.getIntegerValue ("d"));
175
176    if (cl.exists ("n") == true)
177       a_communicator.setMaxMessage (cl.getIntegerValue ("n"));
178
179    if (cl.exists ("trace"))
180       Logger::setLevel (Logger::asLevel (cl.getValue ("trace")));
181
182    CongestionController::instantiate ().setLimit (cl.getIntegerValue ("limit"));
183
184    if (cl.exists ("timeout") == true)
185       a_communicator.setTimeout ((Millisecond)cl.getIntegerValue ("timeout"));
186
187    a_communicator.accept ();
188 }
189
190 xml::Node* WIMS20ArithmeticServer::asXML (xml::Node* app) const 
191    throw ()
192 {
193    xml::Node* node = app::Application::asXML (app);
194    
195    node->createAttribute ("MaxMessage", a_communicator.getMaxMessage ());
196    node->createAttribute ("Message", a_communicator.getMessage ());
197    
198    return node;
199 }
200
201 void MyHandler::initialize ()
202    throw (RuntimeException)
203 {
204    a_communicator = app::functions::component <test::Communicator> (ANNA_FILE_LOCATION);
205    
206    /**
207     * Crea el documento XML que usaremos para codificar la respuesta y 
208     * pre-localiza los objetos sobre los que tendrá que actuar
209     */
210    a_xmlResponse = new xml::Node ("Response");
211    a_xmlAttributes [Attribute::ValueOne] = a_xmlResponse->createAttribute ("ValueOne", 0);
212    a_xmlAttributes [Attribute::ValueTwo] = a_xmlResponse->createAttribute ("ValueTwo", 0);
213    a_xmlAttributes [Attribute::Operator] = a_xmlResponse->createAttribute ("Operator", 0);
214    a_xmlAttributes [Attribute::Result] = a_xmlResponse->createAttribute ("Result", 0);
215    a_xmlAttributes [Attribute::Time] = a_xmlResponse->createAttribute ("Time", 0);
216 }
217
218 /*
219  * Recibe una peticion
220  */
221 void MyHandler::evRequest (ClientSocket& clientSocket, const http::Request& httpRequest)
222    throw (RuntimeException)
223 {
224    LOGMETHOD (TraceMethod tm ("MyReceiver", "apply", ANNA_FILE_LOCATION));
225
226    if (a_communicator->canContinue (clientSocket) == false)
227       return;      
228       
229    // Extrace el documento XML de la petición.
230    a_xmlRequest.initialize (httpRequest.getBody ());
231    
232    const xml::Node* request = a_xmlRequest.parse (); 
233    
234    http::Response* response = allocateResponse ();
235
236    // Antes de contestar espera el tiempo indicado en la configuración
237    a_communicator->delay ();
238    
239    /**
240     * Obtiene los valores de los atributos del documento XML
241     */
242    const char* op = request->getAttribute ("Operator")->getCStringValue ();
243    int v1 = request->getAttribute ("ValueOne")->getIntegerValue ();
244    int v2 = request->getAttribute ("ValueTwo")->getIntegerValue ();
245       
246    /**
247     * Establece el valor de los objetos XML pre-localizados que irán en la respuesta
248     */
249    a_xmlAttributes [Attribute::ValueOne]->setValue (v1);
250    a_xmlAttributes [Attribute::ValueTwo]->setValue (v2);
251    a_xmlAttributes [Attribute::Operator]->setValue (op);
252    
253    // Este dato sirve para calcular el tiempo de respuesta del servidor 
254    a_xmlAttributes [Attribute::Time]->setValue (request->getAttribute ("Millisecond")->getIntegerValue ());
255    
256    response->setStatusCode (200);
257
258    switch (*op) {
259       case '+': a_xmlAttributes [Attribute::Result]->setValue (v1 + v2); break;
260       case '-': a_xmlAttributes [Attribute::Result]->setValue (v1 - v2); break;
261       case '*': a_xmlAttributes [Attribute::Result]->setValue (v1 * v2); break;
262       case '/':
263          if (v2 == 0) {
264             response->setStatusCode (400);
265             response->setReasonPhrase ("Division por cero");
266          }
267          else
268             a_xmlAttributes [Attribute::Result]->setValue (v1 / v2);
269          break;
270       default:
271          response->setStatusCode (501);
272          break;
273    }
274
275    /* Observar que establece directamente el documento XML como cuerpo
276     * de la respuesta HTTP.
277     */    
278    if (response->getStatusCode () == 200)
279       response->setBody (a_xmlResponse);
280    else
281       response->clearBody ();      
282    
283    clientSocket.send (*response);
284 }