Config.h

Go to the documentation of this file.
00001 #ifndef __CONFIG_H__
00002 #define __CONFIG_H__
00003 
00004 /*
00005 
00006 $Header$
00007 
00008 */
00009 
00010 #include <map>
00011 
00012 #include "Singleton.h"
00013 #include "S11n.h"
00014 #include "BuildInfo.h"
00015 #include "XmlDocument.h"
00016 #include "XmlRegistryElement.h"
00017 
00018 // Messages.
00019 static const char *const MSG_CONFIG_INVALID_TYPE  = "Invalid type of preference '%s'.";
00020 static const char *const MSG_CONFIG_NOT_FOUND     = "Preference '%s' is not found.";
00021 static const char *const MSG_CONFIG_WRONG_FORMAT  = "Wrong config file format near '%s'.";
00022 static const char *const MSG_CONFIG_TYPE_MISMATCH = "Type of preference '%s' and type of the default value for this preference are mismatched.";
00023 
00024 static const char *const CONFIG_PATH = "/etc/pylon.conf.xml";
00025 
00026 using namespace std;
00027 
00028 class Config : public Object,
00029                public Singleton<Config>
00030 {
00031 
00032 friend class Singleton<Config>;
00033 
00034   PYLON_OBJECT
00035 
00036 public:
00037 
00038   int save();
00039   int remove(const String &name);
00040 
00041   template<class T>
00042   int set(const String &name, const T &value);
00043 
00044   template<class T>
00045   int get(const String &name, T &value, const T &defaultValue = T());
00046 
00047 private:
00048 
00049   Config();
00050   virtual ~Config();
00051 
00052 #ifdef DEBUG_MODE
00053   int print() const;
00054 #endif
00055 
00056   XmlDocument *_xml;
00057 };
00058 
00059 inline
00060 Config *CONFIG()
00061 {
00062   return Config::instance();
00063 }
00064 
00065 // Implementation.
00066 
00067 template<class T>
00068 int Config::set(const String &name, const T &value)
00069 {
00070   XmlElement *element;
00071   int res;
00072 
00073   if (FAILED(res = _xml->getElementById(name, &element)))
00074     return ERROR_BACKTRACE(res);
00075 
00076   if (!element)
00077     if (FAILED(res = _xml->createElement(XML_TAG_REGISTRY, &element, new XmlAttribute(XML_ATTR_ID, name))))
00078       return ERROR_BACKTRACE(res);
00079 
00080   if (FAILED(res = S11n<T>::toXml(value, element)))
00081     return ERROR_BACKTRACE(res);
00082 
00083   return OK;
00084 }
00085 
00086 template<class T>
00087 int Config::get(const String &name, T &value, const T &defaultValue)
00088 {
00089   XmlElement *element;
00090   int res;
00091 
00092   if (FAILED(res = _xml->getElementById(name, &element)))
00093     return ERROR_BACKTRACE(res);
00094 
00095   if (element) {
00096     if (FAILED(res = S11n<T>::fromXml(element, value)))
00097       return ERROR_BACKTRACE(res);
00098   } else {
00099       WARNING(MSG_CONFIG_NOT_FOUND, CSTRING(name));
00100       value = defaultValue;
00101     }
00102 
00103   return OK;
00104 }
00105 
00106 #endif

Generated on Thu Sep 6 20:11:25 2007 for Pylon Application Platform by  doxygen 1.5.1