mbsim  4.0.0
MBSim Kernel
objectfactory.h
1 /* Copyright (C) 2004-2010 MBSim Development Team
2  *
3  * This library is free software; you can redistribute it and/or
4  * modify it under the terms of the GNU Lesser General Public
5  * License as published by the Free Software Foundation; either
6  * version 2.1 of the License, or (at your option) any later version.
7  *
8  * This library is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11  * Lesser General Public License for more details.
12  *
13  * You should have received a copy of the GNU Lesser General Public
14  * License along with this library; if not, write to the Free Software
15  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16  *
17  * Contact: friedrich.at.gc@googlemail.com
18  */
19 
20 #ifndef _MBSIM_OBJECTFACTORY_H_
21 #define _MBSIM_OBJECTFACTORY_H_
22 
23 #include "objectfactory_part.h"
24 #include <utility>
25 #include <vector>
26 #include <functional>
27 #include <stdexcept>
28 #include <typeinfo>
29 #include <mbsim/mbsim_event.h>
30 #include <xercesc/dom/DOMAttr.hpp>
31 #include <mbxmlutilshelper/utils.h>
32 #include "fmatvec/atom.h"
33 #include <boost/core/demangle.hpp>
34 
35 namespace MBSim {
36 
37 /* A tree of DOMEvalException's which store the tree of failed objects
38  * creations of the object factory */
40  public:
41  DOMEvalExceptionStack(const xercesc::DOMElement *element) : MBXMLUtils::DOMEvalException("", element) {}
42  DOMEvalExceptionStack(const DOMEvalExceptionStack &src) : MBXMLUtils::DOMEvalException(src), exVec(src.exVec) {}
43  ~DOMEvalExceptionStack() noexcept override = default;
44  void add(const std::string &type, const std::shared_ptr<MBXMLUtils::DOMEvalException> &ex);
45  const char* what() const noexcept override;
46  std::vector<std::pair<std::string, std::shared_ptr<MBXMLUtils::DOMEvalException>>> &getExceptionVector();
47  protected:
48  std::vector<std::pair<std::string, std::shared_ptr<MBXMLUtils::DOMEvalException>>> exVec;
49  mutable std::string whatStr;
50  void generateWhat(std::stringstream &str, const std::string &indent) const;
51 };
52 
53 /* Just to distinguish a wrong type (not castable) error of the object factory
54  * from others */
56  public:
57  DOMEvalExceptionWrongType(const std::string &type, const xercesc::DOMElement *element) :
58  MBXMLUtils::DOMEvalException(type, element) {}
60  ~DOMEvalExceptionWrongType() noexcept override = default;
61 };
62 
67 
68  friend void registerClass_internal(const MBXMLUtils::FQN &name, const AllocateBase *alloc, const DeallocateBase *dealloc);
69  friend void deregisterClass_internal(const MBXMLUtils::FQN &name, const AllocateBase *alloc);
70 
71  public:
72 
75  template<class ContainerType>
76  static ContainerType* createAndInit(const xercesc::DOMElement *element) {
77  // just check if ContainerType is derived from fmatvec::Atom if not throw a compile error
78  static_assert(std::is_convertible<ContainerType*, fmatvec::Atom*>::value,
79  "In MBSim::ObjectFactory::create<ContainerType>(...) ContainerType must be derived from fmatvec::Atom.");
80  // throw error if NULL is supplied as element
81  if(element==nullptr)
82  throw std::runtime_error("Internal error: NULL argument specified.");
83  // get all allocate functions for the given name
84  MBXMLUtils::FQN fqn=MBXMLUtils::E(element)->getTagName();
85  auto nameIt=instance().registeredType.find(fqn);
86  if(nameIt==instance().registeredType.end())
87  throw MBXMLUtils::DOMEvalException("Internal error: No objects of name {"+fqn.first+"}"+fqn.second+" registred", element);
88  DOMEvalExceptionStack allErrors(static_cast<xercesc::DOMElement*>(element->getParentNode()));
89  // try to create and init a object which each of the allocate function
90  for(auto & allocDeallocIt : nameIt->second) {
91  // create element
92  fmatvec::Atom *ele=(*allocDeallocIt.first)();
93  // try to cast the element to ContainerType
94  auto *ret=dynamic_cast<ContainerType*>(ele);
95  if(!ret) {
96  // cast not possible -> deallocate again and try next
97  allErrors.add(boost::core::demangle(typeid(*ele).name()),
98  std::make_shared<DOMEvalExceptionWrongType>(
99  boost::core::demangle(typeid(ContainerType).name()), element));
100  (*allocDeallocIt.second)(ele);
101  continue;
102  }
103  try {
104  ret->initializeUsingXML(const_cast<xercesc::DOMElement*>(element));
105  return ret;
106  }
107  catch(DOMEvalExceptionStack &ex) {
108  allErrors.add(boost::core::demangle(typeid(*ele).name()), std::make_shared<DOMEvalExceptionStack>(ex));
109  }
110  catch(MBXMLUtils::DOMEvalException &ex) {
111  allErrors.add(boost::core::demangle(typeid(*ele).name()), std::make_shared<MBXMLUtils::DOMEvalException>(ex));
112  }
113  catch(std::exception &ex) { // handles also MBSimError
114  allErrors.add(boost::core::demangle(typeid(*ele).name()),
115  std::make_shared<MBXMLUtils::DOMEvalException>(ex.what(), element));
116  }
117  catch(...) {
118  allErrors.add(boost::core::demangle(typeid(*ele).name()),
119  std::make_shared<MBXMLUtils::DOMEvalException>("Unknwon exception", element));
120  }
121  (*allocDeallocIt.second)(ele);
122  }
123  // if all failed -> return errors of all trys
124  throw allErrors;
125  }
126 
127  private:
128 
129  // convinence typedefs
130  typedef std::pair<const AllocateBase*, const DeallocateBase*> AllocDeallocPair;
131  typedef std::vector<AllocDeallocPair> AllocDeallocVector;
132  typedef AllocDeallocVector::iterator AllocDeallocVectorIt;
133  typedef std::map<MBXMLUtils::FQN, AllocDeallocVector> NameMap;
134  typedef NameMap::iterator NameMapIt;
135 
136  // private ctor
137  ObjectFactory() = default;
138 
139  // create an singleton instance of the object factory.
140  static ObjectFactory& instance();
141 
142  // a vector of all registered types
143  NameMap registeredType;
144 };
145 
146 // a wrapper to allocate an object of type CreateType
147 template<class CreateType>
148 struct Allocate : public AllocateBase {
149  // create a new object of type CreateType using new
150  fmatvec::Atom* operator()() const override {
151  return new CreateType;
152  }
153  // check if this Allocator allocates the same object as other.
154  // This is the case if the type of this template class matches
155  // the type of other.
156  bool isEqual(const AllocateBase& other) const override {
157  return typeid(*this)==typeid(other);
158  }
159 };
160 
161 // a wrapper to deallocate an object created by allocate
162 struct Deallocate : public DeallocateBase {
163  // deallocate a object using delete
164  void operator()(fmatvec::Atom *obj) const override {
165  delete obj;
166  }
167 };
168 
172 template<class CreateType>
174 
175  public:
176 
178  ObjectFactoryRegisterClassHelper(MBXMLUtils::FQN name_) : name(std::move(name_)) {
179  MBSim::registerClass_internal(name, new Allocate<CreateType>(), new Deallocate());
180  }
181 
184  MBSim::deregisterClass_internal(name, new Allocate<CreateType>());
185  }
186 
187  private:
188  MBXMLUtils::FQN name;
189 
190 };
191 
195 template<class EnumType>
196 class EnumFactory {
197 
198  template<class EV> friend void registerEnum_internal(const MBXMLUtils::FQN &name, const EV& value);
199  template<class EV> friend void deregisterEnum_internal(const MBXMLUtils::FQN &name);
200 
201  public:
202 
204  EnumFactory(const EnumType &enumVar, MBXMLUtils::FQN fqn_) : fqn(std::move(fqn_)) {
205  registerEnum_internal<EnumType>(fqn, enumVar);
206  }
207 
210  deregisterEnum_internal<EnumType>(fqn);
211  }
212 
214  static const EnumType& get(const MBXMLUtils::FQN &fqn, const xercesc::DOMElement *e=nullptr) {
215  auto it=regmap().find(fqn);
216  if(it==regmap().end())
217  throw MBXMLUtils::DOMEvalException("No enumeration value named {"+fqn.first+"}"+fqn.second+" registred", e);
218  return it->second.get();
219  }
220 
221  private:
222  MBXMLUtils::FQN fqn;
223 
224  // return the register map of the enum factory.
225  // (note: this function must not be defined in this file to avoid any imlicit instantation)
226  static std::map<MBXMLUtils::FQN, std::reference_wrapper<const EnumType>>& regmap();
227 };
228 
229 template<class EV>
230 void registerEnum_internal(const MBXMLUtils::FQN &name, const EV& value) {
231  EnumFactory<EV>::regmap().insert(std::make_pair(name, std::ref(value)));
232 }
233 
234 template<class EV>
235 void deregisterEnum_internal(const MBXMLUtils::FQN &name) {
236  EnumFactory<EV>::regmap().erase(name);
237 }
238 
239 // fix local xml name (remove template and namespace)
240 std::string fixXMLLocalName(std::string name);
241 
242 }
243 
244 #define MBSIM_OBJECTFACTORY_CONCAT1(X, Y) X##Y
245 #define MBSIM_OBJECTFACTORY_CONCAT(X, Y) MBSIM_OBJECTFACTORY_CONCAT1(X, Y)
246 #define MBSIM_OBJECTFACTORY_APPENDLINE(X) MBSIM_OBJECTFACTORY_CONCAT(X, __LINE__)
247 
251 #define MBSIM_OBJECTFACTORY_REGISTERCLASS(NS, Class) \
252  static MBSim::ObjectFactoryRegisterClassHelper<Class> \
253  MBSIM_OBJECTFACTORY_APPENDLINE(objectFactoryRegistrationDummyVariable)((NS)%MBSim::fixXMLLocalName(#Class));
254 
257 #define MBSIM_OBJECTFACTORY_REGISTERCLASS_AND_INSTANTIATE(NS, Class) \
258  template class Class; \
259  static MBSim::ObjectFactoryRegisterClassHelper<Class> \
260  MBSIM_OBJECTFACTORY_APPENDLINE(objectFactoryRegistrationDummyVariable)((NS)%MBSim::fixXMLLocalName(#Class));
261 
264 #define MBSIM_OBJECTFACTORY_REGISTERCLASSWITHTEMPLATENAME_AND_INSTANTIATE(NS, Class, TemplateName) \
265  template class Class; \
266  static MBSim::ObjectFactoryRegisterClassHelper<Class> \
267  MBSIM_OBJECTFACTORY_APPENDLINE(objectFactoryRegistrationDummyVariable)((NS)%(MBSim::fixXMLLocalName(#Class)+"_"+#TemplateName));
268 
270 #define MBSIM_OBJECTFACTORY_REGISTERENUM(EnumType, NS, enumName) \
271  static MBSim::EnumFactory<EnumType> \
272  MBSIM_OBJECTFACTORY_APPENDLINE(objectFactoryRegistrationDummyVariable)(enumName, (NS)%#enumName);
273 
274 #endif
EnumFactory(const EnumType &enumVar, MBXMLUtils::FQN fqn_)
Definition: objectfactory.h:204
Definition: objectfactory.h:39
Definition: objectfactory.h:173
~ObjectFactoryRegisterClassHelper()
Definition: objectfactory.h:183
static const EnumType & get(const MBXMLUtils::FQN &fqn, const xercesc::DOMElement *e=nullptr)
Definition: objectfactory.h:214
Definition: objectfactory_part.h:49
Definition: objectfactory.h:148
ObjectFactoryRegisterClassHelper(MBXMLUtils::FQN name_)
Definition: objectfactory.h:178
~EnumFactory()
Definition: objectfactory.h:209
Definition: objectfactory.h:162
Definition: objectfactory.h:66
Definition: objectfactory_part.h:37
Definition: objectfactory.h:55
static ContainerType * createAndInit(const xercesc::DOMElement *element)
Definition: objectfactory.h:76
fmatvec::Atom * operator()() const override
Implement this function to allocate a new object.
Definition: objectfactory.h:150
Definition: objectfactory.h:196
void operator()(fmatvec::Atom *obj) const override
Implement this function to deallocate the object obj.
Definition: objectfactory.h:164
namespace MBSim
Definition: bilateral_constraint.cc:29
bool isEqual(const AllocateBase &other) const override
Definition: objectfactory.h:156