src/XMLDocumentConstructor.h
author František Kučera <franta-hg@frantovo.cz>
Thu, 22 Jul 2021 20:01:03 +0200
branchv_0
changeset 40 85b6f13f1088
parent 13 d5e2cb9e31f1
permissions -rw-r--r--
configuration: --parser-option encoding, parse-encapsulated, root-name, tree-style, tree-with-namespaces

/**
 * Relational pipes
 * Copyright © 2021 František Kučera (Frantovo.cz, GlobalCode.info)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
#pragma once

#include <memory>
#include <stdexcept>

#include <libxml++-2.6/libxml++/libxml++.h>

#include "lib/BasicASN1Reader.h"
#include "lib/GenericASN1ContentHandler.h"
#include "lib/DOMBuildingXMLContentHandler.h"
#include "lib/TransactionalBuffer.h"

namespace relpipe {
namespace in {
namespace xmltable {

class XMLDocumentConstructor {
private:
	std::istream* input = nullptr;
	xmlpp::DomParser* parser = nullptr;
	relpipe::in::asn1::lib::BasicASN1Reader reader;
	std::shared_ptr<relpipe::in::asn1::lib::GenericASN1ContentHandler> asn1handler;
	std::shared_ptr<relpipe::in::asn1::lib::DOMBuildingXMLContentHandler> saxHandler;
public:

	XMLDocumentConstructor(std::istream* input, xmlpp::DomParser* parser) : input(input), parser(parser) {
		asn1handler = make_shared<relpipe::in::asn1::lib::GenericASN1ContentHandler>();
		saxHandler = make_shared<relpipe::in::asn1::lib::DOMBuildingXMLContentHandler>(parser->get_document());
		asn1handler->addHandler(saxHandler);
		reader.addHandler(asn1handler);
	}

	void setOption(const std::string& uri, const std::string& value) {
		int n = 0;
		n += reader.setOption(uri, value);
		n += asn1handler->setOption(uri, value);
		n += saxHandler->setOption(uri, value);
		if (n == 0) throw std::invalid_argument(std::string("Invalid parser option: „") + uri + "“ with value: „" + value + "“");
	}

	void process() {
		try {
			// TODO: buffering? (reader itself also buffers)
			for (uint8_t b = input->get(); input->good(); b = input->get()) reader.write(&b, 1);
		} catch (const relpipe::in::asn1::lib::TransactionalBuffer::WriteBufferOverflowException& e) {
			// TODO: avoid leaky abstraction and use different exception
			throw relpipe::writer::RelpipeWriterException(L"Transactional buffer for ASN.1 input is too small");
		}

		reader.close();

		if (parser->get_document()->get_root_node() == nullptr) throw relpipe::writer::RelpipeWriterException(L"Empty ASN.1 input"); // TODO: move to common class
	}
};

}
}
}