libt2n: (gerd) basic command handling (still some todos)
[libt2n] / src / command_server.cpp
CommitLineData
7087e187
GE
1/***************************************************************************
2 * Copyright (C) 2006 by Gerd v. Egidy *
3 * gve@intra2net.com *
4 * *
5 * This library is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU Lesser General Public License version *
7 * 2.1 as published by the Free Software Foundation. *
8 * *
9 * This library is distributed in the hope that it will be useful, *
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
12 * GNU Lesser General Public License for more details. *
13 * *
14 * You should have received a copy of the GNU Lesser General Public *
15 * License along with this program; if not, write to the *
16 * Free Software Foundation, Inc., *
17 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
18 ***************************************************************************/
19
20#include <string>
21#include <sstream>
22#include <stdexcept>
23
24#include <boost/archive/binary_oarchive.hpp>
25#include <boost/archive/binary_iarchive.hpp>
26#include <boost/archive/xml_oarchive.hpp>
27#include <boost/archive/xml_iarchive.hpp>
28#include <boost/serialization/serialization.hpp>
29#include <boost/serialization/export.hpp>
30
31#include "command_server.hxx"
32#include "container.hxx"
33
34using namespace std;
35
36namespace libt2n
37{
38
39/// handle a command including deserialization and answering
40void command_server::handle_packet(const std::string& packet, server_connection* conn)
41{
42 // deserialize packet
43 istringstream ifs(packet);
44 boost::archive::binary_iarchive ia(ifs);
45 command_container ccont;
46
47 // TODO: catch
48 ia >> ccont;
49
50 // TODO: cast to command subclass (template)
51 command *cmd=ccont.get_command();
52
53 result_container res;
54
55 if (cmd)
56 {
57 try
58 {
59 res.set_result((*cmd)());
60 }
61 catch (t2n_exception &e)
62 { res.set_exception(e.clone()); }
63 catch (...)
64 { throw; }
65 }
66 else
67 throw logic_error("uninitialized command called");
68
69 ostringstream ofs;
70 boost::archive::binary_oarchive oa(ofs);
71
72 // TODO: catch
73 oa << res;
74
75 conn->write(ofs.str());
76}
77
78/** @brief handle incoming commands
79 @param usec_timeout wait until new data is found, max timeout usecs.
80 -1: wait endless, 0: no timeout
81*/
82void command_server::handle(long long usec_timeout)
83{
84 if (s.fill_buffer(usec_timeout))
85 {
86 string packet;
87 unsigned int conn_id;
88
89 while (s.get_packet(packet,conn_id))
90 handle_packet(packet,s.get_connection(conn_id));
91 }
92 s.cleanup();
93}
94
95}