1 //
2 // Copyright (C) 2016 Google, Inc.
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at:
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16
17 #include <rapidjson/document.h>
18 #include <rapidjson/writer.h>
19 #include <rapidjson/stringbuffer.h>
20 #include <map>
21 #include <string>
22 #include <tuple>
23
24 #include <base.h>
25 #include <utils/command_receiver.h>
26 #include <utils/common_utils.h>
27
28 typedef std::map<std::string, MFP> function_map;
29 function_map* _funcMap = NULL;
30
_clean_result(rapidjson::Document & doc)31 void _clean_result(rapidjson::Document &doc) {
32 doc.RemoveMember(sl4n::kMethodStr);
33 doc.RemoveMember(sl4n::kParamsStr);
34 }
35
initiate(rapidjson::Document & doc)36 void initiate(rapidjson::Document &doc) {
37 doc.AddMember(sl4n::kStatusStr, sl4n::kSuccessStr, doc.GetAllocator());
38 }
39
CommandReceiver()40 CommandReceiver::CommandReceiver() {
41 if (_funcMap == NULL) {
42 _funcMap = new function_map();
43 }
44 _funcMap->insert(std::make_pair("initiate", &initiate));
45 _funcMap->insert(std::make_pair("continue", &initiate));
46 }
47
Call(rapidjson::Document & doc)48 void CommandReceiver::Call(rapidjson::Document& doc) {
49 std::string cmd;
50 if (doc.HasMember(sl4n::kCmdStr)) {
51 cmd = doc[sl4n::kCmdStr].GetString();
52 } else if (doc.HasMember(sl4n::kMethodStr)) {
53 cmd = doc[sl4n::kMethodStr].GetString();
54 }
55
56 function_map::const_iterator iter = _funcMap->find(cmd);
57 if (iter != _funcMap->end()) {
58 iter->second(doc);
59 }
60 _clean_result(doc);
61 }
62
RegisterCommand(std::string name,MFP command)63 void CommandReceiver::RegisterCommand(std::string name, MFP command) {
64 if (_funcMap == NULL) {
65 _funcMap = new function_map();
66 }
67
68 _funcMap->insert(std::make_pair(name, command));
69 }
70