aboutsummaryrefslogtreecommitdiff
path: root/src/support/include_entity_resolver.cc
blob: 07577c1f46db2a0b53d45935b11b8b752e1d7d77 (plain)
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
#include "include_entity_resolver.h"

#include <xercesc/framework/LocalFileInputSource.hpp>

#include "boost/filesystem.hpp"

#include "support/xalan_string.h"
#include "support/xerces_string_guard.h"

namespace {

boost::optional<boost::filesystem::path> extractFilePath(
	const std::string& rawPath) {
	const std::size_t leadingDelimiter = rawPath.find_first_of('[');
	const std::size_t closingDelimiter = rawPath.find_last_of(']');

	if ( leadingDelimiter != std::string::npos &&
		 closingDelimiter != std::string::npos &&
		 leadingDelimiter <  closingDelimiter ) {
		return boost::make_optional(
			boost::filesystem::path(
				rawPath.substr(
					leadingDelimiter + 1,
					closingDelimiter - leadingDelimiter - 1
				)
			)
		);
	} else {
		return boost::optional<boost::filesystem::path>();
	}
}

}

namespace InputXSLT {

boost::filesystem::path IncludeEntityResolver::getPathFromSystemId(
	const XMLCh* const systemId) {
	return boost::filesystem::path(
		*XercesStringGuard<char>(systemId) + 7
	);
}

IncludeEntityResolver::IncludeEntityResolver(
	const std::vector<std::string>& path):
	path_(path.begin(), path.end()) { }

xercesc::InputSource* IncludeEntityResolver::resolveEntity(
	const XMLCh* const,
	const XMLCh* const systemId
) {
	if ( systemId != nullptr ) {
		const std::string systemIdString(
			*XercesStringGuard<char>(systemId)
		);

		if ( auto resolvedPath = this->resolve(systemIdString) ) {
			return new xercesc::LocalFileInputSource(
				*XercesStringGuard<XMLCh>((*resolvedPath).string())
			);
		} else {
			return new xercesc::LocalFileInputSource(
				*XercesStringGuard<XMLCh>(systemIdString)
			);
		}
	} else {
		return nullptr;
	}
}

boost::optional<boost::filesystem::path> IncludeEntityResolver::resolve(
	const std::string& rawPath) const {
	if ( auto filePath = extractFilePath(rawPath) ) {
		if ( auto resolvedPath = this->tryIncludePaths(*filePath) ) {
			return boost::make_optional(*resolvedPath);
		} else {
			return boost::make_optional(*filePath);
		}
	} else {
		return boost::optional<boost::filesystem::path>();
	}
}

boost::optional<boost::filesystem::path> IncludeEntityResolver::tryIncludePaths(
	const boost::filesystem::path& filePath) const {
	for ( auto&& context : this->path_ ) {
		const boost::filesystem::path resolvedPath(
			context.resolve(filePath)
		);

		if ( boost::filesystem::exists(resolvedPath) ) {
			return boost::make_optional(resolvedPath);
		}
	}

	return boost::optional<boost::filesystem::path>();
}

}