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 <boost/tuple/tuple_io.hpp>
00024 #include <vector>
00025 #include <stdexcept>
00026 #include <typeinfo>
00027 #ifdef HAVE_BOOST_TYPE_TRAITS_HPP
00028 # include <boost/static_assert.hpp>
00029 # include <boost/type_traits.hpp>
00030 #endif
00031 #include "mbsim/utils/utils.h"
00032 #include <mbsim/mbsim_event.h>
00033 #include <mbxmlutilshelper/utils.h>
00034 #include "fmatvec/atom.h"
00035 
00036 #define COMMA ,
00037 
00038 namespace MBSim {
00039 
00040 class ObjectFactoryNoObject : public MBXMLUtils::DOMEvalException {
00041   public:
00042     ObjectFactoryNoObject(const xercesc::DOMElement *e_, const std::type_info &cppType_) throw() :
00043       MBXMLUtils::DOMEvalException("Unable to create an object with name <"+MBXMLUtils::X()%e_->getTagName()+"> which is of the requested type "+
00044         MBXMLUtils::demangleSymbolName(cppType_.name())+".", e_) {
00045     }
00046     virtual ~ObjectFactoryNoObject() throw() {}
00047 };
00048 
00052 class ObjectFactory {
00053 
00054   public:
00055 
00059     template<class CreateType>
00060     static void registerXMLName(const MBXMLUtils::FQN &name) {
00061       registerXMLName(name, &allocate<CreateType>, &deallocate);
00062     }
00063 
00067     template<class CreateType>
00068     static void registerXMLNameAsSingleton(const MBXMLUtils::FQN &name) {
00069       registerXMLName(name, &getSingleton<CreateType>, &deallocateSingleton);
00070     }
00071 
00075     template<class CreateType>
00076     static void deregisterXMLName(const MBXMLUtils::FQN &name) {
00077       deregisterXMLName(name, &allocate<CreateType>);
00078     }
00079 
00083     template<class CreateType>
00084     static void deregisterXMLNameAsSingleton(const MBXMLUtils::FQN &name) {
00085       deregisterXMLName(name, &getSingleton<CreateType>);
00086     }
00087 
00091     template<class ContainerType>
00092     static ContainerType* createAndInit(const xercesc::DOMElement *element) {
00093       size_t useMatchNr=1;
00094       std::vector<std::string> error;
00095       do {
00096         std::pair<ContainerType*, DeallocateFkt> p=std::pair<ContainerType*, DeallocateFkt>(NULL, &deallocateSingleton);
00097         try {
00098           p=create<ContainerType>(element, useMatchNr++);
00099           p.first->initializeUsingXML(const_cast<xercesc::DOMElement*>(element));
00100           return p.first;
00101         }
00102         catch(const ObjectFactoryNoObject &ex) {
00103           // delete the created object using the provided deallocater (calls delete or nothing for singletons)
00104           p.second(p.first);
00105           // save exception, only if this is the first exception during this run (this error has a very low priority)
00106           if(error.size()==0)
00107             error.push_back(ex.what());
00108           // break if useMatchNr number is larger then the factory size: nothing found which can be initialized.
00109           if(useMatchNr>instance().registeredType.size()) {
00110             std::string message;
00111             // collect the message of all previous errors and throw them all!
00112             for(std::vector<std::string>::iterator it=error.begin(); it!=error.end(); it++) {
00113               std::vector<std::string>::iterator it2=it; it2++;
00114               message+=*it+(it2!=error.end()?"\n":"");
00115             }
00116             throw MBSimError(message);
00117           }
00118         }
00119         catch(const MBSimError &ex) {
00120           // delete the created object using the provided deallocater (calls delete or nothing for singletons)
00121           p.second(p.first);
00122           // save exception: it is rethrow (including others) alter if everything fails
00123           error.push_back(ex.what());
00124         }
00125       }
00126       while(true); // loop until we are able to create and init a object without errors
00127     }
00128 
00129   private:
00130 
00131     // a pointer to a function allocating an object
00132     typedef fmatvec::Atom* (*AllocateFkt)();
00133     // a pointer to a function deallocating an object
00134     typedef void (*DeallocateFkt)(fmatvec::Atom *obj);
00135 
00139     template<class ContainerType>
00140     static std::pair<ContainerType*, DeallocateFkt> create(const xercesc::DOMElement *element, size_t useMatchNr=1) {
00141 #ifdef HAVE_BOOST_TYPE_TRAITS_HPP
00142       // just check if ContainerType is derived from fmatvec::Atom if not throw a compile error if boost is avaliable
00143       // if boost is not avaliable a runtime error will occure later. (so it does not care if boost is not available)
00144       BOOST_STATIC_ASSERT_MSG((boost::is_convertible<ContainerType*, fmatvec::Atom*>::value),
00145         "In MBSim::ObjectFactory::create<ContainerType>(...) ContainerType must be derived from fmatvec::Atom.");
00146 #endif
00147       // throw error if NULL is supplied as element
00148       if(element==NULL) throw MBSimError("Internal error: NULL argument specified.");
00149       // loop over all all registred types corresponding to element->ValueStr()
00150       size_t matchNr=1;
00151       for(VectorIt it=instance().registeredType.begin(); it!=instance().registeredType.end(); it++) {
00152         // skip type with wrong key value get<0>()
00153         
00154         if(it->template get<0>()!=MBXMLUtils::E(element)->getTagName()) continue;
00155 
00156         // allocate a new object OR get singleton object using the allocate function pointer
00157         fmatvec::Atom *ele=it->template get<1>()();
00158         // try to cast ele up to ContainerType
00159         ContainerType *ret=dynamic_cast<ContainerType*>(ele);
00160         // if possible (and it is the useMatchNr'st element, return it
00161         if(ret && (matchNr++)==useMatchNr)
00162           return std::pair<ContainerType*, DeallocateFkt>(ret, it->template get<2>());
00163         // if not possible, deallocate newly created (wrong) object OR do nothing for
00164         // singleton objects (is maybe reused later) and continue searching
00165         else
00166           it->template get<2>()(ele);
00167       }
00168       // no matching element found: throw error
00169       throw ObjectFactoryNoObject(element, typeid(ContainerType));
00170     }
00171 
00172     // convinence typedefs
00173     typedef boost::tuple<MBXMLUtils::FQN, AllocateFkt, DeallocateFkt> VectorContent;
00174     typedef std::vector<VectorContent> Vector;
00175     typedef typename Vector::iterator VectorIt;
00176 
00177     // private ctor
00178     ObjectFactory() {}
00179 
00180     static void registerXMLName(const MBXMLUtils::FQN &name, AllocateFkt alloc, DeallocateFkt dealloc);
00181 
00182     static void deregisterXMLName(const MBXMLUtils::FQN &name, AllocateFkt alloc);
00183 
00184     // create an singleton instance of the object factory.
00185     // only declaration here and defition and explicit instantation for all fmatvec::Atom in objectfactory.cc (required for Windows)
00186     static ObjectFactory& instance();
00187 
00188     // a vector of all registered types
00189     Vector registeredType;
00190 
00191     // a wrapper to allocate an object of type CreateType
00192     template<class CreateType>
00193     static fmatvec::Atom* allocate() {
00194       return new CreateType;
00195     }
00196 
00197     // a wrapper to deallocate an object created by allocate
00198     static void deallocate(fmatvec::Atom *obj) {
00199       delete obj;
00200     }
00201 
00202     // a wrapper to get an singleton object of type CreateType (Must have the same signature as allocate()
00203     template<class CreateType>
00204     static fmatvec::Atom* getSingleton() {
00205       return CreateType::getInstance();
00206     }
00207 
00208     // a wrapper to "deallocate" an singleton object (Must have the same signature as deallocate()
00209     static void deallocateSingleton(fmatvec::Atom *obj) {
00210       // just do nothing for singletons
00211     }
00212 
00213 };
00214 
00218 template<class CreateType>
00219 class ObjectFactoryRegisterXMLNameHelper {
00220 
00221   public:
00222 
00224     ObjectFactoryRegisterXMLNameHelper(const MBXMLUtils::FQN &name_) : name(name_) {
00225       ObjectFactory::template registerXMLName<CreateType>(name);
00226     };
00227 
00229     ~ObjectFactoryRegisterXMLNameHelper() {
00230       ObjectFactory::template deregisterXMLName<CreateType>(name);
00231     };
00232 
00233   private:
00234     MBXMLUtils::FQN name;
00235 
00236 };
00237 
00241 template<class CreateType>
00242 class ObjectFactoryRegisterXMLNameHelperAsSingleton {
00243 
00244   public:
00245 
00247     ObjectFactoryRegisterXMLNameHelperAsSingleton(const MBXMLUtils::FQN &name_) : name(name_) {
00248       ObjectFactory::template registerXMLNameAsSingleton<CreateType>(name);
00249     };
00250 
00252     ~ObjectFactoryRegisterXMLNameHelperAsSingleton() {
00253       ObjectFactory::template deregisterXMLNameAsSingleton<CreateType>(name);
00254     };
00255 
00256   private:
00257     MBXMLUtils::FQN name;
00258 
00259 };
00260 
00261 }
00262 
00263 #define MBSIM_OBJECTFACTORY_CONCAT1(X, Y) X##Y
00264 #define MBSIM_OBJECTFACTORY_CONCAT(X, Y) MBSIM_OBJECTFACTORY_CONCAT1(X, Y)
00265 #define MBSIM_OBJECTFACTORY_APPENDLINE(X) MBSIM_OBJECTFACTORY_CONCAT(X, __LINE__)
00266 
00270 #define MBSIM_OBJECTFACTORY_REGISTERXMLNAME(ThisType, name) \
00271   static MBSim::ObjectFactoryRegisterXMLNameHelper<ThisType> \
00272     MBSIM_OBJECTFACTORY_APPENDLINE(objectFactoryRegistrationDummyVariable)(name);
00273 
00277 #define MBSIM_OBJECTFACTORY_REGISTERXMLNAMEASSINGLETON(ThisType, name) \
00278   static MBSim::ObjectFactoryRegisterXMLNameHelperAsSingleton<ThisType> \
00279     MBSIM_OBJECTFACTORY_APPENDLINE(objectFactoryRegistrationDummyVariableAsSingleTon)(name);
00280 
00281 #endif