Updated license
[anna.git] / example / http / server / main.cpp
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 /*
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
54 #include <anna/comm/comm.hpp>
55
56 #include <anna/http/Request.hpp>
57 #include <anna/http/Response.hpp>
58 #include <anna/http/Handler.hpp>
59 #include <anna/http/Transport.hpp>
60 #include <anna/http/functions.hpp>
61
62 #include <anna/test/Request.hpp>
63 #include <anna/test/Response.hpp>
64 #include <anna/test/Communicator.hpp>
65
66 using namespace std;
67
68 class MyHandler : public http::Handler {
69 public:
70    MyHandler () : http::Handler ("http_server::MyHandler") {    
71       allocateResponse ()->createHeader (http::Header::Type::Date); 
72    }
73
74 private:
75    test::Request a_testRequest;
76    test::Response a_testResponse;
77
78    void evRequest (ClientSocket&, const http::Request& request) throw (RuntimeException);
79    void evResponse (ClientSocket&, const http::Response&) throw (RuntimeException) {;}
80 };
81
82 class MyCommunicator : public test::Communicator {
83 public:
84    MyCommunicator () : 
85       a_contexts ("Contexts")
86    {;}
87
88 private:
89    ThreadData <MyHandler> a_contexts;
90    
91    void eventReceiveMessage (comm::ClientSocket&, const Message&) throw (RuntimeException);
92 };
93
94 class HTTPArithmeticServer : public comm::Application {
95 public:
96    HTTPArithmeticServer ();
97       
98 private:
99    MyCommunicator a_communicator;
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    HTTPArithmeticServer 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 HTTPArithmeticServer::HTTPArithmeticServer () : 
136    Application ("http_server", "Servidor HTTP de operaciones aritmeticas", "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 direccin", 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, "Milisegundos transcurridos sin actividad para cerrar el socket");
148 }
149
150 void HTTPArithmeticServer::initialize () 
151    throw (RuntimeException)
152 {
153    CommandLine& cl (CommandLine::instantiate ());
154
155    int port = cl.getIntegerValue ("p");
156    const comm::Device* device = Network::instantiate ().find (Device::asAddress (cl.getValue ("a")));
157
158    a_serverSocket = new ServerSocket (INetAddress (device, port), cl.exists ("r"), &http::Transport::getFactory ());
159 }
160
161 void HTTPArithmeticServer::run ()
162    throw (RuntimeException)
163 {
164    CommandLine& cl (CommandLine::instantiate ());
165
166    a_communicator.attach (a_serverSocket);
167    a_communicator.setDelay ((Millisecond)cl.getIntegerValue ("d"));
168
169    if (cl.exists ("n") == true)
170       a_communicator.setMaxMessage (cl.getIntegerValue ("n"));
171
172    if (cl.exists ("trace"))
173       Logger::setLevel (Logger::asLevel (cl.getValue ("trace")));
174
175    CongestionController::instantiate ().setLimit (cl.getIntegerValue ("limit"));
176
177    if (cl.exists ("timeout"))
178       a_communicator.setTimeout ((Millisecond)cl.getIntegerValue ("timeout"));
179
180    a_communicator.accept ();
181 }
182
183 xml::Node* HTTPArithmeticServer::asXML (xml::Node* app) const 
184    throw ()
185 {
186    xml::Node* node = app::Application::asXML (app);
187    
188    node->createAttribute ("MaxMessage", a_communicator.getMaxMessage ());
189    node->createAttribute ("Message", a_communicator.getMessage ());
190    
191    return node;
192 }
193
194 void MyCommunicator::eventReceiveMessage (ClientSocket& clientSocket, const Message& message)
195    throw (RuntimeException)
196 {
197    LOGMETHOD (TraceMethod tm ("MyCommunicator", "eventReceiveMessage", ANNA_FILE_LOCATION));
198
199    if (clientSocket.support (http::Transport::className ()) == false)
200       return;
201
202    if (canContinue (clientSocket) == false)
203       return;   
204
205    delay ();   
206
207    MyHandler& httpHandler = a_contexts.get ();
208
209    httpHandler.apply (clientSocket, message);
210 }
211
212 void MyHandler::evRequest (ClientSocket& clientSocket, const http::Request& request)
213    throw (RuntimeException)
214 {
215    const DataBlock& body = request.getBody ();
216
217    if (body.getSize () == 0)
218       throw RuntimeException ("La peticion no incorpora los parametros de operacion", ANNA_FILE_LOCATION);
219
220    LOGINFORMATION (
221       string msg ("Body recibido: ");
222       msg += anna::functions::asString (body);
223       Logger::information (msg, ANNA_FILE_LOCATION);
224    );
225
226    if (Codec::getType (body) != test::Request::Id) 
227       throw RuntimeException ("El mensaje recibido no es una peticion aritmetica", ANNA_FILE_LOCATION);
228
229    a_testRequest.decode (body);
230
231    a_testResponse.x = a_testRequest.x;
232    a_testResponse.y = a_testRequest.y;
233    a_testResponse.initTime = a_testRequest.initTime;
234    
235    http::Response* response = allocateResponse ();
236
237    response->setStatusCode (200);
238
239    switch (a_testResponse.op = a_testRequest.op) {
240       case '+':
241          a_testResponse.result = a_testRequest.x + a_testRequest.y;
242          break;
243       case '-':
244          a_testResponse.result = a_testRequest.x - a_testRequest.y;
245          break;
246       case '*':
247          a_testResponse.result = a_testRequest.x * a_testRequest.y;
248          break;
249       case '/':
250          if (a_testRequest.y == 0) {
251             response->setStatusCode (400);
252             response->setReasonPhrase ("Division por cero");
253             a_testResponse.result = 0;
254          }
255          else
256             a_testResponse.result = a_testRequest.x / a_testRequest.y;
257          break;
258    }
259
260    response->setBody (a_testResponse.code ());      
261
262    response->find (http::Header::Type::Date)->setValue ("Mon, 30 Jan 2006 14:36:18 GMT");
263    
264    http::Header* keepAlive = response->find ("Keep-Alive");
265    
266    if (keepAlive == NULL)
267       keepAlive = response->createHeader ("Keep-Alive");   
268    
269    keepAlive->setValue ("Verificacion del cambio 1.0.7");
270       
271
272    LOGINFORMATION (
273       string msg = anna::functions::asString ("%d %c %d = %d", a_testRequest.x, a_testRequest.op, a_testRequest.y, a_testResponse.result);
274       Logger::information (msg, ANNA_FILE_LOCATION);
275    );
276
277    try {
278       clientSocket.send (*response);
279    }
280    catch (Exception& ex) {
281       ex.trace ();
282    }
283 }
284