1 // ANNA - Anna is Not Nothingness Anymore //
3 // (c) Copyright 2005-2015 Eduardo Ramos Testillano & Francisco Ruiz Rayo //
5 // See project site at http://redmine.teslayout.com/projects/anna-suite //
6 // See accompanying file LICENSE or copy at http://www.teslayout.com/projects/public/anna.LICENSE //
10 Ejemplo de programa servidor. Atiende peticiones aritmeticas, el protocolo de transporte sera HTTP
11 ver http::Transport y el contenido del mensaje sera el resutaldo de un comm::Codec con los
12 (x, y, op) -> El resultado sera estos tres componente mas result.
14 Para poder probar el sistema de congestion se puede indicar un numero de milisegundos de
15 retardo aplicados a cada contestacion.
17 Los clientes pueden ser: http_kclient.p http_client.p
21 #include <anna/core/core.hpp>
23 #include <anna/xml/Node.hpp>
24 #include <anna/xml/Attribute.hpp>
26 #include <anna/comm/comm.hpp>
28 #include <anna/http/Request.hpp>
29 #include <anna/http/Response.hpp>
30 #include <anna/http/Handler.hpp>
31 #include <anna/http/Transport.hpp>
32 #include <anna/http/functions.hpp>
34 #include <anna/http/wims20/ServerSide.hpp>
36 #include <anna/test/Communicator.hpp>
40 class MyHandler : public http::Handler {
42 MyHandler () : http::Handler ("http_rserver::MyHandler"),
46 anna_memset (a_xmlAttributes, 0, sizeof (a_xmlAttributes));
53 static const char* className () throw () { return "http_rserver::ReceiverFactory"; }
56 struct Attribute { enum _v { ValueOne, ValueTwo, Operator, Result, Time, Max }; };
58 test::Communicator* a_communicator;
59 http::wims20::ServerSide* a_request;
60 xml::Node* a_xmlResponse;
61 xml::Attribute* a_xmlAttributes [Attribute::Max];
62 std::string a_serviceID;
65 void initialize () throw (RuntimeException);
66 void evRequest (ClientSocket&, const http::Request& request) throw (RuntimeException);
67 void evResponse (ClientSocket&, const http::Response&) throw (RuntimeException) {;}
70 class WIMS20ArithmeticServer : public comm::Application {
72 WIMS20ArithmeticServer ();
75 test::Communicator a_communicator;
76 ReceiverFactoryImpl <MyHandler> a_receiverFactory;
77 comm::ServerSocket* a_serverSocket;
79 void initialize () throw (RuntimeException);
80 void run () throw (RuntimeException);
81 xml::Node* asXML (xml::Node* app) const throw ();
85 using namespace anna::comm;
87 int main (int argc, const char** argv)
89 CommandLine& commandLine (CommandLine::instantiate ());
90 WIMS20ArithmeticServer app;
92 http::functions::initialize ();
97 commandLine.initialize (argv, argc);
98 commandLine.verify ();
100 Logger::setLevel (Logger::Debug);
101 Logger::initialize ("http_server", new anna::TraceWriter ("file.trace", 4048000));
105 catch (Exception& ex) {
106 cout << ex.asString () << endl;
112 WIMS20ArithmeticServer::WIMS20ArithmeticServer () :
113 Application ("http_rserver", "Servidor WIMS20 de operaciones aritmeticas (iRS)", "1.0")
115 CommandLine& commandLine (CommandLine::instantiate ());
117 commandLine.add ("p", CommandLine::Argument::Mandatory, "Puerto en el que atender peticiones");
118 commandLine.add ("a", CommandLine::Argument::Mandatory, "Direccin IP en la que atender");
119 commandLine.add ("d", CommandLine::Argument::Mandatory, "Retardo aplicado a la contestacion");
120 commandLine.add ("r", CommandLine::Argument::Optional, "Indicador de reuso de direccion", false);
121 commandLine.add ("limit", CommandLine::Argument::Mandatory, "% de ocupacion que permitimos");
122 commandLine.add ("n", CommandLine::Argument::Optional, "Numero de mensajes a servir", true);
123 commandLine.add ("trace", CommandLine::Argument::Optional, "Nivel de trazas (debug,warning, error,...)");
124 commandLine.add ("timeout", CommandLine::Argument::Optional, "Timeout (ms) del cliente sin enviar peticiones");
125 commandLine.add ("quota", CommandLine::Argument::Optional, "Numero de bytes aceptados antes de cerrar el socket");
126 commandLine.add ("domain", CommandLine::Argument::Mandatory, "http://domain-openapis/path-openapis/serviceID/guid/other_possible_levels?query_parameters");
127 commandLine.add ("service", CommandLine::Argument::Mandatory, "http://domain-openapis/path-openapis/serviceID/guid/other_possible_levels?query_parameters");
128 commandLine.add ("guid", CommandLine::Argument::Mandatory, "http://domain-openapis/path-openapis/serviceID/guid/other_possible_levels?query_parameters");
131 void WIMS20ArithmeticServer::initialize ()
132 throw (RuntimeException)
134 CommandLine& cl (CommandLine::instantiate ());
136 int port = cl.getIntegerValue ("p");
137 const comm::Device* device = Network::instantiate ().find (Device::asAddress (cl.getValue ("a")));
139 comm::TransportFactory* ttff = &http::Transport::getFactory ();
141 if (cl.exists ("quota") == true)
142 ttff->setOverQuotaSize (cl.getIntegerValue ("quota"));
144 a_serverSocket = new ServerSocket (INetAddress (device, port), cl.exists ("r"), ttff);
145 a_serverSocket->setReceiverFactory (a_receiverFactory);
148 void WIMS20ArithmeticServer::run ()
149 throw (RuntimeException)
151 CommandLine& cl (CommandLine::instantiate ());
153 a_communicator.attach (a_serverSocket);
154 a_communicator.setDelay ((Millisecond)cl.getIntegerValue ("d"));
156 if (cl.exists ("n") == true)
157 a_communicator.setMaxMessage (cl.getIntegerValue ("n"));
159 if (cl.exists ("trace"))
160 Logger::setLevel (Logger::asLevel (cl.getValue ("trace")));
162 CongestionController::instantiate ().setLimit (cl.getIntegerValue ("limit"));
164 if (cl.exists ("timeout") == true)
165 a_communicator.setTimeout ((Millisecond)cl.getIntegerValue ("timeout"));
167 a_communicator.accept ();
170 xml::Node* WIMS20ArithmeticServer::asXML (xml::Node* app) const
173 xml::Node* node = app::Application::asXML (app);
175 node->createAttribute ("MaxMessage", a_communicator.getMaxMessage ());
176 node->createAttribute ("Message", a_communicator.getMessage ());
181 void MyHandler::initialize ()
182 throw (RuntimeException)
184 CommandLine& cl (CommandLine::instantiate ());
186 a_communicator = app::functions::component <test::Communicator> (ANNA_FILE_LOCATION);
189 * Crea el documento XML que usaremos para codificar la respuesta y
190 * pre-localiza los objetos sobre los que tendrá que actuar
192 a_xmlResponse = new xml::Node ("Response");
193 a_xmlAttributes [Attribute::ValueOne] = a_xmlResponse->createAttribute ("ValueOne", 0);
194 a_xmlAttributes [Attribute::ValueTwo] = a_xmlResponse->createAttribute ("ValueTwo", 0);
195 a_xmlAttributes [Attribute::Operator] = a_xmlResponse->createAttribute ("Operator", 0);
196 a_xmlAttributes [Attribute::Result] = a_xmlResponse->createAttribute ("Result", 0);
197 a_xmlAttributes [Attribute::Time] = a_xmlResponse->createAttribute ("Time", 0);
200 * Crea el analizador de la petición REST, que viene formateada según la especificación WIMS2.0
202 a_request = new http::wims20::ServerSide (cl.getValue ("domain"));
203 a_serviceID = cl.getValue ("service");
204 a_guid = cl.getValue ("guid");
208 * Recibe una URI que puede ser similar a:
209 * URI: http://www.localhost.es/math/user@tid.es?Operator=*&ValueOne=20&ValueTwo=2&Time=10000
211 void MyHandler::evRequest (ClientSocket& clientSocket, const http::Request& request)
212 throw (RuntimeException)
214 LOGMETHOD (TraceMethod tm ("MyReceiver", "apply", ANNA_FILE_LOCATION));
216 if (a_communicator->canContinue (clientSocket) == false)
219 // Extrae los parámetros de la petición REST de la URI de la petición HTTP
220 a_request->decode (request);
222 http::Response* response = allocateResponse ();
225 * Si la petición no tiene los parámetros esperados devuelve error.
227 if (a_request->getServiceID () != a_serviceID || a_request->getGUID () != a_guid) {
228 response->setStatusCode (401);
229 clientSocket.send (*response);
233 // Antes de contestar espera el tiempo indicado en la configuración
234 a_communicator->delay ();
237 * Obtiene los valores de la URI correspondiente a la petición REST
239 const char* op = a_request->getCStringValue ("Operator");
240 int v1 = a_request->getIntegerValue ("ValueOne");
241 int v2 = a_request->getIntegerValue ("ValueTwo");
244 * Establece el valor de los objetos XML pre-localizados.
246 a_xmlAttributes [Attribute::ValueOne]->setValue (v1);
247 a_xmlAttributes [Attribute::ValueTwo]->setValue (v2);
248 a_xmlAttributes [Attribute::Operator]->setValue (op);
250 // Este dato sirve para calcular el tiempo de respuesta del servidor
251 a_xmlAttributes [Attribute::Time]->setValue (a_request->getIntegerValue ("Time"));
253 response->setStatusCode (200);
256 case 'a': a_xmlAttributes [Attribute::Result]->setValue (v1 + v2); break;
257 case 's': a_xmlAttributes [Attribute::Result]->setValue (v1 - v2); break;
258 case 'm': a_xmlAttributes [Attribute::Result]->setValue (v1 * v2); break;
261 response->setStatusCode (400);
262 response->setReasonPhrase ("Division por cero");
265 a_xmlAttributes [Attribute::Result]->setValue (v1 / v2);
268 response->setStatusCode (501);
272 /* Observar que establece directamente el documento XML como cuerpo
273 * de la respuesta HTTP.
275 if (response->getStatusCode () == 200)
276 response->setBody (a_xmlResponse);
278 response->clearBody ();
280 clientSocket.send (*response);