blob: 8018310e58a988f385f6c741b7342f702dd651f5 [file] [log] [blame]
Steve DiBenedettobb75b552014-02-08 12:12:11 -07001/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2/**
3 * Copyright (C) 2014 Named Data Networking Project
4 * See COPYING for copyright and distribution information.
5 */
6
7
8#include "config-file.hpp"
9
10#include <boost/property_tree/info_parser.hpp>
11
12namespace nfd {
13
14NFD_LOG_INIT("ConfigFile");
15
16ConfigFile::ConfigFile()
17{
18
19}
20
21void
22ConfigFile::addSectionHandler(const std::string& sectionName,
23 OnConfig subscriber)
24{
25 m_subscriptions[sectionName] = subscriber;
26}
27
28void
29ConfigFile::parse(const char* filename, bool isDryRun)
30{
31 std::ifstream inputFile;
32 inputFile.open(filename);
33 if (!inputFile.is_open())
34 {
35 std::string msg = "Failed to read configuration file: ";
36 msg += filename;
Steve DiBenedetto2c2b8892014-02-27 11:46:48 -070037 throw Error(msg);
Steve DiBenedettobb75b552014-02-08 12:12:11 -070038 }
39 parse(inputFile, isDryRun, filename);
40 inputFile.close();
41}
42
43void
44ConfigFile::parse(const std::string& input, bool isDryRun, const char* filename)
45{
46 std::istringstream inputStream(input);
47 parse(inputStream, isDryRun, filename);
48}
49
50
51void
52ConfigFile::parse(std::istream& input, bool isDryRun, const char* filename)
53{
54 try
55 {
56 boost::property_tree::read_info(input, m_global);
57 }
58 catch (const boost::property_tree::info_parser_error& error)
59 {
60 std::stringstream msg;
61 msg << "Failed to parse configuration file";
62 if (filename != 0)
63 {
64 msg << " " << filename;
65 }
66 msg << " " << error.message() << " line " << error.line();
67 throw Error(msg.str());
68 }
69
70 process(isDryRun, filename);
71}
72
73void
74ConfigFile::process(bool isDryRun, const char* filename)
75{
76 // NFD_LOG_DEBUG("processing..." << ((isDryRun)?("dry run"):("")));
77
78 if (m_global.begin() == m_global.end())
79 {
80 std::string msg = "Error processing configuration file";
81 if (filename != 0)
82 {
83 msg += ": ";
84 msg += filename;
85 }
86 msg += " no data";
87 throw Error(msg);
88 }
89
90 for (ConfigSection::const_iterator i = m_global.begin(); i != m_global.end(); ++i)
91 {
92 const std::string& sectionName = i->first;
93 const ConfigSection& section = i->second;
94
95 SubscriptionTable::iterator subscriberIt = m_subscriptions.find(sectionName);
96 if (subscriberIt != m_subscriptions.end())
97 {
98 OnConfig subscriber = subscriberIt->second;
99 subscriber(section, isDryRun);
100 }
101 else
102 {
103 std::string msg = "Error processing configuration file";
104 if (filename != 0)
105 {
106 msg += " ";
107 msg += filename;
108 }
109 msg += " no module subscribed for section: " + sectionName;
110 throw Error(msg);
111 }
112 }
113}
114
115}
116