
 //
 // XML storage C++ classes version 1.5
 //
 // Copyright (c) 2006, 2008, 2010 Martin Fuchs <martin-fuchs@gmx.net>
 //

 /// \file xs-xerces.cpp
 /// XMLStorage code using the Xerces XML parser


/*

  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

  * Redistributions of source code must retain the above copyright
	notice, this list of conditions and the following disclaimer.
  * Redistributions in binary form must reproduce the above copyright
	notice, this list of conditions and the following disclaimer in
	the documentation and/or other materials provided with the
	distribution.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  POSSIBILITY OF SUCH DAMAGE.

*/

#ifdef XS_USE_XERCES

#ifndef XS_NO_COMMENT
#define XS_NO_COMMENT	// no #pragma comment(lib, ...) statements in .lib files to enable static linking
#endif

#include "xmlstorage.h"


#include <xercesc/sax/Locator.hpp>
#include <xercesc/util/XMemory.hpp>
#include <xercesc/framework/LocalFileInputSource.hpp>
#include <xercesc/framework/MemBufInputSource.hpp>


namespace XMLStorage {


#pragma init_seg(lib)
static struct XercesInit
{
	XercesInit()
	{
		XERCES_CPP_NAMESPACE_QUALIFIER XMLPlatformUtils::Initialize();
	}
} s_XercesInit;


XMLReaderBase::XMLReaderBase(XMLNode* node, InputSource* source, bool adoptSource)
 :	_pos(node),
#ifdef XMLNODE_LOCATION
	_locator(NULL),
#endif
	_source(source),
	_deleteSource(adoptSource)
{
	 // Create a SAX parser object.
	_parser = new SAXParser;

	_parser->setValidationScheme(SAXParser::Val_Always);
	_parser->setDoNamespaces(true);
	_parser->setDoSchema(true);
	_parser->setValidationSchemaFullChecking(true);

	 // Install the reader as the document and error handler on the parser.
	_parser->setDocumentHandler(this);
	_parser->setErrorHandler(this);

	_last_tag = TAG_NONE;
}

XMLReaderBase::~XMLReaderBase()
{
	if (_deleteSource)
		delete _source;

	delete _parser;
}

 /// read XML stream into XML tree below _pos
void XMLReaderBase::read()
{
    try {
		_parser->parse(*_source);
    } catch(const XERCES_CPP_NAMESPACE_QUALIFIER SAXParseException& e) {
		XMLError err;

		err._message = e.getMessage();
		err._systemId = e.getSystemId();
		err._line = e.getLineNumber();
		err._column = e.getColumnNumber();

		_errors.push_back(err);
    } catch(const XERCES_CPP_NAMESPACE_QUALIFIER SAXException& e) {
		XMLError err;

		err._message = e.getMessage();

		_errors.push_back(err);
    } catch(const XERCES_CPP_NAMESPACE_QUALIFIER XMLException& e) {
		XMLError err;

		err._message = e.getMessage();

		_errors.push_back(err);
    }
}


XercesXMLReader::XercesXMLReader(XMLNode* node, LPCTSTR path)
 :	XMLReaderBase(node, new XERCES_CPP_NAMESPACE_QUALIFIER LocalFileInputSource(
#ifdef UNICODE
		path
#else
		std::wstring(XS_String(path)).c_str()
#endif
	), true)
{
}

XercesXMLReader::XercesXMLReader(XMLNode* node, const XMLByte* buffer, size_t bytes, const std::string& system_id)
#ifdef UNICODE
 :	XMLReaderBase(node, new XERCES_CPP_NAMESPACE_QUALIFIER MemBufInputSource(buffer, bytes, system_id, true)
#else
 :	XMLReaderBase(node, new XERCES_CPP_NAMESPACE_QUALIFIER MemBufInputSource(buffer, bytes, std::wstring(XS_String(system_id)).c_str()), true)
#endif
{
}


#ifdef XMLNODE_LOCATION

XMLLocation XMLReaderBase::get_location() const
{
	if (_locator)
		// only temporary: XS_String(_locator->getSystemId())
		return XMLLocation(_display_path, _locator->getLineNumber(), _locator->getColumnNumber());

	return XMLLocation(_display_path, 0, 0);
}

#endif


 /// store XML version and encoding into XML reader
void XMLReaderBase::XMLDecl(const XMLCh* const versionStr, const XMLCh* const encodingStr,
							const XMLCh* const standaloneStr, const XMLCh* const actualEncodingStr)
{
	int standalone;

	if (standaloneStr)
		standalone = !_stricmp(String_from_XML_Char(standaloneStr).c_str(), "yes");
	else
		standalone = -1;

#ifdef UNICODE
	XmlDeclHandler(std::string(String_from_XML_Char(versionStr)).c_str(),
					std::string(String_from_XML_Char(encodingStr)).c_str(), standalone);
#else
	XmlDeclHandler(String_from_XML_Char(versionStr),
					String_from_XML_Char(encodingStr), standalone);
#endif
}

void XMLReaderBase::setDocumentLocator(const Locator* const locator)
{
#ifdef XMLNODE_LOCATION
	_locator = locator;
#endif
}

 /// notifications about XML start tag
void XMLReaderBase::startElement(const XMLCh* const name, AttributeList& attributes)
{
	XMLNode::AttributeMap attribs;

	for(int i=attributes.getLength(); --i>=0; ) {
		const XMLCh* attr_name = attributes.getName(i);
		const XMLCh* attr_value = attributes.getValue(i);

		attribs[String_from_XML_Char(attr_name)] = String_from_XML_Char(attr_value);
	}

	StartElementHandler(String_from_XML_Char(name), attribs);
}

 /// notifications about XML end tag
void XMLReaderBase::endElement(const XMLCh* const name)
{
	EndElementHandler();
}

 /// store content
void XMLReaderBase::characters(const XMLCh* const chars, const unsigned int length)
{
	DefaultHandler(chars, length);
}

 /// store white space and comments
void XMLReaderBase::ignorableWhitespace(const XMLCh* const chars, const unsigned int length)
{
	DefaultHandler(chars, length);
}


void XMLReaderBase::error(const SAXParseException& e)
{
	XMLError err;

	err._message = e.getMessage();
	err._systemId = e.getSystemId();
	err._line = e.getLineNumber();
	err._column = e.getColumnNumber();

	_errors.push_back(err);
}

void XMLReaderBase::fatalError(const SAXParseException& e)
{
	XMLError err;

	err._message = e.getMessage();
	err._systemId = e.getSystemId();
	err._line = e.getLineNumber();
	err._column = e.getColumnNumber();

	_errors.push_back(err);
}

void XMLReaderBase::warning(const SAXParseException& e)
{
	XMLError err;

	err._message = e.getMessage();
	err._systemId = e.getSystemId();
	err._line = e.getLineNumber();
	err._column = e.getColumnNumber();

	_warnings.push_back(err);
}

void XMLReaderBase::resetErrors()
{
	_errors.clear();
}


}	// namespace XMLStorage

#endif // XS_USE_XERCES
