All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
LocalJsonFileLoader.h
1 // Copyright eeGeo Ltd (2012-2014), All Rights Reserved
2 
3 #pragma once
4 
5 #include "IJsonFileLoader.h"
6 #include "IJsonFileParser.h"
7 #include "Types.h"
8 #include "CallbackCollection.h"
9 #include "IFileIO.h"
10 #include <vector>
11 #include <string>
12 #include <fstream>
13 
14 namespace Eegeo
15 {
16  namespace Io
17  {
18  template <class T>
20  {
21  public:
23 
24  private:
25 
26  struct LocalJsonFileLoad
27  {
28  LocalJsonFileLoad(const std::string& url, LoadCompleteCallbackType& callback)
29  : m_url(url)
30  , m_pCallback(&callback)
31  {}
32 
33  const std::string& GetUrl() const { return m_url; }
34  LoadCompleteCallbackType& GetCallback() const { return *m_pCallback; }
35  private:
36  std::string m_url;
37  LoadCompleteCallbackType* m_pCallback;
38  };
39 
40  Helpers::IFileIO& m_fileIO;
41  const IJsonFileParser<T>& m_parser;
42  TParsedResultsCallbacks& m_parsedResultsCallbacks;
43 
44  std::vector<LocalJsonFileLoad> m_loads;
45 
46  bool TryLoad(const LocalJsonFileLoad& load)
47  {
48  std::fstream stream;
49  size_t size;
50 
51  const bool fileOpenSuccess = m_fileIO.OpenFile(stream, size, load.GetUrl());
52 
53  if (!fileOpenSuccess)
54  {
55  return false;
56  }
57 
58  const std::string categoryJson((std::istreambuf_iterator<char>(stream)), std::istreambuf_iterator<char>());
59  stream.close();
60 
61  T parserResult;
62  const bool parseSuccess = m_parser.TryParse(categoryJson, parserResult);
63 
64  if (!parseSuccess)
65  {
66  return false;
67  }
68 
69  m_parsedResultsCallbacks.ExecuteCallbacks(parserResult);
70 
71  return true;
72  }
73 
74  public:
75 
77  const IJsonFileParser<T>& jsonParser,
78  TParsedResultsCallbacks& parsedResultsCallbacks
79  )
80  : m_fileIO(fileIO)
81  , m_parser(jsonParser)
82  , m_parsedResultsCallbacks(parsedResultsCallbacks)
83  {
84  }
85 
86  void Load(const std::string& url, LoadCompleteCallbackType& callback)
87  {
88  // work deferred until Update - similar behaviour to if we were doing web request
89  m_loads.emplace_back(url, callback);
90  }
91 
92  void Update()
93  {
94  for (typename std::vector<LocalJsonFileLoad>::const_iterator iter = m_loads.begin(); iter != m_loads.end(); ++iter)
95  {
96  bool success = TryLoad(*iter);
97  if(!success)
98  {
99  Eegeo_TTY("Failed to load interior label category json file %s", iter->GetUrl().c_str());
100  }
101 
102  JsonFileLoaderResult result(iter->GetUrl(), success);
103  iter->GetCallback()(result);
104  }
105  m_loads.clear();
106  }
107 
108 
109  };
110  }
111 }