Updated license
[anna.git] / example / comm / kxClient / 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    Establece un manejador externo para controlar el teclado, recoge los parametros de la operacion
39    por este y envia la peticion al servidor que devolvera el resultado de aplicar la operacion 
40    sobre los parametros recogidos.
41
42    Este proceso, a diferencia de kclient, abre una nueva conexion por cada peticion que tiene que lanzar.
43
44    El cliente de esta aplicacion es: server.p => Transporte: comm::Transport.
45 */
46 #include <iostream>
47
48 #include <string.h>
49
50 #include <anna/core/core.hpp>
51
52 #include <anna/comm/Application.hpp>
53 #include <anna/comm/Communicator.hpp>
54 #include <anna/comm/INetAddress.hpp>
55 #include <anna/comm/ClientSocket.hpp>
56 #include <anna/comm/Network.hpp>
57 #include <anna/comm/Device.hpp>
58
59 #include <anna/test/Menu.hpp>
60 #include <anna/test/Request.hpp>
61 #include <anna/test/Response.hpp>
62
63 class MyCommunicator : public comm::Communicator {
64 public:   
65    class ClientSocketAllocator {
66    public:
67       static comm::INetAddress* st_inetAddress;      
68       static comm::ClientSocket* create ()  throw () { return new comm::ClientSocket (*st_inetAddress); }
69       static void destroy (comm::ClientSocket* clientSocket) throw () { delete clientSocket; }
70    };   
71    
72 private:
73    test::Response a_response;   
74    test::Request a_request;
75    comm::INetAddress a_inetAddress;
76    Recycler <comm::ClientSocket, ClientSocketAllocator> a_clientSockets;
77
78    void do_initialize () throw (RuntimeException);
79    
80    void eventReceiveMessage (comm::ClientSocket&, const comm::Message&) throw (RuntimeException);
81    void eventBreakConnection (const comm::ClientSocket&) throw ();
82    void eventUser (const char* id, const void* context) throw ();   
83 };
84
85 class KXClient : public anna::comm::Application {
86 public:
87    KXClient ();
88       
89    const test::Menu& getMenu () const throw () { return a_menu; }
90    
91 private:
92    MyCommunicator a_communicator;
93    test::Menu a_menu;
94
95    void initialize () throw (RuntimeException);
96    void run () throw (RuntimeException);    
97 };
98
99 using namespace std;
100 using namespace test;
101
102 comm::INetAddress* MyCommunicator::ClientSocketAllocator::st_inetAddress = NULL;
103
104 int main (int argc, const char** argv)
105 {
106    CommandLine& commandLine (CommandLine::instantiate ());
107    KXClient app;
108    
109    try {
110       commandLine.initialize (argv, argc);
111       commandLine.verify ();
112
113       Logger::setLevel (Logger::Debug); 
114       Logger::initialize ("kclient", new TraceWriter ("file.trace", 4096000));
115  
116       app.start ();
117    }
118    catch (Exception& ex) {
119       cout << ex.asString () << endl;
120    }
121    
122    return 0;
123 }
124
125 KXClient::KXClient () : 
126    Application ("kclient", "KXClient", "1.0.0"),
127    a_menu (&a_communicator)
128 {
129    CommandLine& commandLine (CommandLine::instantiate ());
130       
131    commandLine.add ("p", CommandLine::Argument::Mandatory, "Puerto en el que el servidor atiende respuestas.");
132    commandLine.add ("a", CommandLine::Argument::Mandatory, "Direccion IP Puerto en el que el servidor atiende respuestas.");
133 }
134
135 void KXClient::initialize () 
136    throw (RuntimeException)
137 {
138    a_communicator.attach (&a_menu);
139 }
140
141 void KXClient::run ()
142    throw (RuntimeException)
143 {   
144    a_menu.paint ();
145    a_communicator.accept ();
146 }
147
148 //--------------------------------------------------------------------------------------------
149 // Crea la direccion a la que se conectaran los ClientSocket para enviar las peticiones.
150 //--------------------------------------------------------------------------------------------
151 void MyCommunicator::do_initialize () 
152    throw (RuntimeException)
153 {
154    CommandLine& cl (CommandLine::instantiate ());    
155
156    using namespace anna::comm;
157
158    Network& network = Network::instantiate ();
159    
160    Device* device = network.find (Device::asAddress (cl.getValue ("a")));
161    
162    a_inetAddress.setAddress (device);
163    a_inetAddress.setPort (cl.getIntegerValue ("p"));
164    
165    ClientSocketAllocator::st_inetAddress = &a_inetAddress;
166 }
167
168 void MyCommunicator::eventReceiveMessage (comm::ClientSocket&, const comm::Message& message)
169    throw (RuntimeException)
170 {
171    a_response.decode (message.getBody ());
172    
173    cout << endl << "Resultado de la peticion: " << a_response.x << (char) a_response.op << a_response.y  << " = " << a_response.result << endl << endl;
174    
175    static_cast <KXClient&> (anna::comm::functions::getApp ()).getMenu ().paint ();
176 }
177
178 //-----------------------------------------------------------------------------------------
179 // Cuando el servidor remoto cierra el socket => debemos liberar este extremo para poder
180 // reutilizar la instancia (no la conexion).
181 //-----------------------------------------------------------------------------------------
182 void MyCommunicator::eventBreakConnection (const comm::ClientSocket& clientSocket) 
183    throw ()
184 {
185    a_clientSockets.release (&clientSocket);
186 }
187
188 //-----------------------------------------------------------------------------------------
189 // Cuando el Menu tiene disponibles todos los datos necesarios para la peticiĆ³n se lo
190 // notifica al comunicador mediante un evento de usuario.
191 //-----------------------------------------------------------------------------------------
192 void MyCommunicator::eventUser (const char* id, const void* context) 
193    throw ()
194 {
195    LOGMETHOD (TraceMethod tm ("MyCommunicator", "eventUser", ANNA_FILE_LOCATION));
196
197    if (anna_strcmp (id, Menu::EventData) == 0) {
198       const Menu::Data* data (reinterpret_cast <const Menu::Data*>  (context));
199       
200       a_request.op = data->a_operation;
201       a_request.x = data->a_op1;
202       a_request.y = data->a_op2;
203       
204       comm::ClientSocket* clientSocket = a_clientSockets.create ();
205             
206       try {
207          attach (clientSocket);
208          clientSocket->send (a_request);
209       }
210       catch (RuntimeException& ex) {
211          a_clientSockets.release (clientSocket);
212          ex.trace ();
213       }
214    } 
215 }