-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreadoutbuffer.cpp
128 lines (107 loc) · 2.29 KB
/
readoutbuffer.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#include "readoutbuffer.h"
#include "logger.h"
readoutFile::readoutFile(const std::string& filename)
{
_content.clear();
_last_read_timestamp = 0;
setFilename(filename);
}
readoutFile::~readoutFile()
{
_content.clear();
_filename.clear();
}
void readoutFile::setFilename(const std::string& filename)
{
_filename = filename;
_isHTTP = false;
if(_filename.size() >= 7) // http:// ?
{
if(_filename.substr(0, 7) == "http://")
_isHTTP = true;
}
if(_filename.size() >= 8) // https:// ?
{
if(_filename.substr(0, 8) == "https://")
_isHTTP = true;
}
}
void readoutFile::cleanUp(uint64_t currentTimestamp)
{
if((currentTimestamp - _last_read_timestamp) > BUFFERTIME)
{
_content.clear();
}
}
std::string readoutFile::getContent(logger* root, uint64_t currentTimestamp)
{
if((currentTimestamp - _last_read_timestamp) > BUFFERTIME)
{
_content.clear();
if(_isHTTP)
{
try
{
_content = root->httpRequest(_filename);
}
catch(int e)
{
root->error("Cannot read from: " + _filename);
}
}
else // file in file system
{
// Try twice:
for(int i=0; i<N_TRIALS; ++i)
{
std::ifstream fs(_filename);
if(fs.is_open())
{
std::stringstream strStream;
strStream<<fs.rdbuf();
_content = strStream.str();
fs.close();
break;
}
if(i >= (N_TRIALS-1))
{
std::cerr<<"Cannot open file: "<<_filename<<std::endl;
throw E_UNABLE_TO_OPEN_FILE;
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
_last_read_timestamp = currentTimestamp;
}
return _content;
}
readoutBuffer::readoutBuffer(logger* root)
{
_root = root;
}
void readoutBuffer::cleanUp(uint64_t currentTimestamp)
{
for(unsigned i=0; i<_files.size(); ++i)
_files.at(i)->cleanUp(currentTimestamp);
}
void readoutBuffer::clear()
{
for(unsigned i=0; i<_files.size(); ++i)
delete _files.at(i);
_files.clear();
}
readoutBuffer::~readoutBuffer()
{
clear();
}
std::string readoutBuffer::getFileContents(const std::string& filename, uint64_t currentTimestamp)
{
for(unsigned i=0; i<_files.size(); ++i)
{
if(_files.at(i)->_filename == filename)
return _files.at(i)->getContent(_root, currentTimestamp);
}
readoutFile* f = new readoutFile(filename);
_files.push_back(f);
return f->getContent(_root, currentTimestamp);
}