00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022 #include <cmath>
00023 #include <map>
00024 #include <libxml/xmlwriter.h>
00025
00026 #include "common/configuration.hpp"
00027
00028 #include "utils/logger.h"
00029 #include "utils/xml.hpp"
00030
00032 static std::map< std::string, std::string > options;
00034 static std::string configPath;
00035
00036 void Configuration::initialize(const std::string &filename)
00037 {
00038 configPath = filename;
00039
00040 xmlDocPtr doc = xmlReadFile(filename.c_str(), NULL, 0);
00041
00042 if (!doc) return;
00043
00044 xmlNodePtr node = xmlDocGetRootElement(doc);
00045
00046 if (!node || !xmlStrEqual(node->name, BAD_CAST "configuration")) {
00047 LOG_WARN("No configuration file '" << filename.c_str() << "'.");
00048 return;
00049 }
00050
00051 for (node = node->xmlChildrenNode; node != NULL; node = node->next)
00052 {
00053 if (xmlStrEqual(node->name, BAD_CAST "option"))
00054 {
00055 std::string key = XML::getProperty(node, "name", "");
00056 std::string value = XML::getProperty(node, "value", "");
00057
00058 if (!key.empty() && !value.empty())
00059 {
00060 options[key] = value;
00061 }
00062 }
00063 }
00064
00065 xmlFreeDoc(doc);
00066 }
00067
00068 void Configuration::deinitialize()
00069 {
00070 xmlTextWriterPtr writer = xmlNewTextWriterFilename(configPath.c_str(), 0);
00071
00072 if (writer)
00073 {
00074 xmlTextWriterSetIndent(writer, 1);
00075 xmlTextWriterStartDocument(writer, NULL, NULL, NULL);
00076 xmlTextWriterStartElement(writer, BAD_CAST "configuration");
00077
00078 std::map<std::string, std::string>::iterator iter;
00079
00080 for (iter = options.begin(); iter != options.end(); iter++)
00081 {
00082 xmlTextWriterStartElement(writer, BAD_CAST "option");
00083 xmlTextWriterWriteAttribute(writer,
00084 BAD_CAST "name", BAD_CAST iter->first.c_str());
00085 xmlTextWriterWriteAttribute(writer,
00086 BAD_CAST "value", BAD_CAST iter->second.c_str());
00087 xmlTextWriterEndElement(writer);
00088 }
00089
00090 xmlTextWriterEndDocument(writer);
00091 xmlFreeTextWriter(writer);
00092 }
00093 }
00094
00095 void Configuration::setValue(const std::string &key, const std::string &value)
00096 {
00097 options[key] = value;
00098 }
00099
00100 void Configuration::setValue(const std::string &key, int value)
00101 {
00102 std::ostringstream ss;
00103 ss << value;
00104 setValue(key, ss.str());
00105 }
00106
00107 const std::string &Configuration::getValue(const std::string &key,
00108 const std::string &deflt)
00109 {
00110 std::map<std::string, std::string>::iterator iter = options.find(key);
00111 if (iter == options.end()) return deflt;
00112 return iter->second;
00113 }
00114
00115 int Configuration::getValue(const std::string &key, int deflt)
00116 {
00117 std::map<std::string, std::string>::iterator iter = options.find(key);
00118 if (iter == options.end()) return deflt;
00119 return atoi(iter->second.c_str());
00120 }