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

#include <xercesc/framework/LocalFileInputSource.hpp>

#include "boost/filesystem.hpp"

#include "support/xerces_string_guard.h"

namespace {

using InputXSLT::XercesStringGuard;

boost::optional<std::string> extractFilePath(const XMLCh* const rawPath) {
	const std::string filePath         = *XercesStringGuard<char>(rawPath);
	const std::size_t leadingDelimiter = filePath.find_first_of('[');
	const std::size_t closingDelimiter = filePath.find_last_of(']');

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

}

namespace InputXSLT {

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 ) {
		if ( auto filePath = extractFilePath(systemId) ) {
			if ( auto resolvedPath = this->resolve(*filePath) ) {
				return new xercesc::LocalFileInputSource(
					*XercesStringGuard<XMLCh>((*resolvedPath).string())
				);
			} else {
				return new xercesc::LocalFileInputSource(
					*XercesStringGuard<XMLCh>(*filePath)
				);
			}
		} else {
			return nullptr;
		}
	} else {
		return nullptr;
	}
}

boost::optional<boost::filesystem::path> IncludeEntityResolver::resolve(
	const std::string& filePath) const {
	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 boost::make_optional(resolvedPath);
		}
	}

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

}