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

#include <xercesc/framework/LocalFileInputSource.hpp>

#include "boost/filesystem.hpp"

#include "support/xerces_string_guard.h"

namespace {

std::pair<bool, std::string> 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 std::make_pair(
			true,
			rawPath.substr(
				leadingDelimiter + 1,
				closingDelimiter - leadingDelimiter - 1
			)
		);
	} else {
		return std::make_pair(false, std::string());
	}
}

}

namespace InputXSLT {

IncludeEntityResolver::IncludeEntityResolver(
	const std::vector<std::string>& path):
	path_() {
	this->path_.reserve(path.size());

	std::transform(
		path.begin(),
		path.end(),
		std::back_inserter(this->path_),
		[](const std::string& path) -> FilesystemContext {
			return FilesystemContext(path);
		}
	);
}

xercesc::InputSource* IncludeEntityResolver::resolveEntity(
	const XMLCh* const,
	const XMLCh* const systemId
) {
	if ( systemId != nullptr ) {
		auto filePath = extractFilePath(*XercesStringGuard<char>(systemId));

		if ( filePath.first ) {
			auto resolvedPath = this->resolve(filePath.second);

			if ( resolvedPath.first ) {
				return new xercesc::LocalFileInputSource(
					*XercesStringGuard<XMLCh>(resolvedPath.second.string())
				);
			} else {
				return nullptr;
			}
		} else {
			return nullptr;
		}
	} else {
		return nullptr;
	}
}

std::pair<bool, boost::filesystem::path> IncludeEntityResolver::resolve(
	const std::string& filePath) {
	for ( auto&& context : this->path_ ) {
		const boost::filesystem::path resolvedPath(
			context.resolve(filePath)
		);

		if ( boost::filesystem::exists(resolvedPath) &&
			 boost::filesystem::is_regular_file(resolvedPath) ) {
			return std::make_pair(true, resolvedPath);
		}
	}

	return std::make_pair(false, boost::filesystem::path());
}

}