MBSim

Project Page
objectfactory.h
00001 /* Copyright (C) 2004-2010 MBSim Development Team
00002  *
00003  * This library is free software; you can redistribute it and/or 
00004  * modify it under the terms of the GNU Lesser General Public 
00005  * License as published by the Free Software Foundation; either 
00006  * version 2.1 of the License, or (at your option) any later version. 
00007  *  
00008  * This library is distributed in the hope that it will be useful, 
00009  * but WITHOUT ANY WARRANTY; without even the implied warranty of 
00010  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
00011  * Lesser General Public License for more details. 
00012  *  
00013  * You should have received a copy of the GNU Lesser General Public 
00014  * License along with this library; if not, write to the Free Software 
00015  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA
00016  *
00017  * Contact: friedrich.at.gc@googlemail.com
00018  */
00019 
00020 #ifndef _MBSIM_OBJECTFACTORY_H_
00021 #define _MBSIM_OBJECTFACTORY_H_
00022 
00023 #include <vector>
00024 #include <stdexcept>
00025 #include <typeinfo>
00026 #ifdef HAVE_BOOST_TYPE_TRAITS_HPP
00027 # include <boost/static_assert.hpp>
00028 # include <boost/type_traits.hpp>
00029 #endif
00030 #include "mbsim/utils/utils.h"
00031 #include <mbsim/mbsim_event.h>
00032 #include <mbxmlutilshelper/utils.h>
00033 #include "fmatvec/atom.h"
00034 
00035 #define COMMA ,
00036 
00037 namespace MBSim {
00038 
00039 /* A tree of DOMEvalException's which store the tree of failed objects
00040  * creations of the object factory */
00041 class DOMEvalExceptionStack : public MBXMLUtils::DOMEvalException {
00042   public:
00043     DOMEvalExceptionStack(const xercesc::DOMElement *element) : MBXMLUtils::DOMEvalException("", element) {}
00044     DOMEvalExceptionStack(const DOMEvalExceptionStack &src) : MBXMLUtils::DOMEvalException(src), exVec(src.exVec) {}
00045     ~DOMEvalExceptionStack() throw() {}
00046     void add(const std::string &type, const boost::shared_ptr<MBXMLUtils::DOMEvalException> &ex);
00047     const char* what() const throw();
00048     std::vector<std::pair<std::string, boost::shared_ptr<MBXMLUtils::DOMEvalException> > > &getExceptionVector();
00049   protected:
00050     std::vector<std::pair<std::string, boost::shared_ptr<MBXMLUtils::DOMEvalException> > > exVec;
00051     mutable std::string whatStr;
00052     void generateWhat(std::stringstream &str, const std::string &indent) const;
00053 };
00054 
00055 /* Just to distinguish a wrong type (not castable) error of the object factory
00056  * from others */
00057 class DOMEvalExceptionWrongType : public MBXMLUtils::DOMEvalException {
00058   public:
00059     DOMEvalExceptionWrongType(const std::string &type, const xercesc::DOMElement *element) :
00060       MBXMLUtils::DOMEvalException(type, element) {}
00061     DOMEvalExceptionWrongType(const DOMEvalExceptionWrongType &src) : MBXMLUtils::DOMEvalException(src) {}
00062     ~DOMEvalExceptionWrongType() throw() {}
00063 };
00064 
00068 class ObjectFactory {
00069 
00070   public:
00071 
00075     template<class CreateType>
00076     static void registerXMLName(const MBXMLUtils::FQN &name) {
00077       registerXMLName(name, &allocate<CreateType>, &deallocate);
00078     }
00079 
00083     template<class CreateType>
00084     static void registerXMLNameAsSingleton(const MBXMLUtils::FQN &name) {
00085       registerXMLName(name, &getSingleton<CreateType>, &deallocateSingleton);
00086     }
00087 
00091     template<class CreateType>
00092     static void deregisterXMLName(const MBXMLUtils::FQN &name) {
00093       deregisterXMLName(name, &allocate<CreateType>);
00094     }
00095 
00099     template<class CreateType>
00100     static void deregisterXMLNameAsSingleton(const MBXMLUtils::FQN &name) {
00101       deregisterXMLName(name, &getSingleton<CreateType>);
00102     }
00103 
00107     template<class ContainerType>
00108     static ContainerType* createAndInit(const xercesc::DOMElement *element) {
00109 #ifdef HAVE_BOOST_TYPE_TRAITS_HPP
00110       // just check if ContainerType is derived from fmatvec::Atom if not throw a compile error if boost is avaliable
00111       // if boost is not avaliable a runtime error will occure later. (so it does not care if boost is not available)
00112       BOOST_STATIC_ASSERT_MSG((boost::is_convertible<ContainerType*, fmatvec::Atom*>::value),
00113         "In MBSim::ObjectFactory::create<ContainerType>(...) ContainerType must be derived from fmatvec::Atom.");
00114 #endif
00115       // throw error if NULL is supplied as element
00116       if(element==NULL)
00117         throw MBSimError("Internal error: NULL argument specified.");
00118       // get all allocate functions for the given name
00119       MBXMLUtils::FQN fqn=MBXMLUtils::E(element)->getTagName();
00120       NameMapIt nameIt=instance().registeredType.find(fqn);
00121       if(nameIt==instance().registeredType.end())
00122         throw MBXMLUtils::DOMEvalException("Internal error: No objects of name {"+fqn.first+"}"+fqn.second+" registred", element);
00123       DOMEvalExceptionStack allErrors(static_cast<xercesc::DOMElement*>(element->getParentNode()));
00124       // try to create and init a object which each of the allocate function
00125       for(AllocDeallocVectorIt allocDeallocIt=nameIt->second.begin(); allocDeallocIt!=nameIt->second.end(); ++allocDeallocIt) {
00126         // create element
00127         fmatvec::Atom *ele=allocDeallocIt->first();
00128         // try to cast the element to ContainerType
00129         ContainerType *ret=dynamic_cast<ContainerType*>(ele);
00130         if(!ret) {
00131           // cast not possible -> deallocate again and try next
00132           allErrors.add(MBXMLUtils::demangleSymbolName(typeid(*ele).name()),
00133                         boost::make_shared<DOMEvalExceptionWrongType>(
00134                         MBXMLUtils::demangleSymbolName(typeid(ContainerType).name()), element));
00135           allocDeallocIt->second(ele); 
00136           continue;
00137         }
00138         try {
00139           ret->initializeUsingXML(const_cast<xercesc::DOMElement*>(element));
00140           return ret;
00141         }
00142         catch(DOMEvalExceptionStack &ex) {
00143           allErrors.add(MBXMLUtils::demangleSymbolName(typeid(*ele).name()), boost::make_shared<DOMEvalExceptionStack>(ex));
00144         }
00145         catch(MBXMLUtils::DOMEvalException &ex) {
00146           allErrors.add(MBXMLUtils::demangleSymbolName(typeid(*ele).name()), boost::make_shared<MBXMLUtils::DOMEvalException>(ex));
00147         }
00148         catch(std::exception &ex) { // handles also MBSimError
00149           allErrors.add(MBXMLUtils::demangleSymbolName(typeid(*ele).name()),
00150                         boost::make_shared<MBXMLUtils::DOMEvalException>(ex.what(), element));
00151         }
00152         catch(...) {
00153           allErrors.add(MBXMLUtils::demangleSymbolName(typeid(*ele).name()),
00154                         boost::make_shared<MBXMLUtils::DOMEvalException>("Unknwon exception", element));
00155         }
00156         allocDeallocIt->second(ele);
00157       }
00158       // if all failed -> return errors of all trys
00159       throw allErrors;
00160     }
00161 
00162   private:
00163 
00164     // a pointer to a function allocating an object
00165     typedef fmatvec::Atom* (*AllocateFkt)();
00166     // a pointer to a function deallocating an object
00167     typedef void (*DeallocateFkt)(fmatvec::Atom *obj);
00168 
00169     // convinence typedefs
00170     typedef std::vector<std::pair<AllocateFkt, DeallocateFkt> > AllocDeallocVector;
00171     typedef AllocDeallocVector::iterator AllocDeallocVectorIt;
00172     typedef std::map<MBXMLUtils::FQN, AllocDeallocVector> NameMap;
00173     typedef NameMap::iterator NameMapIt;
00174 
00175     // private ctor
00176     ObjectFactory() {}
00177 
00178     static void registerXMLName(const MBXMLUtils::FQN &name, AllocateFkt alloc, DeallocateFkt dealloc);
00179 
00180     static void deregisterXMLName(const MBXMLUtils::FQN &name, AllocateFkt alloc);
00181 
00182     // create an singleton instance of the object factory.
00183     // only declaration here and defition and explicit instantation for all fmatvec::Atom in objectfactory.cc (required for Windows)
00184     static ObjectFactory& instance();
00185 
00186     // a vector of all registered types
00187     NameMap registeredType;
00188 
00189     // a wrapper to allocate an object of type CreateType
00190     template<class CreateType>
00191     static fmatvec::Atom* allocate() {
00192       return new CreateType;
00193     }
00194 
00195     // a wrapper to deallocate an object created by allocate
00196     static void deallocate(fmatvec::Atom *obj) {
00197       delete obj;
00198     }
00199 
00200     // a wrapper to get an singleton object of type CreateType (Must have the same signature as allocate()
00201     template<class CreateType>
00202     static fmatvec::Atom* getSingleton() {
00203       return CreateType::getInstance();
00204     }
00205 
00206     // a wrapper to "deallocate" an singleton object (Must have the same signature as deallocate()
00207     static void deallocateSingleton(fmatvec::Atom *obj) {
00208       // just do nothing for singletons
00209     }
00210 
00211 };
00212 
00216 template<class CreateType>
00217 class ObjectFactoryRegisterXMLNameHelper {
00218 
00219   public:
00220 
00222     ObjectFactoryRegisterXMLNameHelper(const MBXMLUtils::FQN &name_) : name(name_) {
00223       ObjectFactory::template registerXMLName<CreateType>(name);
00224     };
00225 
00227     ~ObjectFactoryRegisterXMLNameHelper() {
00228       ObjectFactory::template deregisterXMLName<CreateType>(name);
00229     };
00230 
00231   private:
00232     MBXMLUtils::FQN name;
00233 
00234 };
00235 
00239 template<class CreateType>
00240 class ObjectFactoryRegisterXMLNameHelperAsSingleton {
00241 
00242   public:
00243 
00245     ObjectFactoryRegisterXMLNameHelperAsSingleton(const MBXMLUtils::FQN &name_) : name(name_) {
00246       ObjectFactory::template registerXMLNameAsSingleton<CreateType>(name);
00247     };
00248 
00250     ~ObjectFactoryRegisterXMLNameHelperAsSingleton() {
00251       ObjectFactory::template deregisterXMLNameAsSingleton<CreateType>(name);
00252     };
00253 
00254   private:
00255     MBXMLUtils::FQN name;
00256 
00257 };
00258 
00259 }
00260 
00261 #define MBSIM_OBJECTFACTORY_CONCAT1(X, Y) X##Y
00262 #define MBSIM_OBJECTFACTORY_CONCAT(X, Y) MBSIM_OBJECTFACTORY_CONCAT1(X, Y)
00263 #define MBSIM_OBJECTFACTORY_APPENDLINE(X) MBSIM_OBJECTFACTORY_CONCAT(X, __LINE__)
00264 
00268 #define MBSIM_OBJECTFACTORY_REGISTERXMLNAME(ThisType, name) \
00269   static MBSim::ObjectFactoryRegisterXMLNameHelper<ThisType> \
00270     MBSIM_OBJECTFACTORY_APPENDLINE(objectFactoryRegistrationDummyVariable)(name);
00271 
00275 #define MBSIM_OBJECTFACTORY_REGISTERXMLNAMEASSINGLETON(ThisType, name) \
00276   static MBSim::ObjectFactoryRegisterXMLNameHelperAsSingleton<ThisType> \
00277     MBSIM_OBJECTFACTORY_APPENDLINE(objectFactoryRegistrationDummyVariableAsSingleTon)(name);
00278 
00281 #define MBSIM_OBJECTFACTORY_REGISTERXMLNAME_AND_INSTANTIATE(ThisType, name) \
00282   template class ThisType; \
00283   static MBSim::ObjectFactoryRegisterXMLNameHelper<ThisType> \
00284     MBSIM_OBJECTFACTORY_APPENDLINE(objectFactoryRegistrationDummyVariable)(name);
00285 
00288 #define MBSIM_OBJECTFACTORY_REGISTERXMLNAMEASSINGLETON_AND_INSTANTIATE(ThisType, name) \
00289   template class ThisType; \
00290   static MBSim::ObjectFactoryRegisterXMLNameHelperAsSingleton<ThisType> \
00291     MBSIM_OBJECTFACTORY_APPENDLINE(objectFactoryRegistrationDummyVariableAsSingleTon)(name);
00292 
00293 #endif