/**
* Relational pipes
* Copyright © 2019 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, either version 3 of the License, or
* (at your option) any later version.
*
* 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 <cstdlib>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
#include <libxml++-2.6/libxml++/libxml++.h>
#include <relpipe/writer/typedefs.h>
#include "Configuration.h"
namespace relpipe {
namespace in {
namespace xmltable {
using namespace relpipe::writer;
class XMLCommand {
private:
std::wstring_convert<codecvt_utf8<wchar_t>> convertor; // TODO: support also other encodings.
public:
void process(std::istream& input, std::ostream& output, Configuration& configuration) {
std::shared_ptr<RelationalWriter> writer(Factory::create(output));
xmlpp::DomParser parser;
parser.parse_stream(input);
xmlpp::Element* root = parser.get_document()->get_root_node();
xmlpp::Node::PrefixNsMap ns;
for (int i = 0; i < configuration.namespaceMappings.size(); i++) {
std::string prefix = convertor.to_bytes(configuration.namespaceMappings[i]);
std::string uri = convertor.to_bytes(configuration.namespaceMappings[++i]);
ns[prefix] = uri;
}
for (const RelationConfiguration& r : configuration.relationConfigurations) {
std::vector<relpipe::writer::AttributeMetadata> attributesMetadata;
for (AttributeRecipe a : r.attributes) attributesMetadata.push_back(AttributeMetadata{a.name, a.type});
relpipe::writer::string_t name = r.nameIsXPath ? convertor.from_bytes(root->eval_to_string(convertor.to_bytes(r.relation), ns)) : r.relation;
writer->startRelation(name, attributesMetadata, true);
for (xmlpp::Node* n : root->find(convertor.to_bytes(r.xpath), ns)) {
for (AttributeRecipe a : r.attributes) {
// TODO: convert to bytes only once
writer->writeAttribute(convertor.from_bytes(n->eval_to_string(convertor.to_bytes(a.xpath), ns)));
}
}
}
}
};
}
}
}