From 940b4d1848e8c70ab7642901a68594e8016caffc Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Sat, 27 Apr 2024 18:51:28 +0200 Subject: Adding upstream version 1:7.0.4. Signed-off-by: Daniel Baumann --- sax/CppunitTest_sax.mk | 30 + sax/CppunitTest_sax_attributes.mk | 29 + sax/CppunitTest_sax_parser.mk | 49 + sax/CppunitTest_sax_xmlimport.mk | 57 + sax/IwyuFilter_sax.yaml | 2 + sax/Library_expwrap.mk | 52 + sax/Library_sax.mk | 42 + sax/Makefile | 7 + sax/Module_sax.mk | 24 + sax/README | 13 + sax/inc/xml2utf.hxx | 129 ++ sax/qa/cppunit/attributes.cxx | 75 + sax/qa/cppunit/parser.cxx | 101 ++ sax/qa/cppunit/test_converter.cxx | 623 +++++++ sax/qa/cppunit/xmlimport.cxx | 450 +++++ sax/qa/data/defaultns.xml | 11 + sax/qa/data/inlinens.xml | 12 + sax/qa/data/manifestwithnsdecl.xml | 12 + sax/qa/data/manifestwithoutnsdecl.xml | 12 + sax/qa/data/multiplens.xml | 13 + sax/qa/data/multiplepfx.xml | 9 + sax/qa/data/nestedns.xml | 32 + sax/qa/data/nstoattributes.xml | 17 + sax/qa/data/simple.xml | 11 + sax/qa/data/testthreading.xml | 5 + sax/source/expatwrap/expwrap.component | 38 + sax/source/expatwrap/sax_expat.cxx | 959 +++++++++++ sax/source/expatwrap/saxwriter.cxx | 1418 ++++++++++++++++ sax/source/expatwrap/xml2utf.cxx | 519 ++++++ sax/source/fastparser/fastparser.cxx | 1436 ++++++++++++++++ sax/source/fastparser/legacyfastparser.cxx | 378 +++++ sax/source/tools/CachedOutputStream.hxx | 118 ++ sax/source/tools/converter.cxx | 2448 ++++++++++++++++++++++++++++ sax/source/tools/fastattribs.cxx | 281 ++++ sax/source/tools/fastserializer.cxx | 813 +++++++++ sax/source/tools/fastserializer.hxx | 254 +++ sax/source/tools/fshelper.cxx | 158 ++ sax/test/makefile.mk | 58 + sax/test/sax/exports.dxp | 2 + sax/test/sax/factory.hxx | 80 + sax/test/sax/makefile.mk | 52 + sax/test/sax/testsax.cxx | 795 +++++++++ sax/test/sax/testwriter.cxx | 662 ++++++++ sax/test/saxdemo.cxx | 626 +++++++ sax/test/testcomponent.cxx | 223 +++ 45 files changed, 13135 insertions(+) create mode 100644 sax/CppunitTest_sax.mk create mode 100644 sax/CppunitTest_sax_attributes.mk create mode 100644 sax/CppunitTest_sax_parser.mk create mode 100644 sax/CppunitTest_sax_xmlimport.mk create mode 100644 sax/IwyuFilter_sax.yaml create mode 100644 sax/Library_expwrap.mk create mode 100644 sax/Library_sax.mk create mode 100644 sax/Makefile create mode 100644 sax/Module_sax.mk create mode 100644 sax/README create mode 100644 sax/inc/xml2utf.hxx create mode 100644 sax/qa/cppunit/attributes.cxx create mode 100644 sax/qa/cppunit/parser.cxx create mode 100644 sax/qa/cppunit/test_converter.cxx create mode 100644 sax/qa/cppunit/xmlimport.cxx create mode 100644 sax/qa/data/defaultns.xml create mode 100644 sax/qa/data/inlinens.xml create mode 100644 sax/qa/data/manifestwithnsdecl.xml create mode 100644 sax/qa/data/manifestwithoutnsdecl.xml create mode 100644 sax/qa/data/multiplens.xml create mode 100644 sax/qa/data/multiplepfx.xml create mode 100644 sax/qa/data/nestedns.xml create mode 100644 sax/qa/data/nstoattributes.xml create mode 100644 sax/qa/data/simple.xml create mode 100644 sax/qa/data/testthreading.xml create mode 100644 sax/source/expatwrap/expwrap.component create mode 100644 sax/source/expatwrap/sax_expat.cxx create mode 100644 sax/source/expatwrap/saxwriter.cxx create mode 100644 sax/source/expatwrap/xml2utf.cxx create mode 100644 sax/source/fastparser/fastparser.cxx create mode 100644 sax/source/fastparser/legacyfastparser.cxx create mode 100644 sax/source/tools/CachedOutputStream.hxx create mode 100644 sax/source/tools/converter.cxx create mode 100644 sax/source/tools/fastattribs.cxx create mode 100644 sax/source/tools/fastserializer.cxx create mode 100644 sax/source/tools/fastserializer.hxx create mode 100644 sax/source/tools/fshelper.cxx create mode 100644 sax/test/makefile.mk create mode 100644 sax/test/sax/exports.dxp create mode 100644 sax/test/sax/factory.hxx create mode 100644 sax/test/sax/makefile.mk create mode 100644 sax/test/sax/testsax.cxx create mode 100644 sax/test/sax/testwriter.cxx create mode 100644 sax/test/saxdemo.cxx create mode 100644 sax/test/testcomponent.cxx (limited to 'sax') diff --git a/sax/CppunitTest_sax.mk b/sax/CppunitTest_sax.mk new file mode 100644 index 000000000..282ba2414 --- /dev/null +++ b/sax/CppunitTest_sax.mk @@ -0,0 +1,30 @@ +# -*- Mode: makefile-gmake; tab-width: 4; indent-tabs-mode: t -*- +# +# This file is part of the LibreOffice project. +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +# + +$(eval $(call gb_CppunitTest_CppunitTest,sax)) + +$(eval $(call gb_CppunitTest_use_sdk_api,sax)) + +$(eval $(call gb_CppunitTest_use_external,sax,boost_headers)) + +$(eval $(call gb_CppunitTest_use_common_precompiled_header,sax)) + +$(eval $(call gb_CppunitTest_use_libraries,sax, \ + sax \ + sal \ + comphelper \ + cppu \ +)) + +$(eval $(call gb_CppunitTest_add_exception_objects,sax, \ + sax/qa/cppunit/test_converter \ +)) + + +# vim: set noet sw=4 ts=4: diff --git a/sax/CppunitTest_sax_attributes.mk b/sax/CppunitTest_sax_attributes.mk new file mode 100644 index 000000000..198629814 --- /dev/null +++ b/sax/CppunitTest_sax_attributes.mk @@ -0,0 +1,29 @@ +# -*- Mode: makefile-gmake; tab-width: 4; indent-tabs-mode: t -*- +# +# This file is part of the LibreOffice project. +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +# + +$(eval $(call gb_CppunitTest_CppunitTest,sax_attributes)) + +$(eval $(call gb_CppunitTest_use_common_precompiled_header,sax_attributes)) + +$(eval $(call gb_CppunitTest_add_exception_objects,sax_attributes, \ + sax/qa/cppunit/attributes \ +)) + +$(eval $(call gb_CppunitTest_use_libraries,sax_attributes, \ + cppu \ + cppuhelper \ + sal \ + sax \ +)) + +$(eval $(call gb_CppunitTest_use_sdk_api,sax_attributes)) + +$(eval $(call gb_CppunitTest_use_ure,sax_attributes)) + +# vim: set noet sw=4 ts=4: diff --git a/sax/CppunitTest_sax_parser.mk b/sax/CppunitTest_sax_parser.mk new file mode 100644 index 000000000..59a90fd13 --- /dev/null +++ b/sax/CppunitTest_sax_parser.mk @@ -0,0 +1,49 @@ +# -*- Mode: makefile-gmake; tab-width: 4; indent-tabs-mode: t -*- +# +# This file is part of the LibreOffice project. +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +# + +$(eval $(call gb_CppunitTest_CppunitTest,sax_parser)) + +$(eval $(call gb_CppunitTest_use_common_precompiled_header,sax_parser)) + +$(eval $(call gb_CppunitTest_add_exception_objects,sax_parser, \ + sax/qa/cppunit/parser \ +)) + +$(eval $(call gb_CppunitTest_use_libraries,sax_parser, \ + comphelper \ + cppu \ + cppuhelper \ + unotest \ + expwrap \ + sal \ + sax \ + test \ +)) + +$(eval $(call gb_CppunitTest_use_externals,sax_parser, \ + boost_headers \ +)) + +$(eval $(call gb_CppunitTest_use_sdk_api,sax_parser)) + +$(eval $(call gb_CppunitTest_use_ure,sax_parser)) +$(eval $(call gb_CppunitTest_use_vcl,sax_parser)) + +$(eval $(call gb_CppunitTest_use_components,sax_parser,\ + configmgr/source/configmgr \ + framework/util/fwk \ + i18npool/util/i18npool \ + sfx2/util/sfx \ + ucb/source/core/ucb1 \ + ucb/source/ucp/file/ucpfile1 \ +)) + +$(eval $(call gb_CppunitTest_use_configuration,sax_parser)) + +# vim: set noet sw=4 ts=4: diff --git a/sax/CppunitTest_sax_xmlimport.mk b/sax/CppunitTest_sax_xmlimport.mk new file mode 100644 index 000000000..2e1073632 --- /dev/null +++ b/sax/CppunitTest_sax_xmlimport.mk @@ -0,0 +1,57 @@ +# -*- Mode: makefile-gmake; tab-width: 4; indent-tabs-mode: t -*- +# +# This file is part of the LibreOffice project. +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +# + +$(eval $(call gb_CppunitTest_CppunitTest,sax_xmlimport)) + +$(eval $(call gb_CppunitTest_use_common_precompiled_header,sax_xmlimport)) + +$(eval $(call gb_CppunitTest_add_exception_objects,sax_xmlimport, \ +sax/qa/cppunit/xmlimport \ +)) + +$(eval $(call gb_CppunitTest_use_libraries,sax_xmlimport, \ + test \ + cppu \ + comphelper \ + sal \ + cppuhelper \ + sax \ + unotest \ + utl \ + salhelper \ +)) + +$(eval $(call gb_CppunitTest_use_api,sax_xmlimport,\ + offapi \ + udkapi \ +)) + +$(eval $(call gb_CppunitTest_use_externals,sax_xmlimport, \ + boost_headers \ +)) + +$(eval $(call gb_CppunitTest_use_ure,sax_xmlimport)) +$(eval $(call gb_CppunitTest_use_vcl,sax_xmlimport)) + +$(eval $(call gb_CppunitTest_set_include,sax_xmlimport,\ + -I$(SRCDIR)/sax/inc \ + $$(INCLUDE) \ +)) + +$(eval $(call gb_CppunitTest_use_components,sax_xmlimport,\ + configmgr/source/configmgr \ + sax/source/expatwrap/expwrap \ + ucb/source/core/ucb1 \ + ucb/source/ucp/file/ucpfile1 \ + uui/util/uui \ +)) + +$(eval $(call gb_CppunitTest_use_configuration,sax_xmlimport)) + +# vim: set noet sw=4 ts=4: diff --git a/sax/IwyuFilter_sax.yaml b/sax/IwyuFilter_sax.yaml new file mode 100644 index 000000000..986dcdc98 --- /dev/null +++ b/sax/IwyuFilter_sax.yaml @@ -0,0 +1,2 @@ +--- +assumeFilename: sax/source/fastparser/fastparser.cxx diff --git a/sax/Library_expwrap.mk b/sax/Library_expwrap.mk new file mode 100644 index 000000000..7f4e9004c --- /dev/null +++ b/sax/Library_expwrap.mk @@ -0,0 +1,52 @@ +# -*- Mode: makefile-gmake; tab-width: 4; indent-tabs-mode: t -*- +# +# This file is part of the LibreOffice project. +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +# + +$(eval $(call gb_Library_Library,expwrap)) + +$(eval $(call gb_Library_set_componentfile,expwrap,sax/source/expatwrap/expwrap)) + +$(eval $(call gb_Library_set_include,expwrap,\ + -I$(SRCDIR)/sax/inc \ + $$(INCLUDE) \ +)) + +$(eval $(call gb_Library_use_common_precompiled_header,expwrap)) + +$(eval $(call gb_Library_add_defs,expwrap,\ + -DFASTSAX_DLLIMPLEMENTATION \ +)) + +$(eval $(call gb_Library_use_sdk_api,expwrap)) + +$(eval $(call gb_Library_use_externals,expwrap,\ + boost_headers \ + libxml2 \ + expat \ + zlib \ +)) + +$(eval $(call gb_Library_use_libraries,expwrap,\ + comphelper \ + cppu \ + cppuhelper \ + sal \ + salhelper \ + sax \ + tl \ +)) + +$(eval $(call gb_Library_add_exception_objects,expwrap,\ + sax/source/expatwrap/sax_expat \ + sax/source/expatwrap/saxwriter \ + sax/source/expatwrap/xml2utf \ + sax/source/fastparser/fastparser \ + sax/source/fastparser/legacyfastparser \ +)) + +# vim: set noet sw=4 ts=4: diff --git a/sax/Library_sax.mk b/sax/Library_sax.mk new file mode 100644 index 000000000..6e84a0426 --- /dev/null +++ b/sax/Library_sax.mk @@ -0,0 +1,42 @@ +# -*- Mode: makefile-gmake; tab-width: 4; indent-tabs-mode: t -*- +# +# This file is part of the LibreOffice project. +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +# + +$(eval $(call gb_Library_Library,sax)) + +$(eval $(call gb_Library_set_include,sax,\ + -I$(SRCDIR)/sax/inc \ + $$(INCLUDE) \ +)) + +$(eval $(call gb_Library_use_external,sax,boost_headers)) + +$(eval $(call gb_Library_use_common_precompiled_header,sax)) + +$(eval $(call gb_Library_use_sdk_api,sax)) + +$(eval $(call gb_Library_use_libraries,sax,\ + comphelper \ + cppu \ + cppuhelper \ + sal \ + tl \ +)) + +$(eval $(call gb_Library_add_defs,sax,\ + -DSAX_DLLIMPLEMENTATION \ +)) + +$(eval $(call gb_Library_add_exception_objects,sax,\ + sax/source/tools/converter \ + sax/source/tools/fastattribs \ + sax/source/tools/fastserializer \ + sax/source/tools/fshelper \ +)) + +# vim: set noet sw=4 ts=4: diff --git a/sax/Makefile b/sax/Makefile new file mode 100644 index 000000000..ccb1c85a0 --- /dev/null +++ b/sax/Makefile @@ -0,0 +1,7 @@ +# -*- Mode: makefile-gmake; tab-width: 4; indent-tabs-mode: t -*- + +module_directory:=$(dir $(realpath $(firstword $(MAKEFILE_LIST)))) + +include $(module_directory)/../solenv/gbuild/partial_build.mk + +# vim: set noet sw=4 ts=4: diff --git a/sax/Module_sax.mk b/sax/Module_sax.mk new file mode 100644 index 000000000..4fca4efdc --- /dev/null +++ b/sax/Module_sax.mk @@ -0,0 +1,24 @@ +# -*- Mode: makefile-gmake; tab-width: 4; indent-tabs-mode: t -*- +# +# This file is part of the LibreOffice project. +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +# + +$(eval $(call gb_Module_Module,sax)) + +$(eval $(call gb_Module_add_targets,sax,\ + Library_expwrap \ + Library_sax \ +)) + +$(eval $(call gb_Module_add_check_targets,sax,\ + CppunitTest_sax \ + CppunitTest_sax_attributes \ + CppunitTest_sax_parser \ + CppunitTest_sax_xmlimport \ +)) + +# vim: set noet sw=4 ts=4: diff --git a/sax/README b/sax/README new file mode 100644 index 000000000..00ca0f1af --- /dev/null +++ b/sax/README @@ -0,0 +1,13 @@ +UNO services for SAX parsing and C++ functions for XMLSchema-2 data types. + +* source/expwrap: + string-based SAX parser UNO service wrapping expat +* source/fastparser: + multi-threaded token-based SAX parser UNO service wrapping libxml2 +* source/tools: + + C++ wrapper for fast SAX parser + + C++ XMLSchema-2 data type conversion helpers + +Multi-threading in FastParser can be disabled for debugging purposes with: +SAX_DISABLE_THREADS=1 SAL_LOG="+INFO.sax.fastparser+WARN" + diff --git a/sax/inc/xml2utf.hxx b/sax/inc/xml2utf.hxx new file mode 100644 index 000000000..ead6ac114 --- /dev/null +++ b/sax/inc/xml2utf.hxx @@ -0,0 +1,129 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SAX_INC_XML2UTF_HXX +#define INCLUDED_SAX_INC_XML2UTF_HXX + +#include + +#include + +#include +#include + +#include + +namespace sax_expatwrap { + +class Text2UnicodeConverter +{ + +public: + Text2UnicodeConverter( const OString & sEncoding ); + ~Text2UnicodeConverter(); + + css::uno::Sequence < sal_Unicode > convert( const css::uno::Sequence & ); + bool canContinue() const { return m_bCanContinue; } + +private: + void init( rtl_TextEncoding encoding ); + + rtl_TextToUnicodeConverter m_convText2Unicode; + rtl_TextToUnicodeContext m_contextText2Unicode; + bool m_bCanContinue; + bool m_bInitialized; + css::uno::Sequence m_seqSource; +}; + +/*---------------------------------------- +* +* Unicode2TextConverter +* +**-----------------------------------------*/ +class Unicode2TextConverter +{ +public: + Unicode2TextConverter( rtl_TextEncoding encoding ); + ~Unicode2TextConverter(); + + css::uno::Sequence convert( const sal_Unicode * , sal_Int32 nLength ); + +private: + rtl_UnicodeToTextConverter m_convUnicode2Text; + rtl_UnicodeToTextContext m_contextUnicode2Text; + css::uno::Sequence m_seqSource; +}; + + +/*---------------------------------------- +* +* XMLFile2UTFConverter +* +**-----------------------------------------*/ +class XMLFile2UTFConverter +{ +public: + XMLFile2UTFConverter( ): + m_bStarted( false ) + {} + + void setInputStream( css::uno::Reference< css::io::XInputStream > const &r ) { m_in = r; } + void setEncoding( const OString &s ) { m_sEncoding = s; } + + + // @param nMaxToRead The number of chars, that should be read. Note that this is no exact number. There + // may be returned less or more bytes than ordered. + /// @throws css::io::IOException + /// @throws css::io::NotConnectedException + /// @throws css::io::BufferSizeExceededException + /// @throws css::uno::RuntimeException + sal_Int32 readAndConvert( css::uno::Sequence &seq , sal_Int32 nMaxToRead ); + +private: + + // Called only on first Sequence of bytes. Tries to figure out file format and encoding information. + // @return TRUE, when encoding information could be retrieved + // @return FALSE, when no encoding information was found in file + bool scanForEncoding( css::uno::Sequence &seq ); + + // Called only on first Sequence of bytes. Tries to figure out + // if enough data is available to scan encoding + // @return TRUE, when encoding is retrievable + // @return FALSE, when more data is needed + static bool isEncodingRecognizable( const css::uno::Sequence< sal_Int8 > & seq ); + + // When encoding attribute is within the text (in the first line), it is removed. + static void removeEncoding( css::uno::Sequence &seq ); + + // Initializes decoding depending on m_sEncoding setting + void initializeDecoding(); +private: + css::uno::Reference< css::io::XInputStream > m_in; + + bool m_bStarted; + OString m_sEncoding; + + std::unique_ptr m_pText2Unicode; + std::unique_ptr m_pUnicode2Text; +}; +} + +#endif // INCLUDED_SAX_INC_XML2UTF_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sax/qa/cppunit/attributes.cxx b/sax/qa/cppunit/attributes.cxx new file mode 100644 index 000000000..6c71e9aa1 --- /dev/null +++ b/sax/qa/cppunit/attributes.cxx @@ -0,0 +1,75 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#include +#include +#include +#include +#include + +#include +#include + +using namespace css; +using namespace css::xml; + +namespace { + +class AttributesTest: public CppUnit::TestFixture +{ +public: + void test(); + + CPPUNIT_TEST_SUITE( AttributesTest ); + CPPUNIT_TEST( test ); + CPPUNIT_TEST_SUITE_END(); +}; + +void AttributesTest::test() +{ + rtl::Reference xAttributeList( new sax_fastparser::FastAttributeList(nullptr) ); + xAttributeList->add(1, "1"); + xAttributeList->add(2, OString("2")); + + // We can't test getValueToken() and getOptionalValueToken() + // without XFastTokenHandler :-( + // Uncomment to get segmentation fault: + // xAttributeList->getOptionalValueToken(1, 0); + // xAttributeList->getValueToken(2); + + CPPUNIT_ASSERT( xAttributeList->hasAttribute(1) ); + CPPUNIT_ASSERT( !xAttributeList->hasAttribute(3) ); + + CPPUNIT_ASSERT_EQUAL( OUString("2"), xAttributeList->getOptionalValue(2) ); + CPPUNIT_ASSERT_EQUAL( OUString(), xAttributeList->getOptionalValue(3) ); + + CPPUNIT_ASSERT_EQUAL( OUString("1"), xAttributeList->getValue(1) ); + CPPUNIT_ASSERT_THROW( xAttributeList->getValue(3), xml::sax::SAXException ); + + xAttributeList->addUnknown("a", "a"); + xAttributeList->addUnknown("b", "b", "b"); + xAttributeList->addUnknown("c", "c"); + CPPUNIT_ASSERT_EQUAL( sal_Int32(3), xAttributeList->getUnknownAttributes().getLength() ); + + CPPUNIT_ASSERT_EQUAL( sal_Int32(2), xAttributeList->getFastAttributes().getLength() ); + + xAttributeList->clear(); + CPPUNIT_ASSERT( !xAttributeList->hasAttribute(1) ); + CPPUNIT_ASSERT( !xAttributeList->getFastAttributes().hasElements() ); + xAttributeList->addUnknown("c", "c"); + CPPUNIT_ASSERT_EQUAL( sal_Int32(1), xAttributeList->getUnknownAttributes().getLength() ); +} + +CPPUNIT_TEST_SUITE_REGISTRATION( AttributesTest ); + +} + +CPPUNIT_PLUGIN_IMPLEMENT(); + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sax/qa/cppunit/parser.cxx b/sax/qa/cppunit/parser.cxx new file mode 100644 index 000000000..e5fd9e2ab --- /dev/null +++ b/sax/qa/cppunit/parser.cxx @@ -0,0 +1,101 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +using namespace css; +using namespace css::xml::sax; + +namespace { + +class DummyTokenHandler : public sax_fastparser::FastTokenHandlerBase +{ +public: + DummyTokenHandler() {} + + virtual sal_Int32 SAL_CALL getTokenFromUTF8( const uno::Sequence& ) override + { + return FastToken::DONTKNOW; + } + virtual uno::Sequence< sal_Int8 > SAL_CALL getUTF8Identifier( sal_Int32 ) override + { + CPPUNIT_ASSERT_MESSAGE( "getUTF8Identifier: unexpected call", false ); + return uno::Sequence(); + } + virtual sal_Int32 getTokenDirect( const char * /* pToken */, sal_Int32 /* nLength */ ) const override + { + return -1; + } +}; + +class ParserTest: public test::BootstrapFixture +{ + InputSource maInput; + rtl::Reference< sax_fastparser::FastSaxParser > mxParser; + rtl::Reference< DummyTokenHandler > mxTokenHandler; + +public: + virtual void setUp() override; + + void parse(); + + CPPUNIT_TEST_SUITE(ParserTest); + CPPUNIT_TEST(parse); + CPPUNIT_TEST_SUITE_END(); + +private: + uno::Reference< io::XInputStream > createStream(const OString& sInput); +}; + +void ParserTest::setUp() +{ + test::BootstrapFixture::setUp(); + mxTokenHandler.set( new DummyTokenHandler() ); + mxParser.set( new sax_fastparser::FastSaxParser() ); + mxParser->setTokenHandler( mxTokenHandler.get() ); +} + +uno::Reference< io::XInputStream > ParserTest::createStream(const OString& sInput) +{ + uno::Reference< io::XOutputStream > xPipe( io::Pipe::create(m_xContext) ); + uno::Reference< io::XInputStream > xInStream( xPipe, uno::UNO_QUERY ); + uno::Sequence< sal_Int8 > aSeq( reinterpret_cast(sInput.getStr()), sInput.getLength() ); + xPipe->writeBytes( aSeq ); + xPipe->flush(); + xPipe->closeOutput(); + return xInStream; +} + +void ParserTest::parse() +{ + maInput.aInputStream = createStream("....."); + mxParser->parseStream( maInput ); + + maInput.aInputStream = createStream(""); + CPPUNIT_ASSERT_THROW( mxParser->parseStream( maInput ), css::xml::sax::SAXParseException ); +} + +CPPUNIT_TEST_SUITE_REGISTRATION(ParserTest); + +} + +CPPUNIT_PLUGIN_IMPLEMENT(); + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sax/qa/cppunit/test_converter.cxx b/sax/qa/cppunit/test_converter.cxx new file mode 100644 index 000000000..525e110c1 --- /dev/null +++ b/sax/qa/cppunit/test_converter.cxx @@ -0,0 +1,623 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + +#include +#include + + +using namespace ::com::sun::star; +using namespace ::com::sun::star::util; +using sax::Converter; + + +namespace { + +class ConverterTest + : public ::CppUnit::TestFixture +{ +public: + + void testDuration(); + void testDateTime(); + void testTime(); + void testDouble(); + void testMeasure(); + void testBool(); + void testPercent(); + void testColor(); + void testNumber(); + + CPPUNIT_TEST_SUITE(ConverterTest); + CPPUNIT_TEST(testDuration); + CPPUNIT_TEST(testDateTime); + CPPUNIT_TEST(testTime); + CPPUNIT_TEST(testDouble); + CPPUNIT_TEST(testMeasure); + CPPUNIT_TEST(testBool); + CPPUNIT_TEST(testPercent); + CPPUNIT_TEST(testColor); + CPPUNIT_TEST(testNumber); + CPPUNIT_TEST_SUITE_END(); + +private: +}; + +void doTest(util::Duration const & rid, char const*const pis, + char const*const i_pos = nullptr) +{ + char const*const pos(i_pos ? i_pos : pis); + util::Duration od; + OUString is(OUString::createFromAscii(pis)); + SAL_INFO("sax.cppunit","about to convert '" << is << "'"); + bool bSuccess = Converter::convertDuration(od, is); + SAL_INFO("sax.cppunit","" << (od.Negative ? "-" : "+") << " " << od.Years << "Y " << od.Months << "M " << od.Days << "D " << od.Hours << "H " << od.Minutes << "M " << od.Seconds << "S " << od.NanoSeconds << "n"); + CPPUNIT_ASSERT(bSuccess); + CPPUNIT_ASSERT_EQUAL(rid.Years, od.Years); + CPPUNIT_ASSERT_EQUAL(rid.Months, od.Months); + CPPUNIT_ASSERT_EQUAL(rid.Days, od.Days); + CPPUNIT_ASSERT_EQUAL(rid.Hours, od.Hours); + CPPUNIT_ASSERT_EQUAL(rid.Minutes, od.Minutes); + CPPUNIT_ASSERT_EQUAL(rid.Seconds, od.Seconds); + CPPUNIT_ASSERT_EQUAL(rid.NanoSeconds, od.NanoSeconds); + CPPUNIT_ASSERT_EQUAL(rid.Negative, od.Negative); + OUStringBuffer buf(64); + Converter::convertDuration(buf, od); + SAL_INFO("sax.cppunit","" << buf.toString()); + CPPUNIT_ASSERT(buf.makeStringAndClear().equalsAscii(pos)); +} + +void doTestDurationF(char const*const pis) +{ + util::Duration od; + bool bSuccess = Converter::convertDuration(od, + OUString::createFromAscii(pis)); + SAL_INFO("sax.cppunit","" << (od.Negative ? "-" : "+") << " " << od.Years << "Y " << od.Months << "M " << od.Days << "D " << od.Hours << "H " << od.Minutes << "M " << od.Seconds << "S " << od.NanoSeconds << "n"); + CPPUNIT_ASSERT_MESSAGE(pis, !bSuccess); +} + +void ConverterTest::testDuration() +{ + SAL_INFO("sax.cppunit","\nSAX CONVERTER TEST BEGIN"); + doTest( util::Duration(false, 1, 0, 0, 0, 0, 0, 0), "P1Y" ); + doTest( util::Duration(false, 0, 42, 0, 0, 0, 0, 0), "P42M" ); + doTest( util::Duration(false, 0, 0, 111, 0, 0, 0, 0), "P111D" ); + doTest( util::Duration(false, 0, 0, 0, 52, 0, 0, 0), "PT52H" ); + doTest( util::Duration(false, 0, 0, 0, 0, 717, 0, 0), "PT717M" ); + doTest( util::Duration(false, 0, 0, 0, 0, 0, 121, 0), "PT121S" ); + doTest( util::Duration(false, 0, 0, 0, 0, 0, 0, 190000000), "PT0.19S", "PT0.190000000S"); + doTest( util::Duration(false, 0, 0, 0, 0, 0, 0, 90000000), "PT0.09S", "PT0.090000000S" ); + doTest( util::Duration(false, 0, 0, 0, 0, 0, 0, 9000000), "PT0.009S", "PT0.009000000S" ); + doTest( util::Duration(false, 0, 0, 0, 0, 0, 0, 9), "PT0.000000009S", "PT0.000000009S" ); + doTest( util::Duration(false, 0, 0, 0, 0, 0, 9, 999999999), + "PT9.999999999999999999999999999999S", "PT9.999999999S" ); + doTest( util::Duration(true , 0, 0, 9999, 0, 0, 0, 0), "-P9999D" ); + doTest( util::Duration(true , 7, 6, 5, 4, 3, 2, 10000000), + "-P7Y6M5DT4H3M2.01000S", "-P7Y6M5DT4H3M2.010000000S" ); + doTest( util::Duration(false, 0, 6, 0, 0, 3, 0, 0), "P6MT3M" ); + doTest( util::Duration(false, 0, 0, 0, 0, 0, 0, 0), "P0D" ); + doTestDurationF("1Y1M"); // invalid: no ^P + doTestDurationF("P-1Y1M"); // invalid: - after P + doTestDurationF("P1M1Y"); // invalid: Y after M + doTestDurationF("PT1Y"); // invalid: Y after T + doTestDurationF("P1Y1M1M"); // invalid: M twice, no T + doTestDurationF("P1YT1MT1M"); // invalid: T twice + doTestDurationF("P1YT"); // invalid: T but no H,M,S + doTestDurationF("P99999999999Y"); // cannot parse so many Ys + doTestDurationF("PT.1S"); // invalid: no 0 preceding . + doTestDurationF("PT5M.134S"); // invalid: no 0 preceding . + doTestDurationF("PT1.S"); // invalid: no digit following . + SAL_INFO("sax.cppunit","\nSAX CONVERTER TEST END"); +} + + +bool eqDateTime(const util::DateTime& a, const util::DateTime& b) { + return a.Year == b.Year && a.Month == b.Month && a.Day == b.Day + && a.Hours == b.Hours && a.Minutes == b.Minutes + && a.Seconds == b.Seconds + && a.NanoSeconds == b.NanoSeconds + && a.IsUTC == b.IsUTC; +} + +void doTest(util::DateTime const & rdt, char const*const pis, + char const*const i_pos = nullptr) +{ + char const*const pos(i_pos ? i_pos : pis); + OUString is(OUString::createFromAscii(pis)); + util::DateTime odt; + SAL_INFO("sax.cppunit","about to convert '" << is << "'"); + bool bSuccess( Converter::parseDateTime(odt, is) ); + SAL_INFO("sax.cppunit","Y:" << odt.Year << " M:" << odt.Month << " D:" << odt.Day << " H:" << odt.Hours << " M:" << odt.Minutes << " S:" << odt.Seconds << " nS:" << odt.NanoSeconds << " UTC: " << static_cast(odt.IsUTC)); + CPPUNIT_ASSERT(bSuccess); + CPPUNIT_ASSERT(eqDateTime(rdt, odt)); + OUStringBuffer buf(32); + Converter::convertDateTime(buf, odt, nullptr, true); + SAL_INFO("sax.cppunit","" << buf.toString()); + CPPUNIT_ASSERT_EQUAL(OUString::createFromAscii(pos), + buf.makeStringAndClear()); +} + +void doTestDateTimeF(char const*const pis) +{ + util::DateTime odt; + bool bSuccess = Converter::parseDateTime(odt, OUString::createFromAscii(pis)); + SAL_INFO("sax.cppunit","Y:" << odt.Year << " M:" << odt.Month << " D:" << odt.Day << " H:" << odt.Hours << "H M:" << odt.Minutes << " S:" << odt.Seconds << " nS:" << odt.NanoSeconds); + CPPUNIT_ASSERT(!bSuccess); +} + +void ConverterTest::testDateTime() +{ + SAL_INFO("sax.cppunit","\nSAX CONVERTER TEST BEGIN"); + doTest( util::DateTime(0, 0, 0, 0, 1, 1, 1, false), "0001-01-01T00:00:00" ); + doTest( util::DateTime(0, 0, 0, 0, 1, 1, 1, true), "0001-01-01T00:00:00Z" ); + doTest( util::DateTime(0, 0, 0, 0, 1, 1, -1, false), + "-0001-01-01T00:00:00"); + doTest( util::DateTime(0, 0, 0, 0, 1, 1, -1, true), + "-0001-01-01T01:00:00+01:00", "-0001-01-01T00:00:00Z"); + doTest( util::DateTime(0, 0, 0, 0, 1, 1, -324, false), + "-0324-01-01T00:00:00" ); + doTest( util::DateTime(0, 0, 0, 0, 1, 1, 1, true), + "0001-01-01T00:00:00-00:00", "0001-01-01T00:00:00Z" ); + doTest( util::DateTime(0, 0, 0, 0, 1, 1, 1, true), + "0001-01-01T00:00:00+00:00", "0001-01-01T00:00:00Z" ); + doTest( util::DateTime(0, 0, 0, 12, 2, 1, 1, true), + "0001-01-02T00:00:00-12:00", "0001-01-02T12:00:00Z" ); + doTest( util::DateTime(0, 0, 0, 12, 1, 1, 1, true), + "0001-01-02T00:00:00+12:00", "0001-01-01T12:00:00Z" ); + doTest( util::DateTime(990000000, 59, 59, 23, 31, 12, 9999, false), + "9999-12-31T23:59:59.99", "9999-12-31T23:59:59.990000000" ); + doTest( util::DateTime(990000000, 59, 59, 23, 31, 12, 9999, true), + "9999-12-31T23:59:59.99Z", "9999-12-31T23:59:59.990000000Z" ); + doTest( util::DateTime(999999999, 59, 59, 23, 31, 12, 9999, false), + "9999-12-31T23:59:59.9999999999999999999999999999999999999", + "9999-12-31T23:59:59.999999999" ); + doTest( util::DateTime(999999999, 59, 59, 23, 31, 12, 9999, true), + "9999-12-31T23:59:59.9999999999999999999999999999999999999Z", + "9999-12-31T23:59:59.999999999Z" ); + doTest( util::DateTime(0, 0, 0, 0, 29, 2, 2000, true), // leap year + "2000-02-29T00:00:00-00:00", "2000-02-29T00:00:00Z" ); + doTest( util::DateTime(0, 0, 0, 0, 29, 2, 1600, true), // leap year + "1600-02-29T00:00:00-00:00", "1600-02-29T00:00:00Z" ); + doTest( util::DateTime(0, 0, 0, 24, 1, 1, 333, false) + /*(0, 0, 0, 0, 2, 1, 333)*/, + "0333-01-01T24:00:00"/*, "0333-01-02T00:00:00"*/ ); + // While W3C XMLSchema specifies a minimum of 4 year digits we are lenient + // in what we accept. + doTest( util::DateTime(0, 0, 0, 0, 1, 1, 1, false), + "1-01-01T00:00:00", "0001-01-01T00:00:00" ); + doTestDateTimeF( "+0001-01-01T00:00:00" ); // invalid: ^+ + doTestDateTimeF( "0001-1-01T00:00:00" ); // invalid: < 2 M + doTestDateTimeF( "0001-01-1T00:00:00" ); // invalid: < 2 D + doTestDateTimeF( "0001-01-01T0:00:00" ); // invalid: < 2 H + doTestDateTimeF( "0001-01-01T00:0:00" ); // invalid: < 2 M + doTestDateTimeF( "0001-01-01T00:00:0" ); // invalid: < 2 S + doTestDateTimeF( "0001-01-01T00:00:00." ); // invalid: .$ + doTestDateTimeF( "0001-01-01T00:00:00+1:00" ); // invalid: < 2 TZ H + doTestDateTimeF( "0001-01-01T00:00:00+00:1" ); // invalid: < 2 TZ M + doTestDateTimeF( "0001-13-01T00:00:00" ); // invalid: M > 12 + doTestDateTimeF( "0001-01-32T00:00:00" ); // invalid: D > 31 + doTestDateTimeF( "0001-01-01T25:00:00" ); // invalid: H > 24 + doTestDateTimeF( "0001-01-01T00:60:00" ); // invalid: M > 59 + doTestDateTimeF( "0001-01-01T00:00:60" ); // invalid: S > 59 + doTestDateTimeF( "0001-01-01T24:01:00" ); // invalid: H=24, but M != 0 + doTestDateTimeF( "0001-01-01T24:00:01" ); // invalid: H=24, but S != 0 + doTestDateTimeF( "0001-01-01T24:00:00.1" ); // invalid: H=24, but H != 0 + doTestDateTimeF( "0001-01-02T00:00:00+15:00" ); // invalid: TZ > +14:00 + doTestDateTimeF( "0001-01-02T00:00:00+14:01" ); // invalid: TZ > +14:00 + doTestDateTimeF( "0001-01-02T00:00:00-15:00" ); // invalid: TZ < -14:00 + doTestDateTimeF( "0001-01-02T00:00:00-14:01" ); // invalid: TZ < -14:00 + doTestDateTimeF( "2100-02-29T00:00:00-00:00" ); // invalid: no leap year + doTestDateTimeF( "1900-02-29T00:00:00-00:00" ); // invalid: no leap year + doTestDateTimeF( "00:00:00" ); // invalid: no date + doTestDateTimeF( "T00:00:00" ); // invalid: no date + SAL_INFO("sax.cppunit","\nSAX CONVERTER TEST END"); +} + +void doTestTime(util::DateTime const & rdt, char const*const pis, + char const*const i_pos = nullptr) +{ + char const*const pos(i_pos ? i_pos : pis); + OUString is(OUString::createFromAscii(pis)); + util::DateTime odt; + SAL_INFO("sax.cppunit","about to convert '" << is << "'"); + bool bSuccess( Converter::parseTimeOrDateTime(odt, is) ); + SAL_INFO("sax.cppunit","Y:" << odt.Year << " M:" << odt.Month << " D:" << odt.Day << " H:" << odt.Hours << " M:" << odt.Minutes << " S:" << odt.Seconds << " nS:" << odt.NanoSeconds << " UTC: " << static_cast(odt.IsUTC)); + CPPUNIT_ASSERT(bSuccess); + CPPUNIT_ASSERT(eqDateTime(rdt, odt)); + OUStringBuffer buf(32); + Converter::convertTimeOrDateTime(buf, odt); + SAL_INFO("sax.cppunit","" << buf.toString()); + CPPUNIT_ASSERT_EQUAL(OUString::createFromAscii(pos), + buf.makeStringAndClear()); +} + +void doTestTimeF(char const*const pis) +{ + util::DateTime odt; + bool bSuccess = Converter::parseTimeOrDateTime(odt, OUString::createFromAscii(pis)); + SAL_INFO("sax.cppunit","Y:" << odt.Year << " M:" << odt.Month << " D:" << odt.Day << " H:" << odt.Hours << "H M:" << odt.Minutes << " S:" << odt.Seconds << " nS:" << odt.NanoSeconds); + CPPUNIT_ASSERT_MESSAGE(pis, !bSuccess); +} + +void ConverterTest::testTime() // time or dateTime + horrible backcompat mess +{ + doTestTime( util::DateTime(0, 0, 0, 0, 1, 1, 1, false), + "0001-01-01T00:00:00" ); + doTestTime( util::DateTime(0, 0, 0, 0, 1, 1, 1, false), + "0001-01-01T00:00:00" ); + doTestTime( util::DateTime(0, 0, 0, 0, 1, 1, 1, true), + "0001-01-01T00:00:00Z" ); + doTestTime( util::DateTime(0, 0, 0, 0, 1, 1, -1, false), + "-0001-01-01T00:00:00"); + doTestTime( util::DateTime(0, 0, 0, 0, 1, 1, -1, true), + "-0001-01-01T01:00:00+01:00", "-0001-01-01T00:00:00Z"); + doTestTime( util::DateTime(0, 0, 0, 0, 1, 1, -324, false), + "-0324-01-01T00:00:00" ); + doTestTime( util::DateTime(0, 0, 0, 0, 1, 1, 1, true), + "0001-01-01T00:00:00-00:00", "0001-01-01T00:00:00Z" ); + doTestTime( util::DateTime(0, 0, 0, 0, 1, 1, 1, true), + "0001-01-01T00:00:00+00:00", "0001-01-01T00:00:00Z" ); + doTestTime( util::DateTime(0, 0, 0, 12, 2, 1, 1, true), + "0001-01-02T00:00:00-12:00", "0001-01-02T12:00:00Z" ); + doTestTime( util::DateTime(0, 0, 0, 12, 1, 1, 1, true), + "0001-01-02T00:00:00+12:00", "0001-01-01T12:00:00Z" ); + doTestTime( util::DateTime(990000000, 59, 59, 23, 31, 12, 9999, false), + "9999-12-31T23:59:59.99", "9999-12-31T23:59:59.990000000" ); + doTestTime( util::DateTime(990000000, 59, 59, 23, 31, 12, 9999, true), + "9999-12-31T23:59:59.99Z", "9999-12-31T23:59:59.990000000Z" ); + doTestTime( util::DateTime(999999999, 59, 59, 23, 31, 12, 9999, false), + "9999-12-31T23:59:59.9999999999999999999999999999999999999", + "9999-12-31T23:59:59.999999999" ); + doTestTime( util::DateTime(999999999, 59, 59, 23, 31, 12, 9999, true), + "9999-12-31T23:59:59.9999999999999999999999999999999999999Z", + "9999-12-31T23:59:59.999999999Z" ); + doTestTime( util::DateTime(0, 0, 0, 0, 29, 2, 2000, true), // leap year + "2000-02-29T00:00:00-00:00", "2000-02-29T00:00:00Z" ); + doTestTime( util::DateTime(0, 0, 0, 0, 29, 2, 1600, true), // leap year + "1600-02-29T00:00:00-00:00", "1600-02-29T00:00:00Z" ); + doTestTime( util::DateTime(0, 0, 0, 24, 1, 1, 333, false) + /*(0, 0, 0, 0, 2, 1, 333)*/, + "0333-01-01T24:00:00"/*, "0333-01-02T00:00:00"*/ ); + // While W3C XMLSchema specifies a minimum of 4 year digits we are lenient + // in what we accept. + doTestTime( util::DateTime(0, 0, 0, 0, 1, 1, 1, false), + "1-01-01T00:00:00", "0001-01-01T00:00:00" ); + + doTestTime( util::DateTime(0, 0, 0, 0, 0, 0, 0, false), "00:00:00" ); + doTestTime( util::DateTime(0, 0, 0, 24, 0, 0, 0, false), "24:00:00" ); + doTestTime( util::DateTime(0, 0, 59, 0, 0, 0, 0, false), "00:59:00" ); + doTestTime( util::DateTime(0, 1, 2, 4, 0, 0, 0, true), "04:02:01Z" ); + doTestTime( util::DateTime(0, 1, 2, 4, 0, 0, 0, true), + "05:02:01+01:00", "04:02:01Z" ); + doTestTime( util::DateTime(0, 11, 12, 9, 0, 0, 0, true), + "05:12:11-04:00", "09:12:11Z" ); + doTestTime( util::DateTime(990000000, 59, 59, 23, 0, 0, 0, false), + "23:59:59.99", "23:59:59.990000000" ); + doTestTime( util::DateTime(990000000, 59, 59, 23, 0, 0, 0, true), + "23:59:59.99Z", "23:59:59.990000000Z" ); + // backwards compatible: recognize invalid 0000-00-00 date (LO 3.5) + doTestTime( util::DateTime(0, 1, 0, 0, 0, 0, 0, false), + "0000-00-00T00:00:01", "00:00:01" ); + // backwards compatible: recognize invalid 0-00-00 date (OOo) + doTestTime( util::DateTime(0, 0, 1, 0, 0, 0, 0, false), + "0-00-00T00:01:00", "00:01:00" ); + + doTestTimeF( "+0001-01-01T00:00:00" ); // invalid: ^+ + doTestTimeF( "0001-1-01T00:00:00" ); // invalid: < 2 M + doTestTimeF( "0001-01-1T00:00:00" ); // invalid: < 2 D + doTestTimeF( "0001-01-01T0:00:00" ); // invalid: < 2 H + doTestTimeF( "0001-01-01T00:0:00" ); // invalid: < 2 M + doTestTimeF( "0001-01-01T00:00:0" ); // invalid: < 2 S + doTestTimeF( "0001-01-01T00:00:00." ); // invalid: .$ + doTestTimeF( "0001-01-01T00:00:00+1:00" ); // invalid: < 2 TZ H + doTestTimeF( "0001-01-01T00:00:00+00:1" ); // invalid: < 2 TZ M + doTestTimeF( "0001-13-01T00:00:00" ); // invalid: M > 12 + doTestTimeF( "0001-01-32T00:00:00" ); // invalid: D > 31 + doTestTimeF( "0001-01-01T25:00:00" ); // invalid: H > 24 + doTestTimeF( "0001-01-01T00:60:00" ); // invalid: M > 59 + doTestTimeF( "0001-01-01T00:00:60" ); // invalid: S > 59 + doTestTimeF( "0001-01-01T24:01:00" ); // invalid: H=24, but M != 0 + doTestTimeF( "0001-01-01T24:00:01" ); // invalid: H=24, but S != 0 + doTestTimeF( "0001-01-01T24:00:00.1" ); // invalid: H=24, but H != 0 + doTestTimeF( "0001-01-02T00:00:00+15:00" ); // invalid: TZ > +14:00 + doTestTimeF( "0001-01-02T00:00:00+14:01" ); // invalid: TZ > +14:00 + doTestTimeF( "0001-01-02T00:00:00-15:00" ); // invalid: TZ < -14:00 + doTestTimeF( "0001-01-02T00:00:00-14:01" ); // invalid: TZ < -14:00 + doTestTimeF( "2100-02-29T00:00:00-00:00" ); // invalid: no leap year + doTestTimeF( "1900-02-29T00:00:00-00:00" ); // invalid: no leap year + doTestTimeF( "T00:00:00" ); // invalid: T + doTestTimeF( "0:00:00" ); // invalid: < 2 H + doTestTimeF( "00:0:00" ); // invalid: < 2 M + doTestTimeF( "00:00:0" ); // invalid: < 2 S + doTestTimeF( "00:00:00." ); // invalid: .$ + doTestTimeF( "00:00:00+1:00" ); // invalid: < 2 TZ H + doTestTimeF( "00:00:00+00:1" ); // invalid: < 2 TZ M + doTestTimeF( "25:00:00" ); // invalid: H > 24 + doTestTimeF( "00:60:00" ); // invalid: M > 59 + doTestTimeF( "00:00:60" ); // invalid: S > 59 + doTestTimeF( "24:01:00" ); // invalid: H=24, but M != 0 + doTestTimeF( "24:00:01" ); // invalid: H=24, but S != 0 + doTestTimeF( "24:00:00.1" ); // invalid: H=24, but H != 0 + doTestTimeF( "00:00:00+15:00" ); // invalid: TZ > +14:00 + doTestTimeF( "00:00:00+14:01" ); // invalid: TZ > +14:00 + doTestTimeF( "00:00:00-15:00" ); // invalid: TZ < -14:00 + doTestTimeF( "00:00:00-14:01" ); // invalid: TZ < -14:00 +} + +void doTestDouble(char const*const pis, double const rd, + sal_Int16 const nSourceUnit, sal_Int16 const nTargetUnit) +{ + OUString const is(OUString::createFromAscii(pis)); + double od; + bool bSuccess(Converter::convertDouble(od, is, nSourceUnit, nTargetUnit)); + SAL_INFO("sax.cppunit","" << od); + CPPUNIT_ASSERT(bSuccess); + CPPUNIT_ASSERT_DOUBLES_EQUAL(rd, od, 0.00000001); + OUStringBuffer buf; + Converter::convertDouble(buf, od, true, nTargetUnit, nSourceUnit); + SAL_INFO("sax.cppunit","" << buf.toString()); + CPPUNIT_ASSERT_EQUAL(is, buf.makeStringAndClear()); +} + +void ConverterTest::testDouble() +{ + doTestDouble("42", 42.0, MeasureUnit::TWIP, MeasureUnit::TWIP); + doTestDouble("42", 42.0, MeasureUnit::POINT, MeasureUnit::POINT); + doTestDouble("42", 42.0, MeasureUnit::MM_100TH, MeasureUnit::MM_100TH); + doTestDouble("42", 42.0, MeasureUnit::MM_10TH, MeasureUnit::MM_10TH); + doTestDouble("42", 42.0, MeasureUnit::MM, MeasureUnit::MM); // identity don't seem to add unit? + doTestDouble("42", 42.0, MeasureUnit::CM, MeasureUnit::CM); + doTestDouble("42", 42.0, MeasureUnit::INCH, MeasureUnit::INCH); + doTestDouble("2pt", 40.0, MeasureUnit::POINT, MeasureUnit::TWIP); + doTestDouble("20pc", 1, MeasureUnit::TWIP, MeasureUnit::POINT); + doTestDouble("4", 2.26771653543307, MeasureUnit::MM_100TH, MeasureUnit::TWIP); + doTestDouble("4", 22.6771653543307, MeasureUnit::MM_10TH, MeasureUnit::TWIP); + doTestDouble("4mm", 226.771653543307, MeasureUnit::MM, MeasureUnit::TWIP); + doTestDouble("4cm", 2267.71653543307, MeasureUnit::CM, MeasureUnit::TWIP); + doTestDouble("4in", 5760.0, MeasureUnit::INCH, MeasureUnit::TWIP); + doTestDouble("1440pc", 1.0, MeasureUnit::TWIP, MeasureUnit::INCH); + doTestDouble("567pc", 1.000125, MeasureUnit::TWIP, MeasureUnit::CM); + doTestDouble("56.7pc", 1.000125, MeasureUnit::TWIP, MeasureUnit::MM); + doTestDouble("5.67pc", 1.000125, MeasureUnit::TWIP, MeasureUnit::MM_10TH); + doTestDouble("0.567pc", 1.000125, MeasureUnit::TWIP, MeasureUnit::MM_100TH); + doTestDouble("42pt", 1.4816666666666, MeasureUnit::POINT, MeasureUnit::CM); + doTestDouble("42pt", 14.816666666666, MeasureUnit::POINT, MeasureUnit::MM); + doTestDouble("42pt", 148.16666666666, MeasureUnit::POINT, MeasureUnit::MM_10TH); + doTestDouble("42pt", 1481.6666666666, MeasureUnit::POINT, MeasureUnit::MM_100TH); + doTestDouble("72pt", 1.0, MeasureUnit::POINT, MeasureUnit::INCH); + doTestDouble("3.5in", 8.89, MeasureUnit::INCH, MeasureUnit::CM); + doTestDouble("3.5in", 88.9, MeasureUnit::INCH, MeasureUnit::MM); + doTestDouble("3.5in", 889.0, MeasureUnit::INCH, MeasureUnit::MM_10TH); + doTestDouble("3.5in", 8890.0, MeasureUnit::INCH, MeasureUnit::MM_100TH); + doTestDouble("2in", 144, MeasureUnit::INCH, MeasureUnit::POINT); + doTestDouble("5.08cm", 2.0, MeasureUnit::CM, MeasureUnit::INCH); + doTestDouble("3.5cm", 3500.0, MeasureUnit::CM, MeasureUnit::MM_100TH); + doTestDouble("3.5cm", 350.0, MeasureUnit::CM, MeasureUnit::MM_10TH); + doTestDouble("3.5cm", 35.0, MeasureUnit::CM, MeasureUnit::MM); + doTestDouble("10cm", 283.464566929134, MeasureUnit::CM, MeasureUnit::POINT); + doTestDouble("0.5cm", 283.464566929134, MeasureUnit::CM, MeasureUnit::TWIP); + doTestDouble("10mm", 28.3464566929134, MeasureUnit::MM, MeasureUnit::POINT); + doTestDouble("0.5mm", 28.3464566929134, MeasureUnit::MM, MeasureUnit::TWIP); + doTestDouble("10", 2.83464566929134, MeasureUnit::MM_10TH, MeasureUnit::POINT); + doTestDouble("0.5", 2.83464566929134, MeasureUnit::MM_10TH, MeasureUnit::TWIP); + doTestDouble("10", 0.283464566929134, MeasureUnit::MM_100TH, MeasureUnit::POINT); + doTestDouble("0.5", 0.283464566929134, MeasureUnit::MM_100TH, MeasureUnit::TWIP); + doTestDouble("10mm", 1.0, MeasureUnit::MM, MeasureUnit::CM); + doTestDouble("10mm", 100.0, MeasureUnit::MM, MeasureUnit::MM_10TH); + doTestDouble("20mm", 2000.0, MeasureUnit::MM, MeasureUnit::MM_100TH); + doTestDouble("300", 30.0, MeasureUnit::MM_10TH, MeasureUnit::MM); + doTestDouble("400", 4.0, MeasureUnit::MM_100TH, MeasureUnit::MM); + doTestDouble("600", 6000.0, MeasureUnit::MM_10TH, MeasureUnit::MM_100TH); + doTestDouble("700", 70.0, MeasureUnit::MM_100TH, MeasureUnit::MM_10TH); +} + +void doTestStringToMeasure(sal_Int32 rValue, char const*const pis, sal_Int16 nTargetUnit, sal_Int32 nMin, sal_Int32 nMax) +{ + OUString const is(OUString::createFromAscii(pis)); + sal_Int32 nVal; + bool bSuccess(Converter::convertMeasure(nVal, is, nTargetUnit, nMin, nMax)); + SAL_INFO("sax.cppunit","" << nVal); + CPPUNIT_ASSERT(bSuccess); + CPPUNIT_ASSERT_EQUAL(rValue, nVal); +} + +void doTestMeasureToString(char const*const pis, sal_Int32 nMeasure, sal_Int16 const nSourceUnit, sal_Int16 const nTargetUnit) +{ + OUString const is(OUString::createFromAscii(pis)); + OUStringBuffer buf; + Converter::convertMeasure(buf, nMeasure, nSourceUnit, nTargetUnit); + SAL_INFO("sax.cppunit","" << buf.toString()); + CPPUNIT_ASSERT_EQUAL(is, buf.makeStringAndClear()); +} + +void ConverterTest::testMeasure() +{ + //check all the measure units + doTestStringToMeasure(1000, "10mm", MeasureUnit::MM_100TH, -1, 4321); + doTestStringToMeasure(200, "20mm", MeasureUnit::MM_10TH, 12, 4567); + doTestStringToMeasure(300, "300", MeasureUnit::MM, 31, 555); + doTestStringToMeasure(400, "400", MeasureUnit::CM, 10, 4321); + doTestStringToMeasure(120, "120", MeasureUnit::INCH_1000TH, 10, 4321); + doTestStringToMeasure(111, "111", MeasureUnit::INCH_100TH, 10, 4321); + doTestStringToMeasure(22, "22", MeasureUnit::INCH_10TH, 10, 4321); + doTestStringToMeasure(27, "27", MeasureUnit::INCH, 10, 4321); + doTestStringToMeasure(52, "52", MeasureUnit::POINT, 10, 4321); + doTestStringToMeasure(120, "120", MeasureUnit::TWIP, 10, 4321); + doTestStringToMeasure(666, "666", MeasureUnit::M, 10, 4321); + doTestStringToMeasure(42, "42", MeasureUnit::KM, 10, 4321); + doTestStringToMeasure(30, "30", MeasureUnit::PICA, 10, 4321); + doTestStringToMeasure(20, "20", MeasureUnit::FOOT, 10, 4321); + doTestStringToMeasure(40, "40", MeasureUnit::MILE, 10, 4321); + doTestStringToMeasure(40, "40%", MeasureUnit::PERCENT, 10, 4321); + doTestStringToMeasure(800, "800", MeasureUnit::PIXEL, 10, 4321); + doTestStringToMeasure(600, "600px", MeasureUnit::PIXEL, 10, 4321); + doTestStringToMeasure(777, "777", MeasureUnit::APPFONT, 10, 4321); + doTestStringToMeasure(80000, "80000", MeasureUnit::SYSFONT, 10, 432100); + //strange values (negative, too large etc.) + doTestStringToMeasure(555, "666", MeasureUnit::MM, -1000, 555); + doTestStringToMeasure(-1000, "-1001", MeasureUnit::MM, -1000, 555); + doTestStringToMeasure(0, "-0", MeasureUnit::MM, -1, 0); + doTestStringToMeasure(::std::numeric_limits::max(), "1234567890mm", MeasureUnit::MM_10TH, 12, ::std::numeric_limits::max()); + doTestStringToMeasure(-300, "-300", MeasureUnit::MM, -1000, 555); + doTestStringToMeasure(::std::numeric_limits::min(), "-999999999999999px", MeasureUnit::PIXEL, ::std::numeric_limits::min(), 555); //really crazy numbers... + + doTestMeasureToString("6mm", 600, MeasureUnit::MM_100TH, MeasureUnit::MM); + doTestMeasureToString("0.005cm", 000000005, MeasureUnit::MM_100TH, MeasureUnit::CM); // zeros in the front doesn't count + doTestMeasureToString("3mm", 30, MeasureUnit::MM_10TH, MeasureUnit::MM); + doTestMeasureToString("6.66cm", 666, MeasureUnit::MM_10TH, MeasureUnit::CM); + doTestMeasureToString("-157.3pt", -555, MeasureUnit::MM_10TH, MeasureUnit::POINT); + doTestMeasureToString("174976.378in", 44444000, MeasureUnit::MM_10TH, MeasureUnit::INCH); //let's check accuracy + doTestMeasureToString("40%", 40, MeasureUnit::PERCENT, MeasureUnit::PERCENT); + doTestMeasureToString("70.56mm", 4000, MeasureUnit::TWIP, MeasureUnit::MM); + doTestMeasureToString("979.928cm", 555550, MeasureUnit::TWIP, MeasureUnit::CM); + doTestMeasureToString("111.1pt", 2222, MeasureUnit::TWIP, MeasureUnit::POINT); + doTestMeasureToString("385.7986in", 555550, MeasureUnit::TWIP, MeasureUnit::INCH); + doTestMeasureToString("-2147483.648cm", std::numeric_limits::min(), MeasureUnit::MM_100TH, MeasureUnit::CM); +} + +void doTestStringToBool(bool bBool, char const*const pis) +{ + OUString const is(OUString::createFromAscii(pis)); + bool bTemp; + bool bSuccess(Converter::convertBool(bTemp, is)); + SAL_INFO("sax.cppunit","" << bTemp); + CPPUNIT_ASSERT(bSuccess); + CPPUNIT_ASSERT_EQUAL(bBool, bTemp); + +} + +void doTestBoolToString(char const*const pis, bool bValue ) +{ + OUString const is(OUString::createFromAscii(pis)); + OUStringBuffer buf; + Converter::convertBool(buf, bValue); + SAL_INFO("sax.cppunit","" << buf.toString()); + CPPUNIT_ASSERT_EQUAL(is, buf.makeStringAndClear()); +} + +void ConverterTest::testBool() +{ + doTestStringToBool(true, "true"); + doTestStringToBool(false, "false"); + doTestBoolToString("true", true); + doTestBoolToString("false", false); +} + +void doTestStringToPercent(sal_Int32 nValue, char const*const pis) +{ + OUString const is(OUString::createFromAscii(pis)); + sal_Int32 nTemp; + bool bSuccess(Converter::convertPercent(nTemp, is)); + SAL_INFO("sax.cppunit","" << nTemp); + CPPUNIT_ASSERT(bSuccess); + CPPUNIT_ASSERT_EQUAL(nValue, nTemp); +} + +void doTestPercentToString(char const*const pis, sal_Int32 nValue) +{ + OUString const is(OUString::createFromAscii(pis)); + OUStringBuffer buf; + Converter::convertPercent(buf, nValue); + SAL_INFO("sax.cppunit","" << buf.toString()); + CPPUNIT_ASSERT_EQUAL(is, buf.makeStringAndClear()); +} + +void ConverterTest::testPercent() +{ + doTestStringToPercent(40, "40%"); + doTestStringToPercent(30, "30"); + doTestStringToPercent(120, "120%"); + doTestStringToPercent(-40, "-40%"); + doTestStringToPercent(0, "0%"); + doTestPercentToString("12%", 12); + doTestPercentToString("-123%", -123); + doTestPercentToString("0%", 0); + doTestPercentToString("1%", 00001); +} + +void doTestStringToColor(sal_Int32 nValue, char const*const pis) +{ + OUString const is(OUString::createFromAscii(pis)); + sal_Int32 nTemp; + bool bSuccess(Converter::convertColor(nTemp, is)); + SAL_INFO("sax.cppunit","" << nTemp); + CPPUNIT_ASSERT(bSuccess); + CPPUNIT_ASSERT_EQUAL(nValue, nTemp); +} + +void doTestColorToString(char const*const pis, sal_Int32 nValue) +{ + OUString const is(OUString::createFromAscii(pis)); + OUStringBuffer buf; + Converter::convertColor(buf, nValue); + SAL_INFO("sax.cppunit","" << buf.toString()); + CPPUNIT_ASSERT_EQUAL(is, buf.makeStringAndClear()); +} + +void ConverterTest::testColor() +{ + doTestStringToColor(11259375, "#abcdef"); + doTestStringToColor(160, "#0000a0"); + doTestStringToColor(40960, "#00a000"); + doTestStringToColor(0, "#000000"); + doTestColorToString("#000615", 1557); + doTestColorToString("#5bcd15", 123456789); + doTestColorToString("#fffac7", -1337); + doTestColorToString("#000000", 0); +} + +void doTestStringToNumber(sal_Int32 nValue, char const*const pis, sal_Int32 nMin, sal_Int32 nMax) +{ + OUString const is(OUString::createFromAscii(pis)); + sal_Int32 nTemp; + bool bSuccess(Converter::convertNumber(nTemp, is, nMin, nMax)); + SAL_INFO("sax.cppunit","" << nTemp); + CPPUNIT_ASSERT(bSuccess); + CPPUNIT_ASSERT_EQUAL(nValue, nTemp); +} + +void ConverterTest::testNumber() +{ + doTestStringToNumber(30, "30", 1, 40); + doTestStringToNumber(1, "-5", 1, 300); + doTestStringToNumber(-30, "7", -100, -30); + doTestStringToNumber(0, "-0", 0, 1); + doTestStringToNumber(0, "666", -0, 0); +} + +CPPUNIT_TEST_SUITE_REGISTRATION(ConverterTest); + +} + +CPPUNIT_PLUGIN_IMPLEMENT(); + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sax/qa/cppunit/xmlimport.cxx b/sax/qa/cppunit/xmlimport.cxx new file mode 100644 index 000000000..449c9ef3b --- /dev/null +++ b/sax/qa/cppunit/xmlimport.cxx @@ -0,0 +1,450 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace { + +using namespace css; +using namespace uno; +using namespace io; +using namespace xml::sax; +using namespace std; +using namespace ::osl; +using namespace sax_fastparser; + +Reference< XInputStream > createStreamFromFile ( + const OUString & filePath) +{ + Reference< XInputStream > xInputStream; + OUString aInStr; + FileBase::getFileURLFromSystemPath(filePath, aInStr); + std::unique_ptr pStream = utl::UcbStreamHelper::CreateStream(aInStr, StreamMode::READ); + if(pStream == nullptr) + CPPUNIT_ASSERT(false); + Reference< XStream > xStream(new utl::OStreamWrapper(std::move(pStream))); + xInputStream.set(xStream, UNO_QUERY); + return xInputStream; +} + +class TestDocumentHandler : public cppu::WeakImplHelper< XDocumentHandler > +{ +private: + OUString m_aStr; + deque< pair > m_aNamespaceStack; + stack m_aCountStack; + + OUString canonicalform(const OUString &sName, const OUString &sValue, bool isElement); + OUString getNamespace(const OUString &sName); + +public: + TestDocumentHandler() {} + const OUString & getString() const { return m_aStr; } + + // XDocumentHandler + virtual void SAL_CALL startDocument() override; + virtual void SAL_CALL endDocument() override; + virtual void SAL_CALL startElement( const OUString& aName, const Reference< XAttributeList >& xAttribs ) override; + virtual void SAL_CALL endElement( const OUString& aName ) override; + virtual void SAL_CALL characters( const OUString& aChars ) override; + virtual void SAL_CALL ignorableWhitespace( const OUString& aWhitespaces ) override; + virtual void SAL_CALL processingInstruction( const OUString& aTarget, const OUString& aData ) override; + virtual void SAL_CALL setDocumentLocator( const Reference< XLocator >& xLocator ) override; +}; + +OUString TestDocumentHandler::canonicalform(const OUString &sName, const OUString &sValue, bool isElement) +{ + sal_Int16 nIndex = sName.indexOf(":"); + if ( !isElement && sName.match( "xmlns" ) ) + { + m_aCountStack.top() += 1; + if ( nIndex < 0 ) + m_aNamespaceStack.emplace_back( OUString( "default" ), sValue ); + else + m_aNamespaceStack.emplace_back( sName.copy( nIndex + 1 ), sValue ); + } + else + { + if ( nIndex >= 0 ) + { + OUString sNamespace = getNamespace( sName.copy( 0, nIndex ) ); + return sNamespace + sName.copy(nIndex); + } + else + { + OUString sDefaultns = getNamespace( "default" ); + if ( !isElement || sDefaultns.isEmpty() ) + return sName; + else + return sDefaultns + ":" + sName; + } + } + return OUString(); +} + +OUString TestDocumentHandler::getNamespace(const OUString &sName) +{ + for (sal_Int16 i = m_aNamespaceStack.size() - 1; i>=0; i--) + { + pair aPair = m_aNamespaceStack.at(i); + if (aPair.first == sName) + return aPair.second; + } + return OUString(); +} + +void SAL_CALL TestDocumentHandler::startDocument() +{ + m_aStr.clear(); + m_aNamespaceStack.clear(); + m_aNamespaceStack.emplace_back( make_pair( OUString( "default" ), OUString() ) ); + m_aCountStack = stack(); + m_aCountStack.emplace(0); +} + + +void SAL_CALL TestDocumentHandler::endDocument() +{ +} + +void SAL_CALL TestDocumentHandler::startElement( const OUString& aName, const Reference< XAttributeList >& xAttribs ) +{ + OUString sAttributes; + m_aCountStack.push(0); + sal_uInt16 len = xAttribs->getLength(); + for (sal_uInt16 i=0; igetValueByIndex(i); + OUString sAttrName = canonicalform(xAttribs->getNameByIndex(i), sAttrValue, false); + if (!sAttrName.isEmpty()) + sAttributes += sAttrName + sAttrValue; + } + m_aStr += canonicalform(aName, "", true) + sAttributes; +} + + +void SAL_CALL TestDocumentHandler::endElement( const OUString& aName ) +{ + m_aStr += canonicalform(aName, "", true); + sal_uInt16 nPopQty = m_aCountStack.top(); + for (sal_uInt16 i=0; i& /*xLocator*/ ) +{ +} + +class NSDocumentHandler : public cppu::WeakImplHelper< XDocumentHandler > +{ +public: + NSDocumentHandler() {} + + // XDocumentHandler + virtual void SAL_CALL startDocument() override {} + virtual void SAL_CALL endDocument() override {} + virtual void SAL_CALL startElement( const OUString& aName, const Reference< XAttributeList >& xAttribs ) override; + virtual void SAL_CALL endElement( const OUString& /* aName */ ) override {} + virtual void SAL_CALL characters( const OUString& /* aChars */ ) override {} + virtual void SAL_CALL ignorableWhitespace( const OUString& /* aWhitespaces */ ) override {} + virtual void SAL_CALL processingInstruction( const OUString& /* aTarget */, const OUString& /* aData */ ) override {} + virtual void SAL_CALL setDocumentLocator( const Reference< XLocator >& /* xLocator */ ) override {} +}; + +OUString getNamespaceValue( const OUString& rNamespacePrefix ) +{ + OUString aNamespaceURI; + if (rNamespacePrefix == "office") + aNamespaceURI = "urn:oasis:names:tc:opendocument:xmlns:office:1.0"; + else if (rNamespacePrefix == "text") + aNamespaceURI = "urn:oasis:names:tc:opendocument:xmlns:text:1.0"; + else if (rNamespacePrefix == "note") + aNamespaceURI = "urn:oasis:names:tc:opendocument:xmlns:text:1.0"; + return aNamespaceURI; +} + +OUString resolveNamespace( const OUString& aName ) +{ + int index; + if (( index = aName.indexOf( ':' )) > 0 ) + { + if ( aName.getLength() > index + 1 ) + { + OUString aAttributeName = getNamespaceValue( aName.copy( 0, index ) ) + + ":" + aName.copy( index + 1 ); + return aAttributeName; + } + } + return aName; +} + +void SAL_CALL NSDocumentHandler::startElement( const OUString& aName, const Reference< XAttributeList >&/* xAttribs */ ) +{ + if (! (aName == "office:document" || aName == "office:body" || aName == "office:text" || + aName == "text:p" || aName == "note:p") ) + CPPUNIT_ASSERT(false); + + OUString sResolvedName = resolveNamespace(aName); + if (! ( sResolvedName == "urn:oasis:names:tc:opendocument:xmlns:office:1.0:document" || + sResolvedName == "urn:oasis:names:tc:opendocument:xmlns:office:1.0:body" || + sResolvedName == "urn:oasis:names:tc:opendocument:xmlns:office:1.0:text" || + sResolvedName == "urn:oasis:names:tc:opendocument:xmlns:text:1.0:p") ) + CPPUNIT_ASSERT(false); +} + +class DummyTokenHandler : public sax_fastparser::FastTokenHandlerBase +{ +public: + const static OString tokens[]; + const static OUStringLiteral namespaceURIs[]; + const static OString namespacePrefixes[]; + + // XFastTokenHandler + virtual Sequence< sal_Int8 > SAL_CALL getUTF8Identifier( sal_Int32 nToken ) override; + virtual sal_Int32 SAL_CALL getTokenFromUTF8( const css::uno::Sequence< sal_Int8 >& Identifier ) override; + //FastTokenHandlerBase + virtual sal_Int32 getTokenDirect( const char *pToken, sal_Int32 nLength ) const override; +}; + +const OString DummyTokenHandler::tokens[] = { "Signature", "CanonicalizationMethod", "Algorithm", "Type", + "DigestMethod", "Reference", "document", + "spacing", "Player", "Height" }; + +const OUStringLiteral DummyTokenHandler::namespaceURIs[] = { "http://www.w3.org/2000/09/xmldsig#", + "http://schemas.openxmlformats.org/wordprocessingml/2006/main/", + "xyzsports.com/players/football/" }; + +const OString DummyTokenHandler::namespacePrefixes[] = { "", "w", "Player" }; + +Sequence< sal_Int8 > DummyTokenHandler::getUTF8Identifier( sal_Int32 nToken ) +{ + OString aUtf8Token; + if ( ( nToken & 0xffff0000 ) != 0 ) //namespace + { + sal_uInt32 nNamespaceToken = ( nToken >> 16 ) - 1; + if ( nNamespaceToken < SAL_N_ELEMENTS(namespacePrefixes) ) + aUtf8Token = namespacePrefixes[ nNamespaceToken ]; + } + else //element or attribute + { + size_t nElementToken = nToken & 0xffff; + if ( nElementToken < SAL_N_ELEMENTS(tokens) ) + aUtf8Token = tokens[ nElementToken ]; + } + Sequence< sal_Int8 > aSeq( reinterpret_cast< const sal_Int8* >( + aUtf8Token.getStr() ), aUtf8Token.getLength() ); + return aSeq; +} + +sal_Int32 DummyTokenHandler::getTokenFromUTF8( const uno::Sequence< sal_Int8 >& rIdentifier ) +{ + return getTokenDirect( reinterpret_cast< const char* >( + rIdentifier.getConstArray() ), rIdentifier.getLength() ); +} + +sal_Int32 DummyTokenHandler::getTokenDirect( const char* pToken, sal_Int32 nLength ) const +{ + OString sToken( pToken, nLength ); + for( size_t i = 0; i < SAL_N_ELEMENTS(tokens); i++ ) + { + if ( tokens[i] == sToken ) + return static_cast(i); + } + return FastToken::DONTKNOW; +} + + +class XMLImportTest : public test::BootstrapFixture +{ +private: + OUString m_sDirPath; + rtl::Reference< TestDocumentHandler > m_xDocumentHandler; + Reference< XParser > m_xParser; + Reference< XParser > m_xLegacyFastParser; + +public: + virtual void setUp() override; + + XMLImportTest() : BootstrapFixture(true, false) {} + void parse(); + void testMissingNamespaceDeclaration(); + void testIllegalNamespaceUse(); + + CPPUNIT_TEST_SUITE( XMLImportTest ); + CPPUNIT_TEST( parse ); + CPPUNIT_TEST( testMissingNamespaceDeclaration ); + CPPUNIT_TEST( testIllegalNamespaceUse ); + CPPUNIT_TEST_SUITE_END(); +}; + +void XMLImportTest::setUp() +{ + test::BootstrapFixture::setUp(); + Reference< XComponentContext > xContext = comphelper::getProcessComponentContext(); + m_xDocumentHandler.set( new TestDocumentHandler() ); + m_xParser = Parser::create( xContext ); + m_xParser->setDocumentHandler( m_xDocumentHandler.get() ); + m_xLegacyFastParser.set( xContext->getServiceManager()->createInstanceWithContext + ( "com.sun.star.xml.sax.LegacyFastParser", xContext ), UNO_QUERY ); + m_xLegacyFastParser->setDocumentHandler( m_xDocumentHandler.get() ); + + Reference< XFastTokenHandler > xTokenHandler; + xTokenHandler.set( new DummyTokenHandler ); + uno::Reference const xInit(m_xLegacyFastParser, + uno::UNO_QUERY_THROW); + uno::Sequence args(1); + args[0] <<= xTokenHandler; + xInit->initialize( args ); + + sal_Int32 nNamespaceCount = SAL_N_ELEMENTS(DummyTokenHandler::namespaceURIs); + uno::Sequence namespaceArgs( nNamespaceCount + 1 ); + namespaceArgs[0] <<= OUString( "registerNamespaces" ); + for (sal_Int32 i = 1; i <= nNamespaceCount; i++ ) + { + css::beans::Pair rPair( DummyTokenHandler::namespaceURIs[i - 1], i << 16 ); + namespaceArgs[i] <<= rPair; + } + xInit->initialize( namespaceArgs ); + + m_sDirPath = m_directories.getPathFromSrc( "/sax/qa/data/" ); +} + +void XMLImportTest::parse() +{ + OUString fileNames[] = {"simple.xml", "defaultns.xml", "inlinens.xml", + "multiplens.xml", "multiplepfx.xml", + "nstoattributes.xml", "nestedns.xml", "testthreading.xml"}; + + for (size_t i = 0; i < SAL_N_ELEMENTS( fileNames ); i++) + { + InputSource source; + source.sSystemId = "internal"; + + source.aInputStream = createStreamFromFile( m_sDirPath + fileNames[i] ); + m_xParser->parseStream(source); + const OUString rParserStr = m_xDocumentHandler->getString(); + + source.aInputStream = createStreamFromFile( m_sDirPath + fileNames[i] ); + m_xLegacyFastParser->parseStream(source); + const OUString rLegacyFastParserStr = m_xDocumentHandler->getString(); + + CPPUNIT_ASSERT_EQUAL( rParserStr, rLegacyFastParserStr ); + // OString o = OUStringToOString( Str, RTL_TEXTENCODING_ASCII_US ); + // CPPUNIT_ASSERT_MESSAGE( string(o.pData->buffer), false ); + } +} + +void XMLImportTest::testMissingNamespaceDeclaration() +{ + OUString fileNames[] = { "manifestwithnsdecl.xml", "manifestwithoutnsdecl.xml" }; + + uno::Reference const xInit(m_xLegacyFastParser, + uno::UNO_QUERY_THROW); + uno::Sequence args(1); + args[0] <<= OUString("IgnoreMissingNSDecl"); + xInit->initialize( args ); + + for (sal_uInt16 i = 0; i < SAL_N_ELEMENTS( fileNames ); i++) + { + try + { + InputSource source; + source.sSystemId = "internal"; + + source.aInputStream = createStreamFromFile( m_sDirPath + fileNames[i] ); + m_xParser->parseStream(source); + const OUString rParserStr = m_xDocumentHandler->getString(); + + source.aInputStream = createStreamFromFile( m_sDirPath + fileNames[i] ); + m_xLegacyFastParser->parseStream(source); + const OUString rLegacyFastParserStr = m_xDocumentHandler->getString(); + + CPPUNIT_ASSERT_EQUAL( rParserStr, rLegacyFastParserStr ); + } + catch( const SAXException & ) + { + } + } +} + +void XMLImportTest::testIllegalNamespaceUse() +{ + rtl::Reference< NSDocumentHandler > m_xNSDocumentHandler; + m_xNSDocumentHandler.set( new NSDocumentHandler() ); + m_xParser->setDocumentHandler( m_xNSDocumentHandler.get() ); + InputSource source; + source.sSystemId = "internal"; + + source.aInputStream = createStreamFromFile( m_sDirPath + "multiplepfx.xml" ); + m_xParser->parseStream(source); + + m_xLegacyFastParser->setDocumentHandler( m_xNSDocumentHandler.get() ); + source.aInputStream = createStreamFromFile( m_sDirPath + "multiplepfx.xml" ); + m_xLegacyFastParser->parseStream(source); +} + +CPPUNIT_TEST_SUITE_REGISTRATION( XMLImportTest ); +} //namespace + +CPPUNIT_PLUGIN_IMPLEMENT(); + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sax/qa/data/defaultns.xml b/sax/qa/data/defaultns.xml new file mode 100644 index 000000000..2e7819b16 --- /dev/null +++ b/sax/qa/data/defaultns.xml @@ -0,0 +1,11 @@ + + + + War and Peace + Leo Tolstoy + + + To Kill a Mockingbird + Harper Lee + + diff --git a/sax/qa/data/inlinens.xml b/sax/qa/data/inlinens.xml new file mode 100644 index 000000000..02c421408 --- /dev/null +++ b/sax/qa/data/inlinens.xml @@ -0,0 +1,12 @@ + + + + ABC + Computer Science + 7.9 + + + PQR + Artificial Intelligence + + \ No newline at end of file diff --git a/sax/qa/data/manifestwithnsdecl.xml b/sax/qa/data/manifestwithnsdecl.xml new file mode 100644 index 000000000..ac61c3e20 --- /dev/null +++ b/sax/qa/data/manifestwithnsdecl.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/sax/qa/data/manifestwithoutnsdecl.xml b/sax/qa/data/manifestwithoutnsdecl.xml new file mode 100644 index 000000000..1c8f53596 --- /dev/null +++ b/sax/qa/data/manifestwithoutnsdecl.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/sax/qa/data/multiplens.xml b/sax/qa/data/multiplens.xml new file mode 100644 index 000000000..e1dc4ce01 --- /dev/null +++ b/sax/qa/data/multiplens.xml @@ -0,0 +1,13 @@ + + + + Lionel Messi + 1.70 m + Forward + + + Sachin Ramesh Tendulkar + 165 cm + Right handed + + \ No newline at end of file diff --git a/sax/qa/data/multiplepfx.xml b/sax/qa/data/multiplepfx.xml new file mode 100644 index 000000000..b7686cad5 --- /dev/null +++ b/sax/qa/data/multiplepfx.xml @@ -0,0 +1,9 @@ + + + + + Test Document + For testing purposes only + + + diff --git a/sax/qa/data/nestedns.xml b/sax/qa/data/nestedns.xml new file mode 100644 index 000000000..566332b40 --- /dev/null +++ b/sax/qa/data/nestedns.xml @@ -0,0 +1,32 @@ + + + + + Sherlock Holmes - I + Arthur Conan Doyle + + Sherlock Holmes - II + Arthur Conan Doyle + + Sherlock Holmes - III + Arthur Conan Doyle + + + + Apple iPhone 6s + + $324 + + + Philips Aqua Touch Shaver + + AT890 + $74 + + + + Macbook Pro + $500 + + + \ No newline at end of file diff --git a/sax/qa/data/nstoattributes.xml b/sax/qa/data/nstoattributes.xml new file mode 100644 index 000000000..dee2edfdc --- /dev/null +++ b/sax/qa/data/nstoattributes.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/sax/qa/data/simple.xml b/sax/qa/data/simple.xml new file mode 100644 index 000000000..67c4fbde5 --- /dev/null +++ b/sax/qa/data/simple.xml @@ -0,0 +1,11 @@ + + + + Bryan Cranston + Breaking Bad + + + Peter Dinklage + Game of Thrones + + \ No newline at end of file diff --git a/sax/qa/data/testthreading.xml b/sax/qa/data/testthreading.xml new file mode 100644 index 000000000..0d05fd995 --- /dev/null +++ b/sax/qa/data/testthreading.xml @@ -0,0 +1,5 @@ +NOjlH6v6g2ojDvQoi4M5B8Bght0y3ES4fjxlRk2xtVE=mq1H1GLrTZSuUUTqX5HpjytFwl8nJFggNsXJUgQZT0U=6jeT5n6jeqOspz6K6BIgitwfLZf4s1/uS9dPdOQRF8s=UZwOWZbOm9ysRa+eYwoksUW8d+jBFPOkqOtfTvT8waHWDe3siDc4N79W6jPCYMIHMtPQjCb4qMDe +dhCYvg6TTWFWCvU/br+A1Qo0xovWHD3DwB29qk7NDBfbnEIPxbOe2D70cZa86Zl2MgW5YqQlgRFH +g6+XxwBUp+ZYx4knFWEg8zgbe3JnV7zeI/RG/1iq9TYH1GUBloF10df4qaulrp2AUkdSvnnUcxRP +ZfbS+14YxUHkW0UTyV+6ZeXqtTnXS0F/LG5JH2/xkN+mgwLB6TPfxtQD6vcj+Tdnf0hHlnuOmvBS +L7Pn+zwS0ueMOTxIozcaYPsmJc9fVpEU2I59PA==MIIE7jCCAtagAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwVzELMAkGA1UEBhMCVUsxEDAOBgNVBAgMB0VuZ2xhbmQxEjAQBgNVBAoMCVRTQ1AgVGVzdDEiMCAGA1UEAwwZVFNDUCBJbnRlcm1lZGlhdGUgUm9vdCBDQTAeFw0xNTEyMTgwNzU4MTlaFw0xNjEyMjcwNzU4MTlaMFUxCzAJBgNVBAYTAlVLMRAwDgYDVQQIDAdFbmdsYW5kMRIwEAYDVQQKDAlUU0NQIFRlc3QxIDAeBgNVBAMMF1RTQ1AgVGVzdCBleGFtcGxlIEFsaWNlMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3m2YNdX+nc1LkhlrNrcIPI3yCWnv0/0k9zDKpKiwjMH4vjWM46M6ptAiupxVpAMW5ojnhEyxaNHvZNsCwddYE6778hut2SJvz0szSBuHUuedcALI2EhVwdM0yLqfGo6WGeOIBDId49TemdNCMhk2zOpb1BqYhKls0LfdbxT/an3JaDmmLhPjvgYMJNYVX86L199OQFLJ1zLqQ0YirkKqXL9cSPmyYBKjgnqQ4Z5YfPL63EP0TsEfa5oQmy/0gS5FB2Wz9CqIptB130v0GR4XObTpOkhPFfC5RDBFTMZoi4NCK10wn2NCbr7qZ3aMrOlfeKbsNIifwu0KYFHXyxL5AwIDAQABo4HFMIHCMAkGA1UdEwQCMAAwEQYJYIZIAYb4QgEBBAQDAgWgMDMGCWCGSAGG+EIBDQQmFiRPcGVuU1NMIEdlbmVyYXRlZCBDbGllbnQgQ2VydGlmaWNhdGUwHQYDVR0OBBYEFCL6DzsuAbni8475Z+HkX5tv8iiWMB8GA1UdIwQYMBaAFMuejS1rWjUf3x1+2QbPSVpuXFl+MA4GA1UdDwEB/wQEAwIF4DAdBgNVHSUEFjAUBggrBgEFBQcDAgYIKwYBBQUHAwQwDQYJKoZIhvcNAQELBQADggIBAFs0DeCDjttHQ0UHsYcnhfBCWRdOFdIr3F/IEbN2BL/grScGXoXRaYMIQJv/s5dKgZIuH7xMCVKazoftPVqU4bOEduAv0IJ6hQF/wEMBueA0UjvQQVYZgsOALi7TD3gYpFqYcH2Wfx5/5Ln6dllL8UsHoP+6gSLaYwjJd7FQ+IlNTzR65dRMLoJhoKqqyuM6cf/PM8sbK2NH2r8toypjfPixvD/w3wP7xn4oo/IGXcRK4DTHBF/rSMqeR6ePwXm5tVHrQBfnxN3dsGsXkQgqzBvvbPY0raraO4CPR7mZp4GVFHOsUNh5TI1SlfxWZ49HU3F5jWeiI9jPuw1RmuAyZdFEt403Wi67v6revXe1By6UqIZjq3b2pJGBKZH+60P1cJScawzrN8pi1qQFV8JiiJM6/MSciqplTT5F7SG0XZx1CjnBz5rMdYNhI9NNtF3oy9Xy9RvgYehFaC43ZlBBUMDmZFj5a78hOOkkq1UnrHUdeXyWhiEFzv5d8My2i0kWGq8r0HuC25BmOa17lHVxQ2o7Rdu9jDFP9oNizC7kQfA5QVRTfBFcWH7jml69RmVgfM+X+wdQgen9hJAILhBzmDfeteJ5ZEaoEYtw3isOGkpSyg7odjgYq7I+bOiN1toDg07vzfIkvF9KxlkDeRLXbmcFIvQsqFeF6cUwlZQYLOHAMq3mDDWudLiaQFa1psBgLG+/en7p7r8re0MtlxnuiUI=fLpr0+BDSSPPgsv2eBghgw8hu/vi7IslCQuCSKGf2X4=7Hrf+Oz9oMcqn7nOKgy1P39L313r8SO/pT3wQpVwq5k=VZENondrzBVuF5GsYtsdSYgGNQS11L4XQ7vYiTn5PBE=nYb+Wnf/ttBtq0PSR33tt+yKzvx6RdYmtEhD3XnBwaI=4W+Exf0d9q8aHyBJ94YvTqRgdlhjR2r7F+eO3udy01s=L8HrIbYZUORASW6Jbsljhmie2tLKO9ld8ME0syr+ZDE=8JastnM5t30OLdmv2PyPNOe1YxAXc/Qz0O1UCFnWyxM=YYYY-MM-DDThh:mm:ssTZD2016-01-11T15:32:02Zpurpose6.116.016.01128080032{00000000-0000-0000-0000-000000000000}912016-01-11T15:32:02ZVRk3WQgpNIAnRxA9txzm7L2v1Iuwu2WrHpwa5WNTKV0=CN=TSCP Intermediate Root CA, O=TSCP Test, S=England, C=UK4096MIIFiDCCA3CgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwTzELMAkGA1UEBhMCVUsxEDAOBgNVBAgMB0VuZ2xhbmQxEjAQBgNVBAoMCVRTQ1AgVGVzdDEaMBgGA1UEAwwRVFNDUCBUZXN0IFJvb3QgQ0EwHhcNMTUxMjE4MDc1ODE5WhcNMjUxMjE1MDc1ODE5WjBXMQswCQYDVQQGEwJVSzEQMA4GA1UECAwHRW5nbGFuZDESMBAGA1UECgwJVFNDUCBUZXN0MSIwIAYDVQQDDBlUU0NQIEludGVybWVkaWF0ZSBSb290IENBMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAz7cet97WutWedG8L4cU7vjXkkzc8PkXnuvoF6ltIbDbnt2jt+0JH8xjGpfMVF+si0RPMwNQDmrTSj6SCpBcFV11hgyLXeovO17cSfbUYhl53ghyY0w/J3We19JJNeXtXlgZKrzre1gaXPxUG6Q4/TGo/gh9DmqEWjGkL3E6FboNfrIXHvOyhYT0kuTJkp8uqbBhhb/jO/FUV2DvTdoX04YZlFsheP00FHYz5ge6e3tG/WSeabTCUOsqq4+1jFOGNapvBrMkYC4QJwOc4bjIP8UmMlHqJae2mQVTVK3hiXtdMuS/H7rM/ZzCzcNQ2kyXUr843oul2FZ9UK3HI0TVrBFi0mpcWtvo/PMLNNXHJ/2MVZcHVgQ5+uBk0/Zq1vrqmxEev5t9lkKIzXRdztKP/EuBEjSvtcx+KZiHei+CvN+5nn5D0A6BfMYiQKmr2lVkCDs5v++iLINGbf54UoeM/dv2VEaC9bcdPeR8JHcvzS1f/cjHAbmnbMUumX985jha9SJavXkgWU6LgL5+txGD2X4Sb/+cf4ver1Zd1QGxqZ80wwK/qRUFGHWehcjCKAzeqnMRTJLUeNH5TcnvYv5fRq9wDMLzcjXXHaKEE+n3xt4fyCdEn5AFWeCPenqW3iZpEJTOHXm65Gj33/OTqoMLj8Mas3shoES1tL7LqQu/ZhgMCAwEAAaNmMGQwHQYDVR0OBBYEFMuejS1rWjUf3x1+2QbPSVpuXFl+MB8GA1UdIwQYMBaAFBtcCsdShJelvNJRLLHhVOy17wRXMBIGA1UdEwEB/wQIMAYBAf8CAQAwDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEBCwUAA4ICAQAzYDupn8D+Vh5NYcyiufM86F7GqmQ8Rows5R9o1c/5iax4G95Ley5EjUXo7/Hq2JSmtGVwkmlCBKduxsWmkbcBCJwr5AFX4TY8QFgTwKm4+IDlDA+Qs5m5bFKwbpJ8+oakz2L4j032hh6pRlezYh0P6ciVrTUNIFdR4GLusV8ronHa2AIJy9OIihI8zwDvT5rlPtDVs/wPiSq5+qcM/wnKo8X1JYU/tM1w6xvge0WNIf2yzedl2jZbbQm6wmCioCMZ7nUyyywC7WYFgCgOwOKfEa7pWhwCXpWt4MetNzXSpumurhrmn7B8y6NNarHNMhB9xv4Do4VwezMRCydnOGkl/B2fMMSoS3hxItJWDzEMkD51M6uk3yGnrQnApfEcGhEUTE8WvR8Il+Od4qFX7r50A5LguHXc4EshDJU4IaZEcYvOu91Xh2vsIZU72CXUELqMwJB7NjAkVwv8dQzHbKnK4E6y0zO1dHsjvwBfJl56PNRYx9fxJoBqdK4VrVVZAQ+wQ7wrvbjF2p5EnciHQS1NmLJjNeVvCY1dprYjp9mDxBFNNm4DhXYHF1TXpDqS7nC5cdJlTtdg4LxI4isMY/R1plDq2oxwaxhd1+5CxtMTsuv1A2qFvaRLUNS8SQE6PjWz1NxdczS5aBrXBfBFhxkEP3AtEbAyv0HiHidUAcq4pw==MIIFhDCCA2ygAwIBAgIJAIc74NSdmtB4MA0GCSqGSIb3DQEBCwUAME8xCzAJBgNVBAYTAlVLMRAwDgYDVQQIDAdFbmdsYW5kMRIwEAYDVQQKDAlUU0NQIFRlc3QxGjAYBgNVBAMMEVRTQ1AgVGVzdCBSb290IENBMB4XDTE1MTIxODA3NTgxOFoXDTM1MTIxMzA3NTgxOFowTzELMAkGA1UEBhMCVUsxEDAOBgNVBAgMB0VuZ2xhbmQxEjAQBgNVBAoMCVRTQ1AgVGVzdDEaMBgGA1UEAwwRVFNDUCBUZXN0IFJvb3QgQ0EwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCwJHjSIV2YE31STJk/bvGrTY5O949l2TnA0nt3nlIC+oe2O+dLnMIwZsSvZwZdGMjvc25AoQHJAiX8zeq/0AVMz9mhm9y239ziJBnSdP4eLBEntPFtZZooFQUV9uXHejIJs3czZmQsOBz9Ko5cL3fC0qZYXeNL14MGpAWQ0EbEMaz0uDSz3BCcJBLSgXmCEBCbXNP7mCt9vWoa0nE8HQUVmiB+SL9ltCLUojVEB9EsssH1Wo3rFR03Wk9ZbMcmmn8Av1ZLexFDD2TKhGcNHNfguB5rf+Sc/Vt45pSPemE60ro1ej4n/wwpyFM+5w6rOYqZTaBiRwzgTwYoS1JcgKnu0ACIxYqpIhxeBbNT6rA45bBvTQOCNdUWALyRkTiLYiX5HKbrrhg2ZsmX62GwEPtm+okJIQLmQp7nLfQMDONrETrBnj/D2aUo6LuwtONBD35c/hLKTMVCDIBOS35Js55GJr2Y+dhG5ly0dKoMnu0fXScrEYQzjJ1Pbv7zvpO7RBV0El8Qg8AfR2ZAD/UlugRnEDCyVhAXz8g333r0whz3LvacHTwMJoMXFXt9yVnt3ivrZ2NGLcvSNx2ZjBU7Y2EWJoEKGl49+idqmHK1Equ3dM+FNiCNX2PCEL3DGs8GpuzFFM9d9q863xCCNRecgG8rrQKSo328Q656g3iSUqFcCwIDAQABo2MwYTAdBgNVHQ4EFgQUG1wKx1KEl6W80lEsseFU7LXvBFcwHwYDVR0jBBgwFoAUG1wKx1KEl6W80lEsseFU7LXvBFcwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAYYwDQYJKoZIhvcNAQELBQADggIBADNoTWI0fdkdQW8/knVy+pEYh4y4f/9rit55MznmMsuOTHv9svNH9AMw/ZBvsfu4fEcXQyhmeonRMPdsz26ZigxG4k2wcN9fV2VMI3MlIbefCJZhIS89c3kyBF5MhbnaWxvP95nfa41cfbsXnSrj31VNMSXiA6YegbiL/v/0IkUd1mwXcXTcyxbkMLuTORgA6WiPpHVMN//YnQSMWa9ukh0uHsAuoDc2NvteXZsQkpOdZdJB4pIL2t68agyGy1Wv78jiaoxVbfYL4T3TJMxIGFSZFoV+1SYmVsfPxrSQ7vopT6y61r9c/b2fTPaHO+22pFx8lNsHII5kXpWQZIpRHgqjydN/VtnaC6dKq1lPvQTplzQVfCNWGaa/BddinGNV2qwo2a1QnEv7/6t1Gtxs5rte31aCNkfIx/mThk10fMmwJK9ECWKT/+X5iWpydI3zBIE+OvO0MKpaOeVVz1JehkZxGWP+qduF8lgL7Hs4osQNbQIu41twarpSjVCEm/FLVqo8wLmTi2Y5a7QTANeNLdyAKxjTJn3uuAvVYUUHzKOXgKF/X0tCZrUsH3//2MW3nqenN0ldXIzf7OjnVcbv2iKUzqYFzJHYtAuWHbew/kj2TvWeFFzdigLYjfnfZvHQ5sPxwrx6YpDeNf8inj48oEj6Raos0ClF0nmVg2eLMe9f \ No newline at end of file diff --git a/sax/source/expatwrap/expwrap.component b/sax/source/expatwrap/expwrap.component new file mode 100644 index 000000000..1f72eccf3 --- /dev/null +++ b/sax/source/expatwrap/expwrap.component @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + diff --git a/sax/source/expatwrap/sax_expat.cxx b/sax/source/expatwrap/sax_expat.cxx new file mode 100644 index 000000000..b80ebf033 --- /dev/null +++ b/sax/source/expatwrap/sax_expat.cxx @@ -0,0 +1,959 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include +#include +#include +#include +#include + + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include + +using namespace ::std; +using namespace ::osl; +using namespace ::cppu; +using namespace ::com::sun::star::lang; +using namespace ::com::sun::star::xml::sax; +using namespace ::com::sun::star::io; + +#include + +namespace { + +#define XML_CHAR_TO_OUSTRING(x) OUString(x , strlen( x ), RTL_TEXTENCODING_UTF8) +#define XML_CHAR_N_TO_USTRING(x,n) OUString(x,n, RTL_TEXTENCODING_UTF8 ) + + +/* +* The following macro encapsulates any call to an event handler. +* It ensures, that exceptions thrown by the event handler are +* treated properly. +*/ +#define CALL_ELEMENT_HANDLER_AND_CARE_FOR_EXCEPTIONS(pThis,call) \ + if( ! pThis->bExceptionWasThrown ) { \ + try {\ + pThis->call;\ + }\ + catch( const SAXParseException &e ) {\ + callErrorHandler( pThis , e );\ + }\ + catch( const SAXException &e ) {\ + callErrorHandler( pThis , SAXParseException(\ + e.Message, \ + e.Context, \ + e.WrappedException,\ + pThis->rDocumentLocator->getPublicId(),\ + pThis->rDocumentLocator->getSystemId(),\ + pThis->rDocumentLocator->getLineNumber(),\ + pThis->rDocumentLocator->getColumnNumber()\ + ) );\ + }\ + catch( const css::uno::RuntimeException &e ) {\ + pThis->bExceptionWasThrown = true; \ + pThis->bRTExceptionWasThrown = true; \ + pImpl->rtexception = e; \ + }\ + catch( const css::uno::Exception &e ) {\ + pThis->bExceptionWasThrown = true; \ + pThis->bRTExceptionWasThrown = true; \ + pImpl->rtexception = WrappedTargetRuntimeException("Non-runtime UNO exception caught during parse", e.Context, makeAny(e)); \ + }\ + }\ + ((void)0) + + +class SaxExpatParser_Impl; + +// This class implements the external Parser interface +class SaxExpatParser + : public WeakImplHelper< XInitialization + , XServiceInfo + , XParser > +{ + +public: + SaxExpatParser(); + + // css::lang::XInitialization: + virtual void SAL_CALL initialize(css::uno::Sequence const& rArguments) override; + + // The SAX-Parser-Interface + virtual void SAL_CALL parseStream( const InputSource& structSource) override; + virtual void SAL_CALL setDocumentHandler(const css::uno::Reference< XDocumentHandler > & xHandler) override; + + virtual void SAL_CALL setErrorHandler(const css::uno::Reference< XErrorHandler > & xHandler) override; + virtual void SAL_CALL setDTDHandler(const css::uno::Reference < XDTDHandler > & xHandler) override; + virtual void SAL_CALL setEntityResolver(const css::uno::Reference< XEntityResolver >& xResolver) override; + + virtual void SAL_CALL setLocale( const Locale &locale ) override; + +public: // XServiceInfo + OUString SAL_CALL getImplementationName() override; + css::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames() override; + sal_Bool SAL_CALL supportsService(const OUString& ServiceName) override; + +private: + std::unique_ptr m_pImpl; +}; + + +// Entity binds all information needed for a single file +struct Entity +{ + InputSource structSource; + XML_Parser pParser; + sax_expatwrap::XMLFile2UTFConverter converter; +}; + + +static constexpr OUStringLiteral gsCDATA = "CDATA"; + +class SaxExpatParser_Impl +{ +public: // module scope + Mutex aMutex; + bool m_bEnableDoS; // fdo#60471 thank you Adobe Illustrator + + css::uno::Reference< XDocumentHandler > rDocumentHandler; + css::uno::Reference< XExtendedDocumentHandler > rExtendedDocumentHandler; + + css::uno::Reference< XErrorHandler > rErrorHandler; + css::uno::Reference< XDTDHandler > rDTDHandler; + css::uno::Reference< XEntityResolver > rEntityResolver; + css::uno::Reference < XLocator > rDocumentLocator; + + + rtl::Reference < comphelper::AttributeList > rAttrList; + + // External entity stack + vector vecEntity; + void pushEntity( Entity &&entity ) + { vecEntity.push_back( std::move(entity) ); } + void popEntity() + { vecEntity.pop_back( ); } + struct Entity &getEntity() + { return vecEntity.back(); } + + + // Exception cannot be thrown through the C-XmlParser (possible resource leaks), + // therefore the exception must be saved somewhere. + SAXParseException exception; + css::uno::RuntimeException rtexception; + bool bExceptionWasThrown; + bool bRTExceptionWasThrown; + +public: + SaxExpatParser_Impl() + : m_bEnableDoS(false) + , bExceptionWasThrown(false) + , bRTExceptionWasThrown(false) + { + } + + // the C-Callbacks for the expat parser + void static callbackStartElement(void *userData, const XML_Char *name , const XML_Char **atts); + void static callbackEndElement(void *userData, const XML_Char *name); + void static callbackCharacters( void *userData , const XML_Char *s , int nLen ); + void static callbackProcessingInstruction( void *userData , + const XML_Char *sTarget , + const XML_Char *sData ); + + void static callbackEntityDecl( void *userData , + const XML_Char *entityName, + int is_parameter_entity, + const XML_Char *value, + int value_length, + const XML_Char *base, + const XML_Char *systemId, + const XML_Char *publicId, + const XML_Char *notationName); + + void static callbackNotationDecl( void *userData, + const XML_Char *notationName, + const XML_Char *base, + const XML_Char *systemId, + const XML_Char *publicId); + + bool static callbackExternalEntityRef( XML_Parser parser, + const XML_Char *openEntityNames, + const XML_Char *base, + const XML_Char *systemId, + const XML_Char *publicId); + + int static callbackUnknownEncoding(void *encodingHandlerData, + const XML_Char *name, + XML_Encoding *info); + + void static callbackDefault( void *userData, const XML_Char *s, int len); + + void static callbackStartCDATA( void *userData ); + void static callbackEndCDATA( void *userData ); + void static callbackComment( void *userData , const XML_Char *s ); + void static callErrorHandler( SaxExpatParser_Impl *pImpl , const SAXParseException &e ); + +public: + void parse(); +}; + +extern "C" +{ + static void call_callbackStartElement(void *userData, const XML_Char *name , const XML_Char **atts) + { + SaxExpatParser_Impl::callbackStartElement(userData,name,atts); + } + static void call_callbackEndElement(void *userData, const XML_Char *name) + { + SaxExpatParser_Impl::callbackEndElement(userData,name); + } + static void call_callbackCharacters( void *userData , const XML_Char *s , int nLen ) + { + SaxExpatParser_Impl::callbackCharacters(userData,s,nLen); + } + static void call_callbackProcessingInstruction(void *userData,const XML_Char *sTarget,const XML_Char *sData ) + { + SaxExpatParser_Impl::callbackProcessingInstruction(userData,sTarget,sData ); + } + static void call_callbackEntityDecl(void *userData , + const XML_Char *entityName, + int is_parameter_entity, + const XML_Char *value, + int value_length, + const XML_Char *base, + const XML_Char *systemId, + const XML_Char *publicId, + const XML_Char *notationName) + { + SaxExpatParser_Impl::callbackEntityDecl(userData, entityName, + is_parameter_entity, value, value_length, + base, systemId, publicId, notationName); + } + static void call_callbackNotationDecl(void *userData, + const XML_Char *notationName, + const XML_Char *base, + const XML_Char *systemId, + const XML_Char *publicId) + { + SaxExpatParser_Impl::callbackNotationDecl(userData,notationName,base,systemId,publicId); + } + static int call_callbackExternalEntityRef(XML_Parser parser, + const XML_Char *openEntityNames, + const XML_Char *base, + const XML_Char *systemId, + const XML_Char *publicId) + { + return SaxExpatParser_Impl::callbackExternalEntityRef(parser,openEntityNames,base,systemId,publicId); + } + static int call_callbackUnknownEncoding(void *encodingHandlerData, + const XML_Char *name, + XML_Encoding *info) + { + return SaxExpatParser_Impl::callbackUnknownEncoding(encodingHandlerData,name,info); + } + static void call_callbackDefault( void *userData, const XML_Char *s, int len) + { + SaxExpatParser_Impl::callbackDefault(userData,s,len); + } + static void call_callbackStartCDATA( void *userData ) + { + SaxExpatParser_Impl::callbackStartCDATA(userData); + } + static void call_callbackEndCDATA( void *userData ) + { + SaxExpatParser_Impl::callbackEndCDATA(userData); + } + static void call_callbackComment( void *userData , const XML_Char *s ) + { + SaxExpatParser_Impl::callbackComment(userData,s); + } +} + + +// LocatorImpl + +class LocatorImpl : + public WeakImplHelper< XLocator, css::io::XSeekable > + // should use a different interface for stream positions! +{ +public: + explicit LocatorImpl(SaxExpatParser_Impl *p) + : m_pParser(p) + { + } + +public: //XLocator + virtual sal_Int32 SAL_CALL getColumnNumber() override + { + return XML_GetCurrentColumnNumber( m_pParser->getEntity().pParser ); + } + virtual sal_Int32 SAL_CALL getLineNumber() override + { + return XML_GetCurrentLineNumber( m_pParser->getEntity().pParser ); + } + virtual OUString SAL_CALL getPublicId() override + { + return m_pParser->getEntity().structSource.sPublicId; + } + virtual OUString SAL_CALL getSystemId() override + { + return m_pParser->getEntity().structSource.sSystemId; + } + + // XSeekable (only for getPosition) + + virtual void SAL_CALL seek( sal_Int64 ) override + { + } + virtual sal_Int64 SAL_CALL getPosition() override + { + return XML_GetCurrentByteIndex( m_pParser->getEntity().pParser ); + } + virtual ::sal_Int64 SAL_CALL getLength() override + { + return 0; + } + +private: + + SaxExpatParser_Impl *m_pParser; +}; + + +SaxExpatParser::SaxExpatParser( ) +{ + m_pImpl.reset( new SaxExpatParser_Impl ); + + LocatorImpl *pLoc = new LocatorImpl( m_pImpl.get() ); + m_pImpl->rDocumentLocator.set( pLoc ); + + // Performance-improvement; handing out the same object with every call of + // the startElement callback is allowed (see sax-specification): + m_pImpl->rAttrList = new comphelper::AttributeList; + + m_pImpl->bExceptionWasThrown = false; + m_pImpl->bRTExceptionWasThrown = false; +} + +// css::lang::XInitialization: +void SAL_CALL +SaxExpatParser::initialize(css::uno::Sequence< css::uno::Any > const& rArguments) +{ + // possible arguments: a string "DoSmeplease" + if (rArguments.hasElements()) + { + OUString str; + if ((rArguments[0] >>= str) && "DoSmeplease" == str) + { + MutexGuard guard( m_pImpl->aMutex ); + m_pImpl->m_bEnableDoS = true; + } + } +} + +class ParserCleanup +{ +private: + SaxExpatParser_Impl& m_rParser; + XML_Parser m_xmlParser; +public: + ParserCleanup(SaxExpatParser_Impl& rParser, XML_Parser xmlParser) + : m_rParser(rParser) + , m_xmlParser(xmlParser) + { + } + ~ParserCleanup() + { + m_rParser.popEntity(); + //XML_ParserFree accepts a null arg + XML_ParserFree(m_xmlParser); + } +}; + +/*************** +* +* parseStream does Parser-startup initializations. The SaxExpatParser_Impl::parse() method does +* the file-specific initialization work. (During a parser run, external files may be opened) +* +****************/ +void SaxExpatParser::parseStream( const InputSource& structSource) +{ + // Only one text at one time + MutexGuard guard( m_pImpl->aMutex ); + + + struct Entity entity; + entity.structSource = structSource; + + if( ! entity.structSource.aInputStream.is() ) + { + throw SAXException("No input source", + css::uno::Reference< css::uno::XInterface > () , css::uno::Any() ); + } + + entity.converter.setInputStream( entity.structSource.aInputStream ); + if( !entity.structSource.sEncoding.isEmpty() ) + { + entity.converter.setEncoding( + OUStringToOString( entity.structSource.sEncoding , RTL_TEXTENCODING_ASCII_US ) ); + } + + // create parser with proper encoding + entity.pParser = XML_ParserCreate( nullptr ); + if( ! entity.pParser ) + { + throw SAXException("Couldn't create parser", + css::uno::Reference< css::uno::XInterface > (), css::uno::Any() ); + } + + // set all necessary C-Callbacks + XML_SetUserData( entity.pParser, m_pImpl.get() ); + XML_SetElementHandler( entity.pParser , + call_callbackStartElement , + call_callbackEndElement ); + XML_SetCharacterDataHandler( entity.pParser , call_callbackCharacters ); + XML_SetProcessingInstructionHandler(entity.pParser , + call_callbackProcessingInstruction ); + if (!m_pImpl->m_bEnableDoS) + { + XML_SetEntityDeclHandler(entity.pParser, call_callbackEntityDecl); + } + XML_SetNotationDeclHandler( entity.pParser, call_callbackNotationDecl ); + XML_SetExternalEntityRefHandler( entity.pParser, + call_callbackExternalEntityRef); + XML_SetUnknownEncodingHandler( entity.pParser, call_callbackUnknownEncoding ,nullptr); + + if( m_pImpl->rExtendedDocumentHandler.is() ) { + + // These handlers just delegate calls to the ExtendedHandler. If no extended handler is + // given, these callbacks can be ignored + XML_SetDefaultHandlerExpand( entity.pParser, call_callbackDefault ); + XML_SetCommentHandler( entity.pParser, call_callbackComment ); + XML_SetCdataSectionHandler( entity.pParser , + call_callbackStartCDATA , + call_callbackEndCDATA ); + } + + + m_pImpl->exception = SAXParseException(); + auto const xmlParser = entity.pParser; + m_pImpl->pushEntity( std::move(entity) ); + + ParserCleanup aEnsureFree(*m_pImpl, xmlParser); + + // start the document + if( m_pImpl->rDocumentHandler.is() ) { + m_pImpl->rDocumentHandler->setDocumentLocator( m_pImpl->rDocumentLocator ); + m_pImpl->rDocumentHandler->startDocument(); + } + + m_pImpl->parse(); + + // finish document + if( m_pImpl->rDocumentHandler.is() ) { + m_pImpl->rDocumentHandler->endDocument(); + } +} + +void SaxExpatParser::setDocumentHandler(const css::uno::Reference< XDocumentHandler > & xHandler) +{ + m_pImpl->rDocumentHandler = xHandler; + m_pImpl->rExtendedDocumentHandler = + css::uno::Reference< XExtendedDocumentHandler >( xHandler , css::uno::UNO_QUERY ); +} + +void SaxExpatParser::setErrorHandler(const css::uno::Reference< XErrorHandler > & xHandler) +{ + m_pImpl->rErrorHandler = xHandler; +} + +void SaxExpatParser::setDTDHandler(const css::uno::Reference< XDTDHandler > & xHandler) +{ + m_pImpl->rDTDHandler = xHandler; +} + +void SaxExpatParser::setEntityResolver(const css::uno::Reference < XEntityResolver > & xResolver) +{ + m_pImpl->rEntityResolver = xResolver; +} + + +void SaxExpatParser::setLocale( const Locale & ) +{ + // not implemented +} + +// XServiceInfo +OUString SaxExpatParser::getImplementationName() +{ + return "com.sun.star.comp.extensions.xml.sax.ParserExpat"; +} + +// XServiceInfo +sal_Bool SaxExpatParser::supportsService(const OUString& ServiceName) +{ + return cppu::supportsService(this, ServiceName); +} + +// XServiceInfo +css::uno::Sequence< OUString > SaxExpatParser::getSupportedServiceNames() +{ + return { "com.sun.star.xml.sax.Parser" }; +} + + +/*--------------------------------------- +* +* Helper functions and classes +* +* +*-------------------------------------------*/ +OUString getErrorMessage( XML_Error xmlE, const OUString& sSystemId , sal_Int32 nLine ) +{ + OUString Message; + if( XML_ERROR_NONE == xmlE ) { + Message = "No"; + } + else if( XML_ERROR_NO_MEMORY == xmlE ) { + Message = "no memory"; + } + else if( XML_ERROR_SYNTAX == xmlE ) { + Message = "syntax"; + } + else if( XML_ERROR_NO_ELEMENTS == xmlE ) { + Message = "no elements"; + } + else if( XML_ERROR_INVALID_TOKEN == xmlE ) { + Message = "invalid token"; + } + else if( XML_ERROR_UNCLOSED_TOKEN == xmlE ) { + Message = "unclosed token"; + } + else if( XML_ERROR_PARTIAL_CHAR == xmlE ) { + Message = "partial char"; + } + else if( XML_ERROR_TAG_MISMATCH == xmlE ) { + Message = "tag mismatch"; + } + else if( XML_ERROR_DUPLICATE_ATTRIBUTE == xmlE ) { + Message = "duplicate attribute"; + } + else if( XML_ERROR_JUNK_AFTER_DOC_ELEMENT == xmlE ) { + Message = "junk after doc element"; + } + else if( XML_ERROR_PARAM_ENTITY_REF == xmlE ) { + Message = "parameter entity reference"; + } + else if( XML_ERROR_UNDEFINED_ENTITY == xmlE ) { + Message = "undefined entity"; + } + else if( XML_ERROR_RECURSIVE_ENTITY_REF == xmlE ) { + Message = "recursive entity reference"; + } + else if( XML_ERROR_ASYNC_ENTITY == xmlE ) { + Message = "async entity"; + } + else if( XML_ERROR_BAD_CHAR_REF == xmlE ) { + Message = "bad char reference"; + } + else if( XML_ERROR_BINARY_ENTITY_REF == xmlE ) { + Message = "binary entity reference"; + } + else if( XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF == xmlE ) { + Message = "attribute external entity reference"; + } + else if( XML_ERROR_MISPLACED_XML_PI == xmlE ) { + Message = "misplaced xml processing instruction"; + } + else if( XML_ERROR_UNKNOWN_ENCODING == xmlE ) { + Message = "unknown encoding"; + } + else if( XML_ERROR_INCORRECT_ENCODING == xmlE ) { + Message = "incorrect encoding"; + } + else if( XML_ERROR_UNCLOSED_CDATA_SECTION == xmlE ) { + Message = "unclosed cdata section"; + } + else if( XML_ERROR_EXTERNAL_ENTITY_HANDLING == xmlE ) { + Message = "external entity reference"; + } + else if( XML_ERROR_NOT_STANDALONE == xmlE ) { + Message = "not standalone"; + } + + OUString str = "[" + + sSystemId + + " line " + + OUString::number( nLine ) + + "]: " + + Message + + "error"; + + return str; +} + + +// starts parsing with actual parser ! +void SaxExpatParser_Impl::parse( ) +{ + const int nBufSize = 16*1024; + + int nRead = nBufSize; + css::uno::Sequence< sal_Int8 > seqOut(nBufSize); + + while( nRead ) { + nRead = getEntity().converter.readAndConvert( seqOut , nBufSize ); + + bool bContinue(false); + + if( ! nRead ) { + // last call - must return OK + XML_Status const ret = XML_Parse( getEntity().pParser, + reinterpret_cast(seqOut.getConstArray()), + 0 , + 1 ); + if (ret == XML_STATUS_OK) { + break; + } + } else { + bContinue = ( XML_Parse( getEntity().pParser, + reinterpret_cast(seqOut.getConstArray()), + nRead, + 0 ) != XML_STATUS_ERROR ); + } + + if( ! bContinue || bExceptionWasThrown ) { + + if ( bRTExceptionWasThrown ) + throw rtexception; + + // Error during parsing ! + XML_Error xmlE = XML_GetErrorCode( getEntity().pParser ); + OUString sSystemId = rDocumentLocator->getSystemId(); + sal_Int32 nLine = rDocumentLocator->getLineNumber(); + + SAXParseException aExcept( + getErrorMessage(xmlE , sSystemId, nLine) , + css::uno::Reference< css::uno::XInterface >(), + css::uno::Any( &exception , cppu::UnoType::get() ), + rDocumentLocator->getPublicId(), + rDocumentLocator->getSystemId(), + rDocumentLocator->getLineNumber(), + rDocumentLocator->getColumnNumber() + ); + + if( rErrorHandler.is() ) { + + // error handler is set, so the handler may throw the exception + css::uno::Any a; + a <<= aExcept; + rErrorHandler->fatalError( a ); + } + + // Error handler has not thrown an exception, but parsing cannot go on, + // so an exception MUST be thrown. + throw aExcept; + } // if( ! bContinue ) + } // while +} + + +// The C-Callbacks + + +void SaxExpatParser_Impl::callbackStartElement( void *pvThis , + const XML_Char *pwName , + const XML_Char **awAttributes ) +{ + SaxExpatParser_Impl *pImpl = static_cast(pvThis); + + if( !pImpl->rDocumentHandler.is() ) + return; + + int i = 0; + pImpl->rAttrList->Clear(); + + while( awAttributes[i] ) { + assert(awAttributes[i+1]); + pImpl->rAttrList->AddAttribute( + XML_CHAR_TO_OUSTRING( awAttributes[i] ) , + gsCDATA, // expat doesn't know types + XML_CHAR_TO_OUSTRING( awAttributes[i+1] ) ); + i +=2; + } + + CALL_ELEMENT_HANDLER_AND_CARE_FOR_EXCEPTIONS( + pImpl , + rDocumentHandler->startElement( XML_CHAR_TO_OUSTRING( pwName ) , + pImpl->rAttrList.get() ) ); +} + +void SaxExpatParser_Impl::callbackEndElement( void *pvThis , const XML_Char *pwName ) +{ + SaxExpatParser_Impl *pImpl = static_cast(pvThis); + + if( pImpl->rDocumentHandler.is() ) { + CALL_ELEMENT_HANDLER_AND_CARE_FOR_EXCEPTIONS( pImpl, + rDocumentHandler->endElement( XML_CHAR_TO_OUSTRING( pwName ) ) ); + } +} + + +void SaxExpatParser_Impl::callbackCharacters( void *pvThis , const XML_Char *s , int nLen ) +{ + SaxExpatParser_Impl *pImpl = static_cast(pvThis); + + if( pImpl->rDocumentHandler.is() ) { + CALL_ELEMENT_HANDLER_AND_CARE_FOR_EXCEPTIONS( pImpl , + rDocumentHandler->characters( XML_CHAR_N_TO_USTRING(s,nLen) ) ); + } +} + +void SaxExpatParser_Impl::callbackProcessingInstruction( void *pvThis, + const XML_Char *sTarget , + const XML_Char *sData ) +{ + SaxExpatParser_Impl *pImpl = static_cast(pvThis); + if( pImpl->rDocumentHandler.is() ) { + CALL_ELEMENT_HANDLER_AND_CARE_FOR_EXCEPTIONS( + pImpl , + rDocumentHandler->processingInstruction( XML_CHAR_TO_OUSTRING( sTarget ), + XML_CHAR_TO_OUSTRING( sData ) ) ); + } +} + + +void SaxExpatParser_Impl::callbackEntityDecl( + void *pvThis, const XML_Char *entityName, + SAL_UNUSED_PARAMETER int /*is_parameter_entity*/, + const XML_Char *value, SAL_UNUSED_PARAMETER int /*value_length*/, + SAL_UNUSED_PARAMETER const XML_Char * /*base*/, const XML_Char *systemId, + const XML_Char *publicId, const XML_Char *notationName) +{ + SaxExpatParser_Impl *pImpl = static_cast(pvThis); + if (value) { // value != 0 means internal entity + SAL_INFO("sax","SaxExpatParser: internal entity declaration, stopping"); + XML_StopParser(pImpl->getEntity().pParser, XML_FALSE); + pImpl->exception = SAXParseException( + "SaxExpatParser: internal entity declaration, stopping", + nullptr, css::uno::Any(), + pImpl->rDocumentLocator->getPublicId(), + pImpl->rDocumentLocator->getSystemId(), + pImpl->rDocumentLocator->getLineNumber(), + pImpl->rDocumentLocator->getColumnNumber() ); + pImpl->bExceptionWasThrown = true; + } else { + if( pImpl->rDTDHandler.is() ) { + CALL_ELEMENT_HANDLER_AND_CARE_FOR_EXCEPTIONS( + pImpl , + rDTDHandler->unparsedEntityDecl( + XML_CHAR_TO_OUSTRING( entityName ), + XML_CHAR_TO_OUSTRING( publicId ) , + XML_CHAR_TO_OUSTRING( systemId ) , + XML_CHAR_TO_OUSTRING( notationName ) ) ); + } + } +} + +void SaxExpatParser_Impl::callbackNotationDecl( + void *pvThis, const XML_Char *notationName, + SAL_UNUSED_PARAMETER const XML_Char * /*base*/, const XML_Char *systemId, + const XML_Char *publicId) +{ + SaxExpatParser_Impl *pImpl = static_cast(pvThis); + if( pImpl->rDTDHandler.is() ) { + CALL_ELEMENT_HANDLER_AND_CARE_FOR_EXCEPTIONS( pImpl, + rDTDHandler->notationDecl( XML_CHAR_TO_OUSTRING( notationName ) , + XML_CHAR_TO_OUSTRING( publicId ) , + XML_CHAR_TO_OUSTRING( systemId ) ) ); + } + +} + + +bool SaxExpatParser_Impl::callbackExternalEntityRef( + XML_Parser parser, const XML_Char *context, + SAL_UNUSED_PARAMETER const XML_Char * /*base*/, const XML_Char *systemId, + const XML_Char *publicId) +{ + bool bOK = true; + SaxExpatParser_Impl *pImpl = static_cast(XML_GetUserData( parser )); + + struct Entity entity; + + if( pImpl->rEntityResolver.is() ) { + try + { + entity.structSource = pImpl->rEntityResolver->resolveEntity( + XML_CHAR_TO_OUSTRING( publicId ) , + XML_CHAR_TO_OUSTRING( systemId ) ); + } + catch( const SAXParseException & e ) + { + pImpl->exception = e; + bOK = false; + } + catch( const SAXException & e ) + { + pImpl->exception = SAXParseException( + e.Message , e.Context , e.WrappedException , + pImpl->rDocumentLocator->getPublicId(), + pImpl->rDocumentLocator->getSystemId(), + pImpl->rDocumentLocator->getLineNumber(), + pImpl->rDocumentLocator->getColumnNumber() ); + bOK = false; + } + } + + if( entity.structSource.aInputStream.is() ) { + entity.pParser = XML_ExternalEntityParserCreate( parser , context, nullptr ); + if( ! entity.pParser ) + { + return false; + } + + entity.converter.setInputStream( entity.structSource.aInputStream ); + auto const xmlParser = entity.pParser; + pImpl->pushEntity( std::move(entity) ); + try + { + pImpl->parse(); + } + catch( const SAXParseException & e ) + { + pImpl->exception = e; + bOK = false; + } + catch( const IOException &e ) + { + pImpl->exception.WrappedException <<= e; + bOK = false; + } + catch( const css::uno::RuntimeException &e ) + { + pImpl->exception.WrappedException <<=e; + bOK = false; + } + + pImpl->popEntity(); + + XML_ParserFree( xmlParser ); + } + + return bOK; +} + +int SaxExpatParser_Impl::callbackUnknownEncoding( + SAL_UNUSED_PARAMETER void * /*encodingHandlerData*/, + SAL_UNUSED_PARAMETER const XML_Char * /*name*/, + SAL_UNUSED_PARAMETER XML_Encoding * /*info*/) +{ + return 0; +} + +void SaxExpatParser_Impl::callbackDefault( void *pvThis, const XML_Char *s, int len) +{ + SaxExpatParser_Impl *pImpl = static_cast(pvThis); + + CALL_ELEMENT_HANDLER_AND_CARE_FOR_EXCEPTIONS( pImpl, + rExtendedDocumentHandler->unknown( XML_CHAR_N_TO_USTRING( s ,len) ) ); +} + +void SaxExpatParser_Impl::callbackComment( void *pvThis , const XML_Char *s ) +{ + SaxExpatParser_Impl *pImpl = static_cast(pvThis); + CALL_ELEMENT_HANDLER_AND_CARE_FOR_EXCEPTIONS( pImpl, + rExtendedDocumentHandler->comment( XML_CHAR_TO_OUSTRING( s ) ) ); +} + +void SaxExpatParser_Impl::callbackStartCDATA( void *pvThis ) +{ + SaxExpatParser_Impl *pImpl = static_cast(pvThis); + + CALL_ELEMENT_HANDLER_AND_CARE_FOR_EXCEPTIONS( pImpl, rExtendedDocumentHandler->startCDATA() ); +} + + +void SaxExpatParser_Impl::callErrorHandler( SaxExpatParser_Impl *pImpl , + const SAXParseException & e ) +{ + try + { + if( pImpl->rErrorHandler.is() ) { + css::uno::Any a; + a <<= e; + pImpl->rErrorHandler->error( a ); + } + else { + pImpl->exception = e; + pImpl->bExceptionWasThrown = true; + } + } + catch( const SAXParseException & ex ) { + pImpl->exception = ex; + pImpl->bExceptionWasThrown = true; + } + catch( const SAXException & ex ) { + pImpl->exception = SAXParseException( + ex.Message, + ex.Context, + ex.WrappedException, + pImpl->rDocumentLocator->getPublicId(), + pImpl->rDocumentLocator->getSystemId(), + pImpl->rDocumentLocator->getLineNumber(), + pImpl->rDocumentLocator->getColumnNumber() + ); + pImpl->bExceptionWasThrown = true; + } +} + +void SaxExpatParser_Impl::callbackEndCDATA( void *pvThis ) +{ + SaxExpatParser_Impl *pImpl = static_cast(pvThis); + + CALL_ELEMENT_HANDLER_AND_CARE_FOR_EXCEPTIONS(pImpl,rExtendedDocumentHandler->endCDATA() ); +} + +} // namespace + +extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface * +com_sun_star_comp_extensions_xml_sax_ParserExpat_get_implementation( + css::uno::XComponentContext *, + css::uno::Sequence const &) +{ + return cppu::acquire(new SaxExpatParser); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sax/source/expatwrap/saxwriter.cxx b/sax/source/expatwrap/saxwriter.cxx new file mode 100644 index 000000000..f4f4c4bae --- /dev/null +++ b/sax/source/expatwrap/saxwriter.cxx @@ -0,0 +1,1418 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include + +using namespace ::std; +using namespace ::osl; +using namespace ::cppu; +using namespace ::com::sun::star::uno; +using namespace ::com::sun::star::lang; +using namespace ::com::sun::star::xml::sax; +using namespace ::com::sun::star::util; +using namespace ::com::sun::star::io; + +#include + +#define LINEFEED 10 +#define SEQUENCESIZE 1024 +#define MAXCOLUMNCOUNT 72 + +/****** +* +* +* Character conversion functions +* +* +*****/ + +namespace { + +enum SaxInvalidCharacterError +{ + SAX_NONE, + SAX_WARNING, + SAX_ERROR +}; + +class SaxWriterHelper +{ +#ifdef DBG_UTIL +public: + ::std::stack m_DebugStartedElements; +#endif + +private: + Reference< XOutputStream > m_out; + Sequence < sal_Int8 > m_Sequence; + sal_Int8* mp_Sequence; + + sal_Int32 nLastLineFeedPos; // is negative after writing a sequence + sal_uInt32 nCurrentPos; + bool m_bStartElementFinished; + + /// @throws SAXException + sal_uInt32 writeSequence(); + + // use only if to insert the bytes more space in the sequence is needed and + // so the sequence has to write out and reset rPos to 0 + // writes sequence only on overflow, sequence could be full on the end (rPos == SEQUENCESIZE) + /// @throws SAXException + void AddBytes(sal_Int8* pTarget, sal_uInt32& rPos, + const sal_Int8* pBytes, sal_uInt32 nBytesCount); + /// @throws SAXException + bool convertToXML(const sal_Unicode * pStr, + sal_Int32 nStrLen, + bool bDoNormalization, + bool bNormalizeWhitespace, + sal_Int8 *pTarget, + sal_uInt32& rPos); + /// @throws SAXException + void FinishStartElement(); +public: + explicit SaxWriterHelper(Reference< XOutputStream > const & m_TempOut) + : m_out(m_TempOut) + , m_Sequence(SEQUENCESIZE) + , mp_Sequence(nullptr) + , nLastLineFeedPos(0) + , nCurrentPos(0) + , m_bStartElementFinished(true) + { + OSL_ENSURE(SEQUENCESIZE > 50, "Sequence cache size too small"); + mp_Sequence = m_Sequence.getArray(); + } + ~SaxWriterHelper() + { + OSL_ENSURE(!nCurrentPos, "cached Sequence not written"); + OSL_ENSURE(m_bStartElementFinished, "StartElement not completely written"); + } + + /// @throws SAXException + void insertIndentation(sal_uInt32 m_nLevel); + +// returns whether it works correct or invalid characters were in the string +// If there are invalid characters in the string it returns sal_False. +// Than the calling method has to throw the needed Exception. + /// @throws SAXException + bool writeString(const OUString& rWriteOutString, + bool bDoNormalization, + bool bNormalizeWhitespace); + + sal_uInt32 GetLastColumnCount() const throw() + { return static_cast(nCurrentPos - nLastLineFeedPos); } + + /// @throws SAXException + void startDocument(); + +// returns whether it works correct or invalid characters were in the strings +// If there are invalid characters in one of the strings it returns sal_False. +// Than the calling method has to throw the needed Exception. + /// @throws SAXException + SaxInvalidCharacterError startElement(const OUString& rName, const Reference< XAttributeList >& xAttribs); + /// @throws SAXException + bool FinishEmptyElement(); + +// returns whether it works correct or invalid characters were in the string +// If there are invalid characters in the string it returns sal_False. +// Than the calling method has to throw the needed Exception. + /// @throws SAXException + bool endElement(const OUString& rName); + /// @throws SAXException + void endDocument(); + +// returns whether it works correct or invalid characters were in the strings +// If there are invalid characters in the string it returns sal_False. +// Than the calling method has to throw the needed Exception. + /// @throws SAXException + bool processingInstruction(const OUString& rTarget, const OUString& rData); + /// @throws SAXException + void startCDATA(); + /// @throws SAXException + void endCDATA(); + +// returns whether it works correct or invalid characters were in the strings +// If there are invalid characters in the string it returns sal_False. +// Than the calling method has to throw the needed Exception. + /// @throws SAXException + bool comment(const OUString& rComment); + + /// @throws SAXException + void clearBuffer(); +}; + +const bool g_bValidCharsBelow32[32] = +{ +// 0 1 2 3 4 5 6 7 + false,false,false,false,false,false,false,false, //0 + false,true, true, false,false,true, false,false, //8 + false,false,false,false,false,false,false,false, //16 + false,false,false,false,false,false,false,false +}; + +bool IsInvalidChar(const sal_Unicode aChar) +{ + bool bRet(false); + // check first for the most common characters + if( aChar < 32 || aChar >= 0xd800 ) + bRet = ( (aChar < 32 && ! g_bValidCharsBelow32[aChar]) || + aChar == 0xffff || + aChar == 0xfffe ); + return bRet; +} + +/******** +* write through to the output stream +* +*****/ +sal_uInt32 SaxWriterHelper::writeSequence() +{ + try + { + m_out->writeBytes( m_Sequence ); + } + catch (const IOException &) + { + css::uno::Any anyEx = cppu::getCaughtException(); + throw SAXException( + "IO exception during writing", + Reference< XInterface > (), + anyEx ); + } + nLastLineFeedPos -= SEQUENCESIZE; + return 0; +} + +void SaxWriterHelper::AddBytes(sal_Int8* pTarget, sal_uInt32& rPos, + const sal_Int8* pBytes, sal_uInt32 nBytesCount) +{ + OSL_ENSURE((rPos + nBytesCount) > SEQUENCESIZE, "wrong use of AddBytesMethod"); + sal_uInt32 nCount(SEQUENCESIZE - rPos); + memcpy( &(pTarget[rPos]) , pBytes, nCount); + + OSL_ENSURE(rPos + nCount == SEQUENCESIZE, "the position should be the at the end"); + + rPos = writeSequence(); + sal_uInt32 nRestCount(nBytesCount - nCount); + if ((rPos + nRestCount) <= SEQUENCESIZE) + { + memcpy( &(pTarget[rPos]), &pBytes[nCount], nRestCount); + rPos += nRestCount; + } + else + AddBytes(pTarget, rPos, &pBytes[nCount], nRestCount); +} + +/** Converts a UTF-16 string to UTF-8 and does XML normalization + + @param pTarget + Pointer to a piece of memory, to where the output should be written. The caller + must call calcXMLByteLength on the same string, to ensure, + that there is enough memory for converting. + */ +bool SaxWriterHelper::convertToXML( const sal_Unicode * pStr, + sal_Int32 nStrLen, + bool bDoNormalization, + bool bNormalizeWhitespace, + sal_Int8 *pTarget, + sal_uInt32& rPos ) +{ + bool bRet(true); + sal_uInt32 nSurrogate = 0; + + for( sal_Int32 i = 0 ; i < nStrLen ; i ++ ) + { + sal_uInt16 c = pStr[i]; + if (IsInvalidChar(c)) + bRet = false; + else if( (c >= 0x0001) && (c <= 0x007F) ) + { + if( bDoNormalization ) + { + switch( c ) + { + case '&': // resemble to & + { + if ((rPos + 5) > SEQUENCESIZE) + AddBytes(pTarget, rPos, reinterpret_cast("&"), 5); + else + { + memcpy( &(pTarget[rPos]) , "&", 5 ); + rPos += 5; + } + } + break; + case '<': + { + if ((rPos + 4) > SEQUENCESIZE) + AddBytes(pTarget, rPos, reinterpret_cast("<"), 4); + else + { + memcpy( &(pTarget[rPos]) , "<" , 4 ); + rPos += 4; // < + } + } + break; + case '>': + { + if ((rPos + 4) > SEQUENCESIZE) + AddBytes(pTarget, rPos, reinterpret_cast(">"), 4); + else + { + memcpy( &(pTarget[rPos]) , ">" , 4 ); + rPos += 4; // > + } + } + break; + case 39: // 39 == ''' + { + if ((rPos + 6) > SEQUENCESIZE) + AddBytes(pTarget, rPos, reinterpret_cast("'"), 6); + else + { + memcpy( &(pTarget[rPos]) , "'" , 6 ); + rPos += 6; // ' + } + } + break; + case '"': + { + if ((rPos + 6) > SEQUENCESIZE) + AddBytes(pTarget, rPos, reinterpret_cast("""), 6); + else + { + memcpy( &(pTarget[rPos]) , """ , 6 ); + rPos += 6; // " + } + } + break; + case 13: + { + if ((rPos + 6) > SEQUENCESIZE) + AddBytes(pTarget, rPos, reinterpret_cast(" "), 6); + else + { + memcpy( &(pTarget[rPos]) , " " , 6 ); + rPos += 6; + } + } + break; + case LINEFEED: + { + if( bNormalizeWhitespace ) + { + if ((rPos + 6) > SEQUENCESIZE) + AddBytes(pTarget, rPos, reinterpret_cast(" "), 6); + else + { + memcpy( &(pTarget[rPos]) , " " , 6 ); + rPos += 6; + } + } + else + { + pTarget[rPos] = LINEFEED; + nLastLineFeedPos = rPos; + rPos ++; + } + } + break; + case 9: + { + if( bNormalizeWhitespace ) + { + if ((rPos + 6) > SEQUENCESIZE) + AddBytes(pTarget, rPos, reinterpret_cast(" "), 6); + else + { + memcpy( &(pTarget[rPos]) , " " , 6 ); + rPos += 6; + } + } + else + { + pTarget[rPos] = 9; + rPos ++; + } + } + break; + default: + { + pTarget[rPos] = static_cast(c); + rPos ++; + } + break; + } + } + else + { + pTarget[rPos] = static_cast(c); + if (static_cast(c) == LINEFEED) + nLastLineFeedPos = rPos; + rPos ++; + } + } + else if( c >= 0xd800 && c < 0xdc00 ) + { + // 1. surrogate: save (until 2. surrogate) + OSL_ENSURE( nSurrogate == 0, "left-over Unicode surrogate" ); + nSurrogate = ( ( c & 0x03ff ) + 0x0040 ); + } + else if( c >= 0xdc00 && c < 0xe000 ) + { + // 2. surrogate: write as UTF-8 + OSL_ENSURE( nSurrogate != 0, "lone 2nd Unicode surrogate" ); + + nSurrogate = ( nSurrogate << 10 ) | ( c & 0x03ff ); + if( rtl::isUnicodeScalarValue(nSurrogate) && nSurrogate >= 0x00010000 ) + { + sal_Int8 aBytes[] = { sal_Int8(0xF0 | ((nSurrogate >> 18) & 0x0F)), + sal_Int8(0x80 | ((nSurrogate >> 12) & 0x3F)), + sal_Int8(0x80 | ((nSurrogate >> 6) & 0x3F)), + sal_Int8(0x80 | ((nSurrogate >> 0) & 0x3F)) }; + if ((rPos + 4) > SEQUENCESIZE) + AddBytes(pTarget, rPos, aBytes, 4); + else + { + pTarget[rPos] = aBytes[0]; + rPos ++; + pTarget[rPos] = aBytes[1]; + rPos ++; + pTarget[rPos] = aBytes[2]; + rPos ++; + pTarget[rPos] = aBytes[3]; + rPos ++; + } + } + else + { + OSL_FAIL( "illegal Unicode character" ); + bRet = false; + } + + // reset surrogate + nSurrogate = 0; + } + else if( c > 0x07FF ) + { + sal_Int8 aBytes[] = { sal_Int8(0xE0 | ((c >> 12) & 0x0F)), + sal_Int8(0x80 | ((c >> 6) & 0x3F)), + sal_Int8(0x80 | ((c >> 0) & 0x3F)) }; + if ((rPos + 3) > SEQUENCESIZE) + AddBytes(pTarget, rPos, aBytes, 3); + else + { + pTarget[rPos] = aBytes[0]; + rPos ++; + pTarget[rPos] = aBytes[1]; + rPos ++; + pTarget[rPos] = aBytes[2]; + rPos ++; + } + } + else + { + sal_Int8 aBytes[] = { sal_Int8(0xC0 | ((c >> 6) & 0x1F)), + sal_Int8(0x80 | ((c >> 0) & 0x3F)) }; + if ((rPos + 2) > SEQUENCESIZE) + AddBytes(pTarget, rPos, aBytes, 2); + else + { + pTarget[rPos] = aBytes[0]; + rPos ++; + pTarget[rPos] = aBytes[1]; + rPos ++; + } + } + OSL_ENSURE(rPos <= SEQUENCESIZE, "not reset current position"); + if (rPos == SEQUENCESIZE) + rPos = writeSequence(); + + // reset left-over surrogate + if( ( nSurrogate != 0 ) && !( c >= 0xd800 && c < 0xdc00 ) ) + { + OSL_ENSURE( nSurrogate != 0, "left-over Unicode surrogate" ); + nSurrogate = 0; + bRet = false; + } + } + return bRet; +} + +void SaxWriterHelper::FinishStartElement() +{ + if (!m_bStartElementFinished) + { + mp_Sequence[nCurrentPos] = '>'; + nCurrentPos++; + if (nCurrentPos == SEQUENCESIZE) + nCurrentPos = writeSequence(); + m_bStartElementFinished = true; + } +} + +void SaxWriterHelper::insertIndentation(sal_uInt32 m_nLevel) +{ + FinishStartElement(); + if (m_nLevel > 0) + { + if ((nCurrentPos + m_nLevel + 1) <= SEQUENCESIZE) + { + mp_Sequence[nCurrentPos] = LINEFEED; + nLastLineFeedPos = nCurrentPos; + nCurrentPos++; + memset( &(mp_Sequence[nCurrentPos]) , 32 , m_nLevel ); + nCurrentPos += m_nLevel; + if (nCurrentPos == SEQUENCESIZE) + nCurrentPos = writeSequence(); + } + else + { + sal_uInt32 nCount(m_nLevel + 1); + std::unique_ptr pBytes(new sal_Int8[nCount]); + pBytes[0] = LINEFEED; + memset( &(pBytes[1]), 32, m_nLevel ); + AddBytes(mp_Sequence, nCurrentPos, pBytes.get(), nCount); + pBytes.reset(); + nLastLineFeedPos = nCurrentPos - nCount; + if (nCurrentPos == SEQUENCESIZE) + nCurrentPos = writeSequence(); + } + } + else + { + mp_Sequence[nCurrentPos] = LINEFEED; + nLastLineFeedPos = nCurrentPos; + nCurrentPos++; + if (nCurrentPos == SEQUENCESIZE) + nCurrentPos = writeSequence(); + } +} + +bool SaxWriterHelper::writeString( const OUString& rWriteOutString, + bool bDoNormalization, + bool bNormalizeWhitespace ) +{ + FinishStartElement(); + return convertToXML(rWriteOutString.getStr(), + rWriteOutString.getLength(), + bDoNormalization, + bNormalizeWhitespace, + mp_Sequence, + nCurrentPos); +} + +void SaxWriterHelper::startDocument() +{ + const char pc[] = ""; + const int nLen = strlen( pc ); + if ((nCurrentPos + nLen) <= SEQUENCESIZE) + { + memcpy( mp_Sequence, pc , nLen ); + nCurrentPos += nLen; + } + else + { + AddBytes(mp_Sequence, nCurrentPos, reinterpret_cast(pc), nLen); + } + OSL_ENSURE(nCurrentPos <= SEQUENCESIZE, "not reset current position"); + if (nCurrentPos == SEQUENCESIZE) + nCurrentPos = writeSequence(); + mp_Sequence[nCurrentPos] = LINEFEED; + nCurrentPos++; + if (nCurrentPos == SEQUENCESIZE) + nCurrentPos = writeSequence(); +} + +#ifndef NDEBUG +bool inrange(sal_Unicode c, sal_Unicode start, sal_Unicode end) +{ + return c >= start && c <= end; +} +#endif + +void CheckValidName(OUString const& rName) +{ +#ifdef NDEBUG + (void) rName; +#else + assert(!rName.isEmpty()); + bool hasColon(false); + for (sal_Int32 i = 0; i < rName.getLength(); ++i) + { + auto const c(rName[i]); + if (c == ':') + { + // see https://www.w3.org/TR/REC-xml-names/#ns-qualnames + assert(!hasColon && "only one colon allowed"); + hasColon = true; + } + else if (!rtl::isAsciiAlphanumeric(c) && c != '_' && c != '-' && c != '.' && + !inrange(c, 0x00C0, 0x00D6) && !inrange(c, 0x00D8, 0x00F6) && + !inrange(c, 0x00F8, 0x02FF) && !inrange(c, 0x0370, 0x037D) && + !inrange(c, 0x037F, 0x1FFF) && !inrange(c, 0x200C, 0x200D) && + !inrange(c, 0x2070, 0x218F) && !inrange(c, 0x2C00, 0x2FEF) && + !inrange(c, 0x3001, 0xD7FF) && !inrange(c, 0xF900, 0xFDCF) && + !inrange(c, 0xFDF0, 0xFFFD) && c != 0x00B7 && + !inrange(c, 0x0300, 0x036F) && !inrange(c, 0x203F, 0x2040)) + { + // https://www.w3.org/TR/xml11/#NT-NameChar + // (currently we don't warn about invalid start chars) + assert(!"unexpected character in attribute name"); + } + } +#endif +} + +SaxInvalidCharacterError SaxWriterHelper::startElement(const OUString& rName, const Reference< XAttributeList >& xAttribs) +{ + FinishStartElement(); + +#ifdef DBG_UTIL + m_DebugStartedElements.push(rName); + ::std::set DebugAttributes; +#endif + + mp_Sequence[nCurrentPos] = '<'; + nCurrentPos++; + if (nCurrentPos == SEQUENCESIZE) + nCurrentPos = writeSequence(); + + SaxInvalidCharacterError eRet(SAX_NONE); + CheckValidName(rName); + if (!writeString(rName, false, false)) + eRet = SAX_ERROR; + + sal_Int16 nAttribCount = xAttribs.is() ? xAttribs->getLength() : 0; + for(sal_Int16 i = 0 ; i < nAttribCount ; i++ ) + { + mp_Sequence[nCurrentPos] = ' '; + nCurrentPos++; + if (nCurrentPos == SEQUENCESIZE) + nCurrentPos = writeSequence(); + + OUString const& rAttrName(xAttribs->getNameByIndex(i)); +#ifdef DBG_UTIL + // Well-formedness constraint: Unique Att Spec + assert(DebugAttributes.find(rAttrName) == DebugAttributes.end()); + DebugAttributes.insert(rAttrName); +#endif + CheckValidName(rAttrName); + if (!writeString(rAttrName, false, false)) + eRet = SAX_ERROR; + + mp_Sequence[nCurrentPos] = '='; + nCurrentPos++; + if (nCurrentPos == SEQUENCESIZE) + nCurrentPos = writeSequence(); + mp_Sequence[nCurrentPos] = '"'; + nCurrentPos++; + if (nCurrentPos == SEQUENCESIZE) + nCurrentPos = writeSequence(); + + if (!writeString(xAttribs->getValueByIndex( i ), true, true) && + eRet != SAX_ERROR) + eRet = SAX_WARNING; + + mp_Sequence[nCurrentPos] = '"'; + nCurrentPos++; + if (nCurrentPos == SEQUENCESIZE) + nCurrentPos = writeSequence(); + } + + m_bStartElementFinished = false; // because the '>' character is not added, + // because it is possible, that the "/>" + // characters have to add + return eRet; +} + +bool SaxWriterHelper::FinishEmptyElement() +{ + if (m_bStartElementFinished) + return false; + + mp_Sequence[nCurrentPos] = '/'; + nCurrentPos++; + if (nCurrentPos == SEQUENCESIZE) + nCurrentPos = writeSequence(); + mp_Sequence[nCurrentPos] = '>'; + nCurrentPos++; + if (nCurrentPos == SEQUENCESIZE) + nCurrentPos = writeSequence(); + + m_bStartElementFinished = true; + + return true; +} + +bool SaxWriterHelper::endElement(const OUString& rName) +{ + FinishStartElement(); + + mp_Sequence[nCurrentPos] = '<'; + nCurrentPos++; + if (nCurrentPos == SEQUENCESIZE) + nCurrentPos = writeSequence(); + mp_Sequence[nCurrentPos] = '/'; + nCurrentPos++; + if (nCurrentPos == SEQUENCESIZE) + nCurrentPos = writeSequence(); + + CheckValidName(rName); + bool bRet(writeString( rName, false, false)); + + mp_Sequence[nCurrentPos] = '>'; + nCurrentPos++; + if (nCurrentPos == SEQUENCESIZE) + nCurrentPos = writeSequence(); + + return bRet; +} + +void SaxWriterHelper::endDocument() +{ + if (nCurrentPos > 0) + { + m_Sequence.realloc(nCurrentPos); + nCurrentPos = writeSequence(); + //m_Sequence.realloc(SEQUENCESIZE); + } +} + +void SaxWriterHelper::clearBuffer() +{ + FinishStartElement(); + if (nCurrentPos > 0) + { + m_Sequence.realloc(nCurrentPos); + nCurrentPos = writeSequence(); + m_Sequence.realloc(SEQUENCESIZE); + // Be sure to update the array pointer after the reallocation. + mp_Sequence = m_Sequence.getArray(); + } +} + +bool SaxWriterHelper::processingInstruction(const OUString& rTarget, const OUString& rData) +{ + FinishStartElement(); + mp_Sequence[nCurrentPos] = '<'; + nCurrentPos++; + if (nCurrentPos == SEQUENCESIZE) + nCurrentPos = writeSequence(); + mp_Sequence[nCurrentPos] = '?'; + nCurrentPos++; + if (nCurrentPos == SEQUENCESIZE) + nCurrentPos = writeSequence(); + + bool bRet(writeString( rTarget, false, false )); + + mp_Sequence[nCurrentPos] = ' '; + nCurrentPos++; + if (nCurrentPos == SEQUENCESIZE) + nCurrentPos = writeSequence(); + + if (!writeString( rData, false, false )) + bRet = false; + + mp_Sequence[nCurrentPos] = '?'; + nCurrentPos++; + if (nCurrentPos == SEQUENCESIZE) + nCurrentPos = writeSequence(); + mp_Sequence[nCurrentPos] = '>'; + nCurrentPos++; + if (nCurrentPos == SEQUENCESIZE) + nCurrentPos = writeSequence(); + + return bRet; +} + +void SaxWriterHelper::startCDATA() +{ + FinishStartElement(); + if ((nCurrentPos + 9) <= SEQUENCESIZE) + { + memcpy( &(mp_Sequence[nCurrentPos]), "("" , 3 ); + nCurrentPos += 3; + } + else + AddBytes(mp_Sequence, nCurrentPos, reinterpret_cast("]]>"), 3); + if (nCurrentPos == SEQUENCESIZE) + nCurrentPos = writeSequence(); +} + +bool SaxWriterHelper::comment(const OUString& rComment) +{ + FinishStartElement(); + mp_Sequence[nCurrentPos] = '<'; + nCurrentPos++; + if (nCurrentPos == SEQUENCESIZE) + nCurrentPos = writeSequence(); + mp_Sequence[nCurrentPos] = '!'; + nCurrentPos++; + if (nCurrentPos == SEQUENCESIZE) + nCurrentPos = writeSequence(); + mp_Sequence[nCurrentPos] = '-'; + nCurrentPos++; + if (nCurrentPos == SEQUENCESIZE) + nCurrentPos = writeSequence(); + mp_Sequence[nCurrentPos] = '-'; + nCurrentPos++; + if (nCurrentPos == SEQUENCESIZE) + nCurrentPos = writeSequence(); + + bool bRet(writeString( rComment, false, false)); + + mp_Sequence[nCurrentPos] = '-'; + nCurrentPos++; + if (nCurrentPos == SEQUENCESIZE) + nCurrentPos = writeSequence(); + mp_Sequence[nCurrentPos] = '-'; + nCurrentPos++; + if (nCurrentPos == SEQUENCESIZE) + nCurrentPos = writeSequence(); + mp_Sequence[nCurrentPos] = '>'; + nCurrentPos++; + if (nCurrentPos == SEQUENCESIZE) + nCurrentPos = writeSequence(); + + return bRet; +} + +sal_Int32 calcXMLByteLength( const OUString& rStr, + bool bDoNormalization, + bool bNormalizeWhitespace ) +{ + sal_Int32 nOutputLength = 0; + sal_uInt32 nSurrogate = 0; + + const sal_Unicode *pStr = rStr.getStr(); + sal_Int32 nStrLen = rStr.getLength(); + for( sal_Int32 i = 0 ; i < nStrLen ; i++ ) + { + sal_uInt16 c = pStr[i]; + if( !IsInvalidChar(c) && (c >= 0x0001) && (c <= 0x007F) ) + { + if( bDoNormalization ) + { + switch( c ) + { + case '&': // resemble to & + nOutputLength +=5; + break; + case '<': // < + case '>': // > + nOutputLength +=4; + break; + case 39: // 39 == ''', ' + case '"': // " + case 13: // + nOutputLength += 6; + break; + + case 10: // + case 9: // + if( bNormalizeWhitespace ) + { + nOutputLength += 6; + } + else + { + nOutputLength ++; + } + break; + default: + nOutputLength ++; + } + } + else + { + nOutputLength ++; + } + } + else if( c >= 0xd800 && c < 0xdc00 ) + { + // save surrogate + nSurrogate = ( ( c & 0x03ff ) + 0x0040 ); + } + else if( c >= 0xdc00 && c < 0xe000 ) + { + // 2. surrogate: write as UTF-8 (if range is OK + nSurrogate = ( nSurrogate << 10 ) | ( c & 0x03ff ); + if( rtl::isUnicodeScalarValue(nSurrogate) && nSurrogate >= 0x00010000 ) + nOutputLength += 4; + nSurrogate = 0; + } + else if( c > 0x07FF ) + { + nOutputLength += 3; + } + else + { + nOutputLength += 2; + } + + // surrogate processing + if( ( nSurrogate != 0 ) && !( c >= 0xd800 && c < 0xdc00 ) ) + nSurrogate = 0; + } + + return nOutputLength; +} + +/** returns position of first ascii 10 within the string, -1 when no 10 in string. + */ +sal_Int32 getFirstLineBreak( const OUString & str ) throw () +{ + const sal_Unicode *pSource = str.getStr(); + sal_Int32 nLen = str.getLength(); + + for( int n = 0; n < nLen ; n ++ ) + { + if( LINEFEED == pSource[n] ) { + return n; + } + } + return -1; +} + +class SAXWriter : + public WeakImplHelper< + XWriter, + XServiceInfo > +{ +public: + SAXWriter() + : m_bDocStarted(false) + , m_bIsCDATA(false) + , m_bForceLineBreak(false) + , m_bAllowLineBreak(false) + , m_nLevel(0) + { + } + +public: // XActiveDataSource + virtual void SAL_CALL setOutputStream(const Reference< XOutputStream > & aStream) override + { + try + { + // temporary: set same stream again to clear buffer + if ( m_out == aStream && m_pSaxWriterHelper && m_bDocStarted ) + m_pSaxWriterHelper->clearBuffer(); + else + { + m_out = aStream; + m_pSaxWriterHelper.reset( new SaxWriterHelper(m_out) ); + m_bDocStarted = false; + m_nLevel = 0; + m_bIsCDATA = false; + } + } + catch (const SAXException& e) + { + throw css::lang::WrappedTargetRuntimeException( + e.Message, + static_cast < OWeakObject * > ( this ), + e.WrappedException); + } + } + virtual Reference< XOutputStream > SAL_CALL getOutputStream() override + { + return m_out; + } + +public: // XDocumentHandler + virtual void SAL_CALL startDocument() override; + + virtual void SAL_CALL endDocument() override; + + virtual void SAL_CALL startElement(const OUString& aName, + const Reference< XAttributeList > & xAttribs) override; + + virtual void SAL_CALL endElement(const OUString& aName) override; + + virtual void SAL_CALL characters(const OUString& aChars) override; + + virtual void SAL_CALL ignorableWhitespace(const OUString& aWhitespaces) override; + virtual void SAL_CALL processingInstruction(const OUString& aTarget, + const OUString& aData) override; + virtual void SAL_CALL setDocumentLocator(const Reference< XLocator > & xLocator) override; + +public: // XExtendedDocumentHandler + virtual void SAL_CALL startCDATA() override; + virtual void SAL_CALL endCDATA() override; + virtual void SAL_CALL comment(const OUString& sComment) override; + virtual void SAL_CALL unknown(const OUString& sString) override; + virtual void SAL_CALL allowLineBreak() override; + +public: // XServiceInfo + OUString SAL_CALL getImplementationName() override; + Sequence< OUString > SAL_CALL getSupportedServiceNames() override; + sal_Bool SAL_CALL supportsService(const OUString& ServiceName) override; + +private: + sal_Int32 getIndentPrefixLength( sal_Int32 nFirstLineBreakOccurrence ) throw(); + + Reference< XOutputStream > m_out; + std::unique_ptr m_pSaxWriterHelper; + + // Status information + bool m_bDocStarted : 1; + bool m_bIsCDATA : 1; + bool m_bForceLineBreak : 1; + bool m_bAllowLineBreak : 1; + sal_Int32 m_nLevel; +}; + +sal_Int32 SAXWriter::getIndentPrefixLength( sal_Int32 nFirstLineBreakOccurrence ) throw() +{ + sal_Int32 nLength =-1; + if (m_pSaxWriterHelper) + { + if ( m_bForceLineBreak || + (m_bAllowLineBreak && + ((nFirstLineBreakOccurrence + m_pSaxWriterHelper->GetLastColumnCount()) > MAXCOLUMNCOUNT)) ) + nLength = m_nLevel; + } + m_bForceLineBreak = false; + m_bAllowLineBreak = false; + return nLength; +} + +bool isFirstCharWhitespace( const sal_Unicode *p ) throw() +{ + return *p == ' '; +} + +// XServiceInfo +OUString SAXWriter::getImplementationName() +{ + return "com.sun.star.extensions.xml.sax.Writer"; +} + +// XServiceInfo +sal_Bool SAXWriter::supportsService(const OUString& ServiceName) +{ + return cppu::supportsService(this, ServiceName); +} + +// XServiceInfo +Sequence< OUString > SAXWriter::getSupportedServiceNames() +{ + return { "com.sun.star.xml.sax.Writer" }; +} + +void SAXWriter::startDocument() +{ + if( m_bDocStarted || ! m_out.is() || !m_pSaxWriterHelper ) { + throw SAXException(); + } + m_bDocStarted = true; + m_pSaxWriterHelper->startDocument(); +} + + +void SAXWriter::endDocument() +{ + if( ! m_bDocStarted ) + { + throw SAXException( + "endDocument called before startDocument", + Reference< XInterface >() , Any() ); + } + if( m_nLevel ) { + throw SAXException( + "unexpected end of document", + Reference< XInterface >() , Any() ); + } + m_pSaxWriterHelper->endDocument(); + try + { + m_out->closeOutput(); + } + catch (const IOException &) + { + css::uno::Any anyEx = cppu::getCaughtException(); + throw SAXException( + "IO exception during closing the IO Stream", + Reference< XInterface > (), + anyEx ); + } +} + + +void SAXWriter::startElement(const OUString& aName, const Reference< XAttributeList >& xAttribs) +{ + if( ! m_bDocStarted ) + { + SAXException except; + except.Message = "startElement called before startDocument"; + throw except; + } + if( m_bIsCDATA ) + { + SAXException except; + except.Message = "startElement call not allowed with CDATA sections"; + throw except; + } + + sal_Int32 nLength(0); + if (m_bAllowLineBreak) + { + sal_Int32 nAttribCount = xAttribs.is() ? xAttribs->getLength() : 0; + + nLength ++; // "<" + nLength += calcXMLByteLength( aName, false, false ); // the tag name + + sal_Int16 n; + for( n = 0 ; n < static_cast(nAttribCount) ; n ++ ) { + nLength ++; // " " + OUString tmp = xAttribs->getNameByIndex( n ); + + nLength += calcXMLByteLength( tmp, false, false ); + + nLength += 2; // =" + + tmp = xAttribs->getValueByIndex( n ); + + nLength += calcXMLByteLength( tmp, true, true ); + + nLength += 1; // " + } + + nLength ++; // '>' + } + + // Is there a new indentation necessary ? + sal_Int32 nPrefix(getIndentPrefixLength( nLength )); + + // write into sequence + if( nPrefix >= 0 ) + m_pSaxWriterHelper->insertIndentation( nPrefix ); + + SaxInvalidCharacterError eRet(m_pSaxWriterHelper->startElement(aName, xAttribs)); + + m_nLevel++; + + if (eRet == SAX_WARNING) + { + SAXInvalidCharacterException except; + except.Message = "Invalid character during XML-Export in an attribute value"; + throw except; + } + else if (eRet == SAX_ERROR) + { + SAXException except; + except.Message = "Invalid character during XML-Export"; + throw except; + } +} + +void SAXWriter::endElement(const OUString& aName) +{ + if( ! m_bDocStarted ) { + throw SAXException (); + } + m_nLevel --; + + if( m_nLevel < 0 ) { + throw SAXException(); + } + bool bRet(true); + + // check here because Helper's endElement is not always called +#ifdef DBG_UTIL + assert(!m_pSaxWriterHelper->m_DebugStartedElements.empty()); + // Well-formedness constraint: Element Type Match + assert(aName == m_pSaxWriterHelper->m_DebugStartedElements.top()); + m_pSaxWriterHelper->m_DebugStartedElements.pop(); +#endif + + if( m_pSaxWriterHelper->FinishEmptyElement() ) + m_bForceLineBreak = false; + else + { + // only ascii chars allowed + sal_Int32 nLength(0); + if (m_bAllowLineBreak) + nLength = 3 + calcXMLByteLength( aName, false, false ); + sal_Int32 nPrefix = getIndentPrefixLength( nLength ); + + if( nPrefix >= 0 ) + m_pSaxWriterHelper->insertIndentation( nPrefix ); + + bRet = m_pSaxWriterHelper->endElement(aName); + } + + if (!bRet) + { + SAXException except; + except.Message = "Invalid character during XML-Export"; + throw except; + } +} + +void SAXWriter::characters(const OUString& aChars) +{ + if( ! m_bDocStarted ) + { + SAXException except; + except.Message = "characters method called before startDocument"; + throw except; + } + + bool bThrowException(false); + if( !aChars.isEmpty() ) + { + if( m_bIsCDATA ) + bThrowException = !m_pSaxWriterHelper->writeString( aChars, false, false ); + else + { + // Note : nFirstLineBreakOccurrence is not exact, because we don't know, how + // many 2 and 3 byte chars are inbetween. However this whole stuff + // is eitherway for pretty printing only, so it does not need to be exact. + sal_Int32 nLength(0); + sal_Int32 nIndentPrefix(-1); + if (m_bAllowLineBreak) + { + sal_Int32 nFirstLineBreakOccurrence = getFirstLineBreak( aChars ); + + nLength = calcXMLByteLength( aChars, ! m_bIsCDATA , false ); + nIndentPrefix = getIndentPrefixLength( + nFirstLineBreakOccurrence >= 0 ? nFirstLineBreakOccurrence : nLength ); + } + else + nIndentPrefix = getIndentPrefixLength(nLength); + + // insert indentation + if( nIndentPrefix >= 0 ) + { + if( isFirstCharWhitespace( aChars.getStr() ) ) + m_pSaxWriterHelper->insertIndentation( nIndentPrefix - 1 ); + else + m_pSaxWriterHelper->insertIndentation( nIndentPrefix ); + } + bThrowException = !m_pSaxWriterHelper->writeString(aChars, true , false); + } + } + if (bThrowException) + { + SAXInvalidCharacterException except; + except.Message = "Invalid character during XML-Export"; + throw except; + } +} + + +void SAXWriter::ignorableWhitespace(const OUString&) +{ + if( ! m_bDocStarted ) + { + throw SAXException (); + } + + m_bForceLineBreak = true; +} + +void SAXWriter::processingInstruction(const OUString& aTarget, const OUString& aData) +{ + if( ! m_bDocStarted || m_bIsCDATA ) + { + throw SAXException(); + } + + sal_Int32 nLength(0); + if (m_bAllowLineBreak) + { + nLength = 2; // "" + } + + sal_Int32 nPrefix = getIndentPrefixLength( nLength ); + + if( nPrefix >= 0 ) + m_pSaxWriterHelper->insertIndentation( nPrefix ); + + if (!m_pSaxWriterHelper->processingInstruction(aTarget, aData)) + { + SAXException except; + except.Message = "Invalid character during XML-Export"; + throw except; + } +} + + +void SAXWriter::setDocumentLocator(const Reference< XLocator >&) +{ + +} + +void SAXWriter::startCDATA() +{ + if( ! m_bDocStarted || m_bIsCDATA) + { + throw SAXException (); + } + + sal_Int32 nPrefix = getIndentPrefixLength( 9 ); + if( nPrefix >= 0 ) + m_pSaxWriterHelper->insertIndentation( nPrefix ); + + m_pSaxWriterHelper->startCDATA(); + + m_bIsCDATA = true; +} + +void SAXWriter::endCDATA() +{ + if( ! m_bDocStarted || ! m_bIsCDATA) + { + SAXException except; + except.Message = "endCDATA was called without startCDATA"; + throw except; + } + + sal_Int32 nPrefix = getIndentPrefixLength( 3 ); + if( nPrefix >= 0 ) + m_pSaxWriterHelper->insertIndentation( nPrefix ); + + m_pSaxWriterHelper->endCDATA(); + + m_bIsCDATA = false; +} + + +void SAXWriter::comment(const OUString& sComment) +{ + if( ! m_bDocStarted || m_bIsCDATA ) + { + throw SAXException(); + } + + sal_Int32 nLength(0); + if (m_bAllowLineBreak) + { + nLength = 4; // "\n" , o1.getStr() ); + } + } + virtual void SAL_CALL unknown(const OUString& sString) throw (SAXException,RuntimeException) + { + if( m_bPrint ) + { + OString o1 = OUStringToOString(sString, RTL_TEXTENCODING_UTF8 ); + printf( "UNKNOWN : {%s}\n" , o1.getStr() ); + } + } + + virtual void SAL_CALL allowLineBreak() throw (SAXException, RuntimeException ) + { + + } + + int m_iLevel; + int m_iElementCount; + int m_iAttributeCount; + int m_iWhitespaceCount; + int m_iCharCount; + sal_Bool m_bPrint; + + Reference < XMultiServiceFactory > m_xSMgr; + Reference < XLocator > m_rLocator; +}; + +void OSaxParserTest::testSimple( const Reference < XParser > &rParser ) +{ + char TestString[] = "\n" + "\n" + "]>\n" + "\n" + " fjklsfdklsdfkl\n" + "fjklsfdklsdfkl\n" + "\n" + "&testInternal;\n" + " blahuhu\n" + " blahi\n" + " Hello, '+1+12world!]]>\n" + " \n" + "\n" + "\n" + "aus XMLTest\n" + "\n" + "\n" + "\n\n\n"; + + Sequence< sal_Int8> seqBytes( strlen( TestString ) ); + memcpy( seqBytes.getArray() , TestString , strlen( TestString ) ); + + Reference< XInputStream > rInStream; + OUString sInput; + rInStream = createStreamFromSequence( seqBytes , m_rFactory ); + sInput = "internal"; + + if( rParser.is() ) { + InputSource source; + + source.aInputStream = rInStream; + source.sSystemId = sInput; + + TestDocumentHandler *pDocHandler = new TestDocumentHandler( m_rFactory , sal_False ); + Reference < XDocumentHandler > rDocHandler( (XDocumentHandler *) pDocHandler , UNO_QUERY ); + Reference< XEntityResolver > + rEntityResolver( (XEntityResolver *) pDocHandler , UNO_QUERY ); + + rParser->setDocumentHandler( rDocHandler ); + rParser->setEntityResolver( rEntityResolver ); + + try + { + rParser->parseStream( source ); + ERROR_ASSERT( pDocHandler->m_iElementCount == 4 , "wrong element count" ); + ERROR_ASSERT( pDocHandler->m_iAttributeCount == 2 , "wrong attribute count" ); + ERROR_ASSERT( pDocHandler->m_iCharCount == 130 , "wrong char count" ); + ERROR_ASSERT( pDocHandler->m_iWhitespaceCount == 0, "wrong whitespace count" ); + } + catch( SAXParseException & e ) + { + OString o1 = OUStringToOString(e.Message, RTL_TEXTENCODING_UTF8 ); + BUILD_ERROR( 1 , o1.getStr() ); + } + catch( SAXException & e ) + { + OString o1 = OUStringToOString(e.Message, RTL_TEXTENCODING_UTF8 ); + BUILD_ERROR( 1 , o1.getStr() ); + } + catch( Exception & e ) + { + OString o1 = OUStringToOString(e.Message, RTL_TEXTENCODING_UTF8 ); + BUILD_ERROR( 1 , o1.getStr() ); + } + catch( ... ) + { + BUILD_ERROR( 1 , "unknown exception" ); + } + } +} + +void OSaxParserTest::testNamespaces( const Reference < XParser > &rParser ) +{ + + char TestString[] = + "\n" + "\n" + "\n" + "Frobnostication\n" + "Moved to \n" + "here.\n" + "\n"; + + Sequence seqBytes( strlen( TestString ) ); + memcpy( seqBytes.getArray() , TestString , strlen( TestString ) ); + + Reference< XInputStream > rInStream; + OUString sInput; + + rInStream = createStreamFromSequence( seqBytes , m_rFactory ); + sInput = "internal"; + + if( rParser.is() ) { + InputSource source; + + source.aInputStream = rInStream; + source.sSystemId = sInput; + + TestDocumentHandler *pDocHandler = new TestDocumentHandler( m_rFactory , sal_False ); + Reference < XDocumentHandler > rDocHandler( (XDocumentHandler *) pDocHandler , UNO_QUERY ); + Reference< XEntityResolver > rEntityResolver( + (XEntityResolver *) pDocHandler , UNO_QUERY ); + + rParser->setDocumentHandler( rDocHandler ); + rParser->setEntityResolver( rEntityResolver ); + + try + { + rParser->parseStream( source ); + ERROR_ASSERT( pDocHandler->m_iElementCount == 6 , "wrong element count" ); + ERROR_ASSERT( pDocHandler->m_iAttributeCount == 2 , "wrong attribute count" ); + ERROR_ASSERT( pDocHandler->m_iCharCount == 33, "wrong char count" ); + ERROR_ASSERT( pDocHandler->m_iWhitespaceCount == 0 , "wrong whitespace count" ); + } + catch( Exception & e ) { + OString o1 = OUStringToOString(e.Message, RTL_TEXTENCODING_UTF8 ); + BUILD_ERROR( 1 , o1.getStr() ); + } + catch( ... ) + { + BUILD_ERROR( 1 , "unknown exception" ); + } + } +} + +void OSaxParserTest::testEncoding( const Reference < XParser > &rParser ) +{ + char TestString[] = + "\n" + "\n" + "\n" + "Frobnostication\n" + "Moved to \337\n" + "here.\n" + "\n"; + + Sequence seqBytes( strlen( TestString ) ); + memcpy( seqBytes.getArray() , TestString , strlen( TestString ) ); + + Reference< XInputStream > rInStream; + OUString sInput; + + rInStream = createStreamFromSequence( seqBytes , m_rFactory ); + sInput = "internal"; + + if( rParser.is() ) { + InputSource source; + + source.aInputStream = rInStream; + source.sSystemId = sInput; + + TestDocumentHandler *pDocHandler = new TestDocumentHandler( m_rFactory , sal_False ); + Reference < XDocumentHandler > rDocHandler( (XDocumentHandler *) pDocHandler , UNO_QUERY ); + Reference< XEntityResolver > rEntityResolver( (XEntityResolver *) pDocHandler , UNO_QUERY ); + + rParser->setDocumentHandler( rDocHandler ); + rParser->setEntityResolver( rEntityResolver ); + try + { + rParser->parseStream( source ); + } + catch( Exception & e ) + { + OString o1 = OUStringToOString(e.Message, RTL_TEXTENCODING_UTF8 ); + BUILD_ERROR( 1 , o1.getStr() ); + } + catch ( ... ) + { + BUILD_ERROR( 1 , "unknown exception" ); + } + } +} + +void OSaxParserTest::testFile( const Reference < XParser > & rParser ) +{ + + Reference< XInputStream > rInStream = createStreamFromFile( "testsax.xml" , m_rFactory ); + OUString sInput = "testsax.xml"; + + if( rParser.is() && rInStream.is() ) { + InputSource source; + + source.aInputStream = rInStream; + source.sSystemId = sInput; + + TestDocumentHandler *pDocHandler = new TestDocumentHandler( m_rFactory , sal_True ); + Reference < XDocumentHandler > rDocHandler( (XDocumentHandler *) pDocHandler , UNO_QUERY ); + Reference < XEntityResolver > rEntityResolver( (XEntityResolver *) pDocHandler , UNO_QUERY ); + Reference < XErrorHandler > rErrorHandler( ( XErrorHandler * )pDocHandler , UNO_QUERY ); + + rParser->setDocumentHandler( rDocHandler ); + rParser->setEntityResolver( rEntityResolver ); + rParser->setErrorHandler( rErrorHandler ); + + try + { + rParser->parseStream( source ); + } + catch( SAXParseException & e ) { + Any any; + any <<= e; + + while(true) { + SAXParseException *pEx; + if( any.getValueType() == cppu::UnoType::get() ) { + pEx = ( SAXParseException * ) any.getValue(); + OString o1 = OUStringToOString(pEx->Message, RTL_TEXTENCODING_UTF8 ); + printf( "%s\n" , o1.getStr() ); + any = pEx->WrappedException; + } + else { + break; + } + } + } + catch( SAXException & e ) + { + OString o1 = OUStringToOString(e.Message, RTL_TEXTENCODING_UTF8 ); + BUILD_ERROR( 1 , o1.getStr() ); + + } + catch( Exception & e ) { + printf( "normal exception ! %s\n", e.Message ); + } + catch ( ... ) + { + printf( "any exception !!!!\n" ); + } + } +} + +void OSaxParserTest::testPerformance( const Reference < XParser > & rParser ) +{ + Reference < XInputStream > rInStream = + createStreamFromFile( "testPerformance.xml" , m_rFactory ); + OUString sInput = "testperformance.xml"; + + if( rParser.is() && rInStream.is() ) { + InputSource source; + + source.aInputStream = rInStream; + source.sSystemId = sInput; + + TestDocumentHandler *pDocHandler = new TestDocumentHandler( m_rFactory , sal_False ); + Reference < XDocumentHandler > rDocHandler( (XDocumentHandler *) pDocHandler , UNO_QUERY ); + Reference < XEntityResolver > rEntityResolver( (XEntityResolver *) pDocHandler , UNO_QUERY ); + Reference < XErrorHandler > rErrorHandler( ( XErrorHandler * )pDocHandler , UNO_QUERY ); + + rParser->setDocumentHandler( rDocHandler ); + rParser->setEntityResolver( rEntityResolver ); + rParser->setErrorHandler( rErrorHandler ); + + try + { + TimeValue aStartTime, aEndTime; + osl_getSystemTime( &aStartTime ); + rParser->parseStream( source ); + osl_getSystemTime( &aEndTime ); + + double fStart = (double)aStartTime.Seconds + ((double)aStartTime.Nanosec / 1000000000.0); + double fEnd = (double)aEndTime.Seconds + ((double)aEndTime.Nanosec / 1000000000.0); + + printf( "Performance reading : %g s\n" , fEnd - fStart ); + + } + catch( SAXParseException &e ) { + Any any; + any <<= e; + while(true) { + if( any.getValueType() == cppu::UnoType::get() ) { + SAXParseException ex; + any >>= ex; + OString o = OUStringToOString( ex.Message , RTL_TEXTENCODING_ASCII_US ); + printf( "%s\n" , o.getStr() ); + any <<= ex.WrappedException; + } + else { + break; + } + } + } + catch( SAXException &e ) { + OString o = OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US ); + printf( "%s\n" , o.getStr() ); + + } + catch( ... ) + { + printf( "any exception !!!!\n" ); + } + } +} +} // namespace + +using namespace sax_test; + +extern "C" +{ + +sal_Bool SAL_CALL component_writeInfo( + void * pServiceManager, void * pRegistryKey ) +{ + if (pRegistryKey) + { + try + { + Reference< XRegistryKey > xKey( + reinterpret_cast< XRegistryKey * >( pRegistryKey ) ); + + OUString str = + OUString( "/" ) + + OSaxParserTest_getImplementationName() + + OUString( "/UNO/SERVICES" ); + Reference< XRegistryKey > xNewKey = xKey->createKey( str ); + xNewKey->createKey( OSaxParserTest_getServiceName() ); + + str = + OUString( "/" ) + + OSaxWriterTest_getImplementationName() + + OUString( "/UNO/SERVICES" ); + + xNewKey = xKey->createKey( str ); + xNewKey->createKey( OSaxWriterTest_getServiceName() ); + + return sal_True; + } + catch (InvalidRegistryException &) + { + OSL_FAIL( "### InvalidRegistryException!" ); + } + } + return sal_False; +} + +SAL_DLLPUBLIC_EXPORT void * SAL_CALL component_getFactory( + const char * pImplName, void * pServiceManager, void * pRegistryKey ) +{ + void * pRet = 0; + + if (pServiceManager ) + { + Reference< XSingleServiceFactory > xRet; + Reference< XMultiServiceFactory > xSMgr = + reinterpret_cast< XMultiServiceFactory * > ( pServiceManager ); + + OUString aImplementationName = OUString::createFromAscii( pImplName ); + + + if (aImplementationName == OSaxWriterTest_getImplementationName() ) + { + xRet = createSingleFactory( xSMgr, aImplementationName, + OSaxWriterTest_CreateInstance, + OSaxWriterTest_getSupportedServiceNames() ); + } + else if (aImplementationName == OSaxParserTest_getImplementationName() ) + { + xRet = createSingleFactory( xSMgr, aImplementationName, + OSaxParserTest_CreateInstance, + OSaxParserTest_getSupportedServiceNames() ); + } + if (xRet.is()) + { + xRet->acquire(); + pRet = xRet.get(); + } + } + return pRet; +} + +} // extern C + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sax/test/sax/testwriter.cxx b/sax/test/sax/testwriter.cxx new file mode 100644 index 000000000..2a5d3706d --- /dev/null +++ b/sax/test/sax/testwriter.cxx @@ -0,0 +1,662 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#include +#include + +#include +#include + +#include +#include +#include +#include +#include + +#include + +#include +#include + + +using namespace ::std; +using namespace ::cppu; +using namespace ::com::sun::star::uno; +using namespace ::com::sun::star::lang; +using namespace ::com::sun::star::test; +using namespace ::com::sun::star::registry; +using namespace ::com::sun::star::io; +using namespace ::com::sun::star::xml::sax; + +namespace sax_test { + +class OFileWriter : + public WeakImplHelper< XOutputStream > +{ +public: + explicit OFileWriter( char *pcFile ) { strncpy( m_pcFile, pcFile, 256 - 1 ); m_f = 0; } + + +public: + virtual void SAL_CALL writeBytes(const Sequence< sal_Int8 >& aData) + throw (NotConnectedException, BufferSizeExceededException, RuntimeException); + virtual void SAL_CALL flush() + throw (NotConnectedException, BufferSizeExceededException, RuntimeException); + virtual void SAL_CALL closeOutput() + throw (NotConnectedException, BufferSizeExceededException, RuntimeException); +private: + char m_pcFile[256]; + FILE *m_f; +}; + + +void OFileWriter::writeBytes(const Sequence< sal_Int8 >& aData) + throw (NotConnectedException, BufferSizeExceededException, RuntimeException) +{ + if( ! m_f ) { + m_f = fopen( m_pcFile , "w" ); + } + + fwrite( aData.getConstArray() , 1 , aData.getLength() , m_f ); +} + + +void OFileWriter::flush() + throw (NotConnectedException, BufferSizeExceededException, RuntimeException) +{ + fflush( m_f ); +} + +void OFileWriter::closeOutput() + throw (NotConnectedException, BufferSizeExceededException, RuntimeException) +{ + fclose( m_f ); + m_f = 0; +} + + +class OSaxWriterTest : + public WeakImplHelper< XSimpleTest > +{ +public: + explicit OSaxWriterTest( const Reference < XMultiServiceFactory > & rFactory ) : m_rFactory( rFactory ) + { + + } + ~OSaxWriterTest() {} + + +public: + virtual void SAL_CALL testInvariant( + const OUString& TestName, + const Reference < XInterface >& TestObject) + throw ( IllegalArgumentException, + RuntimeException); + + virtual sal_Int32 SAL_CALL test( + const OUString& TestName, + const Reference < XInterface >& TestObject, + sal_Int32 hTestHandle) + throw ( IllegalArgumentException,RuntimeException); + + virtual sal_Bool SAL_CALL testPassed() + throw ( RuntimeException); + virtual Sequence< OUString > SAL_CALL getErrors() throw (RuntimeException); + virtual Sequence< Any > SAL_CALL getErrorExceptions() throw (RuntimeException); + virtual Sequence< OUString > SAL_CALL getWarnings() throw (RuntimeException); + +private: + void testSimple( const Reference< XExtendedDocumentHandler > &r ); + void testExceptions( const Reference< XExtendedDocumentHandler > &r ); + void testDTD( const Reference< XExtendedDocumentHandler > &r ); + void testPerformance( const Reference< XExtendedDocumentHandler > &r ); + void writeParagraph( const Reference< XExtendedDocumentHandler > &r , const OUString & s); + +private: + Sequence m_seqExceptions; + Sequence m_seqErrors; + Sequence m_seqWarnings; + Reference < XMultiServiceFactory > m_rFactory; + +}; + + +/*---------------------------------------- +* +* Attributelist implementation +* +*----------------------------------------*/ +struct AttributeListImpl_impl; +class AttributeListImpl : public WeakImplHelper< XAttributeList > +{ +public: + AttributeListImpl(); + AttributeListImpl( const AttributeListImpl & ); + ~AttributeListImpl(); + +public: + virtual sal_Int16 SAL_CALL getLength() throw (RuntimeException); + virtual OUString SAL_CALL getNameByIndex(sal_Int16 i) throw (RuntimeException); + virtual OUString SAL_CALL getTypeByIndex(sal_Int16 i) throw (RuntimeException); + virtual OUString SAL_CALL getTypeByName(const OUString& aName) throw (RuntimeException); + virtual OUString SAL_CALL getValueByIndex(sal_Int16 i) throw (RuntimeException); + virtual OUString SAL_CALL getValueByName(const OUString& aName) throw (RuntimeException); + +public: + void addAttribute( const OUString &sName , + const OUString &sType , + const OUString &sValue ); + void clear(); + +private: + struct AttributeListImpl_impl *m_pImpl; +}; + + +struct TagAttribute +{ + TagAttribute(){} + TagAttribute( const OUString &sName, + const OUString &sType , + const OUString &sValue ) + { + sName = sName; + sType = sType; + sValue = sValue; + } + + OUString sName; + OUString sType; + OUString sValue; +}; + +struct AttributeListImpl_impl +{ + AttributeListImpl_impl() + { + // performance improvement during adding + vecAttribute.reserve(20); + } + vector vecAttribute; +}; + + +sal_Int16 AttributeListImpl::getLength() throw (RuntimeException) +{ + return m_pImpl->vecAttribute.size(); +} + + +AttributeListImpl::AttributeListImpl( const AttributeListImpl &r ) +{ + m_pImpl = new AttributeListImpl_impl; + *m_pImpl = *(r.m_pImpl); +} + +OUString AttributeListImpl::getNameByIndex(sal_Int16 i) throw (RuntimeException) +{ + if( i < m_pImpl->vecAttribute.size() ) { + return m_pImpl->vecAttribute[i].sName; + } + return OUString(); +} + + +OUString AttributeListImpl::getTypeByIndex(sal_Int16 i) throw (RuntimeException) +{ + if( i < m_pImpl->vecAttribute.size() ) { + return m_pImpl->vecAttribute[i].sType; + } + return OUString(); +} + +OUString AttributeListImpl::getValueByIndex(sal_Int16 i) throw (RuntimeException) +{ + if( i < m_pImpl->vecAttribute.size() ) { + return m_pImpl->vecAttribute[i].sValue; + } + return OUString(); + +} + +OUString AttributeListImpl::getTypeByName( const OUString& sName ) throw (RuntimeException) +{ + auto ii = std::find_if(m_pImpl->vecAttribute.begin(), m_pImpl->vecAttribute.end(), + [&sName](const struct TagAttribute& rAttr) { return rAttr.sName == sName; }); + if (ii != m_pImpl->vecAttribute.end()) + return (*ii).sType; + return OUString(); +} + +OUString AttributeListImpl::getValueByName(const OUString& sName) throw (RuntimeException) +{ + auto ii = std::find_if(m_pImpl->vecAttribute.begin(), m_pImpl->vecAttribute.end(), + [&sName](const struct TagAttribute& rAttr) { return rAttr.sName == sName; }); + if (ii != m_pImpl->vecAttribute.end()) + return (*ii).sValue; + return OUString(); +} + + +AttributeListImpl::AttributeListImpl() +{ + m_pImpl = new AttributeListImpl_impl; +} + + +AttributeListImpl::~AttributeListImpl() +{ + delete m_pImpl; +} + + +void AttributeListImpl::addAttribute( const OUString &sName , + const OUString &sType , + const OUString &sValue ) +{ + m_pImpl->vecAttribute.push_back( TagAttribute( sName , sType , sValue ) ); +} + +void AttributeListImpl::clear() +{ + m_pImpl->vecAttribute.clear(); + +} + + +/** +* for external binding +* +* +**/ +Reference < XInterface > SAL_CALL OSaxWriterTest_CreateInstance( const Reference < XMultiServiceFactory > & rSMgr ) throw (Exception) +{ + OSaxWriterTest *p = new OSaxWriterTest( rSMgr ); + Reference < XInterface > xService = *p; + return xService; +} + +OUString OSaxWriterTest_getServiceName( ) throw () +{ + return OUString( "test.com.sun.star.xml.sax.Writer"); +} + +OUString OSaxWriterTest_getImplementationName( ) throw () +{ + return OUString( "test.extensions.xml.sax.Writer"); +} + +Sequence OSaxWriterTest_getSupportedServiceNames( ) throw () +{ + Sequence aRet { OSaxWriterTest_getImplementationName( ) }; + return aRet; +} + + +void OSaxWriterTest::testInvariant( const OUString& TestName, + const Reference < XInterface >& TestObject ) + throw ( IllegalArgumentException, RuntimeException) +{ + if( OUString("com.sun.star.xml.sax.Writer") == TestName ) { + Reference< XDocumentHandler > doc( TestObject , UNO_QUERY ); + Reference< XExtendedDocumentHandler > ext( TestObject , UNO_QUERY ); + Reference< XActiveDataSource > source( TestObject , UNO_QUERY ); + + ERROR_ASSERT( doc.is() , "XDocumentHandler cannot be queried" ); + ERROR_ASSERT( ext.is() , "XExtendedDocumentHandler cannot be queried" ); + ERROR_ASSERT( source.is() , "XActiveDataSource cannot be queried" ); + } + else { + BUILD_ERROR( 0 , "wrong test" ); + } +} + + +sal_Int32 OSaxWriterTest::test( + const OUString& TestName, + const Reference < XInterface >& TestObject, + sal_Int32 hTestHandle) + throw ( IllegalArgumentException,RuntimeException) +{ + if( OUString( "com.sun.star.xml.sax.Writer") == TestName ) + { + try + { + if( 0 == hTestHandle ) + { + testInvariant( TestName , TestObject ); + } + else + { + Reference< XExtendedDocumentHandler > writer( TestObject , UNO_QUERY ); + + if( 1 == hTestHandle ) { + testSimple( writer ); + } + else if( 2 == hTestHandle ) { + testExceptions( writer ); + } + else if( 3 == hTestHandle ) { + testDTD( writer ); + } + else if( 4 == hTestHandle ) { + testPerformance( writer ); + } + } + } + catch( Exception & e ) { + OString o = OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US ); + BUILD_ERROR( 0 , o.getStr() ); + } + catch( ... ) + { + BUILD_ERROR( 0 , "unknown exception (Exception is not base class)" ); + } + + hTestHandle ++; + + if( hTestHandle >= 5) { + // all tests finished. + hTestHandle = -1; + } + } + else { + BUILD_ERROR( 0 , "service not supported by test." ); + } + return hTestHandle; +} + + +sal_Bool OSaxWriterTest::testPassed() throw (RuntimeException) +{ + return m_seqErrors.getLength() == 0; +} + + +Sequence< OUString > OSaxWriterTest::getErrors() throw (RuntimeException) +{ + return m_seqErrors; +} + + +Sequence< Any > OSaxWriterTest::getErrorExceptions() throw (RuntimeException) +{ + return m_seqExceptions; +} + + +Sequence< OUString > OSaxWriterTest::getWarnings() throw (RuntimeException) +{ + return m_seqWarnings; +} + +void OSaxWriterTest::writeParagraph( + const Reference< XExtendedDocumentHandler > &r , + const OUString & s) +{ + int nMax = s.getLength(); + int nStart = 0; + + Sequence seq( s.getLength() ); + memcpy( seq.getArray() , s.getStr() , s.getLength() * sizeof( sal_uInt16 ) ); + + for( int n = 1 ; n < nMax ; n++ ){ + if( 32 == seq.getArray()[n] ) { + r->allowLineBreak(); + r->characters( s.copy( nStart , n - nStart ) ); + nStart = n; + } + } + r->allowLineBreak(); + r->characters( s.copy( nStart , n - nStart ) ); +} + + +void OSaxWriterTest::testSimple( const Reference< XExtendedDocumentHandler > &r ) +{ + OUString testParagraph = OUString( + "This is a stupid test to check whether the SAXWriter possibly makes " + "line breaks halfway correctly or whether it writes the line to the " + "bitter end." ); + + OFileWriter *pw = new OFileWriter("output.xml"); + AttributeListImpl *pList = new AttributeListImpl; + + Reference< XAttributeList > rList( (XAttributeList *) pList , UNO_QUERY ); + Reference< XOutputStream > ref( ( XOutputStream * ) pw , UNO_QUERY ); + + Reference< XActiveDataSource > source( r , UNO_QUERY ); + + ERROR_ASSERT( ref.is() , "no output stream" ); + ERROR_ASSERT( source.is() , "no active data source" ); + + source->setOutputStream( ref ); + + r->startDocument(); + + pList->addAttribute( OUString( "Arg1" ), + OUString( "CDATA") , + OUString( "bla\n u") ); + pList->addAttribute( OUString( "Arg2") , + OUString( "CDATA") , + OUString( "blub") ); + + r->startElement( OUString( "tag1") , rList ); + r->ignorableWhitespace( OUString() ); + + r->characters( OUString( "huhu") ); + r->ignorableWhitespace( OUString() ); + + r->startElement( OUString( "hi") , rList ); + r->ignorableWhitespace( OUString() ); + + // the ampersand must be converted & -> & + r->characters( OUString( "ü") ); + + // Test added for mib. Tests if errors during conversions occurs + r->ignorableWhitespace( OUString() ); + char array[256]; + for( sal_Int32 n = 32 ; n < 254 ; n ++ ) { + array[n-32] = n; + } + array[254-32] = 0; + r->characters( + OStringToOUString( array , RTL_TEXTENCODING_SYMBOL ) + ); + r->ignorableWhitespace( OUString() ); + + // '>' must not be converted + r->startCDATA(); + r->characters( OUString( ">fsfsdf<") ); + r->endCDATA(); + r->ignorableWhitespace( OUString() ); + + writeParagraph( r , testParagraph ); + + + r->ignorableWhitespace( OUString() ); + r->comment( OUString( "This is a comment !") ); + r->ignorableWhitespace( OUString() ); + + r->startElement( OUString( "emptytagtest") , rList ); + r->endElement( OUString( "emptytagtest") ); + + r->endElement( OUString( "hi") ); + r->ignorableWhitespace( OUString() ); + + r->endElement( OUString( "tag1") ); + r->endDocument(); + +} + +void OSaxWriterTest::testExceptions( const Reference< XExtendedDocumentHandler > & r ) +{ + + OFileWriter *pw = new OFileWriter("output2.xml"); + AttributeListImpl *pList = new AttributeListImpl; + + Reference< XAttributeList > rList( (XAttributeList *) pList , UNO_QUERY ); + Reference< XOutputStream > ref( ( XOutputStream * ) pw , UNO_QUERY ); + + Reference< XActiveDataSource > source( r , UNO_QUERY ); + + ERROR_ASSERT( ref.is() , "no output stream" ); + ERROR_ASSERT( source.is() , "no active data source" ); + + source->setOutputStream( ref ); + + { // startDocument must be called before start element + sal_Bool bException = sal_True; + try + { + r->startElement( OUString( "huhu") , rList ); + bException = sal_False; + } + catch( SAXException &e ) + { + + } + ERROR_ASSERT( bException , "expected exception not thrown !" ); + } + + r->startDocument(); + + r->startElement( OUString( "huhu") , rList ); + r->startCDATA(); + + { + sal_Bool bException = sal_True; + try{ + r->startElement( OUString( "huhu") , rList ); + bException = sal_False; + } + catch( SAXException &e ) { + + } + ERROR_ASSERT( bException , "expected exception not thrown !" ); + } + + r->endCDATA(); + + { + sal_Unicode array[] = { 'a' , 'b' , 4 , 9 , 10 }; + OUString o( array , 5 ); + try + { + r->characters( o ); + ERROR_ASSERT( 0 , "Writer allowed to write forbidden characters" ); + } + catch( SAXException & e ) + { + + } + } + r->endElement( OUString( "huhu") ); + + r->endDocument(); +} + + +void OSaxWriterTest::testDTD(const Reference< XExtendedDocumentHandler > &r ) +{ + OFileWriter *pw = new OFileWriter("outputDTD.xml"); + AttributeListImpl *pList = new AttributeListImpl; + + Reference< XAttributeList > rList( (XAttributeList *) pList , UNO_QUERY ); + Reference< XOutputStream > ref( ( XOutputStream * ) pw , UNO_QUERY ); + + Reference< XActiveDataSource > source( r , UNO_QUERY ); + + ERROR_ASSERT( ref.is() , "no output stream" ); + ERROR_ASSERT( source.is() , "no active data source" ); + + source->setOutputStream( ref ); + + + r->startDocument(); + r->unknown( OUString( "\n") ); + r->startElement( OUString( "huhu") , rList ); + + r->endElement( OUString( "huhu") ); + r->endDocument(); +} + +void OSaxWriterTest::testPerformance(const Reference< XExtendedDocumentHandler > &r ) +{ + OFileWriter *pw = new OFileWriter("testPerformance.xml"); + AttributeListImpl *pList = new AttributeListImpl; + + OUString testParagraph = + OUString( + "This is a stupid test to check whether the SAXWriter possibly makes " + "line breaks halfway correctly or whether it writes the line to the " + "bitter end." ); + + + Reference< XAttributeList > rList( (XAttributeList *) pList , UNO_QUERY ); + Reference< XOutputStream > ref( ( XOutputStream * ) pw , UNO_QUERY ); + + Reference< XActiveDataSource > source( r , UNO_QUERY ); + + ERROR_ASSERT( ref.is() , "no output stream" ); + ERROR_ASSERT( source.is() , "no active data source" ); + + source->setOutputStream( ref ); + + TimeValue aStartTime, aEndTime; + osl_getSystemTime( &aStartTime ); + + + r->startDocument(); + // just write a bunch of xml tags ! + // for performance testing + sal_Int32 i2; + OUString huhu( "huhu" ); + const int ITERATIONS = 125; + for( i2 = 0 ; i2 < ITERATIONS ; i2 ++ ) + { + r->startElement( OUString( "tag" ) + + OUString::valueOf( i2 ), rList ); + for( sal_Int32 i = 0 ; i < 450 ; i ++ ) + { + r->ignorableWhitespace( "" ); + r->startElement( huhu , rList ); + r->characters( testParagraph ); + + r->ignorableWhitespace( "" ); + r->endElement( huhu ); + } + } + for( i2 = ITERATIONS-1 ; i2 >= 0 ; i2-- ) + { + r->ignorableWhitespace( "" ); + r->endElement( OUString( "tag" ) + OUString::valueOf( i2 ) ); + } + + r->endDocument(); + + osl_getSystemTime( &aEndTime ); + + double fStart = (double)aStartTime.Seconds + ((double)aStartTime.Nanosec / 1000000000.0); + double fEnd = (double)aEndTime.Seconds + ((double)aEndTime.Nanosec / 1000000000.0); + + printf( "Performance writing : %g s\n" , fEnd - fStart ); +} +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sax/test/saxdemo.cxx b/sax/test/saxdemo.cxx new file mode 100644 index 000000000..7139d60ef --- /dev/null +++ b/sax/test/saxdemo.cxx @@ -0,0 +1,626 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + + +// testcomponent - Loads a service and its testcomponent from dlls performs a test. +// Expands the dll-names depending on the actual environment. +// Example : testcomponent com.sun.star.io.Pipe stm + +// Therefore the testcode must exist in teststm and the testservice must be named test.com.sun.star.uno.io.Pipe + + +#include +#include +#include + +#include +#include + +#include +#include +#include + +#include +#include + +#include +#include + + +using namespace ::std; +using namespace ::cppu; +using namespace ::com::sun::star::uno; +using namespace ::com::sun::star::lang; +using namespace ::com::sun::star::registry; +using namespace ::com::sun::star::xml::sax; +using namespace ::com::sun::star::io; + + +/************ + * Sequence of bytes -> InputStream + ************/ +class OInputStream : public WeakImplHelper < XInputStream > +{ +public: + explicit OInputStream( const Sequence< sal_Int8 >&seq ) : + m_seq( seq ), + nPos( 0 ) + {} + +public: + virtual sal_Int32 SAL_CALL readBytes( Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead ) + throw(NotConnectedException, BufferSizeExceededException, IOException, RuntimeException) + { + nBytesToRead = (nBytesToRead > m_seq.getLength() - nPos ) ? + m_seq.getLength() - nPos : + nBytesToRead; + aData = Sequence< sal_Int8 > ( &(m_seq.getConstArray()[nPos]) , nBytesToRead ); + nPos += nBytesToRead; + return nBytesToRead; + } + virtual sal_Int32 SAL_CALL readSomeBytes( + css::uno::Sequence< sal_Int8 >& aData, + sal_Int32 nMaxBytesToRead ) + throw(NotConnectedException, BufferSizeExceededException, IOException, RuntimeException) + { + return readBytes( aData, nMaxBytesToRead ); + } + virtual void SAL_CALL skipBytes( sal_Int32 /* nBytesToSkip */ ) + throw(NotConnectedException, BufferSizeExceededException, IOException, RuntimeException) + { + // not implemented + } + virtual sal_Int32 SAL_CALL available( ) + throw(NotConnectedException, IOException, RuntimeException) + { + return m_seq.getLength() - nPos; + } + virtual void SAL_CALL closeInput( ) + throw(NotConnectedException, IOException, RuntimeException) + { + // not needed + } + Sequence< sal_Int8> m_seq; + sal_Int32 nPos; +}; + + +// Helper : create an input stream from a file + +Reference< XInputStream > createStreamFromFile( + const char *pcFile ) +{ + FILE *f = fopen( pcFile , "rb" ); + Reference< XInputStream > r; + + if( f ) { + fseek( f , 0 , SEEK_END ); + int nLength = ftell( f ); + fseek( f , 0 , SEEK_SET ); + + Sequence seqIn(nLength); + fread( seqIn.getArray() , nLength , 1 , f ); + + r.set( new OInputStream( seqIn ) ); + fclose( f ); + } + return r; +} + + +// The document handler, which is needed for the saxparser +// The Documenthandler for reading sax + +class TestDocumentHandler : + public WeakImplHelper< XExtendedDocumentHandler , XEntityResolver , XErrorHandler > +{ +public: + TestDocumentHandler( ) + { + } + +public: // Error handler + virtual void SAL_CALL error(const Any& aSAXParseException) throw (SAXException, RuntimeException) + { + printf( "Error !\n" ); + throw SAXException( + OUString( "error from error handler") , + Reference < XInterface >() , + aSAXParseException ); + } + virtual void SAL_CALL fatalError(const Any& /* aSAXParseException */) throw (SAXException, RuntimeException) + { + printf( "Fatal Error !\n" ); + } + virtual void SAL_CALL warning(const Any& /* aSAXParseException */) throw (SAXException, RuntimeException) + { + printf( "Warning !\n" ); + } + + +public: // ExtendedDocumentHandler + + virtual void SAL_CALL startDocument() throw (SAXException, RuntimeException) + { + m_iElementCount = 0; + m_iAttributeCount = 0; + m_iWhitespaceCount =0; + m_iCharCount=0; + printf( "document started\n" ); + } + virtual void SAL_CALL endDocument() throw (SAXException, RuntimeException) + { + printf( "document finished\n" ); + printf( "(ElementCount %d),(AttributeCount %d),(WhitespaceCount %d),(CharCount %d)\n", + m_iElementCount, m_iAttributeCount, m_iWhitespaceCount , m_iCharCount ); + + } + virtual void SAL_CALL startElement(const OUString& /* aName */, + const Reference< XAttributeList > & xAttribs) + throw (SAXException,RuntimeException) + { + m_iElementCount ++; + m_iAttributeCount += xAttribs->getLength(); + } + + virtual void SAL_CALL endElement(const OUString& /* aName */) throw (SAXException,RuntimeException) + { + // ignored + } + + virtual void SAL_CALL characters(const OUString& aChars) throw (SAXException,RuntimeException) + { + m_iCharCount += aChars.getLength(); + } + virtual void SAL_CALL ignorableWhitespace(const OUString& aWhitespaces) throw (SAXException,RuntimeException) + { + m_iWhitespaceCount += aWhitespaces.getLength(); + } + + virtual void SAL_CALL processingInstruction(const OUString& /* aTarget */, const OUString& /* aData */) throw (SAXException,RuntimeException) + { + // ignored + } + + virtual void SAL_CALL setDocumentLocator(const Reference< XLocator> & /* xLocator */) + throw (SAXException,RuntimeException) + { + // ignored + } + + virtual InputSource SAL_CALL resolveEntity( + const OUString& sPublicId, + const OUString& sSystemId) + throw (RuntimeException) + { + InputSource source; + source.sSystemId = sSystemId; + source.sPublicId = sPublicId; + + source.aInputStream = createStreamFromFile( + OUStringToOString( sSystemId, RTL_TEXTENCODING_ASCII_US).getStr() ); + + return source; + } + + virtual void SAL_CALL startCDATA() throw (SAXException,RuntimeException) + { + } + virtual void SAL_CALL endCDATA() throw (SAXException,RuntimeException) + { + } + virtual void SAL_CALL comment(const OUString& /* sComment */) throw (SAXException,RuntimeException) + { + } + virtual void SAL_CALL unknown(const OUString& /* sString */) throw (SAXException,RuntimeException) + { + } + + virtual void SAL_CALL allowLineBreak() throw (SAXException, RuntimeException ) + { + + } + +public: + int m_iElementCount; + int m_iAttributeCount; + int m_iWhitespaceCount; + int m_iCharCount; +}; + + +// helper implementation for writing +// implements an XAttributeList + +struct AttributeListImpl_impl; +class AttributeListImpl : public WeakImplHelper< XAttributeList > +{ +public: + AttributeListImpl(); + AttributeListImpl( const AttributeListImpl & ); + ~AttributeListImpl(); + +public: + virtual sal_Int16 SAL_CALL getLength() throw (RuntimeException); + virtual OUString SAL_CALL getNameByIndex(sal_Int16 i) throw (RuntimeException); + virtual OUString SAL_CALL getTypeByIndex(sal_Int16 i) throw (RuntimeException); + virtual OUString SAL_CALL getTypeByName(const OUString& aName) throw (RuntimeException); + virtual OUString SAL_CALL getValueByIndex(sal_Int16 i) throw (RuntimeException); + virtual OUString SAL_CALL getValueByName(const OUString& aName) throw (RuntimeException); + +public: + void addAttribute( const OUString &sName , + const OUString &sType , + const OUString &sValue ); + void clear(); + +private: + struct AttributeListImpl_impl *m_pImpl; +}; + + +struct TagAttribute +{ + TagAttribute(){} + TagAttribute( const OUString &s_Name, + const OUString &s_Type , + const OUString &s_Value ) + : sName(s_Name), + sType(s_Type), + sValue(s_Value) + { + } + + OUString sName; + OUString sType; + OUString sValue; +}; + +struct AttributeListImpl_impl +{ + AttributeListImpl_impl() + { + // performance improvement during adding + vecAttribute.reserve(20); + } + vector vecAttribute; +}; + + +sal_Int16 AttributeListImpl::getLength() throw (RuntimeException) +{ + return (sal_Int16) m_pImpl->vecAttribute.size(); +} + + +AttributeListImpl::AttributeListImpl( const AttributeListImpl &r ) +{ + m_pImpl = new AttributeListImpl_impl; + *m_pImpl = *(r.m_pImpl); +} + +OUString AttributeListImpl::getNameByIndex(sal_Int16 i) throw (RuntimeException) +{ + if( i < sal::static_int_cast(m_pImpl->vecAttribute.size()) ) { + return m_pImpl->vecAttribute[i].sName; + } + return OUString(); +} + + +OUString AttributeListImpl::getTypeByIndex(sal_Int16 i) throw (RuntimeException) +{ + if( i < sal::static_int_cast(m_pImpl->vecAttribute.size()) ) { + return m_pImpl->vecAttribute[i].sType; + } + return OUString(); +} + +OUString AttributeListImpl::getValueByIndex(sal_Int16 i) throw (RuntimeException) +{ + if( i < sal::static_int_cast(m_pImpl->vecAttribute.size()) ) { + return m_pImpl->vecAttribute[i].sValue; + } + return OUString(); + +} + +OUString AttributeListImpl::getTypeByName( const OUString& sName ) throw (RuntimeException) +{ + auto ii = std::find_if(m_pImpl->vecAttribute.begin(), m_pImpl->vecAttribute.end(), + [&sName](const struct TagAttribute& rAttr) { return rAttr.sName == sName; }); + if (ii != m_pImpl->vecAttribute.end()) + return (*ii).sType; + return OUString(); +} + +OUString AttributeListImpl::getValueByName(const OUString& sName) throw (RuntimeException) +{ + auto ii = std::find_if(m_pImpl->vecAttribute.begin(), m_pImpl->vecAttribute.end(), + [&sName](const struct TagAttribute& rAttr) { return rAttr.sName == sName; }); + if (ii != m_pImpl->vecAttribute.end()) + return (*ii).sValue; + return OUString(); +} + + +AttributeListImpl::AttributeListImpl() +{ + m_pImpl = new AttributeListImpl_impl; +} + + +AttributeListImpl::~AttributeListImpl() +{ + delete m_pImpl; +} + + +void AttributeListImpl::addAttribute( const OUString &sName , + const OUString &sType , + const OUString &sValue ) +{ + m_pImpl->vecAttribute.push_back( TagAttribute( sName , sType , sValue ) ); +} + +void AttributeListImpl::clear() +{ + m_pImpl->vecAttribute.clear(); +} + + +// helper function for writing +// ensures that linebreaks are inserted +// when writing a long text. +// Note: this implementation may be a bit slow, +// but it shows, how the SAX-Writer handles the allowLineBreak calls. + +void writeParagraphHelper( + const Reference< XExtendedDocumentHandler > &r , + const OUString & s) +{ + int nMax = s.getLength(); + int nStart = 0; + int n = 1; + + Sequence seq( s.getLength() ); + memcpy( seq.getArray() , s.getStr() , s.getLength() * sizeof( sal_uInt16 ) ); + + for( n = 1 ; n < nMax ; n++ ){ + if( 32 == seq.getArray()[n] ) { + r->allowLineBreak(); + r->characters( s.copy( nStart , n - nStart ) ); + nStart = n; + } + } + r->allowLineBreak(); + r->characters( s.copy( nStart , n - nStart ) ); +} + + +// helper implementation for SAX-Writer +// writes data to a file + +class OFileWriter : + public WeakImplHelper< XOutputStream > +{ +public: + explicit OFileWriter( char *pcFile ) { strncpy( m_pcFile , pcFile, 256 - 1 ); m_f = 0; } + + +public: + virtual void SAL_CALL writeBytes(const Sequence< sal_Int8 >& aData) + throw (NotConnectedException, BufferSizeExceededException, RuntimeException); + virtual void SAL_CALL flush() + throw (NotConnectedException, BufferSizeExceededException, RuntimeException); + virtual void SAL_CALL closeOutput() + throw (NotConnectedException, BufferSizeExceededException, RuntimeException); +private: + char m_pcFile[256]; + FILE *m_f; +}; + + +void OFileWriter::writeBytes(const Sequence< sal_Int8 >& aData) + throw (NotConnectedException, BufferSizeExceededException, RuntimeException) +{ + if( ! m_f ) { + m_f = fopen( m_pcFile , "w" ); + } + + fwrite( aData.getConstArray() , 1 , aData.getLength() , m_f ); +} + + +void OFileWriter::flush() + throw (NotConnectedException, BufferSizeExceededException, RuntimeException) +{ + fflush( m_f ); +} + +void OFileWriter::closeOutput() + throw (NotConnectedException, BufferSizeExceededException, RuntimeException) +{ + fclose( m_f ); + m_f = 0; +} + + +// Needed to switch on solaris threads +#ifdef __sun +extern "C" void ChangeGlobalInit(); +#endif +int main (int argc, char **argv) +{ + + if( argc < 3) { + printf( "usage : saxdemo inputfile outputfile\n" ); + exit( 0 ); + } +#ifdef __sun + // switch on threads in solaris + ChangeGlobalInit(); +#endif + + // create service manager + Reference< XMultiServiceFactory > xSMgr = createRegistryServiceFactory( + OUString( "applicat.rdb" ) ); + + Reference < XImplementationRegistration > xReg; + try + { + // Create registration service + Reference < XInterface > x = xSMgr->createInstance( "com.sun.star.registry.ImplementationRegistration" ); + xReg.set( x , UNO_QUERY ); + } + catch( Exception & ) { + printf( "Couldn't create ImplementationRegistration service\n" ); + exit(1); + } + + OString sTestName; + try + { + // Load dll for the tested component + OUString aDllName( "sax.uno" SAL_DLLEXTENSION ); + xReg->registerImplementation( + OUString("com.sun.star.loader.SharedLibrary"), + aDllName, + Reference< XSimpleRegistry > () ); + } + catch( Exception &e ) { + printf( "Couldn't reach sax dll\n" ); + printf( "%s\n" , OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US ).getStr() ); + + exit(1); + } + + + // parser demo + // read xml from a file and count elements + + Reference< XInterface > x = xSMgr->createInstance( "com.sun.star.xml.sax.Parser" ); + if( x.is() ) + { + Reference< XParser > rParser( x , UNO_QUERY ); + + // create and connect the document handler to the parser + TestDocumentHandler *pDocHandler = new TestDocumentHandler( ); + + Reference < XDocumentHandler > rDocHandler( (XDocumentHandler *) pDocHandler ); + Reference< XEntityResolver > rEntityResolver( (XEntityResolver *) pDocHandler ); + + rParser->setDocumentHandler( rDocHandler ); + rParser->setEntityResolver( rEntityResolver ); + + // create the input stream + InputSource source; + source.aInputStream = createStreamFromFile( argv[1] ); + source.sSystemId = OUString::createFromAscii( argv[1] ); + + try + { + // start parsing + rParser->parseStream( source ); + } + + catch( Exception & e ) + { + OString o1 = OUStringToOString(e.Message, RTL_TEXTENCODING_UTF8 ); + printf( "Exception during parsing : %s\n" , o1.getStr() ); + } + } + else + { + printf( "couldn't create sax-parser component\n" ); + } + + + // The SAX-Writer demo + + x= xSMgr->createInstance("com.sun.star.xml.sax.Writer"); + if( x.is() ) + { + printf( "start writing to %s\n" , argv[2] ); + + OFileWriter *pw = new OFileWriter( argv[2] ); + Reference< XActiveDataSource > source( x , UNO_QUERY ); + source->setOutputStream( Reference< XOutputStream> ( (XOutputStream*) pw ) ); + + AttributeListImpl *pList = new AttributeListImpl; + Reference< XAttributeList > rList( (XAttributeList *) pList ); + + Reference< XExtendedDocumentHandler > r( x , UNO_QUERY ); + r->startDocument(); + + pList->addAttribute( OUString( "Arg1" ), + OUString( "CDATA") , + OUString( "foo\n u") ); + pList->addAttribute( OUString( "Arg2") , + OUString( "CDATA") , + OUString( "foo2") ); + + r->startElement( OUString( "tag1") , rList ); + // tells the writer to insert a linefeed + r->ignorableWhitespace( OUString() ); + + r->characters( OUString( "huhu") ); + r->ignorableWhitespace( OUString() ); + + r->startElement( OUString( "hi") , rList ); + r->ignorableWhitespace( OUString() ); + + // the enpassant must be converted & -> & + r->characters( OUString( "ü") ); + r->ignorableWhitespace( OUString() ); + + // '>' must not be converted + r->startCDATA(); + r->characters( OUString( " > foo < ") ); + r->endCDATA(); + r->ignorableWhitespace( OUString() ); + + OUString testParagraph = OUString( + "This is only a test to check, if the writer inserts line feeds " + "if needed or if the writer puts the whole text into one line." ); + writeParagraphHelper( r , testParagraph ); + + r->ignorableWhitespace( OUString() ); + r->comment( OUString( "This is a comment !") ); + r->ignorableWhitespace( OUString() ); + + r->startElement( OUString( "emptytagtest") , rList ); + r->endElement( OUString( "emptytagtest") ); + r->ignorableWhitespace( OUString() ); + + r->endElement( OUString( "hi") ); + r->ignorableWhitespace( OUString() ); + + r->endElement( OUString( "tag1") ); + r->endDocument(); + + printf( "finished writing\n" ); + } + else + { + printf( "couldn't create sax-writer component\n" ); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sax/test/testcomponent.cxx b/sax/test/testcomponent.cxx new file mode 100644 index 000000000..51f8f244e --- /dev/null +++ b/sax/test/testcomponent.cxx @@ -0,0 +1,223 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + + +// testcomponent - Loads a service and its testcomponent from dlls performs a test. +// Expands the dll-names depending on the actual environment. +// Example : testcomponent com.sun.star.io.Pipe stm + +// Therefore the testcode must exist in teststm and the testservice must be named com.sun.star.io.Pipe + + +#include +#include +#include + +#include + +#include + + +using namespace ::cppu; +using namespace ::com::sun::star::uno; +using namespace ::com::sun::star::test; +using namespace ::com::sun::star::lang; +using namespace ::com::sun::star::registry; + +// Needed to switch on solaris threads +#ifdef __sun +extern "C" void ChangeGlobalInit(); +#endif + +int main (int argc, char **argv) +{ + + if( argc < 3) { + printf( "usage : testcomponent service dll [additional dlls]\n" ); + exit( 0 ); + } +#ifdef __sun + // switch on threads in solaris + ChangeGlobalInit(); +#endif + + // create service manager + Reference< XMultiServiceFactory > xSMgr = + createRegistryServiceFactory( OUString( "applicat.rdb") ); + + Reference < XImplementationRegistration > xReg; + Reference < XSimpleRegistry > xSimpleReg; + + try + { + // Create registration service + Reference < XInterface > x = xSMgr->createInstance( "com.sun.star.registry.ImplementationRegistration" ); + xReg.set( x , UNO_QUERY ); + } + catch (const Exception&) + { + printf( "Couldn't create ImplementationRegistration service\n" ); + exit(1); + } + + char szBuf[1024]; + OString sTestName; + + try + { + // Load dll for the tested component + for( int n = 2 ; n registerImplementation( + OUString("com.sun.star.loader.SharedLibrary"), + aDllName, + xSimpleReg ); + } + } + catch (const Exception &e) + { + printf( "Couldn't reach dll %s\n" , szBuf ); + printf( "%s\n" , OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US ).getStr() ); + + exit(1); + } + + + try + { + // Load dll for the test component + sTestName = "test"; + sTestName += argv[2]; + +#ifdef _WIN32 + OUString aDllName = OStringToOUString( sTestName , RTL_TEXTENCODING_ASCII_US ); +#else + OUString aDllName = "lib"; + aDllName += OStringToOUString( sTestName , RTL_TEXTENCODING_ASCII_US ); + aDllName += ".so"; +#endif + + xReg->registerImplementation( + OUString("com.sun.star.loader.SharedLibrary") , + aDllName, + xSimpleReg ); + } + catch (const Exception&) + { + printf( "Couldn't reach dll %s\n" , szBuf ); + exit(1); + } + + + // Instantiate test service + sTestName = "test."; + sTestName += argv[1]; + + Reference < XInterface > xIntTest = + xSMgr->createInstance( OStringToOUString( sTestName , RTL_TEXTENCODING_ASCII_US ) ); + Reference< XSimpleTest > xTest( xIntTest , UNO_QUERY ); + + if( ! xTest.is() ) { + printf( "Couldn't instantiate test service \n" ); + exit( 1 ); + } + + + sal_Int32 nHandle = 0; + sal_Int32 nNewHandle; + sal_Int32 nErrorCount = 0; + sal_Int32 nWarningCount = 0; + + // loop until all test are performed + while( nHandle != -1 ) + { + // Instantiate service + Reference< XInterface > x = + xSMgr->createInstance( OStringToOUString( argv[1] , RTL_TEXTENCODING_ASCII_US ) ); + if( ! x.is() ) + { + printf( "Couldn't instantiate service !\n" ); + exit( 1 ); + } + + // do the test + try + { + nNewHandle = xTest->test( + OStringToOUString( argv[1] , RTL_TEXTENCODING_ASCII_US ) , x , nHandle ); + } + catch (const Exception &e) + { + OString o = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US ); + printf( "testcomponent : uncaught exception %s\n" , o.getStr() ); + exit(1); + } + catch (...) + { + printf( "testcomponent : uncaught unknown exception\n" ); + exit(1); + } + + + // print errors and warning + Sequence seqErrors = xTest->getErrors(); + Sequence seqWarnings = xTest->getWarnings(); + if( seqWarnings.getLength() > nWarningCount ) + { + printf( "Warnings during test %" SAL_PRIxUINT32 "!\n" , nHandle ); + for( ; nWarningCount < seqWarnings.getLength() ; nWarningCount ++ ) + { + OString o = OUStringToOString( + seqWarnings.getArray()[nWarningCount], RTL_TEXTENCODING_ASCII_US ); + printf( "Warning\n%s\n---------\n" , o.getStr() ); + } + } + + + if( seqErrors.getLength() > nErrorCount ) { + printf( "Errors during test %" SAL_PRIxUINT32 "!\n" , nHandle ); + for( ; nErrorCount < seqErrors.getLength() ; nErrorCount ++ ) { + OString o = OUStringToOString( + seqErrors.getArray()[nErrorCount], RTL_TEXTENCODING_ASCII_US ); + printf( "%s\n" , o.getStr() ); + } + } + + nHandle = nNewHandle; + } + + if( xTest->testPassed() ) { + printf( "Test passed !\n" ); + } + else { + printf( "Test failed !\n" ); + } + + Reference rComp( xSMgr , UNO_QUERY ); + rComp->dispose(); + return 0; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ -- cgit v1.2.3