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
|
#include "read_file.h"
#include <xercesc/parsers/XercesDOMParser.hpp>
#include <xercesc/framework/LocalFileInputSource.hpp>
#include <boost/optional.hpp>
#include <boost/filesystem/fstream.hpp>
#include "support/xerces_string_guard.h"
#include "support/dom/result_node_facade.h"
namespace {
inline bool isXmlFile(const boost::filesystem::path& filePath) {
return filePath.extension() == ".xml" ||
filePath.extension() == ".xsl";
}
boost::optional<xercesc::DOMNode*> readXmlFile(
const boost::filesystem::path& filePath,
xercesc::DOMDocument* const domDocument
) {
const xercesc::LocalFileInputSource file(
*InputXSLT::XercesStringGuard<XMLCh>(filePath.string().data())
);
xercesc::XercesDOMParser parser;
parser.parse(file);
if ( parser.getErrorCount() == 0 ) {
return boost::make_optional(
domDocument->importNode(
parser.getDocument()->getDocumentElement(),
true
)
);
} else {
return boost::optional<xercesc::DOMNode*>();
}
}
boost::optional<std::string> readPlainFile(
const boost::filesystem::path& filePath) {
boost::filesystem::ifstream file(filePath);
if ( file.is_open() ) {
return boost::make_optional(
std::string(
(std::istreambuf_iterator<char>(file)),
(std::istreambuf_iterator<char>())
)
);
} else {
return boost::optional<std::string>();
}
}
}
namespace InputXSLT {
DomDocumentCache::document_ptr FunctionReadFile::constructDocument(
boost::filesystem::path filePath) const {
DomDocumentCache::document_ptr domDocument(
DomDocumentCache::createDocument("content")
);
ResultNodeFacade result(domDocument.get(), "file");
result.setAttribute("path", filePath.string());
if ( boost::filesystem::is_regular_file(filePath) ) {
try {
if ( isXmlFile(filePath) ) {
result.setAttribute("type", "xml");
if ( auto importedNode = readXmlFile(
filePath,
domDocument.get())
) {
result.setContent(*importedNode);
result.setAttribute("result", "success");
} else {
result.setAttribute("result", "error");
}
} else {
result.setAttribute("type", "plain");
if ( auto plainContent = readPlainFile(filePath) ) {
result.setContent(*plainContent);
result.setAttribute("result", "success");
} else {
result.setAttribute("result", "error");
}
result.setAttribute("result", "success");
}
}
catch ( const xercesc::DOMException& exception ) {
result.setAttribute("result", "error");
result.setValueNode(
"error",
*XercesStringGuard<char>(exception.msg)
);
}
} else {
result.setAttribute("result", "error");
}
return domDocument;
}
}
|