SSAGES  0.1
A MetaDynamics Package
JSONLoader.h
1 
26 #pragma once
27 
28 #include "json/json.h"
29 #include "JSONLoaderPlugin.h"
30 #include <fstream>
31 #include <memory>
32 #include <stdexcept>
33 #include <mxx/bcast.hpp>
34 
35 namespace SSAGES
36 {
38 
41  class JSONLoader
42  {
43  private:
45  std::vector<std::unique_ptr<JSONLoaderPlugin>> plugins_;
46 
47  public:
49 
53  JSONLoader() : plugins_(0)
54  {
55  plugins_.push_back(std::unique_ptr<JSONLoaderPlugin>(new IncludePlugin()));
56  }
57 
59 
68  Json::Value LoadFile(const std::string& filename, const mxx::comm& world)
69  {
70  std::string contents, path;
71  if(world.rank() == 0)
72  {
73  contents = GetFileContents(filename.c_str());
74  path = GetFilePath(filename);
75  }
76 
77  mxx::bcast(contents, 0, world);
78  mxx::bcast(path, 0, world);
79 
80  for(auto& plugin : plugins_)
81  plugin->ApplyFilter(contents, path);
82 
83  // Read JSON.
84  Json::Reader reader;
85  Json::Value root;
86  if(!reader.parse(contents, root))
87  throw std::invalid_argument(
88  filename + ": " + reader.getFormattedErrorMessages()
89  );
90  return root;
91  }
92  };
93 }
JSONLoader()
Constructor.
Definition: JSONLoader.h:53
std::string GetFilePath(const std::string &str)
Gets file path from filename.
Definition: FileContents.h:73
std::vector< std::unique_ptr< JSONLoaderPlugin > > plugins_
List of plugins.
Definition: JSONLoader.h:45
Json::Value LoadFile(const std::string &filename, const mxx::comm &world)
Load file and return JSON tree.
Definition: JSONLoader.h:68
Class for JSON loader include plugin.
std::string GetFileContents(const char *filename)
Read contents from a file.
Definition: FileContents.h:47
Class for loading JSON content from files.
Definition: JSONLoader.h:41