1
2
3
4
5
6 #include <cmajor/build/Message.hpp>
7
8 namespace cmajor { namespace build {
9
10 MessageBase::~MessageBase()
11 {
12 }
13
14 MessageCreator::~MessageCreator()
15 {
16 }
17
18 MessageFactory::MessageFactory()
19 {
20 }
21
22 std::unique_ptr<MessageFactory> MessageFactory::instance;
23
24 void MessageFactory::Init()
25 {
26 instance.reset(new MessageFactory());
27 }
28
29 void MessageFactory::Done()
30 {
31 instance.reset();
32 }
33
34 void MessageFactory::Register(const char* messageId, MessageCreator* messageCreator)
35 {
36 creatorMap[messageId] = messageCreator;
37 creators.push_back(std::unique_ptr<MessageCreator>(messageCreator));
38 }
39
40 std::std::unique_ptr<MessageBase>MessageFactory::CreateMessage(soulng::util::JsonObject*messageObject)
41 {
42 soulng::util::JsonValue* idField = messageObject->GetField(U"id");
43 if (idField)
44 {
45 if (idField->Type() == soulng::util::JsonValueType::string)
46 {
47 soulng::util::JsonString* idStr = static_cast<soulng::util::JsonString*>(idField);
48 std::string id = ToUtf8(idStr->Value());
49 auto it = creatorMap.find(id);
50 if (it != creatorMap.cend())
51 {
52 MessageCreator* creator = it->second;
53 return creator->CreateMessage(messageObject);
54 }
55 else
56 {
57 throw std::runtime_error("message factory error: could not create message, no creator for id '" + id + "'");
58 }
59 }
60 else
61 {
62 throw std::runtime_error("message factory error: could not create message, id field not a JSON string");
63 }
64 }
65 else
66 {
67 throw std::runtime_error("message factory error: could not create message, id field missing");
68 }
69 }
70
71 void MessageInit()
72 {
73 MessageFactory::Init();
74 }
75
76 void MessageDone()
77 {
78 MessageFactory::Done();
79 }
80
81 } }