From eae0f9957cfa836be89590557cf74f6cd9a19152 Mon Sep 17 00:00:00 2001 From: mateng0915 Date: Wed, 11 Jan 2023 16:25:24 +0800 Subject: [PATCH 01/75] Feature: Optimize the replica delay api logic Description: ============ Currently if in the Whole CK instance has one table is read only status then the API /replicas_status will throw error, xxx table is read only For make this monitor can work in prod env, we can catch the read only status instead of directly throw error Solution: ========= Return other normal table's delay value even if the CK instance has readonly Replicatedxxx table Please enter the commit message for your changes. Lines starting --- src/Server/ReplicasStatusHandler.cpp | 20 ++++++++++++++------ src/Storages/StorageReplicatedMergeTree.h | 2 ++ 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/src/Server/ReplicasStatusHandler.cpp b/src/Server/ReplicasStatusHandler.cpp index 4818362c939..a31a368e83d 100644 --- a/src/Server/ReplicasStatusHandler.cpp +++ b/src/Server/ReplicasStatusHandler.cpp @@ -59,14 +59,22 @@ void ReplicasStatusHandler::handleRequest(HTTPServerRequest & request, HTTPServe time_t absolute_delay = 0; time_t relative_delay = 0; - table_replicated->getReplicaDelays(absolute_delay, relative_delay); + if(!table_replicated->isTableReadOnly()) + { + table_replicated->getReplicaDelays(absolute_delay, relative_delay); - if ((settings.min_absolute_delay_to_close && absolute_delay >= static_cast(settings.min_absolute_delay_to_close)) - || (settings.min_relative_delay_to_close && relative_delay >= static_cast(settings.min_relative_delay_to_close))) - ok = false; + if ((settings.min_absolute_delay_to_close && absolute_delay >= static_cast(settings.min_absolute_delay_to_close)) + || (settings.min_relative_delay_to_close && relative_delay >= static_cast(settings.min_relative_delay_to_close))) + ok = false; + + message << backQuoteIfNeed(db.first) << "." << backQuoteIfNeed(iterator->name()) + << ":\tAbsolute delay: " << absolute_delay << ". Relative delay: " << relative_delay << ".\n"; + + } else { + message << backQuoteIfNeed(db.first) << "." << backQuoteIfNeed(iterator->name()) + << ":\tis readonly. \n"; + } - message << backQuoteIfNeed(db.first) << "." << backQuoteIfNeed(iterator->name()) - << ":\tAbsolute delay: " << absolute_delay << ". Relative delay: " << relative_delay << ".\n"; } } diff --git a/src/Storages/StorageReplicatedMergeTree.h b/src/Storages/StorageReplicatedMergeTree.h index 218b9d0e31a..8fd6d46c6d3 100644 --- a/src/Storages/StorageReplicatedMergeTree.h +++ b/src/Storages/StorageReplicatedMergeTree.h @@ -322,6 +322,8 @@ public: const String & replica_name, const String & zookeeper_path, const ContextPtr & local_context, const zkutil::ZooKeeperPtr & zookeeper); bool canUseZeroCopyReplication() const; + + bool isTableReadOnly () { return is_readonly; } private: std::atomic_bool are_restoring_replica {false}; From 19d26828a002993d188e8489fa193a573707ea22 Mon Sep 17 00:00:00 2001 From: Suzy Wang Date: Fri, 20 Jan 2023 21:16:55 +0000 Subject: [PATCH 02/75] s390x build support --- CMakeLists.txt | 8 +- PreLoad.cmake | 10 +- base/base/defines.h | 2 +- cmake/arch.cmake | 4 + cmake/linux/toolchain-s390x.cmake | 25 + cmake/tools.cmake | 29 +- contrib/cityhash102/src/config.h | 2 +- contrib/openldap-cmake/CMakeLists.txt | 1 + .../linux_s390x/include/lber_types.h | 63 + .../linux_s390x/include/ldap_config.h | 74 ++ .../linux_s390x/include/ldap_features.h | 56 + .../linux_s390x/include/portable.h | 1169 +++++++++++++++++ src/Common/StackTrace.cpp | 2 + src/Common/ThreadFuzzer.cpp | 2 + src/Common/formatIPv6.cpp | 8 +- src/Common/waitForPid.cpp | 2 + src/Compression/CompressionFactory.cpp | 6 +- src/Compression/LZ4_decompress_faster.cpp | 4 +- src/Storages/StorageS3Cluster.cpp | 1 + src/Storages/checkAndGetLiteralArgument.cpp | 2 +- 20 files changed, 1439 insertions(+), 31 deletions(-) create mode 100644 cmake/linux/toolchain-s390x.cmake create mode 100644 contrib/openldap-cmake/linux_s390x/include/lber_types.h create mode 100644 contrib/openldap-cmake/linux_s390x/include/ldap_config.h create mode 100644 contrib/openldap-cmake/linux_s390x/include/ldap_features.h create mode 100644 contrib/openldap-cmake/linux_s390x/include/portable.h diff --git a/CMakeLists.txt b/CMakeLists.txt index ab976612401..485c64db0d9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -453,7 +453,7 @@ endif () set (CMAKE_POSTFIX_VARIABLE "CMAKE_${CMAKE_BUILD_TYPE_UC}_POSTFIX") set (CMAKE_POSITION_INDEPENDENT_CODE OFF) -if (OS_LINUX AND NOT ARCH_AARCH64) +if (OS_LINUX AND NOT ARCH_AARCH64 AND NOT ARCH_S390X) # Slightly more efficient code can be generated # It's disabled for ARM because otherwise ClickHouse cannot run on Android. set (CMAKE_CXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS_RELWITHDEBINFO} -fno-pie") @@ -471,7 +471,11 @@ enable_testing() # Enable for tests without binary option(ENABLE_OPENSSL "This option performs a build with OpenSSL. NOTE! This option is insecure and should never be used. By default, ClickHouse uses and only supports BoringSSL" OFF) -option(ENABLE_OPENSSL_DYNAMIC "This option removes SSL from ClickHouse and will link to the OpenSSL version supplied by OS." OFF) +if(ARCH_S390X) + option(ENABLE_OPENSSL_DYNAMIC "This option removes SSL from ClickHouse and will link to the OpenSSL version supplied by OS." ON) +else() + option(ENABLE_OPENSSL_DYNAMIC "This option removes SSL from ClickHouse and will link to the OpenSSL version supplied by OS." OFF) +endif() # when installing to /usr - place configs to /etc but for /usr/local place to /usr/local/etc if (CMAKE_INSTALL_PREFIX STREQUAL "/usr") diff --git a/PreLoad.cmake b/PreLoad.cmake index b11ab080430..a016fee8e68 100644 --- a/PreLoad.cmake +++ b/PreLoad.cmake @@ -58,10 +58,9 @@ execute_process(COMMAND uname -m OUTPUT_VARIABLE ARCH) # By default, prefer clang on Linux # But note, that you still may change the compiler with -DCMAKE_C_COMPILER/-DCMAKE_CXX_COMPILER. if (OS MATCHES "Linux" + # some build systems may use CC/CXX env variables AND "$ENV{CC}" STREQUAL "" - AND "$ENV{CXX}" STREQUAL "" - AND NOT DEFINED CMAKE_C_COMPILER - AND NOT DEFINED CMAKE_CXX_COMPILER) + AND "$ENV{CXX}" STREQUAL "") find_program(CLANG_PATH clang) if (CLANG_PATH) set(CMAKE_C_COMPILER "clang" CACHE INTERNAL "") @@ -84,7 +83,10 @@ if (OS MATCHES "Linux" set (CMAKE_TOOLCHAIN_FILE "cmake/linux/toolchain-aarch64.cmake" CACHE INTERNAL "") elseif (ARCH MATCHES "^(ppc64le.*|PPC64LE.*)") set (CMAKE_TOOLCHAIN_FILE "cmake/linux/toolchain-ppc64le.cmake" CACHE INTERNAL "") - else () + elseif (ARCH MATCHES "^(s390x.*|S390X.*)") + set (CMAKE_TOOLCHAIN_FILE "cmake/linux/toolchain-s390x.cmake" CACHE INTERNAL "") +else () message (FATAL_ERROR "Unsupported architecture: ${ARCH}") endif () + endif() diff --git a/base/base/defines.h b/base/base/defines.h index 391e97ab406..b9f58b072df 100644 --- a/base/base/defines.h +++ b/base/base/defines.h @@ -28,7 +28,7 @@ #define NO_INLINE __attribute__((__noinline__)) #define MAY_ALIAS __attribute__((__may_alias__)) -#if !defined(__x86_64__) && !defined(__aarch64__) && !defined(__PPC__) && !(defined(__riscv) && (__riscv_xlen == 64)) +#if !defined(__x86_64__) && !defined(__aarch64__) && !defined(__PPC__) && !defined(__s390x__) && !(defined(__riscv) && (__riscv_xlen == 64)) # error "The only supported platforms are x86_64 and AArch64, PowerPC (work in progress) and RISC-V 64 (experimental)" #endif diff --git a/cmake/arch.cmake b/cmake/arch.cmake index d8a633ab170..fcb29fc4814 100644 --- a/cmake/arch.cmake +++ b/cmake/arch.cmake @@ -7,8 +7,12 @@ elseif (CMAKE_SYSTEM_PROCESSOR MATCHES "^(aarch64.*|AARCH64.*|arm64.*|ARM64.*)") set (ARCH_AARCH64 1) elseif (CMAKE_SYSTEM_PROCESSOR MATCHES "^(powerpc64le.*|ppc64le.*|PPC64LE.*)") set (ARCH_PPC64LE 1) +elseif (CMAKE_SYSTEM_PROCESSOR MATCHES "^(s390x.*|S390X.*)") + set (ARCH_S390X 1) elseif (CMAKE_SYSTEM_PROCESSOR MATCHES "riscv64") set (ARCH_RISCV64 1) +elseif (CMAKE_SYSTEM_PROCESSOR MATCHES "^(s390x.*|S390X.*)") + set (ARCH_S390X 1) else () message (FATAL_ERROR "Platform ${CMAKE_SYSTEM_PROCESSOR} is not supported") endif () diff --git a/cmake/linux/toolchain-s390x.cmake b/cmake/linux/toolchain-s390x.cmake new file mode 100644 index 00000000000..b09c3301730 --- /dev/null +++ b/cmake/linux/toolchain-s390x.cmake @@ -0,0 +1,25 @@ +set (CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY) + +set (CMAKE_SYSTEM_NAME "Linux") +set (CMAKE_SYSTEM_PROCESSOR "s390x") +set (CMAKE_C_COMPILER_TARGET "s390x-linux-gnu") +set (CMAKE_CXX_COMPILER_TARGET "s390x-linux-gnu") +set (CMAKE_ASM_COMPILER_TARGET "s390x-linux-gnu") + +# Will be changed later, but somehow needed to be set here. +set (CMAKE_AR "ar") +set (CMAKE_RANLIB "ranlib") + +set (TOOLCHAIN_PATH "${CMAKE_CURRENT_LIST_DIR}/../../contrib/sysroot/linux-s390x") + +set (CMAKE_SYSROOT "${TOOLCHAIN_PATH}/s390x-linux-gnu/libc") + +set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} --gcc-toolchain=${TOOLCHAIN_PATH}") +set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --gcc-toolchain=${TOOLCHAIN_PATH}") +set (CMAKE_ASM_FLAGS "${CMAKE_ASM_FLAGS} --gcc-toolchain=${TOOLCHAIN_PATH}") + +set (HAS_PRE_1970_EXITCODE "0" CACHE STRING "Result from TRY_RUN" FORCE) +set (HAS_PRE_1970_EXITCODE__TRYRUN_OUTPUT "" CACHE STRING "Output from TRY_RUN" FORCE) + +set (HAS_POST_2038_EXITCODE "0" CACHE STRING "Result from TRY_RUN" FORCE) +set (HAS_POST_2038_EXITCODE__TRYRUN_OUTPUT "" CACHE STRING "Output from TRY_RUN" FORCE) diff --git a/cmake/tools.cmake b/cmake/tools.cmake index 3ddf8a869be..84376d13d9b 100644 --- a/cmake/tools.cmake +++ b/cmake/tools.cmake @@ -53,20 +53,23 @@ list (GET COMPILER_VERSION_LIST 0 COMPILER_VERSION_MAJOR) # Example values: `lld-10`, `gold`. option (LINKER_NAME "Linker name or full path") -if (NOT LINKER_NAME) - if (COMPILER_GCC) - find_program (LLD_PATH NAMES "ld.lld") - find_program (GOLD_PATH NAMES "ld.gold") - elseif (COMPILER_CLANG) - # llvm lld is a generic driver. - # Invoke ld.lld (Unix), ld64.lld (macOS), lld-link (Windows), wasm-ld (WebAssembly) instead - if (OS_LINUX) - find_program (LLD_PATH NAMES "ld.lld-${COMPILER_VERSION_MAJOR}" "ld.lld") - elseif (OS_DARWIN) - find_program (LLD_PATH NAMES "ld64.lld-${COMPILER_VERSION_MAJOR}" "ld64.lld") +# s390x doesnt support lld +if (NOT ARCH_S390X) + if (NOT LINKER_NAME) + if (COMPILER_GCC) + find_program (LLD_PATH NAMES "ld.lld") + find_program (GOLD_PATH NAMES "ld.gold") + elseif (COMPILER_CLANG) + # llvm lld is a generic driver. + # Invoke ld.lld (Unix), ld64.lld (macOS), lld-link (Windows), wasm-ld (WebAssembly) instead + if (OS_LINUX) + find_program (LLD_PATH NAMES "ld.lld-${COMPILER_VERSION_MAJOR}" "ld.lld") + elseif (OS_DARWIN) + find_program (LLD_PATH NAMES "ld64.lld-${COMPILER_VERSION_MAJOR}" "ld64.lld") + endif () + find_program (GOLD_PATH NAMES "ld.gold" "gold") endif () - find_program (GOLD_PATH NAMES "ld.gold" "gold") - endif () + endif() endif() if ((OS_LINUX OR OS_DARWIN) AND NOT LINKER_NAME) diff --git a/contrib/cityhash102/src/config.h b/contrib/cityhash102/src/config.h index cca744a35c0..4f5182e4072 100644 --- a/contrib/cityhash102/src/config.h +++ b/contrib/cityhash102/src/config.h @@ -68,7 +68,7 @@ /* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most significant byte first (like Motorola and SPARC, unlike Intel). */ -#if defined AC_APPLE_UNIVERSAL_BUILD +#if defined(AC_APPLE_UNIVERSAL_BUILD) || defined(__s390x__) # if defined __BIG_ENDIAN__ # define WORDS_BIGENDIAN 1 # endif diff --git a/contrib/openldap-cmake/CMakeLists.txt b/contrib/openldap-cmake/CMakeLists.txt index f5966474b0d..7af07d5f553 100644 --- a/contrib/openldap-cmake/CMakeLists.txt +++ b/contrib/openldap-cmake/CMakeLists.txt @@ -19,6 +19,7 @@ if (NOT( ( "${_system_name}" STREQUAL "linux" AND "${_system_processor}" STREQUAL "x86_64" ) OR ( "${_system_name}" STREQUAL "linux" AND "${_system_processor}" STREQUAL "aarch64" ) OR ( "${_system_name}" STREQUAL "linux" AND "${_system_processor}" STREQUAL "ppc64le" ) OR + ( "${_system_name}" STREQUAL "linux" AND "${_system_processor}" STREQUAL "s390x" ) OR ( "${_system_name}" STREQUAL "freebsd" AND "${_system_processor}" STREQUAL "x86_64" ) OR ( "${_system_name}" STREQUAL "freebsd" AND "${_system_processor}" STREQUAL "aarch64" ) OR ( "${_system_name}" STREQUAL "darwin" AND "${_system_processor}" STREQUAL "x86_64" ) OR diff --git a/contrib/openldap-cmake/linux_s390x/include/lber_types.h b/contrib/openldap-cmake/linux_s390x/include/lber_types.h new file mode 100644 index 00000000000..0e04ad96034 --- /dev/null +++ b/contrib/openldap-cmake/linux_s390x/include/lber_types.h @@ -0,0 +1,63 @@ +/* include/lber_types.h. Generated from lber_types.hin by configure. */ +/* $OpenLDAP$ */ +/* This work is part of OpenLDAP Software . + * + * Copyright 1998-2020 The OpenLDAP Foundation. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted only as authorized by the OpenLDAP + * Public License. + * + * A copy of this license is available in file LICENSE in the + * top-level directory of the distribution or, alternatively, at + * . + */ + +/* + * LBER types + */ + +#ifndef _LBER_TYPES_H +#define _LBER_TYPES_H + +#include + +LDAP_BEGIN_DECL + +/* LBER boolean, enum, integers (32 bits or larger) */ +#define LBER_INT_T int + +/* LBER tags (32 bits or larger) */ +#define LBER_TAG_T long + +/* LBER socket descriptor */ +#define LBER_SOCKET_T int + +/* LBER lengths (32 bits or larger) */ +#define LBER_LEN_T long + +/* ------------------------------------------------------------ */ + +/* booleans, enumerations, and integers */ +typedef LBER_INT_T ber_int_t; + +/* signed and unsigned versions */ +typedef signed LBER_INT_T ber_sint_t; +typedef unsigned LBER_INT_T ber_uint_t; + +/* tags */ +typedef unsigned LBER_TAG_T ber_tag_t; + +/* "socket" descriptors */ +typedef LBER_SOCKET_T ber_socket_t; + +/* lengths */ +typedef unsigned LBER_LEN_T ber_len_t; + +/* signed lengths */ +typedef signed LBER_LEN_T ber_slen_t; + +LDAP_END_DECL + +#endif /* _LBER_TYPES_H */ diff --git a/contrib/openldap-cmake/linux_s390x/include/ldap_config.h b/contrib/openldap-cmake/linux_s390x/include/ldap_config.h new file mode 100644 index 00000000000..5090a9fa705 --- /dev/null +++ b/contrib/openldap-cmake/linux_s390x/include/ldap_config.h @@ -0,0 +1,74 @@ +/* Generated from ./ldap_config.hin on Thu Mar 31 05:25:33 UTC 2022 */ +/* $OpenLDAP$ */ +/* This work is part of OpenLDAP Software . + * + * Copyright 1998-2020 The OpenLDAP Foundation. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted only as authorized by the OpenLDAP + * Public License. + * + * A copy of this license is available in file LICENSE in the + * top-level directory of the distribution or, alternatively, at + * . + */ + +/* + * This file works in conjunction with OpenLDAP configure system. + * If you do no like the values below, adjust your configure options. + */ + +#ifndef _LDAP_CONFIG_H +#define _LDAP_CONFIG_H + +/* directory separator */ +#ifndef LDAP_DIRSEP +#ifndef _WIN32 +#define LDAP_DIRSEP "/" +#else +#define LDAP_DIRSEP "\\" +#endif +#endif + +/* directory for temporary files */ +#if defined(_WIN32) +# define LDAP_TMPDIR "C:\\." /* we don't have much of a choice */ +#elif defined( _P_tmpdir ) +# define LDAP_TMPDIR _P_tmpdir +#elif defined( P_tmpdir ) +# define LDAP_TMPDIR P_tmpdir +#elif defined( _PATH_TMPDIR ) +# define LDAP_TMPDIR _PATH_TMPDIR +#else +# define LDAP_TMPDIR LDAP_DIRSEP "tmp" +#endif + +/* directories */ +#ifndef LDAP_BINDIR +#define LDAP_BINDIR "/usr/local/bin" +#endif +#ifndef LDAP_SBINDIR +#define LDAP_SBINDIR "/usr/local/sbin" +#endif +#ifndef LDAP_DATADIR +#define LDAP_DATADIR "/usr/local/share/openldap" +#endif +#ifndef LDAP_SYSCONFDIR +#define LDAP_SYSCONFDIR "/usr/local/etc/openldap" +#endif +#ifndef LDAP_LIBEXECDIR +#define LDAP_LIBEXECDIR "/usr/local/libexec" +#endif +#ifndef LDAP_MODULEDIR +#define LDAP_MODULEDIR "/usr/local/libexec/openldap" +#endif +#ifndef LDAP_RUNDIR +#define LDAP_RUNDIR "/usr/local/var" +#endif +#ifndef LDAP_LOCALEDIR +#define LDAP_LOCALEDIR "" +#endif + + +#endif /* _LDAP_CONFIG_H */ diff --git a/contrib/openldap-cmake/linux_s390x/include/ldap_features.h b/contrib/openldap-cmake/linux_s390x/include/ldap_features.h new file mode 100644 index 00000000000..b6909b00773 --- /dev/null +++ b/contrib/openldap-cmake/linux_s390x/include/ldap_features.h @@ -0,0 +1,56 @@ +/* include/ldap_features.h. Generated from ldap_features.hin by configure. */ +/* $OpenLDAP$ */ +/* This work is part of OpenLDAP Software . + * + * Copyright 1998-2020 The OpenLDAP Foundation. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted only as authorized by the OpenLDAP + * Public License. + * + * A copy of this license is available in file LICENSE in the + * top-level directory of the distribution or, alternatively, at + * . + */ + +/* + * LDAP Features + */ + +#ifndef _LDAP_FEATURES_H +#define _LDAP_FEATURES_H 1 + +/* OpenLDAP API version macros */ +#define LDAP_VENDOR_VERSION 000000 +#define LDAP_VENDOR_VERSION_MAJOR 2 +#define LDAP_VENDOR_VERSION_MINOR X +#define LDAP_VENDOR_VERSION_PATCH X + +/* +** WORK IN PROGRESS! +** +** OpenLDAP reentrancy/thread-safeness should be dynamically +** checked using ldap_get_option(). +** +** If built with thread support, the -lldap implementation is: +** LDAP_API_FEATURE_THREAD_SAFE (basic thread safety) +** LDAP_API_FEATURE_SESSION_THREAD_SAFE +** LDAP_API_FEATURE_OPERATION_THREAD_SAFE +** +** The preprocessor flag LDAP_API_FEATURE_X_OPENLDAP_THREAD_SAFE +** can be used to determine if -lldap is thread safe at compile +** time. +** +*/ + +/* is -lldap reentrant or not */ +#define LDAP_API_FEATURE_X_OPENLDAP_REENTRANT 1 + +/* is -lldap thread safe or not */ +#define LDAP_API_FEATURE_X_OPENLDAP_THREAD_SAFE 1 + +/* LDAP v2 Referrals */ +/* #undef LDAP_API_FEATURE_X_OPENLDAP_V2_REFERRALS */ + +#endif /* LDAP_FEATURES */ diff --git a/contrib/openldap-cmake/linux_s390x/include/portable.h b/contrib/openldap-cmake/linux_s390x/include/portable.h new file mode 100644 index 00000000000..9ad942719cd --- /dev/null +++ b/contrib/openldap-cmake/linux_s390x/include/portable.h @@ -0,0 +1,1169 @@ +/* include/portable.h. Generated from portable.hin by configure. */ +/* include/portable.hin. Generated from configure.in by autoheader. */ + + +/* begin of portable.h.pre */ +/* This work is part of OpenLDAP Software . + * + * Copyright 1998-2020 The OpenLDAP Foundation + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted only as authorized by the OpenLDAP + * Public License. + * + * A copy of this license is available in the file LICENSE in the + * top-level directory of the distribution or, alternatively, at + * . + */ + +#ifndef _LDAP_PORTABLE_H +#define _LDAP_PORTABLE_H + +/* define this if needed to get reentrant functions */ +#ifndef REENTRANT +#define REENTRANT 1 +#endif +#ifndef _REENTRANT +#define _REENTRANT 1 +#endif + +/* define this if needed to get threadsafe functions */ +#ifndef THREADSAFE +#define THREADSAFE 1 +#endif +#ifndef _THREADSAFE +#define _THREADSAFE 1 +#endif +#ifndef THREAD_SAFE +#define THREAD_SAFE 1 +#endif +#ifndef _THREAD_SAFE +#define _THREAD_SAFE 1 +#endif + +#ifndef _SGI_MP_SOURCE +#define _SGI_MP_SOURCE 1 +#endif + +/* end of portable.h.pre */ + + +/* Define if building universal (internal helper macro) */ +/* #undef AC_APPLE_UNIVERSAL_BUILD */ + +/* define to use both and */ +/* #undef BOTH_STRINGS_H */ + +/* define if cross compiling */ +/* #undef CROSS_COMPILING */ + +/* set to the number of arguments ctime_r() expects */ +#define CTIME_R_NARGS 2 + +/* define if toupper() requires islower() */ +/* #undef C_UPPER_LOWER */ + +/* define if sys_errlist is not declared in stdio.h or errno.h */ +/* #undef DECL_SYS_ERRLIST */ + +/* define to enable slapi library */ +/* #undef ENABLE_SLAPI */ + +/* defined to be the EXE extension */ +#define EXEEXT "" + +/* set to the number of arguments gethostbyaddr_r() expects */ +#define GETHOSTBYADDR_R_NARGS 8 + +/* set to the number of arguments gethostbyname_r() expects */ +#define GETHOSTBYNAME_R_NARGS 6 + +/* Define to 1 if `TIOCGWINSZ' requires . */ +#define GWINSZ_IN_SYS_IOCTL 1 + +/* define if you have AIX security lib */ +/* #undef HAVE_AIX_SECURITY */ + +/* Define to 1 if you have the header file. */ +#define HAVE_ARPA_INET_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_ARPA_NAMESER_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_ASSERT_H 1 + +/* Define to 1 if you have the `bcopy' function. */ +#define HAVE_BCOPY 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_BITS_TYPES_H 1 + +/* Define to 1 if you have the `chroot' function. */ +#define HAVE_CHROOT 1 + +/* Define to 1 if you have the `closesocket' function. */ +/* #undef HAVE_CLOSESOCKET */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_CONIO_H */ + +/* define if crypt(3) is available */ +/* #undef HAVE_CRYPT */ + +/* Define to 1 if you have the header file. */ +#define HAVE_CRYPT_H 1 + +/* define if crypt_r() is also available */ +/* #undef HAVE_CRYPT_R */ + +/* Define to 1 if you have the `ctime_r' function. */ +#define HAVE_CTIME_R 1 + +/* define if you have Cyrus SASL */ +/* #undef HAVE_CYRUS_SASL */ + +/* define if your system supports /dev/poll */ +/* #undef HAVE_DEVPOLL */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_DIRECT_H */ + +/* Define to 1 if you have the header file, and it defines `DIR'. + */ +#define HAVE_DIRENT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_DLFCN_H 1 + +/* Define to 1 if you don't have `vprintf' but do have `_doprnt.' */ +/* #undef HAVE_DOPRNT */ + +/* define if system uses EBCDIC instead of ASCII */ +/* #undef HAVE_EBCDIC */ + +/* Define to 1 if you have the `endgrent' function. */ +#define HAVE_ENDGRENT 1 + +/* Define to 1 if you have the `endpwent' function. */ +#define HAVE_ENDPWENT 1 + +/* define if your system supports epoll */ +#define HAVE_EPOLL 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_ERRNO_H 1 + +/* Define to 1 if you have the `fcntl' function. */ +#define HAVE_FCNTL 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_FCNTL_H 1 + +/* define if you actually have FreeBSD fetch(3) */ +/* #undef HAVE_FETCH */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_FILIO_H */ + +/* Define to 1 if you have the `flock' function. */ +#define HAVE_FLOCK 1 + +/* Define to 1 if you have the `fmemopen' function. */ +#define HAVE_FMEMOPEN 1 + +/* Define to 1 if you have the `fstat' function. */ +#define HAVE_FSTAT 1 + +/* Define to 1 if you have the `gai_strerror' function. */ +#define HAVE_GAI_STRERROR 1 + +/* Define to 1 if you have the `getaddrinfo' function. */ +#define HAVE_GETADDRINFO 1 + +/* Define to 1 if you have the `getdtablesize' function. */ +#define HAVE_GETDTABLESIZE 1 + +/* Define to 1 if you have the `geteuid' function. */ +#define HAVE_GETEUID 1 + +/* Define to 1 if you have the `getgrgid' function. */ +#define HAVE_GETGRGID 1 + +/* Define to 1 if you have the `gethostbyaddr_r' function. */ +#define HAVE_GETHOSTBYADDR_R 1 + +/* Define to 1 if you have the `gethostbyname_r' function. */ +#define HAVE_GETHOSTBYNAME_R 1 + +/* Define to 1 if you have the `gethostname' function. */ +#define HAVE_GETHOSTNAME 1 + +/* Define to 1 if you have the `getnameinfo' function. */ +#define HAVE_GETNAMEINFO 1 + +/* Define to 1 if you have the `getopt' function. */ +#define HAVE_GETOPT 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_GETOPT_H 1 + +/* Define to 1 if you have the `getpassphrase' function. */ +/* #undef HAVE_GETPASSPHRASE */ + +/* Define to 1 if you have the `getpeereid' function. */ +/* #undef HAVE_GETPEEREID */ + +/* Define to 1 if you have the `getpeerucred' function. */ +/* #undef HAVE_GETPEERUCRED */ + +/* Define to 1 if you have the `getpwnam' function. */ +#define HAVE_GETPWNAM 1 + +/* Define to 1 if you have the `getpwuid' function. */ +#define HAVE_GETPWUID 1 + +/* Define to 1 if you have the `getspnam' function. */ +#define HAVE_GETSPNAM 1 + +/* Define to 1 if you have the `gettimeofday' function. */ +#define HAVE_GETTIMEOFDAY 1 + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_GMP_H */ + +/* Define to 1 if you have the `gmtime_r' function. */ +#define HAVE_GMTIME_R 1 + +/* define if you have GNUtls */ +/* #undef HAVE_GNUTLS */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_GNUTLS_GNUTLS_H */ + +/* if you have GNU Pth */ +/* #undef HAVE_GNU_PTH */ + +/* Define to 1 if you have the header file. */ +#define HAVE_GRP_H 1 + +/* Define to 1 if you have the `hstrerror' function. */ +#define HAVE_HSTRERROR 1 + +/* define to you inet_aton(3) is available */ +#define HAVE_INET_ATON 1 + +/* Define to 1 if you have the `inet_ntoa_b' function. */ +/* #undef HAVE_INET_NTOA_B */ + +/* Define to 1 if you have the `inet_ntop' function. */ +#define HAVE_INET_NTOP 1 + +/* Define to 1 if you have the `initgroups' function. */ +#define HAVE_INITGROUPS 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_INTTYPES_H 1 + +/* Define to 1 if you have the `ioctl' function. */ +#define HAVE_IOCTL 1 + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_IO_H */ + +/* define if your system supports kqueue */ +/* #undef HAVE_KQUEUE */ + +/* Define to 1 if you have the `gen' library (-lgen). */ +/* #undef HAVE_LIBGEN */ + +/* Define to 1 if you have the `gmp' library (-lgmp). */ +/* #undef HAVE_LIBGMP */ + +/* Define to 1 if you have the `inet' library (-linet). */ +/* #undef HAVE_LIBINET */ + +/* define if you have libtool -ltdl */ +/* #undef HAVE_LIBLTDL */ + +/* Define to 1 if you have the `net' library (-lnet). */ +/* #undef HAVE_LIBNET */ + +/* Define to 1 if you have the `nsl' library (-lnsl). */ +/* #undef HAVE_LIBNSL */ + +/* Define to 1 if you have the `nsl_s' library (-lnsl_s). */ +/* #undef HAVE_LIBNSL_S */ + +/* Define to 1 if you have the `socket' library (-lsocket). */ +/* #undef HAVE_LIBSOCKET */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_LIBUTIL_H */ + +/* Define to 1 if you have the `V3' library (-lV3). */ +/* #undef HAVE_LIBV3 */ + +/* Define to 1 if you have the header file. */ +#define HAVE_LIMITS_H 1 + +/* if you have LinuxThreads */ +/* #undef HAVE_LINUX_THREADS */ + +/* Define to 1 if you have the header file. */ +#define HAVE_LOCALE_H 1 + +/* Define to 1 if you have the `localtime_r' function. */ +#define HAVE_LOCALTIME_R 1 + +/* Define to 1 if you have the `lockf' function. */ +#define HAVE_LOCKF 1 + +/* Define to 1 if the system has the type `long long'. */ +#define HAVE_LONG_LONG 1 + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_LTDL_H */ + +/* Define to 1 if you have the header file. */ +#define HAVE_MALLOC_H 1 + +/* Define to 1 if you have the `memcpy' function. */ +#define HAVE_MEMCPY 1 + +/* Define to 1 if you have the `memmove' function. */ +#define HAVE_MEMMOVE 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_MEMORY_H 1 + +/* Define to 1 if you have the `memrchr' function. */ +#define HAVE_MEMRCHR 1 + +/* Define to 1 if you have the `mkstemp' function. */ +#define HAVE_MKSTEMP 1 + +/* Define to 1 if you have the `mktemp' function. */ +#define HAVE_MKTEMP 1 + +/* define this if you have mkversion */ +#define HAVE_MKVERSION 1 + +/* Define to 1 if you have the header file, and it defines `DIR'. */ +/* #undef HAVE_NDIR_H */ + +/* Define to 1 if you have the header file. */ +#define HAVE_NETINET_TCP_H 1 + +/* define if strerror_r returns char* instead of int */ +/* #undef HAVE_NONPOSIX_STRERROR_R */ + +/* if you have NT Event Log */ +/* #undef HAVE_NT_EVENT_LOG */ + +/* if you have NT Service Manager */ +/* #undef HAVE_NT_SERVICE_MANAGER */ + +/* if you have NT Threads */ +/* #undef HAVE_NT_THREADS */ + +/* define if you have OpenSSL */ +#define HAVE_OPENSSL 1 + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_OPENSSL_BN_H */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_OPENSSL_CRYPTO_H */ + +/* Define to 1 if you have the header file. */ +#define HAVE_OPENSSL_SSL_H 1 + +/* Define to 1 if you have the `pipe' function. */ +#define HAVE_PIPE 1 + +/* Define to 1 if you have the `poll' function. */ +#define HAVE_POLL 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_POLL_H 1 + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_PROCESS_H */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_PSAP_H */ + +/* define to pthreads API spec revision */ +#define HAVE_PTHREADS 10 + +/* define if you have pthread_detach function */ +#define HAVE_PTHREAD_DETACH 1 + +/* Define to 1 if you have the `pthread_getconcurrency' function. */ +#define HAVE_PTHREAD_GETCONCURRENCY 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_PTHREAD_H 1 + +/* Define to 1 if you have the `pthread_kill' function. */ +#define HAVE_PTHREAD_KILL 1 + +/* Define to 1 if you have the `pthread_kill_other_threads_np' function. */ +/* #undef HAVE_PTHREAD_KILL_OTHER_THREADS_NP */ + +/* define if you have pthread_rwlock_destroy function */ +#define HAVE_PTHREAD_RWLOCK_DESTROY 1 + +/* Define to 1 if you have the `pthread_setconcurrency' function. */ +#define HAVE_PTHREAD_SETCONCURRENCY 1 + +/* Define to 1 if you have the `pthread_yield' function. */ +#define HAVE_PTHREAD_YIELD 1 + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_PTH_H */ + +/* Define to 1 if the system has the type `ptrdiff_t'. */ +#define HAVE_PTRDIFF_T 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_PWD_H 1 + +/* Define to 1 if you have the `read' function. */ +#define HAVE_READ 1 + +/* Define to 1 if you have the `recv' function. */ +#define HAVE_RECV 1 + +/* Define to 1 if you have the `recvfrom' function. */ +#define HAVE_RECVFROM 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_REGEX_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_RESOLV_H 1 + +/* define if you have res_query() */ +#define HAVE_RES_QUERY 1 + +/* define if OpenSSL needs RSAref */ +/* #undef HAVE_RSAREF */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SASL_H */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SASL_SASL_H */ + +/* define if your SASL library has sasl_version() */ +/* #undef HAVE_SASL_VERSION */ + +/* Define to 1 if you have the header file. */ +#define HAVE_SCHED_H 1 + +/* Define to 1 if you have the `sched_yield' function. */ +#define HAVE_SCHED_YIELD 1 + +/* Define to 1 if you have the `send' function. */ +#define HAVE_SEND 1 + +/* Define to 1 if you have the `sendmsg' function. */ +#define HAVE_SENDMSG 1 + +/* Define to 1 if you have the `sendto' function. */ +#define HAVE_SENDTO 1 + +/* Define to 1 if you have the `setegid' function. */ +#define HAVE_SETEGID 1 + +/* Define to 1 if you have the `seteuid' function. */ +#define HAVE_SETEUID 1 + +/* Define to 1 if you have the `setgid' function. */ +#define HAVE_SETGID 1 + +/* Define to 1 if you have the `setpwfile' function. */ +/* #undef HAVE_SETPWFILE */ + +/* Define to 1 if you have the `setsid' function. */ +#define HAVE_SETSID 1 + +/* Define to 1 if you have the `setuid' function. */ +#define HAVE_SETUID 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SGTTY_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SHADOW_H 1 + +/* Define to 1 if you have the `sigaction' function. */ +#define HAVE_SIGACTION 1 + +/* Define to 1 if you have the `signal' function. */ +#define HAVE_SIGNAL 1 + +/* Define to 1 if you have the `sigset' function. */ +#define HAVE_SIGSET 1 + +/* define if you have -lslp */ +/* #undef HAVE_SLP */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SLP_H */ + +/* Define to 1 if you have the `snprintf' function. */ +#define HAVE_SNPRINTF 1 + +/* if you have spawnlp() */ +/* #undef HAVE_SPAWNLP */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SQLEXT_H */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SQL_H */ + +/* Define to 1 if you have the header file. */ +#define HAVE_STDDEF_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDINT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDLIB_H 1 + +/* Define to 1 if you have the `strdup' function. */ +#define HAVE_STRDUP 1 + +/* Define to 1 if you have the `strerror' function. */ +#define HAVE_STRERROR 1 + +/* Define to 1 if you have the `strerror_r' function. */ +#define HAVE_STRERROR_R 1 + +/* Define to 1 if you have the `strftime' function. */ +#define HAVE_STRFTIME 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STRINGS_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STRING_H 1 + +/* Define to 1 if you have the `strpbrk' function. */ +#define HAVE_STRPBRK 1 + +/* Define to 1 if you have the `strrchr' function. */ +#define HAVE_STRRCHR 1 + +/* Define to 1 if you have the `strsep' function. */ +#define HAVE_STRSEP 1 + +/* Define to 1 if you have the `strspn' function. */ +#define HAVE_STRSPN 1 + +/* Define to 1 if you have the `strstr' function. */ +#define HAVE_STRSTR 1 + +/* Define to 1 if you have the `strtol' function. */ +#define HAVE_STRTOL 1 + +/* Define to 1 if you have the `strtoll' function. */ +#define HAVE_STRTOLL 1 + +/* Define to 1 if you have the `strtoq' function. */ +#define HAVE_STRTOQ 1 + +/* Define to 1 if you have the `strtoul' function. */ +#define HAVE_STRTOUL 1 + +/* Define to 1 if you have the `strtoull' function. */ +#define HAVE_STRTOULL 1 + +/* Define to 1 if you have the `strtouq' function. */ +#define HAVE_STRTOUQ 1 + +/* Define to 1 if `msg_accrightslen' is a member of `struct msghdr'. */ +/* #undef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTSLEN */ + +/* Define to 1 if `msg_control' is a member of `struct msghdr'. */ +#define HAVE_STRUCT_MSGHDR_MSG_CONTROL 1 + +/* Define to 1 if `pw_gecos' is a member of `struct passwd'. */ +#define HAVE_STRUCT_PASSWD_PW_GECOS 1 + +/* Define to 1 if `pw_passwd' is a member of `struct passwd'. */ +#define HAVE_STRUCT_PASSWD_PW_PASSWD 1 + +/* Define to 1 if `st_blksize' is a member of `struct stat'. */ +#define HAVE_STRUCT_STAT_ST_BLKSIZE 1 + +/* Define to 1 if `st_fstype' is a member of `struct stat'. */ +/* #undef HAVE_STRUCT_STAT_ST_FSTYPE */ + +/* define to 1 if st_fstype is char * */ +/* #undef HAVE_STRUCT_STAT_ST_FSTYPE_CHAR */ + +/* define to 1 if st_fstype is int */ +/* #undef HAVE_STRUCT_STAT_ST_FSTYPE_INT */ + +/* Define to 1 if `st_vfstype' is a member of `struct stat'. */ +/* #undef HAVE_STRUCT_STAT_ST_VFSTYPE */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SYNCH_H */ + +/* Define to 1 if you have the `sysconf' function. */ +#define HAVE_SYSCONF 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYSEXITS_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYSLOG_H 1 + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SYS_DEVPOLL_H */ + +/* Define to 1 if you have the header file, and it defines `DIR'. + */ +/* #undef HAVE_SYS_DIR_H */ + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_EPOLL_H 1 + +/* define if you actually have sys_errlist in your libs */ +#define HAVE_SYS_ERRLIST 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_ERRNO_H 1 + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SYS_EVENT_H */ + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_FILE_H 1 + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SYS_FILIO_H */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SYS_FSTYP_H */ + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_IOCTL_H 1 + +/* Define to 1 if you have the header file, and it defines `DIR'. + */ +/* #undef HAVE_SYS_NDIR_H */ + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_PARAM_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_POLL_H 1 + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SYS_PRIVGRP_H */ + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_RESOURCE_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_SELECT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_SOCKET_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_STAT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_SYSLOG_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_TIME_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_TYPES_H 1 + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SYS_UCRED_H */ + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_UIO_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_UN_H 1 + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SYS_UUID_H */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SYS_VMOUNT_H */ + +/* Define to 1 if you have that is POSIX.1 compatible. */ +#define HAVE_SYS_WAIT_H 1 + +/* define if you have -lwrap */ +/* #undef HAVE_TCPD */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_TCPD_H */ + +/* Define to 1 if you have the header file. */ +#define HAVE_TERMIOS_H 1 + +/* if you have Solaris LWP (thr) package */ +/* #undef HAVE_THR */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_THREAD_H */ + +/* Define to 1 if you have the `thr_getconcurrency' function. */ +/* #undef HAVE_THR_GETCONCURRENCY */ + +/* Define to 1 if you have the `thr_setconcurrency' function. */ +/* #undef HAVE_THR_SETCONCURRENCY */ + +/* Define to 1 if you have the `thr_yield' function. */ +/* #undef HAVE_THR_YIELD */ + +/* define if you have TLS */ +#define HAVE_TLS 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_UNISTD_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_UTIME_H 1 + +/* define if you have uuid_generate() */ +/* #undef HAVE_UUID_GENERATE */ + +/* define if you have uuid_to_str() */ +/* #undef HAVE_UUID_TO_STR */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_UUID_UUID_H */ + +/* Define to 1 if you have the `vprintf' function. */ +#define HAVE_VPRINTF 1 + +/* Define to 1 if you have the `vsnprintf' function. */ +#define HAVE_VSNPRINTF 1 + +/* Define to 1 if you have the `wait4' function. */ +#define HAVE_WAIT4 1 + +/* Define to 1 if you have the `waitpid' function. */ +#define HAVE_WAITPID 1 + +/* define if you have winsock */ +/* #undef HAVE_WINSOCK */ + +/* define if you have winsock2 */ +/* #undef HAVE_WINSOCK2 */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_WINSOCK2_H */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_WINSOCK_H */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_WIREDTIGER_H */ + +/* Define to 1 if you have the `write' function. */ +#define HAVE_WRITE 1 + +/* define if select implicitly yields */ +#define HAVE_YIELDING_SELECT 1 + +/* Define to 1 if you have the `_vsnprintf' function. */ +/* #undef HAVE__VSNPRINTF */ + +/* define to 32-bit or greater integer type */ +#define LBER_INT_T int + +/* define to large integer type */ +#define LBER_LEN_T long + +/* define to socket descriptor type */ +#define LBER_SOCKET_T int + +/* define to large integer type */ +#define LBER_TAG_T long + +/* define to 1 if library is reentrant */ +#define LDAP_API_FEATURE_X_OPENLDAP_REENTRANT 1 + +/* define to 1 if library is thread safe */ +#define LDAP_API_FEATURE_X_OPENLDAP_THREAD_SAFE 1 + +/* define to LDAP VENDOR VERSION */ +/* #undef LDAP_API_FEATURE_X_OPENLDAP_V2_REFERRALS */ + +/* define this to add debugging code */ +#define LDAP_DEBUG 1 + +/* define if LDAP libs are dynamic */ +/* #undef LDAP_LIBS_DYNAMIC */ + +/* define to support PF_INET6 */ +#define LDAP_PF_INET6 1 + +/* define to support PF_LOCAL */ +#define LDAP_PF_LOCAL 1 + +/* define this to add SLAPI code */ +/* #undef LDAP_SLAPI */ + +/* define this to add syslog code */ +#define LDAP_SYSLOG 1 + +/* Version */ +#define LDAP_VENDOR_VERSION 000000 + +/* Major */ +#define LDAP_VENDOR_VERSION_MAJOR 2 + +/* Minor */ +#define LDAP_VENDOR_VERSION_MINOR X + +/* Patch */ +#define LDAP_VENDOR_VERSION_PATCH X + +/* Define to the sub-directory where libtool stores uninstalled libraries. */ +#define LT_OBJDIR ".libs/" + +/* define if memcmp is not 8-bit clean or is otherwise broken */ +/* #undef NEED_MEMCMP_REPLACEMENT */ + +/* define if you have (or want) no threads */ +/* #undef NO_THREADS */ + +/* define to use the original debug style */ +/* #undef OLD_DEBUG */ + +/* Package */ +#define OPENLDAP_PACKAGE "OpenLDAP" + +/* Version */ +#define OPENLDAP_VERSION "2.X" + +/* Define to the address where bug reports for this package should be sent. */ +#define PACKAGE_BUGREPORT "" + +/* Define to the full name of this package. */ +#define PACKAGE_NAME "" + +/* Define to the full name and version of this package. */ +#define PACKAGE_STRING "" + +/* Define to the one symbol short name of this package. */ +#define PACKAGE_TARNAME "" + +/* Define to the home page for this package. */ +#define PACKAGE_URL "" + +/* Define to the version of this package. */ +#define PACKAGE_VERSION "" + +/* define if sched_yield yields the entire process */ +/* #undef REPLACE_BROKEN_YIELD */ + +/* Define as the return type of signal handlers (`int' or `void'). */ +#define RETSIGTYPE void + +/* Define to the type of arg 1 for `select'. */ +#define SELECT_TYPE_ARG1 int + +/* Define to the type of args 2, 3 and 4 for `select'. */ +#define SELECT_TYPE_ARG234 (fd_set *) + +/* Define to the type of arg 5 for `select'. */ +#define SELECT_TYPE_ARG5 (struct timeval *) + +/* The size of `int', as computed by sizeof. */ +#define SIZEOF_INT 4 + +/* The size of `long', as computed by sizeof. */ +#define SIZEOF_LONG 8 + +/* The size of `long long', as computed by sizeof. */ +#define SIZEOF_LONG_LONG 8 + +/* The size of `short', as computed by sizeof. */ +#define SIZEOF_SHORT 2 + +/* The size of `wchar_t', as computed by sizeof. */ +#define SIZEOF_WCHAR_T 4 + +/* define to support per-object ACIs */ +/* #undef SLAPD_ACI_ENABLED */ + +/* define to support LDAP Async Metadirectory backend */ +/* #undef SLAPD_ASYNCMETA */ + +/* define to support cleartext passwords */ +#define SLAPD_CLEARTEXT 1 + +/* define to support crypt(3) passwords */ +/* #undef SLAPD_CRYPT */ + +/* define to support DNS SRV backend */ +/* #undef SLAPD_DNSSRV */ + +/* define to support LDAP backend */ +/* #undef SLAPD_LDAP */ + +/* define to support MDB backend */ +#define SLAPD_MDB SLAPD_MOD_STATIC + +/* define to support LDAP Metadirectory backend */ +/* #undef SLAPD_META */ + +/* define to support modules */ +/* #undef SLAPD_MODULES */ + +/* dynamically linked module */ +#define SLAPD_MOD_DYNAMIC 2 + +/* statically linked module */ +#define SLAPD_MOD_STATIC 1 + +/* define to support NDB backend */ +/* #undef SLAPD_NDB */ + +/* define to support NULL backend */ +/* #undef SLAPD_NULL */ + +/* define for In-Directory Access Logging overlay */ +/* #undef SLAPD_OVER_ACCESSLOG */ + +/* define for Audit Logging overlay */ +/* #undef SLAPD_OVER_AUDITLOG */ + +/* define for Automatic Certificate Authority overlay */ +/* #undef SLAPD_OVER_AUTOCA */ + +/* define for Collect overlay */ +/* #undef SLAPD_OVER_COLLECT */ + +/* define for Attribute Constraint overlay */ +/* #undef SLAPD_OVER_CONSTRAINT */ + +/* define for Dynamic Directory Services overlay */ +/* #undef SLAPD_OVER_DDS */ + +/* define for Dynamic Directory Services overlay */ +/* #undef SLAPD_OVER_DEREF */ + +/* define for Dynamic Group overlay */ +/* #undef SLAPD_OVER_DYNGROUP */ + +/* define for Dynamic List overlay */ +/* #undef SLAPD_OVER_DYNLIST */ + +/* define for Reverse Group Membership overlay */ +/* #undef SLAPD_OVER_MEMBEROF */ + +/* define for Password Policy overlay */ +/* #undef SLAPD_OVER_PPOLICY */ + +/* define for Proxy Cache overlay */ +/* #undef SLAPD_OVER_PROXYCACHE */ + +/* define for Referential Integrity overlay */ +/* #undef SLAPD_OVER_REFINT */ + +/* define for Return Code overlay */ +/* #undef SLAPD_OVER_RETCODE */ + +/* define for Rewrite/Remap overlay */ +/* #undef SLAPD_OVER_RWM */ + +/* define for Sequential Modify overlay */ +/* #undef SLAPD_OVER_SEQMOD */ + +/* define for ServerSideSort/VLV overlay */ +/* #undef SLAPD_OVER_SSSVLV */ + +/* define for Syncrepl Provider overlay */ +#define SLAPD_OVER_SYNCPROV SLAPD_MOD_STATIC + +/* define for Translucent Proxy overlay */ +/* #undef SLAPD_OVER_TRANSLUCENT */ + +/* define for Attribute Uniqueness overlay */ +/* #undef SLAPD_OVER_UNIQUE */ + +/* define for Value Sorting overlay */ +/* #undef SLAPD_OVER_VALSORT */ + +/* define to support PASSWD backend */ +/* #undef SLAPD_PASSWD */ + +/* define to support PERL backend */ +/* #undef SLAPD_PERL */ + +/* define to support relay backend */ +#define SLAPD_RELAY SLAPD_MOD_STATIC + +/* define to support reverse lookups */ +/* #undef SLAPD_RLOOKUPS */ + +/* define to support SHELL backend */ +/* #undef SLAPD_SHELL */ + +/* define to support SOCK backend */ +/* #undef SLAPD_SOCK */ + +/* define to support SASL passwords */ +/* #undef SLAPD_SPASSWD */ + +/* define to support SQL backend */ +/* #undef SLAPD_SQL */ + +/* define to support WiredTiger backend */ +/* #undef SLAPD_WT */ + +/* define to support run-time loadable ACL */ +/* #undef SLAP_DYNACL */ + +/* Define to 1 if you have the ANSI C header files. */ +#define STDC_HEADERS 1 + +/* Define to 1 if you can safely include both and . */ +#define TIME_WITH_SYS_TIME 1 + +/* Define to 1 if your declares `struct tm'. */ +/* #undef TM_IN_SYS_TIME */ + +/* set to urandom device */ +#define URANDOM_DEVICE "/dev/urandom" + +/* define to use OpenSSL BIGNUM for MP */ +/* #undef USE_MP_BIGNUM */ + +/* define to use GMP for MP */ +/* #undef USE_MP_GMP */ + +/* define to use 'long' for MP */ +/* #undef USE_MP_LONG */ + +/* define to use 'long long' for MP */ +#define USE_MP_LONG_LONG 1 + +/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most + significant byte first (like Motorola and SPARC, unlike Intel). */ +#if defined AC_APPLE_UNIVERSAL_BUILD +# if defined __BIG_ENDIAN__ +# define WORDS_BIGENDIAN 1 +# endif +#else +# ifndef WORDS_BIGENDIAN +# define WORDS_BIGENDIAN 1 +# endif +#endif + +/* Define to the type of arg 3 for `accept'. */ +#define ber_socklen_t socklen_t + +/* Define to `char *' if does not define. */ +/* #undef caddr_t */ + +/* Define to empty if `const' does not conform to ANSI C. */ +/* #undef const */ + +/* Define to `int' if doesn't define. */ +/* #undef gid_t */ + +/* Define to `int' if does not define. */ +/* #undef mode_t */ + +/* Define to `long' if does not define. */ +/* #undef off_t */ + +/* Define to `int' if does not define. */ +/* #undef pid_t */ + +/* Define to `int' if does not define. */ +/* #undef sig_atomic_t */ + +/* Define to `unsigned' if does not define. */ +/* #undef size_t */ + +/* define to snprintf routine */ +/* #undef snprintf */ + +/* Define like ber_socklen_t if does not define. */ +/* #undef socklen_t */ + +/* Define to `signed int' if does not define. */ +/* #undef ssize_t */ + +/* Define to `int' if doesn't define. */ +/* #undef uid_t */ + +/* define as empty if volatile is not supported */ +/* #undef volatile */ + +/* define to snprintf routine */ +/* #undef vsnprintf */ + + +/* begin of portable.h.post */ + +#ifdef _WIN32 + /* don't suck in all of the win32 api */ +# define WIN32_LEAN_AND_MEAN 1 +#endif + +#ifndef LDAP_NEEDS_PROTOTYPES +/* force LDAP_P to always include prototypes */ +#define LDAP_NEEDS_PROTOTYPES 1 +#endif + +#ifndef LDAP_REL_ENG +#if (LDAP_VENDOR_VERSION == 000000) && !defined(LDAP_DEVEL) +#define LDAP_DEVEL +#endif +#if defined(LDAP_DEVEL) && !defined(LDAP_TEST) +#define LDAP_TEST +#endif +#endif + +#ifdef HAVE_STDDEF_H +# include +#endif + +#ifdef HAVE_EBCDIC +/* ASCII/EBCDIC converting replacements for stdio funcs + * vsnprintf and snprintf are used too, but they are already + * checked by the configure script + */ +#define fputs ber_pvt_fputs +#define fgets ber_pvt_fgets +#define printf ber_pvt_printf +#define fprintf ber_pvt_fprintf +#define vfprintf ber_pvt_vfprintf +#define vsprintf ber_pvt_vsprintf +#endif + +#include "ac/fdset.h" + +#include "ldap_cdefs.h" +#include "ldap_features.h" + +#include "ac/assert.h" +#include "ac/localize.h" + +#endif /* _LDAP_PORTABLE_H */ +/* end of portable.h.post */ + diff --git a/src/Common/StackTrace.cpp b/src/Common/StackTrace.cpp index 1c05ccf85ca..0d47d3dcb92 100644 --- a/src/Common/StackTrace.cpp +++ b/src/Common/StackTrace.cpp @@ -221,6 +221,8 @@ static void * getCallerAddress(const ucontext_t & context) return reinterpret_cast(context.uc_mcontext.mc_srr0); #elif defined(__riscv) return reinterpret_cast(context.uc_mcontext.__gregs[REG_PC]); +#elif defined(__s390x__) + return reinterpret_cast(context.uc_mcontext.psw.addr); #else return nullptr; #endif diff --git a/src/Common/ThreadFuzzer.cpp b/src/Common/ThreadFuzzer.cpp index ee6dc222600..2377a241d92 100644 --- a/src/Common/ThreadFuzzer.cpp +++ b/src/Common/ThreadFuzzer.cpp @@ -39,6 +39,8 @@ # define GLIBC_SYMVER "GLIBC_2.27" #elif (defined(__PPC64__) || defined(__powerpc64__)) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ # define GLIBC_SYMVER "GLIBC_2.17" + #elif (defined(__S390X__) || defined(__s390x__)) + # define GLIBC_SYMVER "GLIBC_2.2" #else # error Your platform is not supported. #endif diff --git a/src/Common/formatIPv6.cpp b/src/Common/formatIPv6.cpp index cfa93bf4920..b41fd194323 100644 --- a/src/Common/formatIPv6.cpp +++ b/src/Common/formatIPv6.cpp @@ -164,10 +164,10 @@ void formatIPv6(const unsigned char * src, char *& dst, uint8_t zeroed_tail_byte { uint8_t ipv4_buffer[IPV4_BINARY_LENGTH] = {0}; memcpy(ipv4_buffer, src + 12, IPV4_BINARY_LENGTH); - // Due to historical reasons formatIPv4() takes ipv4 in BE format, but inside ipv6 we store it in LE-format. - if constexpr (std::endian::native == std::endian::little) - std::reverse(std::begin(ipv4_buffer), std::end(ipv4_buffer)); - + // Due to historical reasons formatIPv4() takes ipv4 in BE format, but inside ipv6 we store it in LE-format. +#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ + std::reverse(std::begin(ipv4_buffer), std::end(ipv4_buffer)); +#endif formatIPv4(ipv4_buffer, dst, std::min(zeroed_tail_bytes_count, static_cast(IPV4_BINARY_LENGTH)), "0"); // formatIPv4 has already added a null-terminator for us. return; diff --git a/src/Common/waitForPid.cpp b/src/Common/waitForPid.cpp index 2cf80de644d..5571d7191ee 100644 --- a/src/Common/waitForPid.cpp +++ b/src/Common/waitForPid.cpp @@ -42,6 +42,8 @@ enum PollPidResult #define SYS_pidfd_open 434 #elif defined(__riscv) #define SYS_pidfd_open 434 + #elif defined(__s390x__) + #define SYS_pidfd_open 434 #else #error "Unsupported architecture" #endif diff --git a/src/Compression/CompressionFactory.cpp b/src/Compression/CompressionFactory.cpp index 8154d06371f..b3e7993158a 100644 --- a/src/Compression/CompressionFactory.cpp +++ b/src/Compression/CompressionFactory.cpp @@ -199,9 +199,9 @@ CompressionCodecFactory::CompressionCodecFactory() registerCodecEncrypted(*this); #endif registerCodecFPC(*this); - #ifdef ENABLE_QPL_COMPRESSION - registerCodecDeflateQpl(*this); - #endif +#ifdef ENABLE_QPL_COMPRESSION + registerCodecDeflateQpl(*this); +#endif #endif default_codec = get("LZ4", {}); diff --git a/src/Compression/LZ4_decompress_faster.cpp b/src/Compression/LZ4_decompress_faster.cpp index 34bb440c19c..6f0f148b278 100644 --- a/src/Compression/LZ4_decompress_faster.cpp +++ b/src/Compression/LZ4_decompress_faster.cpp @@ -81,7 +81,7 @@ inline void copyOverlap8(UInt8 * op, const UInt8 *& match, size_t offset) } -#if defined(__x86_64__) || defined(__PPC__) || defined(__riscv) +#if defined(__x86_64__) || defined(__PPC__) || defined(__riscv) || defined(__s390x__) /** We use 'xmm' (128bit SSE) registers here to shuffle 16 bytes. * @@ -272,7 +272,7 @@ inline void copyOverlap16(UInt8 * op, const UInt8 *& match, const size_t offset) } -#if defined(__x86_64__) || defined(__PPC__) || defined (__riscv) +#if defined(__x86_64__) || defined(__PPC__) || defined (__riscv) || defined(__s390x__) inline void copyOverlap16Shuffle(UInt8 * op, const UInt8 *& match, const size_t offset) { diff --git a/src/Storages/StorageS3Cluster.cpp b/src/Storages/StorageS3Cluster.cpp index bf7d3004782..4e3e55fe353 100644 --- a/src/Storages/StorageS3Cluster.cpp +++ b/src/Storages/StorageS3Cluster.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include diff --git a/src/Storages/checkAndGetLiteralArgument.cpp b/src/Storages/checkAndGetLiteralArgument.cpp index 3c43ce98920..1aa942548a7 100644 --- a/src/Storages/checkAndGetLiteralArgument.cpp +++ b/src/Storages/checkAndGetLiteralArgument.cpp @@ -36,5 +36,5 @@ template UInt64 checkAndGetLiteralArgument(const ASTPtr &, const String &); template UInt8 checkAndGetLiteralArgument(const ASTPtr &, const String &); template bool checkAndGetLiteralArgument(const ASTPtr &, const String &); template String checkAndGetLiteralArgument(const ASTLiteral &, const String &); - +template UInt64 checkAndGetLiteralArgument(const ASTLiteral &, const String &); } From fb46b5ed4d0072a5fb611e9791a81343c1d2250e Mon Sep 17 00:00:00 2001 From: Suzy Wang Date: Mon, 23 Jan 2023 14:20:49 +0000 Subject: [PATCH 03/75] s390x support --- contrib/boost-cmake/CMakeLists.txt | 6 ++++++ contrib/libhdfs3-cmake/CMake/Options.cmake | 4 ++-- contrib/libhdfs3-cmake/CMakeLists.txt | 3 ++- contrib/librdkafka-cmake/config.h.in | 2 +- contrib/rocksdb | 2 +- contrib/s2geometry | 2 +- src/Common/HashTable/Hash.h | 2 +- 7 files changed, 14 insertions(+), 7 deletions(-) diff --git a/contrib/boost-cmake/CMakeLists.txt b/contrib/boost-cmake/CMakeLists.txt index 3edc4007fe4..2a70c25ffe1 100644 --- a/contrib/boost-cmake/CMakeLists.txt +++ b/contrib/boost-cmake/CMakeLists.txt @@ -126,6 +126,12 @@ elseif (ARCH_PPC64LE) "${LIBRARY_DIR}/libs/context/src/asm/make_ppc64_sysv_elf_gas.S" "${LIBRARY_DIR}/libs/context/src/asm/ontop_ppc64_sysv_elf_gas.S" ) +elseif (ARCH_S390X) + set (SRCS_CONTEXT ${SRCS_CONTEXT} + "${LIBRARY_DIR}/libs/context/src/asm/jump_s390x_sysv_elf_gas.S" + "${LIBRARY_DIR}/libs/context/src/asm/make_s390x_sysv_elf_gas.S" + "${LIBRARY_DIR}/libs/context/src/asm/ontop_s390x_sysv_elf_gas.S" + ) elseif (ARCH_RISCV64) set (SRCS_CONTEXT ${SRCS_CONTEXT} "${LIBRARY_DIR}/libs/context/src/asm/jump_riscv64_sysv_elf_gas.S" diff --git a/contrib/libhdfs3-cmake/CMake/Options.cmake b/contrib/libhdfs3-cmake/CMake/Options.cmake index dc78920e938..933b24fb9b5 100644 --- a/contrib/libhdfs3-cmake/CMake/Options.cmake +++ b/contrib/libhdfs3-cmake/CMake/Options.cmake @@ -7,9 +7,9 @@ CHECK_FUNCTION_EXISTS(nanosleep HAVE_NANOSLEEP) SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-strict-aliasing") SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fno-strict-aliasing") -IF(ENABLE_SSE STREQUAL ON AND NOT ARCH_PPC64LE AND NOT ARCH_AARCH64 AND NOT ARCH_AARCH64) +IF(ENABLE_SSE STREQUAL ON AND ARCH_AMD64) SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -msse4.2") -ENDIF(ENABLE_SSE STREQUAL ON AND NOT ARCH_PPC64LE AND NOT ARCH_AARCH64 AND NOT ARCH_AARCH64) +ENDIF() IF(NOT TEST_HDFS_PREFIX) SET(TEST_HDFS_PREFIX "./" CACHE STRING "default directory prefix used for test." FORCE) diff --git a/contrib/libhdfs3-cmake/CMakeLists.txt b/contrib/libhdfs3-cmake/CMakeLists.txt index 15d7a4df424..acd7630e90a 100644 --- a/contrib/libhdfs3-cmake/CMakeLists.txt +++ b/contrib/libhdfs3-cmake/CMakeLists.txt @@ -1,4 +1,4 @@ -if(NOT ARCH_AARCH64 AND NOT OS_FREEBSD AND NOT APPLE AND NOT ARCH_PPC64LE) +if(NOT ARCH_AARCH64 AND NOT OS_FREEBSD AND NOT APPLE AND NOT ARCH_PPC64LE AND NOT ARCH_S390X) option(ENABLE_HDFS "Enable HDFS" ${ENABLE_LIBRARIES}) elseif(ENABLE_HDFS) message (${RECONFIGURE_MESSAGE_LEVEL} "Cannot use HDFS3 with current configuration") @@ -70,6 +70,7 @@ set(SRCS "${HDFS3_SOURCE_DIR}/client/Token.cpp" "${HDFS3_SOURCE_DIR}/client/PacketPool.cpp" "${HDFS3_SOURCE_DIR}/client/OutputStream.cpp" + "${HDFS3_SOURCE_DIR}/client/DataReader.cpp" "${HDFS3_SOURCE_DIR}/rpc/RpcChannelKey.cpp" "${HDFS3_SOURCE_DIR}/rpc/RpcProtocolInfo.cpp" "${HDFS3_SOURCE_DIR}/rpc/RpcClient.cpp" diff --git a/contrib/librdkafka-cmake/config.h.in b/contrib/librdkafka-cmake/config.h.in index b6d5fdf046f..52ae70aeea8 100644 --- a/contrib/librdkafka-cmake/config.h.in +++ b/contrib/librdkafka-cmake/config.h.in @@ -66,7 +66,7 @@ #cmakedefine WITH_SASL_OAUTHBEARER 1 #cmakedefine WITH_SASL_CYRUS 1 // crc32chw -#if !defined(__PPC__) && !defined(__riscv) && !defined(__aarch64__) +#if !defined(__PPC__) && !defined(__riscv) && !defined(__aarch64__) && !defined(__s390x__) #define WITH_CRC32C_HW 1 #endif // regex diff --git a/contrib/rocksdb b/contrib/rocksdb index 2c8998e26c6..66e3cbec314 160000 --- a/contrib/rocksdb +++ b/contrib/rocksdb @@ -1 +1 @@ -Subproject commit 2c8998e26c6d46b27c710d7829c3a15e34959f70 +Subproject commit 66e3cbec31400ed3a23deb878c5d7f56f990f0ae diff --git a/contrib/s2geometry b/contrib/s2geometry index 471fe9dc931..4a7ebd5da04 160000 --- a/contrib/s2geometry +++ b/contrib/s2geometry @@ -1 +1 @@ -Subproject commit 471fe9dc931a4bb560333545186e9b5da168ac83 +Subproject commit 4a7ebd5da04cb6c9ea38bbf5914a9f8f3c768564 diff --git a/src/Common/HashTable/Hash.h b/src/Common/HashTable/Hash.h index acac8eeccb2..efdc43917da 100644 --- a/src/Common/HashTable/Hash.h +++ b/src/Common/HashTable/Hash.h @@ -94,7 +94,7 @@ inline DB::UInt64 intHashCRC32(DB::UInt64 x) #elif (defined(__PPC64__) || defined(__powerpc64__)) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ return crc32_ppc(-1U, reinterpret_cast(&x), sizeof(x)); #elif defined(__s390x__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ - return s390x_crc32(-1U, x) + return s390x_crc32(-1U, x); #else /// On other platforms we do not have CRC32. NOTE This can be confusing. /// NOTE: consider using intHash32() From b7ba24945f140a05b16e6734739ec6e08f0d50cd Mon Sep 17 00:00:00 2001 From: Suzy Wang Date: Mon, 23 Jan 2023 22:09:08 -0800 Subject: [PATCH 04/75] fix build --- contrib/libhdfs3-cmake/CMakeLists.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/contrib/libhdfs3-cmake/CMakeLists.txt b/contrib/libhdfs3-cmake/CMakeLists.txt index acd7630e90a..1b4c8036206 100644 --- a/contrib/libhdfs3-cmake/CMakeLists.txt +++ b/contrib/libhdfs3-cmake/CMakeLists.txt @@ -70,7 +70,6 @@ set(SRCS "${HDFS3_SOURCE_DIR}/client/Token.cpp" "${HDFS3_SOURCE_DIR}/client/PacketPool.cpp" "${HDFS3_SOURCE_DIR}/client/OutputStream.cpp" - "${HDFS3_SOURCE_DIR}/client/DataReader.cpp" "${HDFS3_SOURCE_DIR}/rpc/RpcChannelKey.cpp" "${HDFS3_SOURCE_DIR}/rpc/RpcProtocolInfo.cpp" "${HDFS3_SOURCE_DIR}/rpc/RpcClient.cpp" From 3abb00b2e13358a1b7aa3d8e3c55294a463d965f Mon Sep 17 00:00:00 2001 From: Suzy Wang Date: Tue, 24 Jan 2023 07:59:56 -0800 Subject: [PATCH 05/75] remove trailing whitespace --- src/Common/formatIPv6.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Common/formatIPv6.cpp b/src/Common/formatIPv6.cpp index b41fd194323..9a448518c33 100644 --- a/src/Common/formatIPv6.cpp +++ b/src/Common/formatIPv6.cpp @@ -164,8 +164,8 @@ void formatIPv6(const unsigned char * src, char *& dst, uint8_t zeroed_tail_byte { uint8_t ipv4_buffer[IPV4_BINARY_LENGTH] = {0}; memcpy(ipv4_buffer, src + 12, IPV4_BINARY_LENGTH); - // Due to historical reasons formatIPv4() takes ipv4 in BE format, but inside ipv6 we store it in LE-format. -#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ + // Due to historical reasons formatIPv4() takes ipv4 in BE format, but inside ipv6 we store it in LE-format. +#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ std::reverse(std::begin(ipv4_buffer), std::end(ipv4_buffer)); #endif formatIPv4(ipv4_buffer, dst, std::min(zeroed_tail_bytes_count, static_cast(IPV4_BINARY_LENGTH)), "0"); From fe47b43b6afe4c5708fce7e3747dbae1fe22c108 Mon Sep 17 00:00:00 2001 From: Suzy Wang Date: Wed, 25 Jan 2023 05:59:10 -0800 Subject: [PATCH 06/75] replace tab with space --- src/Common/formatIPv6.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Common/formatIPv6.cpp b/src/Common/formatIPv6.cpp index 9a448518c33..608d28ae330 100644 --- a/src/Common/formatIPv6.cpp +++ b/src/Common/formatIPv6.cpp @@ -166,7 +166,7 @@ void formatIPv6(const unsigned char * src, char *& dst, uint8_t zeroed_tail_byte memcpy(ipv4_buffer, src + 12, IPV4_BINARY_LENGTH); // Due to historical reasons formatIPv4() takes ipv4 in BE format, but inside ipv6 we store it in LE-format. #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ - std::reverse(std::begin(ipv4_buffer), std::end(ipv4_buffer)); + std::reverse(std::begin(ipv4_buffer), std::end(ipv4_buffer)); #endif formatIPv4(ipv4_buffer, dst, std::min(zeroed_tail_bytes_count, static_cast(IPV4_BINARY_LENGTH)), "0"); // formatIPv4 has already added a null-terminator for us. From d2d2e3f31e2dbff051b93113c0e4da5892a267bc Mon Sep 17 00:00:00 2001 From: Suzy Wang Date: Wed, 25 Jan 2023 07:49:49 -0800 Subject: [PATCH 07/75] replace tab with spaces --- src/Common/formatIPv6.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Common/formatIPv6.cpp b/src/Common/formatIPv6.cpp index 608d28ae330..7c027a23b4d 100644 --- a/src/Common/formatIPv6.cpp +++ b/src/Common/formatIPv6.cpp @@ -166,7 +166,7 @@ void formatIPv6(const unsigned char * src, char *& dst, uint8_t zeroed_tail_byte memcpy(ipv4_buffer, src + 12, IPV4_BINARY_LENGTH); // Due to historical reasons formatIPv4() takes ipv4 in BE format, but inside ipv6 we store it in LE-format. #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ - std::reverse(std::begin(ipv4_buffer), std::end(ipv4_buffer)); + std::reverse(std::begin(ipv4_buffer), std::end(ipv4_buffer)); #endif formatIPv4(ipv4_buffer, dst, std::min(zeroed_tail_bytes_count, static_cast(IPV4_BINARY_LENGTH)), "0"); // formatIPv4 has already added a null-terminator for us. From 933bb5f42cb91f427a8b914669c0ae5e3b9cfc1e Mon Sep 17 00:00:00 2001 From: Junfu Wu Date: Thu, 12 Jan 2023 01:41:23 +0800 Subject: [PATCH 08/75] fix: return unsorted array element in quantile function --- src/AggregateFunctions/QuantileExact.h | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/AggregateFunctions/QuantileExact.h b/src/AggregateFunctions/QuantileExact.h index a1a71776864..b7af17b52bf 100644 --- a/src/AggregateFunctions/QuantileExact.h +++ b/src/AggregateFunctions/QuantileExact.h @@ -139,9 +139,9 @@ struct QuantileExactExclusive : public QuantileExact auto n = static_cast(h); if (n >= array.size()) - return static_cast(array[array.size() - 1]); + return static_cast(*std::max_element(array.begin(), array.end())); else if (n < 1) - return static_cast(array[0]); + return static_cast(*std::min_element(array.begin(), array.end())); ::nth_element(array.begin(), array.begin() + n - 1, array.end()); auto nth_elem = std::min_element(array.begin() + n, array.end()); @@ -167,9 +167,9 @@ struct QuantileExactExclusive : public QuantileExact auto n = static_cast(h); if (n >= array.size()) - result[indices[i]] = static_cast(array[array.size() - 1]); + result[indices[i]] = static_cast(*std::max_element(array.begin(), array.end())); else if (n < 1) - result[indices[i]] = static_cast(array[0]); + result[indices[i]] = static_cast(*std::min_element(array.begin(), array.end())); else { ::nth_element(array.begin() + prev_n, array.begin() + n - 1, array.end()); @@ -204,9 +204,9 @@ struct QuantileExactInclusive : public QuantileExact auto n = static_cast(h); if (n >= array.size()) - return static_cast(array[array.size() - 1]); + return static_cast(*std::max_element(array.begin(), array.end())); else if (n < 1) - return static_cast(array[0]); + return static_cast(*std::min_element(array.begin(), array.end())); ::nth_element(array.begin(), array.begin() + n - 1, array.end()); auto nth_elem = std::min_element(array.begin() + n, array.end()); @@ -229,9 +229,9 @@ struct QuantileExactInclusive : public QuantileExact auto n = static_cast(h); if (n >= array.size()) - result[indices[i]] = static_cast(array[array.size() - 1]); + result[indices[i]] = static_cast(*std::max_element(array.begin(), array.end())); else if (n < 1) - result[indices[i]] = static_cast(array[0]); + result[indices[i]] = static_cast(*std::min_element(array.begin(), array.end())); else { ::nth_element(array.begin() + prev_n, array.begin() + n - 1, array.end()); From 716d2c4ffb34b7d4ff9298f6112f2a2d884a2c86 Mon Sep 17 00:00:00 2001 From: Suzy Wang Date: Thu, 2 Feb 2023 19:56:18 +0000 Subject: [PATCH 09/75] Update as suggested --- CMakeLists.txt | 13 +++++++------ PreLoad.cmake | 5 +++-- base/base/defines.h | 2 +- cmake/arch.cmake | 2 -- cmake/linux/toolchain-s390x.cmake | 3 +++ src/Compression/LZ4_decompress_faster.cpp | 2 +- 6 files changed, 15 insertions(+), 12 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 485c64db0d9..3cc3d211910 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -453,7 +453,7 @@ endif () set (CMAKE_POSTFIX_VARIABLE "CMAKE_${CMAKE_BUILD_TYPE_UC}_POSTFIX") set (CMAKE_POSITION_INDEPENDENT_CODE OFF) -if (OS_LINUX AND NOT ARCH_AARCH64 AND NOT ARCH_S390X) +if (OS_LINUX AND NOT ARCH_AARCH64) # Slightly more efficient code can be generated # It's disabled for ARM because otherwise ClickHouse cannot run on Android. set (CMAKE_CXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS_RELWITHDEBINFO} -fno-pie") @@ -471,11 +471,12 @@ enable_testing() # Enable for tests without binary option(ENABLE_OPENSSL "This option performs a build with OpenSSL. NOTE! This option is insecure and should never be used. By default, ClickHouse uses and only supports BoringSSL" OFF) -if(ARCH_S390X) - option(ENABLE_OPENSSL_DYNAMIC "This option removes SSL from ClickHouse and will link to the OpenSSL version supplied by OS." ON) -else() - option(ENABLE_OPENSSL_DYNAMIC "This option removes SSL from ClickHouse and will link to the OpenSSL version supplied by OS." OFF) -endif() +if (ARCH_S390X) + set(ENABLE_OPENSSL_DYNAMIC_DEFAULT, ON) +else () + set(ENABLE_OPENSSL_DYNAMIC_DEFAULT, OFF) +endif () +option(ENABLE_OPENSSL_DYNAMIC "This option removes SSL from ClickHouse and will link to the OpenSSL version supplied by OS." ${ENABLE_OPENSSL_DYNAMIC_DEFAULT}) # when installing to /usr - place configs to /etc but for /usr/local place to /usr/local/etc if (CMAKE_INSTALL_PREFIX STREQUAL "/usr") diff --git a/PreLoad.cmake b/PreLoad.cmake index a016fee8e68..a31ca06b150 100644 --- a/PreLoad.cmake +++ b/PreLoad.cmake @@ -58,9 +58,10 @@ execute_process(COMMAND uname -m OUTPUT_VARIABLE ARCH) # By default, prefer clang on Linux # But note, that you still may change the compiler with -DCMAKE_C_COMPILER/-DCMAKE_CXX_COMPILER. if (OS MATCHES "Linux" - # some build systems may use CC/CXX env variables AND "$ENV{CC}" STREQUAL "" - AND "$ENV{CXX}" STREQUAL "") + AND "$ENV{CXX}" STREQUAL "" + AND NOT DEFINED CMAKE_C_COMPILER + AND NOT DEFINED CMAKE_CXX_COMPILER) find_program(CLANG_PATH clang) if (CLANG_PATH) set(CMAKE_C_COMPILER "clang" CACHE INTERNAL "") diff --git a/base/base/defines.h b/base/base/defines.h index b9f58b072df..e1e910eabe7 100644 --- a/base/base/defines.h +++ b/base/base/defines.h @@ -29,7 +29,7 @@ #define MAY_ALIAS __attribute__((__may_alias__)) #if !defined(__x86_64__) && !defined(__aarch64__) && !defined(__PPC__) && !defined(__s390x__) && !(defined(__riscv) && (__riscv_xlen == 64)) -# error "The only supported platforms are x86_64 and AArch64, PowerPC (work in progress) and RISC-V 64 (experimental)" +# error "The only supported platforms are x86_64 and AArch64, PowerPC (work in progress), s390x (work in progress) and RISC-V 64 (experimental)" #endif /// Check for presence of address sanitizer diff --git a/cmake/arch.cmake b/cmake/arch.cmake index fcb29fc4814..5ec05e49e3c 100644 --- a/cmake/arch.cmake +++ b/cmake/arch.cmake @@ -11,8 +11,6 @@ elseif (CMAKE_SYSTEM_PROCESSOR MATCHES "^(s390x.*|S390X.*)") set (ARCH_S390X 1) elseif (CMAKE_SYSTEM_PROCESSOR MATCHES "riscv64") set (ARCH_RISCV64 1) -elseif (CMAKE_SYSTEM_PROCESSOR MATCHES "^(s390x.*|S390X.*)") - set (ARCH_S390X 1) else () message (FATAL_ERROR "Platform ${CMAKE_SYSTEM_PROCESSOR} is not supported") endif () diff --git a/cmake/linux/toolchain-s390x.cmake b/cmake/linux/toolchain-s390x.cmake index b09c3301730..b85d4253b89 100644 --- a/cmake/linux/toolchain-s390x.cmake +++ b/cmake/linux/toolchain-s390x.cmake @@ -1,3 +1,6 @@ +# See linux/toolchain-x86_64.cmake for details about multiple load of toolchain file. +include_guard(GLOBAL) + set (CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY) set (CMAKE_SYSTEM_NAME "Linux") diff --git a/src/Compression/LZ4_decompress_faster.cpp b/src/Compression/LZ4_decompress_faster.cpp index 6f0f148b278..29b7a5679f5 100644 --- a/src/Compression/LZ4_decompress_faster.cpp +++ b/src/Compression/LZ4_decompress_faster.cpp @@ -272,7 +272,7 @@ inline void copyOverlap16(UInt8 * op, const UInt8 *& match, const size_t offset) } -#if defined(__x86_64__) || defined(__PPC__) || defined (__riscv) || defined(__s390x__) +#if defined(__x86_64__) || defined(__PPC__) || defined(__s390x__) || defined (__riscv) inline void copyOverlap16Shuffle(UInt8 * op, const UInt8 *& match, const size_t offset) { From 503c64a45dabb0bf284003d4981945366850c9f0 Mon Sep 17 00:00:00 2001 From: Suzy Wang Date: Thu, 2 Feb 2023 20:44:32 +0000 Subject: [PATCH 10/75] Update as suggested --- src/Compression/LZ4_decompress_faster.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Compression/LZ4_decompress_faster.cpp b/src/Compression/LZ4_decompress_faster.cpp index 29b7a5679f5..c7f6571cb46 100644 --- a/src/Compression/LZ4_decompress_faster.cpp +++ b/src/Compression/LZ4_decompress_faster.cpp @@ -81,7 +81,7 @@ inline void copyOverlap8(UInt8 * op, const UInt8 *& match, size_t offset) } -#if defined(__x86_64__) || defined(__PPC__) || defined(__riscv) || defined(__s390x__) +#if defined(__x86_64__) || defined(__PPC__) || defined(__s390x__) || defined(__riscv) /** We use 'xmm' (128bit SSE) registers here to shuffle 16 bytes. * From dea7e2e1f4d5700efb1a339ede45b17c837c2c1b Mon Sep 17 00:00:00 2001 From: Suzy Wang Date: Thu, 2 Feb 2023 21:00:49 +0000 Subject: [PATCH 11/75] fix spaces --- PreLoad.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/PreLoad.cmake b/PreLoad.cmake index a31ca06b150..0e1ee70fc8f 100644 --- a/PreLoad.cmake +++ b/PreLoad.cmake @@ -86,7 +86,7 @@ if (OS MATCHES "Linux" set (CMAKE_TOOLCHAIN_FILE "cmake/linux/toolchain-ppc64le.cmake" CACHE INTERNAL "") elseif (ARCH MATCHES "^(s390x.*|S390X.*)") set (CMAKE_TOOLCHAIN_FILE "cmake/linux/toolchain-s390x.cmake" CACHE INTERNAL "") -else () + else () message (FATAL_ERROR "Unsupported architecture: ${ARCH}") endif () From cdf35755c96bcc05fda9b2f95d5a32a23fdc01bc Mon Sep 17 00:00:00 2001 From: "Mikhail f. Shiryaev" Date: Thu, 7 Apr 2022 15:08:48 +0200 Subject: [PATCH 12/75] Update clickhouse-server image desription --- docker/server/README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docker/server/README.md b/docker/server/README.md index c60773d99c9..6c42a4dde98 100644 --- a/docker/server/README.md +++ b/docker/server/README.md @@ -8,6 +8,10 @@ ClickHouse works 100-1000x faster than traditional database management systems, For more information and documentation see https://clickhouse.com/. +## Versions + +The `latest` tag points to the latest release of the latest stable branch. Branch tags like `22.2` point to the latest release of the corresponding branch. Full version tags like `22.2.3.5` point to the corresponding release. + ## How to use this image ### start server instance From 5641f56af6868226449fe71205d2ef6d1f0a47c6 Mon Sep 17 00:00:00 2001 From: "Mikhail f. Shiryaev" Date: Wed, 8 Feb 2023 13:06:06 +0100 Subject: [PATCH 13/75] Copy image description from docker hub to sync --- docker/server/README.md | 108 +++++++++++++++++----------------------- 1 file changed, 47 insertions(+), 61 deletions(-) diff --git a/docker/server/README.md b/docker/server/README.md index 6c42a4dde98..5fa5c8875e5 100644 --- a/docker/server/README.md +++ b/docker/server/README.md @@ -2,9 +2,9 @@ ## What is ClickHouse? -We are the creators of the popular open-source column-oriented DBMS (columnar database management system) for online analytical processing (OLAP) which allows users to generate analytical reports using SQL queries in real-time. +ClickHouse is an open-source column-oriented database management system that allows generating analytical data reports in real time. -ClickHouse works 100-1000x faster than traditional database management systems, and processes hundreds of millions to over a billion rows and tens of gigabytes of data per server per second. With a widespread user base around the globe, the technology has received praise for its reliability, ease of use, and fault tolerance. +ClickHouse manages extremely large volumes of data in a stable and sustainable manner. It currently powers [Yandex.Metrica](https://metrica.yandex.com/), world’s [second largest](http://w3techs.com/technologies/overview/traffic_analysis/all) web analytics platform, with over 13 trillion database records and over 20 billion events a day, generating customized reports on-the-fly, directly from non-aggregated data. This system was successfully implemented at [CERN’s LHCb experiment](https://www.yandex.com/company/press_center/press_releases/2012/2012-04-10/) to store and process metadata on 10bn events with over 1000 attributes per event registered in 2011. For more information and documentation see https://clickhouse.com/. @@ -15,135 +15,122 @@ The `latest` tag points to the latest release of the latest stable branch. Branc ## How to use this image ### start server instance - ```bash -docker run -d --name some-clickhouse-server --ulimit nofile=262144:262144 clickhouse/clickhouse-server +$ docker run -d --name some-clickhouse-server --ulimit nofile=262144:262144 clickhouse/clickhouse-server ``` -By default, ClickHouse will be accessible only via the Docker network. See the [networking section below](#networking). +By default ClickHouse will be accessible only via docker network. See the [networking section below](#networking). -By default, starting above server instance will be run as the `default` user without a password. +By default, starting above server instance will be run as default user without password. ### connect to it from a native client - ```bash -docker run -it --rm --link some-clickhouse-server:clickhouse-server --entrypoint clickhouse-client clickhouse/clickhouse-server --host clickhouse-server +$ docker run -it --rm --link some-clickhouse-server:clickhouse-server --entrypoint clickhouse-client clickhouse/clickhouse-server --host clickhouse-server # OR -docker exec -it some-clickhouse-server clickhouse-client +$ docker exec -it some-clickhouse-server clickhouse-client ``` -More information about the [ClickHouse client](https://clickhouse.com/docs/en/interfaces/cli/). +More information about [ClickHouse client](https://clickhouse.com/docs/en/interfaces/cli/). ### connect to it using curl ```bash echo "SELECT 'Hello, ClickHouse!'" | docker run -i --rm --link some-clickhouse-server:clickhouse-server curlimages/curl 'http://clickhouse-server:8123/?query=' -s --data-binary @- ``` - More information about [ClickHouse HTTP Interface](https://clickhouse.com/docs/en/interfaces/http/). -### stopping / removing the container +### stopping / removing the containter ```bash -docker stop some-clickhouse-server -docker rm some-clickhouse-server +$ docker stop some-clickhouse-server +$ docker rm some-clickhouse-server ``` ### networking -You can expose your ClickHouse running in docker by [mapping a particular port](https://docs.docker.com/config/containers/container-networking/) from inside the container using host ports: +You can expose you ClickHouse running in docker by [mapping particular port](https://docs.docker.com/config/containers/container-networking/) from inside container to a host ports: ```bash -docker run -d -p 18123:8123 -p19000:9000 --name some-clickhouse-server --ulimit nofile=262144:262144 clickhouse/clickhouse-server -echo 'SELECT version()' | curl 'http://localhost:18123/' --data-binary @- +$ docker run -d -p 18123:8123 -p19000:9000 --name some-clickhouse-server --ulimit nofile=262144:262144 clickhouse/clickhouse-server +$ echo 'SELECT version()' | curl 'http://localhost:18123/' --data-binary @- +20.12.3.3 ``` -```response -22.6.3.35 -``` - -or by allowing the container to use [host ports directly](https://docs.docker.com/network/host/) using `--network=host` (also allows achieving better network performance): +or by allowing container to use [host ports directly](https://docs.docker.com/network/host/) using `--network=host` (also allows archiving better network performance): ```bash -docker run -d --network=host --name some-clickhouse-server --ulimit nofile=262144:262144 clickhouse/clickhouse-server -echo 'SELECT version()' | curl 'http://localhost:8123/' --data-binary @- -``` - -```response -22.6.3.35 +$ docker run -d --network=host --name some-clickhouse-server --ulimit nofile=262144:262144 clickhouse/clickhouse-server +$ echo 'SELECT version()' | curl 'http://localhost:8123/' --data-binary @- +20.12.3.3 ``` ### Volumes -Typically you may want to mount the following folders inside your container to achieve persistency: +Typically you may want to mount the following folders inside your container to archieve persistency: * `/var/lib/clickhouse/` - main folder where ClickHouse stores the data -* `/var/log/clickhouse-server/` - logs +* `/val/log/clickhouse-server/` - logs ```bash -docker run -d \ - -v $(realpath ./ch_data):/var/lib/clickhouse/ \ - -v $(realpath ./ch_logs):/var/log/clickhouse-server/ \ - --name some-clickhouse-server --ulimit nofile=262144:262144 clickhouse/clickhouse-server +$ docker run -d \ + -v $(realpath ./ch_data):/var/lib/clickhouse/ \ + -v $(realpath ./ch_logs):/var/log/clickhouse-server/ \ + --name some-clickhouse-server --ulimit nofile=262144:262144 clickhouse/clickhouse-server ``` You may also want to mount: * `/etc/clickhouse-server/config.d/*.xml` - files with server configuration adjustmenets -* `/etc/clickhouse-server/users.d/*.xml` - files with user settings adjustmenets +* `/etc/clickhouse-server/usert.d/*.xml` - files with use settings adjustmenets * `/docker-entrypoint-initdb.d/` - folder with database initialization scripts (see below). ### Linux capabilities -ClickHouse has some advanced functionality, which requires enabling several [Linux capabilities](https://man7.org/linux/man-pages/man7/capabilities.7.html). +ClickHouse has some advanced functionality which requite enabling several [linux capabilities](https://man7.org/linux/man-pages/man7/capabilities.7.html). -These are optional and can be enabled using the following [docker command-line arguments](https://docs.docker.com/engine/reference/run/#runtime-privilege-and-linux-capabilities): +It is optional and can be enabled using the following [docker command line agruments](https://docs.docker.com/engine/reference/run/#runtime-privilege-and-linux-capabilities): ```bash -docker run -d \ - --cap-add=SYS_NICE --cap-add=NET_ADMIN --cap-add=IPC_LOCK \ - --name some-clickhouse-server --ulimit nofile=262144:262144 clickhouse/clickhouse-server +$ docker run -d \ + --cap-add=SYS_NICE --cap-add=NET_ADMIN --cap-add=IPC_LOCK \ + --name some-clickhouse-server --ulimit nofile=262144:262144 clickhouse/clickhouse-server ``` ## Configuration -The container exposes port 8123 for the [HTTP interface](https://clickhouse.com/docs/en/interfaces/http_interface/) and port 9000 for the [native client](https://clickhouse.com/docs/en/interfaces/tcp/). +Container exposes 8123 port for [HTTP interface](https://clickhouse.com/docs/en/interfaces/http_interface/) and 9000 port for [native client](https://clickhouse.com/docs/en/interfaces/tcp/). -ClickHouse configuration is represented with a file "config.xml" ([documentation](https://clickhouse.com/docs/en/operations/configuration_files/)) +ClickHouse configuration represented with a file "config.xml" ([documentation](https://clickhouse.com/docs/en/operations/configuration_files/)) ### Start server instance with custom configuration - ```bash -docker run -d --name some-clickhouse-server --ulimit nofile=262144:262144 -v /path/to/your/config.xml:/etc/clickhouse-server/config.xml clickhouse/clickhouse-server +$ docker run -d --name some-clickhouse-server --ulimit nofile=262144:262144 -v /path/to/your/config.xml:/etc/clickhouse-server/config.xml clickhouse/clickhouse-server ``` -### Start server as a custom user - -```bash +### Start server as custom user +``` # $(pwd)/data/clickhouse should exist and be owned by current user -docker run --rm --user ${UID}:${GID} --name some-clickhouse-server --ulimit nofile=262144:262144 -v "$(pwd)/logs/clickhouse:/var/log/clickhouse-server" -v "$(pwd)/data/clickhouse:/var/lib/clickhouse" clickhouse/clickhouse-server +$ docker run --rm --user ${UID}:${GID} --name some-clickhouse-server --ulimit nofile=262144:262144 -v "$(pwd)/logs/clickhouse:/var/log/clickhouse-server" -v "$(pwd)/data/clickhouse:/var/lib/clickhouse" clickhouse/clickhouse-server ``` - -When you use the image with local directories mounted, you probably want to specify the user to maintain the proper file ownership. Use the `--user` argument and mount `/var/lib/clickhouse` and `/var/log/clickhouse-server` inside the container. Otherwise, the image will complain and not start. +When you use the image with mounting local directories inside you probably would like to not mess your directory tree with files owner and permissions. Then you could use `--user` argument. In this case, you should mount every necessary directory (`/var/lib/clickhouse` and `/var/log/clickhouse-server`) inside the container. Otherwise, image will complain and not start. ### Start server from root (useful in case of userns enabled) - -```bash -docker run --rm -e CLICKHOUSE_UID=0 -e CLICKHOUSE_GID=0 --name clickhouse-server-userns -v "$(pwd)/logs/clickhouse:/var/log/clickhouse-server" -v "$(pwd)/data/clickhouse:/var/lib/clickhouse" clickhouse/clickhouse-server +``` +$ docker run --rm -e CLICKHOUSE_UID=0 -e CLICKHOUSE_GID=0 --name clickhouse-server-userns -v "$(pwd)/logs/clickhouse:/var/log/clickhouse-server" -v "$(pwd)/data/clickhouse:/var/lib/clickhouse" clickhouse/clickhouse-server ``` ### How to create default database and user on starting -Sometimes you may want to create a user (user named `default` is used by default) and database on image start. You can do it using environment variables `CLICKHOUSE_DB`, `CLICKHOUSE_USER`, `CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT` and `CLICKHOUSE_PASSWORD`: +Sometimes you may want to create user (user named `default` is used by default) and database on image starting. You can do it using environment variables `CLICKHOUSE_DB`, `CLICKHOUSE_USER`, `CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT` and `CLICKHOUSE_PASSWORD`: -```bash -docker run --rm -e CLICKHOUSE_DB=my_database -e CLICKHOUSE_USER=username -e CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT=1 -e CLICKHOUSE_PASSWORD=password -p 9000:9000/tcp clickhouse/clickhouse-server +``` +$ docker run --rm -e CLICKHOUSE_DB=my_database -e CLICKHOUSE_USER=username -e CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT=1 -e CLICKHOUSE_PASSWORD=password -p 9000:9000/tcp clickhouse/clickhouse-server ``` ## How to extend this image -To perform additional initialization in an image derived from this one, add one or more `*.sql`, `*.sql.gz`, or `*.sh` scripts under `/docker-entrypoint-initdb.d`. After the entrypoint calls `initdb`, it will run any `*.sql` files, run any executable `*.sh` scripts, and source any non-executable `*.sh` scripts found in that directory to do further initialization before starting the service. -Also, you can provide environment variables `CLICKHOUSE_USER` & `CLICKHOUSE_PASSWORD` that will be used for clickhouse-client during initialization. +If you would like to do additional initialization in an image derived from this one, add one or more `*.sql`, `*.sql.gz`, or `*.sh` scripts under `/docker-entrypoint-initdb.d`. After the entrypoint calls `initdb` it will run any `*.sql` files, run any executable `*.sh` scripts, and source any non-executable `*.sh` scripts found in that directory to do further initialization before starting the service. +Also you can provide environment variables `CLICKHOUSE_USER` & `CLICKHOUSE_PASSWORD` that will be used for clickhouse-client during initialization. For example, to add an additional user and database, add the following to `/docker-entrypoint-initdb.d/init-db.sh`: @@ -152,12 +139,11 @@ For example, to add an additional user and database, add the following to `/dock set -e clickhouse client -n <<-EOSQL - CREATE DATABASE docker; - CREATE TABLE docker.docker (x Int32) ENGINE = Log; + CREATE DATABASE docker; + CREATE TABLE docker.docker (x Int32) ENGINE = Log; EOSQL ``` ## License View [license information](https://github.com/ClickHouse/ClickHouse/blob/master/LICENSE) for the software contained in this image. - From b2f583e749672a4ef27d749113e1a8f001419c22 Mon Sep 17 00:00:00 2001 From: "Mikhail f. Shiryaev" Date: Wed, 8 Feb 2023 13:26:41 +0100 Subject: [PATCH 14/75] Fix some typos, improve versions description --- docker/server/README.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/docker/server/README.md b/docker/server/README.md index 5fa5c8875e5..950b829356f 100644 --- a/docker/server/README.md +++ b/docker/server/README.md @@ -10,7 +10,11 @@ For more information and documentation see https://clickhouse.com/. ## Versions -The `latest` tag points to the latest release of the latest stable branch. Branch tags like `22.2` point to the latest release of the corresponding branch. Full version tags like `22.2.3.5` point to the corresponding release. +- The `latest` tag points to the latest release of the latest stable branch. +- Branch tags like `22.2` point to the latest release of the corresponding branch. +- Full version tags like `22.2.3.5` point to the corresponding release. +- The tag `head` is built from the latest commit to the default branch. +- Each tag has optional `-alpine` suffix to reflect that it's built on top of `alpine`. ## How to use this image @@ -81,7 +85,7 @@ $ docker run -d \ You may also want to mount: * `/etc/clickhouse-server/config.d/*.xml` - files with server configuration adjustmenets -* `/etc/clickhouse-server/usert.d/*.xml` - files with use settings adjustmenets +* `/etc/clickhouse-server/users.d/*.xml` - files with user settings adjustmenets * `/docker-entrypoint-initdb.d/` - folder with database initialization scripts (see below). ### Linux capabilities From e8965543c3e478d8100f31b3a8506e8b16fc0f4e Mon Sep 17 00:00:00 2001 From: sanjam Date: Tue, 7 Feb 2023 07:51:25 +0000 Subject: [PATCH 15/75] Issue #2053 - conversion of 256 bit to 128 bit --- base/base/wide_integer_impl.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/base/base/wide_integer_impl.h b/base/base/wide_integer_impl.h index f5b30cbab55..4a54c0fb2a4 100644 --- a/base/base/wide_integer_impl.h +++ b/base/base/wide_integer_impl.h @@ -360,7 +360,7 @@ struct integer::_impl constexpr const unsigned to_copy = min_bits / base_bits; for (unsigned i = 0; i < to_copy; ++i) - self.items[little(i)] = rhs.items[little(i)]; + self.items[little(i)] = rhs.items[integer::_impl::little(i)]; if constexpr (Bits > Bits2) { From 5bc3e703ef82f23fe4e543c2483b4b4cf969198a Mon Sep 17 00:00:00 2001 From: "Mikhail f. Shiryaev" Date: Thu, 9 Feb 2023 19:10:06 +0100 Subject: [PATCH 16/75] Move the heaviest operation to the top --- docker/packager/binary/Dockerfile | 91 ++++++++++++++++--------------- 1 file changed, 47 insertions(+), 44 deletions(-) diff --git a/docker/packager/binary/Dockerfile b/docker/packager/binary/Dockerfile index f750dbf4f74..36f0754413c 100644 --- a/docker/packager/binary/Dockerfile +++ b/docker/packager/binary/Dockerfile @@ -1,7 +1,41 @@ -# rebuild in #33610 # docker build -t clickhouse/binary-builder . ARG FROM_TAG=latest FROM clickhouse/test-util:$FROM_TAG +ENV CC=clang-${LLVM_VERSION} +ENV CXX=clang++-${LLVM_VERSION} +# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +# DO NOT PUT ANYTHING BEFORE THREE NEXT `RUN` DIRECTIVES +# THE MOST HEAVY OPERATION MUST BE THE FIRST IN THE CACHE +# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +# libtapi is required to support .tbh format from recent MacOS SDKs +RUN git clone --depth 1 https://github.com/tpoechtrager/apple-libtapi.git \ + && cd apple-libtapi \ + && INSTALLPREFIX=/cctools ./build.sh \ + && ./install.sh \ + && cd .. \ + && rm -rf apple-libtapi + +# Build and install tools for cross-linking to Darwin (x86-64) +RUN git clone --depth 1 https://github.com/tpoechtrager/cctools-port.git \ + && cd cctools-port/cctools \ + && ./configure --prefix=/cctools --with-libtapi=/cctools \ + --target=x86_64-apple-darwin \ + && make install -j$(nproc) \ + && cd ../.. \ + && rm -rf cctools-port + +# Build and install tools for cross-linking to Darwin (aarch64) +RUN git clone --depth 1 https://github.com/tpoechtrager/cctools-port.git \ + && cd cctools-port/cctools \ + && ./configure --prefix=/cctools --with-libtapi=/cctools \ + --target=aarch64-apple-darwin \ + && make install -j$(nproc) \ + && cd ../.. \ + && rm -rf cctools-port + +# !!!!!!!!!!! +# END COMPILE +# !!!!!!!!!!! # Rust toolchain and libraries ENV RUSTUP_HOME=/rust/rustup @@ -16,58 +50,27 @@ RUN curl https://sh.rustup.rs -sSf | bash -s -- -y && \ rustup target add aarch64-apple-darwin && \ rustup target add powerpc64le-unknown-linux-gnu -RUN apt-get update && \ - apt-get install --yes \ - gcc-aarch64-linux-gnu \ +# NOTE: Seems like gcc-11 is too new for ubuntu20 repository +# A cross-linker for RISC-V 64 (we need it, because LLVM's LLD does not work): +RUN add-apt-repository ppa:ubuntu-toolchain-r/test --yes \ + && apt-get update \ + && apt-get install --yes \ + binutils-riscv64-linux-gnu \ build-essential \ + g++-11 \ + gcc-11 \ + gcc-aarch64-linux-gnu \ libc6 \ libc6-dev \ libc6-dev-arm64-cross \ yasm \ - zstd && \ - apt-get clean - -ENV CC=clang-${LLVM_VERSION} -ENV CXX=clang++-${LLVM_VERSION} - -# libtapi is required to support .tbh format from recent MacOS SDKs -RUN git clone --depth 1 https://github.com/tpoechtrager/apple-libtapi.git \ - && cd apple-libtapi \ - && INSTALLPREFIX=/cctools ./build.sh \ - && ./install.sh \ - && cd .. \ - && rm -rf apple-libtapi - -# Build and install tools for cross-linking to Darwin (x86-64) -RUN git clone --depth 1 https://github.com/tpoechtrager/cctools-port.git \ - && cd cctools-port/cctools \ - && ./configure --prefix=/cctools --with-libtapi=/cctools \ - --target=x86_64-apple-darwin \ - && make install \ - && cd ../.. \ - && rm -rf cctools-port - -# Build and install tools for cross-linking to Darwin (aarch64) -RUN git clone --depth 1 https://github.com/tpoechtrager/cctools-port.git \ - && cd cctools-port/cctools \ - && ./configure --prefix=/cctools --with-libtapi=/cctools \ - --target=aarch64-apple-darwin \ - && make install \ - && cd ../.. \ - && rm -rf cctools-port + zstd \ + && apt-get clean \ + && rm -rf /var/lib/apt/lists # Download toolchain and SDK for Darwin RUN wget -nv https://github.com/phracker/MacOSX-SDKs/releases/download/11.3/MacOSX11.0.sdk.tar.xz -# NOTE: Seems like gcc-11 is too new for ubuntu20 repository -RUN add-apt-repository ppa:ubuntu-toolchain-r/test --yes \ - && apt-get update \ - && apt-get install gcc-11 g++-11 --yes \ - && apt-get clean - -# A cross-linker for RISC-V 64 (we need it, because LLVM's LLD does not work): -RUN apt-get install binutils-riscv64-linux-gnu - # Architecture of the image when BuildKit/buildx is used ARG TARGETARCH ARG NFPM_VERSION=2.20.0 From 1ef1eefa267a308ed98268da55dc75c66b326496 Mon Sep 17 00:00:00 2001 From: "Mikhail f. Shiryaev" Date: Thu, 9 Feb 2023 19:10:48 +0100 Subject: [PATCH 17/75] Format the RUN, update clang-tidy-cache --- docker/packager/binary/Dockerfile | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/docker/packager/binary/Dockerfile b/docker/packager/binary/Dockerfile index 36f0754413c..52c1ecc3a2f 100644 --- a/docker/packager/binary/Dockerfile +++ b/docker/packager/binary/Dockerfile @@ -76,23 +76,25 @@ ARG TARGETARCH ARG NFPM_VERSION=2.20.0 RUN arch=${TARGETARCH:-amd64} \ - && curl -Lo /tmp/nfpm.deb "https://github.com/goreleaser/nfpm/releases/download/v${NFPM_VERSION}/nfpm_${arch}.deb" \ - && dpkg -i /tmp/nfpm.deb \ - && rm /tmp/nfpm.deb + && curl -Lo /tmp/nfpm.deb "https://github.com/goreleaser/nfpm/releases/download/v${NFPM_VERSION}/nfpm_${arch}.deb" \ + && dpkg -i /tmp/nfpm.deb \ + && rm /tmp/nfpm.deb ARG GO_VERSION=1.18.3 # We need go for clickhouse-diagnostics RUN arch=${TARGETARCH:-amd64} \ - && curl -Lo /tmp/go.tgz "https://go.dev/dl/go${GO_VERSION}.linux-${arch}.tar.gz" \ - && tar -xzf /tmp/go.tgz -C /usr/local/ \ - && rm /tmp/go.tgz + && curl -Lo /tmp/go.tgz "https://go.dev/dl/go${GO_VERSION}.linux-${arch}.tar.gz" \ + && tar -xzf /tmp/go.tgz -C /usr/local/ \ + && rm /tmp/go.tgz ENV PATH="$PATH:/usr/local/go/bin" ENV GOPATH=/workdir/go ENV GOCACHE=/workdir/ -RUN curl https://raw.githubusercontent.com/matus-chochlik/ctcache/7fd516e91c17779cbc6fc18bd119313d9532dd90/clang-tidy-cache -Lo /usr/bin/clang-tidy-cache \ - && chmod +x /usr/bin/clang-tidy-cache +ARG CLANG_TIDY_SHA1=03644275e794b0587849bfc2ec6123d5ae0bdb1c +RUN curl -Lo /usr/bin/clang-tidy-cache \ + "https://raw.githubusercontent.com/matus-chochlik/ctcache/$CLANG_TIDY_SHA1/clang-tidy-cache" \ + && chmod +x /usr/bin/clang-tidy-cache RUN mkdir /workdir && chmod 777 /workdir WORKDIR /workdir From 376b5d178f92bc583049536c8db5be257312992f Mon Sep 17 00:00:00 2001 From: "Mikhail f. Shiryaev" Date: Thu, 9 Feb 2023 19:13:44 +0100 Subject: [PATCH 18/75] Experiment with multiple build stages --- docker/packager/binary/Dockerfile | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/docker/packager/binary/Dockerfile b/docker/packager/binary/Dockerfile index 52c1ecc3a2f..60208b5068d 100644 --- a/docker/packager/binary/Dockerfile +++ b/docker/packager/binary/Dockerfile @@ -1,6 +1,8 @@ # docker build -t clickhouse/binary-builder . ARG FROM_TAG=latest -FROM clickhouse/test-util:$FROM_TAG +FROM clickhouse/test-util:latest AS cctools +# The cctools are built always from the clickhouse/test-util:latest and cached inline +# Theoretically, it should improve rebuild speed significantly ENV CC=clang-${LLVM_VERSION} ENV CXX=clang++-${LLVM_VERSION} # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! @@ -37,6 +39,11 @@ RUN git clone --depth 1 https://github.com/tpoechtrager/cctools-port.git \ # END COMPILE # !!!!!!!!!!! +FROM clickhouse/test-util:$FROM_TAG +ENV CC=clang-${LLVM_VERSION} +ENV CXX=clang++-${LLVM_VERSION} +COPY --from=cctools /cctools /cctools + # Rust toolchain and libraries ENV RUSTUP_HOME=/rust/rustup ENV CARGO_HOME=/rust/cargo From 7c6bb55eca4c4cb1c449e99ee02c5979517d2aa5 Mon Sep 17 00:00:00 2001 From: "Mikhail f. Shiryaev" Date: Thu, 9 Feb 2023 20:36:39 +0100 Subject: [PATCH 19/75] Use TeePopen to get logs in the main log --- tests/ci/docker_images_check.py | 59 ++++++++++++++++----------------- tests/ci/docker_test.py | 14 ++------ 2 files changed, 31 insertions(+), 42 deletions(-) diff --git a/tests/ci/docker_images_check.py b/tests/ci/docker_images_check.py index f5b707be48f..d6b2edbcd2b 100644 --- a/tests/ci/docker_images_check.py +++ b/tests/ci/docker_images_check.py @@ -21,6 +21,7 @@ from pr_info import PRInfo from report import TestResults, TestResult from s3_helper import S3Helper from stopwatch import Stopwatch +from tee_popen import TeePopen from upload_result_helper import upload_results NAME = "Push to Dockerhub" @@ -191,20 +192,19 @@ def build_and_push_dummy_image( Path(TEMP_PATH) / f"build_and_push_log_{image.repo.replace('/', '_')}_{version_string}.log" ) - with open(build_log, "wb") as bl: - cmd = ( - f"docker pull {dummy_source}; " - f"docker tag {dummy_source} {image.repo}:{version_string}; " - ) - if push: - cmd += f"docker push {image.repo}:{version_string}" + cmd = ( + f"docker pull {dummy_source}; " + f"docker tag {dummy_source} {image.repo}:{version_string}; " + ) + if push: + cmd += f"docker push {image.repo}:{version_string}" - logging.info("Docker command to run: %s", cmd) - with subprocess.Popen(cmd, shell=True, stderr=bl, stdout=bl) as proc: - retcode = proc.wait() + logging.info("Docker command to run: %s", cmd) + with TeePopen(cmd, build_log) as proc: + retcode = proc.wait() - if retcode != 0: - return False, build_log + if retcode != 0: + return False, build_log logging.info("Processing of %s successfully finished", image.repo) return True, build_log @@ -247,25 +247,24 @@ def build_and_push_one_image( f"--cache-from type=registry,ref={image.repo}:{additional_cache}" ) - with open(build_log, "wb") as bl: - cmd = ( - "docker buildx build --builder default " - f"--label build-url={GITHUB_RUN_URL} " - f"{from_tag_arg}" - # A hack to invalidate cache, grep for it in docker/ dir - f"--build-arg CACHE_INVALIDATOR={GITHUB_RUN_URL} " - f"--tag {image.repo}:{version_string} " - f"{cache_from} " - f"--cache-to type=inline,mode=max " - f"{push_arg}" - f"--progress plain {image.full_path}" - ) - logging.info("Docker command to run: %s", cmd) - with subprocess.Popen(cmd, shell=True, stderr=bl, stdout=bl) as proc: - retcode = proc.wait() + cmd = ( + "docker buildx build --builder default " + f"--label build-url={GITHUB_RUN_URL} " + f"{from_tag_arg}" + # A hack to invalidate cache, grep for it in docker/ dir + f"--build-arg CACHE_INVALIDATOR={GITHUB_RUN_URL} " + f"--tag {image.repo}:{version_string} " + f"{cache_from} " + f"--cache-to type=inline,mode=max " + f"{push_arg}" + f"--progress plain {image.full_path}" + ) + logging.info("Docker command to run: %s", cmd) + with TeePopen(cmd, build_log) as proc: + retcode = proc.wait() - if retcode != 0: - return False, build_log + if retcode != 0: + return False, build_log logging.info("Processing of %s successfully finished", image.repo) return True, build_log diff --git a/tests/ci/docker_test.py b/tests/ci/docker_test.py index e7b54652272..c1f650842e2 100644 --- a/tests/ci/docker_test.py +++ b/tests/ci/docker_test.py @@ -117,15 +117,13 @@ class TestDockerImageCheck(unittest.TestCase): self.assertEqual(versions, ["1", "1-HEAD"]) self.assertEqual(result_version, "1-HEAD") - @patch("builtins.open") - @patch("subprocess.Popen") + @patch("docker_images_check.TeePopen") @patch("platform.machine") - def test_build_and_push_one_image(self, mock_machine, mock_popen, mock_open): + def test_build_and_push_one_image(self, mock_machine, mock_popen): mock_popen.return_value.__enter__.return_value.wait.return_value = 0 image = di.DockerImage("path", "name", False, gh_repo_path="") result, _ = di.build_and_push_one_image(image, "version", "", True, True) - mock_open.assert_called_once() mock_popen.assert_called_once() mock_machine.assert_not_called() self.assertIn( @@ -138,13 +136,11 @@ class TestDockerImageCheck(unittest.TestCase): mock_popen.call_args.args, ) self.assertTrue(result) - mock_open.reset_mock() mock_popen.reset_mock() mock_machine.reset_mock() mock_popen.return_value.__enter__.return_value.wait.return_value = 0 result, _ = di.build_and_push_one_image(image, "version2", "", False, True) - mock_open.assert_called_once() mock_popen.assert_called_once() mock_machine.assert_not_called() self.assertIn( @@ -158,12 +154,10 @@ class TestDockerImageCheck(unittest.TestCase): ) self.assertTrue(result) - mock_open.reset_mock() mock_popen.reset_mock() mock_machine.reset_mock() mock_popen.return_value.__enter__.return_value.wait.return_value = 1 result, _ = di.build_and_push_one_image(image, "version2", "", False, False) - mock_open.assert_called_once() mock_popen.assert_called_once() mock_machine.assert_not_called() self.assertIn( @@ -176,14 +170,12 @@ class TestDockerImageCheck(unittest.TestCase): ) self.assertFalse(result) - mock_open.reset_mock() mock_popen.reset_mock() mock_machine.reset_mock() mock_popen.return_value.__enter__.return_value.wait.return_value = 1 result, _ = di.build_and_push_one_image( image, "version2", "cached-version", False, False ) - mock_open.assert_called_once() mock_popen.assert_called_once() mock_machine.assert_not_called() self.assertIn( @@ -197,7 +189,6 @@ class TestDockerImageCheck(unittest.TestCase): ) self.assertFalse(result) - mock_open.reset_mock() mock_popen.reset_mock() mock_machine.reset_mock() only_amd64_image = di.DockerImage("path", "name", True) @@ -206,7 +197,6 @@ class TestDockerImageCheck(unittest.TestCase): result, _ = di.build_and_push_one_image( only_amd64_image, "version", "", True, True ) - mock_open.assert_called_once() mock_popen.assert_called_once() mock_machine.assert_called_once() self.assertIn( From 20f8cf233bd6aaf3e4380e0ac7372f5a765335b4 Mon Sep 17 00:00:00 2001 From: Suzy Wang Date: Thu, 9 Feb 2023 19:50:45 +0000 Subject: [PATCH 20/75] remove comma --- CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 417a58771d5..b422d7d807b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -477,9 +477,9 @@ enable_testing() # Enable for tests without binary option(ENABLE_OPENSSL "This option performs a build with OpenSSL. NOTE! This option is insecure and should never be used. By default, ClickHouse uses and only supports BoringSSL" OFF) if (ARCH_S390X) - set(ENABLE_OPENSSL_DYNAMIC_DEFAULT, ON) + set(ENABLE_OPENSSL_DYNAMIC_DEFAULT ON) else () - set(ENABLE_OPENSSL_DYNAMIC_DEFAULT, OFF) + set(ENABLE_OPENSSL_DYNAMIC_DEFAULT OFF) endif () option(ENABLE_OPENSSL_DYNAMIC "This option removes SSL from ClickHouse and will link to the OpenSSL version supplied by OS." ${ENABLE_OPENSSL_DYNAMIC_DEFAULT}) From d0f5b6efb5ed3a5d96204bad94818b5304acbebf Mon Sep 17 00:00:00 2001 From: "Mikhail f. Shiryaev" Date: Thu, 9 Feb 2023 21:18:01 +0100 Subject: [PATCH 21/75] Use both release_pr and merged_pr as additional cache --- tests/ci/docker_images_check.py | 24 +++++++++++++----------- tests/ci/docker_test.py | 17 ++++++++++------- 2 files changed, 23 insertions(+), 18 deletions(-) diff --git a/tests/ci/docker_images_check.py b/tests/ci/docker_images_check.py index d6b2edbcd2b..d5d1b1a1085 100644 --- a/tests/ci/docker_images_check.py +++ b/tests/ci/docker_images_check.py @@ -213,7 +213,7 @@ def build_and_push_dummy_image( def build_and_push_one_image( image: DockerImage, version_string: str, - additional_cache: str, + additional_cache: List[str], push: bool, child: bool, ) -> Tuple[bool, Path]: @@ -241,11 +241,9 @@ def build_and_push_one_image( f"--cache-from type=registry,ref={image.repo}:{version_string} " f"--cache-from type=registry,ref={image.repo}:latest" ) - if additional_cache: - cache_from = ( - f"{cache_from} " - f"--cache-from type=registry,ref={image.repo}:{additional_cache}" - ) + for tag in additional_cache: + assert tag + cache_from = f"{cache_from} --cache-from type=registry,ref={image.repo}:{tag}" cmd = ( "docker buildx build --builder default " @@ -273,7 +271,7 @@ def build_and_push_one_image( def process_single_image( image: DockerImage, versions: List[str], - additional_cache: str, + additional_cache: List[str], push: bool, child: bool, ) -> TestResults: @@ -317,7 +315,7 @@ def process_single_image( def process_image_with_parents( image: DockerImage, versions: List[str], - additional_cache: str, + additional_cache: List[str], push: bool, child: bool = False, ) -> TestResults: @@ -437,9 +435,13 @@ def main(): result_images = {} test_results = [] # type: TestResults - additional_cache = "" - if pr_info.release_pr or pr_info.merged_pr: - additional_cache = str(pr_info.release_pr or pr_info.merged_pr) + additional_cache = [] # type: List[str] + if pr_info.release_pr: + logging.info("Use %s as additional cache tag", pr_info.release_pr) + additional_cache.append(str(pr_info.release_pr)) + if pr_info.merged_pr: + logging.info("Use %s as additional cache tag", pr_info.merged_pr) + additional_cache.append(str(pr_info.merged_pr)) for image in changed_images: # If we are in backport PR, then pr_info.release_pr is defined diff --git a/tests/ci/docker_test.py b/tests/ci/docker_test.py index c1f650842e2..9d68f436439 100644 --- a/tests/ci/docker_test.py +++ b/tests/ci/docker_test.py @@ -123,7 +123,7 @@ class TestDockerImageCheck(unittest.TestCase): mock_popen.return_value.__enter__.return_value.wait.return_value = 0 image = di.DockerImage("path", "name", False, gh_repo_path="") - result, _ = di.build_and_push_one_image(image, "version", "", True, True) + result, _ = di.build_and_push_one_image(image, "version", [], True, True) mock_popen.assert_called_once() mock_machine.assert_not_called() self.assertIn( @@ -140,7 +140,7 @@ class TestDockerImageCheck(unittest.TestCase): mock_machine.reset_mock() mock_popen.return_value.__enter__.return_value.wait.return_value = 0 - result, _ = di.build_and_push_one_image(image, "version2", "", False, True) + result, _ = di.build_and_push_one_image(image, "version2", [], False, True) mock_popen.assert_called_once() mock_machine.assert_not_called() self.assertIn( @@ -157,7 +157,7 @@ class TestDockerImageCheck(unittest.TestCase): mock_popen.reset_mock() mock_machine.reset_mock() mock_popen.return_value.__enter__.return_value.wait.return_value = 1 - result, _ = di.build_and_push_one_image(image, "version2", "", False, False) + result, _ = di.build_and_push_one_image(image, "version2", [], False, False) mock_popen.assert_called_once() mock_machine.assert_not_called() self.assertIn( @@ -174,7 +174,7 @@ class TestDockerImageCheck(unittest.TestCase): mock_machine.reset_mock() mock_popen.return_value.__enter__.return_value.wait.return_value = 1 result, _ = di.build_and_push_one_image( - image, "version2", "cached-version", False, False + image, "version2", ["cached-version", "another-cached"], False, False ) mock_popen.assert_called_once() mock_machine.assert_not_called() @@ -184,6 +184,7 @@ class TestDockerImageCheck(unittest.TestCase): "--tag name:version2 --cache-from type=registry,ref=name:version2 " "--cache-from type=registry,ref=name:latest " "--cache-from type=registry,ref=name:cached-version " + "--cache-from type=registry,ref=name:another-cached " "--cache-to type=inline,mode=max --progress plain path", mock_popen.call_args.args, ) @@ -195,7 +196,7 @@ class TestDockerImageCheck(unittest.TestCase): mock_popen.return_value.__enter__.return_value.wait.return_value = 0 result, _ = di.build_and_push_one_image( - only_amd64_image, "version", "", True, True + only_amd64_image, "version", [], True, True ) mock_popen.assert_called_once() mock_machine.assert_called_once() @@ -206,12 +207,14 @@ class TestDockerImageCheck(unittest.TestCase): ) self.assertTrue(result) result, _ = di.build_and_push_one_image( - only_amd64_image, "version", "", False, True + only_amd64_image, "version", [], False, True ) self.assertIn( "docker pull ubuntu:20.04; docker tag ubuntu:20.04 name:version; ", mock_popen.call_args.args, ) + with self.assertRaises(AssertionError): + result, _ = di.build_and_push_one_image(image, "version", [""], False, True) @patch("docker_images_check.build_and_push_one_image") def test_process_image_with_parents(self, mock_build): @@ -223,7 +226,7 @@ class TestDockerImageCheck(unittest.TestCase): # We use list to have determined order of image builgings images = [im4, im1, im3, im2, im1] test_results = [ - di.process_image_with_parents(im, ["v1", "v2", "latest"], "", True) + di.process_image_with_parents(im, ["v1", "v2", "latest"], [], True) for im in images ] # The time is random, so we check it's not None and greater than 0, From 1c2a52c57be412b6991b90e4f140361527f29f5d Mon Sep 17 00:00:00 2001 From: Suzy Wang Date: Fri, 10 Feb 2023 10:09:24 -0500 Subject: [PATCH 22/75] Update src/Storages/StorageS3Cluster.cpp --- src/Storages/StorageS3Cluster.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Storages/StorageS3Cluster.cpp b/src/Storages/StorageS3Cluster.cpp index d6858b6ac74..75aca759103 100644 --- a/src/Storages/StorageS3Cluster.cpp +++ b/src/Storages/StorageS3Cluster.cpp @@ -11,7 +11,6 @@ #include #include #include -#include #include #include #include From ebb41504c02fee4dc1a24c94613985760120d841 Mon Sep 17 00:00:00 2001 From: "Mikhail f. Shiryaev" Date: Sun, 12 Feb 2023 14:55:16 +0100 Subject: [PATCH 23/75] Move copy to the end for parallel image building --- docker/packager/binary/Dockerfile | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docker/packager/binary/Dockerfile b/docker/packager/binary/Dockerfile index 60208b5068d..ea985df975a 100644 --- a/docker/packager/binary/Dockerfile +++ b/docker/packager/binary/Dockerfile @@ -42,7 +42,6 @@ RUN git clone --depth 1 https://github.com/tpoechtrager/cctools-port.git \ FROM clickhouse/test-util:$FROM_TAG ENV CC=clang-${LLVM_VERSION} ENV CXX=clang++-${LLVM_VERSION} -COPY --from=cctools /cctools /cctools # Rust toolchain and libraries ENV RUSTUP_HOME=/rust/rustup @@ -103,6 +102,8 @@ RUN curl -Lo /usr/bin/clang-tidy-cache \ "https://raw.githubusercontent.com/matus-chochlik/ctcache/$CLANG_TIDY_SHA1/clang-tidy-cache" \ && chmod +x /usr/bin/clang-tidy-cache +COPY --from=cctools /cctools /cctools + RUN mkdir /workdir && chmod 777 /workdir WORKDIR /workdir From 6e9dc2527fe00c2960492b8bf2bfc93281136218 Mon Sep 17 00:00:00 2001 From: mateng0915 Date: Mon, 13 Feb 2023 11:43:01 +0800 Subject: [PATCH 24/75] fixed review comments --- src/Server/ReplicasStatusHandler.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Server/ReplicasStatusHandler.cpp b/src/Server/ReplicasStatusHandler.cpp index a31a368e83d..8c0ab0c1a3b 100644 --- a/src/Server/ReplicasStatusHandler.cpp +++ b/src/Server/ReplicasStatusHandler.cpp @@ -59,7 +59,7 @@ void ReplicasStatusHandler::handleRequest(HTTPServerRequest & request, HTTPServe time_t absolute_delay = 0; time_t relative_delay = 0; - if(!table_replicated->isTableReadOnly()) + if (!table_replicated->isTableReadOnly()) { table_replicated->getReplicaDelays(absolute_delay, relative_delay); @@ -69,12 +69,12 @@ void ReplicasStatusHandler::handleRequest(HTTPServerRequest & request, HTTPServe message << backQuoteIfNeed(db.first) << "." << backQuoteIfNeed(iterator->name()) << ":\tAbsolute delay: " << absolute_delay << ". Relative delay: " << relative_delay << ".\n"; - - } else { + } + else + { message << backQuoteIfNeed(db.first) << "." << backQuoteIfNeed(iterator->name()) << ":\tis readonly. \n"; } - } } From fc7c90cd94a02687f3784e3b3044bff0d9a6af96 Mon Sep 17 00:00:00 2001 From: Robert Schulze Date: Mon, 13 Feb 2023 09:00:23 +0000 Subject: [PATCH 25/75] Run clang-format over poco xml --- .../include/Poco/DOM/AbstractContainerNode.h | 106 +- base/poco/XML/include/Poco/DOM/AbstractNode.h | 194 +-- base/poco/XML/include/Poco/DOM/Attr.h | 308 ++--- base/poco/XML/include/Poco/DOM/AttrMap.h | 75 +- base/poco/XML/include/Poco/DOM/AutoPtr.h | 13 +- base/poco/XML/include/Poco/DOM/CDATASection.h | 113 +- .../poco/XML/include/Poco/DOM/CharacterData.h | 189 +-- .../XML/include/Poco/DOM/ChildNodesList.h | 55 +- base/poco/XML/include/Poco/DOM/Comment.h | 59 +- base/poco/XML/include/Poco/DOM/DOMBuilder.h | 166 +-- base/poco/XML/include/Poco/DOM/DOMException.h | 167 +-- .../XML/include/Poco/DOM/DOMImplementation.h | 107 +- base/poco/XML/include/Poco/DOM/DOMObject.h | 151 +-- base/poco/XML/include/Poco/DOM/DOMParser.h | 173 +-- .../poco/XML/include/Poco/DOM/DOMSerializer.h | 193 +-- base/poco/XML/include/Poco/DOM/DOMWriter.h | 199 +-- base/poco/XML/include/Poco/DOM/DTDMap.h | 79 +- base/poco/XML/include/Poco/DOM/Document.h | 511 +++---- .../poco/XML/include/Poco/DOM/DocumentEvent.h | 73 +- .../XML/include/Poco/DOM/DocumentFragment.h | 111 +- base/poco/XML/include/Poco/DOM/DocumentType.h | 195 +-- base/poco/XML/include/Poco/DOM/Element.h | 382 +++--- .../include/Poco/DOM/ElementsByTagNameList.h | 113 +- base/poco/XML/include/Poco/DOM/Entity.h | 200 +-- .../XML/include/Poco/DOM/EntityReference.h | 89 +- base/poco/XML/include/Poco/DOM/Event.h | 361 ++--- .../XML/include/Poco/DOM/EventDispatcher.h | 137 +- .../XML/include/Poco/DOM/EventException.h | 105 +- .../poco/XML/include/Poco/DOM/EventListener.h | 57 +- base/poco/XML/include/Poco/DOM/EventTarget.h | 95 +- .../poco/XML/include/Poco/DOM/MutationEvent.h | 248 ++-- base/poco/XML/include/Poco/DOM/NamedNodeMap.h | 129 +- base/poco/XML/include/Poco/DOM/Node.h | 513 +++---- base/poco/XML/include/Poco/DOM/NodeAppender.h | 106 +- base/poco/XML/include/Poco/DOM/NodeFilter.h | 235 ++-- base/poco/XML/include/Poco/DOM/NodeIterator.h | 279 ++-- base/poco/XML/include/Poco/DOM/NodeList.h | 67 +- base/poco/XML/include/Poco/DOM/Notation.h | 129 +- .../include/Poco/DOM/ProcessingInstruction.h | 141 +- base/poco/XML/include/Poco/DOM/Text.h | 101 +- base/poco/XML/include/Poco/DOM/TreeWalker.h | 365 ++--- base/poco/XML/include/Poco/SAX/Attributes.h | 183 +-- .../XML/include/Poco/SAX/AttributesImpl.h | 582 ++++---- .../XML/include/Poco/SAX/ContentHandler.h | 424 +++--- base/poco/XML/include/Poco/SAX/DTDHandler.h | 117 +- base/poco/XML/include/Poco/SAX/DeclHandler.h | 127 +- .../XML/include/Poco/SAX/DefaultHandler.h | 110 +- .../XML/include/Poco/SAX/EntityResolver.h | 115 +- .../XML/include/Poco/SAX/EntityResolverImpl.h | 99 +- base/poco/XML/include/Poco/SAX/ErrorHandler.h | 129 +- base/poco/XML/include/Poco/SAX/InputSource.h | 281 ++-- .../XML/include/Poco/SAX/LexicalHandler.h | 193 +-- base/poco/XML/include/Poco/SAX/Locator.h | 149 ++- base/poco/XML/include/Poco/SAX/LocatorImpl.h | 119 +- .../XML/include/Poco/SAX/NamespaceSupport.h | 333 ++--- base/poco/XML/include/Poco/SAX/SAXException.h | 301 +++-- base/poco/XML/include/Poco/SAX/SAXParser.h | 169 +-- .../XML/include/Poco/SAX/WhitespaceFilter.h | 107 +- base/poco/XML/include/Poco/SAX/XMLFilter.h | 67 +- .../poco/XML/include/Poco/SAX/XMLFilterImpl.h | 208 +-- base/poco/XML/include/Poco/SAX/XMLReader.h | 353 ++--- base/poco/XML/include/Poco/XML/Content.h | 65 +- base/poco/XML/include/Poco/XML/Name.h | 231 ++-- base/poco/XML/include/Poco/XML/NamePool.h | 101 +- .../XML/include/Poco/XML/NamespaceStrategy.h | 163 +-- base/poco/XML/include/Poco/XML/ParserEngine.h | 728 +++++----- base/poco/XML/include/Poco/XML/QName.h | 235 ++-- base/poco/XML/include/Poco/XML/ValueTraits.h | 115 +- base/poco/XML/include/Poco/XML/XML.h | 30 +- base/poco/XML/include/Poco/XML/XMLException.h | 17 +- base/poco/XML/include/Poco/XML/XMLStream.h | 31 +- .../XML/include/Poco/XML/XMLStreamParser.h | 1173 ++++++++--------- .../Poco/XML/XMLStreamParserException.h | 61 +- base/poco/XML/include/Poco/XML/XMLString.h | 61 +- base/poco/XML/include/Poco/XML/XMLWriter.h | 704 +++++----- base/poco/XML/include/Poco/XML/expat.h | 455 +++---- .../XML/include/Poco/XML/expat_external.h | 70 +- base/poco/XML/src/asciitab.h | 62 +- base/poco/XML/src/expat_config.h | 6 +- base/poco/XML/src/iasciitab.h | 62 +- base/poco/XML/src/internal.h | 83 +- base/poco/XML/src/latin1tab.h | 62 +- base/poco/XML/src/nametab.h | 152 +-- base/poco/XML/src/siphash.h | 288 ++-- base/poco/XML/src/utf8tab.h | 62 +- base/poco/XML/src/xmlrole.h | 148 +-- base/poco/XML/src/xmltok.h | 224 ++-- base/poco/XML/src/xmltok_impl.h | 77 +- 88 files changed, 8470 insertions(+), 8251 deletions(-) diff --git a/base/poco/XML/include/Poco/DOM/AbstractContainerNode.h b/base/poco/XML/include/Poco/DOM/AbstractContainerNode.h index e0f7893b335..dcff2eda01e 100644 --- a/base/poco/XML/include/Poco/DOM/AbstractContainerNode.h +++ b/base/poco/XML/include/Poco/DOM/AbstractContainerNode.h @@ -18,61 +18,69 @@ #define DOM_AbstractContainerNode_INCLUDED -#include "Poco/XML/XML.h" #include "Poco/DOM/AbstractNode.h" +#include "Poco/XML/XML.h" -namespace Poco { -namespace XML { - - -class XML_API AbstractContainerNode: public AbstractNode - /// AbstractContainerNode is an implementation of Node - /// that stores and manages child nodes. - /// - /// Child nodes are organized in a single linked list. +namespace Poco +{ +namespace XML { -public: - // Node - Node* firstChild() const; - Node* lastChild() const; - Node* insertBefore(Node* newChild, Node* refChild); - Node* replaceChild(Node* newChild, Node* oldChild); - Node* removeChild(Node* oldChild); - Node* appendChild(Node* newChild); - bool hasChildNodes() const; - bool hasAttributes() const; - Node* getNodeByPath(const XMLString& path) const; - Node* getNodeByPathNS(const XMLString& path, const NSMap& nsMap) const; - -protected: - AbstractContainerNode(Document* pOwnerDocument); - AbstractContainerNode(Document* pOwnerDocument, const AbstractContainerNode& node); - ~AbstractContainerNode(); - - void dispatchNodeRemovedFromDocument(); - void dispatchNodeInsertedIntoDocument(); - - static const Node* findNode(XMLString::const_iterator& it, const XMLString::const_iterator& end, const Node* pNode, const NSMap* pNSMap, bool& indexBound); - static const Node* findElement(const XMLString& name, const Node* pNode, const NSMap* pNSMap); - static const Node* findElement(int index, const Node* pNode, const NSMap* pNSMap); - static const Node* findElement(const XMLString& attr, const XMLString& value, const Node* pNode, const NSMap* pNSMap); - static const Attr* findAttribute(const XMLString& name, const Node* pNode, const NSMap* pNSMap); - bool hasAttributeValue(const XMLString& name, const XMLString& value, const NSMap* pNSMap) const; - static bool namesAreEqual(const Node* pNode1, const Node* pNode2, const NSMap* pNSMap); - static bool namesAreEqual(const Node* pNode, const XMLString& name, const NSMap* pNSMap); - - static const XMLString WILDCARD; - -private: - AbstractNode* _pFirstChild; - - friend class AbstractNode; - friend class NodeAppender; -}; -} } // namespace Poco::XML + class XML_API AbstractContainerNode : public AbstractNode + /// AbstractContainerNode is an implementation of Node + /// that stores and manages child nodes. + /// + /// Child nodes are organized in a single linked list. + { + public: + // Node + Node * firstChild() const; + Node * lastChild() const; + Node * insertBefore(Node * newChild, Node * refChild); + Node * replaceChild(Node * newChild, Node * oldChild); + Node * removeChild(Node * oldChild); + Node * appendChild(Node * newChild); + bool hasChildNodes() const; + bool hasAttributes() const; + Node * getNodeByPath(const XMLString & path) const; + Node * getNodeByPathNS(const XMLString & path, const NSMap & nsMap) const; + + protected: + AbstractContainerNode(Document * pOwnerDocument); + AbstractContainerNode(Document * pOwnerDocument, const AbstractContainerNode & node); + ~AbstractContainerNode(); + + void dispatchNodeRemovedFromDocument(); + void dispatchNodeInsertedIntoDocument(); + + static const Node * findNode( + XMLString::const_iterator & it, + const XMLString::const_iterator & end, + const Node * pNode, + const NSMap * pNSMap, + bool & indexBound); + static const Node * findElement(const XMLString & name, const Node * pNode, const NSMap * pNSMap); + static const Node * findElement(int index, const Node * pNode, const NSMap * pNSMap); + static const Node * findElement(const XMLString & attr, const XMLString & value, const Node * pNode, const NSMap * pNSMap); + static const Attr * findAttribute(const XMLString & name, const Node * pNode, const NSMap * pNSMap); + bool hasAttributeValue(const XMLString & name, const XMLString & value, const NSMap * pNSMap) const; + static bool namesAreEqual(const Node * pNode1, const Node * pNode2, const NSMap * pNSMap); + static bool namesAreEqual(const Node * pNode, const XMLString & name, const NSMap * pNSMap); + + static const XMLString WILDCARD; + + private: + AbstractNode * _pFirstChild; + + friend class AbstractNode; + friend class NodeAppender; + }; + + +} +} // namespace Poco::XML #endif // DOM_AbstractContainerNode_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/AbstractNode.h b/base/poco/XML/include/Poco/DOM/AbstractNode.h index cedcc73920b..91c3b13c628 100644 --- a/base/poco/XML/include/Poco/DOM/AbstractNode.h +++ b/base/poco/XML/include/Poco/DOM/AbstractNode.h @@ -18,108 +18,112 @@ #define DOM_AbstractNode_INCLUDED -#include "Poco/XML/XML.h" -#include "Poco/DOM/Node.h" #include "Poco/DOM/MutationEvent.h" +#include "Poco/DOM/Node.h" +#include "Poco/XML/XML.h" #include "Poco/XML/XMLString.h" -namespace Poco { -namespace XML { - - -class AbstractContainerNode; -class Attr; -class EventDispatcher; - - -class XML_API AbstractNode: public Node - /// AbstractNode provides a basic implementation - /// of the Node interface for all types of nodes - /// that do not contain other nodes. +namespace Poco +{ +namespace XML { -public: - // Node - const XMLString& nodeName() const; - const XMLString& getNodeValue() const; - void setNodeValue(const XMLString& value); - Node* parentNode() const; - NodeList* childNodes() const; - Node* firstChild() const; - Node* lastChild() const; - Node* previousSibling() const; - Node* nextSibling() const; - NamedNodeMap* attributes() const; - Document* ownerDocument() const; - Node* insertBefore(Node* newChild, Node* refChild); - Node* replaceChild(Node* newChild, Node* oldChild); - Node* removeChild(Node* oldChild); - Node* appendChild(Node* newChild); - bool hasChildNodes() const; - Node* cloneNode(bool deep) const; - void normalize(); - bool isSupported(const XMLString& feature, const XMLString& version) const; - const XMLString& namespaceURI() const; - XMLString prefix() const; - const XMLString& localName() const; - bool hasAttributes() const; - - // EventTarget - void addEventListener(const XMLString& type, EventListener* listener, bool useCapture); - void removeEventListener(const XMLString& type, EventListener* listener, bool useCapture); - bool dispatchEvent(Event* evt); - - // Extensions - XMLString innerText() const; - Node* getNodeByPath(const XMLString& path) const; - Node* getNodeByPathNS(const XMLString& path, const NSMap& nsMap) const; - - virtual void autoRelease(); - -protected: - AbstractNode(Document* pOwnerDocument); - AbstractNode(Document* pOwnerDocument, const AbstractNode& node); - ~AbstractNode(); - - virtual Node* copyNode(bool deep, Document* pOwnerDocument) const = 0; - - virtual bool events() const; - virtual bool eventsSuspended() const; - void captureEvent(Event* evt); - void bubbleEvent(Event* evt); - void dispatchSubtreeModified(); - void dispatchNodeInserted(); - void dispatchNodeRemoved(); - virtual void dispatchNodeRemovedFromDocument(); - virtual void dispatchNodeInsertedIntoDocument(); - void dispatchAttrModified(Attr* pAttr, MutationEvent::AttrChangeType changeType, const XMLString& prevValue, const XMLString& newValue); - void dispatchCharacterDataModified(const XMLString& prevValue, const XMLString& newValue); - void setOwnerDocument(Document* pOwnerDocument); - - static const XMLString EMPTY_STRING; - -private: - AbstractNode(); - - AbstractContainerNode* _pParent; - AbstractNode* _pNext; - Document* _pOwner; - EventDispatcher* _pEventDispatcher; - - static const XMLString NODE_NAME; - - friend class AbstractContainerNode; - friend class Document; - friend class DocumentFragment; - friend class Element; - friend class Attr; - friend class CharacterData; - friend class DOMBuilder; - friend class NodeAppender; -}; -} } // namespace Poco::XML + class AbstractContainerNode; + class Attr; + class EventDispatcher; + + + class XML_API AbstractNode : public Node + /// AbstractNode provides a basic implementation + /// of the Node interface for all types of nodes + /// that do not contain other nodes. + { + public: + // Node + const XMLString & nodeName() const; + const XMLString & getNodeValue() const; + void setNodeValue(const XMLString & value); + Node * parentNode() const; + NodeList * childNodes() const; + Node * firstChild() const; + Node * lastChild() const; + Node * previousSibling() const; + Node * nextSibling() const; + NamedNodeMap * attributes() const; + Document * ownerDocument() const; + Node * insertBefore(Node * newChild, Node * refChild); + Node * replaceChild(Node * newChild, Node * oldChild); + Node * removeChild(Node * oldChild); + Node * appendChild(Node * newChild); + bool hasChildNodes() const; + Node * cloneNode(bool deep) const; + void normalize(); + bool isSupported(const XMLString & feature, const XMLString & version) const; + const XMLString & namespaceURI() const; + XMLString prefix() const; + const XMLString & localName() const; + bool hasAttributes() const; + + // EventTarget + void addEventListener(const XMLString & type, EventListener * listener, bool useCapture); + void removeEventListener(const XMLString & type, EventListener * listener, bool useCapture); + bool dispatchEvent(Event * evt); + + // Extensions + XMLString innerText() const; + Node * getNodeByPath(const XMLString & path) const; + Node * getNodeByPathNS(const XMLString & path, const NSMap & nsMap) const; + + virtual void autoRelease(); + + protected: + AbstractNode(Document * pOwnerDocument); + AbstractNode(Document * pOwnerDocument, const AbstractNode & node); + ~AbstractNode(); + + virtual Node * copyNode(bool deep, Document * pOwnerDocument) const = 0; + + virtual bool events() const; + virtual bool eventsSuspended() const; + void captureEvent(Event * evt); + void bubbleEvent(Event * evt); + void dispatchSubtreeModified(); + void dispatchNodeInserted(); + void dispatchNodeRemoved(); + virtual void dispatchNodeRemovedFromDocument(); + virtual void dispatchNodeInsertedIntoDocument(); + void dispatchAttrModified( + Attr * pAttr, MutationEvent::AttrChangeType changeType, const XMLString & prevValue, const XMLString & newValue); + void dispatchCharacterDataModified(const XMLString & prevValue, const XMLString & newValue); + void setOwnerDocument(Document * pOwnerDocument); + + static const XMLString EMPTY_STRING; + + private: + AbstractNode(); + + AbstractContainerNode * _pParent; + AbstractNode * _pNext; + Document * _pOwner; + EventDispatcher * _pEventDispatcher; + + static const XMLString NODE_NAME; + + friend class AbstractContainerNode; + friend class Document; + friend class DocumentFragment; + friend class Element; + friend class Attr; + friend class CharacterData; + friend class DOMBuilder; + friend class NodeAppender; + }; + + +} +} // namespace Poco::XML #endif // DOM_AbstractNode_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/Attr.h b/base/poco/XML/include/Poco/DOM/Attr.h index 13ace7ecce4..98ba3543698 100644 --- a/base/poco/XML/include/Poco/DOM/Attr.h +++ b/base/poco/XML/include/Poco/DOM/Attr.h @@ -18,163 +18,173 @@ #define DOM_Attr_INCLUDED -#include "Poco/XML/XML.h" #include "Poco/DOM/AbstractNode.h" #include "Poco/DOM/Element.h" #include "Poco/XML/Name.h" +#include "Poco/XML/XML.h" -namespace Poco { -namespace XML { - - -class XML_API Attr: public AbstractNode - /// The Attr interface represents an attribute in an Element object. Typically - /// the allowable values for the attribute are defined in a document type definition. - /// - /// Attr objects inherit the Node interface, but since they are not actually - /// child nodes of the element they describe, the DOM does not consider them - /// part of the document tree. Thus, the Node attributes parentNode, previousSibling, - /// and nextSibling have a null value for Attr objects. The DOM takes the view - /// that attributes are properties of elements rather than having a separate - /// identity from the elements they are associated with; this should make it - /// more efficient to implement such features as default attributes associated - /// with all elements of a given type. Furthermore, Attr nodes may not be immediate - /// children of a DocumentFragment. However, they can be associated with Element - /// nodes contained within a DocumentFragment. In short, users and implementors - /// of the DOM need to be aware that Attr nodes have some things in common with - /// other objects inheriting the Node interface, but they also are quite distinct. - /// - /// The attribute's effective value is determined as follows: if this attribute - /// has been explicitly assigned any value, that value is the attribute's effective - /// value; otherwise, if there is a declaration for this attribute, and that - /// declaration includes a default value, then that default value is the attribute's - /// effective value; otherwise, the attribute does not exist on this element - /// in the structure model until it has been explicitly added. Note that the - /// nodeValue attribute on the Attr instance can also be used to retrieve the - /// string version of the attribute's value(s). - /// - /// In XML, where the value of an attribute can contain entity references, the - /// child nodes of the Attr node provide a representation in which entity references - /// are not expanded. These child nodes may be either Text or EntityReference - /// nodes. Because the attribute type may be unknown, there are no tokenized - /// attribute values. +namespace Poco { -public: - const XMLString& name() const; - /// Returns the name of this attribute. - - bool specified() const; - /// If this attribute was explicitly given a value in the original document, - /// this is true; otherwise, it is false. Note that the implementation is in - /// charge of this attribute, not the user. If the user changes the value of - /// the attribute (even if it ends up having the same value as the default value) - /// then the specified flag is automatically flipped to true. To re-specify - /// the attribute as the default value from the DTD, the user must delete the - /// attribute. The implementation will then make a new attribute available with - /// specified set to false and the default value (if one exists). - /// In summary: - /// - /// * If the attribute has an assigned value in the document then specified - /// is true, and the value is the assigned value. - /// * If the attribute has no assigned value in the document and has a default - /// value in the DTD, then specified is false, and the value is the default - /// value in the DTD. - /// * If the attribute has no assigned value in the document and has a value - /// of #IMPLIED in the DTD, then the attribute does not appear in the structure - /// model of the document. - /// * If the attribute is not associated to any element (i.e. because it - /// was just created or was obtained from some removal or cloning operation) - /// specified is true. - - const XMLString& value() const; - /// Returns the value of the attribute as a string. Character - /// and general entity references are replaced with their values. See also the - /// method getAttribute on the Element interface. - - const XMLString& getValue() const; - /// Returns the value of the attribute as a string. Character - /// and general entity references are replaced with their values. See also the - /// method getAttribute on the Element interface. - - void setValue(const XMLString& value); - /// Sets the value of the attribute as a string. - /// This creates a Text node with the unparsed contents of the string. - /// I.e. any characters that an XML processor would recognize as markup are - /// instead treated as literal text. See also the method setAttribute on the - /// Element interface. - - // DOM Level 2 - Element* ownerElement() const; - /// The Element node this attribute is attached to or null - /// if this attribute is not in use. - - // Node - Node* parentNode() const; - const XMLString& nodeName() const; - const XMLString& getNodeValue() const; - void setNodeValue(const XMLString& value); - unsigned short nodeType() const; - Node* previousSibling() const; - const XMLString& namespaceURI() const; - XMLString prefix() const; - const XMLString& localName() const; - - // Non-standard extensions - XMLString innerText() const; - -protected: - Attr(Document* pOwnerDocument, Element* pOwnerElement, const XMLString& namespaceURI, const XMLString& localName, const XMLString& qname, const XMLString& value, bool specified = true); - Attr(Document* pOwnerDocument, const Attr& attr); - ~Attr(); - - Node* copyNode(bool deep, Document* pOwnerDocument) const; - -private: - const Name& _name; - XMLString _value; - bool _specified; - - friend class Document; - friend class Element; - friend class DOMBuilder; -}; - - -// -// inlines -// -inline const XMLString& Attr::name() const +namespace XML { - return _name.qname(); + + + class XML_API Attr : public AbstractNode + /// The Attr interface represents an attribute in an Element object. Typically + /// the allowable values for the attribute are defined in a document type definition. + /// + /// Attr objects inherit the Node interface, but since they are not actually + /// child nodes of the element they describe, the DOM does not consider them + /// part of the document tree. Thus, the Node attributes parentNode, previousSibling, + /// and nextSibling have a null value for Attr objects. The DOM takes the view + /// that attributes are properties of elements rather than having a separate + /// identity from the elements they are associated with; this should make it + /// more efficient to implement such features as default attributes associated + /// with all elements of a given type. Furthermore, Attr nodes may not be immediate + /// children of a DocumentFragment. However, they can be associated with Element + /// nodes contained within a DocumentFragment. In short, users and implementors + /// of the DOM need to be aware that Attr nodes have some things in common with + /// other objects inheriting the Node interface, but they also are quite distinct. + /// + /// The attribute's effective value is determined as follows: if this attribute + /// has been explicitly assigned any value, that value is the attribute's effective + /// value; otherwise, if there is a declaration for this attribute, and that + /// declaration includes a default value, then that default value is the attribute's + /// effective value; otherwise, the attribute does not exist on this element + /// in the structure model until it has been explicitly added. Note that the + /// nodeValue attribute on the Attr instance can also be used to retrieve the + /// string version of the attribute's value(s). + /// + /// In XML, where the value of an attribute can contain entity references, the + /// child nodes of the Attr node provide a representation in which entity references + /// are not expanded. These child nodes may be either Text or EntityReference + /// nodes. Because the attribute type may be unknown, there are no tokenized + /// attribute values. + { + public: + const XMLString & name() const; + /// Returns the name of this attribute. + + bool specified() const; + /// If this attribute was explicitly given a value in the original document, + /// this is true; otherwise, it is false. Note that the implementation is in + /// charge of this attribute, not the user. If the user changes the value of + /// the attribute (even if it ends up having the same value as the default value) + /// then the specified flag is automatically flipped to true. To re-specify + /// the attribute as the default value from the DTD, the user must delete the + /// attribute. The implementation will then make a new attribute available with + /// specified set to false and the default value (if one exists). + /// In summary: + /// + /// * If the attribute has an assigned value in the document then specified + /// is true, and the value is the assigned value. + /// * If the attribute has no assigned value in the document and has a default + /// value in the DTD, then specified is false, and the value is the default + /// value in the DTD. + /// * If the attribute has no assigned value in the document and has a value + /// of #IMPLIED in the DTD, then the attribute does not appear in the structure + /// model of the document. + /// * If the attribute is not associated to any element (i.e. because it + /// was just created or was obtained from some removal or cloning operation) + /// specified is true. + + const XMLString & value() const; + /// Returns the value of the attribute as a string. Character + /// and general entity references are replaced with their values. See also the + /// method getAttribute on the Element interface. + + const XMLString & getValue() const; + /// Returns the value of the attribute as a string. Character + /// and general entity references are replaced with their values. See also the + /// method getAttribute on the Element interface. + + void setValue(const XMLString & value); + /// Sets the value of the attribute as a string. + /// This creates a Text node with the unparsed contents of the string. + /// I.e. any characters that an XML processor would recognize as markup are + /// instead treated as literal text. See also the method setAttribute on the + /// Element interface. + + // DOM Level 2 + Element * ownerElement() const; + /// The Element node this attribute is attached to or null + /// if this attribute is not in use. + + // Node + Node * parentNode() const; + const XMLString & nodeName() const; + const XMLString & getNodeValue() const; + void setNodeValue(const XMLString & value); + unsigned short nodeType() const; + Node * previousSibling() const; + const XMLString & namespaceURI() const; + XMLString prefix() const; + const XMLString & localName() const; + + // Non-standard extensions + XMLString innerText() const; + + protected: + Attr( + Document * pOwnerDocument, + Element * pOwnerElement, + const XMLString & namespaceURI, + const XMLString & localName, + const XMLString & qname, + const XMLString & value, + bool specified = true); + Attr(Document * pOwnerDocument, const Attr & attr); + ~Attr(); + + Node * copyNode(bool deep, Document * pOwnerDocument) const; + + private: + const Name & _name; + XMLString _value; + bool _specified; + + friend class Document; + friend class Element; + friend class DOMBuilder; + }; + + + // + // inlines + // + inline const XMLString & Attr::name() const + { + return _name.qname(); + } + + + inline const XMLString & Attr::value() const + { + return _value; + } + + + inline const XMLString & Attr::getValue() const + { + return _value; + } + + + inline bool Attr::specified() const + { + return _specified; + } + + + inline Element * Attr::ownerElement() const + { + return static_cast(_pParent); + } + + } - - -inline const XMLString& Attr::value() const -{ - return _value; -} - - -inline const XMLString& Attr::getValue() const -{ - return _value; -} - - -inline bool Attr::specified() const -{ - return _specified; -} - - -inline Element* Attr::ownerElement() const -{ - return static_cast(_pParent); -} - - -} } // namespace Poco::XML +} // namespace Poco::XML #endif // DOM_Attr_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/AttrMap.h b/base/poco/XML/include/Poco/DOM/AttrMap.h index 41f34fd6380..3c29d943064 100644 --- a/base/poco/XML/include/Poco/DOM/AttrMap.h +++ b/base/poco/XML/include/Poco/DOM/AttrMap.h @@ -18,48 +18,51 @@ #define DOM_AttrMap_INCLUDED -#include "Poco/XML/XML.h" #include "Poco/DOM/NamedNodeMap.h" +#include "Poco/XML/XML.h" -namespace Poco { -namespace XML { - - -class Element; - - -class XML_API AttrMap: public NamedNodeMap - // This implementation of NamedNodeMap is - // returned by Element::attributes() +namespace Poco +{ +namespace XML { -public: - Node* getNamedItem(const XMLString& name) const; - Node* setNamedItem(Node* arg); - Node* removeNamedItem(const XMLString& name); - Node* item(unsigned long index) const; - unsigned long length() const; - - Node* getNamedItemNS(const XMLString& namespaceURI, const XMLString& localName) const; - Node* setNamedItemNS(Node* arg); - Node* removeNamedItemNS(const XMLString& namespaceURI, const XMLString& localName); - - void autoRelease(); - -protected: - AttrMap(Element* pElement); - ~AttrMap(); - -private: - AttrMap(); - - Element* _pElement; - - friend class Element; -}; -} } // namespace Poco::XML + class Element; + + + class XML_API AttrMap : public NamedNodeMap + // This implementation of NamedNodeMap is + // returned by Element::attributes() + { + public: + Node * getNamedItem(const XMLString & name) const; + Node * setNamedItem(Node * arg); + Node * removeNamedItem(const XMLString & name); + Node * item(unsigned long index) const; + unsigned long length() const; + + Node * getNamedItemNS(const XMLString & namespaceURI, const XMLString & localName) const; + Node * setNamedItemNS(Node * arg); + Node * removeNamedItemNS(const XMLString & namespaceURI, const XMLString & localName); + + void autoRelease(); + + protected: + AttrMap(Element * pElement); + ~AttrMap(); + + private: + AttrMap(); + + Element * _pElement; + + friend class Element; + }; + + +} +} // namespace Poco::XML #endif // DOM_AttrMap_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/AutoPtr.h b/base/poco/XML/include/Poco/DOM/AutoPtr.h index 85f83d49f7d..f9d6b88dfe1 100644 --- a/base/poco/XML/include/Poco/DOM/AutoPtr.h +++ b/base/poco/XML/include/Poco/DOM/AutoPtr.h @@ -18,18 +18,21 @@ #define DOM_DOMAutoPtr_INCLUDED -#include "Poco/XML/XML.h" #include "Poco/AutoPtr.h" +#include "Poco/XML/XML.h" -namespace Poco { -namespace XML { +namespace Poco +{ +namespace XML +{ -using Poco::AutoPtr; + using Poco::AutoPtr; -} } // namespace Poco::XML +} +} // namespace Poco::XML #endif // DOM_DOMAutoPtr_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/CDATASection.h b/base/poco/XML/include/Poco/DOM/CDATASection.h index 7a0e82b18a1..ceb006ca8d4 100644 --- a/base/poco/XML/include/Poco/DOM/CDATASection.h +++ b/base/poco/XML/include/Poco/DOM/CDATASection.h @@ -18,67 +18,70 @@ #define DOM_CDATASection_INCLUDED -#include "Poco/XML/XML.h" #include "Poco/DOM/Text.h" +#include "Poco/XML/XML.h" -namespace Poco { -namespace XML { - - -class XML_API CDATASection: public Text - /// CDATA sections are used to escape blocks of text containing characters that - /// would otherwise be regarded as markup. The only delimiter that is recognized - /// in a CDATA section is the "]]>" string that ends the CDATA section. CDATA - /// sections cannot be nested. Their primary purpose is for including material - /// such as XML fragments, without needing to escape all the delimiters. - /// - /// The DOMString attribute of the Text node holds the text that is contained - /// by the CDATA section. Note that this may contain characters that need to - /// be escaped outside of CDATA sections and that, depending on the character - /// encoding ("charset") chosen for serialization, it may be impossible to write - /// out some characters as part of a CDATA section. - /// - /// The CDATASection interface inherits from the CharacterData interface through - /// the Text interface. Adjacent CDATASection nodes are not merged by use of - /// the normalize method on the Element interface. - /// - /// Note: Because no markup is recognized within a CDATASection, character numeric - /// references cannot be used as an escape mechanism when serializing. Therefore, - /// action needs to be taken when serializing a CDATASection with a character - /// encoding where some of the contained characters cannot be represented. Failure - /// to do so would not produce well-formed XML. - /// One potential solution in the serialization process is to end the CDATA - /// section before the character, output the character using a character reference - /// or entity reference, and open a new CDATA section for any further characters - /// in the text node. Note, however, that some code conversion libraries at - /// the time of writing do not return an error or exception when a character - /// is missing from the encoding, making the task of ensuring that data is not - /// corrupted on serialization more difficult. +namespace Poco +{ +namespace XML { -public: - // Text - Text* splitText(unsigned long offset); - - // Node - const XMLString& nodeName() const; - unsigned short nodeType() const; - -protected: - CDATASection(Document* pOwnerDocument, const XMLString& data); - CDATASection(Document* pOwnerDocument, const CDATASection& sec); - ~CDATASection(); - - Node* copyNode(bool deep, Document* pOwnerDocument) const; - -private: - static const XMLString NODE_NAME; - - friend class Document; -}; -} } // namespace Poco::XML + class XML_API CDATASection : public Text + /// CDATA sections are used to escape blocks of text containing characters that + /// would otherwise be regarded as markup. The only delimiter that is recognized + /// in a CDATA section is the "]]>" string that ends the CDATA section. CDATA + /// sections cannot be nested. Their primary purpose is for including material + /// such as XML fragments, without needing to escape all the delimiters. + /// + /// The DOMString attribute of the Text node holds the text that is contained + /// by the CDATA section. Note that this may contain characters that need to + /// be escaped outside of CDATA sections and that, depending on the character + /// encoding ("charset") chosen for serialization, it may be impossible to write + /// out some characters as part of a CDATA section. + /// + /// The CDATASection interface inherits from the CharacterData interface through + /// the Text interface. Adjacent CDATASection nodes are not merged by use of + /// the normalize method on the Element interface. + /// + /// Note: Because no markup is recognized within a CDATASection, character numeric + /// references cannot be used as an escape mechanism when serializing. Therefore, + /// action needs to be taken when serializing a CDATASection with a character + /// encoding where some of the contained characters cannot be represented. Failure + /// to do so would not produce well-formed XML. + /// One potential solution in the serialization process is to end the CDATA + /// section before the character, output the character using a character reference + /// or entity reference, and open a new CDATA section for any further characters + /// in the text node. Note, however, that some code conversion libraries at + /// the time of writing do not return an error or exception when a character + /// is missing from the encoding, making the task of ensuring that data is not + /// corrupted on serialization more difficult. + { + public: + // Text + Text * splitText(unsigned long offset); + + // Node + const XMLString & nodeName() const; + unsigned short nodeType() const; + + protected: + CDATASection(Document * pOwnerDocument, const XMLString & data); + CDATASection(Document * pOwnerDocument, const CDATASection & sec); + ~CDATASection(); + + Node * copyNode(bool deep, Document * pOwnerDocument) const; + + private: + static const XMLString NODE_NAME; + + friend class Document; + }; + + +} +} // namespace Poco::XML #endif // DOM_CDATASection_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/CharacterData.h b/base/poco/XML/include/Poco/DOM/CharacterData.h index af5697da7fd..00cace009d3 100644 --- a/base/poco/XML/include/Poco/DOM/CharacterData.h +++ b/base/poco/XML/include/Poco/DOM/CharacterData.h @@ -18,106 +18,109 @@ #define DOM_CharacterData_INCLUDED -#include "Poco/XML/XML.h" #include "Poco/DOM/AbstractNode.h" +#include "Poco/XML/XML.h" #include "Poco/XML/XMLString.h" -namespace Poco { -namespace XML { - - -class XML_API CharacterData: public AbstractNode - /// The CharacterData interface extends Node with a set of attributes and methods - /// for accessing character data in the DOM. For clarity this set is defined - /// here rather than on each object that uses these attributes and methods. - /// No DOM objects correspond directly to CharacterData, though Text and others - /// do inherit the interface from it. All offsets in this interface start from 0. - /// - /// Text strings in the DOM are represented in either UTF-8 (if XML_UNICODE_WCHAR_T is - /// not defined) or in UTF-16 (if XML_UNICODE_WCHAR_T is defined). - /// Indexing on character data is done in XMLChar units. +namespace Poco { -public: - const XMLString& data() const; - /// Returns the character data of the node that - /// implements the interface. - - const XMLString& getData() const; - /// Returns the character data of the node that - /// implements the interface. - - void setData(const XMLString& data); - /// Sets the character data of the node that - /// implements the interface. - - unsigned long length() const; - /// Returns the number of XMLChars that are available - /// through getData and substringData. This may have the - /// value zero. - - XMLString substringData(unsigned long offset, unsigned long count) const; - /// Extracts a range of data from the node. - /// If offset and count exceeds the length, then all - /// the characters to the end of the data are returned. - - void appendData(const XMLString& arg); - /// Append the string to the end of the character data - /// of the node. - - void insertData(unsigned long offset, const XMLString& arg); - /// Insert a string at the specified character offset. - - void deleteData(unsigned long offset, unsigned long count); - /// Remove a range of characters from the node. - - void replaceData(unsigned long offset, unsigned long count, const XMLString& arg); - /// Replace the characters starting at the specified character - /// offset with the specified string. - - // Non-standard extensions - XMLString trimmedData() const; - /// Returns the character data of that node with - /// all surrounding whitespace removed. - /// - /// This method is an extension to the W3C Document Object Model. - - // Node - const XMLString& getNodeValue() const; - void setNodeValue(const XMLString& value); - -protected: - CharacterData(Document* pOwnerDocument, const XMLString& data); - CharacterData(Document* pOwnerDocument, const CharacterData& data); - ~CharacterData(); - -private: - XMLString _data; -}; - - -// -// inlines -// -inline const XMLString& CharacterData::data() const +namespace XML { - return _data; + + + class XML_API CharacterData : public AbstractNode + /// The CharacterData interface extends Node with a set of attributes and methods + /// for accessing character data in the DOM. For clarity this set is defined + /// here rather than on each object that uses these attributes and methods. + /// No DOM objects correspond directly to CharacterData, though Text and others + /// do inherit the interface from it. All offsets in this interface start from 0. + /// + /// Text strings in the DOM are represented in either UTF-8 (if XML_UNICODE_WCHAR_T is + /// not defined) or in UTF-16 (if XML_UNICODE_WCHAR_T is defined). + /// Indexing on character data is done in XMLChar units. + { + public: + const XMLString & data() const; + /// Returns the character data of the node that + /// implements the interface. + + const XMLString & getData() const; + /// Returns the character data of the node that + /// implements the interface. + + void setData(const XMLString & data); + /// Sets the character data of the node that + /// implements the interface. + + unsigned long length() const; + /// Returns the number of XMLChars that are available + /// through getData and substringData. This may have the + /// value zero. + + XMLString substringData(unsigned long offset, unsigned long count) const; + /// Extracts a range of data from the node. + /// If offset and count exceeds the length, then all + /// the characters to the end of the data are returned. + + void appendData(const XMLString & arg); + /// Append the string to the end of the character data + /// of the node. + + void insertData(unsigned long offset, const XMLString & arg); + /// Insert a string at the specified character offset. + + void deleteData(unsigned long offset, unsigned long count); + /// Remove a range of characters from the node. + + void replaceData(unsigned long offset, unsigned long count, const XMLString & arg); + /// Replace the characters starting at the specified character + /// offset with the specified string. + + // Non-standard extensions + XMLString trimmedData() const; + /// Returns the character data of that node with + /// all surrounding whitespace removed. + /// + /// This method is an extension to the W3C Document Object Model. + + // Node + const XMLString & getNodeValue() const; + void setNodeValue(const XMLString & value); + + protected: + CharacterData(Document * pOwnerDocument, const XMLString & data); + CharacterData(Document * pOwnerDocument, const CharacterData & data); + ~CharacterData(); + + private: + XMLString _data; + }; + + + // + // inlines + // + inline const XMLString & CharacterData::data() const + { + return _data; + } + + + inline const XMLString & CharacterData::getData() const + { + return _data; + } + + + inline unsigned long CharacterData::length() const + { + return (unsigned long)_data.length(); + } + + } - - -inline const XMLString& CharacterData::getData() const -{ - return _data; -} - - -inline unsigned long CharacterData::length() const -{ - return (unsigned long) _data.length(); -} - - -} } // namespace Poco::XML +} // namespace Poco::XML #endif // DOM_CharacterData_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/ChildNodesList.h b/base/poco/XML/include/Poco/DOM/ChildNodesList.h index aa7ece1db81..4946933dd22 100644 --- a/base/poco/XML/include/Poco/DOM/ChildNodesList.h +++ b/base/poco/XML/include/Poco/DOM/ChildNodesList.h @@ -18,38 +18,41 @@ #define DOM_ChildNodesList_INCLUDED -#include "Poco/XML/XML.h" #include "Poco/DOM/NodeList.h" +#include "Poco/XML/XML.h" -namespace Poco { -namespace XML { - - -class XML_API ChildNodesList: public NodeList - // This implementation of NodeList is returned - // by Node::getChildNodes(). +namespace Poco +{ +namespace XML { -public: - Node* item(unsigned long index) const; - unsigned long length() const; - - void autoRelease(); - -protected: - ChildNodesList(const Node* pParent); - ~ChildNodesList(); - -private: - ChildNodesList(); - - const Node* _pParent; - - friend class AbstractNode; -}; -} } // namespace Poco::XML + class XML_API ChildNodesList : public NodeList + // This implementation of NodeList is returned + // by Node::getChildNodes(). + { + public: + Node * item(unsigned long index) const; + unsigned long length() const; + + void autoRelease(); + + protected: + ChildNodesList(const Node * pParent); + ~ChildNodesList(); + + private: + ChildNodesList(); + + const Node * _pParent; + + friend class AbstractNode; + }; + + +} +} // namespace Poco::XML #endif // DOM_ChildNodesList_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/Comment.h b/base/poco/XML/include/Poco/DOM/Comment.h index d1de7930647..4953fb566aa 100644 --- a/base/poco/XML/include/Poco/DOM/Comment.h +++ b/base/poco/XML/include/Poco/DOM/Comment.h @@ -18,41 +18,44 @@ #define DOM_Comment_INCLUDED -#include "Poco/XML/XML.h" #include "Poco/DOM/CharacterData.h" +#include "Poco/XML/XML.h" #include "Poco/XML/XMLString.h" -namespace Poco { -namespace XML { - - -class XML_API Comment: public CharacterData - /// This interface inherits from CharacterData and represents the content of - /// a comment, i.e., all the characters between the starting ''. Note that this is the definition of a comment in XML, and, in practice, - /// HTML, although some HTML tools may implement the full SGML comment structure. +namespace Poco +{ +namespace XML { -public: - // Node - const XMLString& nodeName() const; - unsigned short nodeType() const; - -protected: - Comment(Document* pOwnerDocument, const XMLString& data); - Comment(Document* pOwnerDocument, const Comment& comment); - ~Comment(); - - Node* copyNode(bool deep, Document* pOwnerDocument) const; - -private: - static const XMLString NODE_NAME; - - friend class Document; -}; -} } // namespace Poco::XML + class XML_API Comment : public CharacterData + /// This interface inherits from CharacterData and represents the content of + /// a comment, i.e., all the characters between the starting ''. Note that this is the definition of a comment in XML, and, in practice, + /// HTML, although some HTML tools may implement the full SGML comment structure. + { + public: + // Node + const XMLString & nodeName() const; + unsigned short nodeType() const; + + protected: + Comment(Document * pOwnerDocument, const XMLString & data); + Comment(Document * pOwnerDocument, const Comment & comment); + ~Comment(); + + Node * copyNode(bool deep, Document * pOwnerDocument) const; + + private: + static const XMLString NODE_NAME; + + friend class Document; + }; + + +} +} // namespace Poco::XML #endif // DOM_Comment_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/DOMBuilder.h b/base/poco/XML/include/Poco/DOM/DOMBuilder.h index ad91da45f4d..c5fb98d9481 100644 --- a/base/poco/XML/include/Poco/DOM/DOMBuilder.h +++ b/base/poco/XML/include/Poco/DOM/DOMBuilder.h @@ -18,95 +18,99 @@ #define DOM_DOMBuilder_INCLUDED -#include "Poco/XML/XML.h" #include "Poco/SAX/ContentHandler.h" -#include "Poco/SAX/LexicalHandler.h" #include "Poco/SAX/DTDHandler.h" +#include "Poco/SAX/LexicalHandler.h" +#include "Poco/XML/XML.h" #include "Poco/XML/XMLString.h" -namespace Poco { -namespace XML { - - -class XMLReader; -class Document; -class InputSource; -class AbstractNode; -class AbstractContainerNode; -class NamePool; - - -class XML_API DOMBuilder: protected DTDHandler, protected ContentHandler, protected LexicalHandler - /// This class builds a tree representation of an - /// XML document, according to the W3C Document Object Model, Level 1 and 2 - /// specifications. - /// - /// The actual XML parsing is done by an XMLReader, which - /// must be supplied to the DOMBuilder. +namespace Poco +{ +namespace XML { -public: - DOMBuilder(XMLReader& xmlReader, NamePool* pNamePool = 0); - /// Creates a DOMBuilder using the given XMLReader. - /// If a NamePool is given, it becomes the Document's NamePool. - - virtual ~DOMBuilder(); - /// Destroys the DOMBuilder. - - virtual Document* parse(const XMLString& uri); - /// Parse an XML document from a location identified by an URI. - - virtual Document* parse(InputSource* pInputSource); - /// Parse an XML document from a location identified by an InputSource. - - virtual Document* parseMemoryNP(const char* xml, std::size_t size); - /// Parses an XML document from memory. - -protected: - // DTDHandler - void notationDecl(const XMLString& name, const XMLString* publicId, const XMLString* systemId); - void unparsedEntityDecl(const XMLString& name, const XMLString* publicId, const XMLString& systemId, const XMLString& notationName); - - // ContentHandler - void setDocumentLocator(const Locator* loc); - void startDocument(); - void endDocument(); - void startElement(const XMLString& uri, const XMLString& localName, const XMLString& qname, const Attributes& attributes); - void endElement(const XMLString& uri, const XMLString& localName, const XMLString& qname); - void characters(const XMLChar ch[], int start, int length); - void ignorableWhitespace(const XMLChar ch[], int start, int length); - void processingInstruction(const XMLString& target, const XMLString& data); - void startPrefixMapping(const XMLString& prefix, const XMLString& uri); - void endPrefixMapping(const XMLString& prefix); - void skippedEntity(const XMLString& name); - - // LexicalHandler - void startDTD(const XMLString& name, const XMLString& publicId, const XMLString& systemId); - void endDTD(); - void startEntity(const XMLString& name); - void endEntity(const XMLString& name); - void startCDATA(); - void endCDATA(); - void comment(const XMLChar ch[], int start, int length); - - void appendNode(AbstractNode* pNode); - - void setupParse(); - -private: - static const XMLString EMPTY_STRING; - - XMLReader& _xmlReader; - NamePool* _pNamePool; - Document* _pDocument; - AbstractContainerNode* _pParent; - AbstractNode* _pPrevious; - bool _inCDATA; - bool _namespaces; -}; -} } // namespace Poco::XML + class XMLReader; + class Document; + class InputSource; + class AbstractNode; + class AbstractContainerNode; + class NamePool; + + + class XML_API DOMBuilder : protected DTDHandler, protected ContentHandler, protected LexicalHandler + /// This class builds a tree representation of an + /// XML document, according to the W3C Document Object Model, Level 1 and 2 + /// specifications. + /// + /// The actual XML parsing is done by an XMLReader, which + /// must be supplied to the DOMBuilder. + { + public: + DOMBuilder(XMLReader & xmlReader, NamePool * pNamePool = 0); + /// Creates a DOMBuilder using the given XMLReader. + /// If a NamePool is given, it becomes the Document's NamePool. + + virtual ~DOMBuilder(); + /// Destroys the DOMBuilder. + + virtual Document * parse(const XMLString & uri); + /// Parse an XML document from a location identified by an URI. + + virtual Document * parse(InputSource * pInputSource); + /// Parse an XML document from a location identified by an InputSource. + + virtual Document * parseMemoryNP(const char * xml, std::size_t size); + /// Parses an XML document from memory. + + protected: + // DTDHandler + void notationDecl(const XMLString & name, const XMLString * publicId, const XMLString * systemId); + void + unparsedEntityDecl(const XMLString & name, const XMLString * publicId, const XMLString & systemId, const XMLString & notationName); + + // ContentHandler + void setDocumentLocator(const Locator * loc); + void startDocument(); + void endDocument(); + void startElement(const XMLString & uri, const XMLString & localName, const XMLString & qname, const Attributes & attributes); + void endElement(const XMLString & uri, const XMLString & localName, const XMLString & qname); + void characters(const XMLChar ch[], int start, int length); + void ignorableWhitespace(const XMLChar ch[], int start, int length); + void processingInstruction(const XMLString & target, const XMLString & data); + void startPrefixMapping(const XMLString & prefix, const XMLString & uri); + void endPrefixMapping(const XMLString & prefix); + void skippedEntity(const XMLString & name); + + // LexicalHandler + void startDTD(const XMLString & name, const XMLString & publicId, const XMLString & systemId); + void endDTD(); + void startEntity(const XMLString & name); + void endEntity(const XMLString & name); + void startCDATA(); + void endCDATA(); + void comment(const XMLChar ch[], int start, int length); + + void appendNode(AbstractNode * pNode); + + void setupParse(); + + private: + static const XMLString EMPTY_STRING; + + XMLReader & _xmlReader; + NamePool * _pNamePool; + Document * _pDocument; + AbstractContainerNode * _pParent; + AbstractNode * _pPrevious; + bool _inCDATA; + bool _namespaces; + }; + + +} +} // namespace Poco::XML #endif // DOM_DOMBuilder_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/DOMException.h b/base/poco/XML/include/Poco/DOM/DOMException.h index 456526f1116..7b77e360abc 100644 --- a/base/poco/XML/include/Poco/DOM/DOMException.h +++ b/base/poco/XML/include/Poco/DOM/DOMException.h @@ -22,91 +22,94 @@ #include "Poco/XML/XMLException.h" -namespace Poco { -namespace XML { - - -class XML_API DOMException: public XMLException - /// DOM operations only raise exceptions in "exceptional" circumstances, i.e., - /// when an operation is impossible to perform (either for logical reasons, - /// because data is lost, or because the implementation has become unstable). - /// In general, DOM methods return specific error values in ordinary processing - /// situations, such as out-of-bound errors when using NodeList. - /// - /// Implementations should raise other exceptions under other circumstances. - /// For example, implementations should raise an implementation-dependent exception - /// if a null argument is passed when null was not expected. +namespace Poco { -public: - enum - { - INDEX_SIZE_ERR = 1, /// index or size is negative or greater than allowed value - DOMSTRING_SIZE_ERR, /// the specified range of text does not fit into a DOMString (not used) - HIERARCHY_REQUEST_ERR, /// a node is inserted somewhere it doesn't belong - WRONG_DOCUMENT_ERR, /// a node is used in a different document than the one that created it - INVALID_CHARACTER_ERR, /// an invalid character is specified (not used) - NO_DATA_ALLOWED_ERR, /// data is specified for a node which does not support data - NO_MODIFICATION_ALLOWED_ERR, /// an attempt is made to modify an object where modifications are not allowed - NOT_FOUND_ERR, /// an attempt was made to reference a node in a context where it does not exist - NOT_SUPPORTED_ERR, /// the implementation does not support the type of object requested - INUSE_ATTRIBUTE_ERR, /// an attempt is made to add an attribute that is already in use elsewhere - INVALID_STATE_ERR, /// a parameter or an operation is not supported by the underlying object - SYNTAX_ERR, /// an invalid or illegal string is specified - INVALID_MODIFICATION_ERR, /// an attempt is made to modify the type of the underlying object - NAMESPACE_ERR, /// an attempt is made to create or change an object in a way which is incorrect with regard to namespaces - INVALID_ACCESS_ERR, /// an attempt is made to use an object that is not, or is no longer, usable - - _NUMBER_OF_MESSAGES - }; - - DOMException(unsigned short code); - /// Creates a DOMException with the given error code. - - DOMException(const DOMException& exc); - /// Creates a DOMException by copying another one. - - ~DOMException() noexcept; - /// Destroys the DOMException. - - DOMException& operator = (const DOMException& exc); - - const char* name() const noexcept; - /// Returns a static string describing the exception. - - const char* className() const noexcept; - /// Returns the name of the exception class. - - Poco::Exception* clone() const; - /// Creates an exact copy of the exception. - - void rethrow() const; - /// (Re)Throws the exception. - - unsigned short code() const; - /// Returns the DOM exception code. - -protected: - static const std::string& message(unsigned short code); - -private: - DOMException(); - - unsigned short _code; - - static const std::string MESSAGES[_NUMBER_OF_MESSAGES]; -}; - - -// -// inlines -// -inline unsigned short DOMException::code() const +namespace XML { - return _code; + + + class XML_API DOMException : public XMLException + /// DOM operations only raise exceptions in "exceptional" circumstances, i.e., + /// when an operation is impossible to perform (either for logical reasons, + /// because data is lost, or because the implementation has become unstable). + /// In general, DOM methods return specific error values in ordinary processing + /// situations, such as out-of-bound errors when using NodeList. + /// + /// Implementations should raise other exceptions under other circumstances. + /// For example, implementations should raise an implementation-dependent exception + /// if a null argument is passed when null was not expected. + { + public: + enum + { + INDEX_SIZE_ERR = 1, /// index or size is negative or greater than allowed value + DOMSTRING_SIZE_ERR, /// the specified range of text does not fit into a DOMString (not used) + HIERARCHY_REQUEST_ERR, /// a node is inserted somewhere it doesn't belong + WRONG_DOCUMENT_ERR, /// a node is used in a different document than the one that created it + INVALID_CHARACTER_ERR, /// an invalid character is specified (not used) + NO_DATA_ALLOWED_ERR, /// data is specified for a node which does not support data + NO_MODIFICATION_ALLOWED_ERR, /// an attempt is made to modify an object where modifications are not allowed + NOT_FOUND_ERR, /// an attempt was made to reference a node in a context where it does not exist + NOT_SUPPORTED_ERR, /// the implementation does not support the type of object requested + INUSE_ATTRIBUTE_ERR, /// an attempt is made to add an attribute that is already in use elsewhere + INVALID_STATE_ERR, /// a parameter or an operation is not supported by the underlying object + SYNTAX_ERR, /// an invalid or illegal string is specified + INVALID_MODIFICATION_ERR, /// an attempt is made to modify the type of the underlying object + NAMESPACE_ERR, /// an attempt is made to create or change an object in a way which is incorrect with regard to namespaces + INVALID_ACCESS_ERR, /// an attempt is made to use an object that is not, or is no longer, usable + + _NUMBER_OF_MESSAGES + }; + + DOMException(unsigned short code); + /// Creates a DOMException with the given error code. + + DOMException(const DOMException & exc); + /// Creates a DOMException by copying another one. + + ~DOMException() noexcept; + /// Destroys the DOMException. + + DOMException & operator=(const DOMException & exc); + + const char * name() const noexcept; + /// Returns a static string describing the exception. + + const char * className() const noexcept; + /// Returns the name of the exception class. + + Poco::Exception * clone() const; + /// Creates an exact copy of the exception. + + void rethrow() const; + /// (Re)Throws the exception. + + unsigned short code() const; + /// Returns the DOM exception code. + + protected: + static const std::string & message(unsigned short code); + + private: + DOMException(); + + unsigned short _code; + + static const std::string MESSAGES[_NUMBER_OF_MESSAGES]; + }; + + + // + // inlines + // + inline unsigned short DOMException::code() const + { + return _code; + } + + } - - -} } // namespace Poco::XML +} // namespace Poco::XML #endif // DOM_DOMException_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/DOMImplementation.h b/base/poco/XML/include/Poco/DOM/DOMImplementation.h index 0c2d7af1878..4479faf71c9 100644 --- a/base/poco/XML/include/Poco/DOM/DOMImplementation.h +++ b/base/poco/XML/include/Poco/DOM/DOMImplementation.h @@ -22,61 +22,64 @@ #include "Poco/XML/XMLString.h" -namespace Poco { -namespace XML { - - -class DocumentType; -class Document; -class NamePool; - - -class XML_API DOMImplementation - /// The DOMImplementation interface provides a number of methods for - /// performing operations that are independent of any particular instance - /// of the document object model. - /// In this implementation, DOMImplementation is implemented as a singleton. +namespace Poco +{ +namespace XML { -public: - DOMImplementation(); - /// Creates the DOMImplementation. - - ~DOMImplementation(); - /// Destroys the DOMImplementation. - - bool hasFeature(const XMLString& feature, const XMLString& version) const; - /// Tests if the DOM implementation implements a specific feature. - /// - /// The only supported features are "XML", version "1.0" and "Core", - /// "Events", "MutationEvents" and "Traversal", version "2.0". - - // DOM Level 2 - DocumentType* createDocumentType(const XMLString& name, const XMLString& publicId, const XMLString& systemId) const; - /// Creates an empty DocumentType node. Entity declarations and notations - /// are not made available. Entity reference expansions and default attribute - /// additions do not occur. - - Document* createDocument(const XMLString& namespaceURI, const XMLString& qualifiedName, DocumentType* doctype) const; - /// Creates an XML Document object of the specified type with its document element. - /// - /// Note: You can also create a Document directly using the new operator. - - static const DOMImplementation& instance(); - /// Returns a reference to the default DOMImplementation - /// object. - -private: - static const XMLString FEATURE_XML; - static const XMLString FEATURE_CORE; - static const XMLString FEATURE_EVENTS; - static const XMLString FEATURE_MUTATIONEVENTS; - static const XMLString FEATURE_TRAVERSAL; - static const XMLString VERSION_1_0; - static const XMLString VERSION_2_0; -}; -} } // namespace Poco::XML + class DocumentType; + class Document; + class NamePool; + + + class XML_API DOMImplementation + /// The DOMImplementation interface provides a number of methods for + /// performing operations that are independent of any particular instance + /// of the document object model. + /// In this implementation, DOMImplementation is implemented as a singleton. + { + public: + DOMImplementation(); + /// Creates the DOMImplementation. + + ~DOMImplementation(); + /// Destroys the DOMImplementation. + + bool hasFeature(const XMLString & feature, const XMLString & version) const; + /// Tests if the DOM implementation implements a specific feature. + /// + /// The only supported features are "XML", version "1.0" and "Core", + /// "Events", "MutationEvents" and "Traversal", version "2.0". + + // DOM Level 2 + DocumentType * createDocumentType(const XMLString & name, const XMLString & publicId, const XMLString & systemId) const; + /// Creates an empty DocumentType node. Entity declarations and notations + /// are not made available. Entity reference expansions and default attribute + /// additions do not occur. + + Document * createDocument(const XMLString & namespaceURI, const XMLString & qualifiedName, DocumentType * doctype) const; + /// Creates an XML Document object of the specified type with its document element. + /// + /// Note: You can also create a Document directly using the new operator. + + static const DOMImplementation & instance(); + /// Returns a reference to the default DOMImplementation + /// object. + + private: + static const XMLString FEATURE_XML; + static const XMLString FEATURE_CORE; + static const XMLString FEATURE_EVENTS; + static const XMLString FEATURE_MUTATIONEVENTS; + static const XMLString FEATURE_TRAVERSAL; + static const XMLString VERSION_1_0; + static const XMLString VERSION_2_0; + }; + + +} +} // namespace Poco::XML #endif // DOM_DOMImplementation_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/DOMObject.h b/base/poco/XML/include/Poco/DOM/DOMObject.h index 40b29fb2cf7..0ce1fb73886 100644 --- a/base/poco/XML/include/Poco/DOM/DOMObject.h +++ b/base/poco/XML/include/Poco/DOM/DOMObject.h @@ -21,83 +21,86 @@ #include "Poco/XML/XML.h" -namespace Poco { -namespace XML { - - -class XML_API DOMObject - /// The base class for all objects in the Document Object Model. - /// - /// DOMObject defines the rules for memory management - /// in this implementation of the DOM. Violation of these - /// rules, which are outlined in the following, results - /// in memory leaks or dangling pointers. - /// - /// Every object created by new or by a factory - /// method (for example, Document::create*) must be released - /// with a call to release() or autoRelease() when it - /// is no longer needed. - /// - /// Every object created by cloning or importing another - /// object must be released. - /// For every call to duplicate() there must be a matching - /// call to release(). - /// An object obtained via any other way must not be - /// released, except ownership of it has been explicitly - /// taken with a call to duplicate(). - /// - /// While DOMObjects are safe for use in multithreaded programs, - /// a DOMObject or one of its subclasses must not be accessed - /// from multiple threads simultaneously. +namespace Poco { -public: - DOMObject(); - /// Creates the DOMObject. - /// The object's reference count is initialized to one. - - void duplicate() const; - /// Increases the object's reference count. - - void release() const; - /// Decreases the object's reference count. - /// If the reference count reaches zero, - /// the object is deleted. - - virtual void autoRelease() = 0; - /// Adds the object to an appropriate - /// AutoReleasePool, which is usually the - /// AutoReleasePool managed by the Document - /// to which this object belongs. - -protected: - virtual ~DOMObject(); - /// Destroys the DOMObject. - -private: - DOMObject(const DOMObject&); - DOMObject& operator = (const DOMObject&); - - mutable int _rc; -}; - - -// -// inlines -// -inline void DOMObject::duplicate() const +namespace XML { - ++_rc; + + + class XML_API DOMObject + /// The base class for all objects in the Document Object Model. + /// + /// DOMObject defines the rules for memory management + /// in this implementation of the DOM. Violation of these + /// rules, which are outlined in the following, results + /// in memory leaks or dangling pointers. + /// + /// Every object created by new or by a factory + /// method (for example, Document::create*) must be released + /// with a call to release() or autoRelease() when it + /// is no longer needed. + /// + /// Every object created by cloning or importing another + /// object must be released. + /// For every call to duplicate() there must be a matching + /// call to release(). + /// An object obtained via any other way must not be + /// released, except ownership of it has been explicitly + /// taken with a call to duplicate(). + /// + /// While DOMObjects are safe for use in multithreaded programs, + /// a DOMObject or one of its subclasses must not be accessed + /// from multiple threads simultaneously. + { + public: + DOMObject(); + /// Creates the DOMObject. + /// The object's reference count is initialized to one. + + void duplicate() const; + /// Increases the object's reference count. + + void release() const; + /// Decreases the object's reference count. + /// If the reference count reaches zero, + /// the object is deleted. + + virtual void autoRelease() = 0; + /// Adds the object to an appropriate + /// AutoReleasePool, which is usually the + /// AutoReleasePool managed by the Document + /// to which this object belongs. + + protected: + virtual ~DOMObject(); + /// Destroys the DOMObject. + + private: + DOMObject(const DOMObject &); + DOMObject & operator=(const DOMObject &); + + mutable int _rc; + }; + + + // + // inlines + // + inline void DOMObject::duplicate() const + { + ++_rc; + } + + + inline void DOMObject::release() const + { + if (--_rc == 0) + delete this; + } + + } - - -inline void DOMObject::release() const -{ - if (--_rc == 0) - delete this; -} - - -} } // namespace Poco::XML +} // namespace Poco::XML #endif // DOM_DOMObject_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/DOMParser.h b/base/poco/XML/include/Poco/DOM/DOMParser.h index 69d0f5aaac7..802538f04cc 100644 --- a/base/poco/XML/include/Poco/DOM/DOMParser.h +++ b/base/poco/XML/include/Poco/DOM/DOMParser.h @@ -18,97 +18,100 @@ #define DOM_DOMParser_INCLUDED -#include "Poco/XML/XML.h" #include "Poco/SAX/SAXParser.h" +#include "Poco/XML/XML.h" -namespace Poco { -namespace XML { - - -class NamePool; -class Document; -class InputSource; -class EntityResolver; - - -class XML_API DOMParser - /// This is a convenience class that combines a - /// DOMBuilder with a SAXParser, with the optional - /// support of a WhitespaceFilter. +namespace Poco +{ +namespace XML { -public: - explicit DOMParser(NamePool* pNamePool = 0); - /// Creates a new DOMParser. - /// If a NamePool is given, it becomes the Document's NamePool. - - explicit DOMParser(unsigned long namePoolSize); - /// Creates a new DOMParser, using the given NamePool size. - /// - /// The given namePoolSize should be a suitable prime number, - /// e.g. 251, 509, 1021 or 4093, depending on the expected - /// size of the document. - - ~DOMParser(); - /// Destroys the DOMParser. - - void setEncoding(const XMLString& encoding); - /// Sets the encoding used by the parser if no - /// encoding is specified in the XML document. - - const XMLString& getEncoding() const; - /// Returns the name of the encoding used by - /// the parser if no encoding is specified in - /// the XML document. - - void addEncoding(const XMLString& name, Poco::TextEncoding* pEncoding); - /// Adds an encoding to the parser. - - void setFeature(const XMLString& name, bool state); - /// Set the state of a feature. - /// - /// If a feature is not recognized by the DOMParser, it is - /// passed on to the underlying XMLReader. - /// - /// The only currently supported feature is - /// http://www.appinf.com/features/no-whitespace-in-element-content - /// which, when activated, causes the WhitespaceFilter to - /// be used. - - bool getFeature(const XMLString& name) const; - /// Look up the value of a feature. - /// - /// If a feature is not recognized by the DOMParser, the - /// DOMParser queries the underlying SAXParser for the feature. - - Document* parse(const XMLString& uri); - /// Parse an XML document from a location identified by an URI. - - Document* parse(InputSource* pInputSource); - /// Parse an XML document from a location identified by an InputSource. - - Document* parseString(const std::string& xml); - /// Parse an XML document from a string. - - Document* parseMemory(const char* xml, std::size_t size); - /// Parse an XML document from memory. - - EntityResolver* getEntityResolver() const; - /// Returns the entity resolver used by the underlying SAXParser. - - void setEntityResolver(EntityResolver* pEntityResolver); - /// Sets the entity resolver on the underlying SAXParser. - - static const XMLString FEATURE_FILTER_WHITESPACE; - -private: - SAXParser _saxParser; - NamePool* _pNamePool; - bool _filterWhitespace; -}; -} } // namespace Poco::XML + class NamePool; + class Document; + class InputSource; + class EntityResolver; + + + class XML_API DOMParser + /// This is a convenience class that combines a + /// DOMBuilder with a SAXParser, with the optional + /// support of a WhitespaceFilter. + { + public: + explicit DOMParser(NamePool * pNamePool = 0); + /// Creates a new DOMParser. + /// If a NamePool is given, it becomes the Document's NamePool. + + explicit DOMParser(unsigned long namePoolSize); + /// Creates a new DOMParser, using the given NamePool size. + /// + /// The given namePoolSize should be a suitable prime number, + /// e.g. 251, 509, 1021 or 4093, depending on the expected + /// size of the document. + + ~DOMParser(); + /// Destroys the DOMParser. + + void setEncoding(const XMLString & encoding); + /// Sets the encoding used by the parser if no + /// encoding is specified in the XML document. + + const XMLString & getEncoding() const; + /// Returns the name of the encoding used by + /// the parser if no encoding is specified in + /// the XML document. + + void addEncoding(const XMLString & name, Poco::TextEncoding * pEncoding); + /// Adds an encoding to the parser. + + void setFeature(const XMLString & name, bool state); + /// Set the state of a feature. + /// + /// If a feature is not recognized by the DOMParser, it is + /// passed on to the underlying XMLReader. + /// + /// The only currently supported feature is + /// http://www.appinf.com/features/no-whitespace-in-element-content + /// which, when activated, causes the WhitespaceFilter to + /// be used. + + bool getFeature(const XMLString & name) const; + /// Look up the value of a feature. + /// + /// If a feature is not recognized by the DOMParser, the + /// DOMParser queries the underlying SAXParser for the feature. + + Document * parse(const XMLString & uri); + /// Parse an XML document from a location identified by an URI. + + Document * parse(InputSource * pInputSource); + /// Parse an XML document from a location identified by an InputSource. + + Document * parseString(const std::string & xml); + /// Parse an XML document from a string. + + Document * parseMemory(const char * xml, std::size_t size); + /// Parse an XML document from memory. + + EntityResolver * getEntityResolver() const; + /// Returns the entity resolver used by the underlying SAXParser. + + void setEntityResolver(EntityResolver * pEntityResolver); + /// Sets the entity resolver on the underlying SAXParser. + + static const XMLString FEATURE_FILTER_WHITESPACE; + + private: + SAXParser _saxParser; + NamePool * _pNamePool; + bool _filterWhitespace; + }; + + +} +} // namespace Poco::XML #endif // DOM_DOMParser_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/DOMSerializer.h b/base/poco/XML/include/Poco/DOM/DOMSerializer.h index b535105dcad..4326709f75f 100644 --- a/base/poco/XML/include/Poco/DOM/DOMSerializer.h +++ b/base/poco/XML/include/Poco/DOM/DOMSerializer.h @@ -16,107 +16,110 @@ #define DOM_DOMSerializer_INCLUDED -#include "Poco/XML/XML.h" #include "Poco/SAX/XMLReader.h" +#include "Poco/XML/XML.h" -namespace Poco { -namespace XML { - - -class Node; -class Element; -class Text; -class Comment; -class ProcessingInstruction; -class Entity; -class CDATASection; -class Notation; -class Document; -class DocumentType; -class DocumentFragment; -class DeclHandler; -class LexicalHandler; - - -class XML_API DOMSerializer: public XMLReader - /// The DOMSerializer serializes a DOM document - /// into a sequence of SAX events which are - /// reported to the registered SAX event - /// handlers. - /// - /// The DOMWriter uses a DOMSerializer with an - /// XMLWriter to serialize a DOM document into - /// textual XML. +namespace Poco +{ +namespace XML { -public: - DOMSerializer(); - /// Creates the DOMSerializer. - - ~DOMSerializer(); - /// Destroys the DOMSerializer. - - void serialize(const Node* pNode); - /// Serializes a DOM node and its children - /// into a sequence of SAX events, which are - /// reported to the registered SAX event - /// handlers. - - // XMLReader - void setEntityResolver(EntityResolver* pResolver); - EntityResolver* getEntityResolver() const; - void setDTDHandler(DTDHandler* pDTDHandler); - DTDHandler* getDTDHandler() const; - void setContentHandler(ContentHandler* pContentHandler); - ContentHandler* getContentHandler() const; - void setErrorHandler(ErrorHandler* pErrorHandler); - ErrorHandler* getErrorHandler() const; - - void setFeature(const XMLString& featureId, bool state); - bool getFeature(const XMLString& featureId) const; - void setProperty(const XMLString& propertyId, const XMLString& value); - void setProperty(const XMLString& propertyId, void* value); - void* getProperty(const XMLString& propertyId) const; - -protected: - void parse(InputSource* pSource); - /// The DOMSerializer cannot parse an InputSource, - /// so this method simply throws an XMLException when invoked. - - void parse(const XMLString& systemId); - /// The DOMSerializer cannot parse from a system identifier, - /// so this method simply throws an XMLException when invoked. - - void parseMemoryNP(const char* xml, std::size_t size); - /// The DOMSerializer cannot parse from a system identifier, - /// so this method simply throws an XMLException when invoked. - - void iterate(const Node* pNode) const; - void handleNode(const Node* pNode) const; - void handleElement(const Element* pElement) const; - void handleCharacterData(const Text* pText) const; - void handleComment(const Comment* pComment) const; - void handlePI(const ProcessingInstruction* pPI) const; - void handleCDATASection(const CDATASection* pCDATA) const; - void handleDocument(const Document* pDocument) const; - void handleDocumentType(const DocumentType* pDocumentType) const; - void handleFragment(const DocumentFragment* pFragment) const; - void handleNotation(const Notation* pNotation) const; - void handleEntity(const Entity* pEntity) const; - -private: - EntityResolver* _pEntityResolver; - DTDHandler* _pDTDHandler; - ContentHandler* _pContentHandler; - ErrorHandler* _pErrorHandler; - DeclHandler* _pDeclHandler; - LexicalHandler* _pLexicalHandler; - - static const XMLString CDATA; -}; -} } // namespace Poco::XML + class Node; + class Element; + class Text; + class Comment; + class ProcessingInstruction; + class Entity; + class CDATASection; + class Notation; + class Document; + class DocumentType; + class DocumentFragment; + class DeclHandler; + class LexicalHandler; + + + class XML_API DOMSerializer : public XMLReader + /// The DOMSerializer serializes a DOM document + /// into a sequence of SAX events which are + /// reported to the registered SAX event + /// handlers. + /// + /// The DOMWriter uses a DOMSerializer with an + /// XMLWriter to serialize a DOM document into + /// textual XML. + { + public: + DOMSerializer(); + /// Creates the DOMSerializer. + + ~DOMSerializer(); + /// Destroys the DOMSerializer. + + void serialize(const Node * pNode); + /// Serializes a DOM node and its children + /// into a sequence of SAX events, which are + /// reported to the registered SAX event + /// handlers. + + // XMLReader + void setEntityResolver(EntityResolver * pResolver); + EntityResolver * getEntityResolver() const; + void setDTDHandler(DTDHandler * pDTDHandler); + DTDHandler * getDTDHandler() const; + void setContentHandler(ContentHandler * pContentHandler); + ContentHandler * getContentHandler() const; + void setErrorHandler(ErrorHandler * pErrorHandler); + ErrorHandler * getErrorHandler() const; + + void setFeature(const XMLString & featureId, bool state); + bool getFeature(const XMLString & featureId) const; + void setProperty(const XMLString & propertyId, const XMLString & value); + void setProperty(const XMLString & propertyId, void * value); + void * getProperty(const XMLString & propertyId) const; + + protected: + void parse(InputSource * pSource); + /// The DOMSerializer cannot parse an InputSource, + /// so this method simply throws an XMLException when invoked. + + void parse(const XMLString & systemId); + /// The DOMSerializer cannot parse from a system identifier, + /// so this method simply throws an XMLException when invoked. + + void parseMemoryNP(const char * xml, std::size_t size); + /// The DOMSerializer cannot parse from a system identifier, + /// so this method simply throws an XMLException when invoked. + + void iterate(const Node * pNode) const; + void handleNode(const Node * pNode) const; + void handleElement(const Element * pElement) const; + void handleCharacterData(const Text * pText) const; + void handleComment(const Comment * pComment) const; + void handlePI(const ProcessingInstruction * pPI) const; + void handleCDATASection(const CDATASection * pCDATA) const; + void handleDocument(const Document * pDocument) const; + void handleDocumentType(const DocumentType * pDocumentType) const; + void handleFragment(const DocumentFragment * pFragment) const; + void handleNotation(const Notation * pNotation) const; + void handleEntity(const Entity * pEntity) const; + + private: + EntityResolver * _pEntityResolver; + DTDHandler * _pDTDHandler; + ContentHandler * _pContentHandler; + ErrorHandler * _pErrorHandler; + DeclHandler * _pDeclHandler; + LexicalHandler * _pLexicalHandler; + + static const XMLString CDATA; + }; + + +} +} // namespace Poco::XML #endif // DOM_DOMSerializer_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/DOMWriter.h b/base/poco/XML/include/Poco/DOM/DOMWriter.h index 5a5132d5664..ed1edccaf28 100644 --- a/base/poco/XML/include/Poco/DOM/DOMWriter.h +++ b/base/poco/XML/include/Poco/DOM/DOMWriter.h @@ -18,110 +18,113 @@ #define DOM_DOMWriter_INCLUDED -#include "Poco/XML/XML.h" -#include "Poco/XML/XMLString.h" -#include "Poco/XML/XMLStream.h" #include "Poco/TextEncoding.h" +#include "Poco/XML/XML.h" +#include "Poco/XML/XMLStream.h" +#include "Poco/XML/XMLString.h" -namespace Poco { -namespace XML { - - -class Node; -class Document; - - -class XML_API DOMWriter - /// The DOMWriter uses a DOMSerializer with an - /// XMLWriter to serialize a DOM document into - /// textual XML. +namespace Poco { -public: - DOMWriter(); - /// Creates a DOMWriter. - - ~DOMWriter(); - /// Destroys a DOMWriter. - - void setEncoding(const std::string& encodingName, Poco::TextEncoding& textEncoding); - /// Sets the encoding, which will be reflected in the written XML declaration. - - const std::string& getEncoding() const; - /// Returns the encoding name set with setEncoding. - - void setOptions(int options); - /// Sets options for the internal XMLWriter. - /// - /// See class XMLWriter for available options. - - int getOptions() const; - /// Returns the options for the internal XMLWriter. - - void setNewLine(const std::string& newLine); - /// Sets the line ending characters for the internal - /// XMLWriter. See XMLWriter::setNewLine() for a list - /// of supported values. - - const std::string& getNewLine() const; - /// Returns the line ending characters used by the - /// internal XMLWriter. - - void setIndent(const std::string& indent); - /// Sets the string used for one indentation step. - /// - /// The default is a single TAB character. - /// The given string should only contain TAB or SPACE - /// characters (e.g., a single TAB character, or - /// two to four SPACE characters). - - const std::string& getIndent() const; - /// Returns the string used for one indentation step. - - void writeNode(XMLByteOutputStream& ostr, const Node* pNode); - /// Writes the XML for the given node to the specified stream. - - void writeNode(const std::string& systemId, const Node* pNode); - /// Writes the XML for the given node to the file specified in systemId, - /// using a standard file output stream (Poco::FileOutputStream). - -private: - std::string _encodingName; - Poco::TextEncoding* _pTextEncoding; - int _options; - std::string _newLine; - std::string _indent; -}; - - -// -// inlines -// -inline const std::string& DOMWriter::getEncoding() const +namespace XML { - return _encodingName; + + + class Node; + class Document; + + + class XML_API DOMWriter + /// The DOMWriter uses a DOMSerializer with an + /// XMLWriter to serialize a DOM document into + /// textual XML. + { + public: + DOMWriter(); + /// Creates a DOMWriter. + + ~DOMWriter(); + /// Destroys a DOMWriter. + + void setEncoding(const std::string & encodingName, Poco::TextEncoding & textEncoding); + /// Sets the encoding, which will be reflected in the written XML declaration. + + const std::string & getEncoding() const; + /// Returns the encoding name set with setEncoding. + + void setOptions(int options); + /// Sets options for the internal XMLWriter. + /// + /// See class XMLWriter for available options. + + int getOptions() const; + /// Returns the options for the internal XMLWriter. + + void setNewLine(const std::string & newLine); + /// Sets the line ending characters for the internal + /// XMLWriter. See XMLWriter::setNewLine() for a list + /// of supported values. + + const std::string & getNewLine() const; + /// Returns the line ending characters used by the + /// internal XMLWriter. + + void setIndent(const std::string & indent); + /// Sets the string used for one indentation step. + /// + /// The default is a single TAB character. + /// The given string should only contain TAB or SPACE + /// characters (e.g., a single TAB character, or + /// two to four SPACE characters). + + const std::string & getIndent() const; + /// Returns the string used for one indentation step. + + void writeNode(XMLByteOutputStream & ostr, const Node * pNode); + /// Writes the XML for the given node to the specified stream. + + void writeNode(const std::string & systemId, const Node * pNode); + /// Writes the XML for the given node to the file specified in systemId, + /// using a standard file output stream (Poco::FileOutputStream). + + private: + std::string _encodingName; + Poco::TextEncoding * _pTextEncoding; + int _options; + std::string _newLine; + std::string _indent; + }; + + + // + // inlines + // + inline const std::string & DOMWriter::getEncoding() const + { + return _encodingName; + } + + + inline int DOMWriter::getOptions() const + { + return _options; + } + + + inline const std::string & DOMWriter::getNewLine() const + { + return _newLine; + } + + + inline const std::string & DOMWriter::getIndent() const + { + return _indent; + } + + } - - -inline int DOMWriter::getOptions() const -{ - return _options; -} - - -inline const std::string& DOMWriter::getNewLine() const -{ - return _newLine; -} - - -inline const std::string& DOMWriter::getIndent() const -{ - return _indent; -} - - -} } // namespace Poco::XML +} // namespace Poco::XML #endif // DOM_DOMWriter_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/DTDMap.h b/base/poco/XML/include/Poco/DOM/DTDMap.h index 2a475c358ef..9560cd7a7e8 100644 --- a/base/poco/XML/include/Poco/DOM/DTDMap.h +++ b/base/poco/XML/include/Poco/DOM/DTDMap.h @@ -18,50 +18,53 @@ #define DOM_DTDMap_INCLUDED -#include "Poco/XML/XML.h" #include "Poco/DOM/NamedNodeMap.h" +#include "Poco/XML/XML.h" -namespace Poco { -namespace XML { - - -class DocumentType; - - -class XML_API DTDMap: public NamedNodeMap - /// This implementation of NamedNodeMap - /// is returned by DocumentType::entities() - /// and DocumentType::notations(). +namespace Poco +{ +namespace XML { -public: - Node* getNamedItem(const XMLString& name) const; - Node* setNamedItem(Node* arg); - Node* removeNamedItem(const XMLString& name); - Node* item(unsigned long index) const; - unsigned long length() const; - - Node* getNamedItemNS(const XMLString& namespaceURI, const XMLString& localName) const; - Node* setNamedItemNS(Node* arg); - Node* removeNamedItemNS(const XMLString& namespaceURI, const XMLString& localName); - - void autoRelease(); - -protected: - DTDMap(const DocumentType* pDocumentType, unsigned short type); - ~DTDMap(); - -private: - DTDMap(); - - const DocumentType* _pDocumentType; - unsigned short _type; - - friend class DocumentType; -}; -} } // namespace Poco::XML + class DocumentType; + + + class XML_API DTDMap : public NamedNodeMap + /// This implementation of NamedNodeMap + /// is returned by DocumentType::entities() + /// and DocumentType::notations(). + { + public: + Node * getNamedItem(const XMLString & name) const; + Node * setNamedItem(Node * arg); + Node * removeNamedItem(const XMLString & name); + Node * item(unsigned long index) const; + unsigned long length() const; + + Node * getNamedItemNS(const XMLString & namespaceURI, const XMLString & localName) const; + Node * setNamedItemNS(Node * arg); + Node * removeNamedItemNS(const XMLString & namespaceURI, const XMLString & localName); + + void autoRelease(); + + protected: + DTDMap(const DocumentType * pDocumentType, unsigned short type); + ~DTDMap(); + + private: + DTDMap(); + + const DocumentType * _pDocumentType; + unsigned short _type; + + friend class DocumentType; + }; + + +} +} // namespace Poco::XML #endif // DOM_DTDMap_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/Document.h b/base/poco/XML/include/Poco/DOM/Document.h index 082191c0824..f206473b2b4 100644 --- a/base/poco/XML/include/Poco/DOM/Document.h +++ b/base/poco/XML/include/Poco/DOM/Document.h @@ -18,268 +18,273 @@ #define DOM_Document_INCLUDED -#include "Poco/XML/XML.h" +#include "Poco/AutoReleasePool.h" #include "Poco/DOM/AbstractContainerNode.h" #include "Poco/DOM/DocumentEvent.h" #include "Poco/DOM/Element.h" -#include "Poco/XML/XMLString.h" #include "Poco/XML/NamePool.h" -#include "Poco/AutoReleasePool.h" +#include "Poco/XML/XML.h" +#include "Poco/XML/XMLString.h" -namespace Poco { -namespace XML { - - -class NamePool; -class DocumentType; -class DOMImplementation; -class DocumentFragment; -class Text; -class Comment; -class CDATASection; -class ProcessingInstruction; -class Attr; -class EntityReference; -class NodeList; -class Entity; -class Notation; - - -class XML_API Document: public AbstractContainerNode, public DocumentEvent - /// The Document interface represents the entire HTML or XML document. Conceptually, - /// it is the root of the document tree, and provides the primary access to the - /// document's data. - /// - /// Since elements, text nodes, comments, processing instructions, etc. cannot exist - /// outside the context of a Document, the Document interface also contains the - /// factory methods needed to create these objects. The Node objects created have a - /// ownerDocument attribute which associates them with the Document within whose - /// context they were created. +namespace Poco { -public: - using AutoReleasePool = Poco::AutoReleasePool; - - explicit Document(NamePool* pNamePool = 0); - /// Creates a new document. If pNamePool == 0, the document - /// creates its own name pool, otherwise it uses the given name pool. - /// Sharing a name pool makes sense for documents containing instances - /// of the same schema, thus reducing memory usage. - - explicit Document(unsigned long namePoolSize); - /// Creates a new document using a name pool with the given size, which - /// should be a prime number (e.g., 251, 509, 1021, 4093). - - Document(DocumentType* pDocumentType, NamePool* pNamePool = 0); - /// Creates a new document. If pNamePool == 0, the document - /// creates its own name pool, otherwise it uses the given name pool. - /// Sharing a name pool makes sense for documents containing instances - /// of the same schema, thus reducing memory usage. - - Document(DocumentType* pDocumentType, unsigned long namePoolSize); - /// Creates a new document using a name pool with the given size, which - /// should be a prime number (e.g., 251, 509, 1021, 4093). - - NamePool& namePool(); - /// Returns a pointer to the documents Name Pool. - - AutoReleasePool& autoReleasePool(); - /// Returns a pointer to the documents Auto Release Pool. - - void collectGarbage(); - /// Releases all objects in the Auto Release Pool. - - void suspendEvents(); - /// Suspends all events until resumeEvents() is called. - - void resumeEvents(); - /// Resumes all events suspended with suspendEvent(); - - bool eventsSuspended() const; - /// Returns true if events are suspended. - - bool events() const; - /// Returns true if events are not suspended. - - const DocumentType* doctype() const; - /// The Document Type Declaration (see DocumentType) associated with this document. - /// For HTML documents as well as XML documents without a document type declaration - /// this returns null. The DOM Level 1 does not support editing the Document - /// Type Declaration. docType cannot be altered in any way, including through - /// the use of methods inherited from the Node interface, such as insertNode - /// or removeNode. - - const DOMImplementation& implementation() const; - /// The DOMImplementation object that handles this document. A DOM application - /// may use objects from multiple implementations. - - Element* documentElement() const; - /// This is a convenience attribute that allows direct access to the child node - /// that is the root element of the document. For HTML documents, this is the - /// element with the tagName "HTML". - - Element* createElement(const XMLString& tagName) const; - /// Creates an element of the type specified. Note that the instance returned - /// implements the Element interface, so attributes can be specified directly - /// on the returned object. - /// - /// In addition, if there are known attributes with default values, Attr nodes - /// representing them are automatically created and attached to the element. - - DocumentFragment* createDocumentFragment() const; - /// Creates an empty DocumentFragment object. - - Text* createTextNode(const XMLString& data) const; - /// Creates a text node given the specified string. - - Comment* createComment(const XMLString& data) const; - /// Creates a comment node given the specified string. - - CDATASection* createCDATASection(const XMLString& data) const; - /// Creates a CDATASection node whose value is the specified string. - - ProcessingInstruction* createProcessingInstruction(const XMLString& target, const XMLString& data) const; - /// Creates a ProcessingInstruction node given the specified target and data strings. - - Attr* createAttribute(const XMLString& name) const; - /// Creates an Attr of the given name. Note that the Attr instance can then - /// be set on an Element using the setAttributeNode method. - - EntityReference* createEntityReference(const XMLString& name) const; - /// Creates an EntityReference object. In addition, if the referenced entity - /// is known, the child list of the EntityReference node is made the same as - /// that of the corresponding Entity node. - - NodeList* getElementsByTagName(const XMLString& name) const; - /// Returns a NodeList of all Elements with a given tag name in the order - /// in which they would be encountered in a preorder traversal of the - /// document tree. - /// - /// The returned NodeList must be released with a call to release() - /// when no longer needed. - - // DOM Level 2 - Node* importNode(Node* importedNode, bool deep); - /// Imports a node from another document to this document. The returned node - /// has no parent; (parentNode is null). The source node is not altered or removed - /// from the original document; this method creates a new copy of the source - /// node. - /// For all nodes, importing a node creates a node object owned by the importing - /// document, with attribute values identical to the source node's nodeName - /// and nodeType, plus the attributes related to namespaces (prefix, localName, - /// and namespaceURI). As in the cloneNode operation on a Node, the source node - /// is not altered. - /// Additional information is copied as appropriate to the nodeType, attempting - /// to mirror the behavior expected if a fragment of XML or HTML source was - /// copied from one document to another, recognizing that the two documents - /// may have different DTDs in the XML case. - - Element* createElementNS(const XMLString& namespaceURI, const XMLString& qualifiedName) const; - /// Creates an element of the given qualified name and namespace URI. - - Attr* createAttributeNS(const XMLString& namespaceURI, const XMLString& qualifiedName) const; - /// Creates an attribute of the given qualified name and namespace URI. - - NodeList* getElementsByTagNameNS(const XMLString& namespaceURI, const XMLString& localName) const; - /// Returns a NodeList of all the Elements with a given local name and - /// namespace URI in the order in which they are encountered in a - /// preorder traversal of the Document tree. - - Element* getElementById(const XMLString& elementId) const; - /// Returns the Element whose ID is given by elementId. If no such - /// element exists, returns null. Behavior is not defined if more - /// than one element has this ID. - /// - /// Note: The DOM implementation must have information that says - /// which attributes are of type ID. Attributes with the name "ID" - /// are not of type ID unless so defined. Implementations that do - /// not know whether attributes are of type ID or not are expected to - /// return null. This implementation therefore returns null. - /// - /// See also the non-standard two argument variant of getElementById() - /// and getElementByIdNS(). - - // DocumentEvent - Event* createEvent(const XMLString& eventType) const; - - // Node - const XMLString& nodeName() const; - unsigned short nodeType() const; - - // EventTarget - bool dispatchEvent(Event* evt); - - // Extensions - Entity* createEntity(const XMLString& name, const XMLString& publicId, const XMLString& systemId, const XMLString& notationName) const; - /// Creates an Entity with the given name, publicId, systemId and notationName. - /// - /// This method is not part of the W3C Document Object Model. - - Notation* createNotation(const XMLString& name, const XMLString& publicId, const XMLString& systemId) const; - /// Creates a Notation with the given name, publicId and systemId. - /// - /// This method is not part of the W3C Document Object Model. - - Element* getElementById(const XMLString& elementId, const XMLString& idAttribute) const; - /// Returns the first Element whose ID attribute (given in idAttribute) - /// has the given elementId. If no such element exists, returns null. - /// - /// This method is an extension to the W3C Document Object Model. - - Element* getElementByIdNS(const XMLString& elementId, const XMLString& idAttributeURI, const XMLString& idAttributeLocalName) const; - /// Returns the first Element whose ID attribute (given in idAttributeURI and idAttributeLocalName) - /// has the given elementId. If no such element exists, returns null. - /// - /// This method is an extension to the W3C Document Object Model. - -protected: - ~Document(); - - Node* copyNode(bool deep, Document* pOwnerDocument) const; - - DocumentType* getDoctype(); - void setDoctype(DocumentType* pDoctype); - -private: - DocumentType* _pDocumentType; - NamePool* _pNamePool; - AutoReleasePool _autoReleasePool; - int _eventSuspendLevel; - - static const XMLString NODE_NAME; - - friend class DOMBuilder; -}; - - -// -// inlines -// -inline NamePool& Document::namePool() +namespace XML { - return *_pNamePool; + + + class NamePool; + class DocumentType; + class DOMImplementation; + class DocumentFragment; + class Text; + class Comment; + class CDATASection; + class ProcessingInstruction; + class Attr; + class EntityReference; + class NodeList; + class Entity; + class Notation; + + + class XML_API Document : public AbstractContainerNode, public DocumentEvent + /// The Document interface represents the entire HTML or XML document. Conceptually, + /// it is the root of the document tree, and provides the primary access to the + /// document's data. + /// + /// Since elements, text nodes, comments, processing instructions, etc. cannot exist + /// outside the context of a Document, the Document interface also contains the + /// factory methods needed to create these objects. The Node objects created have a + /// ownerDocument attribute which associates them with the Document within whose + /// context they were created. + { + public: + using AutoReleasePool = Poco::AutoReleasePool; + + explicit Document(NamePool * pNamePool = 0); + /// Creates a new document. If pNamePool == 0, the document + /// creates its own name pool, otherwise it uses the given name pool. + /// Sharing a name pool makes sense for documents containing instances + /// of the same schema, thus reducing memory usage. + + explicit Document(unsigned long namePoolSize); + /// Creates a new document using a name pool with the given size, which + /// should be a prime number (e.g., 251, 509, 1021, 4093). + + Document(DocumentType * pDocumentType, NamePool * pNamePool = 0); + /// Creates a new document. If pNamePool == 0, the document + /// creates its own name pool, otherwise it uses the given name pool. + /// Sharing a name pool makes sense for documents containing instances + /// of the same schema, thus reducing memory usage. + + Document(DocumentType * pDocumentType, unsigned long namePoolSize); + /// Creates a new document using a name pool with the given size, which + /// should be a prime number (e.g., 251, 509, 1021, 4093). + + NamePool & namePool(); + /// Returns a pointer to the documents Name Pool. + + AutoReleasePool & autoReleasePool(); + /// Returns a pointer to the documents Auto Release Pool. + + void collectGarbage(); + /// Releases all objects in the Auto Release Pool. + + void suspendEvents(); + /// Suspends all events until resumeEvents() is called. + + void resumeEvents(); + /// Resumes all events suspended with suspendEvent(); + + bool eventsSuspended() const; + /// Returns true if events are suspended. + + bool events() const; + /// Returns true if events are not suspended. + + const DocumentType * doctype() const; + /// The Document Type Declaration (see DocumentType) associated with this document. + /// For HTML documents as well as XML documents without a document type declaration + /// this returns null. The DOM Level 1 does not support editing the Document + /// Type Declaration. docType cannot be altered in any way, including through + /// the use of methods inherited from the Node interface, such as insertNode + /// or removeNode. + + const DOMImplementation & implementation() const; + /// The DOMImplementation object that handles this document. A DOM application + /// may use objects from multiple implementations. + + Element * documentElement() const; + /// This is a convenience attribute that allows direct access to the child node + /// that is the root element of the document. For HTML documents, this is the + /// element with the tagName "HTML". + + Element * createElement(const XMLString & tagName) const; + /// Creates an element of the type specified. Note that the instance returned + /// implements the Element interface, so attributes can be specified directly + /// on the returned object. + /// + /// In addition, if there are known attributes with default values, Attr nodes + /// representing them are automatically created and attached to the element. + + DocumentFragment * createDocumentFragment() const; + /// Creates an empty DocumentFragment object. + + Text * createTextNode(const XMLString & data) const; + /// Creates a text node given the specified string. + + Comment * createComment(const XMLString & data) const; + /// Creates a comment node given the specified string. + + CDATASection * createCDATASection(const XMLString & data) const; + /// Creates a CDATASection node whose value is the specified string. + + ProcessingInstruction * createProcessingInstruction(const XMLString & target, const XMLString & data) const; + /// Creates a ProcessingInstruction node given the specified target and data strings. + + Attr * createAttribute(const XMLString & name) const; + /// Creates an Attr of the given name. Note that the Attr instance can then + /// be set on an Element using the setAttributeNode method. + + EntityReference * createEntityReference(const XMLString & name) const; + /// Creates an EntityReference object. In addition, if the referenced entity + /// is known, the child list of the EntityReference node is made the same as + /// that of the corresponding Entity node. + + NodeList * getElementsByTagName(const XMLString & name) const; + /// Returns a NodeList of all Elements with a given tag name in the order + /// in which they would be encountered in a preorder traversal of the + /// document tree. + /// + /// The returned NodeList must be released with a call to release() + /// when no longer needed. + + // DOM Level 2 + Node * importNode(Node * importedNode, bool deep); + /// Imports a node from another document to this document. The returned node + /// has no parent; (parentNode is null). The source node is not altered or removed + /// from the original document; this method creates a new copy of the source + /// node. + /// For all nodes, importing a node creates a node object owned by the importing + /// document, with attribute values identical to the source node's nodeName + /// and nodeType, plus the attributes related to namespaces (prefix, localName, + /// and namespaceURI). As in the cloneNode operation on a Node, the source node + /// is not altered. + /// Additional information is copied as appropriate to the nodeType, attempting + /// to mirror the behavior expected if a fragment of XML or HTML source was + /// copied from one document to another, recognizing that the two documents + /// may have different DTDs in the XML case. + + Element * createElementNS(const XMLString & namespaceURI, const XMLString & qualifiedName) const; + /// Creates an element of the given qualified name and namespace URI. + + Attr * createAttributeNS(const XMLString & namespaceURI, const XMLString & qualifiedName) const; + /// Creates an attribute of the given qualified name and namespace URI. + + NodeList * getElementsByTagNameNS(const XMLString & namespaceURI, const XMLString & localName) const; + /// Returns a NodeList of all the Elements with a given local name and + /// namespace URI in the order in which they are encountered in a + /// preorder traversal of the Document tree. + + Element * getElementById(const XMLString & elementId) const; + /// Returns the Element whose ID is given by elementId. If no such + /// element exists, returns null. Behavior is not defined if more + /// than one element has this ID. + /// + /// Note: The DOM implementation must have information that says + /// which attributes are of type ID. Attributes with the name "ID" + /// are not of type ID unless so defined. Implementations that do + /// not know whether attributes are of type ID or not are expected to + /// return null. This implementation therefore returns null. + /// + /// See also the non-standard two argument variant of getElementById() + /// and getElementByIdNS(). + + // DocumentEvent + Event * createEvent(const XMLString & eventType) const; + + // Node + const XMLString & nodeName() const; + unsigned short nodeType() const; + + // EventTarget + bool dispatchEvent(Event * evt); + + // Extensions + Entity * + createEntity(const XMLString & name, const XMLString & publicId, const XMLString & systemId, const XMLString & notationName) const; + /// Creates an Entity with the given name, publicId, systemId and notationName. + /// + /// This method is not part of the W3C Document Object Model. + + Notation * createNotation(const XMLString & name, const XMLString & publicId, const XMLString & systemId) const; + /// Creates a Notation with the given name, publicId and systemId. + /// + /// This method is not part of the W3C Document Object Model. + + Element * getElementById(const XMLString & elementId, const XMLString & idAttribute) const; + /// Returns the first Element whose ID attribute (given in idAttribute) + /// has the given elementId. If no such element exists, returns null. + /// + /// This method is an extension to the W3C Document Object Model. + + Element * + getElementByIdNS(const XMLString & elementId, const XMLString & idAttributeURI, const XMLString & idAttributeLocalName) const; + /// Returns the first Element whose ID attribute (given in idAttributeURI and idAttributeLocalName) + /// has the given elementId. If no such element exists, returns null. + /// + /// This method is an extension to the W3C Document Object Model. + + protected: + ~Document(); + + Node * copyNode(bool deep, Document * pOwnerDocument) const; + + DocumentType * getDoctype(); + void setDoctype(DocumentType * pDoctype); + + private: + DocumentType * _pDocumentType; + NamePool * _pNamePool; + AutoReleasePool _autoReleasePool; + int _eventSuspendLevel; + + static const XMLString NODE_NAME; + + friend class DOMBuilder; + }; + + + // + // inlines + // + inline NamePool & Document::namePool() + { + return *_pNamePool; + } + + + inline Document::AutoReleasePool & Document::autoReleasePool() + { + return _autoReleasePool; + } + + + inline const DocumentType * Document::doctype() const + { + return _pDocumentType; + } + + + inline DocumentType * Document::getDoctype() + { + return _pDocumentType; + } + + } - - -inline Document::AutoReleasePool& Document::autoReleasePool() -{ - return _autoReleasePool; -} - - -inline const DocumentType* Document::doctype() const -{ - return _pDocumentType; -} - - -inline DocumentType* Document::getDoctype() -{ - return _pDocumentType; -} - - -} } // namespace Poco::XML +} // namespace Poco::XML #endif // DOM_Document_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/DocumentEvent.h b/base/poco/XML/include/Poco/DOM/DocumentEvent.h index 14bcf270b84..9780576f050 100644 --- a/base/poco/XML/include/Poco/DOM/DocumentEvent.h +++ b/base/poco/XML/include/Poco/DOM/DocumentEvent.h @@ -22,44 +22,47 @@ #include "Poco/XML/XMLString.h" -namespace Poco { -namespace XML { - - -class Event; - - -class XML_API DocumentEvent - /// The DocumentEvent interface provides a mechanism by which the user can create - /// an Event of a type supported by the implementation. It is expected that - /// the DocumentEvent interface will be implemented on the same object which - /// implements the Document interface in an implementation which supports the - /// Event model. +namespace Poco +{ +namespace XML { -public: - virtual Event* createEvent(const XMLString& eventType) const = 0; - /// Creates an event of the specified type. - /// - /// The eventType parameter specifies the type of Event interface to be created. - /// If the Event interface specified is supported by the implementation this - /// method will return a new Event of the interface type requested. If the Event - /// is to be dispatched via the dispatchEvent method the appropriate event init - /// method must be called after creation in order to initialize the Event's - /// values. As an example, a user wishing to synthesize some kind of UIEvent - /// would call createEvent with the parameter "UIEvents". The initUIEvent method - /// could then be called on the newly created UIEvent to set the specific type - /// of UIEvent to be dispatched and set its context information. - /// The createEvent method is used in creating Events when it is either inconvenient - /// or unnecessary for the user to create an Event themselves. In cases where - /// the implementation provided Event is insufficient, users may supply their - /// own Event implementations for use with the dispatchEvent method. - -protected: - virtual ~DocumentEvent(); -}; -} } // namespace Poco::XML + class Event; + + + class XML_API DocumentEvent + /// The DocumentEvent interface provides a mechanism by which the user can create + /// an Event of a type supported by the implementation. It is expected that + /// the DocumentEvent interface will be implemented on the same object which + /// implements the Document interface in an implementation which supports the + /// Event model. + { + public: + virtual Event * createEvent(const XMLString & eventType) const = 0; + /// Creates an event of the specified type. + /// + /// The eventType parameter specifies the type of Event interface to be created. + /// If the Event interface specified is supported by the implementation this + /// method will return a new Event of the interface type requested. If the Event + /// is to be dispatched via the dispatchEvent method the appropriate event init + /// method must be called after creation in order to initialize the Event's + /// values. As an example, a user wishing to synthesize some kind of UIEvent + /// would call createEvent with the parameter "UIEvents". The initUIEvent method + /// could then be called on the newly created UIEvent to set the specific type + /// of UIEvent to be dispatched and set its context information. + /// The createEvent method is used in creating Events when it is either inconvenient + /// or unnecessary for the user to create an Event themselves. In cases where + /// the implementation provided Event is insufficient, users may supply their + /// own Event implementations for use with the dispatchEvent method. + + protected: + virtual ~DocumentEvent(); + }; + + +} +} // namespace Poco::XML #endif // DOM_DocumentEvent_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/DocumentFragment.h b/base/poco/XML/include/Poco/DOM/DocumentFragment.h index 105a2171db3..fe5f737dc59 100644 --- a/base/poco/XML/include/Poco/DOM/DocumentFragment.h +++ b/base/poco/XML/include/Poco/DOM/DocumentFragment.h @@ -18,67 +18,70 @@ #define DOM_DocumentFragment_INCLUDED -#include "Poco/XML/XML.h" #include "Poco/DOM/AbstractContainerNode.h" +#include "Poco/XML/XML.h" #include "Poco/XML/XMLString.h" -namespace Poco { -namespace XML { - - -class XML_API DocumentFragment: public AbstractContainerNode - /// DocumentFragment is a "lightweight" or "minimal" Document object. It is - /// very common to want to be able to extract a portion of a document's tree - /// or to create a new fragment of a document. Imagine implementing a user command - /// like cut or rearranging a document by moving fragments around. It is desirable - /// to have an object which can hold such fragments and it is quite natural - /// to use a Node for this purpose. While it is true that a Document object - /// could fulfill this role, a Document object can potentially be a heavyweight - /// object, depending on the underlying implementation. What is really needed - /// for this is a very lightweight object. DocumentFragment is such an object. - /// - /// Furthermore, various operations -- such as inserting nodes as children of - /// another Node -- may take DocumentFragment objects as arguments; this results - /// in all the child nodes of the DocumentFragment being moved to the child - /// list of this node. - /// - /// The children of a DocumentFragment node are zero or more nodes representing - /// the tops of any sub-trees defining the structure of the document. DocumentFragment - /// nodes do not need to be well-formed XML documents (although they do need - /// to follow the rules imposed upon well-formed XML parsed entities, which - /// can have multiple top nodes). For example, a DocumentFragment might have - /// only one child and that child node could be a Text node. Such a structure - /// model represents neither an HTML document nor a well-formed XML document. - /// - /// When a DocumentFragment is inserted into a Document (or indeed any other - /// Node that may take children) the children of the DocumentFragment and not - /// the DocumentFragment itself are inserted into the Node. This makes the DocumentFragment - /// very useful when the user wishes to create nodes that are siblings; the - /// DocumentFragment acts as the parent of these nodes so that the user can - /// use the standard methods from the Node interface, such as insertBefore and - /// appendChild. +namespace Poco +{ +namespace XML { -public: - // Node - const XMLString& nodeName() const; - unsigned short nodeType() const; - -protected: - DocumentFragment(Document* pOwnerDocument); - DocumentFragment(Document* pOwnerDocument, const DocumentFragment& fragment); - ~DocumentFragment(); - - Node* copyNode(bool deep, Document* pOwnerDocument) const; - -private: - static const XMLString NODE_NAME; - - friend class Document; -}; -} } // namespace Poco::XML + class XML_API DocumentFragment : public AbstractContainerNode + /// DocumentFragment is a "lightweight" or "minimal" Document object. It is + /// very common to want to be able to extract a portion of a document's tree + /// or to create a new fragment of a document. Imagine implementing a user command + /// like cut or rearranging a document by moving fragments around. It is desirable + /// to have an object which can hold such fragments and it is quite natural + /// to use a Node for this purpose. While it is true that a Document object + /// could fulfill this role, a Document object can potentially be a heavyweight + /// object, depending on the underlying implementation. What is really needed + /// for this is a very lightweight object. DocumentFragment is such an object. + /// + /// Furthermore, various operations -- such as inserting nodes as children of + /// another Node -- may take DocumentFragment objects as arguments; this results + /// in all the child nodes of the DocumentFragment being moved to the child + /// list of this node. + /// + /// The children of a DocumentFragment node are zero or more nodes representing + /// the tops of any sub-trees defining the structure of the document. DocumentFragment + /// nodes do not need to be well-formed XML documents (although they do need + /// to follow the rules imposed upon well-formed XML parsed entities, which + /// can have multiple top nodes). For example, a DocumentFragment might have + /// only one child and that child node could be a Text node. Such a structure + /// model represents neither an HTML document nor a well-formed XML document. + /// + /// When a DocumentFragment is inserted into a Document (or indeed any other + /// Node that may take children) the children of the DocumentFragment and not + /// the DocumentFragment itself are inserted into the Node. This makes the DocumentFragment + /// very useful when the user wishes to create nodes that are siblings; the + /// DocumentFragment acts as the parent of these nodes so that the user can + /// use the standard methods from the Node interface, such as insertBefore and + /// appendChild. + { + public: + // Node + const XMLString & nodeName() const; + unsigned short nodeType() const; + + protected: + DocumentFragment(Document * pOwnerDocument); + DocumentFragment(Document * pOwnerDocument, const DocumentFragment & fragment); + ~DocumentFragment(); + + Node * copyNode(bool deep, Document * pOwnerDocument) const; + + private: + static const XMLString NODE_NAME; + + friend class Document; + }; + + +} +} // namespace Poco::XML #endif // DOM_DocumentFragment_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/DocumentType.h b/base/poco/XML/include/Poco/DOM/DocumentType.h index 3d8909798b3..2fbb88c24c5 100644 --- a/base/poco/XML/include/Poco/DOM/DocumentType.h +++ b/base/poco/XML/include/Poco/DOM/DocumentType.h @@ -18,108 +18,111 @@ #define DOM_DocumentType_INCLUDED -#include "Poco/XML/XML.h" #include "Poco/DOM/AbstractContainerNode.h" +#include "Poco/XML/XML.h" -namespace Poco { -namespace XML { - - -class NamedNodeMap; - - -class XML_API DocumentType: public AbstractContainerNode - /// Each Document has a doctype attribute whose value is either null or a DocumentType - /// object. The DocumentType interface in the DOM Level 1 Core provides an - /// interface to the list of entities that are defined for the document, and - /// little else because the effect of namespaces and the various XML scheme - /// efforts on DTD representation are not clearly understood as of this writing. - /// - /// The DOM Level 1 doesn't support editing DocumentType nodes. +namespace Poco { -public: - const XMLString& name() const; - /// The name of the DTD; i.e., the name immediately following the - /// DOCTYPE keyword. - - NamedNodeMap* entities() const; - /// A NamedNodeMap containing the general entities, - /// both external and internal, declared in the DTD. - /// Duplicates are discarded. - /// - /// Note: In this implementation, only the - /// external entities are reported. - /// Every node in this map also implements the - /// Entity interface. - /// - /// The returned NamedNodeMap must be released with a call - /// to release() when no longer needed. - - NamedNodeMap* notations() const; - /// A NamedNodeMap containing the notations declared in the DTD. Duplicates - /// are discarded. Every node in this map also implements the Notation interface. - /// The DOM Level 1 does not support editing notations, therefore notations - /// cannot be altered in any way. - /// - /// The returned NamedNodeMap must be released with a call - /// to release() when no longer needed. - - // DOM Level 2 - const XMLString& publicId() const; - /// Returns the public identifier of the external DTD subset. - - const XMLString& systemId() const; - /// Returns the system identifier of the external DTD subset. - - const XMLString& internalSubset() const; - /// Returns the internal DTD subset. This implementation - /// returns an empty string. - - // Node - const XMLString& nodeName() const; - unsigned short nodeType() const; - -protected: - DocumentType(Document* pOwner, const XMLString& name, const XMLString& publicId, const XMLString& systemId); - DocumentType(Document* pOwner, const DocumentType& dt); - ~DocumentType(); - - Node* copyNode(bool deep, Document* pOwnerDocument) const; - -private: - XMLString _name; - XMLString _publicId; - XMLString _systemId; - - friend class DOMImplementation; - friend class Document; - friend class DOMBuilder; -}; - - -// -// inlines -// -inline const XMLString& DocumentType::name() const +namespace XML { - return _name; + + + class NamedNodeMap; + + + class XML_API DocumentType : public AbstractContainerNode + /// Each Document has a doctype attribute whose value is either null or a DocumentType + /// object. The DocumentType interface in the DOM Level 1 Core provides an + /// interface to the list of entities that are defined for the document, and + /// little else because the effect of namespaces and the various XML scheme + /// efforts on DTD representation are not clearly understood as of this writing. + /// + /// The DOM Level 1 doesn't support editing DocumentType nodes. + { + public: + const XMLString & name() const; + /// The name of the DTD; i.e., the name immediately following the + /// DOCTYPE keyword. + + NamedNodeMap * entities() const; + /// A NamedNodeMap containing the general entities, + /// both external and internal, declared in the DTD. + /// Duplicates are discarded. + /// + /// Note: In this implementation, only the + /// external entities are reported. + /// Every node in this map also implements the + /// Entity interface. + /// + /// The returned NamedNodeMap must be released with a call + /// to release() when no longer needed. + + NamedNodeMap * notations() const; + /// A NamedNodeMap containing the notations declared in the DTD. Duplicates + /// are discarded. Every node in this map also implements the Notation interface. + /// The DOM Level 1 does not support editing notations, therefore notations + /// cannot be altered in any way. + /// + /// The returned NamedNodeMap must be released with a call + /// to release() when no longer needed. + + // DOM Level 2 + const XMLString & publicId() const; + /// Returns the public identifier of the external DTD subset. + + const XMLString & systemId() const; + /// Returns the system identifier of the external DTD subset. + + const XMLString & internalSubset() const; + /// Returns the internal DTD subset. This implementation + /// returns an empty string. + + // Node + const XMLString & nodeName() const; + unsigned short nodeType() const; + + protected: + DocumentType(Document * pOwner, const XMLString & name, const XMLString & publicId, const XMLString & systemId); + DocumentType(Document * pOwner, const DocumentType & dt); + ~DocumentType(); + + Node * copyNode(bool deep, Document * pOwnerDocument) const; + + private: + XMLString _name; + XMLString _publicId; + XMLString _systemId; + + friend class DOMImplementation; + friend class Document; + friend class DOMBuilder; + }; + + + // + // inlines + // + inline const XMLString & DocumentType::name() const + { + return _name; + } + + + inline const XMLString & DocumentType::publicId() const + { + return _publicId; + } + + + inline const XMLString & DocumentType::systemId() const + { + return _systemId; + } + + } - - -inline const XMLString& DocumentType::publicId() const -{ - return _publicId; -} - - -inline const XMLString& DocumentType::systemId() const -{ - return _systemId; -} - - -} } // namespace Poco::XML +} // namespace Poco::XML #endif // DOM_DocumentType_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/Element.h b/base/poco/XML/include/Poco/DOM/Element.h index 90217baab84..5371d57f69d 100644 --- a/base/poco/XML/include/Poco/DOM/Element.h +++ b/base/poco/XML/include/Poco/DOM/Element.h @@ -18,202 +18,206 @@ #define DOM_Element_INCLUDED -#include "Poco/XML/XML.h" #include "Poco/DOM/AbstractContainerNode.h" #include "Poco/XML/Name.h" +#include "Poco/XML/XML.h" -namespace Poco { -namespace XML { - - -class Attr; -class NodeList; -class Document; - - -class XML_API Element: public AbstractContainerNode - /// The Element interface represents an element in an XML document. - /// Elements may have attributes associated with them; since the Element interface - /// inherits from Node, the generic Node interface attribute attributes may - /// be used to retrieve the set of all attributes for an element. There are - /// methods on the Element interface to retrieve either an Attr object by name - /// or an attribute value by name. In XML, where an attribute value may contain - /// entity references, an Attr object should be retrieved to examine the possibly - /// fairly complex sub-tree representing the attribute value. +namespace Poco { -public: - const XMLString& tagName() const; - /// Returns the name of the element. - /// - /// For example, in - /// - /// - /// ... - /// - /// - /// tagName has the value "elementExample". Note that this is case-preserving in XML, - /// as are all of the operations of the DOM. - - const XMLString& getAttribute(const XMLString& name) const; - /// Retrieves an attribute value by name. - /// - /// Returns the attribute's value, if the attribute - /// exists, or an empty string otherwise. - - void setAttribute(const XMLString& name, const XMLString& value); - /// Adds a new attribute. If an attribute with that name is already present - /// in the element, its value is changed to be that of the value parameter. - /// This value is a simple string; it is not parsed as it is being set. So any - /// markup (such as syntax to be recognized as an entity reference) is treated - /// as literal text, and needs to be appropriately escaped by the implementation - /// when it is written out. - - void removeAttribute(const XMLString& name); - /// Removes an attribute by name. - - Attr* getAttributeNode(const XMLString& name) const; - /// Retrieves an Attr node by name. - - Attr* setAttributeNode(Attr* newAttr); - /// Adds a new attribute. If an attribute with that name is already - /// present in the element, it is replaced by the new one. - - Attr* addAttributeNodeNP(Attr* oldAttr, Attr* newAttr); - /// For internal use only. - /// Adds a new attribute after oldAttr. - /// If oldAttr is 0, newAttr is set as first attribute. - /// Returns newAttr. - /// Does not fire any events. - - Attr* removeAttributeNode(Attr* oldAttr); - /// Removes the specified attribute. - - NodeList* getElementsByTagName(const XMLString& name) const; - /// Returns a NodeList of all descendant elements with a given tag - /// name, in the order in which they would be encountered in a - /// preorder traversal of the Element tree. - /// - /// The special name "*" matches all tags. - /// - /// The returned NodeList must be released with a call - /// to release() when no longer needed. - - void normalize(); - /// Puts all Text nodes in the full depth of the sub-tree underneath this Element, - /// including attribute nodes, into a "normal" form where only markup (e.g., - /// tags, comments, processing instructions, CDATA sections, and entity references) - /// separates Text nodes, i.e., there are no adjacent Text nodes. This can be - /// used to ensure that the DOM view of a document is the same as if it were - /// saved and re-loaded, and is useful when operations (such as XPointer - /// lookups) that depend on a particular document tree structure are to be used. - /// - /// Note: In cases where the document contains CDATASections, the normalize - /// operation alone may not be sufficient, since XPointers do not differentiate - /// between Text nodes and CDATASection nodes. - - // DOM Level 2 - const XMLString& getAttributeNS(const XMLString& namespaceURI, const XMLString& localName) const; - /// Retrieves an attribute value by name. - /// - /// Returns the attribute's value, if the attribute - /// exists, or an empty string otherwise. - - void setAttributeNS(const XMLString& namespaceURI, const XMLString& qualifiedName, const XMLString& value); - /// Adds a new attribute. If an attribute with that name - /// is already present in the element, its value is changed - /// to be that of the value parameter. - - void removeAttributeNS(const XMLString& namespaceURI, const XMLString& localName); - /// Removes an attribute by name. - - Attr* getAttributeNodeNS(const XMLString& namespaceURI, const XMLString& localName) const; - /// Retrieves an Attr node by name. - - Attr* setAttributeNodeNS(Attr* newAttr); - /// Adds a new attribute. If an attribute with that name is already - /// present in the element, it is replaced by the new one. - - bool hasAttribute(const XMLString& name) const; - /// Returns true if and only if the element has the specified attribute. - - bool hasAttributeNS(const XMLString& namespaceURI, const XMLString& localName) const; - /// Returns true if and only if the element has the specified attribute. - - NodeList* getElementsByTagNameNS(const XMLString& namespaceURI, const XMLString& localName) const; - /// Returns a NodeList of all the descendant Elements with a given local name and namespace URI - /// in the order in which they are encountered in a preorder traversal of this Element tree. - /// - /// The special value "*" matches all namespaces, or local names respectively. - /// - /// The returned NodeList must be released with a call - /// to release() when no longer needed. - - const XMLString& namespaceURI() const; - XMLString prefix() const; - const XMLString& localName() const; - bool hasAttributes() const; - XMLString innerText() const; - - Element* getChildElement(const XMLString& name) const; - /// Returns the first child element with the given name, or null - /// if such an element does not exist. - /// - /// This method is an extension to the W3C Document Object Model. - - Element* getChildElementNS(const XMLString& namespaceURI, const XMLString& localName) const; - /// Returns the first child element with the given namespaceURI and localName, - /// or null if such an element does not exist. - /// - /// This method is an extension to the W3C Document Object Model. - - Element* getElementById(const XMLString& elementId, const XMLString& idAttribute) const; - /// Returns the first Element whose ID attribute (given in idAttribute) - /// has the given elementId. If no such element exists, returns null. - /// - /// This method is an extension to the W3C Document Object Model. - - Element* getElementByIdNS(const XMLString& elementId, const XMLString& idAttributeURI, const XMLString& idAttributeLocalName) const; - /// Returns the first Element whose ID attribute (given in idAttributeURI and idAttributeLocalName) - /// has the given elementId. If no such element exists, returns null. - /// - /// This method is an extension to the W3C Document Object Model. - - // Node - const XMLString& nodeName() const; - NamedNodeMap* attributes() const; - unsigned short nodeType() const; - -protected: - Element(Document* pOwnerDocument, const XMLString& namespaceURI, const XMLString& localName, const XMLString& qname); - Element(Document* pOwnerDocument, const Element& elem); - ~Element(); - - Node* copyNode(bool deep, Document* pOwnerDocument) const; - - void dispatchNodeRemovedFromDocument(); - void dispatchNodeInsertedIntoDocument(); - -private: - const Name& _name; - Attr* _pFirstAttr; - - friend class Attr; - friend class Document; - friend class AttrMap; -}; - - -// -// inlines -// -inline const XMLString& Element::tagName() const +namespace XML { - return _name.qname(); + + + class Attr; + class NodeList; + class Document; + + + class XML_API Element : public AbstractContainerNode + /// The Element interface represents an element in an XML document. + /// Elements may have attributes associated with them; since the Element interface + /// inherits from Node, the generic Node interface attribute attributes may + /// be used to retrieve the set of all attributes for an element. There are + /// methods on the Element interface to retrieve either an Attr object by name + /// or an attribute value by name. In XML, where an attribute value may contain + /// entity references, an Attr object should be retrieved to examine the possibly + /// fairly complex sub-tree representing the attribute value. + { + public: + const XMLString & tagName() const; + /// Returns the name of the element. + /// + /// For example, in + /// + /// + /// ... + /// + /// + /// tagName has the value "elementExample". Note that this is case-preserving in XML, + /// as are all of the operations of the DOM. + + const XMLString & getAttribute(const XMLString & name) const; + /// Retrieves an attribute value by name. + /// + /// Returns the attribute's value, if the attribute + /// exists, or an empty string otherwise. + + void setAttribute(const XMLString & name, const XMLString & value); + /// Adds a new attribute. If an attribute with that name is already present + /// in the element, its value is changed to be that of the value parameter. + /// This value is a simple string; it is not parsed as it is being set. So any + /// markup (such as syntax to be recognized as an entity reference) is treated + /// as literal text, and needs to be appropriately escaped by the implementation + /// when it is written out. + + void removeAttribute(const XMLString & name); + /// Removes an attribute by name. + + Attr * getAttributeNode(const XMLString & name) const; + /// Retrieves an Attr node by name. + + Attr * setAttributeNode(Attr * newAttr); + /// Adds a new attribute. If an attribute with that name is already + /// present in the element, it is replaced by the new one. + + Attr * addAttributeNodeNP(Attr * oldAttr, Attr * newAttr); + /// For internal use only. + /// Adds a new attribute after oldAttr. + /// If oldAttr is 0, newAttr is set as first attribute. + /// Returns newAttr. + /// Does not fire any events. + + Attr * removeAttributeNode(Attr * oldAttr); + /// Removes the specified attribute. + + NodeList * getElementsByTagName(const XMLString & name) const; + /// Returns a NodeList of all descendant elements with a given tag + /// name, in the order in which they would be encountered in a + /// preorder traversal of the Element tree. + /// + /// The special name "*" matches all tags. + /// + /// The returned NodeList must be released with a call + /// to release() when no longer needed. + + void normalize(); + /// Puts all Text nodes in the full depth of the sub-tree underneath this Element, + /// including attribute nodes, into a "normal" form where only markup (e.g., + /// tags, comments, processing instructions, CDATA sections, and entity references) + /// separates Text nodes, i.e., there are no adjacent Text nodes. This can be + /// used to ensure that the DOM view of a document is the same as if it were + /// saved and re-loaded, and is useful when operations (such as XPointer + /// lookups) that depend on a particular document tree structure are to be used. + /// + /// Note: In cases where the document contains CDATASections, the normalize + /// operation alone may not be sufficient, since XPointers do not differentiate + /// between Text nodes and CDATASection nodes. + + // DOM Level 2 + const XMLString & getAttributeNS(const XMLString & namespaceURI, const XMLString & localName) const; + /// Retrieves an attribute value by name. + /// + /// Returns the attribute's value, if the attribute + /// exists, or an empty string otherwise. + + void setAttributeNS(const XMLString & namespaceURI, const XMLString & qualifiedName, const XMLString & value); + /// Adds a new attribute. If an attribute with that name + /// is already present in the element, its value is changed + /// to be that of the value parameter. + + void removeAttributeNS(const XMLString & namespaceURI, const XMLString & localName); + /// Removes an attribute by name. + + Attr * getAttributeNodeNS(const XMLString & namespaceURI, const XMLString & localName) const; + /// Retrieves an Attr node by name. + + Attr * setAttributeNodeNS(Attr * newAttr); + /// Adds a new attribute. If an attribute with that name is already + /// present in the element, it is replaced by the new one. + + bool hasAttribute(const XMLString & name) const; + /// Returns true if and only if the element has the specified attribute. + + bool hasAttributeNS(const XMLString & namespaceURI, const XMLString & localName) const; + /// Returns true if and only if the element has the specified attribute. + + NodeList * getElementsByTagNameNS(const XMLString & namespaceURI, const XMLString & localName) const; + /// Returns a NodeList of all the descendant Elements with a given local name and namespace URI + /// in the order in which they are encountered in a preorder traversal of this Element tree. + /// + /// The special value "*" matches all namespaces, or local names respectively. + /// + /// The returned NodeList must be released with a call + /// to release() when no longer needed. + + const XMLString & namespaceURI() const; + XMLString prefix() const; + const XMLString & localName() const; + bool hasAttributes() const; + XMLString innerText() const; + + Element * getChildElement(const XMLString & name) const; + /// Returns the first child element with the given name, or null + /// if such an element does not exist. + /// + /// This method is an extension to the W3C Document Object Model. + + Element * getChildElementNS(const XMLString & namespaceURI, const XMLString & localName) const; + /// Returns the first child element with the given namespaceURI and localName, + /// or null if such an element does not exist. + /// + /// This method is an extension to the W3C Document Object Model. + + Element * getElementById(const XMLString & elementId, const XMLString & idAttribute) const; + /// Returns the first Element whose ID attribute (given in idAttribute) + /// has the given elementId. If no such element exists, returns null. + /// + /// This method is an extension to the W3C Document Object Model. + + Element * + getElementByIdNS(const XMLString & elementId, const XMLString & idAttributeURI, const XMLString & idAttributeLocalName) const; + /// Returns the first Element whose ID attribute (given in idAttributeURI and idAttributeLocalName) + /// has the given elementId. If no such element exists, returns null. + /// + /// This method is an extension to the W3C Document Object Model. + + // Node + const XMLString & nodeName() const; + NamedNodeMap * attributes() const; + unsigned short nodeType() const; + + protected: + Element(Document * pOwnerDocument, const XMLString & namespaceURI, const XMLString & localName, const XMLString & qname); + Element(Document * pOwnerDocument, const Element & elem); + ~Element(); + + Node * copyNode(bool deep, Document * pOwnerDocument) const; + + void dispatchNodeRemovedFromDocument(); + void dispatchNodeInsertedIntoDocument(); + + private: + const Name & _name; + Attr * _pFirstAttr; + + friend class Attr; + friend class Document; + friend class AttrMap; + }; + + + // + // inlines + // + inline const XMLString & Element::tagName() const + { + return _name.qname(); + } + + } - - -} } // namespace Poco::XML +} // namespace Poco::XML #endif // DOM_Element_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/ElementsByTagNameList.h b/base/poco/XML/include/Poco/DOM/ElementsByTagNameList.h index 98af2e82075..37f35a7ad43 100644 --- a/base/poco/XML/include/Poco/DOM/ElementsByTagNameList.h +++ b/base/poco/XML/include/Poco/DOM/ElementsByTagNameList.h @@ -18,69 +18,72 @@ #define DOM_ElementsByTagNameList_INCLUDED -#include "Poco/XML/XML.h" #include "Poco/DOM/NodeList.h" +#include "Poco/XML/XML.h" #include "Poco/XML/XMLString.h" -namespace Poco { -namespace XML { - - -class XML_API ElementsByTagNameList: public NodeList - // This implementation of NodeList is returned - // by Document::getElementsByTagName() and - // Element::getElementsByTagName(). +namespace Poco { -public: - Node* item(unsigned long index) const; - unsigned long length() const; - void autoRelease(); - -protected: - ElementsByTagNameList(const Node* pParent, const XMLString& name); - ~ElementsByTagNameList(); - - Node* find(const Node* pParent, unsigned long index) const; - - const Node* _pParent; - XMLString _name; - mutable unsigned long _count; - - friend class AbstractContainerNode; - friend class Element; - friend class Document; -}; - - -class XML_API ElementsByTagNameListNS: public NodeList - // This implementation of NodeList is returned - // by Document::getElementsByTagNameNS() and - // Element::getElementsByTagNameNS(). +namespace XML { -public: - virtual Node* item(unsigned long index) const; - virtual unsigned long length() const; - virtual void autoRelease(); - -protected: - ElementsByTagNameListNS(const Node* pParent, const XMLString& namespaceURI, const XMLString& localName); - ~ElementsByTagNameListNS(); - - Node* find(const Node* pParent, unsigned long index) const; - - const Node* _pParent; - XMLString _localName; - XMLString _namespaceURI; - mutable unsigned long _count; - - friend class AbstractContainerNode; - friend class Element; - friend class Document; -}; -} } // namespace Poco::XML + class XML_API ElementsByTagNameList : public NodeList + // This implementation of NodeList is returned + // by Document::getElementsByTagName() and + // Element::getElementsByTagName(). + { + public: + Node * item(unsigned long index) const; + unsigned long length() const; + void autoRelease(); + + protected: + ElementsByTagNameList(const Node * pParent, const XMLString & name); + ~ElementsByTagNameList(); + + Node * find(const Node * pParent, unsigned long index) const; + + const Node * _pParent; + XMLString _name; + mutable unsigned long _count; + + friend class AbstractContainerNode; + friend class Element; + friend class Document; + }; + + + class XML_API ElementsByTagNameListNS : public NodeList + // This implementation of NodeList is returned + // by Document::getElementsByTagNameNS() and + // Element::getElementsByTagNameNS(). + { + public: + virtual Node * item(unsigned long index) const; + virtual unsigned long length() const; + virtual void autoRelease(); + + protected: + ElementsByTagNameListNS(const Node * pParent, const XMLString & namespaceURI, const XMLString & localName); + ~ElementsByTagNameListNS(); + + Node * find(const Node * pParent, unsigned long index) const; + + const Node * _pParent; + XMLString _localName; + XMLString _namespaceURI; + mutable unsigned long _count; + + friend class AbstractContainerNode; + friend class Element; + friend class Document; + }; + + +} +} // namespace Poco::XML #endif // DOM_ElementsByTagNameList_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/Entity.h b/base/poco/XML/include/Poco/DOM/Entity.h index 40c21f59cde..04e33dc7031 100644 --- a/base/poco/XML/include/Poco/DOM/Entity.h +++ b/base/poco/XML/include/Poco/DOM/Entity.h @@ -18,109 +18,117 @@ #define DOM_Entity_INCLUDED -#include "Poco/XML/XML.h" #include "Poco/DOM/AbstractContainerNode.h" +#include "Poco/XML/XML.h" #include "Poco/XML/XMLString.h" -namespace Poco { -namespace XML { - - -class XML_API Entity: public AbstractContainerNode - /// This interface represents an entity, either parsed or unparsed, in an XML - /// document. Note that this models the entity itself not the entity declaration. - /// Entity declaration modeling has been left for a later Level of the DOM - /// specification. - /// - /// The nodeName attribute that is inherited from Node contains the name of - /// the entity. - /// - /// An XML processor may choose to completely expand entities before the structure - /// model is passed to the DOM; in this case there will be no EntityReference - /// nodes in the document tree. - /// - /// XML does not mandate that a non-validating XML processor read and process - /// entity declarations made in the external subset or declared in external - /// parameter entities. This means that parsed entities declared in the external - /// subset need not be expanded by some classes of applications, and that the - /// replacement value of the entity may not be available. When the replacement - /// value is available, the corresponding Entity node's child list represents - /// the structure of that replacement text. Otherwise, the child list is empty. - /// - /// The resolution of the children of the Entity (the replacement value) may - /// be lazily evaluated; actions by the user (such as calling the childNodes - /// method on the Entity Node) are assumed to trigger the evaluation. - /// - /// The DOM Level 1 does not support editing Entity nodes; if a user wants to - /// make changes to the contents of an Entity, every related EntityReference - /// node has to be replaced in the structure model by a clone of the Entity's - /// contents, and then the desired changes must be made to each of those clones - /// instead. Entity nodes and all their descendants are readonly. - /// - /// An Entity node does not have any parent. +namespace Poco { -public: - const XMLString& publicId() const; - /// Returns the public identifier associated with - /// the entity, if specified. If the public identifier - /// was not specified, this is the empty string. - - const XMLString& systemId() const; - /// Returns the system identifier associated with - /// the entity, if specified. If the system identifier - /// was not specified, this is the empty string. - - const XMLString& notationName() const; - /// Returns, for unparsed entities, the name of the - /// notation for the entity. For parsed entities, this - /// is the empty string. - - // Node - const XMLString& nodeName() const; - unsigned short nodeType() const; - -protected: - Entity(Document* pOwnerDocument, const XMLString& name, const XMLString& publicId, const XMLString& systemId, const XMLString& notationName); - Entity(Document* pOwnerDocument, const Entity& entity); - ~Entity(); - - Node* copyNode(bool deep, Document* pOwnerDocument) const; - -private: - static const XMLString NODE_NAME; - - XMLString _name; - XMLString _publicId; - XMLString _systemId; - XMLString _notationName; - - friend class Document; -}; - - -// -// inlines -// -inline const XMLString& Entity::publicId() const +namespace XML { - return _publicId; + + + class XML_API Entity : public AbstractContainerNode + /// This interface represents an entity, either parsed or unparsed, in an XML + /// document. Note that this models the entity itself not the entity declaration. + /// Entity declaration modeling has been left for a later Level of the DOM + /// specification. + /// + /// The nodeName attribute that is inherited from Node contains the name of + /// the entity. + /// + /// An XML processor may choose to completely expand entities before the structure + /// model is passed to the DOM; in this case there will be no EntityReference + /// nodes in the document tree. + /// + /// XML does not mandate that a non-validating XML processor read and process + /// entity declarations made in the external subset or declared in external + /// parameter entities. This means that parsed entities declared in the external + /// subset need not be expanded by some classes of applications, and that the + /// replacement value of the entity may not be available. When the replacement + /// value is available, the corresponding Entity node's child list represents + /// the structure of that replacement text. Otherwise, the child list is empty. + /// + /// The resolution of the children of the Entity (the replacement value) may + /// be lazily evaluated; actions by the user (such as calling the childNodes + /// method on the Entity Node) are assumed to trigger the evaluation. + /// + /// The DOM Level 1 does not support editing Entity nodes; if a user wants to + /// make changes to the contents of an Entity, every related EntityReference + /// node has to be replaced in the structure model by a clone of the Entity's + /// contents, and then the desired changes must be made to each of those clones + /// instead. Entity nodes and all their descendants are readonly. + /// + /// An Entity node does not have any parent. + { + public: + const XMLString & publicId() const; + /// Returns the public identifier associated with + /// the entity, if specified. If the public identifier + /// was not specified, this is the empty string. + + const XMLString & systemId() const; + /// Returns the system identifier associated with + /// the entity, if specified. If the system identifier + /// was not specified, this is the empty string. + + const XMLString & notationName() const; + /// Returns, for unparsed entities, the name of the + /// notation for the entity. For parsed entities, this + /// is the empty string. + + // Node + const XMLString & nodeName() const; + unsigned short nodeType() const; + + protected: + Entity( + Document * pOwnerDocument, + const XMLString & name, + const XMLString & publicId, + const XMLString & systemId, + const XMLString & notationName); + Entity(Document * pOwnerDocument, const Entity & entity); + ~Entity(); + + Node * copyNode(bool deep, Document * pOwnerDocument) const; + + private: + static const XMLString NODE_NAME; + + XMLString _name; + XMLString _publicId; + XMLString _systemId; + XMLString _notationName; + + friend class Document; + }; + + + // + // inlines + // + inline const XMLString & Entity::publicId() const + { + return _publicId; + } + + + inline const XMLString & Entity::systemId() const + { + return _systemId; + } + + + inline const XMLString & Entity::notationName() const + { + return _notationName; + } + + } - - -inline const XMLString& Entity::systemId() const -{ - return _systemId; -} - - -inline const XMLString& Entity::notationName() const -{ - return _notationName; -} - - -} } // namespace Poco::XML +} // namespace Poco::XML #endif // DOM_Entity_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/EntityReference.h b/base/poco/XML/include/Poco/DOM/EntityReference.h index 5ecd044b577..06fb421e0cc 100644 --- a/base/poco/XML/include/Poco/DOM/EntityReference.h +++ b/base/poco/XML/include/Poco/DOM/EntityReference.h @@ -18,56 +18,59 @@ #define DOM_EntityReference_INCLUDED -#include "Poco/XML/XML.h" #include "Poco/DOM/AbstractNode.h" +#include "Poco/XML/XML.h" #include "Poco/XML/XMLString.h" -namespace Poco { -namespace XML { - - -class XML_API EntityReference: public AbstractNode - /// EntityReference objects may be inserted into the structure model when an - /// entity reference is in the source document, or when the user wishes to insert - /// an entity reference. Note that character references and references to predefined - /// entities are considered to be expanded by the HTML or XML processor so that - /// characters are represented by their Unicode equivalent rather than by an - /// entity reference. Moreover, the XML processor may completely expand references - /// to entities while building the structure model, instead of providing EntityReference - /// objects. If it does provide such objects, then for a given EntityReference - /// node, it may be that there is no Entity node representing the referenced - /// entity. If such an Entity exists, then the child list of the EntityReference - /// node is the same as that of the Entity node. - /// - /// As for Entity nodes, EntityReference nodes and all their descendants are - /// readonly. - /// - /// The resolution of the children of the EntityReference (the replacement value - /// of the referenced Entity) may be lazily evaluated; actions by the user (such - /// as calling the childNodes method on the EntityReference node) are assumed - /// to trigger the evaluation. +namespace Poco +{ +namespace XML { -public: - // Node - const XMLString& nodeName() const; - unsigned short nodeType() const; - -protected: - EntityReference(Document* pOwnerDocument, const XMLString& name); - EntityReference(Document* pOwnerDocument, const EntityReference& ref); - ~EntityReference(); - - Node* copyNode(bool deep, Document* pOwnerDocument) const; - -private: - XMLString _name; - - friend class Document; -}; -} } // namespace Poco::XML + class XML_API EntityReference : public AbstractNode + /// EntityReference objects may be inserted into the structure model when an + /// entity reference is in the source document, or when the user wishes to insert + /// an entity reference. Note that character references and references to predefined + /// entities are considered to be expanded by the HTML or XML processor so that + /// characters are represented by their Unicode equivalent rather than by an + /// entity reference. Moreover, the XML processor may completely expand references + /// to entities while building the structure model, instead of providing EntityReference + /// objects. If it does provide such objects, then for a given EntityReference + /// node, it may be that there is no Entity node representing the referenced + /// entity. If such an Entity exists, then the child list of the EntityReference + /// node is the same as that of the Entity node. + /// + /// As for Entity nodes, EntityReference nodes and all their descendants are + /// readonly. + /// + /// The resolution of the children of the EntityReference (the replacement value + /// of the referenced Entity) may be lazily evaluated; actions by the user (such + /// as calling the childNodes method on the EntityReference node) are assumed + /// to trigger the evaluation. + { + public: + // Node + const XMLString & nodeName() const; + unsigned short nodeType() const; + + protected: + EntityReference(Document * pOwnerDocument, const XMLString & name); + EntityReference(Document * pOwnerDocument, const EntityReference & ref); + ~EntityReference(); + + Node * copyNode(bool deep, Document * pOwnerDocument) const; + + private: + XMLString _name; + + friend class Document; + }; + + +} +} // namespace Poco::XML #endif // DOM_EntityReference_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/Event.h b/base/poco/XML/include/Poco/DOM/Event.h index 5396aa3f5a4..e8c8e7b87a6 100644 --- a/base/poco/XML/include/Poco/DOM/Event.h +++ b/base/poco/XML/include/Poco/DOM/Event.h @@ -18,192 +18,195 @@ #define DOM_Event_INCLUDED +#include "Poco/DOM/DOMObject.h" #include "Poco/XML/XML.h" #include "Poco/XML/XMLString.h" -#include "Poco/DOM/DOMObject.h" -namespace Poco { -namespace XML { - - -class EventTarget; -class Document; - - -class XML_API Event: public DOMObject - /// The Event interface is used to provide contextual information about an event - /// to the handler processing the event. An object which implements the Event - /// interface is generally passed as the first parameter to an event handler. - /// More specific context information is passed to event handlers by deriving - /// additional interfaces from Event which contain information directly relating - /// to the type of event they accompany. These derived interfaces are also implemented - /// by the object passed to the event listener. +namespace Poco { -public: - enum PhaseType - { - CAPTURING_PHASE = 1, /// The event is currently being evaluated at the target EventTarget. - AT_TARGET = 2, /// The current event phase is the bubbling phase. - BUBBLING_PHASE = 3 /// The current event phase is the capturing phase. - }; - - const XMLString& type() const; - /// The name of the event (case-insensitive). The name must be an XML name. - - EventTarget* target() const; - /// Used to indicate the EventTarget to which the event was originally dispatched. - - EventTarget* currentTarget() const; - /// Used to indicate the EventTarget whose EventListeners are currently being - /// processed. This is particularly useful during capturing and bubbling. - - PhaseType eventPhase() const; - /// Used to indicate which phase of event flow is currently being evaluated. - - bool bubbles() const; - /// Used to indicate whether or not an event is a bubbling event. - /// If the event can bubble the value is true, else the value is false. - - bool cancelable() const; - /// Used to indicate whether or not an event can have its default action - /// prevented. If the default action can be prevented the value is - /// true, else the value is false. - - Poco::UInt64 timeStamp() const; - /// Used to specify the time (in milliseconds relative to the epoch) at - /// which the event was created. Due to the fact that some - /// systems may not provide this information the value of timeStamp may - /// be not available for all events. When not available, a - /// value of 0 will be returned. Examples of epoch time are the time of the - /// system start or 0:0:0 UTC 1st January 1970. - /// This implementation always returns 0. - - void stopPropagation(); - /// The stopPropagation method is used prevent further propagation of an - /// event during event flow. If this method is called by - /// any EventListener the event will cease propagating through the tree. - /// The event will complete dispatch to all listeners on the - /// current EventTarget before event flow stops. This method may be used - /// during any stage of event flow. - - void preventDefault(); - /// If an event is cancelable, the preventDefault method is used to signify - /// that the event is to be canceled, meaning any default - /// action normally taken by the implementation as a result of - /// the event will not occur. If, during any stage of event flow, the - /// preventDefault method is called the event is canceled. Any default - /// action associated with the event will not occur. Calling - /// this method for a non-cancelable event has no effect. Once - /// preventDefault has been called it will remain in effect throughout - /// the remainder of the event's propagation. This method may be - /// used during any stage of event flow. - - void initEvent(const XMLString& eventType, bool canBubble, bool isCancelable); - /// The initEvent method is used to initialize the value of an - /// Event created through the DocumentEvent interface. This method - /// may only be called before the Event has been dispatched via the - /// dispatchEvent method, though it may be called multiple - /// times during that phase if necessary. If called multiple - /// times the final invocation takes precedence. If called from - /// a subclass of Event interface only the values specified in the - /// initEvent method are modified, all other attributes are left unchanged. - - void autoRelease(); - -protected: - Event(Document* pOwnerDocument, const XMLString& type); - Event(Document* pOwnerDocument, const XMLString& type, EventTarget* pTarget, bool canBubble, bool isCancelable); - ~Event(); - - bool isCanceled() const; - /// returns true if and only if the event has been cancelled. - - bool isStopped() const; - /// returns true if and only if propagation of the event has been stopped. - - void setTarget(EventTarget* pTarget); - /// sets the target - - void setCurrentPhase(PhaseType phase); - /// sets the current phase - - void setCurrentTarget(EventTarget* pTarget); - /// sets the current target - -private: - Document* _pOwner; - XMLString _type; - EventTarget* _pTarget; - EventTarget* _pCurrentTarget; - PhaseType _currentPhase; - bool _bubbles; - bool _cancelable; - bool _canceled; - bool _stopped; - - friend class AbstractNode; -}; - - -// -// inlines -// -inline const XMLString& Event::type() const +namespace XML { - return _type; + + + class EventTarget; + class Document; + + + class XML_API Event : public DOMObject + /// The Event interface is used to provide contextual information about an event + /// to the handler processing the event. An object which implements the Event + /// interface is generally passed as the first parameter to an event handler. + /// More specific context information is passed to event handlers by deriving + /// additional interfaces from Event which contain information directly relating + /// to the type of event they accompany. These derived interfaces are also implemented + /// by the object passed to the event listener. + { + public: + enum PhaseType + { + CAPTURING_PHASE = 1, /// The event is currently being evaluated at the target EventTarget. + AT_TARGET = 2, /// The current event phase is the bubbling phase. + BUBBLING_PHASE = 3 /// The current event phase is the capturing phase. + }; + + const XMLString & type() const; + /// The name of the event (case-insensitive). The name must be an XML name. + + EventTarget * target() const; + /// Used to indicate the EventTarget to which the event was originally dispatched. + + EventTarget * currentTarget() const; + /// Used to indicate the EventTarget whose EventListeners are currently being + /// processed. This is particularly useful during capturing and bubbling. + + PhaseType eventPhase() const; + /// Used to indicate which phase of event flow is currently being evaluated. + + bool bubbles() const; + /// Used to indicate whether or not an event is a bubbling event. + /// If the event can bubble the value is true, else the value is false. + + bool cancelable() const; + /// Used to indicate whether or not an event can have its default action + /// prevented. If the default action can be prevented the value is + /// true, else the value is false. + + Poco::UInt64 timeStamp() const; + /// Used to specify the time (in milliseconds relative to the epoch) at + /// which the event was created. Due to the fact that some + /// systems may not provide this information the value of timeStamp may + /// be not available for all events. When not available, a + /// value of 0 will be returned. Examples of epoch time are the time of the + /// system start or 0:0:0 UTC 1st January 1970. + /// This implementation always returns 0. + + void stopPropagation(); + /// The stopPropagation method is used prevent further propagation of an + /// event during event flow. If this method is called by + /// any EventListener the event will cease propagating through the tree. + /// The event will complete dispatch to all listeners on the + /// current EventTarget before event flow stops. This method may be used + /// during any stage of event flow. + + void preventDefault(); + /// If an event is cancelable, the preventDefault method is used to signify + /// that the event is to be canceled, meaning any default + /// action normally taken by the implementation as a result of + /// the event will not occur. If, during any stage of event flow, the + /// preventDefault method is called the event is canceled. Any default + /// action associated with the event will not occur. Calling + /// this method for a non-cancelable event has no effect. Once + /// preventDefault has been called it will remain in effect throughout + /// the remainder of the event's propagation. This method may be + /// used during any stage of event flow. + + void initEvent(const XMLString & eventType, bool canBubble, bool isCancelable); + /// The initEvent method is used to initialize the value of an + /// Event created through the DocumentEvent interface. This method + /// may only be called before the Event has been dispatched via the + /// dispatchEvent method, though it may be called multiple + /// times during that phase if necessary. If called multiple + /// times the final invocation takes precedence. If called from + /// a subclass of Event interface only the values specified in the + /// initEvent method are modified, all other attributes are left unchanged. + + void autoRelease(); + + protected: + Event(Document * pOwnerDocument, const XMLString & type); + Event(Document * pOwnerDocument, const XMLString & type, EventTarget * pTarget, bool canBubble, bool isCancelable); + ~Event(); + + bool isCanceled() const; + /// returns true if and only if the event has been cancelled. + + bool isStopped() const; + /// returns true if and only if propagation of the event has been stopped. + + void setTarget(EventTarget * pTarget); + /// sets the target + + void setCurrentPhase(PhaseType phase); + /// sets the current phase + + void setCurrentTarget(EventTarget * pTarget); + /// sets the current target + + private: + Document * _pOwner; + XMLString _type; + EventTarget * _pTarget; + EventTarget * _pCurrentTarget; + PhaseType _currentPhase; + bool _bubbles; + bool _cancelable; + bool _canceled; + bool _stopped; + + friend class AbstractNode; + }; + + + // + // inlines + // + inline const XMLString & Event::type() const + { + return _type; + } + + + inline EventTarget * Event::target() const + { + return _pTarget; + } + + + inline EventTarget * Event::currentTarget() const + { + return _pCurrentTarget; + } + + + inline Event::PhaseType Event::eventPhase() const + { + return _currentPhase; + } + + + inline bool Event::bubbles() const + { + return _bubbles; + } + + + inline bool Event::cancelable() const + { + return _cancelable; + } + + + inline Poco::UInt64 Event::timeStamp() const + { + return 0; + } + + + inline bool Event::isCanceled() const + { + return _canceled; + } + + + inline bool Event::isStopped() const + { + return _stopped; + } + + } - - -inline EventTarget* Event::target() const -{ - return _pTarget; -} - - -inline EventTarget* Event::currentTarget() const -{ - return _pCurrentTarget; -} - - -inline Event::PhaseType Event::eventPhase() const -{ - return _currentPhase; -} - - -inline bool Event::bubbles() const -{ - return _bubbles; -} - - -inline bool Event::cancelable() const -{ - return _cancelable; -} - - -inline Poco::UInt64 Event::timeStamp() const -{ - return 0; -} - - -inline bool Event::isCanceled() const -{ - return _canceled; -} - - -inline bool Event::isStopped() const -{ - return _stopped; -} - - -} } // namespace Poco::XML +} // namespace Poco::XML #endif // DOM_Event_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/EventDispatcher.h b/base/poco/XML/include/Poco/DOM/EventDispatcher.h index 4e825df9c4a..c7955a5c80a 100644 --- a/base/poco/XML/include/Poco/DOM/EventDispatcher.h +++ b/base/poco/XML/include/Poco/DOM/EventDispatcher.h @@ -18,80 +18,83 @@ #define DOM_EventDispatcher_INCLUDED +#include #include "Poco/XML/XML.h" #include "Poco/XML/XMLString.h" -#include -namespace Poco { -namespace XML { - - -class Event; -class EventListener; - - -class XML_API EventDispatcher - /// This helper class manages event listener subscriptions - /// and event dispatching for AbstractNode. - /// - /// The EventListener list is managed in such a way that - /// event listeners can be added and removed even - /// from within an EventListener, while events are being - /// dispatched. +namespace Poco +{ +namespace XML { -public: - EventDispatcher(); - /// Creates the EventDispatcher. - - ~EventDispatcher(); - /// Destroys the EventDispatcher. - - void addEventListener(const XMLString& type, EventListener* listener, bool useCapture); - /// Adds an EventListener to the internal list. - - void removeEventListener(const XMLString& type, EventListener* listener, bool useCapture); - /// Removes an EventListener from the internal list. - /// - /// If a dispatch is currently in progress, the list - /// entry is only marked for deletion. - /// If no dispatch is currently in progress, all EventListeners - /// marked for deletion are removed from the list. - - void dispatchEvent(Event* evt); - /// Dispatches the event. - /// - /// Also removes all EventListeners marked for deletion from the - /// event dispatcher list. - - void captureEvent(Event* evt); - /// Dispatches the event in its capturing phase. - /// - /// Also removes all EventListeners marked for deletion from the - /// event dispatcher list. - - void bubbleEvent(Event* evt); - /// Dispatches the event in its bubbling phase. - /// - /// Also removes all EventListeners marked for deletion from the - /// event dispatcher list. - -private: - struct EventListenerItem - { - XMLString type; - EventListener* pListener; - bool useCapture; - }; - - typedef std::list EventListenerList; - - int _inDispatch; - EventListenerList _listeners; -}; -} } // namespace Poco::XML + class Event; + class EventListener; + + + class XML_API EventDispatcher + /// This helper class manages event listener subscriptions + /// and event dispatching for AbstractNode. + /// + /// The EventListener list is managed in such a way that + /// event listeners can be added and removed even + /// from within an EventListener, while events are being + /// dispatched. + { + public: + EventDispatcher(); + /// Creates the EventDispatcher. + + ~EventDispatcher(); + /// Destroys the EventDispatcher. + + void addEventListener(const XMLString & type, EventListener * listener, bool useCapture); + /// Adds an EventListener to the internal list. + + void removeEventListener(const XMLString & type, EventListener * listener, bool useCapture); + /// Removes an EventListener from the internal list. + /// + /// If a dispatch is currently in progress, the list + /// entry is only marked for deletion. + /// If no dispatch is currently in progress, all EventListeners + /// marked for deletion are removed from the list. + + void dispatchEvent(Event * evt); + /// Dispatches the event. + /// + /// Also removes all EventListeners marked for deletion from the + /// event dispatcher list. + + void captureEvent(Event * evt); + /// Dispatches the event in its capturing phase. + /// + /// Also removes all EventListeners marked for deletion from the + /// event dispatcher list. + + void bubbleEvent(Event * evt); + /// Dispatches the event in its bubbling phase. + /// + /// Also removes all EventListeners marked for deletion from the + /// event dispatcher list. + + private: + struct EventListenerItem + { + XMLString type; + EventListener * pListener; + bool useCapture; + }; + + typedef std::list EventListenerList; + + int _inDispatch; + EventListenerList _listeners; + }; + + +} +} // namespace Poco::XML #endif // DOM_EventDispatcher_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/EventException.h b/base/poco/XML/include/Poco/DOM/EventException.h index cb824410587..40c395b79e0 100644 --- a/base/poco/XML/include/Poco/DOM/EventException.h +++ b/base/poco/XML/include/Poco/DOM/EventException.h @@ -22,60 +22,63 @@ #include "Poco/XML/XMLException.h" -namespace Poco { -namespace XML { - - -class XML_API EventException: public XMLException - /// Event operations may throw an EventException as - /// specified in their method descriptions. +namespace Poco { -public: - enum - { - UNSPECIFIED_EVENT_TYPE_ERR = 0 /// If the Event's type was not specified by initializing the - /// event before the method was called. Specification of the Event's - /// type as null or an empty string will also trigger this exception. - }; - - EventException(int code); - /// Creates an EventException with the given error code. - - EventException(const EventException& exc); - /// Creates an EventException by copying another one. - - ~EventException() noexcept; - /// Destroys the EventException. - - EventException& operator = (const EventException& exc); - - const char* name() const noexcept; - /// Returns a static string describing the exception. - - const char* className() const noexcept; - /// Returns the name of the exception class. - - unsigned short code() const; - /// Returns the Event exception code. - -protected: - Poco::Exception* clone() const; - -private: - EventException(); -}; - - -// -// inlines -// -inline unsigned short EventException::code() const +namespace XML { - return UNSPECIFIED_EVENT_TYPE_ERR; + + + class XML_API EventException : public XMLException + /// Event operations may throw an EventException as + /// specified in their method descriptions. + { + public: + enum + { + UNSPECIFIED_EVENT_TYPE_ERR = 0 /// If the Event's type was not specified by initializing the + /// event before the method was called. Specification of the Event's + /// type as null or an empty string will also trigger this exception. + }; + + EventException(int code); + /// Creates an EventException with the given error code. + + EventException(const EventException & exc); + /// Creates an EventException by copying another one. + + ~EventException() noexcept; + /// Destroys the EventException. + + EventException & operator=(const EventException & exc); + + const char * name() const noexcept; + /// Returns a static string describing the exception. + + const char * className() const noexcept; + /// Returns the name of the exception class. + + unsigned short code() const; + /// Returns the Event exception code. + + protected: + Poco::Exception * clone() const; + + private: + EventException(); + }; + + + // + // inlines + // + inline unsigned short EventException::code() const + { + return UNSPECIFIED_EVENT_TYPE_ERR; + } + + } - - -} } // namespace Poco::XML +} // namespace Poco::XML #endif // DOM_EventException_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/EventListener.h b/base/poco/XML/include/Poco/DOM/EventListener.h index f0951b10a2a..3c9908fba78 100644 --- a/base/poco/XML/include/Poco/DOM/EventListener.h +++ b/base/poco/XML/include/Poco/DOM/EventListener.h @@ -22,36 +22,39 @@ #include "Poco/XML/XMLString.h" -namespace Poco { -namespace XML { - - -class Event; - - -class XML_API EventListener - /// The EventListener interface is the primary method for handling events. Users - /// implement the EventListener interface and register their listener on an - /// EventTarget using the AddEventListener method. The users should also remove - /// their EventListener from its EventTarget after they have completed using - /// the listener. - /// - /// When a Node is copied using the cloneNode method the EventListeners attached - /// to the source Node are not attached to the copied Node. If the user wishes - /// the same EventListeners to be added to the newly created copy the user must - /// add them manually. +namespace Poco +{ +namespace XML { -public: - virtual void handleEvent(Event* evt) = 0; - /// This method is called whenever an event occurs of the - /// type for which the EventListener interface was registered. - -protected: - virtual ~EventListener(); -}; -} } // namespace Poco::XML + class Event; + + + class XML_API EventListener + /// The EventListener interface is the primary method for handling events. Users + /// implement the EventListener interface and register their listener on an + /// EventTarget using the AddEventListener method. The users should also remove + /// their EventListener from its EventTarget after they have completed using + /// the listener. + /// + /// When a Node is copied using the cloneNode method the EventListeners attached + /// to the source Node are not attached to the copied Node. If the user wishes + /// the same EventListeners to be added to the newly created copy the user must + /// add them manually. + { + public: + virtual void handleEvent(Event * evt) = 0; + /// This method is called whenever an event occurs of the + /// type for which the EventListener interface was registered. + + protected: + virtual ~EventListener(); + }; + + +} +} // namespace Poco::XML #endif // DOM_EventListener_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/EventTarget.h b/base/poco/XML/include/Poco/DOM/EventTarget.h index 466d2151ed7..d6d6ab9d709 100644 --- a/base/poco/XML/include/Poco/DOM/EventTarget.h +++ b/base/poco/XML/include/Poco/DOM/EventTarget.h @@ -18,59 +18,62 @@ #define DOM_EventTarget_INCLUDED -#include "Poco/XML/XML.h" #include "Poco/DOM/DOMObject.h" +#include "Poco/XML/XML.h" #include "Poco/XML/XMLString.h" -namespace Poco { -namespace XML { - - -class EventListener; -class Event; - - -class XML_API EventTarget: public DOMObject - /// The EventTarget interface is implemented by all Nodes in an implementation - /// which supports the DOM Event Model. Therefore, this interface can be obtained - /// by using binding-specific casting methods on an instance of the Node interface. - /// The interface allows registration and removal of EventListeners on an EventTarget - /// and dispatch of events to that EventTarget. +namespace Poco +{ +namespace XML { -public: - virtual void addEventListener(const XMLString& type, EventListener* listener, bool useCapture) = 0; - /// This method allows the registration of event listeners on - /// the event target. If an EventListener is added to an - /// EventTarget while it is processing an event, it will not - /// be triggered by the current actions but may be triggered - /// during a later stage of event flow, such as the bubbling phase. - /// If multiple identical EventListeners are registered on the same - /// EventTarget with the same parameters the duplicate instances are - /// discarded. They do not cause the EventListener to be called twice and since they are - /// discarded they do not need to be removed with the removeEventListener method. - - virtual void removeEventListener(const XMLString& type, EventListener* listener, bool useCapture) = 0; - /// This method allows the removal of event listeners from the event - /// target. If an EventListener is removed from an EventTarget while it is - /// processing an event, it will not be triggered by the current actions. - /// EventListeners can never be invoked after being removed. - /// Calling removeEventListener with arguments which do not identify - /// any currently registered EventListener on the EventTarget has no effect. - - virtual bool dispatchEvent(Event* evt) = 0; - /// This method allows the dispatch of events into the implementations - /// event model. Events dispatched in this manner will have the same capturing and - /// bubbling behavior as events dispatched directly by the - /// implementation. The target of the event is the EventTarget on - /// which dispatchEvent is called. - -protected: - virtual ~EventTarget(); -}; -} } // namespace Poco::XML + class EventListener; + class Event; + + + class XML_API EventTarget : public DOMObject + /// The EventTarget interface is implemented by all Nodes in an implementation + /// which supports the DOM Event Model. Therefore, this interface can be obtained + /// by using binding-specific casting methods on an instance of the Node interface. + /// The interface allows registration and removal of EventListeners on an EventTarget + /// and dispatch of events to that EventTarget. + { + public: + virtual void addEventListener(const XMLString & type, EventListener * listener, bool useCapture) = 0; + /// This method allows the registration of event listeners on + /// the event target. If an EventListener is added to an + /// EventTarget while it is processing an event, it will not + /// be triggered by the current actions but may be triggered + /// during a later stage of event flow, such as the bubbling phase. + /// If multiple identical EventListeners are registered on the same + /// EventTarget with the same parameters the duplicate instances are + /// discarded. They do not cause the EventListener to be called twice and since they are + /// discarded they do not need to be removed with the removeEventListener method. + + virtual void removeEventListener(const XMLString & type, EventListener * listener, bool useCapture) = 0; + /// This method allows the removal of event listeners from the event + /// target. If an EventListener is removed from an EventTarget while it is + /// processing an event, it will not be triggered by the current actions. + /// EventListeners can never be invoked after being removed. + /// Calling removeEventListener with arguments which do not identify + /// any currently registered EventListener on the EventTarget has no effect. + + virtual bool dispatchEvent(Event * evt) = 0; + /// This method allows the dispatch of events into the implementations + /// event model. Events dispatched in this manner will have the same capturing and + /// bubbling behavior as events dispatched directly by the + /// implementation. The target of the event is the EventTarget on + /// which dispatchEvent is called. + + protected: + virtual ~EventTarget(); + }; + + +} +} // namespace Poco::XML #endif // DOM_EventTarget_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/MutationEvent.h b/base/poco/XML/include/Poco/DOM/MutationEvent.h index 33a8521c501..bbdd58547f9 100644 --- a/base/poco/XML/include/Poco/DOM/MutationEvent.h +++ b/base/poco/XML/include/Poco/DOM/MutationEvent.h @@ -18,126 +18,146 @@ #define DOM_MutationEvent_INCLUDED -#include "Poco/XML/XML.h" #include "Poco/DOM/Event.h" +#include "Poco/XML/XML.h" -namespace Poco { -namespace XML { - - -class Node; - - -class XML_API MutationEvent: public Event - /// The MutationEvent interface provides specific contextual - /// information associated with Mutation events. +namespace Poco { -public: - enum AttrChangeType - { - MODIFICATION = 1, /// The Attr was modified in place. - ADDITION = 2, /// The Attr was just added. - REMOVAL = 3 /// The Attr was just removed. - }; - - Node* relatedNode() const; - /// relatedNode is used to identify a secondary node related to a mutation - /// event. For example, if a mutation event is dispatched - /// to a node indicating that its parent has changed, the relatedNode is the - /// changed parent. If an event is instead dispatched to a - /// subtree indicating a node was changed within it, the relatedNode is - /// the changed node. In the case of the DOMAttrModified - /// event it indicates the Attr node which was modified, added, or removed. - - const XMLString& prevValue() const; - /// prevValue indicates the previous value of the Attr node in DOMAttrModified - /// events, and of the CharacterData node in DOMCharDataModified events. - - const XMLString& newValue() const; - /// newValue indicates the new value of the Attr node in DOMAttrModified - /// events, and of the CharacterData node in DOMCharDataModified events. - - const XMLString& attrName() const; - /// attrName indicates the name of the changed Attr node in a DOMAttrModified event. - - AttrChangeType attrChange() const; - /// attrChange indicates the type of change which triggered the - /// DOMAttrModified event. The values can be MODIFICATION, - /// ADDITION, or REMOVAL. - - void initMutationEvent(const XMLString& type, bool canBubble, bool cancelable, Node* relatedNode, - const XMLString& prevValue, const XMLString& newValue, const XMLString& attrName, AttrChangeType change); - /// The initMutationEvent method is used to initialize the value of a - /// MutationEvent created through the DocumentEvent - /// interface. This method may only be called before the MutationEvent - /// has been dispatched via the dispatchEvent method, - /// though it may be called multiple times during that phase if - /// necessary. If called multiple times, the final invocation takes - /// precedence. - - // Event Types - static const XMLString DOMSubtreeModified; - static const XMLString DOMNodeInserted; - static const XMLString DOMNodeRemoved; - static const XMLString DOMNodeRemovedFromDocument; - static const XMLString DOMNodeInsertedIntoDocument; - static const XMLString DOMAttrModified; - static const XMLString DOMCharacterDataModified; - -protected: - MutationEvent(Document* pOwnerDocument, const XMLString& type); - MutationEvent(Document* pOwnerDocument, const XMLString& type, EventTarget* pTarget, bool canBubble, bool cancelable, Node* relatedNode); - MutationEvent(Document* pOwnerDocument, const XMLString& type, EventTarget* pTarget, bool canBubble, bool cancelable, Node* relatedNode, - const XMLString& prevValue, const XMLString& newValue, const XMLString& attrName, AttrChangeType change); - ~MutationEvent(); - -private: - XMLString _prevValue; - XMLString _newValue; - XMLString _attrName; - AttrChangeType _change; - Node* _pRelatedNode; - - friend class AbstractNode; - friend class Document; -}; - - -// -// inlines -// -inline Node* MutationEvent::relatedNode() const +namespace XML { - return _pRelatedNode; + + + class Node; + + + class XML_API MutationEvent : public Event + /// The MutationEvent interface provides specific contextual + /// information associated with Mutation events. + { + public: + enum AttrChangeType + { + MODIFICATION = 1, /// The Attr was modified in place. + ADDITION = 2, /// The Attr was just added. + REMOVAL = 3 /// The Attr was just removed. + }; + + Node * relatedNode() const; + /// relatedNode is used to identify a secondary node related to a mutation + /// event. For example, if a mutation event is dispatched + /// to a node indicating that its parent has changed, the relatedNode is the + /// changed parent. If an event is instead dispatched to a + /// subtree indicating a node was changed within it, the relatedNode is + /// the changed node. In the case of the DOMAttrModified + /// event it indicates the Attr node which was modified, added, or removed. + + const XMLString & prevValue() const; + /// prevValue indicates the previous value of the Attr node in DOMAttrModified + /// events, and of the CharacterData node in DOMCharDataModified events. + + const XMLString & newValue() const; + /// newValue indicates the new value of the Attr node in DOMAttrModified + /// events, and of the CharacterData node in DOMCharDataModified events. + + const XMLString & attrName() const; + /// attrName indicates the name of the changed Attr node in a DOMAttrModified event. + + AttrChangeType attrChange() const; + /// attrChange indicates the type of change which triggered the + /// DOMAttrModified event. The values can be MODIFICATION, + /// ADDITION, or REMOVAL. + + void initMutationEvent( + const XMLString & type, + bool canBubble, + bool cancelable, + Node * relatedNode, + const XMLString & prevValue, + const XMLString & newValue, + const XMLString & attrName, + AttrChangeType change); + /// The initMutationEvent method is used to initialize the value of a + /// MutationEvent created through the DocumentEvent + /// interface. This method may only be called before the MutationEvent + /// has been dispatched via the dispatchEvent method, + /// though it may be called multiple times during that phase if + /// necessary. If called multiple times, the final invocation takes + /// precedence. + + // Event Types + static const XMLString DOMSubtreeModified; + static const XMLString DOMNodeInserted; + static const XMLString DOMNodeRemoved; + static const XMLString DOMNodeRemovedFromDocument; + static const XMLString DOMNodeInsertedIntoDocument; + static const XMLString DOMAttrModified; + static const XMLString DOMCharacterDataModified; + + protected: + MutationEvent(Document * pOwnerDocument, const XMLString & type); + MutationEvent( + Document * pOwnerDocument, const XMLString & type, EventTarget * pTarget, bool canBubble, bool cancelable, Node * relatedNode); + MutationEvent( + Document * pOwnerDocument, + const XMLString & type, + EventTarget * pTarget, + bool canBubble, + bool cancelable, + Node * relatedNode, + const XMLString & prevValue, + const XMLString & newValue, + const XMLString & attrName, + AttrChangeType change); + ~MutationEvent(); + + private: + XMLString _prevValue; + XMLString _newValue; + XMLString _attrName; + AttrChangeType _change; + Node * _pRelatedNode; + + friend class AbstractNode; + friend class Document; + }; + + + // + // inlines + // + inline Node * MutationEvent::relatedNode() const + { + return _pRelatedNode; + } + + + inline const XMLString & MutationEvent::prevValue() const + { + return _prevValue; + } + + + inline const XMLString & MutationEvent::newValue() const + { + return _newValue; + } + + + inline const XMLString & MutationEvent::attrName() const + { + return _attrName; + } + + + inline MutationEvent::AttrChangeType MutationEvent::attrChange() const + { + return _change; + } + + } - - -inline const XMLString& MutationEvent::prevValue() const -{ - return _prevValue; -} - - -inline const XMLString& MutationEvent::newValue() const -{ - return _newValue; -} - - -inline const XMLString& MutationEvent::attrName() const -{ - return _attrName; -} - - -inline MutationEvent::AttrChangeType MutationEvent::attrChange() const -{ - return _change; -} - - -} } // namespace Poco::XML +} // namespace Poco::XML #endif // DOM_MutationEvent_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/NamedNodeMap.h b/base/poco/XML/include/Poco/DOM/NamedNodeMap.h index 7b42ca88f4f..00753c99254 100644 --- a/base/poco/XML/include/Poco/DOM/NamedNodeMap.h +++ b/base/poco/XML/include/Poco/DOM/NamedNodeMap.h @@ -18,76 +18,79 @@ #define DOM_NamedNodeMap_INCLUDED -#include "Poco/XML/XML.h" #include "Poco/DOM/DOMObject.h" +#include "Poco/XML/XML.h" #include "Poco/XML/XMLString.h" -namespace Poco { -namespace XML { - - -class Node; - - -class XML_API NamedNodeMap: public DOMObject - /// Objects implementing the NamedNodeMap interface are used to represent collections - /// of nodes that can be accessed by name. Note that NamedNodeMap does not inherit - /// from NodeList; NamedNodeMaps are not maintained in any particular order. - /// Objects contained in an object implementing NamedNodeMap may also be accessed - /// by an ordinal index, but this is simply to allow convenient enumeration - /// of the contents of a NamedNodeMap, and does not imply that the DOM specifies - /// an order to these Nodes. - /// - /// NamedNodeMap objects in the DOM are live. - /// - /// A NamedNodeMap returned from a method must be released with a call to - /// release() when no longer needed. +namespace Poco +{ +namespace XML { -public: - virtual Node* getNamedItem(const XMLString& name) const = 0; - /// Retrieves a node specified by name. - - virtual Node* setNamedItem(Node* arg) = 0; - /// Adds a node using its nodeName attribute. If a node with that name is already - /// present in this map, it is replaced by the new one. - /// As the nodeName attribute is used to derive the name which the node must - /// be stored under, multiple nodes of certain types (those that have a "special" - /// string value) cannot be stored as the names would clash. This is seen as - /// preferable to allowing nodes to be aliased. - - virtual Node* removeNamedItem(const XMLString& name) = 0; - /// Removes a node specified by name. When this map contains the attributes - /// attached to an element, if the removed attribute is known to have a default - /// value, an attribute immediately appears containing the default value. - - virtual Node* item(unsigned long index) const = 0; - /// Returns the index'th item in the map. If index is greater - /// than or equal to the number of nodes in the map, this - /// returns null. - - virtual unsigned long length() const = 0; - /// Returns the number of nodes in the map. The range of valid - /// child node indices is 0 to length - 1 inclusive. - - // DOM Level 2 - virtual Node* getNamedItemNS(const XMLString& namespaceURI, const XMLString& localName) const = 0; - /// Retrieves a node specified by name. - - virtual Node* setNamedItemNS(Node* arg) = 0; - /// Adds a node using its nodeName attribute. - /// If a node with that namespace URI and that local name is already - /// present in this map, it is replaced by the new one. - - virtual Node* removeNamedItemNS(const XMLString& namespaceURI, const XMLString& localName) = 0; - /// Removes a node specified by name. - -protected: - virtual ~NamedNodeMap(); -}; -} } // namespace Poco::XML + class Node; + + + class XML_API NamedNodeMap : public DOMObject + /// Objects implementing the NamedNodeMap interface are used to represent collections + /// of nodes that can be accessed by name. Note that NamedNodeMap does not inherit + /// from NodeList; NamedNodeMaps are not maintained in any particular order. + /// Objects contained in an object implementing NamedNodeMap may also be accessed + /// by an ordinal index, but this is simply to allow convenient enumeration + /// of the contents of a NamedNodeMap, and does not imply that the DOM specifies + /// an order to these Nodes. + /// + /// NamedNodeMap objects in the DOM are live. + /// + /// A NamedNodeMap returned from a method must be released with a call to + /// release() when no longer needed. + { + public: + virtual Node * getNamedItem(const XMLString & name) const = 0; + /// Retrieves a node specified by name. + + virtual Node * setNamedItem(Node * arg) = 0; + /// Adds a node using its nodeName attribute. If a node with that name is already + /// present in this map, it is replaced by the new one. + /// As the nodeName attribute is used to derive the name which the node must + /// be stored under, multiple nodes of certain types (those that have a "special" + /// string value) cannot be stored as the names would clash. This is seen as + /// preferable to allowing nodes to be aliased. + + virtual Node * removeNamedItem(const XMLString & name) = 0; + /// Removes a node specified by name. When this map contains the attributes + /// attached to an element, if the removed attribute is known to have a default + /// value, an attribute immediately appears containing the default value. + + virtual Node * item(unsigned long index) const = 0; + /// Returns the index'th item in the map. If index is greater + /// than or equal to the number of nodes in the map, this + /// returns null. + + virtual unsigned long length() const = 0; + /// Returns the number of nodes in the map. The range of valid + /// child node indices is 0 to length - 1 inclusive. + + // DOM Level 2 + virtual Node * getNamedItemNS(const XMLString & namespaceURI, const XMLString & localName) const = 0; + /// Retrieves a node specified by name. + + virtual Node * setNamedItemNS(Node * arg) = 0; + /// Adds a node using its nodeName attribute. + /// If a node with that namespace URI and that local name is already + /// present in this map, it is replaced by the new one. + + virtual Node * removeNamedItemNS(const XMLString & namespaceURI, const XMLString & localName) = 0; + /// Removes a node specified by name. + + protected: + virtual ~NamedNodeMap(); + }; + + +} +} // namespace Poco::XML #endif // DOM_NamedNodeMap_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/Node.h b/base/poco/XML/include/Poco/DOM/Node.h index 0eb934af538..30eca2c6d42 100644 --- a/base/poco/XML/include/Poco/DOM/Node.h +++ b/base/poco/XML/include/Poco/DOM/Node.h @@ -18,268 +18,271 @@ #define DOM_Node_INCLUDED -#include "Poco/XML/XML.h" #include "Poco/DOM/EventTarget.h" -#include "Poco/XML/XMLString.h" #include "Poco/SAX/NamespaceSupport.h" +#include "Poco/XML/XML.h" +#include "Poco/XML/XMLString.h" -namespace Poco { -namespace XML { - - -class NamedNodeMap; -class Document; -class NodeList; - - -class XML_API Node: public EventTarget - /// The Node interface is the primary datatype for the entire Document Object - /// Model. It represents a single node in the document tree. While all objects - /// implementing the Node interface expose methods for dealing with children, - /// not all objects implementing the Node interface may have children. For - /// example, Text nodes may not have children, and adding children to such - /// nodes results in a DOMException being raised. - /// - /// The attributes nodeName, nodeValue and attributes are included as a mechanism - /// to get at node information without casting down to the specific derived - /// interface. In cases where there is no obvious mapping of these attributes - /// for a specific nodeType (e.g., nodeValue for an Element or attributes for - /// a Comment), this returns null. Note that the specialized interfaces may - /// contain additional and more convenient mechanisms to get and set the relevant - /// information. - /// - /// This implementation differs in some ways from the W3C DOM recommendations. - /// For example, the DOM specifies that some methods can return null strings. - /// Instead of null strings, this implementation always returns empty strings. +namespace Poco { -public: - enum - { - ELEMENT_NODE = 1, /// The node is an Element. - ATTRIBUTE_NODE, /// The node is an Attr. - TEXT_NODE, /// The node is a Text node. - CDATA_SECTION_NODE, /// The node is a CDATASection. - ENTITY_REFERENCE_NODE, /// The node is an EntityReference. - ENTITY_NODE, /// The node is an Entity. - PROCESSING_INSTRUCTION_NODE, /// The node is a ProcessingInstruction. - COMMENT_NODE, /// The node is a Comment. - DOCUMENT_NODE, /// The node is a Document. - DOCUMENT_TYPE_NODE, /// The node is a DocumentType. - DOCUMENT_FRAGMENT_NODE, /// The node is a DocumentFragment. - NOTATION_NODE /// The node is a Notation. - }; - - virtual const XMLString& nodeName() const = 0; - /// Returns the name of this node, depending on its type. - - const XMLString& nodeValue() const; - /// Returns the value of this node, depending on its type. - - virtual const XMLString& getNodeValue() const = 0; - /// Returns the value of this node, depending on its type. - - virtual void setNodeValue(const XMLString& value) = 0; - /// Sets the value of this node. Throws an exception - /// if the node is read-only. - - virtual unsigned short nodeType() const = 0; - /// Returns a code representing the type of the underlying object. - - virtual Node* parentNode() const = 0; - /// The parent of this node. All nodes, except Attr, Document, DocumentFragment, - /// Entity, and Notation may have a parent. However, if a node has just been - /// created and not yet added to the tree, or if it has been removed from the - /// tree, this is null. - - virtual NodeList* childNodes() const = 0; - /// Returns a NodeList containing all children of this node. - /// - /// The returned NodeList must be released with a call - /// to release() when no longer needed. - - virtual Node* firstChild() const = 0; - /// Returns the first child of this node. If there is no such - /// node, this returns null. - - virtual Node* lastChild() const = 0; - /// Returns the last child of this node. If there is no such - /// node, this returns null. - - virtual Node* previousSibling() const = 0; - /// Returns the node immediately preceding this node. If there - /// is no such node, this returns null. - - virtual Node* nextSibling() const = 0; - /// Returns the node immediately following this node. If there - /// is no such node, this returns null. - - virtual NamedNodeMap* attributes() const = 0; - /// Returns a NamedNodeMap containing the attributes of this - /// node (if it is an Element) or null otherwise. - /// - /// The returned NamedNodeMap must be released with a call - /// to release() when no longer needed. - - virtual Document* ownerDocument() const = 0; - /// Returns the Document object associated with this node. - /// This is also the Document object used to create new nodes. - /// When this node is a Document, this is null. - - virtual Node* insertBefore(Node* newChild, Node* refChild) = 0; - /// Inserts the node newChild before the existing child node refChild. - /// - /// If refChild is null, insert newChild at the end of the list of children. - /// If newChild is a DocumentFragment object, all of its children are - /// inserted in the same order, before refChild. If the newChild is already - /// in the tree, it is first removed. - - virtual Node* replaceChild(Node* newChild, Node* oldChild) = 0; - /// Replaces the child node oldChild with newChild in the list of children, - /// and returns the oldChild node. - /// If newChild is a DocumentFragment object, oldChild is replaced by all of - /// the DocumentFragment children, which are inserted in the same order. If - /// the newChild is already in the tree, it is first removed. - - virtual Node* removeChild(Node* oldChild) = 0; - /// Removes the child node indicated by oldChild from the list of children - /// and returns it. - - virtual Node* appendChild(Node* newChild) = 0; - /// Appends the node newChild to the end of the list of children of this node. - /// If newChild is already in the tree, it is first removed. - - virtual bool hasChildNodes() const = 0; - /// This is a convenience method to allow easy determination of whether a - /// node has any children. - /// Returns true if the node has any children, false otherwise. - - virtual Node* cloneNode(bool deep) const = 0; - /// Returns a duplicate of this node, i.e., serves as a generic copy constructor - /// for nodes. The duplicate node has no parent; (parentNode is null.). - /// Cloning an Element copies all attributes and their values, including those - /// generated by the XML processor to represent defaulted attributes, but this - /// method does not copy any text it contains unless it is a deep clone, since - /// the text is contained in a child Text node. Cloning an Attribute directly, - /// as opposed to be cloned as part of an Element cloning operation, returns - /// a specified attribute (specified is true). Cloning any other type of node - /// simply returns a copy of this node. - /// Note that cloning an immutable subtree results in a mutable copy, but the - /// children of an EntityReference clone are readonly. In addition, clones of - /// unspecified Attr nodes are specified. And, cloning Document, DocumentType, - /// Entity, and Notation nodes is implementation dependent. - - // DOM Level 2 - virtual void normalize() = 0; - /// Puts all Text nodes in the full depth of the sub-tree underneath this Node, - /// including attribute nodes, into a "normal" form where only structure (e.g., - /// elements, comments, processing instructions, CDATA sections, and entity - /// references) separates Text nodes, i.e., there are neither adjacent Text - /// nodes nor empty Text nodes. This can be used to ensure that the DOM view - /// of a document is the same as if it were saved and re-loaded, and is useful - /// when operations (such as XPointer lookups) that depend on a particular - /// document tree structure are to be used. - /// - /// Note: In cases where the document contains CDATASections, the normalize - /// operation alone may not be sufficient, since XPointers do not differentiate - /// between Text nodes and CDATASection nodes. - - virtual bool isSupported(const XMLString& feature, const XMLString& version) const = 0; - /// Tests whether the DOM implementation implements a specific - /// feature and that feature is supported by this node. - - virtual const XMLString& namespaceURI() const = 0; - /// Returns the namespace URI of the node. - /// This is not a computed value that is the result of a namespace lookup based on an - /// examination of the namespace declarations in scope. It is merely the namespace URI - /// given at creation time. - /// - /// For nodes of any type other than ELEMENT_NODE and ATTRIBUTE_NODE and nodes created with a - /// DOM Level 1 method, such as createElement from the Document interface, this is always the - /// empty string. - - virtual XMLString prefix() const = 0; - /// Returns the namespace prefix from the qualified name of the node. - - virtual const XMLString& localName() const = 0; - /// Returns the local name of the node. - - virtual bool hasAttributes() const = 0; - /// Returns whether this node (if it is an element) has any attributes. - - // Extensions - using NSMap = Poco::XML::NamespaceSupport; - - virtual XMLString innerText() const = 0; - /// Returns a string containing the concatenated values of the node - /// and all its child nodes. - /// - /// This method is not part of the W3C Document Object Model. - - virtual Node* getNodeByPath(const XMLString& path) const = 0; - /// Searches a node (element or attribute) based on a simplified XPath - /// expression. - /// - /// Only simple XPath expressions are supported. These are the slash - /// notation for specifying paths to elements, and the square bracket - /// expression for finding elements by their index, by attribute value, - /// or finding attributes by names. - /// - /// The slash at the beginning is optional, the evaluation always starts - /// at this element. A double-slash at the beginning recursively searches - /// the entire subtree for the first element. - /// - /// Examples: - /// elem1/elem2/elem3 - /// /elem1/elem2/elem3 - /// /elem1/elem2[1] - /// /elem1/elem2[@attr1] - /// /elem1/elem2[@attr1='value'] - /// //elem2[@attr1='value'] - /// //[@attr1='value'] - /// - /// This method is an extension to the W3C Document Object Model. - - virtual Node* getNodeByPathNS(const XMLString& path, const NSMap& nsMap) const = 0; - /// Searches a node (element or attribute) based on a simplified XPath - /// expression. The given NSMap must contain mappings from namespace - /// prefixes to namespace URIs for all namespace prefixes used in - /// the path expression. - /// - /// Only simple XPath expressions are supported. These are the slash - /// notation for specifying paths to elements, and the square bracket - /// expression for finding elements by their index, by attribute value, - /// or finding attributes by names. - /// - /// The slash at the beginning is optional, the evaluation always starts - /// at this element. A double-slash at the beginning recursively searches - /// the entire subtree for the first element. - /// - /// Examples: - /// /ns1:elem1/ns2:elem2/ns2:elem3 - /// /ns1:elem1/ns2:elem2[1] - /// /ns1:elem1/ns2:elem2[@attr1] - /// /ns1:elem1/ns2:elem2[@attr1='value'] - /// //ns2:elem2[@ns1:attr1='value'] - /// //[@ns1:attr1='value'] - /// - /// This method is an extension to the W3C Document Object Model. - -protected: - virtual ~Node(); -}; - - -// -// inlines -// -inline const XMLString& Node::nodeValue() const +namespace XML { - return getNodeValue(); + + + class NamedNodeMap; + class Document; + class NodeList; + + + class XML_API Node : public EventTarget + /// The Node interface is the primary datatype for the entire Document Object + /// Model. It represents a single node in the document tree. While all objects + /// implementing the Node interface expose methods for dealing with children, + /// not all objects implementing the Node interface may have children. For + /// example, Text nodes may not have children, and adding children to such + /// nodes results in a DOMException being raised. + /// + /// The attributes nodeName, nodeValue and attributes are included as a mechanism + /// to get at node information without casting down to the specific derived + /// interface. In cases where there is no obvious mapping of these attributes + /// for a specific nodeType (e.g., nodeValue for an Element or attributes for + /// a Comment), this returns null. Note that the specialized interfaces may + /// contain additional and more convenient mechanisms to get and set the relevant + /// information. + /// + /// This implementation differs in some ways from the W3C DOM recommendations. + /// For example, the DOM specifies that some methods can return null strings. + /// Instead of null strings, this implementation always returns empty strings. + { + public: + enum + { + ELEMENT_NODE = 1, /// The node is an Element. + ATTRIBUTE_NODE, /// The node is an Attr. + TEXT_NODE, /// The node is a Text node. + CDATA_SECTION_NODE, /// The node is a CDATASection. + ENTITY_REFERENCE_NODE, /// The node is an EntityReference. + ENTITY_NODE, /// The node is an Entity. + PROCESSING_INSTRUCTION_NODE, /// The node is a ProcessingInstruction. + COMMENT_NODE, /// The node is a Comment. + DOCUMENT_NODE, /// The node is a Document. + DOCUMENT_TYPE_NODE, /// The node is a DocumentType. + DOCUMENT_FRAGMENT_NODE, /// The node is a DocumentFragment. + NOTATION_NODE /// The node is a Notation. + }; + + virtual const XMLString & nodeName() const = 0; + /// Returns the name of this node, depending on its type. + + const XMLString & nodeValue() const; + /// Returns the value of this node, depending on its type. + + virtual const XMLString & getNodeValue() const = 0; + /// Returns the value of this node, depending on its type. + + virtual void setNodeValue(const XMLString & value) = 0; + /// Sets the value of this node. Throws an exception + /// if the node is read-only. + + virtual unsigned short nodeType() const = 0; + /// Returns a code representing the type of the underlying object. + + virtual Node * parentNode() const = 0; + /// The parent of this node. All nodes, except Attr, Document, DocumentFragment, + /// Entity, and Notation may have a parent. However, if a node has just been + /// created and not yet added to the tree, or if it has been removed from the + /// tree, this is null. + + virtual NodeList * childNodes() const = 0; + /// Returns a NodeList containing all children of this node. + /// + /// The returned NodeList must be released with a call + /// to release() when no longer needed. + + virtual Node * firstChild() const = 0; + /// Returns the first child of this node. If there is no such + /// node, this returns null. + + virtual Node * lastChild() const = 0; + /// Returns the last child of this node. If there is no such + /// node, this returns null. + + virtual Node * previousSibling() const = 0; + /// Returns the node immediately preceding this node. If there + /// is no such node, this returns null. + + virtual Node * nextSibling() const = 0; + /// Returns the node immediately following this node. If there + /// is no such node, this returns null. + + virtual NamedNodeMap * attributes() const = 0; + /// Returns a NamedNodeMap containing the attributes of this + /// node (if it is an Element) or null otherwise. + /// + /// The returned NamedNodeMap must be released with a call + /// to release() when no longer needed. + + virtual Document * ownerDocument() const = 0; + /// Returns the Document object associated with this node. + /// This is also the Document object used to create new nodes. + /// When this node is a Document, this is null. + + virtual Node * insertBefore(Node * newChild, Node * refChild) = 0; + /// Inserts the node newChild before the existing child node refChild. + /// + /// If refChild is null, insert newChild at the end of the list of children. + /// If newChild is a DocumentFragment object, all of its children are + /// inserted in the same order, before refChild. If the newChild is already + /// in the tree, it is first removed. + + virtual Node * replaceChild(Node * newChild, Node * oldChild) = 0; + /// Replaces the child node oldChild with newChild in the list of children, + /// and returns the oldChild node. + /// If newChild is a DocumentFragment object, oldChild is replaced by all of + /// the DocumentFragment children, which are inserted in the same order. If + /// the newChild is already in the tree, it is first removed. + + virtual Node * removeChild(Node * oldChild) = 0; + /// Removes the child node indicated by oldChild from the list of children + /// and returns it. + + virtual Node * appendChild(Node * newChild) = 0; + /// Appends the node newChild to the end of the list of children of this node. + /// If newChild is already in the tree, it is first removed. + + virtual bool hasChildNodes() const = 0; + /// This is a convenience method to allow easy determination of whether a + /// node has any children. + /// Returns true if the node has any children, false otherwise. + + virtual Node * cloneNode(bool deep) const = 0; + /// Returns a duplicate of this node, i.e., serves as a generic copy constructor + /// for nodes. The duplicate node has no parent; (parentNode is null.). + /// Cloning an Element copies all attributes and their values, including those + /// generated by the XML processor to represent defaulted attributes, but this + /// method does not copy any text it contains unless it is a deep clone, since + /// the text is contained in a child Text node. Cloning an Attribute directly, + /// as opposed to be cloned as part of an Element cloning operation, returns + /// a specified attribute (specified is true). Cloning any other type of node + /// simply returns a copy of this node. + /// Note that cloning an immutable subtree results in a mutable copy, but the + /// children of an EntityReference clone are readonly. In addition, clones of + /// unspecified Attr nodes are specified. And, cloning Document, DocumentType, + /// Entity, and Notation nodes is implementation dependent. + + // DOM Level 2 + virtual void normalize() = 0; + /// Puts all Text nodes in the full depth of the sub-tree underneath this Node, + /// including attribute nodes, into a "normal" form where only structure (e.g., + /// elements, comments, processing instructions, CDATA sections, and entity + /// references) separates Text nodes, i.e., there are neither adjacent Text + /// nodes nor empty Text nodes. This can be used to ensure that the DOM view + /// of a document is the same as if it were saved and re-loaded, and is useful + /// when operations (such as XPointer lookups) that depend on a particular + /// document tree structure are to be used. + /// + /// Note: In cases where the document contains CDATASections, the normalize + /// operation alone may not be sufficient, since XPointers do not differentiate + /// between Text nodes and CDATASection nodes. + + virtual bool isSupported(const XMLString & feature, const XMLString & version) const = 0; + /// Tests whether the DOM implementation implements a specific + /// feature and that feature is supported by this node. + + virtual const XMLString & namespaceURI() const = 0; + /// Returns the namespace URI of the node. + /// This is not a computed value that is the result of a namespace lookup based on an + /// examination of the namespace declarations in scope. It is merely the namespace URI + /// given at creation time. + /// + /// For nodes of any type other than ELEMENT_NODE and ATTRIBUTE_NODE and nodes created with a + /// DOM Level 1 method, such as createElement from the Document interface, this is always the + /// empty string. + + virtual XMLString prefix() const = 0; + /// Returns the namespace prefix from the qualified name of the node. + + virtual const XMLString & localName() const = 0; + /// Returns the local name of the node. + + virtual bool hasAttributes() const = 0; + /// Returns whether this node (if it is an element) has any attributes. + + // Extensions + using NSMap = Poco::XML::NamespaceSupport; + + virtual XMLString innerText() const = 0; + /// Returns a string containing the concatenated values of the node + /// and all its child nodes. + /// + /// This method is not part of the W3C Document Object Model. + + virtual Node * getNodeByPath(const XMLString & path) const = 0; + /// Searches a node (element or attribute) based on a simplified XPath + /// expression. + /// + /// Only simple XPath expressions are supported. These are the slash + /// notation for specifying paths to elements, and the square bracket + /// expression for finding elements by their index, by attribute value, + /// or finding attributes by names. + /// + /// The slash at the beginning is optional, the evaluation always starts + /// at this element. A double-slash at the beginning recursively searches + /// the entire subtree for the first element. + /// + /// Examples: + /// elem1/elem2/elem3 + /// /elem1/elem2/elem3 + /// /elem1/elem2[1] + /// /elem1/elem2[@attr1] + /// /elem1/elem2[@attr1='value'] + /// //elem2[@attr1='value'] + /// //[@attr1='value'] + /// + /// This method is an extension to the W3C Document Object Model. + + virtual Node * getNodeByPathNS(const XMLString & path, const NSMap & nsMap) const = 0; + /// Searches a node (element or attribute) based on a simplified XPath + /// expression. The given NSMap must contain mappings from namespace + /// prefixes to namespace URIs for all namespace prefixes used in + /// the path expression. + /// + /// Only simple XPath expressions are supported. These are the slash + /// notation for specifying paths to elements, and the square bracket + /// expression for finding elements by their index, by attribute value, + /// or finding attributes by names. + /// + /// The slash at the beginning is optional, the evaluation always starts + /// at this element. A double-slash at the beginning recursively searches + /// the entire subtree for the first element. + /// + /// Examples: + /// /ns1:elem1/ns2:elem2/ns2:elem3 + /// /ns1:elem1/ns2:elem2[1] + /// /ns1:elem1/ns2:elem2[@attr1] + /// /ns1:elem1/ns2:elem2[@attr1='value'] + /// //ns2:elem2[@ns1:attr1='value'] + /// //[@ns1:attr1='value'] + /// + /// This method is an extension to the W3C Document Object Model. + + protected: + virtual ~Node(); + }; + + + // + // inlines + // + inline const XMLString & Node::nodeValue() const + { + return getNodeValue(); + } + + } - - -} } // namespace Poco::XML +} // namespace Poco::XML #endif // DOM_Node_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/NodeAppender.h b/base/poco/XML/include/Poco/DOM/NodeAppender.h index 2d36be2e3c7..6c56d875fd6 100644 --- a/base/poco/XML/include/Poco/DOM/NodeAppender.h +++ b/base/poco/XML/include/Poco/DOM/NodeAppender.h @@ -18,64 +18,66 @@ #define DOM_NodeAppender_INCLUDED -#include "Poco/XML/XML.h" #include "Poco/DOM/Node.h" +#include "Poco/XML/XML.h" -namespace Poco { -namespace XML { - - -class AbstractNode; -class Element; - - -class XML_API NodeAppender - /// The NodeAppender class provides a very fast way to - /// build larger DOM documents. - /// - /// In the DOM, child nodes are usually appended to a parent - /// node using the appendChild() method. For nodes containing - /// more than a few children, this method can be quite slow, - /// due to the way it's implemented, and because of the - /// requirements of the DOM specification. - /// - /// While the NodeAppender is being used on an Element, no - /// children-modifying methods of that Element must be used. - /// - /// This class is not part of the DOM specification. +namespace Poco +{ +namespace XML { -public: - NodeAppender(Element* parent); - /// Creates the NodeAppender for the given parent node, - /// which must be an Element. - - ~NodeAppender(); - /// Destroys the NodeAppender. - - void appendChild(Node* newChild); - /// Appends the node newChild to the end of the list of children of - /// the parent node specified in the constructor. - /// If the newChild is already in the tree, it is first removed. - /// - /// NewChild can be a DocumentFragment. In this case, all children - /// of the fragment become children of the parent element. - /// - /// In order to speed up the function, no DOM events - /// are fired. - -private: - NodeAppender(); - NodeAppender(const NodeAppender&); - NodeAppender& operator = (const NodeAppender&); - - Element* _pParent; - AbstractNode* _pLast; -}; -} } // namespace Poco::XML + class AbstractNode; + class Element; + + + class XML_API NodeAppender + /// The NodeAppender class provides a very fast way to + /// build larger DOM documents. + /// + /// In the DOM, child nodes are usually appended to a parent + /// node using the appendChild() method. For nodes containing + /// more than a few children, this method can be quite slow, + /// due to the way it's implemented, and because of the + /// requirements of the DOM specification. + /// + /// While the NodeAppender is being used on an Element, no + /// children-modifying methods of that Element must be used. + /// + /// This class is not part of the DOM specification. + { + public: + NodeAppender(Element * parent); + /// Creates the NodeAppender for the given parent node, + /// which must be an Element. + + ~NodeAppender(); + /// Destroys the NodeAppender. + + void appendChild(Node * newChild); + /// Appends the node newChild to the end of the list of children of + /// the parent node specified in the constructor. + /// If the newChild is already in the tree, it is first removed. + /// + /// NewChild can be a DocumentFragment. In this case, all children + /// of the fragment become children of the parent element. + /// + /// In order to speed up the function, no DOM events + /// are fired. + + private: + NodeAppender(); + NodeAppender(const NodeAppender &); + NodeAppender & operator=(const NodeAppender &); + + Element * _pParent; + AbstractNode * _pLast; + }; + + +} +} // namespace Poco::XML #endif // #include "Poco/XML/XML.h" - diff --git a/base/poco/XML/include/Poco/DOM/NodeFilter.h b/base/poco/XML/include/Poco/DOM/NodeFilter.h index ae8677bf286..20b5cee56a6 100644 --- a/base/poco/XML/include/Poco/DOM/NodeFilter.h +++ b/base/poco/XML/include/Poco/DOM/NodeFilter.h @@ -22,125 +22,128 @@ #include "Poco/XML/XMLString.h" -namespace Poco { -namespace XML { - - -class Node; - - -class XML_API NodeFilter - /// Filters are objects that know how to "filter out" nodes. If a NodeIterator - /// or TreeWalker is given a NodeFilter, it applies the filter before it returns - /// the next node. If the filter says to accept the node, the traversal logic - /// returns it; otherwise, traversal looks for the next node and pretends that - /// the node that was rejected was not there. - /// - /// The DOM does not provide any filters. NodeFilter is just an interface that - /// users can implement to provide their own filters. - /// - /// NodeFilters do not need to know how to traverse from node to node, nor do - /// they need to know anything about the data structure that is being traversed. - /// This makes it very easy to write filters, since the only thing they have - /// to know how to do is evaluate a single node. One filter may be used with - /// a number of different kinds of traversals, encouraging code reuse. +namespace Poco +{ +namespace XML { -public: - enum - { - FILTER_ACCEPT = 1, - /// Accept the node. Navigation methods defined for NodeIterator or TreeWalker will return this node. - - FILTER_REJECT = 2, - /// Reject the node. Navigation methods defined for NodeIterator or TreeWalker - /// will not return this node. For TreeWalker, the children of this node will - /// also be rejected. NodeIterators treat this as a synonym for FILTER_SKIP. - - FILTER_SKIP = 3 - /// Skip this single node. Navigation methods defined for NodeIterator or TreeWalker - /// will not return this node. For both NodeIterator and TreeWalker, the children - /// of this node will still be considered. - }; - - enum WhatToShow - /// These are the available values for the whatToShow parameter used in TreeWalkers - /// and NodeIterators. They are the same as the set of possible types for Node, - /// and their values are derived by using a bit position corresponding to the - /// value of nodeType for the equivalent node type. If a bit in whatToShow is - /// set false, that will be taken as a request to skip over this type of node; - /// the behavior in that case is similar to that of FILTER_SKIP. - /// - /// Note that if node types greater than 32 are ever introduced, they may not - /// be individually testable via whatToShow. If that need should arise, it can - /// be handled by selecting SHOW_ALL together with an appropriate NodeFilter. - { - SHOW_ALL = 0xFFFFFFFF, - /// Show all Nodes. - - SHOW_ELEMENT = 0x00000001, - /// Show Element nodes. - - SHOW_ATTRIBUTE = 0x00000002, - /// Show Attr nodes. This is meaningful only when creating an iterator or tree-walker - /// with an attribute node as its root; in this case, it means that the attribute - /// node will appear in the first position of the iteration or traversal. Since - /// attributes are never children of other nodes, they do not appear when traversing - /// over the document tree. - - SHOW_TEXT = 0x00000004, - /// Show Text nodes. - - SHOW_CDATA_SECTION = 0x00000008, - /// Show CDATASection nodes. - - SHOW_ENTITY_REFERENCE = 0x00000010, - /// Show EntityReference nodes. - - SHOW_ENTITY = 0x00000020, - /// Show Entity nodes. This is meaningful only when creating an iterator or - /// tree-walker with an Entity node as its root; in this case, it means that - /// the Entity node will appear in the first position of the traversal. Since - /// entities are not part of the document tree, they do not appear when traversing - /// over the document tree. - - SHOW_PROCESSING_INSTRUCTION = 0x00000040, - /// Show ProcessingInstruction nodes. - - SHOW_COMMENT = 0x00000080, - /// Show Comment nodes. - - SHOW_DOCUMENT = 0x00000100, - /// Show Document nodes. - - SHOW_DOCUMENT_TYPE = 0x00000200, - /// Show DocumentType nodes. - - SHOW_DOCUMENT_FRAGMENT = 0x00000400, - /// Show DocumentFragment nodes. - - SHOW_NOTATION = 0x00000800 - /// Show Notation nodes. This is meaningful only when creating an iterator or - /// tree-walker with a Notation node as its root; in this case, it means that - /// the Notation node will appear in the first position of the traversal. Since - /// notations are not part of the document tree, they do not appear when traversing - /// over the document tree. - }; - - virtual short acceptNode(Node* node) = 0; - /// Test whether a specified node is visible in the logical view of a TreeWalker - /// or NodeIterator. This function will be called by the implementation of TreeWalker - /// and NodeIterator; it is not normally called directly from user code. (Though - /// you could do so if you wanted to use the same filter to guide your own application - /// logic.) - /// - /// Returns FILTER_ACCEPT, FILTER_REJECT or FILTER_SKIP. - -protected: - virtual ~NodeFilter(); -}; -} } // namespace Poco::XML + class Node; + + + class XML_API NodeFilter + /// Filters are objects that know how to "filter out" nodes. If a NodeIterator + /// or TreeWalker is given a NodeFilter, it applies the filter before it returns + /// the next node. If the filter says to accept the node, the traversal logic + /// returns it; otherwise, traversal looks for the next node and pretends that + /// the node that was rejected was not there. + /// + /// The DOM does not provide any filters. NodeFilter is just an interface that + /// users can implement to provide their own filters. + /// + /// NodeFilters do not need to know how to traverse from node to node, nor do + /// they need to know anything about the data structure that is being traversed. + /// This makes it very easy to write filters, since the only thing they have + /// to know how to do is evaluate a single node. One filter may be used with + /// a number of different kinds of traversals, encouraging code reuse. + { + public: + enum + { + FILTER_ACCEPT = 1, + /// Accept the node. Navigation methods defined for NodeIterator or TreeWalker will return this node. + + FILTER_REJECT = 2, + /// Reject the node. Navigation methods defined for NodeIterator or TreeWalker + /// will not return this node. For TreeWalker, the children of this node will + /// also be rejected. NodeIterators treat this as a synonym for FILTER_SKIP. + + FILTER_SKIP = 3 + /// Skip this single node. Navigation methods defined for NodeIterator or TreeWalker + /// will not return this node. For both NodeIterator and TreeWalker, the children + /// of this node will still be considered. + }; + + enum WhatToShow + /// These are the available values for the whatToShow parameter used in TreeWalkers + /// and NodeIterators. They are the same as the set of possible types for Node, + /// and their values are derived by using a bit position corresponding to the + /// value of nodeType for the equivalent node type. If a bit in whatToShow is + /// set false, that will be taken as a request to skip over this type of node; + /// the behavior in that case is similar to that of FILTER_SKIP. + /// + /// Note that if node types greater than 32 are ever introduced, they may not + /// be individually testable via whatToShow. If that need should arise, it can + /// be handled by selecting SHOW_ALL together with an appropriate NodeFilter. + { + SHOW_ALL = 0xFFFFFFFF, + /// Show all Nodes. + + SHOW_ELEMENT = 0x00000001, + /// Show Element nodes. + + SHOW_ATTRIBUTE = 0x00000002, + /// Show Attr nodes. This is meaningful only when creating an iterator or tree-walker + /// with an attribute node as its root; in this case, it means that the attribute + /// node will appear in the first position of the iteration or traversal. Since + /// attributes are never children of other nodes, they do not appear when traversing + /// over the document tree. + + SHOW_TEXT = 0x00000004, + /// Show Text nodes. + + SHOW_CDATA_SECTION = 0x00000008, + /// Show CDATASection nodes. + + SHOW_ENTITY_REFERENCE = 0x00000010, + /// Show EntityReference nodes. + + SHOW_ENTITY = 0x00000020, + /// Show Entity nodes. This is meaningful only when creating an iterator or + /// tree-walker with an Entity node as its root; in this case, it means that + /// the Entity node will appear in the first position of the traversal. Since + /// entities are not part of the document tree, they do not appear when traversing + /// over the document tree. + + SHOW_PROCESSING_INSTRUCTION = 0x00000040, + /// Show ProcessingInstruction nodes. + + SHOW_COMMENT = 0x00000080, + /// Show Comment nodes. + + SHOW_DOCUMENT = 0x00000100, + /// Show Document nodes. + + SHOW_DOCUMENT_TYPE = 0x00000200, + /// Show DocumentType nodes. + + SHOW_DOCUMENT_FRAGMENT = 0x00000400, + /// Show DocumentFragment nodes. + + SHOW_NOTATION = 0x00000800 + /// Show Notation nodes. This is meaningful only when creating an iterator or + /// tree-walker with a Notation node as its root; in this case, it means that + /// the Notation node will appear in the first position of the traversal. Since + /// notations are not part of the document tree, they do not appear when traversing + /// over the document tree. + }; + + virtual short acceptNode(Node * node) = 0; + /// Test whether a specified node is visible in the logical view of a TreeWalker + /// or NodeIterator. This function will be called by the implementation of TreeWalker + /// and NodeIterator; it is not normally called directly from user code. (Though + /// you could do so if you wanted to use the same filter to guide your own application + /// logic.) + /// + /// Returns FILTER_ACCEPT, FILTER_REJECT or FILTER_SKIP. + + protected: + virtual ~NodeFilter(); + }; + + +} +} // namespace Poco::XML #endif // DOM_NodeFilter_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/NodeIterator.h b/base/poco/XML/include/Poco/DOM/NodeIterator.h index 1f8e9a063b2..58044d40f2b 100644 --- a/base/poco/XML/include/Poco/DOM/NodeIterator.h +++ b/base/poco/XML/include/Poco/DOM/NodeIterator.h @@ -21,147 +21,150 @@ #include "Poco/XML/XML.h" -namespace Poco { -namespace XML { - - -class Node; -class NodeFilter; - - -class XML_API NodeIterator - /// Iterators are used to step through a set of nodes, e.g. the set of nodes - /// in a NodeList, the document subtree governed by a particular Node, the results - /// of a query, or any other set of nodes. The set of nodes to be iterated is - /// determined by the implementation of the NodeIterator. DOM Level 2 specifies - /// a single NodeIterator implementation for document-order traversal of a document - /// subtree. - /// - /// A NodeIterator can be directly instantiated using one of its constructors - - /// the DocumentTraversal interface is not needed and therefore not implemented. - /// Unlike most other DOM classes, NodeIterator supports value semantics. - /// - /// If the NodeIterator's current node is removed from the document, the - /// result of calling any of the movement methods is undefined. This behavior does - /// not conform to the DOM Level 2 Traversal specification. +namespace Poco { -public: - NodeIterator(Node* root, unsigned long whatToShow, NodeFilter* pFilter = 0); - /// Creates a NodeIterator over the subtree rooted at the specified node. - - NodeIterator(const NodeIterator& iterator); - /// Creates a NodeIterator by copying another NodeIterator. - - NodeIterator& operator = (const NodeIterator& iterator); - /// Assignment operator. - - ~NodeIterator(); - /// Destroys the NodeIterator. - - Node* root() const; - /// The root node of the NodeIterator, as specified when it was created. - - unsigned long whatToShow() const; - /// This attribute determines which node types are presented via the iterator. - /// The available set of constants is defined in the NodeFilter interface. - /// Nodes not accepted by whatToShow will be skipped, but their children may - /// still be considered. Note that this skip takes precedence over the filter, - /// if any. - - NodeFilter* filter() const; - /// The NodeFilter used to screen nodes. - - bool expandEntityReferences() const; - /// The value of this flag determines whether the children of entity reference - /// nodes are visible to the iterator. If false, they and their descendants - /// will be rejected. Note that this rejection takes precedence over whatToShow - /// and the filter. Also note that this is currently the only situation where - /// NodeIterators may reject a complete subtree rather than skipping individual - /// nodes. - /// - /// To produce a view of the document that has entity references expanded and - /// does not expose the entity reference node itself, use the whatToShow flags - /// to hide the entity reference node and set expandEntityReferences to true - /// when creating the iterator. To produce a view of the document that has entity - /// reference nodes but no entity expansion, use the whatToShow flags to show - /// the entity reference node and set expandEntityReferences to false. - /// - /// This implementation does not support entity reference expansion and - /// thus always returns false. - - Node* nextNode(); - /// Returns the next node in the set and advances the position of the iterator - /// in the set. After a NodeIterator is created, the first call to nextNode() - /// returns the first node in the set. - - Node* previousNode(); - /// Returns the previous node in the set and moves the position of the NodeIterator - /// backwards in the set. - - Node* currentNodeNP() const; - /// Returns the current node in the set. - /// - /// Leaves the NodeIterator unchanged. - /// - /// Warning: This is a proprietary extension to the DOM Level 2 NodeIterator - /// interface. - - void detach(); - /// Detaches the NodeIterator from the set which it iterated over, releasing - /// any computational resources and placing the iterator in the INVALID state. - /// After detach has been invoked, calls to nextNode or previousNode will raise - /// the exception INVALID_STATE_ERR. - -protected: - bool accept(Node* pNode) const; - Node* next() const; - Node* previous() const; - Node* last(); - -private: - NodeIterator(); - - Node* _pRoot; - unsigned long _whatToShow; - NodeFilter* _pFilter; - Node* _pCurrent; -}; - - -// -// inlines -// -inline Node* NodeIterator::root() const +namespace XML { - return _pRoot; + + + class Node; + class NodeFilter; + + + class XML_API NodeIterator + /// Iterators are used to step through a set of nodes, e.g. the set of nodes + /// in a NodeList, the document subtree governed by a particular Node, the results + /// of a query, or any other set of nodes. The set of nodes to be iterated is + /// determined by the implementation of the NodeIterator. DOM Level 2 specifies + /// a single NodeIterator implementation for document-order traversal of a document + /// subtree. + /// + /// A NodeIterator can be directly instantiated using one of its constructors - + /// the DocumentTraversal interface is not needed and therefore not implemented. + /// Unlike most other DOM classes, NodeIterator supports value semantics. + /// + /// If the NodeIterator's current node is removed from the document, the + /// result of calling any of the movement methods is undefined. This behavior does + /// not conform to the DOM Level 2 Traversal specification. + { + public: + NodeIterator(Node * root, unsigned long whatToShow, NodeFilter * pFilter = 0); + /// Creates a NodeIterator over the subtree rooted at the specified node. + + NodeIterator(const NodeIterator & iterator); + /// Creates a NodeIterator by copying another NodeIterator. + + NodeIterator & operator=(const NodeIterator & iterator); + /// Assignment operator. + + ~NodeIterator(); + /// Destroys the NodeIterator. + + Node * root() const; + /// The root node of the NodeIterator, as specified when it was created. + + unsigned long whatToShow() const; + /// This attribute determines which node types are presented via the iterator. + /// The available set of constants is defined in the NodeFilter interface. + /// Nodes not accepted by whatToShow will be skipped, but their children may + /// still be considered. Note that this skip takes precedence over the filter, + /// if any. + + NodeFilter * filter() const; + /// The NodeFilter used to screen nodes. + + bool expandEntityReferences() const; + /// The value of this flag determines whether the children of entity reference + /// nodes are visible to the iterator. If false, they and their descendants + /// will be rejected. Note that this rejection takes precedence over whatToShow + /// and the filter. Also note that this is currently the only situation where + /// NodeIterators may reject a complete subtree rather than skipping individual + /// nodes. + /// + /// To produce a view of the document that has entity references expanded and + /// does not expose the entity reference node itself, use the whatToShow flags + /// to hide the entity reference node and set expandEntityReferences to true + /// when creating the iterator. To produce a view of the document that has entity + /// reference nodes but no entity expansion, use the whatToShow flags to show + /// the entity reference node and set expandEntityReferences to false. + /// + /// This implementation does not support entity reference expansion and + /// thus always returns false. + + Node * nextNode(); + /// Returns the next node in the set and advances the position of the iterator + /// in the set. After a NodeIterator is created, the first call to nextNode() + /// returns the first node in the set. + + Node * previousNode(); + /// Returns the previous node in the set and moves the position of the NodeIterator + /// backwards in the set. + + Node * currentNodeNP() const; + /// Returns the current node in the set. + /// + /// Leaves the NodeIterator unchanged. + /// + /// Warning: This is a proprietary extension to the DOM Level 2 NodeIterator + /// interface. + + void detach(); + /// Detaches the NodeIterator from the set which it iterated over, releasing + /// any computational resources and placing the iterator in the INVALID state. + /// After detach has been invoked, calls to nextNode or previousNode will raise + /// the exception INVALID_STATE_ERR. + + protected: + bool accept(Node * pNode) const; + Node * next() const; + Node * previous() const; + Node * last(); + + private: + NodeIterator(); + + Node * _pRoot; + unsigned long _whatToShow; + NodeFilter * _pFilter; + Node * _pCurrent; + }; + + + // + // inlines + // + inline Node * NodeIterator::root() const + { + return _pRoot; + } + + + inline Node * NodeIterator::currentNodeNP() const + { + return _pCurrent; + } + + + inline unsigned long NodeIterator::whatToShow() const + { + return _whatToShow; + } + + + inline NodeFilter * NodeIterator::filter() const + { + return _pFilter; + } + + + inline bool NodeIterator::expandEntityReferences() const + { + return false; + } + + } - - -inline Node* NodeIterator::currentNodeNP() const -{ - return _pCurrent; -} - - -inline unsigned long NodeIterator::whatToShow() const -{ - return _whatToShow; -} - - -inline NodeFilter* NodeIterator::filter() const -{ - return _pFilter; -} - - -inline bool NodeIterator::expandEntityReferences() const -{ - return false; -} - - -} } // namespace Poco::XML +} // namespace Poco::XML #endif // DOM_NodeIterator_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/NodeList.h b/base/poco/XML/include/Poco/DOM/NodeList.h index 1f8c12f4cd2..a767636035c 100644 --- a/base/poco/XML/include/Poco/DOM/NodeList.h +++ b/base/poco/XML/include/Poco/DOM/NodeList.h @@ -18,44 +18,47 @@ #define DOM_NodeList_INCLUDED -#include "Poco/XML/XML.h" #include "Poco/DOM/DOMObject.h" +#include "Poco/XML/XML.h" -namespace Poco { -namespace XML { - - -class Node; - - -class XML_API NodeList: public DOMObject - /// The NodeList interface provides the abstraction of an ordered - /// collection of nodes, without defining or constraining how this - /// collection is implemented. - /// - /// The items in the NodeList are accessible via an integral index, - /// starting from 0. - /// - /// A NodeList returned from a method must be released with a call to - /// release() when no longer needed. +namespace Poco +{ +namespace XML { -public: - virtual Node* item(unsigned long index) const = 0; - /// Returns the index'th item in the collection. If index is - /// greater than or equal to the number of nodes in the list, - /// this returns null. - - virtual unsigned long length() const = 0; - /// Returns the number of nodes in the list. The range of valid - /// node indices is 0 to length - 1 inclusive. - -protected: - virtual ~NodeList(); -}; -} } // namespace Poco::XML + class Node; + + + class XML_API NodeList : public DOMObject + /// The NodeList interface provides the abstraction of an ordered + /// collection of nodes, without defining or constraining how this + /// collection is implemented. + /// + /// The items in the NodeList are accessible via an integral index, + /// starting from 0. + /// + /// A NodeList returned from a method must be released with a call to + /// release() when no longer needed. + { + public: + virtual Node * item(unsigned long index) const = 0; + /// Returns the index'th item in the collection. If index is + /// greater than or equal to the number of nodes in the list, + /// this returns null. + + virtual unsigned long length() const = 0; + /// Returns the number of nodes in the list. The range of valid + /// node indices is 0 to length - 1 inclusive. + + protected: + virtual ~NodeList(); + }; + + +} +} // namespace Poco::XML #endif // DOM_NodeList_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/Notation.h b/base/poco/XML/include/Poco/DOM/Notation.h index c9824b0e05d..ef24bf51c51 100644 --- a/base/poco/XML/include/Poco/DOM/Notation.h +++ b/base/poco/XML/include/Poco/DOM/Notation.h @@ -18,76 +18,79 @@ #define DOM_Notation_INCLUDED -#include "Poco/XML/XML.h" #include "Poco/DOM/AbstractNode.h" +#include "Poco/XML/XML.h" #include "Poco/XML/XMLString.h" -namespace Poco { -namespace XML { - - -class XML_API Notation: public AbstractNode - /// This interface represents a notation declared in the DTD. A notation either - /// declares, by name, the format of an unparsed entity (see section 4.7 of - /// the XML 1.0 specification ), - /// or is used for formal declaration of processing - /// instruction targets (see section 2.6 of the XML 1.0 specification). - /// The nodeName attribute inherited from Node is set to the declared name of - /// the notation. - /// - /// The DOM Level 1 does not support editing Notation nodes; they are therefore - /// readonly. - /// - /// A Notation node does not have any parent. +namespace Poco { -public: - const XMLString& publicId() const; - /// Returns the public identifier of this notation. - /// If not specified, this is an empty string (and not null, - /// as in the DOM specification). - - const XMLString& systemId() const; - /// Returns the system identifier of this notation. - /// If not specified, this is an empty string (and not null, - /// as in the DOM specification). - - // Node - const XMLString& nodeName() const; - unsigned short nodeType() const; - -protected: - Notation(Document* pOwnerDocument, const XMLString& name, const XMLString& publicId, const XMLString& systemId); - Notation(Document* pOwnerDocument, const Notation& notation); - ~Notation(); - - Node* copyNode(bool deep, Document* pOwnerDocument) const; - -private: - XMLString _name; - XMLString _publicId; - XMLString _systemId; - - friend class Document; -}; - - -// -// inlines -// -inline const XMLString& Notation::publicId() const +namespace XML { - return _publicId; + + + class XML_API Notation : public AbstractNode + /// This interface represents a notation declared in the DTD. A notation either + /// declares, by name, the format of an unparsed entity (see section 4.7 of + /// the XML 1.0 specification ), + /// or is used for formal declaration of processing + /// instruction targets (see section 2.6 of the XML 1.0 specification). + /// The nodeName attribute inherited from Node is set to the declared name of + /// the notation. + /// + /// The DOM Level 1 does not support editing Notation nodes; they are therefore + /// readonly. + /// + /// A Notation node does not have any parent. + { + public: + const XMLString & publicId() const; + /// Returns the public identifier of this notation. + /// If not specified, this is an empty string (and not null, + /// as in the DOM specification). + + const XMLString & systemId() const; + /// Returns the system identifier of this notation. + /// If not specified, this is an empty string (and not null, + /// as in the DOM specification). + + // Node + const XMLString & nodeName() const; + unsigned short nodeType() const; + + protected: + Notation(Document * pOwnerDocument, const XMLString & name, const XMLString & publicId, const XMLString & systemId); + Notation(Document * pOwnerDocument, const Notation & notation); + ~Notation(); + + Node * copyNode(bool deep, Document * pOwnerDocument) const; + + private: + XMLString _name; + XMLString _publicId; + XMLString _systemId; + + friend class Document; + }; + + + // + // inlines + // + inline const XMLString & Notation::publicId() const + { + return _publicId; + } + + + inline const XMLString & Notation::systemId() const + { + return _systemId; + } + + } - - -inline const XMLString& Notation::systemId() const -{ - return _systemId; -} - - -} } // namespace Poco::XML +} // namespace Poco::XML #endif // DOM_Notation_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/ProcessingInstruction.h b/base/poco/XML/include/Poco/DOM/ProcessingInstruction.h index ab600ca952b..1cc6668861a 100644 --- a/base/poco/XML/include/Poco/DOM/ProcessingInstruction.h +++ b/base/poco/XML/include/Poco/DOM/ProcessingInstruction.h @@ -18,82 +18,85 @@ #define DOM_ProcessingInstruction_INCLUDED -#include "Poco/XML/XML.h" #include "Poco/DOM/AbstractNode.h" +#include "Poco/XML/XML.h" #include "Poco/XML/XMLString.h" -namespace Poco { -namespace XML { - - -class XML_API ProcessingInstruction: public AbstractNode - /// The ProcessingInstruction interface represents a "processing instruction", - /// used in XML as a way to keep processor-specific information in the text - /// of the document. +namespace Poco { -public: - const XMLString& target() const; - /// Returns the target of this processing instruction. - /// XML defines this as being the first token following - /// the markup that begins the processing instruction. - - const XMLString& data() const; - /// Returns the content of this processing instruction. This is from the first non - /// white space character after the target to the character immediately preceding - /// the ?>. - - const XMLString& getData() const; - /// Returns the content of this processing instruction. This is from the first non - /// white space character after the target to the character immediately preceding - /// the ?>. - - void setData(const XMLString& data); - /// Sets the content of this processing instruction. - - // Node - const XMLString& nodeName() const; - const XMLString& getNodeValue() const; - void setNodeValue(const XMLString& data); - unsigned short nodeType() const; - -protected: - ProcessingInstruction(Document* pOwnerDocument, const XMLString& target, const XMLString& data); - ProcessingInstruction(Document* pOwnerDocument, const ProcessingInstruction& processingInstruction); - ~ProcessingInstruction(); - - Node* copyNode(bool deep, Document* pOwnerDocument) const; - -private: - XMLString _target; - XMLString _data; - - friend class Document; -}; - - -// -// inlines -// -inline const XMLString& ProcessingInstruction::target() const +namespace XML { - return _target; + + + class XML_API ProcessingInstruction : public AbstractNode + /// The ProcessingInstruction interface represents a "processing instruction", + /// used in XML as a way to keep processor-specific information in the text + /// of the document. + { + public: + const XMLString & target() const; + /// Returns the target of this processing instruction. + /// XML defines this as being the first token following + /// the markup that begins the processing instruction. + + const XMLString & data() const; + /// Returns the content of this processing instruction. This is from the first non + /// white space character after the target to the character immediately preceding + /// the ?>. + + const XMLString & getData() const; + /// Returns the content of this processing instruction. This is from the first non + /// white space character after the target to the character immediately preceding + /// the ?>. + + void setData(const XMLString & data); + /// Sets the content of this processing instruction. + + // Node + const XMLString & nodeName() const; + const XMLString & getNodeValue() const; + void setNodeValue(const XMLString & data); + unsigned short nodeType() const; + + protected: + ProcessingInstruction(Document * pOwnerDocument, const XMLString & target, const XMLString & data); + ProcessingInstruction(Document * pOwnerDocument, const ProcessingInstruction & processingInstruction); + ~ProcessingInstruction(); + + Node * copyNode(bool deep, Document * pOwnerDocument) const; + + private: + XMLString _target; + XMLString _data; + + friend class Document; + }; + + + // + // inlines + // + inline const XMLString & ProcessingInstruction::target() const + { + return _target; + } + + + inline const XMLString & ProcessingInstruction::data() const + { + return _data; + } + + + inline const XMLString & ProcessingInstruction::getData() const + { + return _data; + } + + } - - -inline const XMLString& ProcessingInstruction::data() const -{ - return _data; -} - - -inline const XMLString& ProcessingInstruction::getData() const -{ - return _data; -} - - -} } // namespace Poco::XML +} // namespace Poco::XML #endif // DOM_ProcessingInstruction_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/Text.h b/base/poco/XML/include/Poco/DOM/Text.h index 3a7931a8b24..e03da65796b 100644 --- a/base/poco/XML/include/Poco/DOM/Text.h +++ b/base/poco/XML/include/Poco/DOM/Text.h @@ -18,62 +18,65 @@ #define DOM_Text_INCLUDED -#include "Poco/XML/XML.h" #include "Poco/DOM/CharacterData.h" +#include "Poco/XML/XML.h" #include "Poco/XML/XMLString.h" -namespace Poco { -namespace XML { - - -class XML_API Text: public CharacterData - /// The Text interface inherits from CharacterData and represents the textual - /// content (termed character data in XML) of an Element or Attr. If there is - /// no markup inside an element's content, the text is contained in a single - /// object implementing the Text interface that is the only child of the element. - /// If there is markup, it is parsed into the information items (elements, comments, - /// etc.) and Text nodes that form the list of children of the element. - /// - /// When a document is first made available via the DOM, there is only one Text - /// node for each block of text. Users may create adjacent Text nodes that represent - /// the contents of a given element without any intervening markup, but should - /// be aware that there is no way to represent the separations between these - /// nodes in XML or HTML, so they will not (in general) persist between DOM - /// editing sessions. The normalize() method on Element merges any such adjacent - /// Text objects into a single node for each block of text. +namespace Poco +{ +namespace XML { -public: - Text* splitText(unsigned long offset); - /// Breaks this node into two nodes at the specified offset, keeping both in - /// the tree as siblings. This node then only contains all the content up to - /// the offset point. A new node of the same type, which is inserted as the - /// next sibling of this node, contains all the content at and after the offset - /// point. When the offset is equal to the length of this node, the new node - /// has no data. - - // Node - const XMLString& nodeName() const; - unsigned short nodeType() const; - - // Non-standard extensions - XMLString innerText() const; - -protected: - Text(Document* pOwnerDocument, const XMLString& data); - Text(Document* pOwnerDocument, const Text& text); - ~Text(); - - Node* copyNode(bool deep, Document* pOwnerDocument) const; - -private: - static const XMLString NODE_NAME; - - friend class Document; -}; -} } // namespace Poco::XML + class XML_API Text : public CharacterData + /// The Text interface inherits from CharacterData and represents the textual + /// content (termed character data in XML) of an Element or Attr. If there is + /// no markup inside an element's content, the text is contained in a single + /// object implementing the Text interface that is the only child of the element. + /// If there is markup, it is parsed into the information items (elements, comments, + /// etc.) and Text nodes that form the list of children of the element. + /// + /// When a document is first made available via the DOM, there is only one Text + /// node for each block of text. Users may create adjacent Text nodes that represent + /// the contents of a given element without any intervening markup, but should + /// be aware that there is no way to represent the separations between these + /// nodes in XML or HTML, so they will not (in general) persist between DOM + /// editing sessions. The normalize() method on Element merges any such adjacent + /// Text objects into a single node for each block of text. + { + public: + Text * splitText(unsigned long offset); + /// Breaks this node into two nodes at the specified offset, keeping both in + /// the tree as siblings. This node then only contains all the content up to + /// the offset point. A new node of the same type, which is inserted as the + /// next sibling of this node, contains all the content at and after the offset + /// point. When the offset is equal to the length of this node, the new node + /// has no data. + + // Node + const XMLString & nodeName() const; + unsigned short nodeType() const; + + // Non-standard extensions + XMLString innerText() const; + + protected: + Text(Document * pOwnerDocument, const XMLString & data); + Text(Document * pOwnerDocument, const Text & text); + ~Text(); + + Node * copyNode(bool deep, Document * pOwnerDocument) const; + + private: + static const XMLString NODE_NAME; + + friend class Document; + }; + + +} +} // namespace Poco::XML #endif // DOM_Text_INCLUDED diff --git a/base/poco/XML/include/Poco/DOM/TreeWalker.h b/base/poco/XML/include/Poco/DOM/TreeWalker.h index 884b37d3c77..1b9e4b3f1ca 100644 --- a/base/poco/XML/include/Poco/DOM/TreeWalker.h +++ b/base/poco/XML/include/Poco/DOM/TreeWalker.h @@ -22,190 +22,193 @@ #include "Poco/XML/XMLString.h" -namespace Poco { -namespace XML { - - -class Node; -class NodeFilter; - - -class XML_API TreeWalker - /// TreeWalker objects are used to navigate a document tree or subtree using - /// the view of the document defined by their whatToShow flags and filter (if - /// any). Any function which performs navigation using a TreeWalker will automatically - /// support any view defined by a TreeWalker. - /// - /// Omitting nodes from the logical view of a subtree can result in a structure - /// that is substantially different from the same subtree in the complete, unfiltered - /// document. Nodes that are siblings in the TreeWalker view may be children - /// of different, widely separated nodes in the original view. For instance, - /// consider a NodeFilter that skips all nodes except for Text nodes and the - /// root node of a document. In the logical view that results, all text nodes - /// will be siblings and appear as direct children of the root node, no matter - /// how deeply nested the structure of the original document. - /// - /// A TreeWalker can be directly instantiated using one of its constructors - - /// the DocumentTraversal interface is not needed and therefore not implemented. - /// Unlike most other DOM classes, TreeWalker supports value semantics. - /// - /// If the TreeWalker's current node is removed from the document, the - /// result of calling any of the movement methods is undefined. This behavior - /// does not conform to the DOM Level 2 Traversal specification. +namespace Poco { -public: - TreeWalker(Node* root, unsigned long whatToShow, NodeFilter* pFilter = 0); - /// Creates a TreeWalker over the subtree rooted at the specified node. - - TreeWalker(const TreeWalker& walker); - /// Creates a TreeWalker by copying another TreeWalker. - - TreeWalker& operator = (const TreeWalker& walker); - /// Assignment operator. - - ~TreeWalker(); - /// Destroys the TreeWalker. - - Node* root() const; - /// The root node of the TreeWalker, as specified when it was created. - - unsigned long whatToShow() const; - /// This attribute determines which node types are presented via the TreeWalker. - /// The available set of constants is defined in the NodeFilter interface. Nodes - /// not accepted by whatToShow will be skipped, but their children may still - /// be considered. Note that this skip takes precedence over the filter, if - /// any. - - NodeFilter* filter() const; - /// The NodeFilter used to screen nodes. - - bool expandEntityReferences() const; - /// The value of this flag determines whether the children of entity reference - /// nodes are visible to the iterator. If false, they and their descendants - /// will be rejected. Note that this rejection takes precedence over whatToShow - /// and the filter. Also note that this is currently the only situation where - /// NodeIterators may reject a complete subtree rather than skipping individual - /// nodes. - /// - /// To produce a view of the document that has entity references expanded and - /// does not expose the entity reference node itself, use the whatToShow flags - /// to hide the entity reference node and set expandEntityReferences to true - /// when creating the iterator. To produce a view of the document that has entity - /// reference nodes but no entity expansion, use the whatToShow flags to show - /// the entity reference node and set expandEntityReferences to false. - /// - /// This implementation does not support entity reference expansion and - /// thus always returns false. - - Node* currentNode() const; - /// The node at which the TreeWalker is currently positioned. - /// Alterations to the DOM tree may cause the current node to no longer be accepted - /// by the TreeWalker's associated filter. currentNode may also be explicitly - /// set to any node, whether or not it is within the subtree specified by the - /// root node or would be accepted by the filter and whatToShow flags. Further - /// traversal occurs relative to currentNode even if it is not part of the current - /// view, by applying the filters in the requested direction; if no traversal - /// is possible, currentNode is not changed. - - Node* getCurrentNode() const; - /// See currentNode(). - - void setCurrentNode(Node* pNode); - /// Sets the current node. - - Node* parentNode(); - /// Moves to and returns the closest visible ancestor node of the current node. - /// If the search for parentNode attempts to step upward from the TreeWalker's - /// root node, or if it fails to find a visible ancestor node, this method retains - /// the current position and returns null. - - Node* firstChild(); - /// Moves the TreeWalker to the first visible child of the current node, and - /// returns the new node. If the current node has no visible children, returns - /// null, and retains the current node. - - Node* lastChild(); - /// Moves the TreeWalker to the last visible child of the current node, and - /// returns the new node. If the current node has no visible children, returns - /// null, and retains the current node. - - Node* previousSibling(); - /// Moves the TreeWalker to the previous sibling of the current node, and returns - /// the new node. If the current node has no visible previous sibling, returns - /// null, and retains the current node. - - Node* nextSibling(); - /// Moves the TreeWalker to the next sibling of the current node, and returns - /// the new node. If the current node has no visible next sibling, returns null, - /// and retains the current node. - - Node* previousNode(); - /// Moves the TreeWalker to the previous visible node in document order relative - /// to the current node, and returns the new node. If the current node has no - /// previous node, or if the search for previousNode attempts to step upward - /// from the TreeWalker's root node, returns null, and retains the current node. - - Node* nextNode(); - /// Moves the TreeWalker to the next visible node in document order relative - /// to the current node, and returns the new node. If the current node has no - /// next node, or if the search for nextNode attempts to step upward from the - /// TreeWalker's root node, returns null, and retains the current node. - -protected: - int accept(Node* pNode) const; - Node* next(Node* pNode) const; - Node* previous(Node* pNode) const; - -private: - TreeWalker(); - - Node* _pRoot; - unsigned long _whatToShow; - NodeFilter* _pFilter; - Node* _pCurrent; -}; - - -// -// inlines -// -inline Node* TreeWalker::root() const +namespace XML { - return _pRoot; + + + class Node; + class NodeFilter; + + + class XML_API TreeWalker + /// TreeWalker objects are used to navigate a document tree or subtree using + /// the view of the document defined by their whatToShow flags and filter (if + /// any). Any function which performs navigation using a TreeWalker will automatically + /// support any view defined by a TreeWalker. + /// + /// Omitting nodes from the logical view of a subtree can result in a structure + /// that is substantially different from the same subtree in the complete, unfiltered + /// document. Nodes that are siblings in the TreeWalker view may be children + /// of different, widely separated nodes in the original view. For instance, + /// consider a NodeFilter that skips all nodes except for Text nodes and the + /// root node of a document. In the logical view that results, all text nodes + /// will be siblings and appear as direct children of the root node, no matter + /// how deeply nested the structure of the original document. + /// + /// A TreeWalker can be directly instantiated using one of its constructors - + /// the DocumentTraversal interface is not needed and therefore not implemented. + /// Unlike most other DOM classes, TreeWalker supports value semantics. + /// + /// If the TreeWalker's current node is removed from the document, the + /// result of calling any of the movement methods is undefined. This behavior + /// does not conform to the DOM Level 2 Traversal specification. + { + public: + TreeWalker(Node * root, unsigned long whatToShow, NodeFilter * pFilter = 0); + /// Creates a TreeWalker over the subtree rooted at the specified node. + + TreeWalker(const TreeWalker & walker); + /// Creates a TreeWalker by copying another TreeWalker. + + TreeWalker & operator=(const TreeWalker & walker); + /// Assignment operator. + + ~TreeWalker(); + /// Destroys the TreeWalker. + + Node * root() const; + /// The root node of the TreeWalker, as specified when it was created. + + unsigned long whatToShow() const; + /// This attribute determines which node types are presented via the TreeWalker. + /// The available set of constants is defined in the NodeFilter interface. Nodes + /// not accepted by whatToShow will be skipped, but their children may still + /// be considered. Note that this skip takes precedence over the filter, if + /// any. + + NodeFilter * filter() const; + /// The NodeFilter used to screen nodes. + + bool expandEntityReferences() const; + /// The value of this flag determines whether the children of entity reference + /// nodes are visible to the iterator. If false, they and their descendants + /// will be rejected. Note that this rejection takes precedence over whatToShow + /// and the filter. Also note that this is currently the only situation where + /// NodeIterators may reject a complete subtree rather than skipping individual + /// nodes. + /// + /// To produce a view of the document that has entity references expanded and + /// does not expose the entity reference node itself, use the whatToShow flags + /// to hide the entity reference node and set expandEntityReferences to true + /// when creating the iterator. To produce a view of the document that has entity + /// reference nodes but no entity expansion, use the whatToShow flags to show + /// the entity reference node and set expandEntityReferences to false. + /// + /// This implementation does not support entity reference expansion and + /// thus always returns false. + + Node * currentNode() const; + /// The node at which the TreeWalker is currently positioned. + /// Alterations to the DOM tree may cause the current node to no longer be accepted + /// by the TreeWalker's associated filter. currentNode may also be explicitly + /// set to any node, whether or not it is within the subtree specified by the + /// root node or would be accepted by the filter and whatToShow flags. Further + /// traversal occurs relative to currentNode even if it is not part of the current + /// view, by applying the filters in the requested direction; if no traversal + /// is possible, currentNode is not changed. + + Node * getCurrentNode() const; + /// See currentNode(). + + void setCurrentNode(Node * pNode); + /// Sets the current node. + + Node * parentNode(); + /// Moves to and returns the closest visible ancestor node of the current node. + /// If the search for parentNode attempts to step upward from the TreeWalker's + /// root node, or if it fails to find a visible ancestor node, this method retains + /// the current position and returns null. + + Node * firstChild(); + /// Moves the TreeWalker to the first visible child of the current node, and + /// returns the new node. If the current node has no visible children, returns + /// null, and retains the current node. + + Node * lastChild(); + /// Moves the TreeWalker to the last visible child of the current node, and + /// returns the new node. If the current node has no visible children, returns + /// null, and retains the current node. + + Node * previousSibling(); + /// Moves the TreeWalker to the previous sibling of the current node, and returns + /// the new node. If the current node has no visible previous sibling, returns + /// null, and retains the current node. + + Node * nextSibling(); + /// Moves the TreeWalker to the next sibling of the current node, and returns + /// the new node. If the current node has no visible next sibling, returns null, + /// and retains the current node. + + Node * previousNode(); + /// Moves the TreeWalker to the previous visible node in document order relative + /// to the current node, and returns the new node. If the current node has no + /// previous node, or if the search for previousNode attempts to step upward + /// from the TreeWalker's root node, returns null, and retains the current node. + + Node * nextNode(); + /// Moves the TreeWalker to the next visible node in document order relative + /// to the current node, and returns the new node. If the current node has no + /// next node, or if the search for nextNode attempts to step upward from the + /// TreeWalker's root node, returns null, and retains the current node. + + protected: + int accept(Node * pNode) const; + Node * next(Node * pNode) const; + Node * previous(Node * pNode) const; + + private: + TreeWalker(); + + Node * _pRoot; + unsigned long _whatToShow; + NodeFilter * _pFilter; + Node * _pCurrent; + }; + + + // + // inlines + // + inline Node * TreeWalker::root() const + { + return _pRoot; + } + + + inline unsigned long TreeWalker::whatToShow() const + { + return _whatToShow; + } + + + inline NodeFilter * TreeWalker::filter() const + { + return _pFilter; + } + + + inline bool TreeWalker::expandEntityReferences() const + { + return false; + } + + + inline Node * TreeWalker::currentNode() const + { + return _pCurrent; + } + + + inline Node * TreeWalker::getCurrentNode() const + { + return _pCurrent; + } + + } - - -inline unsigned long TreeWalker::whatToShow() const -{ - return _whatToShow; -} - - -inline NodeFilter* TreeWalker::filter() const -{ - return _pFilter; -} - - -inline bool TreeWalker::expandEntityReferences() const -{ - return false; -} - - -inline Node* TreeWalker::currentNode() const -{ - return _pCurrent; -} - - -inline Node* TreeWalker::getCurrentNode() const -{ - return _pCurrent; -} - - -} } // namespace Poco::XML +} // namespace Poco::XML #endif // DOM_TreeWalker_INCLUDED diff --git a/base/poco/XML/include/Poco/SAX/Attributes.h b/base/poco/XML/include/Poco/SAX/Attributes.h index d7ba9129ed5..4ae49a86e7c 100644 --- a/base/poco/XML/include/Poco/SAX/Attributes.h +++ b/base/poco/XML/include/Poco/SAX/Attributes.h @@ -22,99 +22,102 @@ #include "Poco/XML/XMLString.h" -namespace Poco { -namespace XML { - - -class XML_API Attributes - /// Interface for a list of XML attributes. - /// This interface allows access to a list of attributes in three different ways: - /// 1.by attribute index; - /// 2.by Namespace-qualified name; or - /// 3.by qualified (prefixed) name. - /// - /// The list will not contain attributes that were declared #IMPLIED but not - /// specified in the start tag. It will also not contain - /// attributes used as Namespace declarations (xmlns*) unless the - /// http://xml.org/sax/features/namespace-prefixes - /// feature is set to true (it is false by default). - /// - /// If the namespace-prefixes feature (see above) is false, access by - /// qualified name may not be available; if the - /// http://xml.org/sax/features/namespaces feature is false, access by - /// Namespace-qualified names may not be available. - /// This interface replaces the now-deprecated SAX1 AttributeList interface, - /// which does not contain Namespace support. In - /// addition to Namespace support, it adds the getIndex methods (below). - /// The order of attributes in the list is unspecified, and will vary from - /// implementation to implementation. +namespace Poco +{ +namespace XML { -public: - virtual int getIndex(const XMLString& name) const = 0; - /// Look up the index of an attribute by a qualified name. - - virtual int getIndex(const XMLString& namespaceURI, const XMLString& localName) const = 0; - /// Look up the index of an attribute by a namspace name. - - virtual int getLength() const = 0; - /// Return the number of attributes in the list. - /// - /// Once you know the number of attributes, you can iterate through the list. - - virtual const XMLString& getLocalName(int i) const = 0; - /// Look up a local attribute name by index. - - virtual const XMLString& getQName(int i) const = 0; - /// Look up a qualified attribute name by index. - - virtual const XMLString& getType(int i) const = 0; - /// Look up an attribute type by index. - /// - /// The attribute type is one of the strings "CDATA", "ID", "IDREF", "IDREFS", "NMTOKEN", - /// "NMTOKENS", "ENTITY", "ENTITIES", or "NOTATION" (always in upper case). - /// - /// If the parser has not read a declaration for the attribute, or if the parser does not - /// report attribute types, then it must return the value "CDATA" as stated in the XML 1.0 - /// Recommendation (clause 3.3.3, "Attribute-Value Normalization"). - /// - /// For an enumerated attribute that is not a notation, the parser will report the type - /// as "NMTOKEN". - - virtual const XMLString& getType(const XMLString& qname) const = 0; - /// Look up an attribute type by a qualified name. - /// - /// See getType(int) for a description of the possible types. - - virtual const XMLString& getType(const XMLString& namespaceURI, const XMLString& localName) const = 0; - /// Look up an attribute type by a namespace name. - /// - /// See getType(int) for a description of the possible types. - - virtual const XMLString& getValue(int i) const = 0; - /// Look up an attribute value by index. - /// - /// If the attribute value is a list of tokens (IDREFS, ENTITIES, or NMTOKENS), the tokens - /// will be concatenated into a single string with each token separated by a single space. - - virtual const XMLString& getValue(const XMLString& qname) const = 0; - /// Look up an attribute value by a qualified name. - /// - /// See getValue(int) for a description of the possible values. - - virtual const XMLString& getValue(const XMLString& uri, const XMLString& localName) const = 0; - /// Look up an attribute value by a namespace name. - /// - /// See getValue(int) for a description of the possible values. - - virtual const XMLString& getURI(int i) const = 0; - /// Look up a namespace URI by index. - -protected: - virtual ~Attributes(); -}; -} } // namespace Poco::XML + class XML_API Attributes + /// Interface for a list of XML attributes. + /// This interface allows access to a list of attributes in three different ways: + /// 1.by attribute index; + /// 2.by Namespace-qualified name; or + /// 3.by qualified (prefixed) name. + /// + /// The list will not contain attributes that were declared #IMPLIED but not + /// specified in the start tag. It will also not contain + /// attributes used as Namespace declarations (xmlns*) unless the + /// http://xml.org/sax/features/namespace-prefixes + /// feature is set to true (it is false by default). + /// + /// If the namespace-prefixes feature (see above) is false, access by + /// qualified name may not be available; if the + /// http://xml.org/sax/features/namespaces feature is false, access by + /// Namespace-qualified names may not be available. + /// This interface replaces the now-deprecated SAX1 AttributeList interface, + /// which does not contain Namespace support. In + /// addition to Namespace support, it adds the getIndex methods (below). + /// The order of attributes in the list is unspecified, and will vary from + /// implementation to implementation. + { + public: + virtual int getIndex(const XMLString & name) const = 0; + /// Look up the index of an attribute by a qualified name. + + virtual int getIndex(const XMLString & namespaceURI, const XMLString & localName) const = 0; + /// Look up the index of an attribute by a namspace name. + + virtual int getLength() const = 0; + /// Return the number of attributes in the list. + /// + /// Once you know the number of attributes, you can iterate through the list. + + virtual const XMLString & getLocalName(int i) const = 0; + /// Look up a local attribute name by index. + + virtual const XMLString & getQName(int i) const = 0; + /// Look up a qualified attribute name by index. + + virtual const XMLString & getType(int i) const = 0; + /// Look up an attribute type by index. + /// + /// The attribute type is one of the strings "CDATA", "ID", "IDREF", "IDREFS", "NMTOKEN", + /// "NMTOKENS", "ENTITY", "ENTITIES", or "NOTATION" (always in upper case). + /// + /// If the parser has not read a declaration for the attribute, or if the parser does not + /// report attribute types, then it must return the value "CDATA" as stated in the XML 1.0 + /// Recommendation (clause 3.3.3, "Attribute-Value Normalization"). + /// + /// For an enumerated attribute that is not a notation, the parser will report the type + /// as "NMTOKEN". + + virtual const XMLString & getType(const XMLString & qname) const = 0; + /// Look up an attribute type by a qualified name. + /// + /// See getType(int) for a description of the possible types. + + virtual const XMLString & getType(const XMLString & namespaceURI, const XMLString & localName) const = 0; + /// Look up an attribute type by a namespace name. + /// + /// See getType(int) for a description of the possible types. + + virtual const XMLString & getValue(int i) const = 0; + /// Look up an attribute value by index. + /// + /// If the attribute value is a list of tokens (IDREFS, ENTITIES, or NMTOKENS), the tokens + /// will be concatenated into a single string with each token separated by a single space. + + virtual const XMLString & getValue(const XMLString & qname) const = 0; + /// Look up an attribute value by a qualified name. + /// + /// See getValue(int) for a description of the possible values. + + virtual const XMLString & getValue(const XMLString & uri, const XMLString & localName) const = 0; + /// Look up an attribute value by a namespace name. + /// + /// See getValue(int) for a description of the possible values. + + virtual const XMLString & getURI(int i) const = 0; + /// Look up a namespace URI by index. + + protected: + virtual ~Attributes(); + }; + + +} +} // namespace Poco::XML #endif // SAX_Attributes_INCLUDED diff --git a/base/poco/XML/include/Poco/SAX/AttributesImpl.h b/base/poco/XML/include/Poco/SAX/AttributesImpl.h index 13dcf03dac1..ee504c5b9df 100644 --- a/base/poco/XML/include/Poco/SAX/AttributesImpl.h +++ b/base/poco/XML/include/Poco/SAX/AttributesImpl.h @@ -18,290 +18,316 @@ #define SAX_AttributesImpl_INCLUDED -#include "Poco/XML/XML.h" -#include "Poco/SAX/Attributes.h" #include +#include "Poco/SAX/Attributes.h" +#include "Poco/XML/XML.h" -namespace Poco { -namespace XML { - - -class XML_API AttributesImpl: public Attributes - /// This class provides a default implementation of the SAX2 Attributes interface, - /// with the addition of manipulators so that the list can be modified or reused. - /// - /// There are two typical uses of this class: - /// 1. to take a persistent snapshot of an Attributes object in a startElement event; or - /// 2. to construct or modify an Attributes object in a SAX2 driver or filter. +namespace Poco { -public: - struct Attribute - { - XMLString localName; - XMLString namespaceURI; - XMLString qname; - XMLString value; - XMLString type; - bool specified; - }; - using AttributeVec = std::vector; - using iterator = AttributeVec::const_iterator; - - AttributesImpl(); - /// Creates the AttributesImpl. - - AttributesImpl(const Attributes& attributes); - /// Creates the AttributesImpl by copying another one. - - AttributesImpl(const AttributesImpl& attributes); - /// Creates the AttributesImpl by copying another one. - - AttributesImpl(AttributesImpl&& attributes) noexcept; - /// Creates the AttributesImpl by copying another one. - - ~AttributesImpl(); - /// Destroys the AttributesImpl. - - AttributesImpl& operator = (const AttributesImpl& attributes); - /// Assignment operator. - - AttributesImpl& operator = (AttributesImpl&& attributes) noexcept; - /// Assignment operator. - - int getIndex(const XMLString& name) const; - int getIndex(const XMLString& namespaceURI, const XMLString& localName) const; - int getLength() const; - const XMLString& getLocalName(int i) const; - const XMLString& getQName(int i) const; - const XMLString& getType(int i) const; - const XMLString& getType(const XMLString& qname) const; - const XMLString& getType(const XMLString& namespaceURI, const XMLString& localName) const; - const XMLString& getValue(int i) const; - const XMLString& getValue(const XMLString& qname) const; - const XMLString& getValue(const XMLString& namespaceURI, const XMLString& localName) const; - const XMLString& getURI(int i) const; - - bool isSpecified(int i) const; - /// Returns true unless the attribute value was provided by DTD defaulting. - /// Extension from Attributes2 interface. - - bool isSpecified(const XMLString& qname) const; - /// Returns true unless the attribute value was provided by DTD defaulting. - /// Extension from Attributes2 interface. - - bool isSpecified(const XMLString& namespaceURI, const XMLString& localName) const; - /// Returns true unless the attribute value was provided by DTD defaulting. - /// Extension from Attributes2 interface. - - void setValue(int i, const XMLString& value); - /// Sets the value of an attribute. - - void setValue(const XMLString& qname, const XMLString& value); - /// Sets the value of an attribute. - - void setValue(const XMLString& namespaceURI, const XMLString& localName, const XMLString& value); - /// Sets the value of an attribute. - - void setAttributes(const Attributes& attributes); - /// Copies the attributes from another Attributes object. - - void setAttribute(int i, const XMLString& namespaceURI, const XMLString& localName, const XMLString& qname, const XMLString& type, const XMLString& value); - /// Sets an attribute. - - void addAttribute(const XMLString& namespaceURI, const XMLString& localName, const XMLString& qname, const XMLString& type, const XMLString& value); - /// Adds an attribute to the end of the list. - - void addAttribute(const XMLString& namespaceURI, const XMLString& localName, const XMLString& qname, const XMLString& type, const XMLString& value, bool specified); - /// Adds an attribute to the end of the list. - - void addAttribute(const XMLChar* namespaceURI, const XMLChar* localName, const XMLChar* qname, const XMLChar* type, const XMLChar* value, bool specified); - /// Adds an attribute to the end of the list. - - Attribute& addAttribute(); - /// Add an (empty) attribute to the end of the list. - /// For internal use only. - /// The returned Attribute element must be filled by the caller. - - void removeAttribute(int i); - /// Removes an attribute. - - void removeAttribute(const XMLString& qname); - /// Removes an attribute. - - void removeAttribute(const XMLString& namespaceURI, const XMLString& localName); - /// Removes an attribute. - - void clear(); - /// Removes all attributes. - - void reserve(std::size_t capacity); - /// Reserves capacity in the internal vector. - - void setLocalName(int i, const XMLString& localName); - /// Sets the local name of an attribute. - - void setQName(int i, const XMLString& qname); - /// Sets the qualified name of an attribute. - - void setType(int i, const XMLString& type); - /// Sets the type of an attribute. - - void setURI(int i, const XMLString& namespaceURI); - /// Sets the namespace URI of an attribute. - - iterator begin() const; - /// Iterator support. - - iterator end() const; - /// Iterator support. - -protected: - Attribute* find(const XMLString& qname) const; - Attribute* find(const XMLString& namespaceURI, const XMLString& localName) const; - - struct EmptyAttribute: Attribute - { - EmptyAttribute(); - }; - -private: - AttributeVec _attributes; - static EmptyAttribute _empty; -}; - - -// -// inlines -// -inline AttributesImpl::iterator AttributesImpl::begin() const +namespace XML { - return _attributes.begin(); + + + class XML_API AttributesImpl : public Attributes + /// This class provides a default implementation of the SAX2 Attributes interface, + /// with the addition of manipulators so that the list can be modified or reused. + /// + /// There are two typical uses of this class: + /// 1. to take a persistent snapshot of an Attributes object in a startElement event; or + /// 2. to construct or modify an Attributes object in a SAX2 driver or filter. + { + public: + struct Attribute + { + XMLString localName; + XMLString namespaceURI; + XMLString qname; + XMLString value; + XMLString type; + bool specified; + }; + using AttributeVec = std::vector; + using iterator = AttributeVec::const_iterator; + + AttributesImpl(); + /// Creates the AttributesImpl. + + AttributesImpl(const Attributes & attributes); + /// Creates the AttributesImpl by copying another one. + + AttributesImpl(const AttributesImpl & attributes); + /// Creates the AttributesImpl by copying another one. + + AttributesImpl(AttributesImpl && attributes) noexcept; + /// Creates the AttributesImpl by copying another one. + + ~AttributesImpl(); + /// Destroys the AttributesImpl. + + AttributesImpl & operator=(const AttributesImpl & attributes); + /// Assignment operator. + + AttributesImpl & operator=(AttributesImpl && attributes) noexcept; + /// Assignment operator. + + int getIndex(const XMLString & name) const; + int getIndex(const XMLString & namespaceURI, const XMLString & localName) const; + int getLength() const; + const XMLString & getLocalName(int i) const; + const XMLString & getQName(int i) const; + const XMLString & getType(int i) const; + const XMLString & getType(const XMLString & qname) const; + const XMLString & getType(const XMLString & namespaceURI, const XMLString & localName) const; + const XMLString & getValue(int i) const; + const XMLString & getValue(const XMLString & qname) const; + const XMLString & getValue(const XMLString & namespaceURI, const XMLString & localName) const; + const XMLString & getURI(int i) const; + + bool isSpecified(int i) const; + /// Returns true unless the attribute value was provided by DTD defaulting. + /// Extension from Attributes2 interface. + + bool isSpecified(const XMLString & qname) const; + /// Returns true unless the attribute value was provided by DTD defaulting. + /// Extension from Attributes2 interface. + + bool isSpecified(const XMLString & namespaceURI, const XMLString & localName) const; + /// Returns true unless the attribute value was provided by DTD defaulting. + /// Extension from Attributes2 interface. + + void setValue(int i, const XMLString & value); + /// Sets the value of an attribute. + + void setValue(const XMLString & qname, const XMLString & value); + /// Sets the value of an attribute. + + void setValue(const XMLString & namespaceURI, const XMLString & localName, const XMLString & value); + /// Sets the value of an attribute. + + void setAttributes(const Attributes & attributes); + /// Copies the attributes from another Attributes object. + + void setAttribute( + int i, + const XMLString & namespaceURI, + const XMLString & localName, + const XMLString & qname, + const XMLString & type, + const XMLString & value); + /// Sets an attribute. + + void addAttribute( + const XMLString & namespaceURI, + const XMLString & localName, + const XMLString & qname, + const XMLString & type, + const XMLString & value); + /// Adds an attribute to the end of the list. + + void addAttribute( + const XMLString & namespaceURI, + const XMLString & localName, + const XMLString & qname, + const XMLString & type, + const XMLString & value, + bool specified); + /// Adds an attribute to the end of the list. + + void addAttribute( + const XMLChar * namespaceURI, + const XMLChar * localName, + const XMLChar * qname, + const XMLChar * type, + const XMLChar * value, + bool specified); + /// Adds an attribute to the end of the list. + + Attribute & addAttribute(); + /// Add an (empty) attribute to the end of the list. + /// For internal use only. + /// The returned Attribute element must be filled by the caller. + + void removeAttribute(int i); + /// Removes an attribute. + + void removeAttribute(const XMLString & qname); + /// Removes an attribute. + + void removeAttribute(const XMLString & namespaceURI, const XMLString & localName); + /// Removes an attribute. + + void clear(); + /// Removes all attributes. + + void reserve(std::size_t capacity); + /// Reserves capacity in the internal vector. + + void setLocalName(int i, const XMLString & localName); + /// Sets the local name of an attribute. + + void setQName(int i, const XMLString & qname); + /// Sets the qualified name of an attribute. + + void setType(int i, const XMLString & type); + /// Sets the type of an attribute. + + void setURI(int i, const XMLString & namespaceURI); + /// Sets the namespace URI of an attribute. + + iterator begin() const; + /// Iterator support. + + iterator end() const; + /// Iterator support. + + protected: + Attribute * find(const XMLString & qname) const; + Attribute * find(const XMLString & namespaceURI, const XMLString & localName) const; + + struct EmptyAttribute : Attribute + { + EmptyAttribute(); + }; + + private: + AttributeVec _attributes; + static EmptyAttribute _empty; + }; + + + // + // inlines + // + inline AttributesImpl::iterator AttributesImpl::begin() const + { + return _attributes.begin(); + } + + + inline AttributesImpl::iterator AttributesImpl::end() const + { + return _attributes.end(); + } + + + inline AttributesImpl::Attribute & AttributesImpl::addAttribute() + { + _attributes.push_back(_empty); + return _attributes.back(); + } + + + inline int AttributesImpl::getLength() const + { + return (int)_attributes.size(); + } + + + inline const XMLString & AttributesImpl::getLocalName(int i) const + { + poco_assert(0 <= i && i < static_cast(_attributes.size())); + return _attributes[i].localName; + } + + + inline const XMLString & AttributesImpl::getQName(int i) const + { + poco_assert(0 <= i && i < static_cast(_attributes.size())); + return _attributes[i].qname; + } + + + inline const XMLString & AttributesImpl::getType(int i) const + { + poco_assert(0 <= i && i < static_cast(_attributes.size())); + return _attributes[i].type; + } + + + inline const XMLString & AttributesImpl::getType(const XMLString & qname) const + { + Attribute * pAttr = find(qname); + if (pAttr) + return pAttr->type; + else + return _empty.type; + } + + + inline const XMLString & AttributesImpl::getType(const XMLString & namespaceURI, const XMLString & localName) const + { + Attribute * pAttr = find(namespaceURI, localName); + if (pAttr) + return pAttr->type; + else + return _empty.type; + } + + + inline const XMLString & AttributesImpl::getValue(int i) const + { + poco_assert(0 <= i && i < static_cast(_attributes.size())); + return _attributes[i].value; + } + + + inline const XMLString & AttributesImpl::getValue(const XMLString & qname) const + { + Attribute * pAttr = find(qname); + if (pAttr) + return pAttr->value; + else + return _empty.value; + } + + + inline const XMLString & AttributesImpl::getValue(const XMLString & namespaceURI, const XMLString & localName) const + { + Attribute * pAttr = find(namespaceURI, localName); + if (pAttr) + return pAttr->value; + else + return _empty.value; + } + + + inline const XMLString & AttributesImpl::getURI(int i) const + { + poco_assert(0 <= i && i < static_cast(_attributes.size())); + return _attributes[i].namespaceURI; + } + + + inline bool AttributesImpl::isSpecified(int i) const + { + poco_assert(0 <= i && i < static_cast(_attributes.size())); + return _attributes[i].specified; + } + + + inline bool AttributesImpl::isSpecified(const XMLString & qname) const + { + Attribute * pAttr = find(qname); + if (pAttr) + return pAttr->specified; + else + return false; + } + + + inline bool AttributesImpl::isSpecified(const XMLString & namespaceURI, const XMLString & localName) const + { + Attribute * pAttr = find(namespaceURI, localName); + if (pAttr) + return pAttr->specified; + else + return false; + } + + } - - -inline AttributesImpl::iterator AttributesImpl::end() const -{ - return _attributes.end(); -} - - -inline AttributesImpl::Attribute& AttributesImpl::addAttribute() -{ - _attributes.push_back(_empty); - return _attributes.back(); -} - - -inline int AttributesImpl::getLength() const -{ - return (int) _attributes.size(); -} - - -inline const XMLString& AttributesImpl::getLocalName(int i) const -{ - poco_assert (0 <= i && i < static_cast(_attributes.size())); - return _attributes[i].localName; -} - - -inline const XMLString& AttributesImpl::getQName(int i) const -{ - poco_assert (0 <= i && i < static_cast(_attributes.size())); - return _attributes[i].qname; -} - - -inline const XMLString& AttributesImpl::getType(int i) const -{ - poco_assert (0 <= i && i < static_cast(_attributes.size())); - return _attributes[i].type; -} - - -inline const XMLString& AttributesImpl::getType(const XMLString& qname) const -{ - Attribute* pAttr = find(qname); - if (pAttr) - return pAttr->type; - else - return _empty.type; -} - - -inline const XMLString& AttributesImpl::getType(const XMLString& namespaceURI, const XMLString& localName) const -{ - Attribute* pAttr = find(namespaceURI, localName); - if (pAttr) - return pAttr->type; - else - return _empty.type; -} - - -inline const XMLString& AttributesImpl::getValue(int i) const -{ - poco_assert (0 <= i && i < static_cast(_attributes.size())); - return _attributes[i].value; -} - - -inline const XMLString& AttributesImpl::getValue(const XMLString& qname) const -{ - Attribute* pAttr = find(qname); - if (pAttr) - return pAttr->value; - else - return _empty.value; -} - - -inline const XMLString& AttributesImpl::getValue(const XMLString& namespaceURI, const XMLString& localName) const -{ - Attribute* pAttr = find(namespaceURI, localName); - if (pAttr) - return pAttr->value; - else - return _empty.value; -} - - -inline const XMLString& AttributesImpl::getURI(int i) const -{ - poco_assert (0 <= i && i < static_cast(_attributes.size())); - return _attributes[i].namespaceURI; -} - - -inline bool AttributesImpl::isSpecified(int i) const -{ - poco_assert (0 <= i && i < static_cast(_attributes.size())); - return _attributes[i].specified; -} - - -inline bool AttributesImpl::isSpecified(const XMLString& qname) const -{ - Attribute* pAttr = find(qname); - if (pAttr) - return pAttr->specified; - else - return false; -} - - -inline bool AttributesImpl::isSpecified(const XMLString& namespaceURI, const XMLString& localName) const -{ - Attribute* pAttr = find(namespaceURI, localName); - if (pAttr) - return pAttr->specified; - else - return false; -} - - -} } // namespace Poco::XML +} // namespace Poco::XML #endif // SAX_AttributesImpl_INCLUDED diff --git a/base/poco/XML/include/Poco/SAX/ContentHandler.h b/base/poco/XML/include/Poco/SAX/ContentHandler.h index 58f2a253ad8..da158db3678 100644 --- a/base/poco/XML/include/Poco/SAX/ContentHandler.h +++ b/base/poco/XML/include/Poco/SAX/ContentHandler.h @@ -22,219 +22,223 @@ #include "Poco/XML/XMLString.h" -namespace Poco { -namespace XML { - - -class Locator; -class Attributes; - - -class XML_API ContentHandler - /// Receive notification of the logical content of a document. - /// - /// This is the main interface that most SAX applications implement: if the - /// application needs to be informed of basic parsing events, it implements - /// this interface and registers an instance with the SAX parser using the setContentHandler - /// method. The parser uses the instance to report basic document-related events - /// like the start and end of elements and character data. - /// - /// The order of events in this interface is very important, and mirrors the - /// order of information in the document itself. For example, all of an element's - /// content (character data, processing instructions, and/or subelements) will - /// appear, in order, between the startElement event and the corresponding endElement - /// event. - /// - /// This interface is similar to the now-deprecated SAX 1.0 DocumentHandler - /// interface, but it adds support for Namespaces and for reporting skipped - /// entities (in non-validating XML processors). - /// Receive notification of the logical content of a document. +namespace Poco +{ +namespace XML { -public: - virtual void setDocumentLocator(const Locator* loc) = 0; - /// Receive an object for locating the origin of SAX document events. - /// - /// SAX parsers are strongly encouraged (though not absolutely required) to - /// supply a locator: if it does so, it must supply the locator to the application - /// by invoking this method before invoking any of the other methods in the - /// ContentHandler interface. - /// - /// The locator allows the application to determine the end position of any - /// document-related event, even if the parser is not reporting an error. Typically, - /// the application will use this information for reporting its own errors (such - /// as character content that does not match an application's business rules). - /// The information returned by the locator is probably not sufficient for use - /// with a search engine. - /// - /// Note that the locator will return correct information only during the invocation - /// SAX event callbacks after startDocument returns and before endDocument is - /// called. The application should not attempt to use it at any other time. - - virtual void startDocument() = 0; - /// Receive notification of the beginning of a document. - /// - /// The SAX parser calls this function one time before calling all other - /// functions of this class (except SetDocumentLocator). - - virtual void endDocument() = 0; - /// Receive notification of the end of a document. - /// - /// The SAX parser will invoke this method only once, and it will be the last - /// method invoked during the parse. The parser shall not invoke this method - /// until it has either abandoned parsing (because of an unrecoverable error) - /// or reached the end of input. - - virtual void startElement(const XMLString& uri, const XMLString& localName, const XMLString& qname, const Attributes& attrList) = 0; - /// Receive notification of the beginning of an element. - /// - /// The Parser will invoke this method at the beginning of every element in - /// the XML document; there will be a corresponding endElement event for every - /// startElement event (even when the element is empty). All of the element's - /// content will be reported, in order, before the corresponding endElement - /// event. - /// - /// This event allows up to three name components for each element: - /// 1. the Namespace URI; - /// 2. the local name; and - /// 3. the qualified (prefixed) name. - /// - /// Any or all of these may be provided, depending on the values of the http://xml.org/sax/features/namespaces - /// and the http://xml.org/sax/features/namespace-prefixes properties: - /// * the Namespace URI and local name are required when the namespaces - /// property is true (the default), and are optional when the namespaces property - /// is false (if one is specified, both must be); - /// * the qualified name is required when the namespace-prefixes property - /// is true, and is optional when the namespace-prefixes property is false (the - /// default). - /// - /// Note that the attribute list provided will contain only attributes with - /// explicit values (specified or defaulted): #IMPLIED attributes will be omitted. - /// The attribute list will contain attributes used for Namespace declarations - /// (xmlns* attributes) only if the http://xml.org/sax/features/namespace-prefixes - /// property is true (it is false by default, and support for a true value is - /// optional). - /// - /// Like characters(), attribute values may have characters that need more than - /// one char value. - - virtual void endElement(const XMLString& uri, const XMLString& localName, const XMLString& qname) = 0; - /// Receive notification of the end of an element. - /// - /// The SAX parser will invoke this method at the end of every element in the - /// XML document; there will be a corresponding startElement event for every - /// endElement event (even when the element is empty). - /// - /// For information on the names, see startElement. - - virtual void characters(const XMLChar ch[], int start, int length) = 0; - /// Receive notification of character data. - /// - /// The Parser will call this method to report each chunk of character data. - /// SAX parsers may return all contiguous character data in a single chunk, - /// or they may split it into several chunks; however, all of the characters - /// in any single event must come from the same external entity so that the - /// Locator provides useful information. - /// - /// The application must not attempt to read from the array outside of the specified - /// range. - /// - /// Individual characters may consist of more than one XMLChar value. There - /// are three important cases where this happens, because characters can't be - /// represented in just sixteen bits. In one case, characters are represented - /// in a Surrogate Pair, using two special Unicode values. Such characters are - /// in the so-called "Astral Planes", with a code point above U+FFFF. A second - /// case involves composite characters, such as a base character combining with - /// one or more accent characters. And most important, if XMLChar is a plain - /// char, characters are encoded in UTF-8. - /// - /// Your code should not assume that algorithms using char-at-a-time idioms - /// will be working in character units; in some cases they will split characters. - /// This is relevant wherever XML permits arbitrary characters, such as attribute - /// values, processing instruction data, and comments as well as in data reported - /// from this method. It's also generally relevant whenever C++ code manipulates - /// internationalized text; the issue isn't unique to XML. - /// - /// Note that some parsers will report whitespace in element content using the - /// ignorableWhitespace method rather than this one (validating parsers must - /// do so). - - virtual void ignorableWhitespace(const XMLChar ch[], int start, int length) = 0; - /// Receive notification of ignorable whitespace in element content. - /// - /// Validating Parsers must use this method to report each chunk of whitespace - /// in element content (see the W3C XML 1.0 recommendation, section 2.10): non-validating - /// parsers may also use this method if they are capable of parsing and using - /// content models. - /// - /// SAX parsers may return all contiguous whitespace in a single chunk, or they - /// may split it into several chunks; however, all of the characters in any - /// single event must come from the same external entity, so that the Locator - /// provides useful information. - /// - /// The application must not attempt to read from the array outside of the specified - /// range. - - virtual void processingInstruction(const XMLString& target, const XMLString& data) = 0; - /// Receive notification of a processing instruction. - /// - /// The Parser will invoke this method once for each processing instruction - /// found: note that processing instructions may occur before or after the main - /// document element. - /// - /// A SAX parser must never report an XML declaration (XML 1.0, section 2.8) - /// or a text declaration (XML 1.0, section 4.3.1) using this method. - /// - /// Like characters(), processing instruction data may have characters that - /// need more than one char value. - - virtual void startPrefixMapping(const XMLString& prefix, const XMLString& uri) = 0; - /// Begin the scope of a prefix-URI Namespace mapping. - /// - /// The information from this event is not necessary for normal Namespace processing: - /// the SAX XML reader will automatically replace prefixes for element and attribute - /// names when the http://xml.org/sax/features/namespaces feature is true (the - /// default). - /// - /// There are cases, however, when applications need to use prefixes in character - /// data or in attribute values, where they cannot safely be expanded automatically; - /// the start/endPrefixMapping event supplies the information to the application - /// to expand prefixes in those contexts itself, if necessary. - /// - /// Note that start/endPrefixMapping events are not guaranteed to be properly - /// nested relative to each other: all startPrefixMapping events will occur - /// immediately before the corresponding startElement event, and all endPrefixMapping - /// events will occur immediately after the corresponding endElement event, - /// but their order is not otherwise guaranteed. - /// - /// There should never be start/endPrefixMapping events for the "xml" prefix, - /// since it is predeclared and immutable. - - virtual void endPrefixMapping(const XMLString& prefix) = 0; - /// End the scope of a prefix-URI mapping. - /// - /// See startPrefixMapping for details. These events will always occur immediately - /// after the corresponding endElement event, but the order of endPrefixMapping - /// events is not otherwise guaranteed. - - virtual void skippedEntity(const XMLString& name) = 0; - /// Receive notification of a skipped entity. This is not called for entity - /// references within markup constructs such as element start tags or markup - /// declarations. (The XML recommendation requires reporting skipped external - /// entities. SAX also reports internal entity expansion/non-expansion, except - /// within markup constructs.) - /// - /// The Parser will invoke this method each time the entity is skipped. Non-validating - /// processors may skip entities if they have not seen the declarations (because, - /// for example, the entity was declared in an external DTD subset). All processors - /// may skip external entities, depending on the values of the http://xml.org/sax/features/external-general-entities - /// and the http://xml.org/sax/features/external-parameter-entities properties. - -protected: - virtual ~ContentHandler(); -}; -} } // namespace Poco::XML + class Locator; + class Attributes; + + + class XML_API ContentHandler + /// Receive notification of the logical content of a document. + /// + /// This is the main interface that most SAX applications implement: if the + /// application needs to be informed of basic parsing events, it implements + /// this interface and registers an instance with the SAX parser using the setContentHandler + /// method. The parser uses the instance to report basic document-related events + /// like the start and end of elements and character data. + /// + /// The order of events in this interface is very important, and mirrors the + /// order of information in the document itself. For example, all of an element's + /// content (character data, processing instructions, and/or subelements) will + /// appear, in order, between the startElement event and the corresponding endElement + /// event. + /// + /// This interface is similar to the now-deprecated SAX 1.0 DocumentHandler + /// interface, but it adds support for Namespaces and for reporting skipped + /// entities (in non-validating XML processors). + /// Receive notification of the logical content of a document. + { + public: + virtual void setDocumentLocator(const Locator * loc) = 0; + /// Receive an object for locating the origin of SAX document events. + /// + /// SAX parsers are strongly encouraged (though not absolutely required) to + /// supply a locator: if it does so, it must supply the locator to the application + /// by invoking this method before invoking any of the other methods in the + /// ContentHandler interface. + /// + /// The locator allows the application to determine the end position of any + /// document-related event, even if the parser is not reporting an error. Typically, + /// the application will use this information for reporting its own errors (such + /// as character content that does not match an application's business rules). + /// The information returned by the locator is probably not sufficient for use + /// with a search engine. + /// + /// Note that the locator will return correct information only during the invocation + /// SAX event callbacks after startDocument returns and before endDocument is + /// called. The application should not attempt to use it at any other time. + + virtual void startDocument() = 0; + /// Receive notification of the beginning of a document. + /// + /// The SAX parser calls this function one time before calling all other + /// functions of this class (except SetDocumentLocator). + + virtual void endDocument() = 0; + /// Receive notification of the end of a document. + /// + /// The SAX parser will invoke this method only once, and it will be the last + /// method invoked during the parse. The parser shall not invoke this method + /// until it has either abandoned parsing (because of an unrecoverable error) + /// or reached the end of input. + + virtual void startElement(const XMLString & uri, const XMLString & localName, const XMLString & qname, const Attributes & attrList) + = 0; + /// Receive notification of the beginning of an element. + /// + /// The Parser will invoke this method at the beginning of every element in + /// the XML document; there will be a corresponding endElement event for every + /// startElement event (even when the element is empty). All of the element's + /// content will be reported, in order, before the corresponding endElement + /// event. + /// + /// This event allows up to three name components for each element: + /// 1. the Namespace URI; + /// 2. the local name; and + /// 3. the qualified (prefixed) name. + /// + /// Any or all of these may be provided, depending on the values of the http://xml.org/sax/features/namespaces + /// and the http://xml.org/sax/features/namespace-prefixes properties: + /// * the Namespace URI and local name are required when the namespaces + /// property is true (the default), and are optional when the namespaces property + /// is false (if one is specified, both must be); + /// * the qualified name is required when the namespace-prefixes property + /// is true, and is optional when the namespace-prefixes property is false (the + /// default). + /// + /// Note that the attribute list provided will contain only attributes with + /// explicit values (specified or defaulted): #IMPLIED attributes will be omitted. + /// The attribute list will contain attributes used for Namespace declarations + /// (xmlns* attributes) only if the http://xml.org/sax/features/namespace-prefixes + /// property is true (it is false by default, and support for a true value is + /// optional). + /// + /// Like characters(), attribute values may have characters that need more than + /// one char value. + + virtual void endElement(const XMLString & uri, const XMLString & localName, const XMLString & qname) = 0; + /// Receive notification of the end of an element. + /// + /// The SAX parser will invoke this method at the end of every element in the + /// XML document; there will be a corresponding startElement event for every + /// endElement event (even when the element is empty). + /// + /// For information on the names, see startElement. + + virtual void characters(const XMLChar ch[], int start, int length) = 0; + /// Receive notification of character data. + /// + /// The Parser will call this method to report each chunk of character data. + /// SAX parsers may return all contiguous character data in a single chunk, + /// or they may split it into several chunks; however, all of the characters + /// in any single event must come from the same external entity so that the + /// Locator provides useful information. + /// + /// The application must not attempt to read from the array outside of the specified + /// range. + /// + /// Individual characters may consist of more than one XMLChar value. There + /// are three important cases where this happens, because characters can't be + /// represented in just sixteen bits. In one case, characters are represented + /// in a Surrogate Pair, using two special Unicode values. Such characters are + /// in the so-called "Astral Planes", with a code point above U+FFFF. A second + /// case involves composite characters, such as a base character combining with + /// one or more accent characters. And most important, if XMLChar is a plain + /// char, characters are encoded in UTF-8. + /// + /// Your code should not assume that algorithms using char-at-a-time idioms + /// will be working in character units; in some cases they will split characters. + /// This is relevant wherever XML permits arbitrary characters, such as attribute + /// values, processing instruction data, and comments as well as in data reported + /// from this method. It's also generally relevant whenever C++ code manipulates + /// internationalized text; the issue isn't unique to XML. + /// + /// Note that some parsers will report whitespace in element content using the + /// ignorableWhitespace method rather than this one (validating parsers must + /// do so). + + virtual void ignorableWhitespace(const XMLChar ch[], int start, int length) = 0; + /// Receive notification of ignorable whitespace in element content. + /// + /// Validating Parsers must use this method to report each chunk of whitespace + /// in element content (see the W3C XML 1.0 recommendation, section 2.10): non-validating + /// parsers may also use this method if they are capable of parsing and using + /// content models. + /// + /// SAX parsers may return all contiguous whitespace in a single chunk, or they + /// may split it into several chunks; however, all of the characters in any + /// single event must come from the same external entity, so that the Locator + /// provides useful information. + /// + /// The application must not attempt to read from the array outside of the specified + /// range. + + virtual void processingInstruction(const XMLString & target, const XMLString & data) = 0; + /// Receive notification of a processing instruction. + /// + /// The Parser will invoke this method once for each processing instruction + /// found: note that processing instructions may occur before or after the main + /// document element. + /// + /// A SAX parser must never report an XML declaration (XML 1.0, section 2.8) + /// or a text declaration (XML 1.0, section 4.3.1) using this method. + /// + /// Like characters(), processing instruction data may have characters that + /// need more than one char value. + + virtual void startPrefixMapping(const XMLString & prefix, const XMLString & uri) = 0; + /// Begin the scope of a prefix-URI Namespace mapping. + /// + /// The information from this event is not necessary for normal Namespace processing: + /// the SAX XML reader will automatically replace prefixes for element and attribute + /// names when the http://xml.org/sax/features/namespaces feature is true (the + /// default). + /// + /// There are cases, however, when applications need to use prefixes in character + /// data or in attribute values, where they cannot safely be expanded automatically; + /// the start/endPrefixMapping event supplies the information to the application + /// to expand prefixes in those contexts itself, if necessary. + /// + /// Note that start/endPrefixMapping events are not guaranteed to be properly + /// nested relative to each other: all startPrefixMapping events will occur + /// immediately before the corresponding startElement event, and all endPrefixMapping + /// events will occur immediately after the corresponding endElement event, + /// but their order is not otherwise guaranteed. + /// + /// There should never be start/endPrefixMapping events for the "xml" prefix, + /// since it is predeclared and immutable. + + virtual void endPrefixMapping(const XMLString & prefix) = 0; + /// End the scope of a prefix-URI mapping. + /// + /// See startPrefixMapping for details. These events will always occur immediately + /// after the corresponding endElement event, but the order of endPrefixMapping + /// events is not otherwise guaranteed. + + virtual void skippedEntity(const XMLString & name) = 0; + /// Receive notification of a skipped entity. This is not called for entity + /// references within markup constructs such as element start tags or markup + /// declarations. (The XML recommendation requires reporting skipped external + /// entities. SAX also reports internal entity expansion/non-expansion, except + /// within markup constructs.) + /// + /// The Parser will invoke this method each time the entity is skipped. Non-validating + /// processors may skip entities if they have not seen the declarations (because, + /// for example, the entity was declared in an external DTD subset). All processors + /// may skip external entities, depending on the values of the http://xml.org/sax/features/external-general-entities + /// and the http://xml.org/sax/features/external-parameter-entities properties. + + protected: + virtual ~ContentHandler(); + }; + + +} +} // namespace Poco::XML #endif // SAX_ContentHandler_INCLUDED diff --git a/base/poco/XML/include/Poco/SAX/DTDHandler.h b/base/poco/XML/include/Poco/SAX/DTDHandler.h index f21a299c81e..20d9ff978a4 100644 --- a/base/poco/XML/include/Poco/SAX/DTDHandler.h +++ b/base/poco/XML/include/Poco/SAX/DTDHandler.h @@ -22,65 +22,70 @@ #include "Poco/XML/XMLString.h" -namespace Poco { -namespace XML { - - -class XML_API DTDHandler - /// If a SAX application needs information about notations and unparsed entities, - /// then the application implements this interface and registers an instance with the - /// SAX parser using the parser's setDTDHandler method. The parser uses the instance - /// to report notation and unparsed entity declarations to the application. - /// - /// Note that this interface includes only those DTD events that the XML recommendation - /// requires processors to report: notation and unparsed entity declarations. - /// - /// The SAX parser may report these events in any order, regardless of the order in - /// which the notations and unparsed entities were declared; however, all DTD events - /// must be reported after the document handler's startDocument event, and before the first - /// startElement event. (If the LexicalHandler is used, these events must also be reported before the endDTD event.) - /// - /// It is up to the application to store the information for future use (perhaps in a hash table or - /// object tree). If the application encounters attributes of type "NOTATION", "ENTITY", or "ENTITIES", - /// it can use the information that it obtained through this interface to find the entity and/or notation - /// corresponding with the attribute value. +namespace Poco +{ +namespace XML { -public: - virtual void notationDecl(const XMLString& name, const XMLString* publicId, const XMLString* systemId) = 0; - /// Receive notification of a notation declaration event. - /// - /// It is up to the application to record the notation for later reference, - /// if necessary; notations may appear as attribute values and in unparsed - /// entity declarations, and are sometime used with processing instruction - /// target names. - /// - /// At least one of publicId and systemId must be non-null. If a system identifier - /// is present, and it is a URL, the SAX parser must resolve it fully before passing - /// it to the application through this event. - /// - /// There is no guarantee that the notation declaration will be reported before any - /// unparsed entities that use it. - /// - /// Note that publicId and systemId maybe null, therefore we pass a pointer rather than a reference. - - virtual void unparsedEntityDecl(const XMLString& name, const XMLString* publicId, const XMLString& systemId, const XMLString& notationName) = 0; - /// Receive notification of an unparsed entity declaration event. - /// - /// Note that the notation name corresponds to a notation reported by the - /// notationDecl event. It is up to the application to record the entity for - /// later reference, if necessary; unparsed entities may appear as attribute values. - /// - /// If the system identifier is a URL, the parser must resolve it fully before - /// passing it to the application. - /// - /// Note that publicId maybe null, therefore we pass a pointer rather than a reference. - -protected: - virtual ~DTDHandler(); -}; -} } // namespace Poco::XML + class XML_API DTDHandler + /// If a SAX application needs information about notations and unparsed entities, + /// then the application implements this interface and registers an instance with the + /// SAX parser using the parser's setDTDHandler method. The parser uses the instance + /// to report notation and unparsed entity declarations to the application. + /// + /// Note that this interface includes only those DTD events that the XML recommendation + /// requires processors to report: notation and unparsed entity declarations. + /// + /// The SAX parser may report these events in any order, regardless of the order in + /// which the notations and unparsed entities were declared; however, all DTD events + /// must be reported after the document handler's startDocument event, and before the first + /// startElement event. (If the LexicalHandler is used, these events must also be reported before the endDTD event.) + /// + /// It is up to the application to store the information for future use (perhaps in a hash table or + /// object tree). If the application encounters attributes of type "NOTATION", "ENTITY", or "ENTITIES", + /// it can use the information that it obtained through this interface to find the entity and/or notation + /// corresponding with the attribute value. + { + public: + virtual void notationDecl(const XMLString & name, const XMLString * publicId, const XMLString * systemId) = 0; + /// Receive notification of a notation declaration event. + /// + /// It is up to the application to record the notation for later reference, + /// if necessary; notations may appear as attribute values and in unparsed + /// entity declarations, and are sometime used with processing instruction + /// target names. + /// + /// At least one of publicId and systemId must be non-null. If a system identifier + /// is present, and it is a URL, the SAX parser must resolve it fully before passing + /// it to the application through this event. + /// + /// There is no guarantee that the notation declaration will be reported before any + /// unparsed entities that use it. + /// + /// Note that publicId and systemId maybe null, therefore we pass a pointer rather than a reference. + + virtual void + unparsedEntityDecl(const XMLString & name, const XMLString * publicId, const XMLString & systemId, const XMLString & notationName) + = 0; + /// Receive notification of an unparsed entity declaration event. + /// + /// Note that the notation name corresponds to a notation reported by the + /// notationDecl event. It is up to the application to record the entity for + /// later reference, if necessary; unparsed entities may appear as attribute values. + /// + /// If the system identifier is a URL, the parser must resolve it fully before + /// passing it to the application. + /// + /// Note that publicId maybe null, therefore we pass a pointer rather than a reference. + + protected: + virtual ~DTDHandler(); + }; + + +} +} // namespace Poco::XML #endif // SAX_DTDHandler_INCLUDED diff --git a/base/poco/XML/include/Poco/SAX/DeclHandler.h b/base/poco/XML/include/Poco/SAX/DeclHandler.h index 578f10275d8..894a92cf1c6 100644 --- a/base/poco/XML/include/Poco/SAX/DeclHandler.h +++ b/base/poco/XML/include/Poco/SAX/DeclHandler.h @@ -22,70 +22,75 @@ #include "Poco/XML/XMLString.h" -namespace Poco { -namespace XML { - - -class XML_API DeclHandler - /// This is an optional extension handler for SAX2 to provide information - /// about DTD declarations in an XML document. XML - /// readers are not required to support this handler, and this handler is - /// not included in the core SAX2 distribution. - /// - /// Note that data-related DTD declarations (unparsed entities and notations) - /// are already reported through the DTDHandler interface. - /// If you are using the declaration handler together with a lexical handler, - /// all of the events will occur between the startDTD and the endDTD events. - /// To set the DeclHandler for an XML reader, use the setProperty method - /// with the propertyId "http://xml.org/sax/properties/declaration-handler". - /// If the reader does not support declaration events, it will throw a - /// SAXNotRecognizedException or a SAXNotSupportedException when you attempt to - /// register the handler. +namespace Poco +{ +namespace XML { -public: - virtual void attributeDecl(const XMLString& eName, const XMLString& aName, const XMLString* valueDefault, const XMLString* value) = 0; - /// Report an attribute type declaration. - /// - /// Only the effective (first) declaration for an attribute will be reported. - /// The type will be one of the strings "CDATA", "ID", "IDREF", "IDREFS", - /// "NMTOKEN", "NMTOKENS", "ENTITY", "ENTITIES", a parenthesized token group - /// with the separator "|" and all whitespace removed, or the word "NOTATION" - /// followed by a space followed by a parenthesized token group with all whitespace - /// removed. - /// - /// The value will be the value as reported to applications, appropriately normalized - /// and with entity and character references expanded. - - virtual void elementDecl(const XMLString& name, const XMLString& model) = 0; - /// Report an element type declaration. - /// - /// The content model will consist of the string "EMPTY", the string "ANY", or a - /// parenthesised group, optionally followed by an occurrence indicator. The model - /// will be normalized so that all parameter entities are fully resolved and all - /// whitespace is removed,and will include the enclosing parentheses. Other - /// normalization (such as removing redundant parentheses or simplifying occurrence - /// indicators) is at the discretion of the parser. - - virtual void externalEntityDecl(const XMLString& name, const XMLString* publicId, const XMLString& systemId) = 0; - /// Report an external entity declaration. - /// - /// Only the effective (first) declaration for each entity will be reported. - /// - /// If the system identifier is a URL, the parser must resolve it fully before - /// passing it to the application. - - virtual void internalEntityDecl(const XMLString& name, const XMLString& value) = 0; - /// Report an internal entity declaration. - /// - /// Only the effective (first) declaration for each entity will be reported. All - /// parameter entities in the value will be expanded, but general entities will not. - -protected: - virtual ~DeclHandler(); -}; -} } // namespace Poco::XML + class XML_API DeclHandler + /// This is an optional extension handler for SAX2 to provide information + /// about DTD declarations in an XML document. XML + /// readers are not required to support this handler, and this handler is + /// not included in the core SAX2 distribution. + /// + /// Note that data-related DTD declarations (unparsed entities and notations) + /// are already reported through the DTDHandler interface. + /// If you are using the declaration handler together with a lexical handler, + /// all of the events will occur between the startDTD and the endDTD events. + /// To set the DeclHandler for an XML reader, use the setProperty method + /// with the propertyId "http://xml.org/sax/properties/declaration-handler". + /// If the reader does not support declaration events, it will throw a + /// SAXNotRecognizedException or a SAXNotSupportedException when you attempt to + /// register the handler. + { + public: + virtual void + attributeDecl(const XMLString & eName, const XMLString & aName, const XMLString * valueDefault, const XMLString * value) + = 0; + /// Report an attribute type declaration. + /// + /// Only the effective (first) declaration for an attribute will be reported. + /// The type will be one of the strings "CDATA", "ID", "IDREF", "IDREFS", + /// "NMTOKEN", "NMTOKENS", "ENTITY", "ENTITIES", a parenthesized token group + /// with the separator "|" and all whitespace removed, or the word "NOTATION" + /// followed by a space followed by a parenthesized token group with all whitespace + /// removed. + /// + /// The value will be the value as reported to applications, appropriately normalized + /// and with entity and character references expanded. + + virtual void elementDecl(const XMLString & name, const XMLString & model) = 0; + /// Report an element type declaration. + /// + /// The content model will consist of the string "EMPTY", the string "ANY", or a + /// parenthesised group, optionally followed by an occurrence indicator. The model + /// will be normalized so that all parameter entities are fully resolved and all + /// whitespace is removed,and will include the enclosing parentheses. Other + /// normalization (such as removing redundant parentheses or simplifying occurrence + /// indicators) is at the discretion of the parser. + + virtual void externalEntityDecl(const XMLString & name, const XMLString * publicId, const XMLString & systemId) = 0; + /// Report an external entity declaration. + /// + /// Only the effective (first) declaration for each entity will be reported. + /// + /// If the system identifier is a URL, the parser must resolve it fully before + /// passing it to the application. + + virtual void internalEntityDecl(const XMLString & name, const XMLString & value) = 0; + /// Report an internal entity declaration. + /// + /// Only the effective (first) declaration for each entity will be reported. All + /// parameter entities in the value will be expanded, but general entities will not. + + protected: + virtual ~DeclHandler(); + }; + + +} +} // namespace Poco::XML #endif // SAX_DeclHandler_INCLUDED diff --git a/base/poco/XML/include/Poco/SAX/DefaultHandler.h b/base/poco/XML/include/Poco/SAX/DefaultHandler.h index 7df1f5479e9..6412c4cbf5b 100644 --- a/base/poco/XML/include/Poco/SAX/DefaultHandler.h +++ b/base/poco/XML/include/Poco/SAX/DefaultHandler.h @@ -18,66 +18,70 @@ #define SAX_DefaultHandler_INCLUDED -#include "Poco/XML/XML.h" -#include "Poco/SAX/EntityResolver.h" -#include "Poco/SAX/DTDHandler.h" #include "Poco/SAX/ContentHandler.h" +#include "Poco/SAX/DTDHandler.h" +#include "Poco/SAX/EntityResolver.h" #include "Poco/SAX/ErrorHandler.h" +#include "Poco/XML/XML.h" -namespace Poco { -namespace XML { - - -class XML_API DefaultHandler: public EntityResolver, public DTDHandler, public ContentHandler, public ErrorHandler - /// Default base class for SAX2 event handlers. - /// This class is available as a convenience base class for SAX2 applications: - /// it provides default implementations for all of the - /// callbacks in the four core SAX2 handler classes: - /// * EntityResolver - /// * DTDHandler - /// * ContentHandler - /// * ErrorHandler - /// Application writers can extend this class when they need to implement only - /// part of an interface; parser writers can instantiate this - /// class to provide default handlers when the application has not supplied its own. +namespace Poco +{ +namespace XML { -public: - DefaultHandler(); - /// Creates the DefaultHandler. - - ~DefaultHandler(); - /// Destroys the DefaultHandler. - - // EntityResolver - InputSource* resolveEntity(const XMLString* publicId, const XMLString& systemId); - void releaseInputSource(InputSource* pSource); - - // DTDHandler - void notationDecl(const XMLString& name, const XMLString* publicId, const XMLString* systemId); - void unparsedEntityDecl(const XMLString& name, const XMLString* publicId, const XMLString& systemId, const XMLString& notationName); - - // ContentHandler - void setDocumentLocator(const Locator* loc); - void startDocument(); - void endDocument(); - void startElement(const XMLString& uri, const XMLString& localName, const XMLString& qname, const Attributes& attributes); - void endElement(const XMLString& uri, const XMLString& localName, const XMLString& qname); - void characters(const XMLChar ch[], int start, int length); - void ignorableWhitespace(const XMLChar ch[], int start, int length); - void processingInstruction(const XMLString& target, const XMLString& data); - void startPrefixMapping(const XMLString& prefix, const XMLString& uri); - void endPrefixMapping(const XMLString& prefix); - void skippedEntity(const XMLString& name); - - // ErrorHandler - void warning(const SAXException& exc); - void error(const SAXException& exc); - void fatalError(const SAXException& exc); -}; -} } // namespace Poco::XML + class XML_API DefaultHandler : public EntityResolver, public DTDHandler, public ContentHandler, public ErrorHandler + /// Default base class for SAX2 event handlers. + /// This class is available as a convenience base class for SAX2 applications: + /// it provides default implementations for all of the + /// callbacks in the four core SAX2 handler classes: + /// * EntityResolver + /// * DTDHandler + /// * ContentHandler + /// * ErrorHandler + /// Application writers can extend this class when they need to implement only + /// part of an interface; parser writers can instantiate this + /// class to provide default handlers when the application has not supplied its own. + { + public: + DefaultHandler(); + /// Creates the DefaultHandler. + + ~DefaultHandler(); + /// Destroys the DefaultHandler. + + // EntityResolver + InputSource * resolveEntity(const XMLString * publicId, const XMLString & systemId); + void releaseInputSource(InputSource * pSource); + + // DTDHandler + void notationDecl(const XMLString & name, const XMLString * publicId, const XMLString * systemId); + void + unparsedEntityDecl(const XMLString & name, const XMLString * publicId, const XMLString & systemId, const XMLString & notationName); + + // ContentHandler + void setDocumentLocator(const Locator * loc); + void startDocument(); + void endDocument(); + void startElement(const XMLString & uri, const XMLString & localName, const XMLString & qname, const Attributes & attributes); + void endElement(const XMLString & uri, const XMLString & localName, const XMLString & qname); + void characters(const XMLChar ch[], int start, int length); + void ignorableWhitespace(const XMLChar ch[], int start, int length); + void processingInstruction(const XMLString & target, const XMLString & data); + void startPrefixMapping(const XMLString & prefix, const XMLString & uri); + void endPrefixMapping(const XMLString & prefix); + void skippedEntity(const XMLString & name); + + // ErrorHandler + void warning(const SAXException & exc); + void error(const SAXException & exc); + void fatalError(const SAXException & exc); + }; + + +} +} // namespace Poco::XML #endif // SAX_DefaultHandler_INCLUDED diff --git a/base/poco/XML/include/Poco/SAX/EntityResolver.h b/base/poco/XML/include/Poco/SAX/EntityResolver.h index 3387ecfca6c..e5d8e77b232 100644 --- a/base/poco/XML/include/Poco/SAX/EntityResolver.h +++ b/base/poco/XML/include/Poco/SAX/EntityResolver.h @@ -22,65 +22,68 @@ #include "Poco/XML/XMLString.h" -namespace Poco { -namespace XML { - - -class InputSource; - - -class XML_API EntityResolver - /// If a SAX application needs to implement customized handling for external entities, - /// it must implement this interface and register an instance with the SAX driver using - /// the setEntityResolver method. - /// - /// The XML reader will then allow the application to intercept any external entities - /// (including the external DTD subset and external parameter entities, if any) before - /// including them. - /// - /// Many SAX applications will not need to implement this interface, but it will be - /// especially useful for applications that build XML documents from databases or other - /// specialised input sources, or for applications that use URI types other than URLs. - /// - /// The application can also use this interface to redirect system identifiers to local - /// URIs or to look up replacements in a catalog (possibly by using the public identifier). +namespace Poco +{ +namespace XML { -public: - virtual InputSource* resolveEntity(const XMLString* publicId, const XMLString& systemId) = 0; - /// Allow the application to resolve external entities. - /// - /// The parser will call this method before opening any external entity except the - /// top-level document entity. Such entities include the external DTD subset and - /// external parameter entities referenced within the DTD (in either case, only - /// if the parser reads external parameter entities), and external general entities - /// referenced within the document element (if the parser reads external general entities). - /// The application may request that the parser locate the entity itself, that it use an - /// alternative URI, or that it use data provided by the application (as a character or - /// byte input stream). - /// - /// Application writers can use this method to redirect external system identifiers to - /// secure and/or local URIs, to look up public identifiers in a catalogue, or to read an - /// entity from a database or other input source (including, for example, a dialog box). - /// Neither XML nor SAX specifies a preferred policy for using public or system IDs to resolve - /// resources. However, SAX specifies how to interpret any InputSource returned by this method, - /// and that if none is returned, then the system ID will be dereferenced as a URL. - /// - /// If the system identifier is a URL, the SAX parser must resolve it fully before reporting it to - /// the application. - /// - /// Note that publicId maybe null, therefore we pass a pointer rather than a reference. - - virtual void releaseInputSource(InputSource* pSource) = 0; - /// This is a non-standard extension to SAX! - /// Called by the parser when the input source returned by ResolveEntity is - /// no longer needed. Should free any resources used by the input source. - -protected: - virtual ~EntityResolver(); -}; -} } // namespace Poco::XML + class InputSource; + + + class XML_API EntityResolver + /// If a SAX application needs to implement customized handling for external entities, + /// it must implement this interface and register an instance with the SAX driver using + /// the setEntityResolver method. + /// + /// The XML reader will then allow the application to intercept any external entities + /// (including the external DTD subset and external parameter entities, if any) before + /// including them. + /// + /// Many SAX applications will not need to implement this interface, but it will be + /// especially useful for applications that build XML documents from databases or other + /// specialised input sources, or for applications that use URI types other than URLs. + /// + /// The application can also use this interface to redirect system identifiers to local + /// URIs or to look up replacements in a catalog (possibly by using the public identifier). + { + public: + virtual InputSource * resolveEntity(const XMLString * publicId, const XMLString & systemId) = 0; + /// Allow the application to resolve external entities. + /// + /// The parser will call this method before opening any external entity except the + /// top-level document entity. Such entities include the external DTD subset and + /// external parameter entities referenced within the DTD (in either case, only + /// if the parser reads external parameter entities), and external general entities + /// referenced within the document element (if the parser reads external general entities). + /// The application may request that the parser locate the entity itself, that it use an + /// alternative URI, or that it use data provided by the application (as a character or + /// byte input stream). + /// + /// Application writers can use this method to redirect external system identifiers to + /// secure and/or local URIs, to look up public identifiers in a catalogue, or to read an + /// entity from a database or other input source (including, for example, a dialog box). + /// Neither XML nor SAX specifies a preferred policy for using public or system IDs to resolve + /// resources. However, SAX specifies how to interpret any InputSource returned by this method, + /// and that if none is returned, then the system ID will be dereferenced as a URL. + /// + /// If the system identifier is a URL, the SAX parser must resolve it fully before reporting it to + /// the application. + /// + /// Note that publicId maybe null, therefore we pass a pointer rather than a reference. + + virtual void releaseInputSource(InputSource * pSource) = 0; + /// This is a non-standard extension to SAX! + /// Called by the parser when the input source returned by ResolveEntity is + /// no longer needed. Should free any resources used by the input source. + + protected: + virtual ~EntityResolver(); + }; + + +} +} // namespace Poco::XML #endif // SAX_EntityResolver_INCLUDED diff --git a/base/poco/XML/include/Poco/SAX/EntityResolverImpl.h b/base/poco/XML/include/Poco/SAX/EntityResolverImpl.h index de088c64b68..f64babff49e 100644 --- a/base/poco/XML/include/Poco/SAX/EntityResolverImpl.h +++ b/base/poco/XML/include/Poco/SAX/EntityResolverImpl.h @@ -18,61 +18,64 @@ #define SAX_EntityResolverImpl_INCLUDED -#include "Poco/XML/XML.h" -#include "Poco/XML/XMLString.h" #include "Poco/SAX/EntityResolver.h" #include "Poco/URIStreamOpener.h" +#include "Poco/XML/XML.h" +#include "Poco/XML/XMLString.h" -namespace Poco { -namespace XML { - - -class XML_API EntityResolverImpl: public EntityResolver - /// A default implementation of the EntityResolver interface. - /// - /// The system ID is first interpreted as an URI and the - /// URIStreamOpener is used to create and open an istream - /// for an InputSource. - /// - /// If the system ID is not a valid URI, it is - /// interpreted as a filesystem path and a Poco::FileInputStream - /// is opened for it. +namespace Poco +{ +namespace XML { -public: - EntityResolverImpl(); - /// Creates an EntityResolverImpl that uses the default - /// URIStreamOpener. - - EntityResolverImpl(const Poco::URIStreamOpener& opener); - /// Creates an EntityResolverImpl that uses the given - /// URIStreamOpener. - - ~EntityResolverImpl(); - /// Destroys the EntityResolverImpl. - - InputSource* resolveEntity(const XMLString* publicId, const XMLString& systemId); - /// Tries to use the URIStreamOpener to create and open an istream - /// for the given systemId, which is interpreted as an URI. - /// - /// If the systemId is not a valid URI, it is interpreted as - /// a local filesystem path and a Poco::FileInputStream is opened for it. - - void releaseInputSource(InputSource* pSource); - /// Deletes the InputSource's stream. - -protected: - std::istream* resolveSystemId(const XMLString& systemId); - -private: - EntityResolverImpl(const EntityResolverImpl&); - EntityResolverImpl& operator = (const EntityResolverImpl&); - - const Poco::URIStreamOpener& _opener; -}; -} } // namespace Poco::XML + class XML_API EntityResolverImpl : public EntityResolver + /// A default implementation of the EntityResolver interface. + /// + /// The system ID is first interpreted as an URI and the + /// URIStreamOpener is used to create and open an istream + /// for an InputSource. + /// + /// If the system ID is not a valid URI, it is + /// interpreted as a filesystem path and a Poco::FileInputStream + /// is opened for it. + { + public: + EntityResolverImpl(); + /// Creates an EntityResolverImpl that uses the default + /// URIStreamOpener. + + EntityResolverImpl(const Poco::URIStreamOpener & opener); + /// Creates an EntityResolverImpl that uses the given + /// URIStreamOpener. + + ~EntityResolverImpl(); + /// Destroys the EntityResolverImpl. + + InputSource * resolveEntity(const XMLString * publicId, const XMLString & systemId); + /// Tries to use the URIStreamOpener to create and open an istream + /// for the given systemId, which is interpreted as an URI. + /// + /// If the systemId is not a valid URI, it is interpreted as + /// a local filesystem path and a Poco::FileInputStream is opened for it. + + void releaseInputSource(InputSource * pSource); + /// Deletes the InputSource's stream. + + protected: + std::istream * resolveSystemId(const XMLString & systemId); + + private: + EntityResolverImpl(const EntityResolverImpl &); + EntityResolverImpl & operator=(const EntityResolverImpl &); + + const Poco::URIStreamOpener & _opener; + }; + + +} +} // namespace Poco::XML #endif // SAX_EntityResolverImpl_INCLUDED diff --git a/base/poco/XML/include/Poco/SAX/ErrorHandler.h b/base/poco/XML/include/Poco/SAX/ErrorHandler.h index 3097e200757..cd7b22ac93e 100644 --- a/base/poco/XML/include/Poco/SAX/ErrorHandler.h +++ b/base/poco/XML/include/Poco/SAX/ErrorHandler.h @@ -21,72 +21,75 @@ #include "Poco/XML/XML.h" -namespace Poco { -namespace XML { - - -class SAXException; - - -class XML_API ErrorHandler - /// If a SAX application needs to implement customized error handling, it must - /// implement this interface and then register an instance with the XML reader - /// using the setErrorHandler method. The parser will then report all errors and - /// warnings through this interface. - /// - /// WARNING: If an application does not register an ErrorHandler, XML parsing errors - /// will go unreported, except that SAXParseExceptions will be thrown for fatal errors. - /// In order to detect validity errors, an ErrorHandler that does something with error() - /// calls must be registered. - /// - /// For XML processing errors, a SAX driver must use this interface in preference to - /// throwing an exception: it is up to the application to decide whether to throw an - /// exception for different types of errors and warnings. Note, however, that there is no - /// requirement that the parser continue to report additional errors after a call to - /// fatalError. In other words, a SAX driver class may throw an exception after reporting - /// any fatalError. Also parsers may throw appropriate exceptions for non-XML errors. For - /// example, XMLReader::parse() would throw an IOException for errors accessing entities or - /// the document. +namespace Poco +{ +namespace XML { -public: - virtual void warning(const SAXException& exc) = 0; - /// Receive notification of a warning. - /// - /// SAX parsers will use this method to report conditions that are not errors or fatal - /// errors as defined by the XML recommendation. The default behaviour is to take no action. - /// - /// The SAX parser must continue to provide normal parsing events after invoking this method: - /// it should still be possible for the application to process the document through to the end. - /// - /// Filters may use this method to report other, non-XML warnings as well. - - virtual void error(const SAXException& exc) = 0; - /// Receive notification of a recoverable error. - /// - /// This corresponds to the definition of "error" in section 1.2 of the W3C XML 1.0 - /// Recommendation. For example, a validating parser would use this callback to report - /// the violation of a validity constraint. The default behaviour is to take no action. - /// - /// The SAX parser must continue to provide normal parsing events after invoking this - /// method: it should still be possible for the application to process the document through - /// to the end. If the application cannot do so, then the parser should report a fatal error - /// even if the XML recommendation does not require it to do so. - /// - /// Filters may use this method to report other, non-XML errors as well. - - virtual void fatalError(const SAXException& exc) = 0; - /// Receive notification of a non-recoverable error. - /// The application must assume that the document is unusable after the parser has - /// invoked this method, and should continue (if at all) only for the sake of collecting - /// additional error messages: in fact, SAX parsers are free to stop reporting any other - /// events once this method has been invoked. - -protected: - virtual ~ErrorHandler(); -}; -} } // namespace Poco::XML + class SAXException; + + + class XML_API ErrorHandler + /// If a SAX application needs to implement customized error handling, it must + /// implement this interface and then register an instance with the XML reader + /// using the setErrorHandler method. The parser will then report all errors and + /// warnings through this interface. + /// + /// WARNING: If an application does not register an ErrorHandler, XML parsing errors + /// will go unreported, except that SAXParseExceptions will be thrown for fatal errors. + /// In order to detect validity errors, an ErrorHandler that does something with error() + /// calls must be registered. + /// + /// For XML processing errors, a SAX driver must use this interface in preference to + /// throwing an exception: it is up to the application to decide whether to throw an + /// exception for different types of errors and warnings. Note, however, that there is no + /// requirement that the parser continue to report additional errors after a call to + /// fatalError. In other words, a SAX driver class may throw an exception after reporting + /// any fatalError. Also parsers may throw appropriate exceptions for non-XML errors. For + /// example, XMLReader::parse() would throw an IOException for errors accessing entities or + /// the document. + { + public: + virtual void warning(const SAXException & exc) = 0; + /// Receive notification of a warning. + /// + /// SAX parsers will use this method to report conditions that are not errors or fatal + /// errors as defined by the XML recommendation. The default behaviour is to take no action. + /// + /// The SAX parser must continue to provide normal parsing events after invoking this method: + /// it should still be possible for the application to process the document through to the end. + /// + /// Filters may use this method to report other, non-XML warnings as well. + + virtual void error(const SAXException & exc) = 0; + /// Receive notification of a recoverable error. + /// + /// This corresponds to the definition of "error" in section 1.2 of the W3C XML 1.0 + /// Recommendation. For example, a validating parser would use this callback to report + /// the violation of a validity constraint. The default behaviour is to take no action. + /// + /// The SAX parser must continue to provide normal parsing events after invoking this + /// method: it should still be possible for the application to process the document through + /// to the end. If the application cannot do so, then the parser should report a fatal error + /// even if the XML recommendation does not require it to do so. + /// + /// Filters may use this method to report other, non-XML errors as well. + + virtual void fatalError(const SAXException & exc) = 0; + /// Receive notification of a non-recoverable error. + /// The application must assume that the document is unusable after the parser has + /// invoked this method, and should continue (if at all) only for the sake of collecting + /// additional error messages: in fact, SAX parsers are free to stop reporting any other + /// events once this method has been invoked. + + protected: + virtual ~ErrorHandler(); + }; + + +} +} // namespace Poco::XML #endif // SAX_ErrorHandler_INCLUDED diff --git a/base/poco/XML/include/Poco/SAX/InputSource.h b/base/poco/XML/include/Poco/SAX/InputSource.h index 7fcecf2589b..b38a280733c 100644 --- a/base/poco/XML/include/Poco/SAX/InputSource.h +++ b/base/poco/XML/include/Poco/SAX/InputSource.h @@ -19,151 +19,154 @@ #include "Poco/XML/XML.h" -#include "Poco/XML/XMLString.h" #include "Poco/XML/XMLStream.h" +#include "Poco/XML/XMLString.h" -namespace Poco { -namespace XML { - - -class XML_API InputSource - /// This class allows a SAX application to encapsulate information about an input - /// source in a single object, which may include a public identifier, a system - /// identifier, a byte stream (possibly with a specified encoding), and/or a character - /// stream. - /// - /// There are two places that the application can deliver an input source to the - /// parser: as the argument to the Parser.parse method, or as the return value of the - /// EntityResolver::resolveEntity() method. - /// - /// The SAX parser will use the InputSource object to determine how to read XML input. - /// If there is a character stream available, the parser will read that stream directly, - /// disregarding any text encoding declaration found in that stream. If there is no character - /// stream, but there is a byte stream, the parser will use that byte stream, using the - /// encoding specified in the InputSource or else (if no encoding is specified) autodetecting - /// the character encoding using an algorithm such as the one in the XML specification. - /// If neither a character stream nor a byte stream is available, the parser will attempt - /// to open a URI connection to the resource identified by the system identifier. - /// - /// An InputSource object belongs to the application: the SAX parser shall never modify it in - /// any way (it may modify a copy if necessary). However, standard processing of both byte and - /// character streams is to close them on as part of end-of-parse cleanup, so applications should - /// not attempt to re-use such streams after they have been handed to a parser. +namespace Poco { -public: - InputSource(); - /// Zero-argument default constructor. - - InputSource(const XMLString& systemId); - /// Creates a new input source with a system identifier. - /// Applications may use setPublicId to include a public identifier as well, - /// or setEncoding to specify the character encoding, if known. - /// - /// If the system identifier is a URL, it must be fully resolved (it may not - /// be a relative URL). - - InputSource(XMLByteInputStream& istr); - /// Creates a new input source with a byte stream. - /// - /// Application writers should use setSystemId() to provide a base for resolving - /// relative URIs, may use setPublicId to include a public identifier, and may use - /// setEncoding to specify the object's character encoding. - - ~InputSource(); - /// Destroys the InputSource. - - void setPublicId(const XMLString& publicId); - /// Set the public identifier for this input source. - /// - /// The public identifier is always optional: if the application writer includes one, - /// it will be provided as part of the location information. - - void setSystemId(const XMLString& systemId); - /// Set the system identifier for this input source. - /// - /// The system identifier is optional if there is a byte stream or a character stream, - /// but it is still useful to provide one, since the application can use it to resolve - /// relative URIs and can include it in error messages and warnings (the parser will - /// attempt to open a connection to the URI only if there is no byte stream or character - /// stream specified). - /// - /// If the application knows the character encoding of the object pointed to by the system - /// identifier, it can register the encoding using the setEncoding method. - /// - /// If the system identifier is a URL, it must be fully resolved (it may not be a relative URL). - - const XMLString& getPublicId() const; - /// Get the public identifier for this input source. - - const XMLString& getSystemId() const; - /// Get the system identifier for this input source. - - void setByteStream(XMLByteInputStream& istr); - /// Set the byte stream for this input source. - /// The SAX parser will ignore this if there is also a character stream specified, but it - /// will use a byte stream in preference to opening a URI connection itself. - - XMLByteInputStream* getByteStream() const; - /// Get the byte stream for this input source. - - void setCharacterStream(XMLCharInputStream& istr); - /// Set the character stream for this input source. - - XMLCharInputStream* getCharacterStream() const; - /// Get the character stream for this input source. - - void setEncoding(const XMLString& encoding); - /// Set the character encoding, if known. - /// The encoding must be a string acceptable for an XML encoding declaration - /// (see section 4.3.3 of the XML 1.0 recommendation). - - const XMLString& getEncoding() const; - /// Get the character encoding for a byte stream or URI. - -private: - XMLString _publicId; - XMLString _systemId; - XMLString _encoding; - XMLByteInputStream* _bistr; - XMLCharInputStream* _cistr; -}; - - -// -// inlines -// -inline const XMLString& InputSource::getPublicId() const +namespace XML { - return _publicId; + + + class XML_API InputSource + /// This class allows a SAX application to encapsulate information about an input + /// source in a single object, which may include a public identifier, a system + /// identifier, a byte stream (possibly with a specified encoding), and/or a character + /// stream. + /// + /// There are two places that the application can deliver an input source to the + /// parser: as the argument to the Parser.parse method, or as the return value of the + /// EntityResolver::resolveEntity() method. + /// + /// The SAX parser will use the InputSource object to determine how to read XML input. + /// If there is a character stream available, the parser will read that stream directly, + /// disregarding any text encoding declaration found in that stream. If there is no character + /// stream, but there is a byte stream, the parser will use that byte stream, using the + /// encoding specified in the InputSource or else (if no encoding is specified) autodetecting + /// the character encoding using an algorithm such as the one in the XML specification. + /// If neither a character stream nor a byte stream is available, the parser will attempt + /// to open a URI connection to the resource identified by the system identifier. + /// + /// An InputSource object belongs to the application: the SAX parser shall never modify it in + /// any way (it may modify a copy if necessary). However, standard processing of both byte and + /// character streams is to close them on as part of end-of-parse cleanup, so applications should + /// not attempt to re-use such streams after they have been handed to a parser. + { + public: + InputSource(); + /// Zero-argument default constructor. + + InputSource(const XMLString & systemId); + /// Creates a new input source with a system identifier. + /// Applications may use setPublicId to include a public identifier as well, + /// or setEncoding to specify the character encoding, if known. + /// + /// If the system identifier is a URL, it must be fully resolved (it may not + /// be a relative URL). + + InputSource(XMLByteInputStream & istr); + /// Creates a new input source with a byte stream. + /// + /// Application writers should use setSystemId() to provide a base for resolving + /// relative URIs, may use setPublicId to include a public identifier, and may use + /// setEncoding to specify the object's character encoding. + + ~InputSource(); + /// Destroys the InputSource. + + void setPublicId(const XMLString & publicId); + /// Set the public identifier for this input source. + /// + /// The public identifier is always optional: if the application writer includes one, + /// it will be provided as part of the location information. + + void setSystemId(const XMLString & systemId); + /// Set the system identifier for this input source. + /// + /// The system identifier is optional if there is a byte stream or a character stream, + /// but it is still useful to provide one, since the application can use it to resolve + /// relative URIs and can include it in error messages and warnings (the parser will + /// attempt to open a connection to the URI only if there is no byte stream or character + /// stream specified). + /// + /// If the application knows the character encoding of the object pointed to by the system + /// identifier, it can register the encoding using the setEncoding method. + /// + /// If the system identifier is a URL, it must be fully resolved (it may not be a relative URL). + + const XMLString & getPublicId() const; + /// Get the public identifier for this input source. + + const XMLString & getSystemId() const; + /// Get the system identifier for this input source. + + void setByteStream(XMLByteInputStream & istr); + /// Set the byte stream for this input source. + /// The SAX parser will ignore this if there is also a character stream specified, but it + /// will use a byte stream in preference to opening a URI connection itself. + + XMLByteInputStream * getByteStream() const; + /// Get the byte stream for this input source. + + void setCharacterStream(XMLCharInputStream & istr); + /// Set the character stream for this input source. + + XMLCharInputStream * getCharacterStream() const; + /// Get the character stream for this input source. + + void setEncoding(const XMLString & encoding); + /// Set the character encoding, if known. + /// The encoding must be a string acceptable for an XML encoding declaration + /// (see section 4.3.3 of the XML 1.0 recommendation). + + const XMLString & getEncoding() const; + /// Get the character encoding for a byte stream or URI. + + private: + XMLString _publicId; + XMLString _systemId; + XMLString _encoding; + XMLByteInputStream * _bistr; + XMLCharInputStream * _cistr; + }; + + + // + // inlines + // + inline const XMLString & InputSource::getPublicId() const + { + return _publicId; + } + + + inline const XMLString & InputSource::getSystemId() const + { + return _systemId; + } + + + inline const XMLString & InputSource::getEncoding() const + { + return _encoding; + } + + + inline XMLByteInputStream * InputSource::getByteStream() const + { + return _bistr; + } + + + inline XMLCharInputStream * InputSource::getCharacterStream() const + { + return _cistr; + } + + } - - -inline const XMLString& InputSource::getSystemId() const -{ - return _systemId; -} - - -inline const XMLString& InputSource::getEncoding() const -{ - return _encoding; -} - - -inline XMLByteInputStream* InputSource::getByteStream() const -{ - return _bistr; -} - - -inline XMLCharInputStream* InputSource::getCharacterStream() const -{ - return _cistr; -} - - -} } // namespace Poco::XML +} // namespace Poco::XML #endif // SAX_InputSource_INCLUDED diff --git a/base/poco/XML/include/Poco/SAX/LexicalHandler.h b/base/poco/XML/include/Poco/SAX/LexicalHandler.h index 772bd5c3fb8..1f330d60274 100644 --- a/base/poco/XML/include/Poco/SAX/LexicalHandler.h +++ b/base/poco/XML/include/Poco/SAX/LexicalHandler.h @@ -22,104 +22,107 @@ #include "Poco/XML/XMLString.h" -namespace Poco { -namespace XML { - - -class XML_API LexicalHandler - /// This is an optional extension handler for SAX2 to provide lexical information - /// about an XML document, such as comments and CDATA section boundaries. - /// XML readers are not required to recognize this handler, and it is not part of - /// core-only SAX2 distributions. - /// - /// The events in the lexical handler apply to the entire document, not just to the - /// document element, and all lexical handler events must appear between the content - /// handler's startDocument and endDocument events. - /// - /// To set the LexicalHandler for an XML reader, use the setProperty method with the - /// property name http://xml.org/sax/properties/lexical-handler and an object implementing - /// this interface (or null) as the value. If the reader does not report lexical events, - /// it will throw a SAXNotRecognizedException when you attempt to register the handler. +namespace Poco +{ +namespace XML { -public: - virtual void startDTD(const XMLString& name, const XMLString& publicId, const XMLString& systemId) = 0; - /// Report the start of DTD declarations, if any. - /// - /// This method is intended to report the beginning of the DOCTYPE declaration; - /// if the document has no DOCTYPE declaration, this method will not be invoked. - /// - /// All declarations reported through DTDHandler or DeclHandler events must appear - /// between the startDTD and endDTD events. Declarations are assumed to belong to - /// the internal DTD subset unless they appear between startEntity and endEntity - /// events. Comments and processing instructions from the DTD should also be reported - /// between the startDTD and endDTD events, in their original order of (logical) occurrence; - /// they are not required to appear in their correct locations relative to DTDHandler or - /// DeclHandler events, however. - /// - /// Note that the start/endDTD events will appear within the start/endDocument events from - /// ContentHandler and before the first startElement event. - - virtual void endDTD() = 0; - /// Report the end of DTD declarations. - /// - /// This method is intended to report the end of the DOCTYPE declaration; if the document - /// has no DOCTYPE declaration, this method will not be invoked. - - virtual void startEntity(const XMLString& name) = 0; - /// Report the beginning of some internal and external XML entities. - /// - /// The reporting of parameter entities (including the external DTD subset) is optional, - /// and SAX2 drivers that report LexicalHandler events may not implement it; you can use the - /// http://xml.org/sax/features/lexical-handler/parameter-entities feature to query or control - /// the reporting of parameter entities. - /// - /// General entities are reported with their regular names, parameter entities have '%' - /// prepended to their names, and the external DTD subset has the pseudo-entity name "[dtd]". - /// - /// When a SAX2 driver is providing these events, all other events must be properly nested - /// within start/end entity events. There is no additional requirement that events from - /// DeclHandler or DTDHandler be properly ordered. - /// - /// Note that skipped entities will be reported through the skippedEntity event, which is part of - /// the ContentHandler interface. - /// - /// Because of the streaming event model that SAX uses, some entity boundaries cannot be reported under - /// any circumstances: - /// - /// * general entities within attribute values - /// * parameter entities within declarations - /// - /// These will be silently expanded, with no indication of where the original entity boundaries were. - /// - /// Note also that the boundaries of character references (which are not really entities anyway) are not reported. - /// - /// All start/endEntity events must be properly nested. - - virtual void endEntity(const XMLString& name) = 0; - /// Report the end of an entity. - - virtual void startCDATA() = 0; - /// Report the start of a CDATA section. - /// - /// The contents of the CDATA section will be reported through the regular characters event; - /// this event is intended only to report the boundary. - - virtual void endCDATA() = 0; - /// Report the end of a CDATA section. - - virtual void comment(const XMLChar ch[], int start, int length) = 0; - /// Report an XML comment anywhere in the document. - /// - /// This callback will be used for comments inside or outside the document element, - /// including comments in the external DTD subset (if read). Comments in the DTD must - /// be properly nested inside start/endDTD and start/endEntity events (if used). - -protected: - virtual ~LexicalHandler(); -}; -} } // namespace Poco::XML + class XML_API LexicalHandler + /// This is an optional extension handler for SAX2 to provide lexical information + /// about an XML document, such as comments and CDATA section boundaries. + /// XML readers are not required to recognize this handler, and it is not part of + /// core-only SAX2 distributions. + /// + /// The events in the lexical handler apply to the entire document, not just to the + /// document element, and all lexical handler events must appear between the content + /// handler's startDocument and endDocument events. + /// + /// To set the LexicalHandler for an XML reader, use the setProperty method with the + /// property name http://xml.org/sax/properties/lexical-handler and an object implementing + /// this interface (or null) as the value. If the reader does not report lexical events, + /// it will throw a SAXNotRecognizedException when you attempt to register the handler. + { + public: + virtual void startDTD(const XMLString & name, const XMLString & publicId, const XMLString & systemId) = 0; + /// Report the start of DTD declarations, if any. + /// + /// This method is intended to report the beginning of the DOCTYPE declaration; + /// if the document has no DOCTYPE declaration, this method will not be invoked. + /// + /// All declarations reported through DTDHandler or DeclHandler events must appear + /// between the startDTD and endDTD events. Declarations are assumed to belong to + /// the internal DTD subset unless they appear between startEntity and endEntity + /// events. Comments and processing instructions from the DTD should also be reported + /// between the startDTD and endDTD events, in their original order of (logical) occurrence; + /// they are not required to appear in their correct locations relative to DTDHandler or + /// DeclHandler events, however. + /// + /// Note that the start/endDTD events will appear within the start/endDocument events from + /// ContentHandler and before the first startElement event. + + virtual void endDTD() = 0; + /// Report the end of DTD declarations. + /// + /// This method is intended to report the end of the DOCTYPE declaration; if the document + /// has no DOCTYPE declaration, this method will not be invoked. + + virtual void startEntity(const XMLString & name) = 0; + /// Report the beginning of some internal and external XML entities. + /// + /// The reporting of parameter entities (including the external DTD subset) is optional, + /// and SAX2 drivers that report LexicalHandler events may not implement it; you can use the + /// http://xml.org/sax/features/lexical-handler/parameter-entities feature to query or control + /// the reporting of parameter entities. + /// + /// General entities are reported with their regular names, parameter entities have '%' + /// prepended to their names, and the external DTD subset has the pseudo-entity name "[dtd]". + /// + /// When a SAX2 driver is providing these events, all other events must be properly nested + /// within start/end entity events. There is no additional requirement that events from + /// DeclHandler or DTDHandler be properly ordered. + /// + /// Note that skipped entities will be reported through the skippedEntity event, which is part of + /// the ContentHandler interface. + /// + /// Because of the streaming event model that SAX uses, some entity boundaries cannot be reported under + /// any circumstances: + /// + /// * general entities within attribute values + /// * parameter entities within declarations + /// + /// These will be silently expanded, with no indication of where the original entity boundaries were. + /// + /// Note also that the boundaries of character references (which are not really entities anyway) are not reported. + /// + /// All start/endEntity events must be properly nested. + + virtual void endEntity(const XMLString & name) = 0; + /// Report the end of an entity. + + virtual void startCDATA() = 0; + /// Report the start of a CDATA section. + /// + /// The contents of the CDATA section will be reported through the regular characters event; + /// this event is intended only to report the boundary. + + virtual void endCDATA() = 0; + /// Report the end of a CDATA section. + + virtual void comment(const XMLChar ch[], int start, int length) = 0; + /// Report an XML comment anywhere in the document. + /// + /// This callback will be used for comments inside or outside the document element, + /// including comments in the external DTD subset (if read). Comments in the DTD must + /// be properly nested inside start/endDTD and start/endEntity events (if used). + + protected: + virtual ~LexicalHandler(); + }; + + +} +} // namespace Poco::XML #endif // SAX_LexicalHandler_INCLUDED diff --git a/base/poco/XML/include/Poco/SAX/Locator.h b/base/poco/XML/include/Poco/SAX/Locator.h index 4f2b47d4812..c1293a3c3a8 100644 --- a/base/poco/XML/include/Poco/SAX/Locator.h +++ b/base/poco/XML/include/Poco/SAX/Locator.h @@ -22,82 +22,85 @@ #include "Poco/XML/XMLString.h" -namespace Poco { -namespace XML { - - -class XML_API Locator - /// Interface for associating a SAX event with a document location. - /// - /// If a SAX parser provides location information to the SAX application, it does so by - /// implementing this interface and then passing an instance to the application using the - /// content handler's setDocumentLocator method. The application can use the object to obtain - /// the location of any other SAX event in the XML source document. - /// - /// Note that the results returned by the object will be valid only during the scope of each - /// callback method: the application will receive unpredictable results if it attempts to use - /// the locator at any other time, or after parsing completes. - /// - /// SAX parsers are not required to supply a locator, but they are very strongly encouraged to - /// do so. If the parser supplies a locator, it must do so before reporting any other document - /// events. If no locator has been set by the time the application receives the startDocument event, - /// the application should assume that a locator is not available. +namespace Poco +{ +namespace XML { -public: - virtual XMLString getPublicId() const = 0; - /// Return the public identifier for the current document event. - /// - /// The return value is the public identifier of the document entity or of the external - /// parsed entity in which the markup triggering the event appears. - - virtual XMLString getSystemId() const = 0; - /// Return the system identifier for the current document event. - /// - /// The return value is the system identifier of the document entity or of the external - /// parsed entity in which the markup triggering the event appears. - /// - /// If the system identifier is a URL, the parser must resolve it fully before passing - /// it to the application. For example, a file name must always be provided as a - /// file:... URL, and other kinds of relative URI are also resolved against their bases. - - virtual int getLineNumber() const = 0; - /// Return the line number where the current document event ends. - /// Lines are delimited by line ends, which are defined in the XML specification. - /// - /// Warning: The return value from the method is intended only as an approximation for - /// the sake of diagnostics; it is not intended to provide sufficient information to - /// edit the character content of the original XML document. In some cases, these "line" - /// numbers match what would be displayed as columns, and in others they may not match the - /// source text due to internal entity expansion. - /// - /// The return value is an approximation of the line number in the document entity or external - /// parsed entity where the markup triggering the event appears. - /// - /// If possible, the SAX driver should provide the line position of the first character after - /// the text associated with the document event. The first line is line 1. - - virtual int getColumnNumber() const = 0; - /// Return the column number where the current document event ends. - /// This is one-based number of characters since the last line end. - /// - /// Warning: The return value from the method is intended only as an approximation - /// for the sake of diagnostics; it is not intended to provide sufficient information - /// to edit the character content of the original XML document. For example, when lines - /// contain combining character sequences, wide characters, surrogate pairs, or bi-directional - /// text, the value may not correspond to the column in a text editor's display. - /// - /// The return value is an approximation of the column number in the document entity or external - /// parsed entity where the markup triggering the event appears. - /// - /// If possible, the SAX driver should provide the line position of the first character after - /// the text associated with the document event. The first column in each line is column 1. - -protected: - virtual ~Locator(); -}; -} } // namespace Poco::XML + class XML_API Locator + /// Interface for associating a SAX event with a document location. + /// + /// If a SAX parser provides location information to the SAX application, it does so by + /// implementing this interface and then passing an instance to the application using the + /// content handler's setDocumentLocator method. The application can use the object to obtain + /// the location of any other SAX event in the XML source document. + /// + /// Note that the results returned by the object will be valid only during the scope of each + /// callback method: the application will receive unpredictable results if it attempts to use + /// the locator at any other time, or after parsing completes. + /// + /// SAX parsers are not required to supply a locator, but they are very strongly encouraged to + /// do so. If the parser supplies a locator, it must do so before reporting any other document + /// events. If no locator has been set by the time the application receives the startDocument event, + /// the application should assume that a locator is not available. + { + public: + virtual XMLString getPublicId() const = 0; + /// Return the public identifier for the current document event. + /// + /// The return value is the public identifier of the document entity or of the external + /// parsed entity in which the markup triggering the event appears. + + virtual XMLString getSystemId() const = 0; + /// Return the system identifier for the current document event. + /// + /// The return value is the system identifier of the document entity or of the external + /// parsed entity in which the markup triggering the event appears. + /// + /// If the system identifier is a URL, the parser must resolve it fully before passing + /// it to the application. For example, a file name must always be provided as a + /// file:... URL, and other kinds of relative URI are also resolved against their bases. + + virtual int getLineNumber() const = 0; + /// Return the line number where the current document event ends. + /// Lines are delimited by line ends, which are defined in the XML specification. + /// + /// Warning: The return value from the method is intended only as an approximation for + /// the sake of diagnostics; it is not intended to provide sufficient information to + /// edit the character content of the original XML document. In some cases, these "line" + /// numbers match what would be displayed as columns, and in others they may not match the + /// source text due to internal entity expansion. + /// + /// The return value is an approximation of the line number in the document entity or external + /// parsed entity where the markup triggering the event appears. + /// + /// If possible, the SAX driver should provide the line position of the first character after + /// the text associated with the document event. The first line is line 1. + + virtual int getColumnNumber() const = 0; + /// Return the column number where the current document event ends. + /// This is one-based number of characters since the last line end. + /// + /// Warning: The return value from the method is intended only as an approximation + /// for the sake of diagnostics; it is not intended to provide sufficient information + /// to edit the character content of the original XML document. For example, when lines + /// contain combining character sequences, wide characters, surrogate pairs, or bi-directional + /// text, the value may not correspond to the column in a text editor's display. + /// + /// The return value is an approximation of the column number in the document entity or external + /// parsed entity where the markup triggering the event appears. + /// + /// If possible, the SAX driver should provide the line position of the first character after + /// the text associated with the document event. The first column in each line is column 1. + + protected: + virtual ~Locator(); + }; + + +} +} // namespace Poco::XML #endif // SAX_Locator_INCLUDED diff --git a/base/poco/XML/include/Poco/SAX/LocatorImpl.h b/base/poco/XML/include/Poco/SAX/LocatorImpl.h index 2c924b3f889..15304ca5f6c 100644 --- a/base/poco/XML/include/Poco/SAX/LocatorImpl.h +++ b/base/poco/XML/include/Poco/SAX/LocatorImpl.h @@ -18,71 +18,74 @@ #define SAX_LocatorImpl_INCLUDED -#include "Poco/XML/XML.h" #include "Poco/SAX/Locator.h" +#include "Poco/XML/XML.h" #include "Poco/XML/XMLString.h" -namespace Poco { -namespace XML { - - -class XML_API LocatorImpl: public Locator - /// Provide an optional convenience implementation of Locator. +namespace Poco +{ +namespace XML { -public: - LocatorImpl(); - /// Zero-argument constructor. - /// - /// This will not normally be useful, since the main purpose of this class is - /// to make a snapshot of an existing Locator. - - LocatorImpl(const Locator& loc); - /// Copy constructor. - /// - /// Create a persistent copy of the current state of a locator. When the original - /// locator changes, this copy will still keep the original values (and it can be - /// used outside the scope of DocumentHandler methods). - - ~LocatorImpl(); - /// Destroys the Locator. - - LocatorImpl& operator = (const Locator& loc); - /// Assignment operator. - - XMLString getPublicId() const; - /// Return the saved public identifier. - - XMLString getSystemId() const; - /// Return the saved system identifier. - - int getLineNumber() const; - /// Return the saved line number (1-based). - - int getColumnNumber() const; - /// Return the saved column number (1-based). - - void setPublicId(const XMLString& publicId); - /// Set the public identifier for this locator. - - void setSystemId(const XMLString& systemId); - /// Set the system identifier for this locator. - - void setLineNumber(int lineNumber); - /// Set the line number for this locator (1-based). - - void setColumnNumber(int columnNumber); - /// Set the column number for this locator (1-based). - -private: - XMLString _publicId; - XMLString _systemId; - int _lineNumber; - int _columnNumber; -}; -} } // namespace Poco::XML + class XML_API LocatorImpl : public Locator + /// Provide an optional convenience implementation of Locator. + { + public: + LocatorImpl(); + /// Zero-argument constructor. + /// + /// This will not normally be useful, since the main purpose of this class is + /// to make a snapshot of an existing Locator. + + LocatorImpl(const Locator & loc); + /// Copy constructor. + /// + /// Create a persistent copy of the current state of a locator. When the original + /// locator changes, this copy will still keep the original values (and it can be + /// used outside the scope of DocumentHandler methods). + + ~LocatorImpl(); + /// Destroys the Locator. + + LocatorImpl & operator=(const Locator & loc); + /// Assignment operator. + + XMLString getPublicId() const; + /// Return the saved public identifier. + + XMLString getSystemId() const; + /// Return the saved system identifier. + + int getLineNumber() const; + /// Return the saved line number (1-based). + + int getColumnNumber() const; + /// Return the saved column number (1-based). + + void setPublicId(const XMLString & publicId); + /// Set the public identifier for this locator. + + void setSystemId(const XMLString & systemId); + /// Set the system identifier for this locator. + + void setLineNumber(int lineNumber); + /// Set the line number for this locator (1-based). + + void setColumnNumber(int columnNumber); + /// Set the column number for this locator (1-based). + + private: + XMLString _publicId; + XMLString _systemId; + int _lineNumber; + int _columnNumber; + }; + + +} +} // namespace Poco::XML #endif // SAX_LocatorImpl_INCLUDED diff --git a/base/poco/XML/include/Poco/SAX/NamespaceSupport.h b/base/poco/XML/include/Poco/SAX/NamespaceSupport.h index 3c4244f0ac5..ddf5881aec3 100644 --- a/base/poco/XML/include/Poco/SAX/NamespaceSupport.h +++ b/base/poco/XML/include/Poco/SAX/NamespaceSupport.h @@ -18,178 +18,181 @@ #define SAX_NamespaceSupport_INCLUDED +#include +#include +#include #include "Poco/XML/XML.h" #include "Poco/XML/XMLString.h" -#include -#include -#include -namespace Poco { -namespace XML { - - -class XML_API NamespaceSupport - /// Encapsulate Namespace logic for use by SAX drivers. - /// This class encapsulates the logic of Namespace processing: - /// it tracks the declarations currently in force for each context and - /// automatically processes qualified XML 1.0 names into their Namespace - /// parts; it can also be used in reverse for generating - /// XML 1.0 from Namespaces. - /// Namespace support objects are reusable, but the reset method - /// must be invoked between each session. +namespace Poco +{ +namespace XML { -public: - using PrefixSet = std::set; - - NamespaceSupport(); - /// Creates a NamespaceSupport object. - - ~NamespaceSupport(); - /// Destroys a NamespaceSupport object. - - bool declarePrefix(const XMLString& prefix, const XMLString& namespaceURI); - /// Declare a Namespace prefix. All prefixes must be declared before they are - /// referenced. For example, a SAX driver (parser) would scan an element's attributes - /// in two passes: first for namespace declarations, then a second pass using - /// processName() to interpret prefixes against (potentially redefined) prefixes. - /// - /// This method declares a prefix in the current Namespace context; the prefix - /// will remain in force until this context is popped, unless it is shadowed - /// in a descendant context. - /// - /// To declare the default element Namespace, use the empty string as the prefix. - /// - /// Note that you must not declare a prefix after you've pushed and popped another - /// Namespace context, or treated the declarations phase as complete by processing - /// a prefixed name. - /// - /// Returns true if the prefix was legal, false otherwise. - - bool undeclarePrefix(const XMLString& prefix); - /// Remove the given namespace prefix. - - void getDeclaredPrefixes(PrefixSet& prefixes) const; - /// Return an enumeration of all prefixes declared in this context. - /// - /// The empty (default) prefix will be included in this enumeration; note that - /// this behaviour differs from that of getPrefix() and getPrefixes(). - - const XMLString& getPrefix(const XMLString& namespaceURI) const; - /// Return one of the prefixes mapped to a Namespace URI. - /// - /// If more than one prefix is currently mapped to the same URI, this method - /// will make an arbitrary selection; if you want all of the prefixes, use the - /// getPrefixes() method instead. - - bool isMapped(const XMLString& namespaceURI) const; - /// Returns true if the given namespaceURI has been mapped to a prefix, - /// false otherwise. - - void getPrefixes(PrefixSet& prefixes) const; - /// Return an enumeration of all prefixes whose declarations are active in the - /// current context. This includes declarations from parent contexts that have - /// not been overridden. - /// - /// Note: if there is a default prefix, it will not be returned in this enumeration; - /// check for the default prefix using the getURI with an argument of "". - - void getPrefixes(const XMLString& namespaceURI, PrefixSet& prefixes) const; - /// Return an enumeration of all prefixes for a given URI whose declarations - /// are active in the current context. This includes declarations from parent - /// contexts that have not been overridden. - /// - /// This method returns prefixes mapped to a specific Namespace URI. The xml: - /// prefix will be included. If you want only one prefix that's mapped to the - /// Namespace URI, and you don't care which one you get, use the getPrefix() method - /// instead. - /// - /// Note: the empty (default) prefix is never included in this enumeration; - /// to check for the presence of a default Namespace, use the getURI() method - /// with an argument of "". - - const XMLString& getURI(const XMLString& prefix) const; - /// Look up a prefix and get the currently-mapped Namespace URI. - /// - /// This method looks up the prefix in the current context. Use the empty string - /// ("") for the default Namespace. - - void pushContext(); - /// Start a new Namespace context. The new context will automatically inherit - /// the declarations of its parent context, but it will also keep track of which - /// declarations were made within this context. - /// - /// Event callback code should start a new context once per element. This means - /// being ready to call this in either of two places. For elements that don't - /// include namespace declarations, the ContentHandler::startElement() callback - /// is the right place. For elements with such a declaration, it'd done in the - /// first ContentHandler::startPrefixMapping() callback. A boolean flag can be - /// used to track whether a context has been started yet. When either of those - /// methods is called, it checks the flag to see if a new context needs to be - /// started. If so, it starts the context and sets the flag. After - /// ContentHandler::startElement() does that, it always clears the flag. - /// - /// Normally, SAX drivers would push a new context at the beginning of each - /// XML element. Then they perform a first pass over the attributes to process - /// all namespace declarations, making ContentHandler::startPrefixMapping() callbacks. - /// Then a second pass is made, to determine the namespace-qualified names for - /// all attributes and for the element name. Finally all the information for - /// the ContentHandler::startElement() callback is available, so it can then - /// be made. - /// - /// The Namespace support object always starts with a base context already in - /// force: in this context, only the "xml" prefix is declared. - - void popContext(); - /// Revert to the previous Namespace context. - /// - /// Normally, you should pop the context at the end of each XML element. After - /// popping the context, all Namespace prefix mappings that were previously - /// in force are restored. - /// - /// You must not attempt to declare additional Namespace prefixes after popping - /// a context, unless you push another context first. - - bool processName(const XMLString& qname, XMLString& namespaceURI, XMLString& localName, bool isAttribute) const; - /// Process a raw XML 1.0 name. - /// This method processes a raw XML 1.0 name in the current context - /// by removing the prefix and looking it up among the - /// prefixes currently declared. The result will be returned in - /// namespaceURI and localName. - /// If the raw name has a prefix that has not been declared, then the return - /// value will be false, otherwise true. - /// - /// Note that attribute names are processed differently than element names: - /// an unprefixed element name will receive the - /// default Namespace (if any), while an unprefixed attribute name will not. - - void reset(); - /// Reset this Namespace support object for reuse. - /// - /// It is necessary to invoke this method before reusing the Namespace support - /// object for a new session. If namespace declaration URIs are to be supported, - /// that flag must also be set to a non-default value. - /// Reset this Namespace support object for reuse. - - static const XMLString XML_NAMESPACE; - static const XMLString XML_NAMESPACE_PREFIX; - static const XMLString XMLNS_NAMESPACE; - static const XMLString XMLNS_NAMESPACE_PREFIX; - -private: - NamespaceSupport(const NamespaceSupport&); - NamespaceSupport& operator = (const NamespaceSupport&); - - typedef std::map Context; - typedef std::vector ContextVec; - - ContextVec _contexts; - - static const XMLString EMPTY_STRING; -}; -} } // namespace Poco::XML + class XML_API NamespaceSupport + /// Encapsulate Namespace logic for use by SAX drivers. + /// This class encapsulates the logic of Namespace processing: + /// it tracks the declarations currently in force for each context and + /// automatically processes qualified XML 1.0 names into their Namespace + /// parts; it can also be used in reverse for generating + /// XML 1.0 from Namespaces. + /// Namespace support objects are reusable, but the reset method + /// must be invoked between each session. + { + public: + using PrefixSet = std::set; + + NamespaceSupport(); + /// Creates a NamespaceSupport object. + + ~NamespaceSupport(); + /// Destroys a NamespaceSupport object. + + bool declarePrefix(const XMLString & prefix, const XMLString & namespaceURI); + /// Declare a Namespace prefix. All prefixes must be declared before they are + /// referenced. For example, a SAX driver (parser) would scan an element's attributes + /// in two passes: first for namespace declarations, then a second pass using + /// processName() to interpret prefixes against (potentially redefined) prefixes. + /// + /// This method declares a prefix in the current Namespace context; the prefix + /// will remain in force until this context is popped, unless it is shadowed + /// in a descendant context. + /// + /// To declare the default element Namespace, use the empty string as the prefix. + /// + /// Note that you must not declare a prefix after you've pushed and popped another + /// Namespace context, or treated the declarations phase as complete by processing + /// a prefixed name. + /// + /// Returns true if the prefix was legal, false otherwise. + + bool undeclarePrefix(const XMLString & prefix); + /// Remove the given namespace prefix. + + void getDeclaredPrefixes(PrefixSet & prefixes) const; + /// Return an enumeration of all prefixes declared in this context. + /// + /// The empty (default) prefix will be included in this enumeration; note that + /// this behaviour differs from that of getPrefix() and getPrefixes(). + + const XMLString & getPrefix(const XMLString & namespaceURI) const; + /// Return one of the prefixes mapped to a Namespace URI. + /// + /// If more than one prefix is currently mapped to the same URI, this method + /// will make an arbitrary selection; if you want all of the prefixes, use the + /// getPrefixes() method instead. + + bool isMapped(const XMLString & namespaceURI) const; + /// Returns true if the given namespaceURI has been mapped to a prefix, + /// false otherwise. + + void getPrefixes(PrefixSet & prefixes) const; + /// Return an enumeration of all prefixes whose declarations are active in the + /// current context. This includes declarations from parent contexts that have + /// not been overridden. + /// + /// Note: if there is a default prefix, it will not be returned in this enumeration; + /// check for the default prefix using the getURI with an argument of "". + + void getPrefixes(const XMLString & namespaceURI, PrefixSet & prefixes) const; + /// Return an enumeration of all prefixes for a given URI whose declarations + /// are active in the current context. This includes declarations from parent + /// contexts that have not been overridden. + /// + /// This method returns prefixes mapped to a specific Namespace URI. The xml: + /// prefix will be included. If you want only one prefix that's mapped to the + /// Namespace URI, and you don't care which one you get, use the getPrefix() method + /// instead. + /// + /// Note: the empty (default) prefix is never included in this enumeration; + /// to check for the presence of a default Namespace, use the getURI() method + /// with an argument of "". + + const XMLString & getURI(const XMLString & prefix) const; + /// Look up a prefix and get the currently-mapped Namespace URI. + /// + /// This method looks up the prefix in the current context. Use the empty string + /// ("") for the default Namespace. + + void pushContext(); + /// Start a new Namespace context. The new context will automatically inherit + /// the declarations of its parent context, but it will also keep track of which + /// declarations were made within this context. + /// + /// Event callback code should start a new context once per element. This means + /// being ready to call this in either of two places. For elements that don't + /// include namespace declarations, the ContentHandler::startElement() callback + /// is the right place. For elements with such a declaration, it'd done in the + /// first ContentHandler::startPrefixMapping() callback. A boolean flag can be + /// used to track whether a context has been started yet. When either of those + /// methods is called, it checks the flag to see if a new context needs to be + /// started. If so, it starts the context and sets the flag. After + /// ContentHandler::startElement() does that, it always clears the flag. + /// + /// Normally, SAX drivers would push a new context at the beginning of each + /// XML element. Then they perform a first pass over the attributes to process + /// all namespace declarations, making ContentHandler::startPrefixMapping() callbacks. + /// Then a second pass is made, to determine the namespace-qualified names for + /// all attributes and for the element name. Finally all the information for + /// the ContentHandler::startElement() callback is available, so it can then + /// be made. + /// + /// The Namespace support object always starts with a base context already in + /// force: in this context, only the "xml" prefix is declared. + + void popContext(); + /// Revert to the previous Namespace context. + /// + /// Normally, you should pop the context at the end of each XML element. After + /// popping the context, all Namespace prefix mappings that were previously + /// in force are restored. + /// + /// You must not attempt to declare additional Namespace prefixes after popping + /// a context, unless you push another context first. + + bool processName(const XMLString & qname, XMLString & namespaceURI, XMLString & localName, bool isAttribute) const; + /// Process a raw XML 1.0 name. + /// This method processes a raw XML 1.0 name in the current context + /// by removing the prefix and looking it up among the + /// prefixes currently declared. The result will be returned in + /// namespaceURI and localName. + /// If the raw name has a prefix that has not been declared, then the return + /// value will be false, otherwise true. + /// + /// Note that attribute names are processed differently than element names: + /// an unprefixed element name will receive the + /// default Namespace (if any), while an unprefixed attribute name will not. + + void reset(); + /// Reset this Namespace support object for reuse. + /// + /// It is necessary to invoke this method before reusing the Namespace support + /// object for a new session. If namespace declaration URIs are to be supported, + /// that flag must also be set to a non-default value. + /// Reset this Namespace support object for reuse. + + static const XMLString XML_NAMESPACE; + static const XMLString XML_NAMESPACE_PREFIX; + static const XMLString XMLNS_NAMESPACE; + static const XMLString XMLNS_NAMESPACE_PREFIX; + + private: + NamespaceSupport(const NamespaceSupport &); + NamespaceSupport & operator=(const NamespaceSupport &); + + typedef std::map Context; + typedef std::vector ContextVec; + + ContextVec _contexts; + + static const XMLString EMPTY_STRING; + }; + + +} +} // namespace Poco::XML #endif // SAX_NamespaceSupport_INCLUDED diff --git a/base/poco/XML/include/Poco/SAX/SAXException.h b/base/poco/XML/include/Poco/SAX/SAXException.h index e1f9cae8e4a..ab7159757bb 100644 --- a/base/poco/XML/include/Poco/SAX/SAXException.h +++ b/base/poco/XML/include/Poco/SAX/SAXException.h @@ -23,154 +23,165 @@ #include "Poco/XML/XMLString.h" -namespace Poco { -namespace XML { - - -POCO_DECLARE_EXCEPTION(XML_API, SAXException, XMLException) - /// The base class for all SAX-related exceptions like SAXParseException, - /// SAXNotRecognizedException or SAXNotSupportedException. - /// - /// This class can contain basic error or warning information from either the XML parser - /// or the application: a parser writer or application writer can subclass it to provide - /// additional functionality. SAX handlers may throw this exception or any exception subclassed - /// from it. - /// - /// If the application needs to pass through other types of exceptions, it must wrap those exceptions - /// in a SAXException or an exception derived from a SAXException. - /// - /// If the parser or application needs to include information about a specific location in an XML - /// document, it should use the SAXParseException subclass. - - -POCO_DECLARE_EXCEPTION(XML_API, SAXNotRecognizedException, SAXException) - /// Exception class for an unrecognized identifier. - /// - /// An XMLReader will throw this exception when it finds an unrecognized feature or property - /// identifier; SAX applications and extensions may use this class for other, similar purposes. - - -POCO_DECLARE_EXCEPTION(XML_API, SAXNotSupportedException, SAXException) - /// Exception class for an unsupported operation. - /// - /// An XMLReader will throw this exception when it recognizes a feature or property identifier, - /// but cannot perform the requested operation (setting a state or value). Other SAX2 applications - /// and extensions may use this class for similar purposes. - - -class Locator; - - -class XML_API SAXParseException: public SAXException - /// Encapsulate an XML parse error or warning. - /// - /// This exception may include information for locating the error in the original XML document, - /// as if it came from a Locator object. Note that although the application will receive a - /// SAXParseException as the argument to the handlers in the ErrorHandler interface, the application - /// is not actually required to throw the exception; instead, it can simply read the information in it - /// and take a different action. - /// - /// Since this exception is a subclass of SAXException, it inherits the ability to wrap another exception. +namespace Poco { -public: - SAXParseException(const std::string& msg, const Locator& loc); - /// Create a new SAXParseException from a message and a Locator. - - SAXParseException(const std::string& msg, const Locator& loc, const Poco::Exception& exc); - /// Wrap an existing exception in a SAXParseException. - - SAXParseException(const std::string& msg, const XMLString& publicId, const XMLString& systemId, int lineNumber, int columnNumber); - /// Create a new SAXParseException with an embedded exception. - /// - /// This constructor is most useful for parser writers. - /// All parameters except the message are as if they were provided by a Locator. - /// For example, if the system identifier is a URL (including relative filename), - /// the caller must resolve it fully before creating the exception. - - SAXParseException(const std::string& msg, const XMLString& publicId, const XMLString& systemId, int lineNumber, int columnNumber, const Poco::Exception& exc); - /// Create a new SAXParseException. - /// - /// This constructor is most useful for parser writers. - /// All parameters except the message are as if they were provided by a Locator. - /// For example, if the system identifier is a URL (including relative filename), - /// the caller must resolve it fully before creating the exception. - - SAXParseException(const SAXParseException& exc); - /// Creates a new SAXParseException from another one. - - ~SAXParseException() noexcept; - /// Destroy the exception. - - SAXParseException& operator = (const SAXParseException& exc); - /// Assignment operator. - - const char* name() const noexcept; - /// Returns a static string describing the exception. - - const char* className() const noexcept; - /// Returns the name of the exception class. - - Poco::Exception* clone() const; - /// Creates an exact copy of the exception. - - void rethrow() const; - /// (Re)Throws the exception. - - const XMLString& getPublicId() const; - /// Get the public identifier of the entity where the exception occurred. - - const XMLString& getSystemId() const; - /// Get the system identifier of the entity where the exception occurred. - - int getLineNumber() const; - /// The line number of the end of the text where the exception occurred. - /// The first line is line 1. - - int getColumnNumber() const; - /// The column number of the end of the text where the exception occurred. - /// The first column in a line is position 1. - -protected: - static std::string buildMessage(const std::string& msg, const XMLString& publicId, const XMLString& systemId, int lineNumber, int columnNumber); - -private: - SAXParseException(); - - XMLString _publicId; - XMLString _systemId; - int _lineNumber; - int _columnNumber; -}; - - -// -// inlines -// -inline const XMLString& SAXParseException::getPublicId() const +namespace XML { - return _publicId; + + + POCO_DECLARE_EXCEPTION(XML_API, SAXException, XMLException) + /// The base class for all SAX-related exceptions like SAXParseException, + /// SAXNotRecognizedException or SAXNotSupportedException. + /// + /// This class can contain basic error or warning information from either the XML parser + /// or the application: a parser writer or application writer can subclass it to provide + /// additional functionality. SAX handlers may throw this exception or any exception subclassed + /// from it. + /// + /// If the application needs to pass through other types of exceptions, it must wrap those exceptions + /// in a SAXException or an exception derived from a SAXException. + /// + /// If the parser or application needs to include information about a specific location in an XML + /// document, it should use the SAXParseException subclass. + + + POCO_DECLARE_EXCEPTION(XML_API, SAXNotRecognizedException, SAXException) + /// Exception class for an unrecognized identifier. + /// + /// An XMLReader will throw this exception when it finds an unrecognized feature or property + /// identifier; SAX applications and extensions may use this class for other, similar purposes. + + + POCO_DECLARE_EXCEPTION(XML_API, SAXNotSupportedException, SAXException) + /// Exception class for an unsupported operation. + /// + /// An XMLReader will throw this exception when it recognizes a feature or property identifier, + /// but cannot perform the requested operation (setting a state or value). Other SAX2 applications + /// and extensions may use this class for similar purposes. + + + class Locator; + + + class XML_API SAXParseException : public SAXException + /// Encapsulate an XML parse error or warning. + /// + /// This exception may include information for locating the error in the original XML document, + /// as if it came from a Locator object. Note that although the application will receive a + /// SAXParseException as the argument to the handlers in the ErrorHandler interface, the application + /// is not actually required to throw the exception; instead, it can simply read the information in it + /// and take a different action. + /// + /// Since this exception is a subclass of SAXException, it inherits the ability to wrap another exception. + { + public: + SAXParseException(const std::string & msg, const Locator & loc); + /// Create a new SAXParseException from a message and a Locator. + + SAXParseException(const std::string & msg, const Locator & loc, const Poco::Exception & exc); + /// Wrap an existing exception in a SAXParseException. + + SAXParseException( + const std::string & msg, const XMLString & publicId, const XMLString & systemId, int lineNumber, int columnNumber); + /// Create a new SAXParseException with an embedded exception. + /// + /// This constructor is most useful for parser writers. + /// All parameters except the message are as if they were provided by a Locator. + /// For example, if the system identifier is a URL (including relative filename), + /// the caller must resolve it fully before creating the exception. + + SAXParseException( + const std::string & msg, + const XMLString & publicId, + const XMLString & systemId, + int lineNumber, + int columnNumber, + const Poco::Exception & exc); + /// Create a new SAXParseException. + /// + /// This constructor is most useful for parser writers. + /// All parameters except the message are as if they were provided by a Locator. + /// For example, if the system identifier is a URL (including relative filename), + /// the caller must resolve it fully before creating the exception. + + SAXParseException(const SAXParseException & exc); + /// Creates a new SAXParseException from another one. + + ~SAXParseException() noexcept; + /// Destroy the exception. + + SAXParseException & operator=(const SAXParseException & exc); + /// Assignment operator. + + const char * name() const noexcept; + /// Returns a static string describing the exception. + + const char * className() const noexcept; + /// Returns the name of the exception class. + + Poco::Exception * clone() const; + /// Creates an exact copy of the exception. + + void rethrow() const; + /// (Re)Throws the exception. + + const XMLString & getPublicId() const; + /// Get the public identifier of the entity where the exception occurred. + + const XMLString & getSystemId() const; + /// Get the system identifier of the entity where the exception occurred. + + int getLineNumber() const; + /// The line number of the end of the text where the exception occurred. + /// The first line is line 1. + + int getColumnNumber() const; + /// The column number of the end of the text where the exception occurred. + /// The first column in a line is position 1. + + protected: + static std::string + buildMessage(const std::string & msg, const XMLString & publicId, const XMLString & systemId, int lineNumber, int columnNumber); + + private: + SAXParseException(); + + XMLString _publicId; + XMLString _systemId; + int _lineNumber; + int _columnNumber; + }; + + + // + // inlines + // + inline const XMLString & SAXParseException::getPublicId() const + { + return _publicId; + } + + + inline const XMLString & SAXParseException::getSystemId() const + { + return _systemId; + } + + + inline int SAXParseException::getLineNumber() const + { + return _lineNumber; + } + + + inline int SAXParseException::getColumnNumber() const + { + return _columnNumber; + } + + } - - -inline const XMLString& SAXParseException::getSystemId() const -{ - return _systemId; -} - - -inline int SAXParseException::getLineNumber() const -{ - return _lineNumber; -} - - -inline int SAXParseException::getColumnNumber() const -{ - return _columnNumber; -} - - -} } // namespace Poco::XML +} // namespace Poco::XML #endif // SAX_SAXException_INCLUDED diff --git a/base/poco/XML/include/Poco/SAX/SAXParser.h b/base/poco/XML/include/Poco/SAX/SAXParser.h index 2fefc67021a..88dc7cfd036 100644 --- a/base/poco/XML/include/Poco/SAX/SAXParser.h +++ b/base/poco/XML/include/Poco/SAX/SAXParser.h @@ -18,96 +18,99 @@ #define SAX_SAXParser_INCLUDED -#include "Poco/XML/XML.h" #include "Poco/SAX/XMLReader.h" #include "Poco/XML/ParserEngine.h" +#include "Poco/XML/XML.h" -namespace Poco { -namespace XML { - - -class XML_API SAXParser: public XMLReader - /// This class provides a SAX2 (Simple API for XML) interface to expat, - /// the XML parser toolkit. - /// The following SAX2 features and properties are supported: - /// * http://xml.org/sax/features/external-general-entities - /// * http://xml.org/sax/features/external-parameter-entities - /// * http://xml.org/sax/features/namespaces - /// * http://xml.org/sax/features/namespace-prefixes - /// * http://xml.org/sax/properties/lexical-handler - /// * http://xml.org/sax/properties/declaration-handler - /// - /// The following proprietary extensions are supported: - /// * http://www.appinf.com/features/enable-partial-reads -- - /// see ParserEngine::setEnablePartialReads() - /// * http://www.appinf.com/properties/bla-maximum-amplification - /// see ParserEngine::setBillionLaughsAttackProtectionMaximumAmplification(); - /// argument must be a float >= 1.0 formatted as string; - /// property is set-only. - /// * http://www.appinf.com/properties/bla-activation-threshold - /// see ParserEngine::setBillionLaughsAttackProtectionActivationThreshold(); - /// argument must be a 64-bit unsigned integer formatted as string; - /// property is set-only. +namespace Poco +{ +namespace XML { -public: - SAXParser(); - /// Creates an SAXParser. - - SAXParser(const XMLString& encoding); - /// Creates an SAXParser with the given encoding. - - ~SAXParser(); - /// Destroys the SAXParser. - - void setEncoding(const XMLString& encoding); - /// Sets the encoding used by the parser if no - /// encoding is specified in the XML document. - - const XMLString& getEncoding() const; - /// Returns the name of the encoding used by - /// the parser if no encoding is specified in - /// the XML document. - - void addEncoding(const XMLString& name, Poco::TextEncoding* pEncoding); - /// Adds an encoding to the parser. Does not take ownership of the pointer! - - /// XMLReader - void setEntityResolver(EntityResolver* pResolver); - EntityResolver* getEntityResolver() const; - void setDTDHandler(DTDHandler* pDTDHandler); - DTDHandler* getDTDHandler() const; - void setContentHandler(ContentHandler* pContentHandler); - ContentHandler* getContentHandler() const; - void setErrorHandler(ErrorHandler* pErrorHandler); - ErrorHandler* getErrorHandler() const; - void setFeature(const XMLString& featureId, bool state); - bool getFeature(const XMLString& featureId) const; - void setProperty(const XMLString& propertyId, const XMLString& value); - void setProperty(const XMLString& propertyId, void* value); - void* getProperty(const XMLString& propertyId) const; - void parse(InputSource* pSource); - void parse(const XMLString& systemId); - void parseMemoryNP(const char* xml, std::size_t size); - - /// Extensions - void parseString(const std::string& xml); - - static const XMLString FEATURE_PARTIAL_READS; - static const XMLString PROPERTY_BLA_MAXIMUM_AMPLIFICATION; - static const XMLString PROPERTY_BLA_ACTIVATION_THRESHOLD; - -protected: - void setupParse(); - -private: - ParserEngine _engine; - bool _namespaces; - bool _namespacePrefixes; -}; -} } // namespace Poco::XML + class XML_API SAXParser : public XMLReader + /// This class provides a SAX2 (Simple API for XML) interface to expat, + /// the XML parser toolkit. + /// The following SAX2 features and properties are supported: + /// * http://xml.org/sax/features/external-general-entities + /// * http://xml.org/sax/features/external-parameter-entities + /// * http://xml.org/sax/features/namespaces + /// * http://xml.org/sax/features/namespace-prefixes + /// * http://xml.org/sax/properties/lexical-handler + /// * http://xml.org/sax/properties/declaration-handler + /// + /// The following proprietary extensions are supported: + /// * http://www.appinf.com/features/enable-partial-reads -- + /// see ParserEngine::setEnablePartialReads() + /// * http://www.appinf.com/properties/bla-maximum-amplification + /// see ParserEngine::setBillionLaughsAttackProtectionMaximumAmplification(); + /// argument must be a float >= 1.0 formatted as string; + /// property is set-only. + /// * http://www.appinf.com/properties/bla-activation-threshold + /// see ParserEngine::setBillionLaughsAttackProtectionActivationThreshold(); + /// argument must be a 64-bit unsigned integer formatted as string; + /// property is set-only. + { + public: + SAXParser(); + /// Creates an SAXParser. + + SAXParser(const XMLString & encoding); + /// Creates an SAXParser with the given encoding. + + ~SAXParser(); + /// Destroys the SAXParser. + + void setEncoding(const XMLString & encoding); + /// Sets the encoding used by the parser if no + /// encoding is specified in the XML document. + + const XMLString & getEncoding() const; + /// Returns the name of the encoding used by + /// the parser if no encoding is specified in + /// the XML document. + + void addEncoding(const XMLString & name, Poco::TextEncoding * pEncoding); + /// Adds an encoding to the parser. Does not take ownership of the pointer! + + /// XMLReader + void setEntityResolver(EntityResolver * pResolver); + EntityResolver * getEntityResolver() const; + void setDTDHandler(DTDHandler * pDTDHandler); + DTDHandler * getDTDHandler() const; + void setContentHandler(ContentHandler * pContentHandler); + ContentHandler * getContentHandler() const; + void setErrorHandler(ErrorHandler * pErrorHandler); + ErrorHandler * getErrorHandler() const; + void setFeature(const XMLString & featureId, bool state); + bool getFeature(const XMLString & featureId) const; + void setProperty(const XMLString & propertyId, const XMLString & value); + void setProperty(const XMLString & propertyId, void * value); + void * getProperty(const XMLString & propertyId) const; + void parse(InputSource * pSource); + void parse(const XMLString & systemId); + void parseMemoryNP(const char * xml, std::size_t size); + + /// Extensions + void parseString(const std::string & xml); + + static const XMLString FEATURE_PARTIAL_READS; + static const XMLString PROPERTY_BLA_MAXIMUM_AMPLIFICATION; + static const XMLString PROPERTY_BLA_ACTIVATION_THRESHOLD; + + protected: + void setupParse(); + + private: + ParserEngine _engine; + bool _namespaces; + bool _namespacePrefixes; + }; + + +} +} // namespace Poco::XML #endif // SAX_SAXParser_INCLUDED diff --git a/base/poco/XML/include/Poco/SAX/WhitespaceFilter.h b/base/poco/XML/include/Poco/SAX/WhitespaceFilter.h index f4f08bc0f36..9a939f9a0dd 100644 --- a/base/poco/XML/include/Poco/SAX/WhitespaceFilter.h +++ b/base/poco/XML/include/Poco/SAX/WhitespaceFilter.h @@ -18,64 +18,67 @@ #define SAX_WhitespaceFilter_INCLUDED -#include "Poco/XML/XML.h" -#include "Poco/SAX/XMLFilterImpl.h" #include "Poco/SAX/LexicalHandler.h" +#include "Poco/SAX/XMLFilterImpl.h" +#include "Poco/XML/XML.h" -namespace Poco { -namespace XML { - - -class XML_API WhitespaceFilter: public XMLFilterImpl, public LexicalHandler - /// This implementation of the SAX2 XMLFilter interface - /// filters all whitespace-only character data element - /// content. +namespace Poco +{ +namespace XML { -public: - WhitespaceFilter(); - /// Creates the WhitespaceFilter, with no parent. - - WhitespaceFilter(XMLReader* pReader); - /// Creates the WhitespaceFilter with the specified parent. - - ~WhitespaceFilter(); - /// Destroys the WhitespaceFilter. - - // XMLReader - void setProperty(const XMLString& propertyId, const XMLString& value); - void setProperty(const XMLString& propertyId, void* value); - void* getProperty(const XMLString& propertyId) const; - - // ContentHandler - void startDocument(); - void endDocument(); - void startElement(const XMLString& uri, const XMLString& localName, const XMLString& qname, const Attributes& attrList); - void endElement(const XMLString& uri, const XMLString& localName, const XMLString& qname); - void characters(const XMLChar ch[], int start, int length); - void ignorableWhitespace(const XMLChar ch[], int start, int length); - void processingInstruction(const XMLString& target, const XMLString& data); - - // LexicalHandler - void startDTD(const XMLString& name, const XMLString& publicId, const XMLString& systemId); - void endDTD(); - void startEntity(const XMLString& name); - void endEntity(const XMLString& name); - void startCDATA(); - void endCDATA(); - void comment(const XMLChar ch[], int start, int length); - -protected: - void setupParse(); - -private: - LexicalHandler* _pLexicalHandler; - XMLString _data; - bool _filter; -}; -} } // namespace Poco::XML + class XML_API WhitespaceFilter : public XMLFilterImpl, public LexicalHandler + /// This implementation of the SAX2 XMLFilter interface + /// filters all whitespace-only character data element + /// content. + { + public: + WhitespaceFilter(); + /// Creates the WhitespaceFilter, with no parent. + + WhitespaceFilter(XMLReader * pReader); + /// Creates the WhitespaceFilter with the specified parent. + + ~WhitespaceFilter(); + /// Destroys the WhitespaceFilter. + + // XMLReader + void setProperty(const XMLString & propertyId, const XMLString & value); + void setProperty(const XMLString & propertyId, void * value); + void * getProperty(const XMLString & propertyId) const; + + // ContentHandler + void startDocument(); + void endDocument(); + void startElement(const XMLString & uri, const XMLString & localName, const XMLString & qname, const Attributes & attrList); + void endElement(const XMLString & uri, const XMLString & localName, const XMLString & qname); + void characters(const XMLChar ch[], int start, int length); + void ignorableWhitespace(const XMLChar ch[], int start, int length); + void processingInstruction(const XMLString & target, const XMLString & data); + + // LexicalHandler + void startDTD(const XMLString & name, const XMLString & publicId, const XMLString & systemId); + void endDTD(); + void startEntity(const XMLString & name); + void endEntity(const XMLString & name); + void startCDATA(); + void endCDATA(); + void comment(const XMLChar ch[], int start, int length); + + protected: + void setupParse(); + + private: + LexicalHandler * _pLexicalHandler; + XMLString _data; + bool _filter; + }; + + +} +} // namespace Poco::XML #endif // SAX_WhitespaceFilter_INCLUDED diff --git a/base/poco/XML/include/Poco/SAX/XMLFilter.h b/base/poco/XML/include/Poco/SAX/XMLFilter.h index 0bc2e965e94..27d073f8759 100644 --- a/base/poco/XML/include/Poco/SAX/XMLFilter.h +++ b/base/poco/XML/include/Poco/SAX/XMLFilter.h @@ -18,44 +18,47 @@ #define SAX_XMLFilter_INCLUDED -#include "Poco/XML/XML.h" #include "Poco/SAX/XMLReader.h" +#include "Poco/XML/XML.h" -namespace Poco { -namespace XML { - - -class XML_API XMLFilter: public XMLReader - /// Interface for an XML filter. - /// - /// An XML filter is like an XML reader, except that it obtains its events from another XML reader - /// rather than a primary source like an XML document or database. Filters can modify a stream of - /// events as they pass on to the final application. - /// - /// The XMLFilterImpl helper class provides a convenient base for creating SAX2 filters, by passing on - /// all EntityResolver, DTDHandler, ContentHandler and ErrorHandler events automatically. +namespace Poco +{ +namespace XML { -public: - virtual XMLReader* getParent() const = 0; - /// Set the parent reader. - /// - /// This method allows the application to link the filter to a parent reader (which may be another - /// filter). The argument may not be null. - - virtual void setParent(XMLReader* pParent) = 0; - /// Get the parent reader. - /// - /// This method allows the application to query the parent reader (which may be another filter). - /// It is generally a bad idea to perform any operations on the parent reader directly: they should - /// all pass through this filter. - -protected: - virtual ~XMLFilter(); -}; -} } // namespace Poco::XML + class XML_API XMLFilter : public XMLReader + /// Interface for an XML filter. + /// + /// An XML filter is like an XML reader, except that it obtains its events from another XML reader + /// rather than a primary source like an XML document or database. Filters can modify a stream of + /// events as they pass on to the final application. + /// + /// The XMLFilterImpl helper class provides a convenient base for creating SAX2 filters, by passing on + /// all EntityResolver, DTDHandler, ContentHandler and ErrorHandler events automatically. + { + public: + virtual XMLReader * getParent() const = 0; + /// Set the parent reader. + /// + /// This method allows the application to link the filter to a parent reader (which may be another + /// filter). The argument may not be null. + + virtual void setParent(XMLReader * pParent) = 0; + /// Get the parent reader. + /// + /// This method allows the application to query the parent reader (which may be another filter). + /// It is generally a bad idea to perform any operations on the parent reader directly: they should + /// all pass through this filter. + + protected: + virtual ~XMLFilter(); + }; + + +} +} // namespace Poco::XML #endif // SAX_XMLFilter_INCLUDED diff --git a/base/poco/XML/include/Poco/SAX/XMLFilterImpl.h b/base/poco/XML/include/Poco/SAX/XMLFilterImpl.h index 33c049c7b27..3baaf4e58ae 100644 --- a/base/poco/XML/include/Poco/SAX/XMLFilterImpl.h +++ b/base/poco/XML/include/Poco/SAX/XMLFilterImpl.h @@ -18,115 +18,119 @@ #define SAX_XMLFilterImpl_INCLUDED -#include "Poco/XML/XML.h" -#include "Poco/SAX/XMLFilter.h" -#include "Poco/SAX/EntityResolver.h" -#include "Poco/SAX/DTDHandler.h" #include "Poco/SAX/ContentHandler.h" +#include "Poco/SAX/DTDHandler.h" +#include "Poco/SAX/EntityResolver.h" #include "Poco/SAX/ErrorHandler.h" +#include "Poco/SAX/XMLFilter.h" +#include "Poco/XML/XML.h" -namespace Poco { -namespace XML { - - -class XML_API XMLFilterImpl: public XMLFilter, public EntityResolver, public DTDHandler, public ContentHandler, public ErrorHandler - /// Base class for deriving an XML filter. - /// - /// This class is designed to sit between an XMLReader and the client application's event - /// handlers. By default, it does nothing but pass requests up to the reader and events on to - /// the handlers unmodified, but subclasses can override specific methods to modify the event - /// stream or the configuration requests as they pass through. +namespace Poco { -public: - XMLFilterImpl(); - /// Construct an empty XML filter, with no parent. - /// - /// This filter will have no parent: you must assign a parent before you start a parse or do any - /// configuration with setFeature or setProperty, unless you use this as a pure event consumer rather - /// than as an XMLReader. - - XMLFilterImpl(XMLReader* pParent); - /// Construct an XML filter with the specified parent. - - ~XMLFilterImpl(); - /// Destroys the XMLFilterImpl. - - // XMLFilter - XMLReader* getParent() const; - void setParent(XMLReader* pParent); - - // XMLReader - void setEntityResolver(EntityResolver* pResolver); - EntityResolver* getEntityResolver() const; - void setDTDHandler(DTDHandler* pDTDHandler); - DTDHandler* getDTDHandler() const; - void setContentHandler(ContentHandler* pContentHandler); - ContentHandler* getContentHandler() const; - void setErrorHandler(ErrorHandler* pErrorHandler); - ErrorHandler* getErrorHandler() const; - void setFeature(const XMLString& featureId, bool state); - bool getFeature(const XMLString& featureId) const; - void setProperty(const XMLString& propertyId, const XMLString& value); - void setProperty(const XMLString& propertyId, void* value); - void* getProperty(const XMLString& propertyId) const; - void parse(InputSource* pSource); - void parse(const XMLString& systemId); - void parseMemoryNP(const char* xml, std::size_t size); - - // EntityResolver - InputSource* resolveEntity(const XMLString* publicId, const XMLString& systemId); - void releaseInputSource(InputSource* pSource); - - // DTDHandler - void notationDecl(const XMLString& name, const XMLString* publicId, const XMLString* systemId); - void unparsedEntityDecl(const XMLString& name, const XMLString* publicId, const XMLString& systemId, const XMLString& notationName); - - // ContentHandler - void setDocumentLocator(const Locator* loc); - void startDocument(); - void endDocument(); - void startElement(const XMLString& uri, const XMLString& localName, const XMLString& qname, const Attributes& attrList); - void endElement(const XMLString& uri, const XMLString& localName, const XMLString& qname); - void characters(const XMLChar ch[], int start, int length); - void ignorableWhitespace(const XMLChar ch[], int start, int length); - void processingInstruction(const XMLString& target, const XMLString& data); - void startPrefixMapping(const XMLString& prefix, const XMLString& uri); - void endPrefixMapping(const XMLString& prefix); - void skippedEntity(const XMLString& prefix); - void warning(const SAXException& e); - void error(const SAXException& e); - void fatalError(const SAXException& e); - -protected: - XMLReader* parent() const; - /// Return a pointer to the parent reader. - /// Subclasses can use this method instead of - /// getParent() for better performance - this method - /// is non-virtual and implemented as inline. - - virtual void setupParse(); - /// Setup the event handlers in the parent reader. - -private: - XMLReader* _pParent; - EntityResolver* _pEntityResolver; - DTDHandler* _pDTDHandler; - ContentHandler* _pContentHandler; - ErrorHandler* _pErrorHandler; -}; - - -// -// inlines -// -inline XMLReader* XMLFilterImpl::parent() const +namespace XML { - return _pParent; + + + class XML_API XMLFilterImpl : public XMLFilter, public EntityResolver, public DTDHandler, public ContentHandler, public ErrorHandler + /// Base class for deriving an XML filter. + /// + /// This class is designed to sit between an XMLReader and the client application's event + /// handlers. By default, it does nothing but pass requests up to the reader and events on to + /// the handlers unmodified, but subclasses can override specific methods to modify the event + /// stream or the configuration requests as they pass through. + { + public: + XMLFilterImpl(); + /// Construct an empty XML filter, with no parent. + /// + /// This filter will have no parent: you must assign a parent before you start a parse or do any + /// configuration with setFeature or setProperty, unless you use this as a pure event consumer rather + /// than as an XMLReader. + + XMLFilterImpl(XMLReader * pParent); + /// Construct an XML filter with the specified parent. + + ~XMLFilterImpl(); + /// Destroys the XMLFilterImpl. + + // XMLFilter + XMLReader * getParent() const; + void setParent(XMLReader * pParent); + + // XMLReader + void setEntityResolver(EntityResolver * pResolver); + EntityResolver * getEntityResolver() const; + void setDTDHandler(DTDHandler * pDTDHandler); + DTDHandler * getDTDHandler() const; + void setContentHandler(ContentHandler * pContentHandler); + ContentHandler * getContentHandler() const; + void setErrorHandler(ErrorHandler * pErrorHandler); + ErrorHandler * getErrorHandler() const; + void setFeature(const XMLString & featureId, bool state); + bool getFeature(const XMLString & featureId) const; + void setProperty(const XMLString & propertyId, const XMLString & value); + void setProperty(const XMLString & propertyId, void * value); + void * getProperty(const XMLString & propertyId) const; + void parse(InputSource * pSource); + void parse(const XMLString & systemId); + void parseMemoryNP(const char * xml, std::size_t size); + + // EntityResolver + InputSource * resolveEntity(const XMLString * publicId, const XMLString & systemId); + void releaseInputSource(InputSource * pSource); + + // DTDHandler + void notationDecl(const XMLString & name, const XMLString * publicId, const XMLString * systemId); + void + unparsedEntityDecl(const XMLString & name, const XMLString * publicId, const XMLString & systemId, const XMLString & notationName); + + // ContentHandler + void setDocumentLocator(const Locator * loc); + void startDocument(); + void endDocument(); + void startElement(const XMLString & uri, const XMLString & localName, const XMLString & qname, const Attributes & attrList); + void endElement(const XMLString & uri, const XMLString & localName, const XMLString & qname); + void characters(const XMLChar ch[], int start, int length); + void ignorableWhitespace(const XMLChar ch[], int start, int length); + void processingInstruction(const XMLString & target, const XMLString & data); + void startPrefixMapping(const XMLString & prefix, const XMLString & uri); + void endPrefixMapping(const XMLString & prefix); + void skippedEntity(const XMLString & prefix); + void warning(const SAXException & e); + void error(const SAXException & e); + void fatalError(const SAXException & e); + + protected: + XMLReader * parent() const; + /// Return a pointer to the parent reader. + /// Subclasses can use this method instead of + /// getParent() for better performance - this method + /// is non-virtual and implemented as inline. + + virtual void setupParse(); + /// Setup the event handlers in the parent reader. + + private: + XMLReader * _pParent; + EntityResolver * _pEntityResolver; + DTDHandler * _pDTDHandler; + ContentHandler * _pContentHandler; + ErrorHandler * _pErrorHandler; + }; + + + // + // inlines + // + inline XMLReader * XMLFilterImpl::parent() const + { + return _pParent; + } + + } - - -} } // namespace Poco::XML +} // namespace Poco::XML #endif // SAX_XMLFilterImpl_INCLUDED diff --git a/base/poco/XML/include/Poco/SAX/XMLReader.h b/base/poco/XML/include/Poco/SAX/XMLReader.h index 0b1d3603233..e3e514682f3 100644 --- a/base/poco/XML/include/Poco/SAX/XMLReader.h +++ b/base/poco/XML/include/Poco/SAX/XMLReader.h @@ -22,184 +22,187 @@ #include "Poco/XML/XMLString.h" -namespace Poco { -namespace XML { - - -class EntityResolver; -class DTDHandler; -class ContentHandler; -class ErrorHandler; -class InputSource; -class LexicalHandler; -class NamespaceHandler; - - -class XML_API XMLReader - /// Interface for reading an XML document using callbacks. - /// XMLReader is the interface that an XML parser's SAX2 driver must - /// implement. This interface allows an application to set and - /// query features and properties in the parser, to register event handlers - /// for document processing, and to initiate a document parse. - /// All SAX interfaces are assumed to be synchronous: the parse methods must not - /// return until parsing is complete, and readers - /// must wait for an event-handler callback to return before reporting the next event. +namespace Poco +{ +namespace XML { -public: - virtual void setEntityResolver(EntityResolver* pResolver) = 0; - /// Allow an application to register an entity resolver. - /// - /// If the application does not register an entity resolver, the - /// XMLReader will perform its own default resolution. - /// - /// Applications may register a new or different resolver in the middle of a - /// parse, and the SAX parser must begin using the new resolver immediately. - - virtual EntityResolver* getEntityResolver() const = 0; - /// Return the current entity resolver. - - virtual void setDTDHandler(DTDHandler* pDTDHandler) = 0; - /// Allow an application to register a DTD event handler. - /// - /// If the application does not register a DTD handler, all DTD events reported by - /// the SAX parser will be silently ignored. - /// - /// Applications may register a new or different handler in the middle of a parse, - /// and the SAX parser must begin using the new handler immediately. - - virtual DTDHandler* getDTDHandler() const = 0; - /// Return the current DTD handler. - - virtual void setContentHandler(ContentHandler* pContentHandler) = 0; - /// Allow an application to register a content event handler. - /// - /// If the application does not register a content handler, all content events - /// reported by the SAX parser will be silently ignored. - /// - /// Applications may register a new or different handler in the middle of a parse, - /// and the SAX parser must begin using the new handler immediately. - - virtual ContentHandler* getContentHandler() const = 0; - /// Return the current content handler. - - virtual void setErrorHandler(ErrorHandler* pErrorHandler) = 0; - /// Allow an application to register an error event handler. - /// - /// If the application does not register an error handler, all error events reported by - /// the SAX parser will be silently ignored; however, normal processing may not continue. - /// It is highly recommended that all SAX applications implement an error handler to avoid - /// unexpected bugs. - /// - /// Applications may register a new or different handler in the middle of a parse, and the - /// SAX parser must begin using the new handler immediately. - - virtual ErrorHandler* getErrorHandler() const = 0; - /// Return the current error handler. - - virtual void setFeature(const XMLString& featureId, bool state) = 0; - /// Set the state of a feature. - /// - /// The feature name is any fully-qualified URI. It is possible for an XMLReader to - /// expose a feature value but to be unable to change the current value. Some feature - /// values may be immutable or mutable only in specific contexts, such as before, during, - /// or after a parse. - /// - /// All XMLReaders are required to support setting http://xml.org/sax/features/namespaces - /// to true and http://xml.org/sax/features/namespace-prefixes to false. - - virtual bool getFeature(const XMLString& featureId) const = 0; - /// Look up the value of a feature. - /// - /// The feature name is any fully-qualified URI. It is possible for an XMLReader - /// to recognize a feature name but temporarily be unable to return its value. - /// Some feature values may be available only in specific contexts, such as before, - /// during, or after a parse. Also, some feature values may not be programmatically - /// accessible. (In the case of an adapter for SAX1 Parser, there is no - /// implementation-independent way to expose whether the underlying parser is performing - /// validation, expanding external entities, and so forth.) - /// - /// All XMLReaders are required to recognize the - /// http://xml.org/sax/features/namespaces and the - /// http://xml.org/sax/features/namespace-prefixes feature names. - /// Implementors are free (and encouraged) to invent their own features, - /// using names built on their own URIs. - - virtual void setProperty(const XMLString& propertyId, const XMLString& value) = 0; - /// Set the value of a property. - /// - /// The property name is any fully-qualified URI. It is possible for an XMLReader - /// to recognize a property name but to be unable to change the current value. - /// Some property values may be immutable or mutable only in specific contexts, - /// such as before, during, or after a parse. - /// - /// XMLReaders are not required to recognize setting any specific property names, though a - /// core set is defined by SAX2. - /// - /// This method is also the standard mechanism for setting extended handlers. - - virtual void setProperty(const XMLString& propertyId, void* value) = 0; - /// Set the value of a property. - /// See also setProperty(const XMLString&, const XMLString&). - - virtual void* getProperty(const XMLString& propertyId) const = 0; - /// Look up the value of a property. - /// String values are returned as XMLChar* - /// The property name is any fully-qualified URI. It is possible for an XMLReader to - /// recognize a property name but temporarily be unable to return its value. Some property - /// values may be available only in specific contexts, such as before, during, or after a parse. - /// - /// XMLReaders are not required to recognize any specific property names, though an initial - /// core set is documented for SAX2. - /// - /// Implementors are free (and encouraged) to invent their own properties, using names - /// built on their own URIs. - - virtual void parse(InputSource* pSource) = 0; - /// Parse an XML document. - /// - /// The application can use this method to instruct the XML reader to begin parsing an - /// XML document from any valid input source (a character stream, a byte stream, or a URI). - /// - /// Applications may not invoke this method while a parse is in progress (they should create - /// a new XMLReader instead for each nested XML document). Once a parse is complete, an - /// application may reuse the same XMLReader object, possibly with a different input source. - /// Configuration of the XMLReader object (such as handler bindings and values established for - /// feature flags and properties) is unchanged by completion of a parse, unless the definition of that - /// aspect of the configuration explicitly specifies other behavior. (For example, feature flags or - /// properties exposing characteristics of the document being parsed.) - /// - /// During the parse, the XMLReader will provide information about the XML document through the registered - /// event handlers. - /// - /// This method is synchronous: it will not return until parsing has ended. If a client application - /// wants to terminate parsing early, it should throw an exception. - - virtual void parse(const XMLString& systemId) = 0; - /// Parse an XML document from a system identifier. - /// See also parse(InputSource*). - - virtual void parseMemoryNP(const char* xml, std::size_t size) = 0; - /// Parse an XML document from memory. - /// See also parse(InputSource*). - - // SAX Features - static const XMLString FEATURE_VALIDATION; - static const XMLString FEATURE_NAMESPACES; - static const XMLString FEATURE_NAMESPACE_PREFIXES; - static const XMLString FEATURE_EXTERNAL_GENERAL_ENTITIES; - static const XMLString FEATURE_EXTERNAL_PARAMETER_ENTITIES; - static const XMLString FEATURE_STRING_INTERNING; - - // SAX Properties - static const XMLString PROPERTY_DECLARATION_HANDLER; - static const XMLString PROPERTY_LEXICAL_HANDLER; - -protected: - virtual ~XMLReader(); -}; -} } // namespace Poco::XML + class EntityResolver; + class DTDHandler; + class ContentHandler; + class ErrorHandler; + class InputSource; + class LexicalHandler; + class NamespaceHandler; + + + class XML_API XMLReader + /// Interface for reading an XML document using callbacks. + /// XMLReader is the interface that an XML parser's SAX2 driver must + /// implement. This interface allows an application to set and + /// query features and properties in the parser, to register event handlers + /// for document processing, and to initiate a document parse. + /// All SAX interfaces are assumed to be synchronous: the parse methods must not + /// return until parsing is complete, and readers + /// must wait for an event-handler callback to return before reporting the next event. + { + public: + virtual void setEntityResolver(EntityResolver * pResolver) = 0; + /// Allow an application to register an entity resolver. + /// + /// If the application does not register an entity resolver, the + /// XMLReader will perform its own default resolution. + /// + /// Applications may register a new or different resolver in the middle of a + /// parse, and the SAX parser must begin using the new resolver immediately. + + virtual EntityResolver * getEntityResolver() const = 0; + /// Return the current entity resolver. + + virtual void setDTDHandler(DTDHandler * pDTDHandler) = 0; + /// Allow an application to register a DTD event handler. + /// + /// If the application does not register a DTD handler, all DTD events reported by + /// the SAX parser will be silently ignored. + /// + /// Applications may register a new or different handler in the middle of a parse, + /// and the SAX parser must begin using the new handler immediately. + + virtual DTDHandler * getDTDHandler() const = 0; + /// Return the current DTD handler. + + virtual void setContentHandler(ContentHandler * pContentHandler) = 0; + /// Allow an application to register a content event handler. + /// + /// If the application does not register a content handler, all content events + /// reported by the SAX parser will be silently ignored. + /// + /// Applications may register a new or different handler in the middle of a parse, + /// and the SAX parser must begin using the new handler immediately. + + virtual ContentHandler * getContentHandler() const = 0; + /// Return the current content handler. + + virtual void setErrorHandler(ErrorHandler * pErrorHandler) = 0; + /// Allow an application to register an error event handler. + /// + /// If the application does not register an error handler, all error events reported by + /// the SAX parser will be silently ignored; however, normal processing may not continue. + /// It is highly recommended that all SAX applications implement an error handler to avoid + /// unexpected bugs. + /// + /// Applications may register a new or different handler in the middle of a parse, and the + /// SAX parser must begin using the new handler immediately. + + virtual ErrorHandler * getErrorHandler() const = 0; + /// Return the current error handler. + + virtual void setFeature(const XMLString & featureId, bool state) = 0; + /// Set the state of a feature. + /// + /// The feature name is any fully-qualified URI. It is possible for an XMLReader to + /// expose a feature value but to be unable to change the current value. Some feature + /// values may be immutable or mutable only in specific contexts, such as before, during, + /// or after a parse. + /// + /// All XMLReaders are required to support setting http://xml.org/sax/features/namespaces + /// to true and http://xml.org/sax/features/namespace-prefixes to false. + + virtual bool getFeature(const XMLString & featureId) const = 0; + /// Look up the value of a feature. + /// + /// The feature name is any fully-qualified URI. It is possible for an XMLReader + /// to recognize a feature name but temporarily be unable to return its value. + /// Some feature values may be available only in specific contexts, such as before, + /// during, or after a parse. Also, some feature values may not be programmatically + /// accessible. (In the case of an adapter for SAX1 Parser, there is no + /// implementation-independent way to expose whether the underlying parser is performing + /// validation, expanding external entities, and so forth.) + /// + /// All XMLReaders are required to recognize the + /// http://xml.org/sax/features/namespaces and the + /// http://xml.org/sax/features/namespace-prefixes feature names. + /// Implementors are free (and encouraged) to invent their own features, + /// using names built on their own URIs. + + virtual void setProperty(const XMLString & propertyId, const XMLString & value) = 0; + /// Set the value of a property. + /// + /// The property name is any fully-qualified URI. It is possible for an XMLReader + /// to recognize a property name but to be unable to change the current value. + /// Some property values may be immutable or mutable only in specific contexts, + /// such as before, during, or after a parse. + /// + /// XMLReaders are not required to recognize setting any specific property names, though a + /// core set is defined by SAX2. + /// + /// This method is also the standard mechanism for setting extended handlers. + + virtual void setProperty(const XMLString & propertyId, void * value) = 0; + /// Set the value of a property. + /// See also setProperty(const XMLString&, const XMLString&). + + virtual void * getProperty(const XMLString & propertyId) const = 0; + /// Look up the value of a property. + /// String values are returned as XMLChar* + /// The property name is any fully-qualified URI. It is possible for an XMLReader to + /// recognize a property name but temporarily be unable to return its value. Some property + /// values may be available only in specific contexts, such as before, during, or after a parse. + /// + /// XMLReaders are not required to recognize any specific property names, though an initial + /// core set is documented for SAX2. + /// + /// Implementors are free (and encouraged) to invent their own properties, using names + /// built on their own URIs. + + virtual void parse(InputSource * pSource) = 0; + /// Parse an XML document. + /// + /// The application can use this method to instruct the XML reader to begin parsing an + /// XML document from any valid input source (a character stream, a byte stream, or a URI). + /// + /// Applications may not invoke this method while a parse is in progress (they should create + /// a new XMLReader instead for each nested XML document). Once a parse is complete, an + /// application may reuse the same XMLReader object, possibly with a different input source. + /// Configuration of the XMLReader object (such as handler bindings and values established for + /// feature flags and properties) is unchanged by completion of a parse, unless the definition of that + /// aspect of the configuration explicitly specifies other behavior. (For example, feature flags or + /// properties exposing characteristics of the document being parsed.) + /// + /// During the parse, the XMLReader will provide information about the XML document through the registered + /// event handlers. + /// + /// This method is synchronous: it will not return until parsing has ended. If a client application + /// wants to terminate parsing early, it should throw an exception. + + virtual void parse(const XMLString & systemId) = 0; + /// Parse an XML document from a system identifier. + /// See also parse(InputSource*). + + virtual void parseMemoryNP(const char * xml, std::size_t size) = 0; + /// Parse an XML document from memory. + /// See also parse(InputSource*). + + // SAX Features + static const XMLString FEATURE_VALIDATION; + static const XMLString FEATURE_NAMESPACES; + static const XMLString FEATURE_NAMESPACE_PREFIXES; + static const XMLString FEATURE_EXTERNAL_GENERAL_ENTITIES; + static const XMLString FEATURE_EXTERNAL_PARAMETER_ENTITIES; + static const XMLString FEATURE_STRING_INTERNING; + + // SAX Properties + static const XMLString PROPERTY_DECLARATION_HANDLER; + static const XMLString PROPERTY_LEXICAL_HANDLER; + + protected: + virtual ~XMLReader(); + }; + + +} +} // namespace Poco::XML #endif // SAX_XMLReader_INCLUDED diff --git a/base/poco/XML/include/Poco/XML/Content.h b/base/poco/XML/include/Poco/XML/Content.h index 8b2b312344f..012ac5333c9 100644 --- a/base/poco/XML/include/Poco/XML/Content.h +++ b/base/poco/XML/include/Poco/XML/Content.h @@ -21,43 +21,40 @@ #define XML_Content_INCLUDED -namespace Poco { -namespace XML { - - -struct Content - /// XML content model. C++11 enum class emulated for C++98. - /// - /// element characters whitespaces notes - /// Empty no no ignored - /// Simple no yes preserved content accumulated - /// Complex yes no ignored - /// Mixed yes yes preserved +namespace Poco +{ +namespace XML { - enum value - { - Empty, - Simple, - Complex, - Mixed - }; - - Content(value v) - : _v(v) - { - } - - operator value() const - { - return _v; - } - -private: - value _v; -}; -} } // namespace Poco::XML + struct Content + /// XML content model. C++11 enum class emulated for C++98. + /// + /// element characters whitespaces notes + /// Empty no no ignored + /// Simple no yes preserved content accumulated + /// Complex yes no ignored + /// Mixed yes yes preserved + { + enum value + { + Empty, + Simple, + Complex, + Mixed + }; + + Content(value v) : _v(v) { } + + operator value() const { return _v; } + + private: + value _v; + }; + + +} +} // namespace Poco::XML #endif // XML_Content_INCLUDED diff --git a/base/poco/XML/include/Poco/XML/Name.h b/base/poco/XML/include/Poco/XML/Name.h index beedea2fa48..040dd9b4934 100644 --- a/base/poco/XML/include/Poco/XML/Name.h +++ b/base/poco/XML/include/Poco/XML/Name.h @@ -22,123 +22,126 @@ #include "Poco/XML/XMLString.h" -namespace Poco { -namespace XML { - - -class XML_API Name - /// An XML element or attribute name, consisting of a - /// qualified name, a namespace URI and a local name. +namespace Poco { -public: - Name(); - /// Creates an empty Name. - - Name(const XMLString& qname); - /// Creates a Name from a qualified name only. - - Name(const XMLString& qname, const XMLString& namespaceURI); - /// Creates a Name from a qualified name and a namespace URI. - /// The local name is extracted from the qualified name. - - Name(const XMLString& qname, const XMLString& namespaceURI, const XMLString& localName); - /// Creates a Name from a qualified name, a namespace URI and a local name. - - Name(const Name& name); - /// Copy constructor. - - Name(Name&& name) noexcept; - /// Move constructor. - - ~Name(); - /// Destroys the name. - - Name& operator = (const Name& name); - /// Assignment operator. - - Name& operator = (Name&& name) noexcept; - /// Move assignment. - - void swap(Name& name); - /// Swaps the name with another one. - - void assign(const XMLString& qname); - /// Assigns a new value to the name. - - void assign(const XMLString& qname, const XMLString& namespaceURI); - /// Assigns new values to the name. - /// The local name is extracted from the qualified name. - - void assign(const XMLString& qname, const XMLString& namespaceURI, const XMLString& localName); - /// Assigns new values to the name. - - bool equals(const Name& name) const; - /// Returns true if both names are equal. - - bool equals(const XMLString& qname, const XMLString& namespaceURI, const XMLString& localName) const; - /// Returns true if all the name's components are equal to the given ones. - - bool equalsWeakly(const XMLString& qname, const XMLString& namespaceURI, const XMLString& localName) const; - /// Returns true if either the qnames are identical or the namespaceURIs and the localNames are identical. - - const XMLString& qname() const; - /// Returns the qualified name. - - const XMLString& namespaceURI() const; - /// Returns the namespace URI. - - const XMLString& localName() const; - /// Returns the local name. - - XMLString prefix() const; - /// Returns the namespace prefix. - - static void split(const XMLString& qname, XMLString& prefix, XMLString& localName); - /// Splits the given qualified name into its prefix and localName parts. - - static XMLString localName(const XMLString& qname); - /// Returns the local name part of the given qualified name. - - static XMLString prefix(const XMLString& qname); - /// Returns the prefix part of the given qualified name. - - static const XMLString EMPTY_NAME; - -private: - XMLString _qname; - XMLString _namespaceURI; - XMLString _localName; -}; - - -// -// inlines -// -inline const XMLString& Name::qname() const +namespace XML { - return _qname; + + + class XML_API Name + /// An XML element or attribute name, consisting of a + /// qualified name, a namespace URI and a local name. + { + public: + Name(); + /// Creates an empty Name. + + Name(const XMLString & qname); + /// Creates a Name from a qualified name only. + + Name(const XMLString & qname, const XMLString & namespaceURI); + /// Creates a Name from a qualified name and a namespace URI. + /// The local name is extracted from the qualified name. + + Name(const XMLString & qname, const XMLString & namespaceURI, const XMLString & localName); + /// Creates a Name from a qualified name, a namespace URI and a local name. + + Name(const Name & name); + /// Copy constructor. + + Name(Name && name) noexcept; + /// Move constructor. + + ~Name(); + /// Destroys the name. + + Name & operator=(const Name & name); + /// Assignment operator. + + Name & operator=(Name && name) noexcept; + /// Move assignment. + + void swap(Name & name); + /// Swaps the name with another one. + + void assign(const XMLString & qname); + /// Assigns a new value to the name. + + void assign(const XMLString & qname, const XMLString & namespaceURI); + /// Assigns new values to the name. + /// The local name is extracted from the qualified name. + + void assign(const XMLString & qname, const XMLString & namespaceURI, const XMLString & localName); + /// Assigns new values to the name. + + bool equals(const Name & name) const; + /// Returns true if both names are equal. + + bool equals(const XMLString & qname, const XMLString & namespaceURI, const XMLString & localName) const; + /// Returns true if all the name's components are equal to the given ones. + + bool equalsWeakly(const XMLString & qname, const XMLString & namespaceURI, const XMLString & localName) const; + /// Returns true if either the qnames are identical or the namespaceURIs and the localNames are identical. + + const XMLString & qname() const; + /// Returns the qualified name. + + const XMLString & namespaceURI() const; + /// Returns the namespace URI. + + const XMLString & localName() const; + /// Returns the local name. + + XMLString prefix() const; + /// Returns the namespace prefix. + + static void split(const XMLString & qname, XMLString & prefix, XMLString & localName); + /// Splits the given qualified name into its prefix and localName parts. + + static XMLString localName(const XMLString & qname); + /// Returns the local name part of the given qualified name. + + static XMLString prefix(const XMLString & qname); + /// Returns the prefix part of the given qualified name. + + static const XMLString EMPTY_NAME; + + private: + XMLString _qname; + XMLString _namespaceURI; + XMLString _localName; + }; + + + // + // inlines + // + inline const XMLString & Name::qname() const + { + return _qname; + } + + + inline const XMLString & Name::namespaceURI() const + { + return _namespaceURI; + } + + + inline const XMLString & Name::localName() const + { + return _localName; + } + + + inline void swap(Name & n1, Name & n2) + { + n1.swap(n2); + } + + } - - -inline const XMLString& Name::namespaceURI() const -{ - return _namespaceURI; -} - - -inline const XMLString& Name::localName() const -{ - return _localName; -} - - -inline void swap(Name& n1, Name& n2) -{ - n1.swap(n2); -} - - -} } // namespace Poco::XML +} // namespace Poco::XML #endif // XML_Name_INCLUDED diff --git a/base/poco/XML/include/Poco/XML/NamePool.h b/base/poco/XML/include/Poco/XML/NamePool.h index 9ffadf1af95..5e55e415cb9 100644 --- a/base/poco/XML/include/Poco/XML/NamePool.h +++ b/base/poco/XML/include/Poco/XML/NamePool.h @@ -18,66 +18,69 @@ #define XML_NamePool_INCLUDED +#include "Poco/XML/Name.h" #include "Poco/XML/XML.h" #include "Poco/XML/XMLString.h" -#include "Poco/XML/Name.h" #ifndef POCO_XML_NAMEPOOL_DEFAULT_SIZE -#define POCO_XML_NAMEPOOL_DEFAULT_SIZE 509 +# define POCO_XML_NAMEPOOL_DEFAULT_SIZE 509 #endif -namespace Poco { -namespace XML { - - -class NamePoolItem; - - -class XML_API NamePool - /// A hashtable that stores XML names consisting of an URI, a - /// local name and a qualified name. +namespace Poco +{ +namespace XML { -public: - NamePool(unsigned long size = POCO_XML_NAMEPOOL_DEFAULT_SIZE); - /// Creates a name pool with room for up to size strings. - /// - /// The given size should be a suitable prime number, - /// e.g. 251, 509, 1021 or 4093. - - const Name& insert(const XMLString& qname, const XMLString& namespaceURI, const XMLString& localName); - /// Returns a const reference to an Name for the given names. - /// Creates the Name if it does not already exist. - /// Throws a PoolOverflowException if the name pool is full. - - const Name& insert(const Name& name); - /// Returns a const reference to an Name for the given name. - /// Creates the Name if it does not already exist. - /// Throws a PoolOverflowException if the name pool is full. - - void duplicate(); - /// Increments the reference count. - - void release(); - /// Decrements the reference count and deletes the object if the reference count reaches zero. - -protected: - unsigned long hash(const XMLString& qname, const XMLString& namespaceURI, const XMLString& localName); - ~NamePool(); - -private: - NamePool(const NamePool&); - NamePool& operator = (const NamePool&); - - NamePoolItem* _pItems; - unsigned long _size; - unsigned long _salt; - int _rc; -}; -} } // namespace Poco::XML + class NamePoolItem; + + + class XML_API NamePool + /// A hashtable that stores XML names consisting of an URI, a + /// local name and a qualified name. + { + public: + NamePool(unsigned long size = POCO_XML_NAMEPOOL_DEFAULT_SIZE); + /// Creates a name pool with room for up to size strings. + /// + /// The given size should be a suitable prime number, + /// e.g. 251, 509, 1021 or 4093. + + const Name & insert(const XMLString & qname, const XMLString & namespaceURI, const XMLString & localName); + /// Returns a const reference to an Name for the given names. + /// Creates the Name if it does not already exist. + /// Throws a PoolOverflowException if the name pool is full. + + const Name & insert(const Name & name); + /// Returns a const reference to an Name for the given name. + /// Creates the Name if it does not already exist. + /// Throws a PoolOverflowException if the name pool is full. + + void duplicate(); + /// Increments the reference count. + + void release(); + /// Decrements the reference count and deletes the object if the reference count reaches zero. + + protected: + unsigned long hash(const XMLString & qname, const XMLString & namespaceURI, const XMLString & localName); + ~NamePool(); + + private: + NamePool(const NamePool &); + NamePool & operator=(const NamePool &); + + NamePoolItem * _pItems; + unsigned long _size; + unsigned long _salt; + int _rc; + }; + + +} +} // namespace Poco::XML #endif // XML_NamePool_INCLUDED diff --git a/base/poco/XML/include/Poco/XML/NamespaceStrategy.h b/base/poco/XML/include/Poco/XML/NamespaceStrategy.h index 1f27e3c23bc..f8e6fd26bb5 100644 --- a/base/poco/XML/include/Poco/XML/NamespaceStrategy.h +++ b/base/poco/XML/include/Poco/XML/NamespaceStrategy.h @@ -18,98 +18,101 @@ #define XML_NamespaceStrategy_INCLUDED +#include "Poco/SAX/AttributesImpl.h" +#include "Poco/SAX/NamespaceSupport.h" #include "Poco/XML/XML.h" #include "Poco/XML/XMLString.h" -#include "Poco/SAX/NamespaceSupport.h" -#include "Poco/SAX/AttributesImpl.h" -namespace Poco { -namespace XML { - - -class ContentHandler; - - -class XML_API NamespaceStrategy - /// This class is used by ParserEngine to handle the - /// startElement, endElement, startPrefixMapping and - /// endPrefixMapping events. +namespace Poco { -public: - virtual ~NamespaceStrategy(); - - virtual void startElement(const XMLChar* name, const XMLChar** atts, int specifiedCount, ContentHandler* pContentHandler) = 0; - /// Translate the arguments as delivered by Expat and - /// call the startElement() method of the ContentHandler. - - virtual void endElement(const XMLChar* name, ContentHandler* pContentHandler) = 0; - /// Translate the arguments as delivered by Expat and - /// call the endElement() method of the ContentHandler. - -protected: - static void splitName(const XMLChar* qname, XMLString& uri, XMLString& localName); - static void splitName(const XMLChar* qname, XMLString& uri, XMLString& localName, XMLString& prefix); - - static const XMLString NOTHING; -}; - - -class XML_API NoNamespacesStrategy: public NamespaceStrategy - /// The NamespaceStrategy implementation used if no namespaces - /// processing is requested. +namespace XML { -public: - NoNamespacesStrategy(); - ~NoNamespacesStrategy(); - - void startElement(const XMLChar* name, const XMLChar** atts, int specifiedCount, ContentHandler* pContentHandler); - void endElement(const XMLChar* name, ContentHandler* pContentHandler); - -private: - XMLString _name; - AttributesImpl _attrs; -}; -class XML_API NoNamespacePrefixesStrategy: public NamespaceStrategy - /// The NamespaceStrategy implementation used if namespaces - /// processing is requested, but prefixes are not reported. -{ -public: - NoNamespacePrefixesStrategy(); - ~NoNamespacePrefixesStrategy(); - - void startElement(const XMLChar* name, const XMLChar** atts, int specifiedCount, ContentHandler* pContentHandler); - void endElement(const XMLChar* name, ContentHandler* pContentHandler); - -private: - XMLString _uri; - XMLString _local; - AttributesImpl _attrs; -}; + class ContentHandler; -class XML_API NamespacePrefixesStrategy: public NamespaceStrategy - /// The NamespaceStrategy implementation used if namespaces - /// processing is requested and prefixes are reported. -{ -public: - NamespacePrefixesStrategy(); - ~NamespacePrefixesStrategy(); - - void startElement(const XMLChar* name, const XMLChar** atts, int specifiedCount, ContentHandler* pContentHandler); - void endElement(const XMLChar* name, ContentHandler* pContentHandler); - -private: - XMLString _uri; - XMLString _local; - XMLString _qname; - AttributesImpl _attrs; -}; + class XML_API NamespaceStrategy + /// This class is used by ParserEngine to handle the + /// startElement, endElement, startPrefixMapping and + /// endPrefixMapping events. + { + public: + virtual ~NamespaceStrategy(); + + virtual void startElement(const XMLChar * name, const XMLChar ** atts, int specifiedCount, ContentHandler * pContentHandler) = 0; + /// Translate the arguments as delivered by Expat and + /// call the startElement() method of the ContentHandler. + + virtual void endElement(const XMLChar * name, ContentHandler * pContentHandler) = 0; + /// Translate the arguments as delivered by Expat and + /// call the endElement() method of the ContentHandler. + + protected: + static void splitName(const XMLChar * qname, XMLString & uri, XMLString & localName); + static void splitName(const XMLChar * qname, XMLString & uri, XMLString & localName, XMLString & prefix); + + static const XMLString NOTHING; + }; -} } // namespace Poco::XML + class XML_API NoNamespacesStrategy : public NamespaceStrategy + /// The NamespaceStrategy implementation used if no namespaces + /// processing is requested. + { + public: + NoNamespacesStrategy(); + ~NoNamespacesStrategy(); + + void startElement(const XMLChar * name, const XMLChar ** atts, int specifiedCount, ContentHandler * pContentHandler); + void endElement(const XMLChar * name, ContentHandler * pContentHandler); + + private: + XMLString _name; + AttributesImpl _attrs; + }; + + + class XML_API NoNamespacePrefixesStrategy : public NamespaceStrategy + /// The NamespaceStrategy implementation used if namespaces + /// processing is requested, but prefixes are not reported. + { + public: + NoNamespacePrefixesStrategy(); + ~NoNamespacePrefixesStrategy(); + + void startElement(const XMLChar * name, const XMLChar ** atts, int specifiedCount, ContentHandler * pContentHandler); + void endElement(const XMLChar * name, ContentHandler * pContentHandler); + + private: + XMLString _uri; + XMLString _local; + AttributesImpl _attrs; + }; + + + class XML_API NamespacePrefixesStrategy : public NamespaceStrategy + /// The NamespaceStrategy implementation used if namespaces + /// processing is requested and prefixes are reported. + { + public: + NamespacePrefixesStrategy(); + ~NamespacePrefixesStrategy(); + + void startElement(const XMLChar * name, const XMLChar ** atts, int specifiedCount, ContentHandler * pContentHandler); + void endElement(const XMLChar * name, ContentHandler * pContentHandler); + + private: + XMLString _uri; + XMLString _local; + XMLString _qname; + AttributesImpl _attrs; + }; + + +} +} // namespace Poco::XML #endif // XML_NamespaceStrategy_INCLUDED diff --git a/base/poco/XML/include/Poco/XML/ParserEngine.h b/base/poco/XML/include/Poco/XML/ParserEngine.h index da5e19db805..0890a2ad56f 100644 --- a/base/poco/XML/include/Poco/XML/ParserEngine.h +++ b/base/poco/XML/include/Poco/XML/ParserEngine.h @@ -19,366 +19,392 @@ #include "Poco/XML/XML.h" #if defined(POCO_UNBUNDLED_EXPAT) -#include +# include #else -#include "Poco/XML/expat.h" +# include "Poco/XML/expat.h" #endif -#include "Poco/XML/XMLString.h" -#include "Poco/XML/XMLStream.h" -#include "Poco/SAX/Locator.h" -#include "Poco/TextEncoding.h" #include #include +#include "Poco/SAX/Locator.h" +#include "Poco/TextEncoding.h" +#include "Poco/XML/XMLStream.h" +#include "Poco/XML/XMLString.h" -namespace Poco { -namespace XML { - - -class InputSource; -class EntityResolver; -class DTDHandler; -class DeclHandler; -class ContentHandler; -class LexicalHandler; -class ErrorHandler; -class NamespaceStrategy; -class ContextLocator; - - -class XML_API ParserEngine: public Locator - /// This class provides an object-oriented, stream-based, - /// low-level interface to the XML Parser Toolkit (expat). - /// It is strongly recommended, that you use the - /// SAX parser classes (which are based on this - /// class) instead of this class, since they provide - /// a standardized, higher-level interface to the parser. +namespace Poco { -public: - ParserEngine(); - /// Creates the parser engine. - - ParserEngine(const XMLString& encoding); - /// Creates the parser engine and passes the encoding - /// to the underlying parser. - - ~ParserEngine(); - /// Destroys the parser. - - void setEncoding(const XMLString& encoding); - /// Sets the encoding used by expat. The encoding must be - /// set before parsing begins, otherwise it will be ignored. - - const XMLString& getEncoding() const; - /// Returns the encoding used by expat. - - void addEncoding(const XMLString& name, Poco::TextEncoding* pEncoding); - /// Adds an encoding to the parser. - - void setNamespaceStrategy(NamespaceStrategy* pStrategy); - /// Sets the NamespaceStrategy used by the parser. - /// The parser takes ownership of the strategy object - /// and deletes it when it's no longer needed. - /// The default is NoNamespacesStrategy. - - NamespaceStrategy* getNamespaceStrategy() const; - /// Returns the NamespaceStrategy currently in use. - - void setExpandInternalEntities(bool flag = true); - /// Enables/disables expansion of internal entities (enabled by - /// default). If entity expansion is disabled, internal entities - /// are reported via the default handler. - /// Must be set before parsing begins, otherwise it will be - /// ignored. - - bool getExpandInternalEntities() const; - /// Returns true if internal entities will be expanded automatically, - /// which is the default. - - void setExternalGeneralEntities(bool flag = true); - /// Enable or disable processing of external general entities. - - bool getExternalGeneralEntities() const; - /// Returns true if external general entities will be processed; false otherwise. - - void setExternalParameterEntities(bool flag = true); - /// Enable or disable processing of external parameter entities. - - bool getExternalParameterEntities() const; - /// Returns true if external parameter entities will be processed; false otherwise. - - void setEntityResolver(EntityResolver* pResolver); - /// Allow an application to register an entity resolver. - - EntityResolver* getEntityResolver() const; - /// Return the current entity resolver. - - void setDTDHandler(DTDHandler* pDTDHandler); - /// Allow an application to register a DTD event handler. - - DTDHandler* getDTDHandler() const; - /// Return the current DTD handler. - - void setDeclHandler(DeclHandler* pDeclHandler); - /// Allow an application to register a DTD declarations event handler. - - DeclHandler* getDeclHandler() const; - /// Return the current DTD declarations handler. - - void setContentHandler(ContentHandler* pContentHandler); - /// Allow an application to register a content event handler. - - ContentHandler* getContentHandler() const; - /// Return the current content handler. - - void setLexicalHandler(LexicalHandler* pLexicalHandler); - /// Allow an application to register a lexical event handler. - - LexicalHandler* getLexicalHandler() const; - /// Return the current lexical handler. - - void setErrorHandler(ErrorHandler* pErrorHandler); - /// Allow an application to register an error event handler. - - ErrorHandler* getErrorHandler() const; - /// Return the current error handler. - - void setEnablePartialReads(bool flag = true); - /// Enable or disable partial reads from the input source. - /// - /// This is useful for parsing XML from a socket stream for - /// a protocol like XMPP, where basically single elements - /// are read one at a time from the input source's stream, and - /// following elements depend upon responses sent back to - /// the peer. - /// - /// Normally, the parser always reads blocks of PARSE_BUFFER_SIZE - /// at a time, and blocks until a complete block has been read (or - /// the end of the stream has been reached). - /// This allows for efficient parsing of "complete" XML documents, - /// but fails in a case such as XMPP, where only XML fragments - /// are sent at a time. - - bool getEnablePartialReads() const; - /// Returns true if partial reads are enabled (see - /// setEnablePartialReads()), false otherwise. - - void setBillionLaughsAttackProtectionMaximumAmplification(float maximumAmplificationFactor); - /// Sets the maximum tolerated amplification factor - /// for protection against Billion Laughs Attacks. - /// - /// The amplification factor is calculated as: - /// amplification := (direct + indirect) / direct - /// while parsing, whereas: - /// - direct is the number of bytes read from the primary document in parsing and - /// - indirect is the number of bytes added by expanding entities and reading of - /// external DTD files, combined. - /// - /// maximumAmplificationFactor must be non-NaN and greater than or equal to 1.0. - /// - /// Requires an underlying Expat version >= 2.4.0. - - void setBillionLaughsAttackProtectionActivationThreshold(Poco::UInt64 activationThresholdBytes); - /// Sets number of output bytes (including amplification from entity expansion and reading DTD files) - /// needed to activate protection against Billion Laughs Attacks. - /// - /// Defaults to 8 MiB. - /// - /// Requires an underlying Expat version >= 2.4.0. - - void parse(InputSource* pInputSource); - /// Parse an XML document from the given InputSource. - - void parse(const char* pBuffer, std::size_t size); - /// Parses an XML document from the given buffer. - - // Locator - XMLString getPublicId() const; - /// Return the public identifier for the current document event. - - XMLString getSystemId() const; - /// Return the system identifier for the current document event. - - int getLineNumber() const; - /// Return the line number where the current document event ends. - - int getColumnNumber() const; - /// Return the column number where the current document event ends. - -protected: - void init(); - /// initializes expat - - void parseByteInputStream(XMLByteInputStream& istr); - /// Parses an entity from the given stream. - - void parseCharInputStream(XMLCharInputStream& istr); - /// Parses an entity from the given stream. - - std::streamsize readBytes(XMLByteInputStream& istr, char* pBuffer, std::streamsize bufferSize); - /// Reads at most bufferSize bytes from the given stream into the given buffer. - - std::streamsize readChars(XMLCharInputStream& istr, XMLChar* pBuffer, std::streamsize bufferSize); - /// Reads at most bufferSize chars from the given stream into the given buffer. - - void handleError(int errorNo); - /// Throws an XMLException with a message corresponding - /// to the given Expat error code. - - void parseExternal(XML_Parser extParser, InputSource* pInputSource); - /// Parse an XML document from the given InputSource. - - void parseExternalByteInputStream(XML_Parser extParser, XMLByteInputStream& istr); - /// Parses an external entity from the given stream, with a separate parser. - - void parseExternalCharInputStream(XML_Parser extParser, XMLCharInputStream& istr); - /// Parses an external entity from the given stream, with a separate parser. - - void pushContext(XML_Parser parser, InputSource* pInputSource); - /// Pushes a new entry to the context stack. - - void popContext(); - /// Pops the top-most entry from the context stack. - - void resetContext(); - /// Resets and clears the context stack. - - const Locator& locator() const; - /// Returns a locator denoting the current parse location. - - // expat handler procedures - static void handleStartElement(void* userData, const XML_Char* name, const XML_Char** atts); - static void handleEndElement(void* userData, const XML_Char* name); - static void handleCharacterData(void* userData, const XML_Char* s, int len); - static void handleProcessingInstruction(void* userData, const XML_Char* target, const XML_Char* data); - static void handleDefault(void* userData, const XML_Char* s, int len); - static void handleUnparsedEntityDecl(void* userData, const XML_Char* entityName, const XML_Char* base, const XML_Char* systemId, const XML_Char* publicId, const XML_Char* notationName); - static void handleNotationDecl(void* userData, const XML_Char* notationName, const XML_Char* base, const XML_Char* systemId, const XML_Char* publicId); - static int handleExternalEntityRef(XML_Parser parser, const XML_Char* openEntityNames, const XML_Char* base, const XML_Char* systemId, const XML_Char* publicId); - static int handleUnknownEncoding(void* encodingHandlerData, const XML_Char* name, XML_Encoding* info); - static void handleComment(void* userData, const XML_Char* data); - static void handleStartCdataSection(void* userData); - static void handleEndCdataSection(void* userData); - static void handleStartNamespaceDecl(void* userData, const XML_Char* prefix, const XML_Char* uri); - static void handleEndNamespaceDecl(void* userData, const XML_Char* prefix); - static void handleStartDoctypeDecl(void* userData, const XML_Char* doctypeName, const XML_Char *systemId, const XML_Char* publicId, int hasInternalSubset); - static void handleEndDoctypeDecl(void* userData); - static void handleEntityDecl(void *userData, const XML_Char *entityName, int isParamEntity, const XML_Char *value, int valueLength, - const XML_Char *base, const XML_Char *systemId, const XML_Char *publicId, const XML_Char *notationName); - static void handleExternalParsedEntityDecl(void* userData, const XML_Char* entityName, const XML_Char* base, const XML_Char* systemId, const XML_Char* publicId); - static void handleInternalParsedEntityDecl(void* userData, const XML_Char* entityName, const XML_Char* replacementText, int replacementTextLength); - static void handleSkippedEntity(void* userData, const XML_Char* entityName, int isParameterEntity); - - // encoding support - static int convert(void *data, const char *s); - -private: - typedef std::map EncodingMap; - typedef std::vector ContextStack; - - XML_Parser _parser; - char* _pBuffer; - bool _encodingSpecified; - XMLString _encoding; - bool _expandInternalEntities; - bool _externalGeneralEntities; - bool _externalParameterEntities; - bool _enablePartialReads; - NamespaceStrategy* _pNamespaceStrategy; - EncodingMap _encodings; - ContextStack _context; - - EntityResolver* _pEntityResolver; - DTDHandler* _pDTDHandler; - DeclHandler* _pDeclHandler; - ContentHandler* _pContentHandler; - LexicalHandler* _pLexicalHandler; - ErrorHandler* _pErrorHandler; - - float _maximumAmplificationFactor; - Poco::UInt64 _activationThresholdBytes; - - static const int PARSE_BUFFER_SIZE; - static const XMLString EMPTY_STRING; -}; - - -// -// inlines -// -inline const XMLString& ParserEngine::getEncoding() const +namespace XML { - return _encoding; + + + class InputSource; + class EntityResolver; + class DTDHandler; + class DeclHandler; + class ContentHandler; + class LexicalHandler; + class ErrorHandler; + class NamespaceStrategy; + class ContextLocator; + + + class XML_API ParserEngine : public Locator + /// This class provides an object-oriented, stream-based, + /// low-level interface to the XML Parser Toolkit (expat). + /// It is strongly recommended, that you use the + /// SAX parser classes (which are based on this + /// class) instead of this class, since they provide + /// a standardized, higher-level interface to the parser. + { + public: + ParserEngine(); + /// Creates the parser engine. + + ParserEngine(const XMLString & encoding); + /// Creates the parser engine and passes the encoding + /// to the underlying parser. + + ~ParserEngine(); + /// Destroys the parser. + + void setEncoding(const XMLString & encoding); + /// Sets the encoding used by expat. The encoding must be + /// set before parsing begins, otherwise it will be ignored. + + const XMLString & getEncoding() const; + /// Returns the encoding used by expat. + + void addEncoding(const XMLString & name, Poco::TextEncoding * pEncoding); + /// Adds an encoding to the parser. + + void setNamespaceStrategy(NamespaceStrategy * pStrategy); + /// Sets the NamespaceStrategy used by the parser. + /// The parser takes ownership of the strategy object + /// and deletes it when it's no longer needed. + /// The default is NoNamespacesStrategy. + + NamespaceStrategy * getNamespaceStrategy() const; + /// Returns the NamespaceStrategy currently in use. + + void setExpandInternalEntities(bool flag = true); + /// Enables/disables expansion of internal entities (enabled by + /// default). If entity expansion is disabled, internal entities + /// are reported via the default handler. + /// Must be set before parsing begins, otherwise it will be + /// ignored. + + bool getExpandInternalEntities() const; + /// Returns true if internal entities will be expanded automatically, + /// which is the default. + + void setExternalGeneralEntities(bool flag = true); + /// Enable or disable processing of external general entities. + + bool getExternalGeneralEntities() const; + /// Returns true if external general entities will be processed; false otherwise. + + void setExternalParameterEntities(bool flag = true); + /// Enable or disable processing of external parameter entities. + + bool getExternalParameterEntities() const; + /// Returns true if external parameter entities will be processed; false otherwise. + + void setEntityResolver(EntityResolver * pResolver); + /// Allow an application to register an entity resolver. + + EntityResolver * getEntityResolver() const; + /// Return the current entity resolver. + + void setDTDHandler(DTDHandler * pDTDHandler); + /// Allow an application to register a DTD event handler. + + DTDHandler * getDTDHandler() const; + /// Return the current DTD handler. + + void setDeclHandler(DeclHandler * pDeclHandler); + /// Allow an application to register a DTD declarations event handler. + + DeclHandler * getDeclHandler() const; + /// Return the current DTD declarations handler. + + void setContentHandler(ContentHandler * pContentHandler); + /// Allow an application to register a content event handler. + + ContentHandler * getContentHandler() const; + /// Return the current content handler. + + void setLexicalHandler(LexicalHandler * pLexicalHandler); + /// Allow an application to register a lexical event handler. + + LexicalHandler * getLexicalHandler() const; + /// Return the current lexical handler. + + void setErrorHandler(ErrorHandler * pErrorHandler); + /// Allow an application to register an error event handler. + + ErrorHandler * getErrorHandler() const; + /// Return the current error handler. + + void setEnablePartialReads(bool flag = true); + /// Enable or disable partial reads from the input source. + /// + /// This is useful for parsing XML from a socket stream for + /// a protocol like XMPP, where basically single elements + /// are read one at a time from the input source's stream, and + /// following elements depend upon responses sent back to + /// the peer. + /// + /// Normally, the parser always reads blocks of PARSE_BUFFER_SIZE + /// at a time, and blocks until a complete block has been read (or + /// the end of the stream has been reached). + /// This allows for efficient parsing of "complete" XML documents, + /// but fails in a case such as XMPP, where only XML fragments + /// are sent at a time. + + bool getEnablePartialReads() const; + /// Returns true if partial reads are enabled (see + /// setEnablePartialReads()), false otherwise. + + void setBillionLaughsAttackProtectionMaximumAmplification(float maximumAmplificationFactor); + /// Sets the maximum tolerated amplification factor + /// for protection against Billion Laughs Attacks. + /// + /// The amplification factor is calculated as: + /// amplification := (direct + indirect) / direct + /// while parsing, whereas: + /// - direct is the number of bytes read from the primary document in parsing and + /// - indirect is the number of bytes added by expanding entities and reading of + /// external DTD files, combined. + /// + /// maximumAmplificationFactor must be non-NaN and greater than or equal to 1.0. + /// + /// Requires an underlying Expat version >= 2.4.0. + + void setBillionLaughsAttackProtectionActivationThreshold(Poco::UInt64 activationThresholdBytes); + /// Sets number of output bytes (including amplification from entity expansion and reading DTD files) + /// needed to activate protection against Billion Laughs Attacks. + /// + /// Defaults to 8 MiB. + /// + /// Requires an underlying Expat version >= 2.4.0. + + void parse(InputSource * pInputSource); + /// Parse an XML document from the given InputSource. + + void parse(const char * pBuffer, std::size_t size); + /// Parses an XML document from the given buffer. + + // Locator + XMLString getPublicId() const; + /// Return the public identifier for the current document event. + + XMLString getSystemId() const; + /// Return the system identifier for the current document event. + + int getLineNumber() const; + /// Return the line number where the current document event ends. + + int getColumnNumber() const; + /// Return the column number where the current document event ends. + + protected: + void init(); + /// initializes expat + + void parseByteInputStream(XMLByteInputStream & istr); + /// Parses an entity from the given stream. + + void parseCharInputStream(XMLCharInputStream & istr); + /// Parses an entity from the given stream. + + std::streamsize readBytes(XMLByteInputStream & istr, char * pBuffer, std::streamsize bufferSize); + /// Reads at most bufferSize bytes from the given stream into the given buffer. + + std::streamsize readChars(XMLCharInputStream & istr, XMLChar * pBuffer, std::streamsize bufferSize); + /// Reads at most bufferSize chars from the given stream into the given buffer. + + void handleError(int errorNo); + /// Throws an XMLException with a message corresponding + /// to the given Expat error code. + + void parseExternal(XML_Parser extParser, InputSource * pInputSource); + /// Parse an XML document from the given InputSource. + + void parseExternalByteInputStream(XML_Parser extParser, XMLByteInputStream & istr); + /// Parses an external entity from the given stream, with a separate parser. + + void parseExternalCharInputStream(XML_Parser extParser, XMLCharInputStream & istr); + /// Parses an external entity from the given stream, with a separate parser. + + void pushContext(XML_Parser parser, InputSource * pInputSource); + /// Pushes a new entry to the context stack. + + void popContext(); + /// Pops the top-most entry from the context stack. + + void resetContext(); + /// Resets and clears the context stack. + + const Locator & locator() const; + /// Returns a locator denoting the current parse location. + + // expat handler procedures + static void handleStartElement(void * userData, const XML_Char * name, const XML_Char ** atts); + static void handleEndElement(void * userData, const XML_Char * name); + static void handleCharacterData(void * userData, const XML_Char * s, int len); + static void handleProcessingInstruction(void * userData, const XML_Char * target, const XML_Char * data); + static void handleDefault(void * userData, const XML_Char * s, int len); + static void handleUnparsedEntityDecl( + void * userData, + const XML_Char * entityName, + const XML_Char * base, + const XML_Char * systemId, + const XML_Char * publicId, + const XML_Char * notationName); + static void handleNotationDecl( + void * userData, const XML_Char * notationName, const XML_Char * base, const XML_Char * systemId, const XML_Char * publicId); + static int handleExternalEntityRef( + XML_Parser parser, + const XML_Char * openEntityNames, + const XML_Char * base, + const XML_Char * systemId, + const XML_Char * publicId); + static int handleUnknownEncoding(void * encodingHandlerData, const XML_Char * name, XML_Encoding * info); + static void handleComment(void * userData, const XML_Char * data); + static void handleStartCdataSection(void * userData); + static void handleEndCdataSection(void * userData); + static void handleStartNamespaceDecl(void * userData, const XML_Char * prefix, const XML_Char * uri); + static void handleEndNamespaceDecl(void * userData, const XML_Char * prefix); + static void handleStartDoctypeDecl( + void * userData, const XML_Char * doctypeName, const XML_Char * systemId, const XML_Char * publicId, int hasInternalSubset); + static void handleEndDoctypeDecl(void * userData); + static void handleEntityDecl( + void * userData, + const XML_Char * entityName, + int isParamEntity, + const XML_Char * value, + int valueLength, + const XML_Char * base, + const XML_Char * systemId, + const XML_Char * publicId, + const XML_Char * notationName); + static void handleExternalParsedEntityDecl( + void * userData, const XML_Char * entityName, const XML_Char * base, const XML_Char * systemId, const XML_Char * publicId); + static void handleInternalParsedEntityDecl( + void * userData, const XML_Char * entityName, const XML_Char * replacementText, int replacementTextLength); + static void handleSkippedEntity(void * userData, const XML_Char * entityName, int isParameterEntity); + + // encoding support + static int convert(void * data, const char * s); + + private: + typedef std::map EncodingMap; + typedef std::vector ContextStack; + + XML_Parser _parser; + char * _pBuffer; + bool _encodingSpecified; + XMLString _encoding; + bool _expandInternalEntities; + bool _externalGeneralEntities; + bool _externalParameterEntities; + bool _enablePartialReads; + NamespaceStrategy * _pNamespaceStrategy; + EncodingMap _encodings; + ContextStack _context; + + EntityResolver * _pEntityResolver; + DTDHandler * _pDTDHandler; + DeclHandler * _pDeclHandler; + ContentHandler * _pContentHandler; + LexicalHandler * _pLexicalHandler; + ErrorHandler * _pErrorHandler; + + float _maximumAmplificationFactor; + Poco::UInt64 _activationThresholdBytes; + + static const int PARSE_BUFFER_SIZE; + static const XMLString EMPTY_STRING; + }; + + + // + // inlines + // + inline const XMLString & ParserEngine::getEncoding() const + { + return _encoding; + } + + + inline NamespaceStrategy * ParserEngine::getNamespaceStrategy() const + { + return _pNamespaceStrategy; + } + + + inline bool ParserEngine::getExpandInternalEntities() const + { + return _expandInternalEntities; + } + + + inline bool ParserEngine::getExternalGeneralEntities() const + { + return _externalGeneralEntities; + } + + + inline bool ParserEngine::getExternalParameterEntities() const + { + return _externalParameterEntities; + } + + + inline EntityResolver * ParserEngine::getEntityResolver() const + { + return _pEntityResolver; + } + + + inline DTDHandler * ParserEngine::getDTDHandler() const + { + return _pDTDHandler; + } + + + inline DeclHandler * ParserEngine::getDeclHandler() const + { + return _pDeclHandler; + } + + + inline ContentHandler * ParserEngine::getContentHandler() const + { + return _pContentHandler; + } + + + inline LexicalHandler * ParserEngine::getLexicalHandler() const + { + return _pLexicalHandler; + } + + + inline ErrorHandler * ParserEngine::getErrorHandler() const + { + return _pErrorHandler; + } + + + inline bool ParserEngine::getEnablePartialReads() const + { + return _enablePartialReads; + } + + } - - -inline NamespaceStrategy* ParserEngine::getNamespaceStrategy() const -{ - return _pNamespaceStrategy; -} - - -inline bool ParserEngine::getExpandInternalEntities() const -{ - return _expandInternalEntities; -} - - -inline bool ParserEngine::getExternalGeneralEntities() const -{ - return _externalGeneralEntities; -} - - -inline bool ParserEngine::getExternalParameterEntities() const -{ - return _externalParameterEntities; -} - - -inline EntityResolver* ParserEngine::getEntityResolver() const -{ - return _pEntityResolver; -} - - -inline DTDHandler* ParserEngine::getDTDHandler() const -{ - return _pDTDHandler; -} - - -inline DeclHandler* ParserEngine::getDeclHandler() const -{ - return _pDeclHandler; -} - - -inline ContentHandler* ParserEngine::getContentHandler() const -{ - return _pContentHandler; -} - - -inline LexicalHandler* ParserEngine::getLexicalHandler() const -{ - return _pLexicalHandler; -} - - -inline ErrorHandler* ParserEngine::getErrorHandler() const -{ - return _pErrorHandler; -} - - -inline bool ParserEngine::getEnablePartialReads() const -{ - return _enablePartialReads; -} - - -} } // namespace Poco::XML +} // namespace Poco::XML #endif // XML_ParserEngine_INCLUDED diff --git a/base/poco/XML/include/Poco/XML/QName.h b/base/poco/XML/include/Poco/XML/QName.h index 9aab3305b6d..71f23ae456d 100644 --- a/base/poco/XML/include/Poco/XML/QName.h +++ b/base/poco/XML/include/Poco/XML/QName.h @@ -21,128 +21,131 @@ #define XML_QName_INCLUDED -#include "Poco/XML/XML.h" -#include #include +#include +#include "Poco/XML/XML.h" -namespace Poco { -namespace XML { - - -class XML_API QName - /// This class represents a qualified XML name in the stream parser. - /// - /// Note that the optional prefix is just a "syntactic sugar". In - /// particular, it is ignored by the comparison operators and the - /// std::ostream insertion operator. +namespace Poco { -public: - QName(); - QName(const std::string& name); - QName(const std::string& ns, const std::string& name); - QName(const std::string& ns, const std::string& name, const std::string& prefix); - QName(const QName& qname); - QName(QName&& qname) noexcept; - - QName& operator = (const QName& qname); - QName& operator = (QName&& qname) noexcept; - void swap(QName& qname); - - const std::string& namespaceURI() const; - /// Returns the namespace URI part of the name. - - const std::string& localName() const; - /// Returns the local part of the name. - - const std::string& prefix() const; - /// Returns the namespace prefix of the name. - - std::string& namespaceURI(); - /// Returns the namespace URI part of the name. - - std::string& localName(); - /// Returns the local part of the name. - - std::string& prefix(); - /// Returns the namespace prefix of the name. - - std::string toString() const; - /// Returns a printable representation in the [#] form. - -public: - friend bool operator < (const QName& x, const QName& y); - friend bool operator == (const QName& x, const QName& y); - friend bool operator != (const QName& x, const QName& y); - -private: - std::string _ns; - std::string _name; - std::string _prefix; -}; - - -// -// inlines -// -inline const std::string& QName::namespaceURI() const +namespace XML { - return _ns; + + + class XML_API QName + /// This class represents a qualified XML name in the stream parser. + /// + /// Note that the optional prefix is just a "syntactic sugar". In + /// particular, it is ignored by the comparison operators and the + /// std::ostream insertion operator. + { + public: + QName(); + QName(const std::string & name); + QName(const std::string & ns, const std::string & name); + QName(const std::string & ns, const std::string & name, const std::string & prefix); + QName(const QName & qname); + QName(QName && qname) noexcept; + + QName & operator=(const QName & qname); + QName & operator=(QName && qname) noexcept; + void swap(QName & qname); + + const std::string & namespaceURI() const; + /// Returns the namespace URI part of the name. + + const std::string & localName() const; + /// Returns the local part of the name. + + const std::string & prefix() const; + /// Returns the namespace prefix of the name. + + std::string & namespaceURI(); + /// Returns the namespace URI part of the name. + + std::string & localName(); + /// Returns the local part of the name. + + std::string & prefix(); + /// Returns the namespace prefix of the name. + + std::string toString() const; + /// Returns a printable representation in the [#] form. + + public: + friend bool operator<(const QName & x, const QName & y); + friend bool operator==(const QName & x, const QName & y); + friend bool operator!=(const QName & x, const QName & y); + + private: + std::string _ns; + std::string _name; + std::string _prefix; + }; + + + // + // inlines + // + inline const std::string & QName::namespaceURI() const + { + return _ns; + } + + + inline const std::string & QName::localName() const + { + return _name; + } + + + inline const std::string & QName::prefix() const + { + return _prefix; + } + + + inline std::string & QName::namespaceURI() + { + return _ns; + } + + + inline std::string & QName::localName() + { + return _name; + } + + + inline std::string & QName::prefix() + { + return _prefix; + } + + + XML_API std::ostream & operator<<(std::ostream &, const QName &); + + + inline bool operator<(const QName & x, const QName & y) + { + return x._ns < y._ns || (x._ns == y._ns && x._name < y._name); + } + + + inline bool operator==(const QName & x, const QName & y) + { + return x._ns == y._ns && x._name == y._name; + } + + + inline bool operator!=(const QName & x, const QName & y) + { + return !(x == y); + } + + } - - -inline const std::string& QName::localName() const -{ - return _name; -} - - -inline const std::string& QName::prefix() const -{ - return _prefix; -} - - -inline std::string& QName::namespaceURI() -{ - return _ns; -} - - -inline std::string& QName::localName() -{ - return _name; -} - - -inline std::string& QName::prefix() -{ - return _prefix; -} - - -XML_API std::ostream& operator << (std::ostream&, const QName&); - - -inline bool operator < (const QName& x, const QName& y) -{ - return x._ns < y._ns || (x._ns == y._ns && x._name < y._name); -} - - -inline bool operator == (const QName& x, const QName& y) -{ - return x._ns == y._ns && x._name == y._name; -} - - -inline bool operator != (const QName& x, const QName& y) -{ - return !(x == y); -} - - -} } // namespace Poco::XML +} // namespace Poco::XML #endif // XML_QName_INCLUDED diff --git a/base/poco/XML/include/Poco/XML/ValueTraits.h b/base/poco/XML/include/Poco/XML/ValueTraits.h index 46631c93984..3158f691d5b 100644 --- a/base/poco/XML/include/Poco/XML/ValueTraits.h +++ b/base/poco/XML/include/Poco/XML/ValueTraits.h @@ -21,84 +21,75 @@ #define XML_ValueTraits_INCLUDED -#include "XMLStreamParserException.h" -#include #include #include #include +#include +#include "XMLStreamParserException.h" -namespace Poco { -namespace XML { - - -class XMLStreamParser; -class XMLStreamSerializer; - - -template -struct DefaultValueTraits +namespace Poco { - static T - parse(std::string, const XMLStreamParser&); - - static std::string - serialize(const T&, const XMLStreamSerializer&); -}; - - -template <> -struct XML_API DefaultValueTraits +namespace XML { - static bool - parse(std::string, const XMLStreamParser&); - - static std::string serialize(bool v, const XMLStreamSerializer&) - { - return v ? "true" : "false"; - } -}; -template <> -struct XML_API DefaultValueTraits -{ - static std::string parse(std::string s, const XMLStreamParser&) - { - return s; - } - - static std::string serialize(const std::string& v, const XMLStreamSerializer&) - { - return v; - } -}; + class XMLStreamParser; + class XMLStreamSerializer; -template -struct ValueTraits: DefaultValueTraits -{ -}; + template + struct DefaultValueTraits + { + static T parse(std::string, const XMLStreamParser &); + + static std::string serialize(const T &, const XMLStreamSerializer &); + }; -template -struct ValueTraits : DefaultValueTraits -{ -}; + template <> + struct XML_API DefaultValueTraits + { + static bool parse(std::string, const XMLStreamParser &); + + static std::string serialize(bool v, const XMLStreamSerializer &) { return v ? "true" : "false"; } + }; + + + template <> + struct XML_API DefaultValueTraits + { + static std::string parse(std::string s, const XMLStreamParser &) { return s; } + + static std::string serialize(const std::string & v, const XMLStreamSerializer &) { return v; } + }; + + + template + struct ValueTraits : DefaultValueTraits + { + }; + + + template + struct ValueTraits : DefaultValueTraits + { + }; + + + template + T DefaultValueTraits::parse(std::string s, const XMLStreamParser & p) + { + T r; + std::istringstream is(s); + if (!(is >> r && is.eof())) + throw XMLStreamParserException(p, "invalid value '" + s + "'"); + return r; + } -template -T DefaultValueTraits::parse(std::string s, const XMLStreamParser& p) -{ - T r; - std::istringstream is(s); - if (!(is >> r && is.eof())) - throw XMLStreamParserException(p, "invalid value '" + s + "'"); - return r; } - - -} } // namespace Poco::XML +} // namespace Poco::XML #endif // XML_ValueTraits_INCLUDED diff --git a/base/poco/XML/include/Poco/XML/XML.h b/base/poco/XML/include/Poco/XML/XML.h index 19a21a3b479..a5b611a76dd 100644 --- a/base/poco/XML/include/Poco/XML/XML.h +++ b/base/poco/XML/include/Poco/XML/XML.h @@ -24,28 +24,28 @@ // -// The following block is the standard way of creating macros which make exporting +// The following block is the standard way of creating macros which make exporting // from a DLL simpler. All files within this DLL are compiled with the XML_EXPORTS // symbol defined on the command line. this symbol should not be defined on any project -// that uses this DLL. This way any other project whose source files include this file see +// that uses this DLL. This way any other project whose source files include this file see // XML_API functions as being imported from a DLL, whereas this DLL sees symbols // defined with this macro as being exported. // #if defined(_WIN32) && defined(POCO_DLL) - #if defined(XML_EXPORTS) - #define XML_API __declspec(dllexport) - #else - #define XML_API __declspec(dllimport) - #endif +# if defined(XML_EXPORTS) +# define XML_API __declspec(dllexport) +# else +# define XML_API __declspec(dllimport) +# endif #endif #if !defined(XML_API) - #if !defined(POCO_NO_GCC_API_ATTRIBUTE) && defined (__GNUC__) && (__GNUC__ >= 4) - #define XML_API __attribute__ ((visibility ("default"))) - #else - #define XML_API - #endif +# if !defined(POCO_NO_GCC_API_ATTRIBUTE) && defined(__GNUC__) && (__GNUC__ >= 4) +# define XML_API __attribute__((visibility("default"))) +# else +# define XML_API +# endif #endif @@ -53,9 +53,9 @@ // Automatically link XML library. // #if defined(_MSC_VER) - #if !defined(POCO_NO_AUTOMATIC_LIBS) && !defined(XML_EXPORTS) - #pragma comment(lib, "PocoXML" POCO_LIB_SUFFIX) - #endif +# if !defined(POCO_NO_AUTOMATIC_LIBS) && !defined(XML_EXPORTS) +# pragma comment(lib, "PocoXML" POCO_LIB_SUFFIX) +# endif #endif diff --git a/base/poco/XML/include/Poco/XML/XMLException.h b/base/poco/XML/include/Poco/XML/XMLException.h index 9805badf063..4d6eaa1d601 100644 --- a/base/poco/XML/include/Poco/XML/XMLException.h +++ b/base/poco/XML/include/Poco/XML/XMLException.h @@ -18,20 +18,23 @@ #define XML_XMLException_INCLUDED -#include "Poco/XML/XML.h" #include "Poco/Exception.h" +#include "Poco/XML/XML.h" -namespace Poco { -namespace XML { +namespace Poco +{ +namespace XML +{ -POCO_DECLARE_EXCEPTION(XML_API, XMLException, Poco::RuntimeException) - /// The base class for all XML-related exceptions like SAXException - /// and DOMException. + POCO_DECLARE_EXCEPTION(XML_API, XMLException, Poco::RuntimeException) + /// The base class for all XML-related exceptions like SAXException + /// and DOMException. -} } // namespace Poco::XML +} +} // namespace Poco::XML #endif // XML_XMLException_INCLUDED diff --git a/base/poco/XML/include/Poco/XML/XMLStream.h b/base/poco/XML/include/Poco/XML/XMLStream.h index 23a3999af14..b2a55ab0c33 100644 --- a/base/poco/XML/include/Poco/XML/XMLStream.h +++ b/base/poco/XML/include/Poco/XML/XMLStream.h @@ -18,18 +18,20 @@ #define XML_XMLStream_INCLUDED -#include "Poco/XML/XML.h" #include #include +#include "Poco/XML/XML.h" -namespace Poco { -namespace XML { +namespace Poco +{ +namespace XML +{ -// The byte input stream is always a narrow stream. -using XMLByteInputStream = std::istream; -using XMLByteOutputStream = std::ostream; + // The byte input stream is always a narrow stream. + using XMLByteInputStream = std::istream; + using XMLByteOutputStream = std::ostream; // @@ -48,24 +50,25 @@ using XMLByteOutputStream = std::ostream; // #if defined(XML_UNICODE_WCHAR_T) - // Unicode - use wide streams - using XMLCharInputStream = std::wistream; - using XMLCharOutputStream = std::wostream; + // Unicode - use wide streams + using XMLCharInputStream = std::wistream; + using XMLCharOutputStream = std::wostream; #elif defined(XML_UNICODE) - // not supported - leave XMLString undefined + // not supported - leave XMLString undefined #else - // Characters are UTF-8 encoded - using XMLCharInputStream = std::istream; - using XMLCharOutputStream = std::ostream; + // Characters are UTF-8 encoded + using XMLCharInputStream = std::istream; + using XMLCharOutputStream = std::ostream; #endif -} } // namespace Poco::XML +} +} // namespace Poco::XML #endif // XML_XMLStream_INCLUDED diff --git a/base/poco/XML/include/Poco/XML/XMLStreamParser.h b/base/poco/XML/include/Poco/XML/XMLStreamParser.h index 31e309d564b..76e1019f8f1 100644 --- a/base/poco/XML/include/Poco/XML/XMLStreamParser.h +++ b/base/poco/XML/include/Poco/XML/XMLStreamParser.h @@ -23,612 +23,601 @@ // We only support UTF-8 expat. #ifdef XML_UNICODE -#error UTF-16 expat (XML_UNICODE defined) is not supported +# error UTF-16 expat (XML_UNICODE defined) is not supported #endif +#include "Poco/XML/Content.h" #include "Poco/XML/QName.h" #include "Poco/XML/ValueTraits.h" -#include "Poco/XML/Content.h" #if defined(POCO_UNBUNDLED_EXPAT) -#include +# include #else -#include "Poco/XML/expat.h" +# include "Poco/XML/expat.h" #endif -#include -#include -#include -#include #include +#include +#include +#include +#include -namespace Poco { -namespace XML { - - -class XML_API XMLStreamParser - /// The streaming XML pull parser and streaming XML serializer. The parser - /// is a conforming, non-validating XML 1.0 implementation (see Implementation Notes - /// for details). The application character encoding (that is, the encoding used - /// in the application's memory) for both parser and serializer is UTF-8. - /// The output encoding of the serializer is UTF-8 as well. The parser supports - /// UTF-8, UTF-16, ISO-8859-1, and US-ASCII input encodings. - /// - /// Attribute map: - /// - /// Attribute map lookup. If attribute is not found, then the version - /// without the default value throws an appropriate parsing exception - /// while the version with the default value returns that value. - /// - /// Note also that there is no attribute(ns, name) version since it - /// would conflict with attribute(name, dv) (qualified attributes - /// are not very common). - /// - /// Attribute map is valid throughout at the "element level" until - /// end_element and not just during EV_START_ELEMENT. As a special case, - /// the map is still valid after peek() that returned end_element until - /// this end_element event is retrieved with next(). - /// - /// Using parser: - /// - /// XMLStreamParser p(ifs, argv[1]); - /// for (XMLStreamParser::EventType e: p) - /// { - /// switch (e) - /// { - /// case XMLStreamParser::EV_START_ELEMENT: - /// cerr << p.line () << ':' << p.column () << ": start " << p.name () << endl; - /// break; - /// case XMLStreamParser::EV_END_ELEMENT: - /// cerr << p.line () << ':' << p.column () << ": end " << p.name () << endl; - /// break; - /// case XMLStreamParser::EV_START_ATTRIBUTE: - /// ... - /// case XMLStreamParser::EV_END_ATTRIBUTE: - /// ... - /// case XMLStreamParser::EV_CHARACTERS: - /// ... - /// } - /// } +namespace Poco { -public: - enum EventType - /// Parsing events. - { - EV_START_ELEMENT, - EV_END_ELEMENT, - EV_START_ATTRIBUTE, - EV_END_ATTRIBUTE, - EV_CHARACTERS, - EV_START_NAMESPACE_DECL, - EV_END_NAMESPACE_DECL, - EV_EOF - }; - - using FeatureType = unsigned short; - /// If both receive_attributes_event and RECEIVE_ATTRIBUTE_MAP are - /// specified, then RECEIVE_ATTRIBUTES_EVENT is assumed. - - static const FeatureType RECEIVE_ELEMENTS = 0x0001; - static const FeatureType RECEIVE_CHARACTERS = 0x0002; - static const FeatureType RECEIVE_ATTRIBUTE_MAP = 0x0004; - static const FeatureType RECEIVE_ATTRIBUTES_EVENT = 0x0008; - static const FeatureType RECEIVE_NAMESPACE_DECLS = 0x0010; - static const FeatureType RECEIVE_DEFAULT = RECEIVE_ELEMENTS | RECEIVE_CHARACTERS | RECEIVE_ATTRIBUTE_MAP; - - struct AttributeValueType - { - std::string value; - mutable bool handled; - }; - - using AttributeMapType = std::map; - - struct XML_API Iterator - // C++11 range-based for support. Generally, the iterator interface - // doesn't make much sense for the XMLStreamParser so for now we have an - // implementation that is just enough to the range-based for. - { - using value_type = EventType; - - Iterator(XMLStreamParser* p = 0, EventType e = EV_EOF): - _parser(p), - _e(e) - { - } - - value_type operator * () const - { - return _e; - } - - Iterator& operator ++ () - { - _e = _parser->next(); - return *this; - } - - bool operator == (Iterator y) const - /// Comparison only makes sense when comparing to end (eof). - { - return _e == EV_EOF && y._e == EV_EOF; - } - - bool operator != (Iterator y) const - /// Comparison only makes sense when comparing to end (eof). - { - return !(*this == y); - } - - private: - XMLStreamParser* _parser; - EventType _e; - }; - - Iterator begin() - { - return Iterator(this, next()); - } - - Iterator end() - { - return Iterator(this, EV_EOF); - } - - XMLStreamParser(std::istream&, const std::string& inputName, FeatureType = RECEIVE_DEFAULT); - /// The parser constructor takes three arguments: the stream to parse, - /// input name that is used in diagnostics to identify the document being - /// parsed, and the list of events we want the parser to report. - /// - /// Parse std::istream. Input name is used in diagnostics to identify - /// the document being parsed. - /// - /// If stream exceptions are enabled then std::ios_base::failure - /// exception is used to report io errors (badbit and failbit). - /// Otherwise, those are reported as the parsing exception. - - XMLStreamParser(const void* data, std::size_t size, const std::string& inputName, FeatureType = RECEIVE_DEFAULT); - /// Parse memory buffer that contains the whole document. Input name - /// is used in diagnostics to identify the document being parsed. - - ~XMLStreamParser(); - /// Destroys the XMLStreamParser. - - EventType next(); - /// Call the next() function when we are ready to handle the next piece of XML. - - void nextExpect(EventType); - /// Get the next event and make sure that it's what's expected. If it - /// is not, then throw an appropriate parsing exception. - - void nextExpect(EventType, const std::string& name); - void nextExpect(EventType, const QName& qname); - void nextExpect(EventType, const std::string& ns, const std::string& name); - - EventType peek(); - EventType event(); - /// Return the event that was last returned by the call to next() or peek(). - - const std::string& inputName() const; - const QName& getQName() const; - const std::string& namespaceURI() const; - const std::string& localName() const; - const std::string& prefix() const; - std::string& value(); - const std::string& value() const; - template T value() const; - Poco::UInt64 line() const; - Poco::UInt64 column() const; - const std::string& attribute(const std::string& name) const; - template - T attribute(const std::string& name) const; - std::string attribute(const std::string& name, const std::string& deflt) const; - template - T attribute(const std::string& name, const T& deflt) const; - const std::string& attribute(const QName& qname) const; - template - T attribute(const QName& qname) const; - std::string attribute(const QName& qname, const std::string& deflt) const; - template - T attribute(const QName& qname, const T& deflt) const; - bool attributePresent(const std::string& name) const; - bool attributePresent(const QName& qname) const; - const AttributeMapType& attributeMap() const; - - void content(Content); - Content content() const; - - void nextExpect(EventType, const std::string& name, Content); - void nextExpect(EventType, const QName& qname, Content); - void nextExpect(EventType, const std::string& ns, const std::string& name, Content); - - // Helpers for parsing elements with simple content. The first two - // functions assume that EV_START_ELEMENT has already been parsed. The - // rest parse the complete element, from start to end. - // - // Note also that as with attribute(), there is no (namespace,name) - // overload since it would conflicts with (namespace,deflt). - std::string element(); - - template - T element(); - std::string element(const std::string& name); - std::string element(const QName& qname); - template - T element(const std::string& name); - template - T element(const QName& qname); - std::string element(const std::string& name, const std::string& deflt); - std::string element(const QName& qname, const std::string& deflt); - template - T element(const std::string& name, const T& deflt); - template - T element(const QName& qname, const T& deflt); - -private: - XMLStreamParser(const XMLStreamParser&); - XMLStreamParser& operator = (const XMLStreamParser&); - - static void XMLCALL handleStartElement(void*, const XML_Char*, const XML_Char**); - static void XMLCALL handleEndElement(void*, const XML_Char*); - static void XMLCALL handleCharacters(void*, const XML_Char*, int); - static void XMLCALL handleStartNamespaceDecl(void*, const XML_Char*, const XML_Char*); - static void XMLCALL handleEndNamespaceDecl(void*, const XML_Char*); - - void init(); - EventType nextImpl(bool peek); - EventType nextBody(); - void handleError(); - - // If _size is 0, then data is std::istream. Otherwise, it is a buffer. - union - { - std::istream* is; - const void* buf; - } - _data; - - std::size_t _size; - const std::string _inputName; - FeatureType _feature; - XML_Parser _parser; - std::size_t _depth; - bool _accumulateContent; // Whether we are accumulating character content. - enum { state_next, state_peek } _parserState; - EventType _currentEvent; - EventType _queue; - QName _qname; - std::string _value; - const QName* _qualifiedName; - std::string* _pvalue; - Poco::UInt64 _line; - Poco::UInt64 _column; - - struct AttributeType - { - QName qname; - std::string value; - }; - - typedef std::vector attributes; - attributes _attributes; - attributes::size_type _currentAttributeIndex; // Index of the current attribute. - - typedef std::vector NamespaceDecls; - NamespaceDecls _startNamespace; - NamespaceDecls::size_type _startNamespaceIndex;// Index of the current decl. - NamespaceDecls _endNamespace; - NamespaceDecls::size_type _endNamespaceIndex;// Index of the current decl. - - struct ElementEntry - { - ElementEntry(std::size_t d, Content c = Content::Mixed): - depth(d), - content(c), - attributesUnhandled(0) - { - } - - std::size_t depth; - Content content; - AttributeMapType attributeMap; - mutable AttributeMapType::size_type attributesUnhandled; - }; - - typedef std::vector ElementState; - std::vector _elementState; - - const AttributeMapType _emptyAttrMap; - - const ElementEntry* getElement() const; - const ElementEntry* getElementImpl() const; - void popElement(); -}; - - -XML_API std::ostream& operator << (std::ostream&, XMLStreamParser::EventType); - - -// -// inlines -// -inline XMLStreamParser::EventType XMLStreamParser::event() - // Return the even that was last returned by the call to next() or peek(). +namespace XML { - return _currentEvent; + + + class XML_API XMLStreamParser + /// The streaming XML pull parser and streaming XML serializer. The parser + /// is a conforming, non-validating XML 1.0 implementation (see Implementation Notes + /// for details). The application character encoding (that is, the encoding used + /// in the application's memory) for both parser and serializer is UTF-8. + /// The output encoding of the serializer is UTF-8 as well. The parser supports + /// UTF-8, UTF-16, ISO-8859-1, and US-ASCII input encodings. + /// + /// Attribute map: + /// + /// Attribute map lookup. If attribute is not found, then the version + /// without the default value throws an appropriate parsing exception + /// while the version with the default value returns that value. + /// + /// Note also that there is no attribute(ns, name) version since it + /// would conflict with attribute(name, dv) (qualified attributes + /// are not very common). + /// + /// Attribute map is valid throughout at the "element level" until + /// end_element and not just during EV_START_ELEMENT. As a special case, + /// the map is still valid after peek() that returned end_element until + /// this end_element event is retrieved with next(). + /// + /// Using parser: + /// + /// XMLStreamParser p(ifs, argv[1]); + /// for (XMLStreamParser::EventType e: p) + /// { + /// switch (e) + /// { + /// case XMLStreamParser::EV_START_ELEMENT: + /// cerr << p.line () << ':' << p.column () << ": start " << p.name () << endl; + /// break; + /// case XMLStreamParser::EV_END_ELEMENT: + /// cerr << p.line () << ':' << p.column () << ": end " << p.name () << endl; + /// break; + /// case XMLStreamParser::EV_START_ATTRIBUTE: + /// ... + /// case XMLStreamParser::EV_END_ATTRIBUTE: + /// ... + /// case XMLStreamParser::EV_CHARACTERS: + /// ... + /// } + /// } + { + public: + enum EventType + /// Parsing events. + { + EV_START_ELEMENT, + EV_END_ELEMENT, + EV_START_ATTRIBUTE, + EV_END_ATTRIBUTE, + EV_CHARACTERS, + EV_START_NAMESPACE_DECL, + EV_END_NAMESPACE_DECL, + EV_EOF + }; + + using FeatureType = unsigned short; + /// If both receive_attributes_event and RECEIVE_ATTRIBUTE_MAP are + /// specified, then RECEIVE_ATTRIBUTES_EVENT is assumed. + + static const FeatureType RECEIVE_ELEMENTS = 0x0001; + static const FeatureType RECEIVE_CHARACTERS = 0x0002; + static const FeatureType RECEIVE_ATTRIBUTE_MAP = 0x0004; + static const FeatureType RECEIVE_ATTRIBUTES_EVENT = 0x0008; + static const FeatureType RECEIVE_NAMESPACE_DECLS = 0x0010; + static const FeatureType RECEIVE_DEFAULT = RECEIVE_ELEMENTS | RECEIVE_CHARACTERS | RECEIVE_ATTRIBUTE_MAP; + + struct AttributeValueType + { + std::string value; + mutable bool handled; + }; + + using AttributeMapType = std::map; + + struct XML_API Iterator + // C++11 range-based for support. Generally, the iterator interface + // doesn't make much sense for the XMLStreamParser so for now we have an + // implementation that is just enough to the range-based for. + { + using value_type = EventType; + + Iterator(XMLStreamParser * p = 0, EventType e = EV_EOF) : _parser(p), _e(e) { } + + value_type operator*() const { return _e; } + + Iterator & operator++() + { + _e = _parser->next(); + return *this; + } + + bool operator==(Iterator y) const + /// Comparison only makes sense when comparing to end (eof). + { + return _e == EV_EOF && y._e == EV_EOF; + } + + bool operator!=(Iterator y) const + /// Comparison only makes sense when comparing to end (eof). + { + return !(*this == y); + } + + private: + XMLStreamParser * _parser; + EventType _e; + }; + + Iterator begin() { return Iterator(this, next()); } + + Iterator end() { return Iterator(this, EV_EOF); } + + XMLStreamParser(std::istream &, const std::string & inputName, FeatureType = RECEIVE_DEFAULT); + /// The parser constructor takes three arguments: the stream to parse, + /// input name that is used in diagnostics to identify the document being + /// parsed, and the list of events we want the parser to report. + /// + /// Parse std::istream. Input name is used in diagnostics to identify + /// the document being parsed. + /// + /// If stream exceptions are enabled then std::ios_base::failure + /// exception is used to report io errors (badbit and failbit). + /// Otherwise, those are reported as the parsing exception. + + XMLStreamParser(const void * data, std::size_t size, const std::string & inputName, FeatureType = RECEIVE_DEFAULT); + /// Parse memory buffer that contains the whole document. Input name + /// is used in diagnostics to identify the document being parsed. + + ~XMLStreamParser(); + /// Destroys the XMLStreamParser. + + EventType next(); + /// Call the next() function when we are ready to handle the next piece of XML. + + void nextExpect(EventType); + /// Get the next event and make sure that it's what's expected. If it + /// is not, then throw an appropriate parsing exception. + + void nextExpect(EventType, const std::string & name); + void nextExpect(EventType, const QName & qname); + void nextExpect(EventType, const std::string & ns, const std::string & name); + + EventType peek(); + EventType event(); + /// Return the event that was last returned by the call to next() or peek(). + + const std::string & inputName() const; + const QName & getQName() const; + const std::string & namespaceURI() const; + const std::string & localName() const; + const std::string & prefix() const; + std::string & value(); + const std::string & value() const; + template + T value() const; + Poco::UInt64 line() const; + Poco::UInt64 column() const; + const std::string & attribute(const std::string & name) const; + template + T attribute(const std::string & name) const; + std::string attribute(const std::string & name, const std::string & deflt) const; + template + T attribute(const std::string & name, const T & deflt) const; + const std::string & attribute(const QName & qname) const; + template + T attribute(const QName & qname) const; + std::string attribute(const QName & qname, const std::string & deflt) const; + template + T attribute(const QName & qname, const T & deflt) const; + bool attributePresent(const std::string & name) const; + bool attributePresent(const QName & qname) const; + const AttributeMapType & attributeMap() const; + + void content(Content); + Content content() const; + + void nextExpect(EventType, const std::string & name, Content); + void nextExpect(EventType, const QName & qname, Content); + void nextExpect(EventType, const std::string & ns, const std::string & name, Content); + + // Helpers for parsing elements with simple content. The first two + // functions assume that EV_START_ELEMENT has already been parsed. The + // rest parse the complete element, from start to end. + // + // Note also that as with attribute(), there is no (namespace,name) + // overload since it would conflicts with (namespace,deflt). + std::string element(); + + template + T element(); + std::string element(const std::string & name); + std::string element(const QName & qname); + template + T element(const std::string & name); + template + T element(const QName & qname); + std::string element(const std::string & name, const std::string & deflt); + std::string element(const QName & qname, const std::string & deflt); + template + T element(const std::string & name, const T & deflt); + template + T element(const QName & qname, const T & deflt); + + private: + XMLStreamParser(const XMLStreamParser &); + XMLStreamParser & operator=(const XMLStreamParser &); + + static void XMLCALL handleStartElement(void *, const XML_Char *, const XML_Char **); + static void XMLCALL handleEndElement(void *, const XML_Char *); + static void XMLCALL handleCharacters(void *, const XML_Char *, int); + static void XMLCALL handleStartNamespaceDecl(void *, const XML_Char *, const XML_Char *); + static void XMLCALL handleEndNamespaceDecl(void *, const XML_Char *); + + void init(); + EventType nextImpl(bool peek); + EventType nextBody(); + void handleError(); + + // If _size is 0, then data is std::istream. Otherwise, it is a buffer. + union + { + std::istream * is; + const void * buf; + } _data; + + std::size_t _size; + const std::string _inputName; + FeatureType _feature; + XML_Parser _parser; + std::size_t _depth; + bool _accumulateContent; // Whether we are accumulating character content. + enum + { + state_next, + state_peek + } _parserState; + EventType _currentEvent; + EventType _queue; + QName _qname; + std::string _value; + const QName * _qualifiedName; + std::string * _pvalue; + Poco::UInt64 _line; + Poco::UInt64 _column; + + struct AttributeType + { + QName qname; + std::string value; + }; + + typedef std::vector attributes; + attributes _attributes; + attributes::size_type _currentAttributeIndex; // Index of the current attribute. + + typedef std::vector NamespaceDecls; + NamespaceDecls _startNamespace; + NamespaceDecls::size_type _startNamespaceIndex; // Index of the current decl. + NamespaceDecls _endNamespace; + NamespaceDecls::size_type _endNamespaceIndex; // Index of the current decl. + + struct ElementEntry + { + ElementEntry(std::size_t d, Content c = Content::Mixed) : depth(d), content(c), attributesUnhandled(0) { } + + std::size_t depth; + Content content; + AttributeMapType attributeMap; + mutable AttributeMapType::size_type attributesUnhandled; + }; + + typedef std::vector ElementState; + std::vector _elementState; + + const AttributeMapType _emptyAttrMap; + + const ElementEntry * getElement() const; + const ElementEntry * getElementImpl() const; + void popElement(); + }; + + + XML_API std::ostream & operator<<(std::ostream &, XMLStreamParser::EventType); + + + // + // inlines + // + inline XMLStreamParser::EventType XMLStreamParser::event() + // Return the even that was last returned by the call to next() or peek(). + { + return _currentEvent; + } + + + inline const std::string & XMLStreamParser::inputName() const + { + return _inputName; + } + + + inline const QName & XMLStreamParser::getQName() const + { + return *_qualifiedName; + } + + + inline const std::string & XMLStreamParser::namespaceURI() const + { + return _qualifiedName->namespaceURI(); + } + + + inline const std::string & XMLStreamParser::localName() const + { + return _qualifiedName->localName(); + } + + + inline const std::string & XMLStreamParser::prefix() const + { + return _qualifiedName->prefix(); + } + + + inline std::string & XMLStreamParser::value() + { + return *_pvalue; + } + + + inline const std::string & XMLStreamParser::value() const + { + return *_pvalue; + } + + + inline Poco::UInt64 XMLStreamParser::line() const + { + return _line; + } + + + inline Poco::UInt64 XMLStreamParser::column() const + { + return _column; + } + + + inline XMLStreamParser::EventType XMLStreamParser::peek() + { + if (_parserState == state_peek) + return _currentEvent; + else + { + EventType e(nextImpl(true)); + _parserState = state_peek; // Set it after the call to nextImpl(). + return e; + } + } + + + template + inline T XMLStreamParser::value() const + { + return ValueTraits::parse(value(), *this); + } + + + inline const std::string & XMLStreamParser::attribute(const std::string & n) const + { + return attribute(QName(n)); + } + + + template + inline T XMLStreamParser::attribute(const std::string & n) const + { + return attribute(QName(n)); + } + + + inline std::string XMLStreamParser::attribute(const std::string & n, const std::string & dv) const + { + return attribute(QName(n), dv); + } + + + template + inline T XMLStreamParser::attribute(const std::string & n, const T & dv) const + { + return attribute(QName(n), dv); + } + + + template + inline T XMLStreamParser::attribute(const QName & qn) const + { + return ValueTraits::parse(attribute(qn), *this); + } + + + inline bool XMLStreamParser::attributePresent(const std::string & n) const + { + return attributePresent(QName(n)); + } + + + inline const XMLStreamParser::AttributeMapType & XMLStreamParser::attributeMap() const + { + if (const ElementEntry * e = getElement()) + { + e->attributesUnhandled = 0; // Assume all handled. + return e->attributeMap; + } + + return _emptyAttrMap; + } + + + inline void XMLStreamParser::nextExpect(EventType e, const QName & qn) + { + nextExpect(e, qn.namespaceURI(), qn.localName()); + } + + + inline void XMLStreamParser::nextExpect(EventType e, const std::string & n) + { + nextExpect(e, std::string(), n); + } + + + inline void XMLStreamParser::nextExpect(EventType e, const QName & qn, Content c) + { + nextExpect(e, qn); + poco_assert(e == EV_START_ELEMENT); + content(c); + } + + + inline void XMLStreamParser::nextExpect(EventType e, const std::string & n, Content c) + { + nextExpect(e, std::string(), n); + poco_assert(e == EV_START_ELEMENT); + content(c); + } + + + inline void XMLStreamParser::nextExpect(EventType e, const std::string & ns, const std::string & n, Content c) + { + nextExpect(e, ns, n); + poco_assert(e == EV_START_ELEMENT); + content(c); + } + + + template + inline T XMLStreamParser::element() + { + return ValueTraits::parse(element(), *this); + } + + + inline std::string XMLStreamParser::element(const std::string & n) + { + nextExpect(EV_START_ELEMENT, n); + return element(); + } + + + inline std::string XMLStreamParser::element(const QName & qn) + { + nextExpect(EV_START_ELEMENT, qn); + return element(); + } + + + template + inline T XMLStreamParser::element(const std::string & n) + { + return ValueTraits::parse(element(n), *this); + } + + + template + inline T XMLStreamParser::element(const QName & qn) + { + return ValueTraits::parse(element(qn), *this); + } + + + inline std::string XMLStreamParser::element(const std::string & n, const std::string & dv) + { + return element(QName(n), dv); + } + + + template + inline T XMLStreamParser::element(const std::string & n, const T & dv) + { + return element(QName(n), dv); + } + + + inline void XMLStreamParser::content(Content c) + { + poco_assert(_parserState == state_next); + + if (!_elementState.empty() && _elementState.back().depth == _depth) + _elementState.back().content = c; + else + _elementState.emplace_back(_depth, c); + } + + + inline Content XMLStreamParser::content() const + { + poco_assert(_parserState == state_next); + + return !_elementState.empty() && _elementState.back().depth == _depth ? _elementState.back().content : Content(Content::Mixed); + } + + + inline const XMLStreamParser::ElementEntry * XMLStreamParser::getElement() const + { + return _elementState.empty() ? 0 : getElementImpl(); + } + + + template + T XMLStreamParser::attribute(const QName & qn, const T & dv) const + { + if (const ElementEntry * e = getElement()) + { + AttributeMapType::const_iterator i(e->attributeMap.find(qn)); + + if (i != e->attributeMap.end()) + { + if (!i->second.handled) + { + i->second.handled = true; + e->attributesUnhandled--; + } + return ValueTraits::parse(i->second.value, *this); + } + } + + return dv; + } + + + template + T XMLStreamParser::element(const QName & qn, const T & dv) + { + if (peek() == EV_START_ELEMENT && getQName() == qn) + { + next(); + return element(); + } + + return dv; + } + + } - - -inline const std::string& XMLStreamParser::inputName() const -{ - return _inputName; -} - - -inline const QName& XMLStreamParser::getQName() const -{ - return *_qualifiedName; -} - - -inline const std::string& XMLStreamParser::namespaceURI() const -{ - return _qualifiedName->namespaceURI(); -} - - -inline const std::string& XMLStreamParser::localName() const -{ - return _qualifiedName->localName(); -} - - -inline const std::string& XMLStreamParser::prefix() const -{ - return _qualifiedName->prefix(); -} - - -inline std::string& XMLStreamParser::value() -{ - return *_pvalue; -} - - -inline const std::string& XMLStreamParser::value() const -{ - return *_pvalue; -} - - -inline Poco::UInt64 XMLStreamParser::line() const -{ - return _line; -} - - -inline Poco::UInt64 XMLStreamParser::column() const -{ - return _column; -} - - -inline XMLStreamParser::EventType XMLStreamParser::peek() -{ - if (_parserState == state_peek) - return _currentEvent; - else - { - EventType e(nextImpl(true)); - _parserState = state_peek; // Set it after the call to nextImpl(). - return e; - } -} - - -template -inline T XMLStreamParser::value() const -{ - return ValueTraits < T > ::parse(value(), *this); -} - - -inline const std::string& XMLStreamParser::attribute(const std::string& n) const -{ - return attribute(QName(n)); -} - - -template -inline T XMLStreamParser::attribute(const std::string& n) const -{ - return attribute < T > (QName(n)); -} - - -inline std::string XMLStreamParser::attribute(const std::string& n, const std::string& dv) const -{ - return attribute(QName(n), dv); -} - - -template -inline T XMLStreamParser::attribute(const std::string& n, const T& dv) const -{ - return attribute < T > (QName(n), dv); -} - - -template -inline T XMLStreamParser::attribute(const QName& qn) const -{ - return ValueTraits < T > ::parse(attribute(qn), *this); -} - - -inline bool XMLStreamParser::attributePresent(const std::string& n) const -{ - return attributePresent(QName(n)); -} - - -inline const XMLStreamParser::AttributeMapType& XMLStreamParser::attributeMap() const -{ - if (const ElementEntry* e = getElement()) - { - e->attributesUnhandled = 0; // Assume all handled. - return e->attributeMap; - } - - return _emptyAttrMap; -} - - -inline void XMLStreamParser::nextExpect(EventType e, const QName& qn) -{ - nextExpect(e, qn.namespaceURI(), qn.localName()); -} - - -inline void XMLStreamParser::nextExpect(EventType e, const std::string& n) -{ - nextExpect(e, std::string(), n); -} - - -inline void XMLStreamParser::nextExpect(EventType e, const QName& qn, Content c) -{ - nextExpect(e, qn); - poco_assert(e == EV_START_ELEMENT); - content(c); -} - - -inline void XMLStreamParser::nextExpect(EventType e, const std::string& n, Content c) -{ - nextExpect(e, std::string(), n); - poco_assert(e == EV_START_ELEMENT); - content(c); -} - - -inline void XMLStreamParser::nextExpect(EventType e, const std::string& ns, const std::string& n, Content c) -{ - nextExpect(e, ns, n); - poco_assert(e == EV_START_ELEMENT); - content(c); -} - - -template -inline T XMLStreamParser::element() -{ - return ValueTraits < T > ::parse(element(), *this); -} - - -inline std::string XMLStreamParser::element(const std::string& n) -{ - nextExpect(EV_START_ELEMENT, n); - return element(); -} - - -inline std::string XMLStreamParser::element(const QName& qn) -{ - nextExpect(EV_START_ELEMENT, qn); - return element(); -} - - -template -inline T XMLStreamParser::element(const std::string& n) -{ - return ValueTraits < T > ::parse(element(n), *this); -} - - -template -inline T XMLStreamParser::element(const QName& qn) -{ - return ValueTraits < T > ::parse(element(qn), *this); -} - - -inline std::string XMLStreamParser::element(const std::string& n, const std::string& dv) -{ - return element(QName(n), dv); -} - - -template -inline T XMLStreamParser::element(const std::string& n, const T& dv) -{ - return element < T > (QName(n), dv); -} - - -inline void XMLStreamParser::content(Content c) -{ - poco_assert(_parserState == state_next); - - if (!_elementState.empty() && _elementState.back().depth == _depth) - _elementState.back().content = c; - else - _elementState.emplace_back(_depth, c); -} - - -inline Content XMLStreamParser::content() const -{ - poco_assert(_parserState == state_next); - - return !_elementState.empty() && _elementState.back().depth == _depth ? _elementState.back().content : Content(Content::Mixed); -} - - -inline const XMLStreamParser::ElementEntry* XMLStreamParser::getElement() const -{ - return _elementState.empty() ? 0 : getElementImpl(); -} - - -template -T XMLStreamParser::attribute(const QName& qn, const T& dv) const -{ - if (const ElementEntry* e = getElement()) - { - AttributeMapType::const_iterator i(e->attributeMap.find(qn)); - - if (i != e->attributeMap.end()) - { - if (!i->second.handled) - { - i->second.handled = true; - e->attributesUnhandled--; - } - return ValueTraits < T > ::parse(i->second.value, *this); - } - } - - return dv; -} - - -template -T XMLStreamParser::element(const QName& qn, const T& dv) -{ - if (peek() == EV_START_ELEMENT && getQName() == qn) - { - next(); - return element(); - } - - return dv; -} - - -} } // namespace Poco::XML +} // namespace Poco::XML #endif // XML_XMLStreamParser_INCLUDED diff --git a/base/poco/XML/include/Poco/XML/XMLStreamParserException.h b/base/poco/XML/include/Poco/XML/XMLStreamParserException.h index b2ccedadb9d..034347df98d 100644 --- a/base/poco/XML/include/Poco/XML/XMLStreamParserException.h +++ b/base/poco/XML/include/Poco/XML/XMLStreamParserException.h @@ -21,38 +21,41 @@ #include "Poco/XML/XMLException.h" -namespace Poco { -namespace XML { - - -class XMLStreamParser; - - -class XML_API XMLStreamParserException: public Poco::XML::XMLException +namespace Poco +{ +namespace XML { -public: - XMLStreamParserException(const std::string& name, Poco::UInt64 line, Poco::UInt64 column, const std::string& description); - XMLStreamParserException(const XMLStreamParser&, const std::string& description); - virtual ~XMLStreamParserException() throw (); - - const char* name() const noexcept; - Poco::UInt64 line() const; - Poco::UInt64 column() const; - const std::string& description() const; - virtual const char* what() const throw (); - -private: - void init(); - - std::string _name; - Poco::UInt64 _line; - Poco::UInt64 _column; - std::string _description; - std::string _what; -}; -} } // namespace Poco::XML + class XMLStreamParser; + + + class XML_API XMLStreamParserException : public Poco::XML::XMLException + { + public: + XMLStreamParserException(const std::string & name, Poco::UInt64 line, Poco::UInt64 column, const std::string & description); + XMLStreamParserException(const XMLStreamParser &, const std::string & description); + virtual ~XMLStreamParserException() throw(); + + const char * name() const noexcept; + Poco::UInt64 line() const; + Poco::UInt64 column() const; + const std::string & description() const; + virtual const char * what() const throw(); + + private: + void init(); + + std::string _name; + Poco::UInt64 _line; + Poco::UInt64 _column; + std::string _description; + std::string _what; + }; + + +} +} // namespace Poco::XML #endif // XML_XMLStreamParserException_INCLUDED diff --git a/base/poco/XML/include/Poco/XML/XMLString.h b/base/poco/XML/include/Poco/XML/XMLString.h index 719fe7b8b6f..3b9c1d443a7 100644 --- a/base/poco/XML/include/Poco/XML/XMLString.h +++ b/base/poco/XML/include/Poco/XML/XMLString.h @@ -21,8 +21,10 @@ #include "Poco/XML/XML.h" -namespace Poco { -namespace XML { +namespace Poco +{ +namespace XML +{ // @@ -42,46 +44,47 @@ namespace XML { // #if defined(XML_UNICODE_WCHAR_T) - // Unicode - use wchar_t - using XMLChar = wchar_t; - using XMLString = std::wstring; + // Unicode - use wchar_t + using XMLChar = wchar_t; + using XMLString = std::wstring; - std::string fromXMLString(const XMLString& str); - /// Converts an XMLString into an UTF-8 encoded - /// string. - - XMLString toXMLString(const std::string& str); - /// Converts an UTF-8 encoded string into an - /// XMLString - - #define XML_LIT(lit) L##lit + std::string fromXMLString(const XMLString & str); + /// Converts an XMLString into an UTF-8 encoded + /// string. + + XMLString toXMLString(const std::string & str); + /// Converts an UTF-8 encoded string into an + /// XMLString + +# define XML_LIT(lit) L##lit #elif defined(XML_UNICODE) - // not supported - leave XMLString undefined + // not supported - leave XMLString undefined #else - // Characters are UTF-8 encoded - using XMLChar = char; - using XMLString = std::string; + // Characters are UTF-8 encoded + using XMLChar = char; + using XMLString = std::string; - inline const std::string& fromXMLString(const XMLString& str) - { - return str; - } + inline const std::string & fromXMLString(const XMLString & str) + { + return str; + } - inline const XMLString& toXMLString(const std::string& str) - { - return str; - } - - #define XML_LIT(lit) lit + inline const XMLString & toXMLString(const std::string & str) + { + return str; + } + +# define XML_LIT(lit) lit #endif -} } // namespace Poco::XML +} +} // namespace Poco::XML #endif // XML_XMLString_INCLUDED diff --git a/base/poco/XML/include/Poco/XML/XMLWriter.h b/base/poco/XML/include/Poco/XML/XMLWriter.h index 5f947ef1716..66b968fd2f5 100644 --- a/base/poco/XML/include/Poco/XML/XMLWriter.h +++ b/base/poco/XML/include/Poco/XML/XMLWriter.h @@ -18,358 +18,370 @@ #define XML_XMLWriter_INCLUDED -#include "Poco/XML/XML.h" -#include "Poco/SAX/ContentHandler.h" -#include "Poco/SAX/LexicalHandler.h" -#include "Poco/SAX/DTDHandler.h" -#include "Poco/SAX/NamespaceSupport.h" -#include "Poco/XML/XMLString.h" -#include "Poco/XML/XMLStream.h" -#include "Poco/XML/Name.h" -#include "Poco/TextEncoding.h" -#include "Poco/StreamConverter.h" -#include #include +#include +#include "Poco/SAX/ContentHandler.h" +#include "Poco/SAX/DTDHandler.h" +#include "Poco/SAX/LexicalHandler.h" +#include "Poco/SAX/NamespaceSupport.h" +#include "Poco/StreamConverter.h" +#include "Poco/TextEncoding.h" +#include "Poco/XML/Name.h" +#include "Poco/XML/XML.h" +#include "Poco/XML/XMLStream.h" +#include "Poco/XML/XMLString.h" -namespace Poco { -namespace XML { - - -class Locator; - - -class XML_API XMLWriter: public ContentHandler, public LexicalHandler, public DTDHandler - /// This class serializes SAX2 ContentHandler, LexicalHandler and - /// DTDHandler events back into a stream. - /// - /// Various consistency checks are performed on the written data - /// (i.e. there must be exactly one root element and every startElement() - /// must have a matching endElement()). - /// - /// The XMLWriter supports optional pretty-printing of the serialized XML. - /// Note, however, that pretty-printing XML data alters the - /// information set of the document being written, since in - /// XML all whitespace is potentially relevant to an application. - /// - /// The writer contains extensive support for XML Namespaces, so that a client - /// application does not have to keep track of prefixes and supply xmlns attributes. - /// - /// If the client does not provide namespace prefixes (either by specifying them - /// as part of the qualified name given to startElement(), or by calling - /// startPrefixMapping()), the XMLWriter automatically generates namespace - /// prefixes in the form ns1, ns2, etc. +namespace Poco { -public: - enum Options - { - CANONICAL = 0x00, - /// Do not write an XML declaration (default). - - CANONICAL_XML = 0x01, - /// Enables basic support for Canonical XML: - /// - do not write an XML declaration - /// - do not use special empty element syntax - /// - set the New Line character to NEWLINE_LF - /// - write namespace declarations and attributes - /// in canonical order - /// - use default namespace as much as possible - - WRITE_XML_DECLARATION = 0x02, - /// Write an XML declaration. - - PRETTY_PRINT = 0x04, - /// Pretty-print XML markup. - - PRETTY_PRINT_ATTRIBUTES = 0x08 - /// Write each attribute on a separate line. - /// PRETTY_PRINT must be specified as well. - }; - - XMLWriter(XMLByteOutputStream& str, int options); - /// Creates the XMLWriter and sets the specified options. - /// - /// The resulting stream will be UTF-8 encoded. - - XMLWriter(XMLByteOutputStream& str, int options, const std::string& encodingName, Poco::TextEncoding& textEncoding); - /// Creates the XMLWriter and sets the specified options. - /// - /// The encoding is reflected in the XML declaration. - /// The caller is responsible for that the given encodingName matches with - /// the given textEncoding. - - XMLWriter(XMLByteOutputStream& str, int options, const std::string& encodingName, Poco::TextEncoding* pTextEncoding); - /// Creates the XMLWriter and sets the specified options. - /// - /// The encoding is reflected in the XML declaration. - /// The caller is responsible for that the given encodingName matches with - /// the given textEncoding. - /// If pTextEncoding is null, the given encodingName is ignored and the - /// default UTF-8 encoding is used. - - ~XMLWriter(); - /// Destroys the XMLWriter. - - void setNewLine(const std::string& newLineCharacters); - /// Sets the line ending for the resulting XML file. - /// - /// Possible values are: - /// * NEWLINE_DEFAULT (whatever is appropriate for the current platform) - /// * NEWLINE_CRLF (Windows), - /// * NEWLINE_LF (Unix), - /// * NEWLINE_CR (Macintosh) - - const std::string& getNewLine() const; - /// Returns the line ending currently in use. - - void setIndent(const std::string& indent); - /// Sets the string used for one indentation step. - /// - /// The default is a single TAB character. - /// The given string should only contain TAB or SPACE - /// characters (e.g., a single TAB character, or - /// two to four SPACE characters). - - const std::string& getIndent() const; - /// Returns the string used for one indentation step. - - // ContentHandler - void setDocumentLocator(const Locator* loc); - /// Currently unused. - - void startDocument(); - /// Writes a generic XML declaration to the stream. - /// If a document type has been set (see SetDocumentType), - /// a DOCTYPE declaration is also written. - - void endDocument(); - /// Checks that all elements are closed and prints a final newline. - - void startFragment(); - /// Use this instead of StartDocument() if you want to write - /// a fragment rather than a document (no XML declaration and - /// more than one "root" element allowed). - - void endFragment(); - /// Checks that all elements are closed and prints a final newline. - - void startElement(const XMLString& namespaceURI, const XMLString& localName, const XMLString& qname, const Attributes& attributes); - /// Writes an XML start element tag. - /// - /// Namespaces are handled as follows. - /// 1. If a qname, but no namespaceURI and localName are given, the qname is taken as element name. - /// 2. If a namespaceURI and a localName, but no qname is given, and the given namespaceURI has been - /// declared earlier, the namespace prefix for the given namespaceURI together with the localName - /// is taken as element name. If the namespace has not been declared, a prefix in the form - /// "ns1", "ns2", etc. is generated and the namespace is declared with the generated prefix. - /// 3. If all three are given, and the namespace given in namespaceURI has not been declared, it is declared now. - /// Otherwise, see 2. - - void startElement(const XMLString& namespaceURI, const XMLString& localName, const XMLString& qname); - /// Writes an XML start element tag with no attributes. - /// See the other startElement() method for more information. - - void endElement(const XMLString& namespaceURI, const XMLString& localName, const XMLString& qname); - /// Writes an XML end element tag. - /// - /// Throws an exception if the name of doesn't match the - /// one of the most recent startElement(). - - void emptyElement(const XMLString& namespaceURI, const XMLString& localName, const XMLString& qname); - /// Writes an empty XML element tag (). - - void emptyElement(const XMLString& namespaceURI, const XMLString& localName, const XMLString& qname, const Attributes& attributes); - /// Writes an empty XML element tag with the given attributes (). - - void characters(const XMLChar ch[], int start, int length); - /// Writes XML character data. Quotes, ampersand's, less-than and - /// greater-than signs are escaped, unless a CDATA section - /// has been opened by calling startCDATA(). - /// - /// The characters must be encoded in UTF-8 (if XMLChar is char) or - /// UTF-16 (if XMLChar is wchar_t). - - void characters(const XMLString& str); - /// Writes XML character data. Quotes, ampersand's, less-than and - /// greater-than signs are escaped, unless a CDATA section - /// has been opened by calling startCDATA(). - /// - /// The characters must be encoded in UTF-8 (if XMLChar is char) or - /// UTF-16 (if XMLChar is wchar_t). - - void rawCharacters(const XMLString& str); - /// Writes the characters in the given string as they are. - /// The caller is responsible for escaping characters as - /// necessary to produce valid XML. - /// - /// The characters must be encoded in UTF-8 (if XMLChar is char) or - /// UTF-16 (if XMLChar is wchar_t). - - void ignorableWhitespace(const XMLChar ch[], int start, int length); - /// Writes whitespace characters by simply passing them to - /// characters(). - - void processingInstruction(const XMLString& target, const XMLString& data); - /// Writes a processing instruction. - - void startPrefixMapping(const XMLString& prefix, const XMLString& namespaceURI); - /// Begin the scope of a prefix-URI Namespace mapping. - /// A namespace declaration is written with the next element. - - void endPrefixMapping(const XMLString& prefix); - /// End the scope of a prefix-URI mapping. - - void skippedEntity(const XMLString& name); - /// Does nothing. - - void dataElement(const XMLString& namespaceURI, const XMLString& localName, const XMLString& qname, const XMLString& data, - const XMLString& attr1 = XMLString(), const XMLString& value1 = XMLString(), - const XMLString& attr2 = XMLString(), const XMLString& value2 = XMLString(), - const XMLString& attr3 = XMLString(), const XMLString& value3 = XMLString()); - /// Writes a data element in the form data. - - // LexicalHandler - void startCDATA(); - /// Writes the string that ends a CDATA section. - - void comment(const XMLChar ch[], int start, int length); - /// Writes a comment. - - void startDTD(const XMLString& name, const XMLString& publicId, const XMLString& systemId); - /// Writes a DTD declaration. - - void endDTD(); - /// Writes the closing characters of a DTD declaration. - - void startEntity(const XMLString& name); - /// Does nothing. - - void endEntity(const XMLString& name); - /// Does nothing. - - // DTDHandler - void notationDecl(const XMLString& name, const XMLString* publicId, const XMLString* systemId); - void unparsedEntityDecl(const XMLString& name, const XMLString* publicId, const XMLString& systemId, const XMLString& notationName); - - static const std::string NEWLINE_DEFAULT; - static const std::string NEWLINE_CR; - static const std::string NEWLINE_CRLF; - static const std::string NEWLINE_LF; - - // Namespace support. - XMLString uniquePrefix(); - /// Creates and returns a unique namespace prefix that - /// can be used with startPrefixMapping(). - - bool isNamespaceMapped(const XMLString& namespc) const; - /// Returns true if the given namespace has been mapped - /// to a prefix in the current element or its ancestors. - - // Misc. - int depth() const; - /// Return the number of nested XML elements. - /// - /// Will be -1 if no document or fragment has been started, - /// 0 if the document or fragment has been started, - /// 1 if the document element has been written and - /// > 1 for every element nested within the document element. - -protected: - typedef std::map AttributeMap; - typedef std::map> CanonicalAttributeMap; - - void writeStartElement(const XMLString& namespaceURI, const XMLString& localName, const XMLString& qname, const Attributes& attributes); - void writeCanonicalStartElement(const XMLString& namespaceURI, const XMLString& localName, const XMLString& qname, const Attributes& attributes); - void writeEndElement(const XMLString& namespaceURI, const XMLString& localName, const XMLString& qname); - void writeMarkup(const std::string& str) const; - void writeXML(const XMLString& str) const; - void writeXML(XMLChar ch) const; - void writeNewLine() const; - void writeIndent() const; - void writeIndent(int indent) const; - void writeName(const XMLString& prefix, const XMLString& localName); - void writeXMLDeclaration(); - void closeStartTag(); - void declareNamespaces(const XMLString& namespaceURI, const XMLString& localName, const XMLString& qname, const Attributes& attributes); - void declareAttributeNamespaces(const Attributes& attributes); - void addNamespaceAttributes(AttributeMap& attributeMap); - void addNamespaceAttributes(CanonicalAttributeMap& attributeMap); - void addAttributes(AttributeMap& attributeMap, const Attributes& attributes, const XMLString& elementNamespaceURI); - void addAttributes(CanonicalAttributeMap& attributeMap, const Attributes& attributes, const XMLString& elementNamespaceURI); - void writeAttributes(const AttributeMap& attributeMap); - void writeAttributes(const CanonicalAttributeMap& attributeMap); - void prettyPrint() const; - static std::string nameToString(const XMLString& localName, const XMLString& qname); - -private: - struct Namespace - { - Namespace(const XMLString& thePrefix, const XMLString& theNamespaceURI): - prefix(thePrefix), - namespaceURI(theNamespaceURI) - { - } - - XMLString prefix; - XMLString namespaceURI; - }; - typedef std::vector ElementStack; - - Poco::OutputStreamConverter* _pTextConverter; - Poco::TextEncoding* _pInEncoding; - Poco::TextEncoding* _pOutEncoding; - int _options; - std::string _encoding; - std::string _newLine; - int _depth; - int _elementCount; - bool _inFragment; - bool _inCDATA; - bool _inDTD; - bool _inInternalDTD; - bool _contentWritten; - bool _unclosedStartTag; - ElementStack _elementStack; - NamespaceSupport _namespaces; - int _prefix; - bool _nsContextPushed; - std::string _indent; - - static const std::string MARKUP_QUOTENC; - static const std::string MARKUP_AMPENC; - static const std::string MARKUP_LTENC; - static const std::string MARKUP_GTENC; - static const std::string MARKUP_TABENC; - static const std::string MARKUP_CRENC; - static const std::string MARKUP_LFENC; - static const std::string MARKUP_LT; - static const std::string MARKUP_GT; - static const std::string MARKUP_SLASHGT; - static const std::string MARKUP_LTSLASH; - static const std::string MARKUP_COLON; - static const std::string MARKUP_EQQUOT; - static const std::string MARKUP_QUOT; - static const std::string MARKUP_SPACE; - static const std::string MARKUP_TAB; - static const std::string MARKUP_BEGIN_CDATA; - static const std::string MARKUP_END_CDATA; -}; - - -// -// inlines -// -inline int XMLWriter::depth() const +namespace XML { - return _depth; + + + class Locator; + + + class XML_API XMLWriter : public ContentHandler, public LexicalHandler, public DTDHandler + /// This class serializes SAX2 ContentHandler, LexicalHandler and + /// DTDHandler events back into a stream. + /// + /// Various consistency checks are performed on the written data + /// (i.e. there must be exactly one root element and every startElement() + /// must have a matching endElement()). + /// + /// The XMLWriter supports optional pretty-printing of the serialized XML. + /// Note, however, that pretty-printing XML data alters the + /// information set of the document being written, since in + /// XML all whitespace is potentially relevant to an application. + /// + /// The writer contains extensive support for XML Namespaces, so that a client + /// application does not have to keep track of prefixes and supply xmlns attributes. + /// + /// If the client does not provide namespace prefixes (either by specifying them + /// as part of the qualified name given to startElement(), or by calling + /// startPrefixMapping()), the XMLWriter automatically generates namespace + /// prefixes in the form ns1, ns2, etc. + { + public: + enum Options + { + CANONICAL = 0x00, + /// Do not write an XML declaration (default). + + CANONICAL_XML = 0x01, + /// Enables basic support for Canonical XML: + /// - do not write an XML declaration + /// - do not use special empty element syntax + /// - set the New Line character to NEWLINE_LF + /// - write namespace declarations and attributes + /// in canonical order + /// - use default namespace as much as possible + + WRITE_XML_DECLARATION = 0x02, + /// Write an XML declaration. + + PRETTY_PRINT = 0x04, + /// Pretty-print XML markup. + + PRETTY_PRINT_ATTRIBUTES = 0x08 + /// Write each attribute on a separate line. + /// PRETTY_PRINT must be specified as well. + }; + + XMLWriter(XMLByteOutputStream & str, int options); + /// Creates the XMLWriter and sets the specified options. + /// + /// The resulting stream will be UTF-8 encoded. + + XMLWriter(XMLByteOutputStream & str, int options, const std::string & encodingName, Poco::TextEncoding & textEncoding); + /// Creates the XMLWriter and sets the specified options. + /// + /// The encoding is reflected in the XML declaration. + /// The caller is responsible for that the given encodingName matches with + /// the given textEncoding. + + XMLWriter(XMLByteOutputStream & str, int options, const std::string & encodingName, Poco::TextEncoding * pTextEncoding); + /// Creates the XMLWriter and sets the specified options. + /// + /// The encoding is reflected in the XML declaration. + /// The caller is responsible for that the given encodingName matches with + /// the given textEncoding. + /// If pTextEncoding is null, the given encodingName is ignored and the + /// default UTF-8 encoding is used. + + ~XMLWriter(); + /// Destroys the XMLWriter. + + void setNewLine(const std::string & newLineCharacters); + /// Sets the line ending for the resulting XML file. + /// + /// Possible values are: + /// * NEWLINE_DEFAULT (whatever is appropriate for the current platform) + /// * NEWLINE_CRLF (Windows), + /// * NEWLINE_LF (Unix), + /// * NEWLINE_CR (Macintosh) + + const std::string & getNewLine() const; + /// Returns the line ending currently in use. + + void setIndent(const std::string & indent); + /// Sets the string used for one indentation step. + /// + /// The default is a single TAB character. + /// The given string should only contain TAB or SPACE + /// characters (e.g., a single TAB character, or + /// two to four SPACE characters). + + const std::string & getIndent() const; + /// Returns the string used for one indentation step. + + // ContentHandler + void setDocumentLocator(const Locator * loc); + /// Currently unused. + + void startDocument(); + /// Writes a generic XML declaration to the stream. + /// If a document type has been set (see SetDocumentType), + /// a DOCTYPE declaration is also written. + + void endDocument(); + /// Checks that all elements are closed and prints a final newline. + + void startFragment(); + /// Use this instead of StartDocument() if you want to write + /// a fragment rather than a document (no XML declaration and + /// more than one "root" element allowed). + + void endFragment(); + /// Checks that all elements are closed and prints a final newline. + + void + startElement(const XMLString & namespaceURI, const XMLString & localName, const XMLString & qname, const Attributes & attributes); + /// Writes an XML start element tag. + /// + /// Namespaces are handled as follows. + /// 1. If a qname, but no namespaceURI and localName are given, the qname is taken as element name. + /// 2. If a namespaceURI and a localName, but no qname is given, and the given namespaceURI has been + /// declared earlier, the namespace prefix for the given namespaceURI together with the localName + /// is taken as element name. If the namespace has not been declared, a prefix in the form + /// "ns1", "ns2", etc. is generated and the namespace is declared with the generated prefix. + /// 3. If all three are given, and the namespace given in namespaceURI has not been declared, it is declared now. + /// Otherwise, see 2. + + void startElement(const XMLString & namespaceURI, const XMLString & localName, const XMLString & qname); + /// Writes an XML start element tag with no attributes. + /// See the other startElement() method for more information. + + void endElement(const XMLString & namespaceURI, const XMLString & localName, const XMLString & qname); + /// Writes an XML end element tag. + /// + /// Throws an exception if the name of doesn't match the + /// one of the most recent startElement(). + + void emptyElement(const XMLString & namespaceURI, const XMLString & localName, const XMLString & qname); + /// Writes an empty XML element tag (). + + void + emptyElement(const XMLString & namespaceURI, const XMLString & localName, const XMLString & qname, const Attributes & attributes); + /// Writes an empty XML element tag with the given attributes (). + + void characters(const XMLChar ch[], int start, int length); + /// Writes XML character data. Quotes, ampersand's, less-than and + /// greater-than signs are escaped, unless a CDATA section + /// has been opened by calling startCDATA(). + /// + /// The characters must be encoded in UTF-8 (if XMLChar is char) or + /// UTF-16 (if XMLChar is wchar_t). + + void characters(const XMLString & str); + /// Writes XML character data. Quotes, ampersand's, less-than and + /// greater-than signs are escaped, unless a CDATA section + /// has been opened by calling startCDATA(). + /// + /// The characters must be encoded in UTF-8 (if XMLChar is char) or + /// UTF-16 (if XMLChar is wchar_t). + + void rawCharacters(const XMLString & str); + /// Writes the characters in the given string as they are. + /// The caller is responsible for escaping characters as + /// necessary to produce valid XML. + /// + /// The characters must be encoded in UTF-8 (if XMLChar is char) or + /// UTF-16 (if XMLChar is wchar_t). + + void ignorableWhitespace(const XMLChar ch[], int start, int length); + /// Writes whitespace characters by simply passing them to + /// characters(). + + void processingInstruction(const XMLString & target, const XMLString & data); + /// Writes a processing instruction. + + void startPrefixMapping(const XMLString & prefix, const XMLString & namespaceURI); + /// Begin the scope of a prefix-URI Namespace mapping. + /// A namespace declaration is written with the next element. + + void endPrefixMapping(const XMLString & prefix); + /// End the scope of a prefix-URI mapping. + + void skippedEntity(const XMLString & name); + /// Does nothing. + + void dataElement( + const XMLString & namespaceURI, + const XMLString & localName, + const XMLString & qname, + const XMLString & data, + const XMLString & attr1 = XMLString(), + const XMLString & value1 = XMLString(), + const XMLString & attr2 = XMLString(), + const XMLString & value2 = XMLString(), + const XMLString & attr3 = XMLString(), + const XMLString & value3 = XMLString()); + /// Writes a data element in the form data. + + // LexicalHandler + void startCDATA(); + /// Writes the string that ends a CDATA section. + + void comment(const XMLChar ch[], int start, int length); + /// Writes a comment. + + void startDTD(const XMLString & name, const XMLString & publicId, const XMLString & systemId); + /// Writes a DTD declaration. + + void endDTD(); + /// Writes the closing characters of a DTD declaration. + + void startEntity(const XMLString & name); + /// Does nothing. + + void endEntity(const XMLString & name); + /// Does nothing. + + // DTDHandler + void notationDecl(const XMLString & name, const XMLString * publicId, const XMLString * systemId); + void + unparsedEntityDecl(const XMLString & name, const XMLString * publicId, const XMLString & systemId, const XMLString & notationName); + + static const std::string NEWLINE_DEFAULT; + static const std::string NEWLINE_CR; + static const std::string NEWLINE_CRLF; + static const std::string NEWLINE_LF; + + // Namespace support. + XMLString uniquePrefix(); + /// Creates and returns a unique namespace prefix that + /// can be used with startPrefixMapping(). + + bool isNamespaceMapped(const XMLString & namespc) const; + /// Returns true if the given namespace has been mapped + /// to a prefix in the current element or its ancestors. + + // Misc. + int depth() const; + /// Return the number of nested XML elements. + /// + /// Will be -1 if no document or fragment has been started, + /// 0 if the document or fragment has been started, + /// 1 if the document element has been written and + /// > 1 for every element nested within the document element. + + protected: + typedef std::map AttributeMap; + typedef std::map> CanonicalAttributeMap; + + void writeStartElement( + const XMLString & namespaceURI, const XMLString & localName, const XMLString & qname, const Attributes & attributes); + void writeCanonicalStartElement( + const XMLString & namespaceURI, const XMLString & localName, const XMLString & qname, const Attributes & attributes); + void writeEndElement(const XMLString & namespaceURI, const XMLString & localName, const XMLString & qname); + void writeMarkup(const std::string & str) const; + void writeXML(const XMLString & str) const; + void writeXML(XMLChar ch) const; + void writeNewLine() const; + void writeIndent() const; + void writeIndent(int indent) const; + void writeName(const XMLString & prefix, const XMLString & localName); + void writeXMLDeclaration(); + void closeStartTag(); + void declareNamespaces( + const XMLString & namespaceURI, const XMLString & localName, const XMLString & qname, const Attributes & attributes); + void declareAttributeNamespaces(const Attributes & attributes); + void addNamespaceAttributes(AttributeMap & attributeMap); + void addNamespaceAttributes(CanonicalAttributeMap & attributeMap); + void addAttributes(AttributeMap & attributeMap, const Attributes & attributes, const XMLString & elementNamespaceURI); + void addAttributes(CanonicalAttributeMap & attributeMap, const Attributes & attributes, const XMLString & elementNamespaceURI); + void writeAttributes(const AttributeMap & attributeMap); + void writeAttributes(const CanonicalAttributeMap & attributeMap); + void prettyPrint() const; + static std::string nameToString(const XMLString & localName, const XMLString & qname); + + private: + struct Namespace + { + Namespace(const XMLString & thePrefix, const XMLString & theNamespaceURI) : prefix(thePrefix), namespaceURI(theNamespaceURI) { } + + XMLString prefix; + XMLString namespaceURI; + }; + typedef std::vector ElementStack; + + Poco::OutputStreamConverter * _pTextConverter; + Poco::TextEncoding * _pInEncoding; + Poco::TextEncoding * _pOutEncoding; + int _options; + std::string _encoding; + std::string _newLine; + int _depth; + int _elementCount; + bool _inFragment; + bool _inCDATA; + bool _inDTD; + bool _inInternalDTD; + bool _contentWritten; + bool _unclosedStartTag; + ElementStack _elementStack; + NamespaceSupport _namespaces; + int _prefix; + bool _nsContextPushed; + std::string _indent; + + static const std::string MARKUP_QUOTENC; + static const std::string MARKUP_AMPENC; + static const std::string MARKUP_LTENC; + static const std::string MARKUP_GTENC; + static const std::string MARKUP_TABENC; + static const std::string MARKUP_CRENC; + static const std::string MARKUP_LFENC; + static const std::string MARKUP_LT; + static const std::string MARKUP_GT; + static const std::string MARKUP_SLASHGT; + static const std::string MARKUP_LTSLASH; + static const std::string MARKUP_COLON; + static const std::string MARKUP_EQQUOT; + static const std::string MARKUP_QUOT; + static const std::string MARKUP_SPACE; + static const std::string MARKUP_TAB; + static const std::string MARKUP_BEGIN_CDATA; + static const std::string MARKUP_END_CDATA; + }; + + + // + // inlines + // + inline int XMLWriter::depth() const + { + return _depth; + } + + } - - -} } // namespace Poco::XML +} // namespace Poco::XML #endif // XML_XMLWriter_INCLUDED diff --git a/base/poco/XML/include/Poco/XML/expat.h b/base/poco/XML/include/Poco/XML/expat.h index 93a5d19d53f..db2eedb3f07 100644 --- a/base/poco/XML/include/Poco/XML/expat.h +++ b/base/poco/XML/include/Poco/XML/expat.h @@ -49,7 +49,7 @@ extern "C" { #endif struct XML_ParserStruct; -typedef struct XML_ParserStruct *XML_Parser; +typedef struct XML_ParserStruct * XML_Parser; typedef unsigned char XML_Bool; #define XML_TRUE ((XML_Bool)1) @@ -68,82 +68,86 @@ typedef unsigned char XML_Bool; Otherwise, the #define hackery is quite ugly and would have been dropped. */ -enum XML_Status { - XML_STATUS_ERROR = 0, +enum XML_Status +{ + XML_STATUS_ERROR = 0, #define XML_STATUS_ERROR XML_STATUS_ERROR - XML_STATUS_OK = 1, + XML_STATUS_OK = 1, #define XML_STATUS_OK XML_STATUS_OK - XML_STATUS_SUSPENDED = 2 + XML_STATUS_SUSPENDED = 2 #define XML_STATUS_SUSPENDED XML_STATUS_SUSPENDED }; -enum XML_Error { - XML_ERROR_NONE, - XML_ERROR_NO_MEMORY, - XML_ERROR_SYNTAX, - XML_ERROR_NO_ELEMENTS, - XML_ERROR_INVALID_TOKEN, - XML_ERROR_UNCLOSED_TOKEN, - XML_ERROR_PARTIAL_CHAR, - XML_ERROR_TAG_MISMATCH, - XML_ERROR_DUPLICATE_ATTRIBUTE, - XML_ERROR_JUNK_AFTER_DOC_ELEMENT, - XML_ERROR_PARAM_ENTITY_REF, - XML_ERROR_UNDEFINED_ENTITY, - XML_ERROR_RECURSIVE_ENTITY_REF, - XML_ERROR_ASYNC_ENTITY, - XML_ERROR_BAD_CHAR_REF, - XML_ERROR_BINARY_ENTITY_REF, - XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF, - XML_ERROR_MISPLACED_XML_PI, - XML_ERROR_UNKNOWN_ENCODING, - XML_ERROR_INCORRECT_ENCODING, - XML_ERROR_UNCLOSED_CDATA_SECTION, - XML_ERROR_EXTERNAL_ENTITY_HANDLING, - XML_ERROR_NOT_STANDALONE, - XML_ERROR_UNEXPECTED_STATE, - XML_ERROR_ENTITY_DECLARED_IN_PE, - XML_ERROR_FEATURE_REQUIRES_XML_DTD, - XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING, - /* Added in 1.95.7. */ - XML_ERROR_UNBOUND_PREFIX, - /* Added in 1.95.8. */ - XML_ERROR_UNDECLARING_PREFIX, - XML_ERROR_INCOMPLETE_PE, - XML_ERROR_XML_DECL, - XML_ERROR_TEXT_DECL, - XML_ERROR_PUBLICID, - XML_ERROR_SUSPENDED, - XML_ERROR_NOT_SUSPENDED, - XML_ERROR_ABORTED, - XML_ERROR_FINISHED, - XML_ERROR_SUSPEND_PE, - /* Added in 2.0. */ - XML_ERROR_RESERVED_PREFIX_XML, - XML_ERROR_RESERVED_PREFIX_XMLNS, - XML_ERROR_RESERVED_NAMESPACE_URI, - /* Added in 2.2.1. */ - XML_ERROR_INVALID_ARGUMENT, - /* Added in 2.3.0. */ - XML_ERROR_NO_BUFFER, - /* Added in 2.4.0. */ - XML_ERROR_AMPLIFICATION_LIMIT_BREACH +enum XML_Error +{ + XML_ERROR_NONE, + XML_ERROR_NO_MEMORY, + XML_ERROR_SYNTAX, + XML_ERROR_NO_ELEMENTS, + XML_ERROR_INVALID_TOKEN, + XML_ERROR_UNCLOSED_TOKEN, + XML_ERROR_PARTIAL_CHAR, + XML_ERROR_TAG_MISMATCH, + XML_ERROR_DUPLICATE_ATTRIBUTE, + XML_ERROR_JUNK_AFTER_DOC_ELEMENT, + XML_ERROR_PARAM_ENTITY_REF, + XML_ERROR_UNDEFINED_ENTITY, + XML_ERROR_RECURSIVE_ENTITY_REF, + XML_ERROR_ASYNC_ENTITY, + XML_ERROR_BAD_CHAR_REF, + XML_ERROR_BINARY_ENTITY_REF, + XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF, + XML_ERROR_MISPLACED_XML_PI, + XML_ERROR_UNKNOWN_ENCODING, + XML_ERROR_INCORRECT_ENCODING, + XML_ERROR_UNCLOSED_CDATA_SECTION, + XML_ERROR_EXTERNAL_ENTITY_HANDLING, + XML_ERROR_NOT_STANDALONE, + XML_ERROR_UNEXPECTED_STATE, + XML_ERROR_ENTITY_DECLARED_IN_PE, + XML_ERROR_FEATURE_REQUIRES_XML_DTD, + XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING, + /* Added in 1.95.7. */ + XML_ERROR_UNBOUND_PREFIX, + /* Added in 1.95.8. */ + XML_ERROR_UNDECLARING_PREFIX, + XML_ERROR_INCOMPLETE_PE, + XML_ERROR_XML_DECL, + XML_ERROR_TEXT_DECL, + XML_ERROR_PUBLICID, + XML_ERROR_SUSPENDED, + XML_ERROR_NOT_SUSPENDED, + XML_ERROR_ABORTED, + XML_ERROR_FINISHED, + XML_ERROR_SUSPEND_PE, + /* Added in 2.0. */ + XML_ERROR_RESERVED_PREFIX_XML, + XML_ERROR_RESERVED_PREFIX_XMLNS, + XML_ERROR_RESERVED_NAMESPACE_URI, + /* Added in 2.2.1. */ + XML_ERROR_INVALID_ARGUMENT, + /* Added in 2.3.0. */ + XML_ERROR_NO_BUFFER, + /* Added in 2.4.0. */ + XML_ERROR_AMPLIFICATION_LIMIT_BREACH }; -enum XML_Content_Type { - XML_CTYPE_EMPTY = 1, - XML_CTYPE_ANY, - XML_CTYPE_MIXED, - XML_CTYPE_NAME, - XML_CTYPE_CHOICE, - XML_CTYPE_SEQ +enum XML_Content_Type +{ + XML_CTYPE_EMPTY = 1, + XML_CTYPE_ANY, + XML_CTYPE_MIXED, + XML_CTYPE_NAME, + XML_CTYPE_CHOICE, + XML_CTYPE_SEQ }; -enum XML_Content_Quant { - XML_CQUANT_NONE, - XML_CQUANT_OPT, - XML_CQUANT_REP, - XML_CQUANT_PLUS +enum XML_Content_Quant +{ + XML_CQUANT_NONE, + XML_CQUANT_OPT, + XML_CQUANT_REP, + XML_CQUANT_PLUS }; /* If type == XML_CTYPE_EMPTY or XML_CTYPE_ANY, then quant will be @@ -166,12 +170,13 @@ enum XML_Content_Quant { typedef struct XML_cp XML_Content; -struct XML_cp { - enum XML_Content_Type type; - enum XML_Content_Quant quant; - XML_Char *name; - unsigned int numchildren; - XML_Content *children; +struct XML_cp +{ + enum XML_Content_Type type; + enum XML_Content_Quant quant; + XML_Char * name; + unsigned int numchildren; + XML_Content * children; }; /* This is called for an element declaration. See above for @@ -180,9 +185,7 @@ struct XML_cp { There is no need to free the model from the handler, it can be kept around and freed at a later stage. */ -typedef void(XMLCALL *XML_ElementDeclHandler)(void *userData, - const XML_Char *name, - XML_Content *model); +typedef void(XMLCALL * XML_ElementDeclHandler)(void * userData, const XML_Char * name, XML_Content * model); XMLPARSEAPI(void) XML_SetElementDeclHandler(XML_Parser parser, XML_ElementDeclHandler eldecl); @@ -195,9 +198,8 @@ XML_SetElementDeclHandler(XML_Parser parser, XML_ElementDeclHandler eldecl); value will be NULL in the case of "#REQUIRED". If "isrequired" is true and default is non-NULL, then this is a "#FIXED" default. */ -typedef void(XMLCALL *XML_AttlistDeclHandler)( - void *userData, const XML_Char *elname, const XML_Char *attname, - const XML_Char *att_type, const XML_Char *dflt, int isrequired); +typedef void(XMLCALL * XML_AttlistDeclHandler)( + void * userData, const XML_Char * elname, const XML_Char * attname, const XML_Char * att_type, const XML_Char * dflt, int isrequired); XMLPARSEAPI(void) XML_SetAttlistDeclHandler(XML_Parser parser, XML_AttlistDeclHandler attdecl); @@ -210,25 +212,23 @@ XML_SetAttlistDeclHandler(XML_Parser parser, XML_AttlistDeclHandler attdecl); was no standalone parameter in the declaration, that it was given as no, or that it was given as yes. */ -typedef void(XMLCALL *XML_XmlDeclHandler)(void *userData, - const XML_Char *version, - const XML_Char *encoding, - int standalone); +typedef void(XMLCALL * XML_XmlDeclHandler)(void * userData, const XML_Char * version, const XML_Char * encoding, int standalone); XMLPARSEAPI(void) XML_SetXmlDeclHandler(XML_Parser parser, XML_XmlDeclHandler xmldecl); -typedef struct { - void *(*malloc_fcn)(size_t size); - void *(*realloc_fcn)(void *ptr, size_t size); - void (*free_fcn)(void *ptr); +typedef struct +{ + void * (*malloc_fcn)(size_t size); + void * (*realloc_fcn)(void * ptr, size_t size); + void (*free_fcn)(void * ptr); } XML_Memory_Handling_Suite; /* Constructs a new parser; encoding is the encoding specified by the external protocol or NULL if there is none specified. */ XMLPARSEAPI(XML_Parser) -XML_ParserCreate(const XML_Char *encoding); +XML_ParserCreate(const XML_Char * encoding); /* Constructs a new parser and namespace processor. Element type names and attribute names that belong to a namespace will be @@ -253,7 +253,7 @@ XML_ParserCreate(const XML_Char *encoding); be ready to receive namespace URIs containing non-URI characters. */ XMLPARSEAPI(XML_Parser) -XML_ParserCreateNS(const XML_Char *encoding, XML_Char namespaceSeparator); +XML_ParserCreateNS(const XML_Char * encoding, XML_Char namespaceSeparator); /* Constructs a new parser using the memory management suite referred to by memsuite. If memsuite is NULL, then use the standard library memory @@ -265,9 +265,7 @@ XML_ParserCreateNS(const XML_Char *encoding, XML_Char namespaceSeparator); the given suite. */ XMLPARSEAPI(XML_Parser) -XML_ParserCreate_MM(const XML_Char *encoding, - const XML_Memory_Handling_Suite *memsuite, - const XML_Char *namespaceSeparator); +XML_ParserCreate_MM(const XML_Char * encoding, const XML_Memory_Handling_Suite * memsuite, const XML_Char * namespaceSeparator); /* Prepare a parser object to be re-used. This is particularly valuable when memory allocation overhead is disproportionately high, @@ -279,32 +277,26 @@ XML_ParserCreate_MM(const XML_Char *encoding, Added in Expat 1.95.3. */ XMLPARSEAPI(XML_Bool) -XML_ParserReset(XML_Parser parser, const XML_Char *encoding); +XML_ParserReset(XML_Parser parser, const XML_Char * encoding); /* atts is array of name/value pairs, terminated by 0; names and values are 0 terminated. */ -typedef void(XMLCALL *XML_StartElementHandler)(void *userData, - const XML_Char *name, - const XML_Char **atts); +typedef void(XMLCALL * XML_StartElementHandler)(void * userData, const XML_Char * name, const XML_Char ** atts); -typedef void(XMLCALL *XML_EndElementHandler)(void *userData, - const XML_Char *name); +typedef void(XMLCALL * XML_EndElementHandler)(void * userData, const XML_Char * name); /* s is not 0 terminated. */ -typedef void(XMLCALL *XML_CharacterDataHandler)(void *userData, - const XML_Char *s, int len); +typedef void(XMLCALL * XML_CharacterDataHandler)(void * userData, const XML_Char * s, int len); /* target and data are 0 terminated */ -typedef void(XMLCALL *XML_ProcessingInstructionHandler)(void *userData, - const XML_Char *target, - const XML_Char *data); +typedef void(XMLCALL * XML_ProcessingInstructionHandler)(void * userData, const XML_Char * target, const XML_Char * data); /* data is 0 terminated */ -typedef void(XMLCALL *XML_CommentHandler)(void *userData, const XML_Char *data); +typedef void(XMLCALL * XML_CommentHandler)(void * userData, const XML_Char * data); -typedef void(XMLCALL *XML_StartCdataSectionHandler)(void *userData); -typedef void(XMLCALL *XML_EndCdataSectionHandler)(void *userData); +typedef void(XMLCALL * XML_StartCdataSectionHandler)(void * userData); +typedef void(XMLCALL * XML_EndCdataSectionHandler)(void * userData); /* This is called for any characters in the XML document for which there is no applicable handler. This includes both characters that @@ -319,23 +311,19 @@ typedef void(XMLCALL *XML_EndCdataSectionHandler)(void *userData); default handler: for example, a comment might be split between multiple calls. */ -typedef void(XMLCALL *XML_DefaultHandler)(void *userData, const XML_Char *s, - int len); +typedef void(XMLCALL * XML_DefaultHandler)(void * userData, const XML_Char * s, int len); /* This is called for the start of the DOCTYPE declaration, before any DTD or internal subset is parsed. */ -typedef void(XMLCALL *XML_StartDoctypeDeclHandler)(void *userData, - const XML_Char *doctypeName, - const XML_Char *sysid, - const XML_Char *pubid, - int has_internal_subset); +typedef void(XMLCALL * XML_StartDoctypeDeclHandler)( + void * userData, const XML_Char * doctypeName, const XML_Char * sysid, const XML_Char * pubid, int has_internal_subset); /* This is called for the end of the DOCTYPE declaration when the closing > is encountered, but after processing any external subset. */ -typedef void(XMLCALL *XML_EndDoctypeDeclHandler)(void *userData); +typedef void(XMLCALL * XML_EndDoctypeDeclHandler)(void * userData); /* This is called for entity declarations. The is_parameter_entity argument will be non-zero if the entity is a parameter entity, zero @@ -355,11 +343,16 @@ typedef void(XMLCALL *XML_EndDoctypeDeclHandler)(void *userData); Note that is_parameter_entity can't be changed to XML_Bool, since that would break binary compatibility. */ -typedef void(XMLCALL *XML_EntityDeclHandler)( - 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); +typedef void(XMLCALL * XML_EntityDeclHandler)( + 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); XMLPARSEAPI(void) XML_SetEntityDeclHandler(XML_Parser parser, XML_EntityDeclHandler handler); @@ -373,20 +366,20 @@ XML_SetEntityDeclHandler(XML_Parser parser, XML_EntityDeclHandler handler); entityName, systemId and notationName arguments will never be NULL. The other arguments may be. */ -typedef void(XMLCALL *XML_UnparsedEntityDeclHandler)( - void *userData, const XML_Char *entityName, const XML_Char *base, - const XML_Char *systemId, const XML_Char *publicId, - const XML_Char *notationName); +typedef void(XMLCALL * XML_UnparsedEntityDeclHandler)( + void * userData, + const XML_Char * entityName, + const XML_Char * base, + const XML_Char * systemId, + const XML_Char * publicId, + const XML_Char * notationName); /* This is called for a declaration of notation. The base argument is whatever was set by XML_SetBase. The notationName will never be NULL. The other arguments can be. */ -typedef void(XMLCALL *XML_NotationDeclHandler)(void *userData, - const XML_Char *notationName, - const XML_Char *base, - const XML_Char *systemId, - const XML_Char *publicId); +typedef void(XMLCALL * XML_NotationDeclHandler)( + void * userData, const XML_Char * notationName, const XML_Char * base, const XML_Char * systemId, const XML_Char * publicId); /* When namespace processing is enabled, these are called once for each namespace declaration. The call to the start and end element @@ -394,12 +387,9 @@ typedef void(XMLCALL *XML_NotationDeclHandler)(void *userData, declaration handlers. For an xmlns attribute, prefix will be NULL. For an xmlns="" attribute, uri will be NULL. */ -typedef void(XMLCALL *XML_StartNamespaceDeclHandler)(void *userData, - const XML_Char *prefix, - const XML_Char *uri); +typedef void(XMLCALL * XML_StartNamespaceDeclHandler)(void * userData, const XML_Char * prefix, const XML_Char * uri); -typedef void(XMLCALL *XML_EndNamespaceDeclHandler)(void *userData, - const XML_Char *prefix); +typedef void(XMLCALL * XML_EndNamespaceDeclHandler)(void * userData, const XML_Char * prefix); /* This is called if the document is not standalone, that is, it has an external subset or a reference to a parameter entity, but does not @@ -410,7 +400,7 @@ typedef void(XMLCALL *XML_EndNamespaceDeclHandler)(void *userData, conditions above this handler will only be called if the referenced entity was actually read. */ -typedef int(XMLCALL *XML_NotStandaloneHandler)(void *userData); +typedef int(XMLCALL * XML_NotStandaloneHandler)(void * userData); /* This is called for a reference to an external parsed general entity. The referenced entity is not automatically parsed. The @@ -446,11 +436,8 @@ typedef int(XMLCALL *XML_NotStandaloneHandler)(void *userData); Note that unlike other handlers the first argument is the parser, not userData. */ -typedef int(XMLCALL *XML_ExternalEntityRefHandler)(XML_Parser parser, - const XML_Char *context, - const XML_Char *base, - const XML_Char *systemId, - const XML_Char *publicId); +typedef int(XMLCALL * XML_ExternalEntityRefHandler)( + XML_Parser parser, const XML_Char * context, const XML_Char * base, const XML_Char * systemId, const XML_Char * publicId); /* This is called in two situations: 1) An entity reference is encountered for which no declaration @@ -462,9 +449,7 @@ typedef int(XMLCALL *XML_ExternalEntityRefHandler)(XML_Parser parser, the event would be out of sync with the reporting of the declarations or attribute values */ -typedef void(XMLCALL *XML_SkippedEntityHandler)(void *userData, - const XML_Char *entityName, - int is_parameter_entity); +typedef void(XMLCALL * XML_SkippedEntityHandler)(void * userData, const XML_Char * entityName, int is_parameter_entity); /* This structure is filled in by the XML_UnknownEncodingHandler to provide information to the parser about encodings that are unknown @@ -518,11 +503,12 @@ typedef void(XMLCALL *XML_SkippedEntityHandler)(void *userData, 4. No Unicode character may be encoded by more than one distinct sequence of bytes. */ -typedef struct { - int map[256]; - void *data; - int(XMLCALL *convert)(void *data, const char *s); - void(XMLCALL *release)(void *data); +typedef struct +{ + int map[256]; + void * data; + int(XMLCALL * convert)(void * data, const char * s); + void(XMLCALL * release)(void * data); } XML_Encoding; /* This is called for an encoding that is unknown to the parser. @@ -540,13 +526,10 @@ typedef struct { If info does not describe a suitable encoding, then the parser will return an XML_ERROR_UNKNOWN_ENCODING error. */ -typedef int(XMLCALL *XML_UnknownEncodingHandler)(void *encodingHandlerData, - const XML_Char *name, - XML_Encoding *info); +typedef int(XMLCALL * XML_UnknownEncodingHandler)(void * encodingHandlerData, const XML_Char * name, XML_Encoding * info); XMLPARSEAPI(void) -XML_SetElementHandler(XML_Parser parser, XML_StartElementHandler start, - XML_EndElementHandler end); +XML_SetElementHandler(XML_Parser parser, XML_StartElementHandler start, XML_EndElementHandler end); XMLPARSEAPI(void) XML_SetStartElementHandler(XML_Parser parser, XML_StartElementHandler handler); @@ -555,27 +538,21 @@ XMLPARSEAPI(void) XML_SetEndElementHandler(XML_Parser parser, XML_EndElementHandler handler); XMLPARSEAPI(void) -XML_SetCharacterDataHandler(XML_Parser parser, - XML_CharacterDataHandler handler); +XML_SetCharacterDataHandler(XML_Parser parser, XML_CharacterDataHandler handler); XMLPARSEAPI(void) -XML_SetProcessingInstructionHandler(XML_Parser parser, - XML_ProcessingInstructionHandler handler); +XML_SetProcessingInstructionHandler(XML_Parser parser, XML_ProcessingInstructionHandler handler); XMLPARSEAPI(void) XML_SetCommentHandler(XML_Parser parser, XML_CommentHandler handler); XMLPARSEAPI(void) -XML_SetCdataSectionHandler(XML_Parser parser, - XML_StartCdataSectionHandler start, - XML_EndCdataSectionHandler end); +XML_SetCdataSectionHandler(XML_Parser parser, XML_StartCdataSectionHandler start, XML_EndCdataSectionHandler end); XMLPARSEAPI(void) -XML_SetStartCdataSectionHandler(XML_Parser parser, - XML_StartCdataSectionHandler start); +XML_SetStartCdataSectionHandler(XML_Parser parser, XML_StartCdataSectionHandler start); XMLPARSEAPI(void) -XML_SetEndCdataSectionHandler(XML_Parser parser, - XML_EndCdataSectionHandler end); +XML_SetEndCdataSectionHandler(XML_Parser parser, XML_EndCdataSectionHandler end); /* This sets the default handler and also inhibits expansion of internal entities. These entity references will be passed to the @@ -592,59 +569,47 @@ XMLPARSEAPI(void) XML_SetDefaultHandlerExpand(XML_Parser parser, XML_DefaultHandler handler); XMLPARSEAPI(void) -XML_SetDoctypeDeclHandler(XML_Parser parser, XML_StartDoctypeDeclHandler start, - XML_EndDoctypeDeclHandler end); +XML_SetDoctypeDeclHandler(XML_Parser parser, XML_StartDoctypeDeclHandler start, XML_EndDoctypeDeclHandler end); XMLPARSEAPI(void) -XML_SetStartDoctypeDeclHandler(XML_Parser parser, - XML_StartDoctypeDeclHandler start); +XML_SetStartDoctypeDeclHandler(XML_Parser parser, XML_StartDoctypeDeclHandler start); XMLPARSEAPI(void) XML_SetEndDoctypeDeclHandler(XML_Parser parser, XML_EndDoctypeDeclHandler end); XMLPARSEAPI(void) -XML_SetUnparsedEntityDeclHandler(XML_Parser parser, - XML_UnparsedEntityDeclHandler handler); +XML_SetUnparsedEntityDeclHandler(XML_Parser parser, XML_UnparsedEntityDeclHandler handler); XMLPARSEAPI(void) XML_SetNotationDeclHandler(XML_Parser parser, XML_NotationDeclHandler handler); XMLPARSEAPI(void) -XML_SetNamespaceDeclHandler(XML_Parser parser, - XML_StartNamespaceDeclHandler start, - XML_EndNamespaceDeclHandler end); +XML_SetNamespaceDeclHandler(XML_Parser parser, XML_StartNamespaceDeclHandler start, XML_EndNamespaceDeclHandler end); XMLPARSEAPI(void) -XML_SetStartNamespaceDeclHandler(XML_Parser parser, - XML_StartNamespaceDeclHandler start); +XML_SetStartNamespaceDeclHandler(XML_Parser parser, XML_StartNamespaceDeclHandler start); XMLPARSEAPI(void) -XML_SetEndNamespaceDeclHandler(XML_Parser parser, - XML_EndNamespaceDeclHandler end); +XML_SetEndNamespaceDeclHandler(XML_Parser parser, XML_EndNamespaceDeclHandler end); XMLPARSEAPI(void) -XML_SetNotStandaloneHandler(XML_Parser parser, - XML_NotStandaloneHandler handler); +XML_SetNotStandaloneHandler(XML_Parser parser, XML_NotStandaloneHandler handler); XMLPARSEAPI(void) -XML_SetExternalEntityRefHandler(XML_Parser parser, - XML_ExternalEntityRefHandler handler); +XML_SetExternalEntityRefHandler(XML_Parser parser, XML_ExternalEntityRefHandler handler); /* If a non-NULL value for arg is specified here, then it will be passed as the first argument to the external entity ref handler instead of the parser object. */ XMLPARSEAPI(void) -XML_SetExternalEntityRefHandlerArg(XML_Parser parser, void *arg); +XML_SetExternalEntityRefHandlerArg(XML_Parser parser, void * arg); XMLPARSEAPI(void) -XML_SetSkippedEntityHandler(XML_Parser parser, - XML_SkippedEntityHandler handler); +XML_SetSkippedEntityHandler(XML_Parser parser, XML_SkippedEntityHandler handler); XMLPARSEAPI(void) -XML_SetUnknownEncodingHandler(XML_Parser parser, - XML_UnknownEncodingHandler handler, - void *encodingHandlerData); +XML_SetUnknownEncodingHandler(XML_Parser parser, XML_UnknownEncodingHandler handler, void * encodingHandlerData); /* This can be called within a handler for a start element, end element, processing instruction or character data. It causes the @@ -672,7 +637,7 @@ XML_SetReturnNSTriplet(XML_Parser parser, int do_nst); /* This value is passed as the userData argument to callbacks. */ XMLPARSEAPI(void) -XML_SetUserData(XML_Parser parser, void *userData); +XML_SetUserData(XML_Parser parser, void * userData); /* Returns the last value set by XML_SetUserData or NULL. */ #define XML_GetUserData(parser) (*(void **)(parser)) @@ -684,7 +649,7 @@ XML_SetUserData(XML_Parser parser, void *userData); has no effect and returns XML_STATUS_ERROR. */ XMLPARSEAPI(enum XML_Status) -XML_SetEncoding(XML_Parser parser, const XML_Char *encoding); +XML_SetEncoding(XML_Parser parser, const XML_Char * encoding); /* If this function is called, then the parser will be passed as the first argument to callbacks instead of userData. The userData will @@ -724,7 +689,7 @@ XML_UseForeignDTD(XML_Parser parser, XML_Bool useDTD); XML_STATUS_OK otherwise. */ XMLPARSEAPI(enum XML_Status) -XML_SetBase(XML_Parser parser, const XML_Char *base); +XML_SetBase(XML_Parser parser, const XML_Char * base); XMLPARSEAPI(const XML_Char *) XML_GetBase(XML_Parser parser); @@ -753,11 +718,12 @@ XML_GetIdAttributeIndex(XML_Parser parser); file an attribute value of "blah" will yield: info->valueEnd - info->valueStart = 4 bytes. */ -typedef struct { - XML_Index nameStart; /* Offset to beginning of the attribute name. */ - XML_Index nameEnd; /* Offset after the attribute name's last byte. */ - XML_Index valueStart; /* Offset to beginning of the attribute value. */ - XML_Index valueEnd; /* Offset after the attribute value's last byte. */ +typedef struct +{ + XML_Index nameStart; /* Offset to beginning of the attribute name. */ + XML_Index nameEnd; /* Offset after the attribute name's last byte. */ + XML_Index valueStart; /* Offset to beginning of the attribute value. */ + XML_Index valueEnd; /* Offset after the attribute value's last byte. */ } XML_AttrInfo; /* Returns an array of XML_AttrInfo structures for the attribute/value pairs @@ -780,7 +746,7 @@ XML_GetAttributeInfo(XML_Parser parser); values. */ XMLPARSEAPI(enum XML_Status) -XML_Parse(XML_Parser parser, const char *s, int len, int isFinal); +XML_Parse(XML_Parser parser, const char * s, int len, int isFinal); XMLPARSEAPI(void *) XML_GetBuffer(XML_Parser parser, int len); @@ -837,11 +803,18 @@ XML_StopParser(XML_Parser parser, XML_Bool resumable); XMLPARSEAPI(enum XML_Status) XML_ResumeParser(XML_Parser parser); -enum XML_Parsing { XML_INITIALIZED, XML_PARSING, XML_FINISHED, XML_SUSPENDED }; +enum XML_Parsing +{ + XML_INITIALIZED, + XML_PARSING, + XML_FINISHED, + XML_SUSPENDED +}; -typedef struct { - enum XML_Parsing parsing; - XML_Bool finalBuffer; +typedef struct +{ + enum XML_Parsing parsing; + XML_Bool finalBuffer; } XML_ParsingStatus; /* Returns status of parser with respect to being initialized, parsing, @@ -850,7 +823,7 @@ typedef struct { XXX with XML_FINISHED_OK or XML_FINISHED_ERROR replacing XML_FINISHED */ XMLPARSEAPI(void) -XML_GetParsingStatus(XML_Parser parser, XML_ParsingStatus *status); +XML_GetParsingStatus(XML_Parser parser, XML_ParsingStatus * status); /* Creates an XML_Parser object that can parse an external general entity; context is a '\0'-terminated string specifying the parse @@ -869,13 +842,13 @@ XML_GetParsingStatus(XML_Parser parser, XML_ParsingStatus *status); Otherwise returns a new XML_Parser object. */ XMLPARSEAPI(XML_Parser) -XML_ExternalEntityParserCreate(XML_Parser parser, const XML_Char *context, - const XML_Char *encoding); +XML_ExternalEntityParserCreate(XML_Parser parser, const XML_Char * context, const XML_Char * encoding); -enum XML_ParamEntityParsing { - XML_PARAM_ENTITY_PARSING_NEVER, - XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE, - XML_PARAM_ENTITY_PARSING_ALWAYS +enum XML_ParamEntityParsing +{ + XML_PARAM_ENTITY_PARSING_NEVER, + XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE, + XML_PARAM_ENTITY_PARSING_ALWAYS }; /* Controls parsing of parameter entities (including the external DTD @@ -903,8 +876,7 @@ enum XML_ParamEntityParsing { Note: If parser == NULL, the function will do nothing and return 0. */ XMLPARSEAPI(int) -XML_SetParamEntityParsing(XML_Parser parser, - enum XML_ParamEntityParsing parsing); +XML_SetParamEntityParsing(XML_Parser parser, enum XML_ParamEntityParsing parsing); /* Sets the hash salt to use for internal hash calculations. Helps in preventing DoS attacks based on predicting hash @@ -962,7 +934,7 @@ XML_GetCurrentByteCount(XML_Parser parser); the handler that makes the call. */ XMLPARSEAPI(const char *) -XML_GetInputContext(XML_Parser parser, int *offset, int *size); +XML_GetInputContext(XML_Parser parser, int * offset, int * size); /* For backwards compatibility with previous versions. */ #define XML_GetErrorLineNumber XML_GetCurrentLineNumber @@ -971,7 +943,7 @@ XML_GetInputContext(XML_Parser parser, int *offset, int *size); /* Frees the content model passed to the element declaration handler */ XMLPARSEAPI(void) -XML_FreeContentModel(XML_Parser parser, XML_Content *model); +XML_FreeContentModel(XML_Parser parser, XML_Content * model); /* Exposing the memory handling functions used in Expat */ XMLPARSEAPI(void *) @@ -981,10 +953,10 @@ XML_MemMalloc(XML_Parser parser, size_t size); XMLPARSEAPI(void *) XML_ATTR_ALLOC_SIZE(3) -XML_MemRealloc(XML_Parser parser, void *ptr, size_t size); +XML_MemRealloc(XML_Parser parser, void * ptr, size_t size); XMLPARSEAPI(void) -XML_MemFree(XML_Parser parser, void *ptr); +XML_MemFree(XML_Parser parser, void * ptr); /* Frees memory used by the parser. */ XMLPARSEAPI(void) @@ -998,10 +970,11 @@ XML_ErrorString(enum XML_Error code); XMLPARSEAPI(const XML_LChar *) XML_ExpatVersion(void); -typedef struct { - int major; - int minor; - int micro; +typedef struct +{ + int major; + int minor; + int micro; } XML_Expat_Version; /* Return an XML_Expat_Version structure containing numeric version @@ -1011,28 +984,30 @@ XMLPARSEAPI(XML_Expat_Version) XML_ExpatVersionInfo(void); /* Added in Expat 1.95.5. */ -enum XML_FeatureEnum { - XML_FEATURE_END = 0, - XML_FEATURE_UNICODE, - XML_FEATURE_UNICODE_WCHAR_T, - XML_FEATURE_DTD, - XML_FEATURE_CONTEXT_BYTES, - XML_FEATURE_MIN_SIZE, - XML_FEATURE_SIZEOF_XML_CHAR, - XML_FEATURE_SIZEOF_XML_LCHAR, - XML_FEATURE_NS, - XML_FEATURE_LARGE_SIZE, - XML_FEATURE_ATTR_INFO, - /* Added in Expat 2.4.0. */ - XML_FEATURE_BILLION_LAUGHS_ATTACK_PROTECTION_MAXIMUM_AMPLIFICATION_DEFAULT, - XML_FEATURE_BILLION_LAUGHS_ATTACK_PROTECTION_ACTIVATION_THRESHOLD_DEFAULT - /* Additional features must be added to the end of this enum. */ +enum XML_FeatureEnum +{ + XML_FEATURE_END = 0, + XML_FEATURE_UNICODE, + XML_FEATURE_UNICODE_WCHAR_T, + XML_FEATURE_DTD, + XML_FEATURE_CONTEXT_BYTES, + XML_FEATURE_MIN_SIZE, + XML_FEATURE_SIZEOF_XML_CHAR, + XML_FEATURE_SIZEOF_XML_LCHAR, + XML_FEATURE_NS, + XML_FEATURE_LARGE_SIZE, + XML_FEATURE_ATTR_INFO, + /* Added in Expat 2.4.0. */ + XML_FEATURE_BILLION_LAUGHS_ATTACK_PROTECTION_MAXIMUM_AMPLIFICATION_DEFAULT, + XML_FEATURE_BILLION_LAUGHS_ATTACK_PROTECTION_ACTIVATION_THRESHOLD_DEFAULT + /* Additional features must be added to the end of this enum. */ }; -typedef struct { - enum XML_FeatureEnum feature; - const XML_LChar *name; - long int value; +typedef struct +{ + enum XML_FeatureEnum feature; + const XML_LChar * name; + long int value; } XML_Feature; XMLPARSEAPI(const XML_Feature *) @@ -1041,13 +1016,11 @@ XML_GetFeatureList(void); #ifdef XML_DTD /* Added in Expat 2.4.0. */ XMLPARSEAPI(XML_Bool) -XML_SetBillionLaughsAttackProtectionMaximumAmplification( - XML_Parser parser, float maximumAmplificationFactor); +XML_SetBillionLaughsAttackProtectionMaximumAmplification(XML_Parser parser, float maximumAmplificationFactor); /* Added in Expat 2.4.0. */ XMLPARSEAPI(XML_Bool) -XML_SetBillionLaughsAttackProtectionActivationThreshold( - XML_Parser parser, unsigned long long activationThresholdBytes); +XML_SetBillionLaughsAttackProtectionActivationThreshold(XML_Parser parser, unsigned long long activationThresholdBytes); #endif /* Expat follows the semantic versioning convention. diff --git a/base/poco/XML/include/Poco/XML/expat_external.h b/base/poco/XML/include/Poco/XML/expat_external.h index 9c5fc8a2e8b..cb5905c7b04 100644 --- a/base/poco/XML/include/Poco/XML/expat_external.h +++ b/base/poco/XML/include/Poco/XML/expat_external.h @@ -65,11 +65,11 @@ system headers may assume the cdecl convention. */ #ifndef XMLCALL -# if defined(_MSC_VER) -# define XMLCALL __cdecl -# elif defined(__GNUC__) && defined(__i386) && ! defined(__INTEL_COMPILER) -# define XMLCALL __attribute__((cdecl)) -# else +# if defined(_MSC_VER) +# define XMLCALL __cdecl +# elif defined(__GNUC__) && defined(__i386) && !defined(__INTEL_COMPILER) +# define XMLCALL __attribute__((cdecl)) +# else /* For any platform which uses this definition and supports more than one calling convention, we need to extend this definition to declare the convention used on that platform, if it's possible to @@ -80,46 +80,44 @@ pre-processor and how to specify the same calling convention as the platform's malloc() implementation. */ -# define XMLCALL -# endif +# define XMLCALL +# endif #endif /* not defined XMLCALL */ -#if ! defined(XML_STATIC) && ! defined(XMLIMPORT) -# ifndef XML_BUILDING_EXPAT +#if !defined(XML_STATIC) && !defined(XMLIMPORT) +# ifndef XML_BUILDING_EXPAT /* using Expat from an application */ -# if defined(_MSC_EXTENSIONS) && ! defined(__BEOS__) && ! defined(__CYGWIN__) -# define XMLIMPORT __declspec(dllimport) -# endif +# if defined(_MSC_EXTENSIONS) && !defined(__BEOS__) && !defined(__CYGWIN__) +# define XMLIMPORT __declspec(dllimport) +# endif -# endif +# endif #endif /* not defined XML_STATIC */ #ifndef XML_ENABLE_VISIBILITY -# define XML_ENABLE_VISIBILITY 0 +# define XML_ENABLE_VISIBILITY 0 #endif -#if ! defined(XMLIMPORT) && XML_ENABLE_VISIBILITY -# define XMLIMPORT __attribute__((visibility("default"))) +#if !defined(XMLIMPORT) && XML_ENABLE_VISIBILITY +# define XMLIMPORT __attribute__((visibility("default"))) #endif /* If we didn't define it above, define it away: */ #ifndef XMLIMPORT -# define XMLIMPORT +# define XMLIMPORT #endif -#if defined(__GNUC__) \ - && (__GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 96)) -# define XML_ATTR_MALLOC __attribute__((__malloc__)) +#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 96)) +# define XML_ATTR_MALLOC __attribute__((__malloc__)) #else -# define XML_ATTR_MALLOC +# define XML_ATTR_MALLOC #endif -#if defined(__GNUC__) \ - && ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) -# define XML_ATTR_ALLOC_SIZE(x) __attribute__((__alloc_size__(x))) +#if defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) +# define XML_ATTR_ALLOC_SIZE(x) __attribute__((__alloc_size__(x))) #else -# define XML_ATTR_ALLOC_SIZE(x) +# define XML_ATTR_ALLOC_SIZE(x) #endif #define XMLPARSEAPI(type) XMLIMPORT type XMLCALL @@ -129,26 +127,26 @@ extern "C" { #endif #ifdef XML_UNICODE_WCHAR_T -# ifndef XML_UNICODE -# define XML_UNICODE -# endif -# if defined(__SIZEOF_WCHAR_T__) && (__SIZEOF_WCHAR_T__ != 2) -# error "sizeof(wchar_t) != 2; Need -fshort-wchar for both Expat and libc" -# endif +# ifndef XML_UNICODE +# define XML_UNICODE +# endif +# if defined(__SIZEOF_WCHAR_T__) && (__SIZEOF_WCHAR_T__ != 2) +# error "sizeof(wchar_t) != 2; Need -fshort-wchar for both Expat and libc" +# endif #endif #ifdef XML_UNICODE /* Information is UTF-16 encoded. */ -# ifdef XML_UNICODE_WCHAR_T +# ifdef XML_UNICODE_WCHAR_T typedef wchar_t XML_Char; typedef wchar_t XML_LChar; -# else +# else typedef unsigned short XML_Char; typedef char XML_LChar; -# endif /* XML_UNICODE_WCHAR_T */ -#else /* Information is UTF-8 encoded. */ +# endif /* XML_UNICODE_WCHAR_T */ +#else /* Information is UTF-8 encoded. */ typedef char XML_Char; typedef char XML_LChar; -#endif /* XML_UNICODE */ +#endif /* XML_UNICODE */ #ifdef XML_LARGE_SIZE /* Use large integers for file/stream positions. */ typedef long long XML_Index; diff --git a/base/poco/XML/src/asciitab.h b/base/poco/XML/src/asciitab.h index 86df212f5a1..2f15c3c3806 100644 --- a/base/poco/XML/src/asciitab.h +++ b/base/poco/XML/src/asciitab.h @@ -33,34 +33,34 @@ */ /* 0x00 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, -/* 0x04 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, -/* 0x08 */ BT_NONXML, BT_S, BT_LF, BT_NONXML, -/* 0x0C */ BT_NONXML, BT_CR, BT_NONXML, BT_NONXML, -/* 0x10 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, -/* 0x14 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, -/* 0x18 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, -/* 0x1C */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, -/* 0x20 */ BT_S, BT_EXCL, BT_QUOT, BT_NUM, -/* 0x24 */ BT_OTHER, BT_PERCNT, BT_AMP, BT_APOS, -/* 0x28 */ BT_LPAR, BT_RPAR, BT_AST, BT_PLUS, -/* 0x2C */ BT_COMMA, BT_MINUS, BT_NAME, BT_SOL, -/* 0x30 */ BT_DIGIT, BT_DIGIT, BT_DIGIT, BT_DIGIT, -/* 0x34 */ BT_DIGIT, BT_DIGIT, BT_DIGIT, BT_DIGIT, -/* 0x38 */ BT_DIGIT, BT_DIGIT, BT_COLON, BT_SEMI, -/* 0x3C */ BT_LT, BT_EQUALS, BT_GT, BT_QUEST, -/* 0x40 */ BT_OTHER, BT_HEX, BT_HEX, BT_HEX, -/* 0x44 */ BT_HEX, BT_HEX, BT_HEX, BT_NMSTRT, -/* 0x48 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, -/* 0x4C */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, -/* 0x50 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, -/* 0x54 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, -/* 0x58 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_LSQB, -/* 0x5C */ BT_OTHER, BT_RSQB, BT_OTHER, BT_NMSTRT, -/* 0x60 */ BT_OTHER, BT_HEX, BT_HEX, BT_HEX, -/* 0x64 */ BT_HEX, BT_HEX, BT_HEX, BT_NMSTRT, -/* 0x68 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, -/* 0x6C */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, -/* 0x70 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, -/* 0x74 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, -/* 0x78 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_OTHER, -/* 0x7C */ BT_VERBAR, BT_OTHER, BT_OTHER, BT_OTHER, + /* 0x04 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, + /* 0x08 */ BT_NONXML, BT_S, BT_LF, BT_NONXML, + /* 0x0C */ BT_NONXML, BT_CR, BT_NONXML, BT_NONXML, + /* 0x10 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, + /* 0x14 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, + /* 0x18 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, + /* 0x1C */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, + /* 0x20 */ BT_S, BT_EXCL, BT_QUOT, BT_NUM, + /* 0x24 */ BT_OTHER, BT_PERCNT, BT_AMP, BT_APOS, + /* 0x28 */ BT_LPAR, BT_RPAR, BT_AST, BT_PLUS, + /* 0x2C */ BT_COMMA, BT_MINUS, BT_NAME, BT_SOL, + /* 0x30 */ BT_DIGIT, BT_DIGIT, BT_DIGIT, BT_DIGIT, + /* 0x34 */ BT_DIGIT, BT_DIGIT, BT_DIGIT, BT_DIGIT, + /* 0x38 */ BT_DIGIT, BT_DIGIT, BT_COLON, BT_SEMI, + /* 0x3C */ BT_LT, BT_EQUALS, BT_GT, BT_QUEST, + /* 0x40 */ BT_OTHER, BT_HEX, BT_HEX, BT_HEX, + /* 0x44 */ BT_HEX, BT_HEX, BT_HEX, BT_NMSTRT, + /* 0x48 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, + /* 0x4C */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, + /* 0x50 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, + /* 0x54 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, + /* 0x58 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_LSQB, + /* 0x5C */ BT_OTHER, BT_RSQB, BT_OTHER, BT_NMSTRT, + /* 0x60 */ BT_OTHER, BT_HEX, BT_HEX, BT_HEX, + /* 0x64 */ BT_HEX, BT_HEX, BT_HEX, BT_NMSTRT, + /* 0x68 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, + /* 0x6C */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, + /* 0x70 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, + /* 0x74 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, + /* 0x78 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_OTHER, + /* 0x7C */ BT_VERBAR, BT_OTHER, BT_OTHER, BT_OTHER, diff --git a/base/poco/XML/src/expat_config.h b/base/poco/XML/src/expat_config.h index 78904d1e122..14383d0b261 100644 --- a/base/poco/XML/src/expat_config.h +++ b/base/poco/XML/src/expat_config.h @@ -18,7 +18,7 @@ #if !defined(POCO_VXWORKS) -#include +# include #endif #include @@ -27,9 +27,9 @@ #if defined POCO_ARCH_LITTLE_ENDIAN -#define BYTEORDER 1234 +# define BYTEORDER 1234 #else -#define BYTEORDER 4321 +# define BYTEORDER 4321 #endif diff --git a/base/poco/XML/src/iasciitab.h b/base/poco/XML/src/iasciitab.h index 44bd93f691e..3af3bd25414 100644 --- a/base/poco/XML/src/iasciitab.h +++ b/base/poco/XML/src/iasciitab.h @@ -34,34 +34,34 @@ /* Like asciitab.h, except that 0xD has code BT_S rather than BT_CR */ /* 0x00 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, -/* 0x04 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, -/* 0x08 */ BT_NONXML, BT_S, BT_LF, BT_NONXML, -/* 0x0C */ BT_NONXML, BT_S, BT_NONXML, BT_NONXML, -/* 0x10 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, -/* 0x14 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, -/* 0x18 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, -/* 0x1C */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, -/* 0x20 */ BT_S, BT_EXCL, BT_QUOT, BT_NUM, -/* 0x24 */ BT_OTHER, BT_PERCNT, BT_AMP, BT_APOS, -/* 0x28 */ BT_LPAR, BT_RPAR, BT_AST, BT_PLUS, -/* 0x2C */ BT_COMMA, BT_MINUS, BT_NAME, BT_SOL, -/* 0x30 */ BT_DIGIT, BT_DIGIT, BT_DIGIT, BT_DIGIT, -/* 0x34 */ BT_DIGIT, BT_DIGIT, BT_DIGIT, BT_DIGIT, -/* 0x38 */ BT_DIGIT, BT_DIGIT, BT_COLON, BT_SEMI, -/* 0x3C */ BT_LT, BT_EQUALS, BT_GT, BT_QUEST, -/* 0x40 */ BT_OTHER, BT_HEX, BT_HEX, BT_HEX, -/* 0x44 */ BT_HEX, BT_HEX, BT_HEX, BT_NMSTRT, -/* 0x48 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, -/* 0x4C */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, -/* 0x50 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, -/* 0x54 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, -/* 0x58 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_LSQB, -/* 0x5C */ BT_OTHER, BT_RSQB, BT_OTHER, BT_NMSTRT, -/* 0x60 */ BT_OTHER, BT_HEX, BT_HEX, BT_HEX, -/* 0x64 */ BT_HEX, BT_HEX, BT_HEX, BT_NMSTRT, -/* 0x68 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, -/* 0x6C */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, -/* 0x70 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, -/* 0x74 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, -/* 0x78 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_OTHER, -/* 0x7C */ BT_VERBAR, BT_OTHER, BT_OTHER, BT_OTHER, + /* 0x04 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, + /* 0x08 */ BT_NONXML, BT_S, BT_LF, BT_NONXML, + /* 0x0C */ BT_NONXML, BT_S, BT_NONXML, BT_NONXML, + /* 0x10 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, + /* 0x14 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, + /* 0x18 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, + /* 0x1C */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, + /* 0x20 */ BT_S, BT_EXCL, BT_QUOT, BT_NUM, + /* 0x24 */ BT_OTHER, BT_PERCNT, BT_AMP, BT_APOS, + /* 0x28 */ BT_LPAR, BT_RPAR, BT_AST, BT_PLUS, + /* 0x2C */ BT_COMMA, BT_MINUS, BT_NAME, BT_SOL, + /* 0x30 */ BT_DIGIT, BT_DIGIT, BT_DIGIT, BT_DIGIT, + /* 0x34 */ BT_DIGIT, BT_DIGIT, BT_DIGIT, BT_DIGIT, + /* 0x38 */ BT_DIGIT, BT_DIGIT, BT_COLON, BT_SEMI, + /* 0x3C */ BT_LT, BT_EQUALS, BT_GT, BT_QUEST, + /* 0x40 */ BT_OTHER, BT_HEX, BT_HEX, BT_HEX, + /* 0x44 */ BT_HEX, BT_HEX, BT_HEX, BT_NMSTRT, + /* 0x48 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, + /* 0x4C */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, + /* 0x50 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, + /* 0x54 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, + /* 0x58 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_LSQB, + /* 0x5C */ BT_OTHER, BT_RSQB, BT_OTHER, BT_NMSTRT, + /* 0x60 */ BT_OTHER, BT_HEX, BT_HEX, BT_HEX, + /* 0x64 */ BT_HEX, BT_HEX, BT_HEX, BT_NMSTRT, + /* 0x68 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, + /* 0x6C */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, + /* 0x70 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, + /* 0x74 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, + /* 0x78 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_OTHER, + /* 0x7C */ BT_VERBAR, BT_OTHER, BT_OTHER, BT_OTHER, diff --git a/base/poco/XML/src/internal.h b/base/poco/XML/src/internal.h index d9e592052f9..c34e3ae3f83 100644 --- a/base/poco/XML/src/internal.h +++ b/base/poco/XML/src/internal.h @@ -53,7 +53,7 @@ USE OR OTHER DEALINGS IN THE SOFTWARE. */ -#if defined(__GNUC__) && defined(__i386__) && ! defined(__MINGW32__) +#if defined(__GNUC__) && defined(__i386__) && !defined(__MINGW32__) /* We'll use this version by default only where we know it helps. regparm() generates warnings on Solaris boxes. See SF bug #692878. @@ -63,8 +63,8 @@ #define FASTCALL __attribute__((stdcall, regparm(3))) and let's try this: */ -# define FASTCALL __attribute__((regparm(3))) -# define PTRFASTCALL __attribute__((regparm(3))) +# define FASTCALL __attribute__((regparm(3))) +# define PTRFASTCALL __attribute__((regparm(3))) #endif /* Using __fastcall seems to have an unexpected negative effect under @@ -78,69 +78,67 @@ /* Make sure all of these are defined if they aren't already. */ #ifndef FASTCALL -# define FASTCALL +# define FASTCALL #endif #ifndef PTRCALL -# define PTRCALL +# define PTRCALL #endif #ifndef PTRFASTCALL -# define PTRFASTCALL +# define PTRFASTCALL #endif #ifndef XML_MIN_SIZE -# if ! defined(__cplusplus) && ! defined(inline) -# ifdef __GNUC__ -# define inline __inline -# endif /* __GNUC__ */ -# endif +# if !defined(__cplusplus) && !defined(inline) +# ifdef __GNUC__ +# define inline __inline +# endif /* __GNUC__ */ +# endif #endif /* XML_MIN_SIZE */ #ifdef __cplusplus -# define inline inline +# define inline inline #else -# ifndef inline -# define inline -# endif +# ifndef inline +# define inline +# endif #endif #include // ULONG_MAX -#if defined(_WIN32) && ! defined(__USE_MINGW_ANSI_STDIO) -# define EXPAT_FMT_ULL(midpart) "%" midpart "I64u" -# if defined(_WIN64) // Note: modifiers "td" and "zu" do not work for MinGW -# define EXPAT_FMT_PTRDIFF_T(midpart) "%" midpart "I64d" -# define EXPAT_FMT_SIZE_T(midpart) "%" midpart "I64u" -# else -# define EXPAT_FMT_PTRDIFF_T(midpart) "%" midpart "d" -# define EXPAT_FMT_SIZE_T(midpart) "%" midpart "u" -# endif +#if defined(_WIN32) && !defined(__USE_MINGW_ANSI_STDIO) +# define EXPAT_FMT_ULL(midpart) "%" midpart "I64u" +# if defined(_WIN64) // Note: modifiers "td" and "zu" do not work for MinGW +# define EXPAT_FMT_PTRDIFF_T(midpart) "%" midpart "I64d" +# define EXPAT_FMT_SIZE_T(midpart) "%" midpart "I64u" +# else +# define EXPAT_FMT_PTRDIFF_T(midpart) "%" midpart "d" +# define EXPAT_FMT_SIZE_T(midpart) "%" midpart "u" +# endif #else -# define EXPAT_FMT_ULL(midpart) "%" midpart "llu" -# if ! defined(ULONG_MAX) -# error Compiler did not define ULONG_MAX for us -# elif ULONG_MAX == 18446744073709551615u // 2^64-1 -# define EXPAT_FMT_PTRDIFF_T(midpart) "%" midpart "ld" -# define EXPAT_FMT_SIZE_T(midpart) "%" midpart "lu" -# else -# define EXPAT_FMT_PTRDIFF_T(midpart) "%" midpart "d" -# define EXPAT_FMT_SIZE_T(midpart) "%" midpart "u" -# endif +# define EXPAT_FMT_ULL(midpart) "%" midpart "llu" +# if !defined(ULONG_MAX) +# error Compiler did not define ULONG_MAX for us +# elif ULONG_MAX == 18446744073709551615u // 2^64-1 +# define EXPAT_FMT_PTRDIFF_T(midpart) "%" midpart "ld" +# define EXPAT_FMT_SIZE_T(midpart) "%" midpart "lu" +# else +# define EXPAT_FMT_PTRDIFF_T(midpart) "%" midpart "d" +# define EXPAT_FMT_SIZE_T(midpart) "%" midpart "u" +# endif #endif #ifndef UNUSED_P -# define UNUSED_P(p) (void)p +# define UNUSED_P(p) (void)p #endif /* NOTE BEGIN If you ever patch these defaults to greater values for non-attack XML payload in your environment, please file a bug report with libexpat. Thank you! */ -#define EXPAT_BILLION_LAUGHS_ATTACK_PROTECTION_MAXIMUM_AMPLIFICATION_DEFAULT \ - 100.0f -#define EXPAT_BILLION_LAUGHS_ATTACK_PROTECTION_ACTIVATION_THRESHOLD_DEFAULT \ - 8388608 // 8 MiB, 2^23 +#define EXPAT_BILLION_LAUGHS_ATTACK_PROTECTION_MAXIMUM_AMPLIFICATION_DEFAULT 100.0f +#define EXPAT_BILLION_LAUGHS_ATTACK_PROTECTION_ACTIVATION_THRESHOLD_DEFAULT 8388608 // 8 MiB, 2^23 /* NOTE END */ #include "Poco/XML/expat.h" // so we can use type XML_Parser below @@ -149,14 +147,13 @@ extern "C" { #endif -void _INTERNAL_trim_to_complete_utf8_characters(const char *from, - const char **fromLimRef); +void _INTERNAL_trim_to_complete_utf8_characters(const char * from, const char ** fromLimRef); #if defined(XML_DTD) unsigned long long testingAccountingGetCountBytesDirect(XML_Parser parser); unsigned long long testingAccountingGetCountBytesIndirect(XML_Parser parser); -const char *unsignedCharToPrintable(unsigned char c); -# endif +const char * unsignedCharToPrintable(unsigned char c); +#endif #ifdef __cplusplus } diff --git a/base/poco/XML/src/latin1tab.h b/base/poco/XML/src/latin1tab.h index a63ebd6a122..e4f2871f1dd 100644 --- a/base/poco/XML/src/latin1tab.h +++ b/base/poco/XML/src/latin1tab.h @@ -33,34 +33,34 @@ */ /* 0x80 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, -/* 0x84 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, -/* 0x88 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, -/* 0x8C */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, -/* 0x90 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, -/* 0x94 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, -/* 0x98 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, -/* 0x9C */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, -/* 0xA0 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, -/* 0xA4 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, -/* 0xA8 */ BT_OTHER, BT_OTHER, BT_NMSTRT, BT_OTHER, -/* 0xAC */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, -/* 0xB0 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, -/* 0xB4 */ BT_OTHER, BT_NMSTRT, BT_OTHER, BT_NAME, -/* 0xB8 */ BT_OTHER, BT_OTHER, BT_NMSTRT, BT_OTHER, -/* 0xBC */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, -/* 0xC0 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, -/* 0xC4 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, -/* 0xC8 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, -/* 0xCC */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, -/* 0xD0 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, -/* 0xD4 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_OTHER, -/* 0xD8 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, -/* 0xDC */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, -/* 0xE0 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, -/* 0xE4 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, -/* 0xE8 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, -/* 0xEC */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, -/* 0xF0 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, -/* 0xF4 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_OTHER, -/* 0xF8 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, -/* 0xFC */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, + /* 0x84 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, + /* 0x88 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, + /* 0x8C */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, + /* 0x90 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, + /* 0x94 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, + /* 0x98 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, + /* 0x9C */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, + /* 0xA0 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, + /* 0xA4 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, + /* 0xA8 */ BT_OTHER, BT_OTHER, BT_NMSTRT, BT_OTHER, + /* 0xAC */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, + /* 0xB0 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, + /* 0xB4 */ BT_OTHER, BT_NMSTRT, BT_OTHER, BT_NAME, + /* 0xB8 */ BT_OTHER, BT_OTHER, BT_NMSTRT, BT_OTHER, + /* 0xBC */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, + /* 0xC0 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, + /* 0xC4 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, + /* 0xC8 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, + /* 0xCC */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, + /* 0xD0 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, + /* 0xD4 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_OTHER, + /* 0xD8 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, + /* 0xDC */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, + /* 0xE0 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, + /* 0xE4 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, + /* 0xE8 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, + /* 0xEC */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, + /* 0xF0 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, + /* 0xF4 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_OTHER, + /* 0xF8 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, + /* 0xFC */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, diff --git a/base/poco/XML/src/nametab.h b/base/poco/XML/src/nametab.h index e8cf8d7d9d2..514e4d0c9b3 100644 --- a/base/poco/XML/src/nametab.h +++ b/base/poco/XML/src/nametab.h @@ -31,106 +31,62 @@ */ static const unsigned namingBitmap[] = { - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, - 0x00000000, 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, - 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0x04000000, - 0x87FFFFFE, 0x07FFFFFE, 0x00000000, 0x00000000, 0xFF7FFFFF, 0xFF7FFFFF, - 0xFFFFFFFF, 0x7FF3FFFF, 0xFFFFFDFE, 0x7FFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, - 0xFFFFE00F, 0xFC31FFFF, 0x00FFFFFF, 0x00000000, 0xFFFF0000, 0xFFFFFFFF, - 0xFFFFFFFF, 0xF80001FF, 0x00000003, 0x00000000, 0x00000000, 0x00000000, - 0x00000000, 0x00000000, 0xFFFFD740, 0xFFFFFFFB, 0x547F7FFF, 0x000FFFFD, - 0xFFFFDFFE, 0xFFFFFFFF, 0xDFFEFFFF, 0xFFFFFFFF, 0xFFFF0003, 0xFFFFFFFF, - 0xFFFF199F, 0x033FCFFF, 0x00000000, 0xFFFE0000, 0x027FFFFF, 0xFFFFFFFE, - 0x0000007F, 0x00000000, 0xFFFF0000, 0x000707FF, 0x00000000, 0x07FFFFFE, - 0x000007FE, 0xFFFE0000, 0xFFFFFFFF, 0x7CFFFFFF, 0x002F7FFF, 0x00000060, - 0xFFFFFFE0, 0x23FFFFFF, 0xFF000000, 0x00000003, 0xFFF99FE0, 0x03C5FDFF, - 0xB0000000, 0x00030003, 0xFFF987E0, 0x036DFDFF, 0x5E000000, 0x001C0000, - 0xFFFBAFE0, 0x23EDFDFF, 0x00000000, 0x00000001, 0xFFF99FE0, 0x23CDFDFF, - 0xB0000000, 0x00000003, 0xD63DC7E0, 0x03BFC718, 0x00000000, 0x00000000, - 0xFFFDDFE0, 0x03EFFDFF, 0x00000000, 0x00000003, 0xFFFDDFE0, 0x03EFFDFF, - 0x40000000, 0x00000003, 0xFFFDDFE0, 0x03FFFDFF, 0x00000000, 0x00000003, - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFFFFFFFE, 0x000D7FFF, - 0x0000003F, 0x00000000, 0xFEF02596, 0x200D6CAE, 0x0000001F, 0x00000000, - 0x00000000, 0x00000000, 0xFFFFFEFF, 0x000003FF, 0x00000000, 0x00000000, - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, - 0x00000000, 0xFFFFFFFF, 0xFFFF003F, 0x007FFFFF, 0x0007DAED, 0x50000000, - 0x82315001, 0x002C62AB, 0x40000000, 0xF580C900, 0x00000007, 0x02010800, - 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x0FFFFFFF, 0xFFFFFFFF, - 0xFFFFFFFF, 0x03FFFFFF, 0x3F3FFFFF, 0xFFFFFFFF, 0xAAFF3F3F, 0x3FFFFFFF, - 0xFFFFFFFF, 0x5FDFFFFF, 0x0FCF1FDC, 0x1FDC1FFF, 0x00000000, 0x00004C40, - 0x00000000, 0x00000000, 0x00000007, 0x00000000, 0x00000000, 0x00000000, - 0x00000080, 0x000003FE, 0xFFFFFFFE, 0xFFFFFFFF, 0x001FFFFF, 0xFFFFFFFE, - 0xFFFFFFFF, 0x07FFFFFF, 0xFFFFFFE0, 0x00001FFF, 0x00000000, 0x00000000, - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF, - 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x0000003F, 0x00000000, 0x00000000, - 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x0000000F, - 0x00000000, 0x00000000, 0x00000000, 0x07FF6000, 0x87FFFFFE, 0x07FFFFFE, - 0x00000000, 0x00800000, 0xFF7FFFFF, 0xFF7FFFFF, 0x00FFFFFF, 0x00000000, - 0xFFFF0000, 0xFFFFFFFF, 0xFFFFFFFF, 0xF80001FF, 0x00030003, 0x00000000, - 0xFFFFFFFF, 0xFFFFFFFF, 0x0000003F, 0x00000003, 0xFFFFD7C0, 0xFFFFFFFB, - 0x547F7FFF, 0x000FFFFD, 0xFFFFDFFE, 0xFFFFFFFF, 0xDFFEFFFF, 0xFFFFFFFF, - 0xFFFF007B, 0xFFFFFFFF, 0xFFFF199F, 0x033FCFFF, 0x00000000, 0xFFFE0000, - 0x027FFFFF, 0xFFFFFFFE, 0xFFFE007F, 0xBBFFFFFB, 0xFFFF0016, 0x000707FF, - 0x00000000, 0x07FFFFFE, 0x0007FFFF, 0xFFFF03FF, 0xFFFFFFFF, 0x7CFFFFFF, - 0xFFEF7FFF, 0x03FF3DFF, 0xFFFFFFEE, 0xF3FFFFFF, 0xFF1E3FFF, 0x0000FFCF, - 0xFFF99FEE, 0xD3C5FDFF, 0xB080399F, 0x0003FFCF, 0xFFF987E4, 0xD36DFDFF, - 0x5E003987, 0x001FFFC0, 0xFFFBAFEE, 0xF3EDFDFF, 0x00003BBF, 0x0000FFC1, - 0xFFF99FEE, 0xF3CDFDFF, 0xB0C0398F, 0x0000FFC3, 0xD63DC7EC, 0xC3BFC718, - 0x00803DC7, 0x0000FF80, 0xFFFDDFEE, 0xC3EFFDFF, 0x00603DDF, 0x0000FFC3, - 0xFFFDDFEC, 0xC3EFFDFF, 0x40603DDF, 0x0000FFC3, 0xFFFDDFEC, 0xC3FFFDFF, - 0x00803DCF, 0x0000FFC3, 0x00000000, 0x00000000, 0x00000000, 0x00000000, - 0xFFFFFFFE, 0x07FF7FFF, 0x03FF7FFF, 0x00000000, 0xFEF02596, 0x3BFF6CAE, - 0x03FF3F5F, 0x00000000, 0x03000000, 0xC2A003FF, 0xFFFFFEFF, 0xFFFE03FF, - 0xFEBF0FDF, 0x02FE3FFF, 0x00000000, 0x00000000, 0x00000000, 0x00000000, - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1FFF0000, 0x00000002, - 0x000000A0, 0x003EFFFE, 0xFFFFFFFE, 0xFFFFFFFF, 0x661FFFFF, 0xFFFFFFFE, - 0xFFFFFFFF, 0x77FFFFFF, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, + 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0x04000000, 0x87FFFFFE, 0x07FFFFFE, 0x00000000, 0x00000000, + 0xFF7FFFFF, 0xFF7FFFFF, 0xFFFFFFFF, 0x7FF3FFFF, 0xFFFFFDFE, 0x7FFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFE00F, 0xFC31FFFF, 0x00FFFFFF, + 0x00000000, 0xFFFF0000, 0xFFFFFFFF, 0xFFFFFFFF, 0xF80001FF, 0x00000003, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0xFFFFD740, 0xFFFFFFFB, 0x547F7FFF, 0x000FFFFD, 0xFFFFDFFE, 0xFFFFFFFF, 0xDFFEFFFF, 0xFFFFFFFF, 0xFFFF0003, 0xFFFFFFFF, 0xFFFF199F, + 0x033FCFFF, 0x00000000, 0xFFFE0000, 0x027FFFFF, 0xFFFFFFFE, 0x0000007F, 0x00000000, 0xFFFF0000, 0x000707FF, 0x00000000, 0x07FFFFFE, + 0x000007FE, 0xFFFE0000, 0xFFFFFFFF, 0x7CFFFFFF, 0x002F7FFF, 0x00000060, 0xFFFFFFE0, 0x23FFFFFF, 0xFF000000, 0x00000003, 0xFFF99FE0, + 0x03C5FDFF, 0xB0000000, 0x00030003, 0xFFF987E0, 0x036DFDFF, 0x5E000000, 0x001C0000, 0xFFFBAFE0, 0x23EDFDFF, 0x00000000, 0x00000001, + 0xFFF99FE0, 0x23CDFDFF, 0xB0000000, 0x00000003, 0xD63DC7E0, 0x03BFC718, 0x00000000, 0x00000000, 0xFFFDDFE0, 0x03EFFDFF, 0x00000000, + 0x00000003, 0xFFFDDFE0, 0x03EFFDFF, 0x40000000, 0x00000003, 0xFFFDDFE0, 0x03FFFDFF, 0x00000000, 0x00000003, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xFFFFFFFE, 0x000D7FFF, 0x0000003F, 0x00000000, 0xFEF02596, 0x200D6CAE, 0x0000001F, 0x00000000, 0x00000000, + 0x00000000, 0xFFFFFEFF, 0x000003FF, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0xFFFFFFFF, 0xFFFF003F, 0x007FFFFF, 0x0007DAED, 0x50000000, 0x82315001, 0x002C62AB, 0x40000000, 0xF580C900, 0x00000007, + 0x02010800, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x0FFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x03FFFFFF, 0x3F3FFFFF, 0xFFFFFFFF, + 0xAAFF3F3F, 0x3FFFFFFF, 0xFFFFFFFF, 0x5FDFFFFF, 0x0FCF1FDC, 0x1FDC1FFF, 0x00000000, 0x00004C40, 0x00000000, 0x00000000, 0x00000007, + 0x00000000, 0x00000000, 0x00000000, 0x00000080, 0x000003FE, 0xFFFFFFFE, 0xFFFFFFFF, 0x001FFFFF, 0xFFFFFFFE, 0xFFFFFFFF, 0x07FFFFFF, + 0xFFFFFFE0, 0x00001FFF, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, + 0xFFFFFFFF, 0xFFFFFFFF, 0x0000003F, 0x00000000, 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x0000000F, + 0x00000000, 0x00000000, 0x00000000, 0x07FF6000, 0x87FFFFFE, 0x07FFFFFE, 0x00000000, 0x00800000, 0xFF7FFFFF, 0xFF7FFFFF, 0x00FFFFFF, + 0x00000000, 0xFFFF0000, 0xFFFFFFFF, 0xFFFFFFFF, 0xF80001FF, 0x00030003, 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF, 0x0000003F, 0x00000003, + 0xFFFFD7C0, 0xFFFFFFFB, 0x547F7FFF, 0x000FFFFD, 0xFFFFDFFE, 0xFFFFFFFF, 0xDFFEFFFF, 0xFFFFFFFF, 0xFFFF007B, 0xFFFFFFFF, 0xFFFF199F, + 0x033FCFFF, 0x00000000, 0xFFFE0000, 0x027FFFFF, 0xFFFFFFFE, 0xFFFE007F, 0xBBFFFFFB, 0xFFFF0016, 0x000707FF, 0x00000000, 0x07FFFFFE, + 0x0007FFFF, 0xFFFF03FF, 0xFFFFFFFF, 0x7CFFFFFF, 0xFFEF7FFF, 0x03FF3DFF, 0xFFFFFFEE, 0xF3FFFFFF, 0xFF1E3FFF, 0x0000FFCF, 0xFFF99FEE, + 0xD3C5FDFF, 0xB080399F, 0x0003FFCF, 0xFFF987E4, 0xD36DFDFF, 0x5E003987, 0x001FFFC0, 0xFFFBAFEE, 0xF3EDFDFF, 0x00003BBF, 0x0000FFC1, + 0xFFF99FEE, 0xF3CDFDFF, 0xB0C0398F, 0x0000FFC3, 0xD63DC7EC, 0xC3BFC718, 0x00803DC7, 0x0000FF80, 0xFFFDDFEE, 0xC3EFFDFF, 0x00603DDF, + 0x0000FFC3, 0xFFFDDFEC, 0xC3EFFDFF, 0x40603DDF, 0x0000FFC3, 0xFFFDDFEC, 0xC3FFFDFF, 0x00803DCF, 0x0000FFC3, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xFFFFFFFE, 0x07FF7FFF, 0x03FF7FFF, 0x00000000, 0xFEF02596, 0x3BFF6CAE, 0x03FF3F5F, 0x00000000, 0x03000000, + 0xC2A003FF, 0xFFFFFEFF, 0xFFFE03FF, 0xFEBF0FDF, 0x02FE3FFF, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x1FFF0000, 0x00000002, 0x000000A0, 0x003EFFFE, 0xFFFFFFFE, 0xFFFFFFFF, 0x661FFFFF, 0xFFFFFFFE, 0xFFFFFFFF, + 0x77FFFFFF, }; static const unsigned char nmstrtPages[] = { - 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x00, 0x00, 0x09, 0x0A, 0x0B, - 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0x13, 0x00, 0x14, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x15, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x17, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x18, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, + 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x00, 0x00, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0x13, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x15, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x17, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x18, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static const unsigned char namePages[] = { - 0x19, 0x03, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x00, 0x00, 0x1F, 0x20, 0x21, - 0x22, 0x23, 0x24, 0x25, 0x10, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0x13, 0x26, 0x14, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x27, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x17, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x18, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, + 0x19, 0x03, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x00, 0x00, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x10, 0x11, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0x13, 0x26, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x27, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x17, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x18, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; diff --git a/base/poco/XML/src/siphash.h b/base/poco/XML/src/siphash.h index 2199632980d..26f4b36507f 100644 --- a/base/poco/XML/src/siphash.h +++ b/base/poco/XML/src/siphash.h @@ -99,7 +99,7 @@ #define SIPHASH_H #include /* size_t */ -# include /* uint64_t uint32_t uint8_t */ +#include /* uint64_t uint32_t uint8_t */ /* * Workaround to not require a C++11 compiler for using ULL suffix @@ -110,167 +110,172 @@ #define SIP_ROTL(x, b) (uint64_t)(((x) << (b)) | ((x) >> (64 - (b)))) -#define SIP_U32TO8_LE(p, v) \ - (p)[0] = (uint8_t)((v) >> 0); \ - (p)[1] = (uint8_t)((v) >> 8); \ - (p)[2] = (uint8_t)((v) >> 16); \ - (p)[3] = (uint8_t)((v) >> 24); +#define SIP_U32TO8_LE(p, v) \ + (p)[0] = (uint8_t)((v) >> 0); \ + (p)[1] = (uint8_t)((v) >> 8); \ + (p)[2] = (uint8_t)((v) >> 16); \ + (p)[3] = (uint8_t)((v) >> 24); -#define SIP_U64TO8_LE(p, v) \ - SIP_U32TO8_LE((p) + 0, (uint32_t)((v) >> 0)); \ - SIP_U32TO8_LE((p) + 4, (uint32_t)((v) >> 32)); +#define SIP_U64TO8_LE(p, v) \ + SIP_U32TO8_LE((p) + 0, (uint32_t)((v) >> 0)); \ + SIP_U32TO8_LE((p) + 4, (uint32_t)((v) >> 32)); -#define SIP_U8TO64_LE(p) \ - (((uint64_t)((p)[0]) << 0) | ((uint64_t)((p)[1]) << 8) \ - | ((uint64_t)((p)[2]) << 16) | ((uint64_t)((p)[3]) << 24) \ - | ((uint64_t)((p)[4]) << 32) | ((uint64_t)((p)[5]) << 40) \ - | ((uint64_t)((p)[6]) << 48) | ((uint64_t)((p)[7]) << 56)) +#define SIP_U8TO64_LE(p) \ + (((uint64_t)((p)[0]) << 0) | ((uint64_t)((p)[1]) << 8) | ((uint64_t)((p)[2]) << 16) | ((uint64_t)((p)[3]) << 24) \ + | ((uint64_t)((p)[4]) << 32) | ((uint64_t)((p)[5]) << 40) | ((uint64_t)((p)[6]) << 48) | ((uint64_t)((p)[7]) << 56)) -#define SIPHASH_INITIALIZER \ - { 0, 0, 0, 0, {0}, 0, 0 } +#define SIPHASH_INITIALIZER \ + { \ + 0, 0, 0, 0, {0}, 0, 0 \ + } -struct siphash { - uint64_t v0, v1, v2, v3; +struct siphash +{ + uint64_t v0, v1, v2, v3; - unsigned char buf[8], *p; - uint64_t c; + unsigned char buf[8], *p; + uint64_t c; }; /* struct siphash */ #define SIP_KEYLEN 16 -struct sipkey { - uint64_t k[2]; +struct sipkey +{ + uint64_t k[2]; }; /* struct sipkey */ #define sip_keyof(k) sip_tokey(&(struct sipkey){{0}}, (k)) -static struct sipkey * -sip_tokey(struct sipkey *key, const void *src) { - key->k[0] = SIP_U8TO64_LE((const unsigned char *)src); - key->k[1] = SIP_U8TO64_LE((const unsigned char *)src + 8); - return key; +static struct sipkey * sip_tokey(struct sipkey * key, const void * src) +{ + key->k[0] = SIP_U8TO64_LE((const unsigned char *)src); + key->k[1] = SIP_U8TO64_LE((const unsigned char *)src + 8); + return key; } /* sip_tokey() */ #ifdef SIPHASH_TOBIN -# define sip_binof(v) sip_tobin((unsigned char[8]){0}, (v)) +# define sip_binof(v) sip_tobin((unsigned char[8]){0}, (v)) -static void * -sip_tobin(void *dst, uint64_t u64) { - SIP_U64TO8_LE((unsigned char *)dst, u64); - return dst; +static void * sip_tobin(void * dst, uint64_t u64) +{ + SIP_U64TO8_LE((unsigned char *)dst, u64); + return dst; } /* sip_tobin() */ #endif /* SIPHASH_TOBIN */ -static void -sip_round(struct siphash *H, const int rounds) { - int i; +static void sip_round(struct siphash * H, const int rounds) +{ + int i; - for (i = 0; i < rounds; i++) { - H->v0 += H->v1; - H->v1 = SIP_ROTL(H->v1, 13); - H->v1 ^= H->v0; - H->v0 = SIP_ROTL(H->v0, 32); + for (i = 0; i < rounds; i++) + { + H->v0 += H->v1; + H->v1 = SIP_ROTL(H->v1, 13); + H->v1 ^= H->v0; + H->v0 = SIP_ROTL(H->v0, 32); - H->v2 += H->v3; - H->v3 = SIP_ROTL(H->v3, 16); - H->v3 ^= H->v2; + H->v2 += H->v3; + H->v3 = SIP_ROTL(H->v3, 16); + H->v3 ^= H->v2; - H->v0 += H->v3; - H->v3 = SIP_ROTL(H->v3, 21); - H->v3 ^= H->v0; + H->v0 += H->v3; + H->v3 = SIP_ROTL(H->v3, 21); + H->v3 ^= H->v0; - H->v2 += H->v1; - H->v1 = SIP_ROTL(H->v1, 17); - H->v1 ^= H->v2; - H->v2 = SIP_ROTL(H->v2, 32); - } + H->v2 += H->v1; + H->v1 = SIP_ROTL(H->v1, 17); + H->v1 ^= H->v2; + H->v2 = SIP_ROTL(H->v2, 32); + } } /* sip_round() */ -static struct siphash * -sip24_init(struct siphash *H, const struct sipkey *key) { - H->v0 = _SIP_ULL(0x736f6d65U, 0x70736575U) ^ key->k[0]; - H->v1 = _SIP_ULL(0x646f7261U, 0x6e646f6dU) ^ key->k[1]; - H->v2 = _SIP_ULL(0x6c796765U, 0x6e657261U) ^ key->k[0]; - H->v3 = _SIP_ULL(0x74656462U, 0x79746573U) ^ key->k[1]; +static struct siphash * sip24_init(struct siphash * H, const struct sipkey * key) +{ + H->v0 = _SIP_ULL(0x736f6d65U, 0x70736575U) ^ key->k[0]; + H->v1 = _SIP_ULL(0x646f7261U, 0x6e646f6dU) ^ key->k[1]; + H->v2 = _SIP_ULL(0x6c796765U, 0x6e657261U) ^ key->k[0]; + H->v3 = _SIP_ULL(0x74656462U, 0x79746573U) ^ key->k[1]; - H->p = H->buf; - H->c = 0; + H->p = H->buf; + H->c = 0; - return H; + return H; } /* sip24_init() */ #define sip_endof(a) (&(a)[sizeof(a) / sizeof *(a)]) -static struct siphash * -sip24_update(struct siphash *H, const void *src, size_t len) { - const unsigned char *p = (const unsigned char *)src, *pe = p + len; - uint64_t m; +static struct siphash * sip24_update(struct siphash * H, const void * src, size_t len) +{ + const unsigned char *p = (const unsigned char *)src, *pe = p + len; + uint64_t m; - do { - while (p < pe && H->p < sip_endof(H->buf)) - *H->p++ = *p++; + do + { + while (p < pe && H->p < sip_endof(H->buf)) + *H->p++ = *p++; - if (H->p < sip_endof(H->buf)) - break; + if (H->p < sip_endof(H->buf)) + break; - m = SIP_U8TO64_LE(H->buf); - H->v3 ^= m; - sip_round(H, 2); - H->v0 ^= m; + m = SIP_U8TO64_LE(H->buf); + H->v3 ^= m; + sip_round(H, 2); + H->v0 ^= m; - H->p = H->buf; - H->c += 8; - } while (p < pe); + H->p = H->buf; + H->c += 8; + } while (p < pe); - return H; + return H; } /* sip24_update() */ -static uint64_t -sip24_final(struct siphash *H) { - const char left = (char)(H->p - H->buf); - uint64_t b = (H->c + left) << 56; +static uint64_t sip24_final(struct siphash * H) +{ + const char left = (char)(H->p - H->buf); + uint64_t b = (H->c + left) << 56; - switch (left) { - case 7: - b |= (uint64_t)H->buf[6] << 48; - /* fall through */ - case 6: - b |= (uint64_t)H->buf[5] << 40; - /* fall through */ - case 5: - b |= (uint64_t)H->buf[4] << 32; - /* fall through */ - case 4: - b |= (uint64_t)H->buf[3] << 24; - /* fall through */ - case 3: - b |= (uint64_t)H->buf[2] << 16; - /* fall through */ - case 2: - b |= (uint64_t)H->buf[1] << 8; - /* fall through */ - case 1: - b |= (uint64_t)H->buf[0] << 0; - /* fall through */ - case 0: - break; - } + switch (left) + { + case 7: + b |= (uint64_t)H->buf[6] << 48; + /* fall through */ + case 6: + b |= (uint64_t)H->buf[5] << 40; + /* fall through */ + case 5: + b |= (uint64_t)H->buf[4] << 32; + /* fall through */ + case 4: + b |= (uint64_t)H->buf[3] << 24; + /* fall through */ + case 3: + b |= (uint64_t)H->buf[2] << 16; + /* fall through */ + case 2: + b |= (uint64_t)H->buf[1] << 8; + /* fall through */ + case 1: + b |= (uint64_t)H->buf[0] << 0; + /* fall through */ + case 0: + break; + } - H->v3 ^= b; - sip_round(H, 2); - H->v0 ^= b; - H->v2 ^= 0xff; - sip_round(H, 4); + H->v3 ^= b; + sip_round(H, 2); + H->v0 ^= b; + H->v2 ^= 0xff; + sip_round(H, 4); - return H->v0 ^ H->v1 ^ H->v2 ^ H->v3; + return H->v0 ^ H->v1 ^ H->v2 ^ H->v3; } /* sip24_final() */ -static uint64_t -siphash24(const void *src, size_t len, const struct sipkey *key) { - struct siphash state = SIPHASH_INITIALIZER; - return sip24_final(sip24_update(sip24_init(&state, key), src, len)); +static uint64_t siphash24(const void * src, size_t len, const struct sipkey * key) +{ + struct siphash state = SIPHASH_INITIALIZER; + return sip24_final(sip24_update(sip24_init(&state, key), src, len)); } /* siphash24() */ /* @@ -284,9 +289,9 @@ siphash24(const void *src, size_t len, const struct sipkey *key) { * ... * in = 00 01 02 ... 3e (63 bytes) */ -static int -sip24_valid(void) { - /* clang-format off */ +static int sip24_valid(void) +{ + /* clang-format off */ static const unsigned char vectors[64][8] = { { 0x31, 0x0e, 0x0e, 0xdd, 0x47, 0xdb, 0x6f, 0x72, }, { 0xfd, 0x67, 0xdc, 0x93, 0xc5, 0x39, 0xf8, 0x74, }, @@ -353,39 +358,42 @@ sip24_valid(void) { { 0x57, 0x5f, 0xf2, 0x8e, 0x60, 0x38, 0x1b, 0xe5, }, { 0x72, 0x45, 0x06, 0xeb, 0x4c, 0x32, 0x8a, 0x95, } }; - /* clang-format on */ + /* clang-format on */ - unsigned char in[64]; - struct sipkey k; - size_t i; + unsigned char in[64]; + struct sipkey k; + size_t i; - sip_tokey(&k, "\000\001\002\003\004\005\006\007\010\011" - "\012\013\014\015\016\017"); + sip_tokey( + &k, + "\000\001\002\003\004\005\006\007\010\011" + "\012\013\014\015\016\017"); - for (i = 0; i < sizeof in; ++i) { - in[i] = (unsigned char)i; + for (i = 0; i < sizeof in; ++i) + { + in[i] = (unsigned char)i; - if (siphash24(in, i, &k) != SIP_U8TO64_LE(vectors[i])) - return 0; - } + if (siphash24(in, i, &k) != SIP_U8TO64_LE(vectors[i])) + return 0; + } - return 1; + return 1; } /* sip24_valid() */ #ifdef SIPHASH_MAIN -# include +# include -int -main(void) { - const int ok = sip24_valid(); +int main(void) +{ + const int ok = sip24_valid(); - if (ok) - puts("OK"); - else - puts("FAIL"); + if (ok) + puts("OK"); + else + puts("FAIL"); - return ! ok; + return !ok; } /* main() */ #endif /* SIPHASH_MAIN */ diff --git a/base/poco/XML/src/utf8tab.h b/base/poco/XML/src/utf8tab.h index 4e28ec2e9a9..f8d5ad49c62 100644 --- a/base/poco/XML/src/utf8tab.h +++ b/base/poco/XML/src/utf8tab.h @@ -33,34 +33,34 @@ */ /* 0x80 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, -/* 0x84 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, -/* 0x88 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, -/* 0x8C */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, -/* 0x90 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, -/* 0x94 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, -/* 0x98 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, -/* 0x9C */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, -/* 0xA0 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, -/* 0xA4 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, -/* 0xA8 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, -/* 0xAC */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, -/* 0xB0 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, -/* 0xB4 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, -/* 0xB8 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, -/* 0xBC */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, -/* 0xC0 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2, -/* 0xC4 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2, -/* 0xC8 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2, -/* 0xCC */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2, -/* 0xD0 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2, -/* 0xD4 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2, -/* 0xD8 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2, -/* 0xDC */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2, -/* 0xE0 */ BT_LEAD3, BT_LEAD3, BT_LEAD3, BT_LEAD3, -/* 0xE4 */ BT_LEAD3, BT_LEAD3, BT_LEAD3, BT_LEAD3, -/* 0xE8 */ BT_LEAD3, BT_LEAD3, BT_LEAD3, BT_LEAD3, -/* 0xEC */ BT_LEAD3, BT_LEAD3, BT_LEAD3, BT_LEAD3, -/* 0xF0 */ BT_LEAD4, BT_LEAD4, BT_LEAD4, BT_LEAD4, -/* 0xF4 */ BT_LEAD4, BT_NONXML, BT_NONXML, BT_NONXML, -/* 0xF8 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, -/* 0xFC */ BT_NONXML, BT_NONXML, BT_MALFORM, BT_MALFORM, + /* 0x84 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, + /* 0x88 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, + /* 0x8C */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, + /* 0x90 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, + /* 0x94 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, + /* 0x98 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, + /* 0x9C */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, + /* 0xA0 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, + /* 0xA4 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, + /* 0xA8 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, + /* 0xAC */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, + /* 0xB0 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, + /* 0xB4 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, + /* 0xB8 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, + /* 0xBC */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, + /* 0xC0 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2, + /* 0xC4 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2, + /* 0xC8 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2, + /* 0xCC */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2, + /* 0xD0 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2, + /* 0xD4 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2, + /* 0xD8 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2, + /* 0xDC */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2, + /* 0xE0 */ BT_LEAD3, BT_LEAD3, BT_LEAD3, BT_LEAD3, + /* 0xE4 */ BT_LEAD3, BT_LEAD3, BT_LEAD3, BT_LEAD3, + /* 0xE8 */ BT_LEAD3, BT_LEAD3, BT_LEAD3, BT_LEAD3, + /* 0xEC */ BT_LEAD3, BT_LEAD3, BT_LEAD3, BT_LEAD3, + /* 0xF0 */ BT_LEAD4, BT_LEAD4, BT_LEAD4, BT_LEAD4, + /* 0xF4 */ BT_LEAD4, BT_NONXML, BT_NONXML, BT_NONXML, + /* 0xF8 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, + /* 0xFC */ BT_NONXML, BT_NONXML, BT_MALFORM, BT_MALFORM, diff --git a/base/poco/XML/src/xmlrole.h b/base/poco/XML/src/xmlrole.h index 0262f7b24c8..f33f859b2c4 100644 --- a/base/poco/XML/src/xmlrole.h +++ b/base/poco/XML/src/xmlrole.h @@ -39,7 +39,7 @@ #ifdef __VMS /* 0 1 2 3 0 1 2 3 1234567890123456789012345678901 1234567890123456789012345678901 */ -# define XmlPrologStateInitExternalEntity XmlPrologStateInitExternalEnt +# define XmlPrologStateInitExternalEntity XmlPrologStateInitExternalEnt #endif #include "xmltok.h" @@ -48,82 +48,83 @@ extern "C" { #endif -enum { - XML_ROLE_ERROR = -1, - XML_ROLE_NONE = 0, - XML_ROLE_XML_DECL, - XML_ROLE_INSTANCE_START, - XML_ROLE_DOCTYPE_NONE, - XML_ROLE_DOCTYPE_NAME, - XML_ROLE_DOCTYPE_SYSTEM_ID, - XML_ROLE_DOCTYPE_PUBLIC_ID, - XML_ROLE_DOCTYPE_INTERNAL_SUBSET, - XML_ROLE_DOCTYPE_CLOSE, - XML_ROLE_GENERAL_ENTITY_NAME, - XML_ROLE_PARAM_ENTITY_NAME, - XML_ROLE_ENTITY_NONE, - XML_ROLE_ENTITY_VALUE, - XML_ROLE_ENTITY_SYSTEM_ID, - XML_ROLE_ENTITY_PUBLIC_ID, - XML_ROLE_ENTITY_COMPLETE, - XML_ROLE_ENTITY_NOTATION_NAME, - XML_ROLE_NOTATION_NONE, - XML_ROLE_NOTATION_NAME, - XML_ROLE_NOTATION_SYSTEM_ID, - XML_ROLE_NOTATION_NO_SYSTEM_ID, - XML_ROLE_NOTATION_PUBLIC_ID, - XML_ROLE_ATTRIBUTE_NAME, - XML_ROLE_ATTRIBUTE_TYPE_CDATA, - XML_ROLE_ATTRIBUTE_TYPE_ID, - XML_ROLE_ATTRIBUTE_TYPE_IDREF, - XML_ROLE_ATTRIBUTE_TYPE_IDREFS, - XML_ROLE_ATTRIBUTE_TYPE_ENTITY, - XML_ROLE_ATTRIBUTE_TYPE_ENTITIES, - XML_ROLE_ATTRIBUTE_TYPE_NMTOKEN, - XML_ROLE_ATTRIBUTE_TYPE_NMTOKENS, - XML_ROLE_ATTRIBUTE_ENUM_VALUE, - XML_ROLE_ATTRIBUTE_NOTATION_VALUE, - XML_ROLE_ATTLIST_NONE, - XML_ROLE_ATTLIST_ELEMENT_NAME, - XML_ROLE_IMPLIED_ATTRIBUTE_VALUE, - XML_ROLE_REQUIRED_ATTRIBUTE_VALUE, - XML_ROLE_DEFAULT_ATTRIBUTE_VALUE, - XML_ROLE_FIXED_ATTRIBUTE_VALUE, - XML_ROLE_ELEMENT_NONE, - XML_ROLE_ELEMENT_NAME, - XML_ROLE_CONTENT_ANY, - XML_ROLE_CONTENT_EMPTY, - XML_ROLE_CONTENT_PCDATA, - XML_ROLE_GROUP_OPEN, - XML_ROLE_GROUP_CLOSE, - XML_ROLE_GROUP_CLOSE_REP, - XML_ROLE_GROUP_CLOSE_OPT, - XML_ROLE_GROUP_CLOSE_PLUS, - XML_ROLE_GROUP_CHOICE, - XML_ROLE_GROUP_SEQUENCE, - XML_ROLE_CONTENT_ELEMENT, - XML_ROLE_CONTENT_ELEMENT_REP, - XML_ROLE_CONTENT_ELEMENT_OPT, - XML_ROLE_CONTENT_ELEMENT_PLUS, - XML_ROLE_PI, - XML_ROLE_COMMENT, +enum +{ + XML_ROLE_ERROR = -1, + XML_ROLE_NONE = 0, + XML_ROLE_XML_DECL, + XML_ROLE_INSTANCE_START, + XML_ROLE_DOCTYPE_NONE, + XML_ROLE_DOCTYPE_NAME, + XML_ROLE_DOCTYPE_SYSTEM_ID, + XML_ROLE_DOCTYPE_PUBLIC_ID, + XML_ROLE_DOCTYPE_INTERNAL_SUBSET, + XML_ROLE_DOCTYPE_CLOSE, + XML_ROLE_GENERAL_ENTITY_NAME, + XML_ROLE_PARAM_ENTITY_NAME, + XML_ROLE_ENTITY_NONE, + XML_ROLE_ENTITY_VALUE, + XML_ROLE_ENTITY_SYSTEM_ID, + XML_ROLE_ENTITY_PUBLIC_ID, + XML_ROLE_ENTITY_COMPLETE, + XML_ROLE_ENTITY_NOTATION_NAME, + XML_ROLE_NOTATION_NONE, + XML_ROLE_NOTATION_NAME, + XML_ROLE_NOTATION_SYSTEM_ID, + XML_ROLE_NOTATION_NO_SYSTEM_ID, + XML_ROLE_NOTATION_PUBLIC_ID, + XML_ROLE_ATTRIBUTE_NAME, + XML_ROLE_ATTRIBUTE_TYPE_CDATA, + XML_ROLE_ATTRIBUTE_TYPE_ID, + XML_ROLE_ATTRIBUTE_TYPE_IDREF, + XML_ROLE_ATTRIBUTE_TYPE_IDREFS, + XML_ROLE_ATTRIBUTE_TYPE_ENTITY, + XML_ROLE_ATTRIBUTE_TYPE_ENTITIES, + XML_ROLE_ATTRIBUTE_TYPE_NMTOKEN, + XML_ROLE_ATTRIBUTE_TYPE_NMTOKENS, + XML_ROLE_ATTRIBUTE_ENUM_VALUE, + XML_ROLE_ATTRIBUTE_NOTATION_VALUE, + XML_ROLE_ATTLIST_NONE, + XML_ROLE_ATTLIST_ELEMENT_NAME, + XML_ROLE_IMPLIED_ATTRIBUTE_VALUE, + XML_ROLE_REQUIRED_ATTRIBUTE_VALUE, + XML_ROLE_DEFAULT_ATTRIBUTE_VALUE, + XML_ROLE_FIXED_ATTRIBUTE_VALUE, + XML_ROLE_ELEMENT_NONE, + XML_ROLE_ELEMENT_NAME, + XML_ROLE_CONTENT_ANY, + XML_ROLE_CONTENT_EMPTY, + XML_ROLE_CONTENT_PCDATA, + XML_ROLE_GROUP_OPEN, + XML_ROLE_GROUP_CLOSE, + XML_ROLE_GROUP_CLOSE_REP, + XML_ROLE_GROUP_CLOSE_OPT, + XML_ROLE_GROUP_CLOSE_PLUS, + XML_ROLE_GROUP_CHOICE, + XML_ROLE_GROUP_SEQUENCE, + XML_ROLE_CONTENT_ELEMENT, + XML_ROLE_CONTENT_ELEMENT_REP, + XML_ROLE_CONTENT_ELEMENT_OPT, + XML_ROLE_CONTENT_ELEMENT_PLUS, + XML_ROLE_PI, + XML_ROLE_COMMENT, #ifdef XML_DTD - XML_ROLE_TEXT_DECL, - XML_ROLE_IGNORE_SECT, - XML_ROLE_INNER_PARAM_ENTITY_REF, + XML_ROLE_TEXT_DECL, + XML_ROLE_IGNORE_SECT, + XML_ROLE_INNER_PARAM_ENTITY_REF, #endif /* XML_DTD */ - XML_ROLE_PARAM_ENTITY_REF + XML_ROLE_PARAM_ENTITY_REF }; -typedef struct prolog_state { - int(PTRCALL *handler)(struct prolog_state *state, int tok, const char *ptr, - const char *end, const ENCODING *enc); - unsigned level; - int role_none; +typedef struct prolog_state +{ + int(PTRCALL * handler)(struct prolog_state * state, int tok, const char * ptr, const char * end, const ENCODING * enc); + unsigned level; + int role_none; #ifdef XML_DTD - unsigned includeLevel; - int documentEntity; - int inEntityValue; + unsigned includeLevel; + int documentEntity; + int inEntityValue; #endif /* XML_DTD */ } PROLOG_STATE; @@ -132,8 +133,7 @@ void XmlPrologStateInit(PROLOG_STATE *); void XmlPrologStateInitExternalEntity(PROLOG_STATE *); #endif /* XML_DTD */ -#define XmlTokenRole(state, tok, ptr, end, enc) \ - (((state)->handler)(state, tok, ptr, end, enc)) +#define XmlTokenRole(state, tok, ptr, end, enc) (((state)->handler)(state, tok, ptr, end, enc)) #ifdef __cplusplus } diff --git a/base/poco/XML/src/xmltok.h b/base/poco/XML/src/xmltok.h index 4e786a14307..80c78a9eb75 100644 --- a/base/poco/XML/src/xmltok.h +++ b/base/poco/XML/src/xmltok.h @@ -42,18 +42,18 @@ extern "C" { #endif /* The following token may be returned by XmlContentTok */ -#define XML_TOK_TRAILING_RSQB \ - -5 /* ] or ]] at the end of the scan; might be \ +#define XML_TOK_TRAILING_RSQB \ + -5 /* ] or ]] at the end of the scan; might be \ start of illegal ]]> sequence */ /* The following tokens may be returned by both XmlPrologTok and XmlContentTok. */ #define XML_TOK_NONE -4 /* The string to be scanned is empty */ -#define XML_TOK_TRAILING_CR \ - -3 /* A CR at the end of the scan; \ +#define XML_TOK_TRAILING_CR \ + -3 /* A CR at the end of the scan; \ might be part of CRLF sequence */ #define XML_TOK_PARTIAL_CHAR -2 /* only part of a multibyte sequence */ -#define XML_TOK_PARTIAL -1 /* only part of a token */ +#define XML_TOK_PARTIAL -1 /* only part of a token */ #define XML_TOK_INVALID 0 /* The following tokens are returned by XmlContentTok; some are also @@ -73,19 +73,19 @@ extern "C" { /* The following tokens may be returned by both XmlPrologTok and XmlContentTok. */ -#define XML_TOK_PI 11 /* processing instruction */ +#define XML_TOK_PI 11 /* processing instruction */ #define XML_TOK_XML_DECL 12 /* XML decl or text decl */ #define XML_TOK_COMMENT 13 #define XML_TOK_BOM 14 /* Byte order mark */ /* The following tokens are returned only by XmlPrologTok */ #define XML_TOK_PROLOG_S 15 -#define XML_TOK_DECL_OPEN 16 /* */ #define XML_TOK_NAME 18 #define XML_TOK_NMTOKEN 19 #define XML_TOK_POUND_NAME 20 /* #name */ -#define XML_TOK_OR 21 /* | */ +#define XML_TOK_OR 21 /* | */ #define XML_TOK_PERCENT 22 #define XML_TOK_OPEN_PAREN 23 #define XML_TOK_CLOSE_PAREN 24 @@ -96,14 +96,14 @@ extern "C" { #define XML_TOK_INSTANCE_START 29 /* The following occur only in element type declarations */ -#define XML_TOK_NAME_QUESTION 30 /* name? */ -#define XML_TOK_NAME_ASTERISK 31 /* name* */ -#define XML_TOK_NAME_PLUS 32 /* name+ */ -#define XML_TOK_COND_SECT_OPEN 33 /* */ +#define XML_TOK_NAME_QUESTION 30 /* name? */ +#define XML_TOK_NAME_ASTERISK 31 /* name* */ +#define XML_TOK_NAME_PLUS 32 /* name+ */ +#define XML_TOK_COND_SECT_OPEN 33 /* */ #define XML_TOK_CLOSE_PAREN_QUESTION 35 /* )? */ #define XML_TOK_CLOSE_PAREN_ASTERISK 36 /* )* */ -#define XML_TOK_CLOSE_PAREN_PLUS 37 /* )+ */ +#define XML_TOK_CLOSE_PAREN_PLUS 37 /* )+ */ #define XML_TOK_COMMA 38 /* The following token is returned only by XmlAttributeValueTok */ @@ -118,20 +118,20 @@ extern "C" { #define XML_TOK_PREFIXED_NAME 41 #ifdef XML_DTD -# define XML_TOK_IGNORE_SECT 42 +# define XML_TOK_IGNORE_SECT 42 #endif /* XML_DTD */ #ifdef XML_DTD -# define XML_N_STATES 4 +# define XML_N_STATES 4 #else /* not XML_DTD */ -# define XML_N_STATES 3 +# define XML_N_STATES 3 #endif /* not XML_DTD */ #define XML_PROLOG_STATE 0 #define XML_CONTENT_STATE 1 #define XML_CDATA_SECTION_STATE 2 #ifdef XML_DTD -# define XML_IGNORE_SECTION_STATE 3 +# define XML_IGNORE_SECTION_STATE 3 #endif /* XML_DTD */ #define XML_N_LITERAL_TYPES 2 @@ -143,60 +143,52 @@ extern "C" { /* The size of the buffer passed to XmlUtf16Encode must be at least this. */ #define XML_UTF16_ENCODE_MAX 2 -typedef struct position { - /* first line and first column are 0 not 1 */ - XML_Size lineNumber; - XML_Size columnNumber; +typedef struct position +{ + /* first line and first column are 0 not 1 */ + XML_Size lineNumber; + XML_Size columnNumber; } POSITION; -typedef struct { - const char *name; - const char *valuePtr; - const char *valueEnd; - char normalized; +typedef struct +{ + const char * name; + const char * valuePtr; + const char * valueEnd; + char normalized; } ATTRIBUTE; struct encoding; typedef struct encoding ENCODING; -typedef int(PTRCALL *SCANNER)(const ENCODING *, const char *, const char *, - const char **); +typedef int(PTRCALL * SCANNER)(const ENCODING *, const char *, const char *, const char **); -enum XML_Convert_Result { - XML_CONVERT_COMPLETED = 0, - XML_CONVERT_INPUT_INCOMPLETE = 1, - XML_CONVERT_OUTPUT_EXHAUSTED - = 2 /* and therefore potentially input remaining as well */ +enum XML_Convert_Result +{ + XML_CONVERT_COMPLETED = 0, + XML_CONVERT_INPUT_INCOMPLETE = 1, + XML_CONVERT_OUTPUT_EXHAUSTED = 2 /* and therefore potentially input remaining as well */ }; -struct encoding { - SCANNER scanners[XML_N_STATES]; - SCANNER literalScanners[XML_N_LITERAL_TYPES]; - int(PTRCALL *nameMatchesAscii)(const ENCODING *, const char *, const char *, - const char *); - int(PTRFASTCALL *nameLength)(const ENCODING *, const char *); - const char *(PTRFASTCALL *skipS)(const ENCODING *, const char *); - int(PTRCALL *getAtts)(const ENCODING *enc, const char *ptr, int attsMax, - ATTRIBUTE *atts); - int(PTRFASTCALL *charRefNumber)(const ENCODING *enc, const char *ptr); - int(PTRCALL *predefinedEntityName)(const ENCODING *, const char *, - const char *); - void(PTRCALL *updatePosition)(const ENCODING *, const char *ptr, - const char *end, POSITION *); - int(PTRCALL *isPublicId)(const ENCODING *enc, const char *ptr, - const char *end, const char **badPtr); - enum XML_Convert_Result(PTRCALL *utf8Convert)(const ENCODING *enc, - const char **fromP, - const char *fromLim, char **toP, - const char *toLim); - enum XML_Convert_Result(PTRCALL *utf16Convert)(const ENCODING *enc, - const char **fromP, - const char *fromLim, - unsigned short **toP, - const unsigned short *toLim); - int minBytesPerChar; - char isUtf8; - char isUtf16; +struct encoding +{ + SCANNER scanners[XML_N_STATES]; + SCANNER literalScanners[XML_N_LITERAL_TYPES]; + int(PTRCALL * nameMatchesAscii)(const ENCODING *, const char *, const char *, const char *); + int(PTRFASTCALL * nameLength)(const ENCODING *, const char *); + const char *(PTRFASTCALL * skipS)(const ENCODING *, const char *); + int(PTRCALL * getAtts)(const ENCODING * enc, const char * ptr, int attsMax, ATTRIBUTE * atts); + int(PTRFASTCALL * charRefNumber)(const ENCODING * enc, const char * ptr); + int(PTRCALL * predefinedEntityName)(const ENCODING *, const char *, const char *); + void(PTRCALL * updatePosition)(const ENCODING *, const char * ptr, const char * end, POSITION *); + int(PTRCALL * isPublicId)(const ENCODING * enc, const char * ptr, const char * end, const char ** badPtr); + enum XML_Convert_Result(PTRCALL * utf8Convert)( + const ENCODING * enc, const char ** fromP, const char * fromLim, char ** toP, const char * toLim); + enum XML_Convert_Result(PTRCALL * utf16Convert)( + const ENCODING * enc, const char ** fromP, const char * fromLim, unsigned short ** toP, const unsigned short * toLim); + int minBytesPerChar; + char isUtf8; + char isUtf16; }; /* Scan the string starting at ptr until the end of the next complete @@ -220,98 +212,94 @@ struct encoding { the prolog outside literals, comments and processing instructions. */ -#define XmlTok(enc, state, ptr, end, nextTokPtr) \ - (((enc)->scanners[state])(enc, ptr, end, nextTokPtr)) +#define XmlTok(enc, state, ptr, end, nextTokPtr) (((enc)->scanners[state])(enc, ptr, end, nextTokPtr)) -#define XmlPrologTok(enc, ptr, end, nextTokPtr) \ - XmlTok(enc, XML_PROLOG_STATE, ptr, end, nextTokPtr) +#define XmlPrologTok(enc, ptr, end, nextTokPtr) XmlTok(enc, XML_PROLOG_STATE, ptr, end, nextTokPtr) -#define XmlContentTok(enc, ptr, end, nextTokPtr) \ - XmlTok(enc, XML_CONTENT_STATE, ptr, end, nextTokPtr) +#define XmlContentTok(enc, ptr, end, nextTokPtr) XmlTok(enc, XML_CONTENT_STATE, ptr, end, nextTokPtr) -#define XmlCdataSectionTok(enc, ptr, end, nextTokPtr) \ - XmlTok(enc, XML_CDATA_SECTION_STATE, ptr, end, nextTokPtr) +#define XmlCdataSectionTok(enc, ptr, end, nextTokPtr) XmlTok(enc, XML_CDATA_SECTION_STATE, ptr, end, nextTokPtr) #ifdef XML_DTD -# define XmlIgnoreSectionTok(enc, ptr, end, nextTokPtr) \ - XmlTok(enc, XML_IGNORE_SECTION_STATE, ptr, end, nextTokPtr) +# define XmlIgnoreSectionTok(enc, ptr, end, nextTokPtr) XmlTok(enc, XML_IGNORE_SECTION_STATE, ptr, end, nextTokPtr) #endif /* XML_DTD */ /* This is used for performing a 2nd-level tokenization on the content of a literal that has already been returned by XmlTok. */ -#define XmlLiteralTok(enc, literalType, ptr, end, nextTokPtr) \ - (((enc)->literalScanners[literalType])(enc, ptr, end, nextTokPtr)) +#define XmlLiteralTok(enc, literalType, ptr, end, nextTokPtr) (((enc)->literalScanners[literalType])(enc, ptr, end, nextTokPtr)) -#define XmlAttributeValueTok(enc, ptr, end, nextTokPtr) \ - XmlLiteralTok(enc, XML_ATTRIBUTE_VALUE_LITERAL, ptr, end, nextTokPtr) +#define XmlAttributeValueTok(enc, ptr, end, nextTokPtr) XmlLiteralTok(enc, XML_ATTRIBUTE_VALUE_LITERAL, ptr, end, nextTokPtr) -#define XmlEntityValueTok(enc, ptr, end, nextTokPtr) \ - XmlLiteralTok(enc, XML_ENTITY_VALUE_LITERAL, ptr, end, nextTokPtr) +#define XmlEntityValueTok(enc, ptr, end, nextTokPtr) XmlLiteralTok(enc, XML_ENTITY_VALUE_LITERAL, ptr, end, nextTokPtr) -#define XmlNameMatchesAscii(enc, ptr1, end1, ptr2) \ - (((enc)->nameMatchesAscii)(enc, ptr1, end1, ptr2)) +#define XmlNameMatchesAscii(enc, ptr1, end1, ptr2) (((enc)->nameMatchesAscii)(enc, ptr1, end1, ptr2)) #define XmlNameLength(enc, ptr) (((enc)->nameLength)(enc, ptr)) #define XmlSkipS(enc, ptr) (((enc)->skipS)(enc, ptr)) -#define XmlGetAttributes(enc, ptr, attsMax, atts) \ - (((enc)->getAtts)(enc, ptr, attsMax, atts)) +#define XmlGetAttributes(enc, ptr, attsMax, atts) (((enc)->getAtts)(enc, ptr, attsMax, atts)) #define XmlCharRefNumber(enc, ptr) (((enc)->charRefNumber)(enc, ptr)) -#define XmlPredefinedEntityName(enc, ptr, end) \ - (((enc)->predefinedEntityName)(enc, ptr, end)) +#define XmlPredefinedEntityName(enc, ptr, end) (((enc)->predefinedEntityName)(enc, ptr, end)) -#define XmlUpdatePosition(enc, ptr, end, pos) \ - (((enc)->updatePosition)(enc, ptr, end, pos)) +#define XmlUpdatePosition(enc, ptr, end, pos) (((enc)->updatePosition)(enc, ptr, end, pos)) -#define XmlIsPublicId(enc, ptr, end, badPtr) \ - (((enc)->isPublicId)(enc, ptr, end, badPtr)) +#define XmlIsPublicId(enc, ptr, end, badPtr) (((enc)->isPublicId)(enc, ptr, end, badPtr)) -#define XmlUtf8Convert(enc, fromP, fromLim, toP, toLim) \ - (((enc)->utf8Convert)(enc, fromP, fromLim, toP, toLim)) +#define XmlUtf8Convert(enc, fromP, fromLim, toP, toLim) (((enc)->utf8Convert)(enc, fromP, fromLim, toP, toLim)) -#define XmlUtf16Convert(enc, fromP, fromLim, toP, toLim) \ - (((enc)->utf16Convert)(enc, fromP, fromLim, toP, toLim)) +#define XmlUtf16Convert(enc, fromP, fromLim, toP, toLim) (((enc)->utf16Convert)(enc, fromP, fromLim, toP, toLim)) -typedef struct { - ENCODING initEnc; - const ENCODING **encPtr; +typedef struct +{ + ENCODING initEnc; + const ENCODING ** encPtr; } INIT_ENCODING; -int XmlParseXmlDecl(int isGeneralTextEntity, const ENCODING *enc, - const char *ptr, const char *end, const char **badPtr, - const char **versionPtr, const char **versionEndPtr, - const char **encodingNamePtr, - const ENCODING **namedEncodingPtr, int *standalonePtr); +int XmlParseXmlDecl( + int isGeneralTextEntity, + const ENCODING * enc, + const char * ptr, + const char * end, + const char ** badPtr, + const char ** versionPtr, + const char ** versionEndPtr, + const char ** encodingNamePtr, + const ENCODING ** namedEncodingPtr, + int * standalonePtr); -int XmlInitEncoding(INIT_ENCODING *, const ENCODING **, const char *name); -const ENCODING *XmlGetUtf8InternalEncoding(void); -const ENCODING *XmlGetUtf16InternalEncoding(void); -int FASTCALL XmlUtf8Encode(int charNumber, char *buf); -int FASTCALL XmlUtf16Encode(int charNumber, unsigned short *buf); +int XmlInitEncoding(INIT_ENCODING *, const ENCODING **, const char * name); +const ENCODING * XmlGetUtf8InternalEncoding(void); +const ENCODING * XmlGetUtf16InternalEncoding(void); +int FASTCALL XmlUtf8Encode(int charNumber, char * buf); +int FASTCALL XmlUtf16Encode(int charNumber, unsigned short * buf); int XmlSizeOfUnknownEncoding(void); -typedef int(XMLCALL *CONVERTER)(void *userData, const char *p); +typedef int(XMLCALL * CONVERTER)(void * userData, const char * p); -ENCODING *XmlInitUnknownEncoding(void *mem, int *table, CONVERTER convert, - void *userData); +ENCODING * XmlInitUnknownEncoding(void * mem, int * table, CONVERTER convert, void * userData); -int XmlParseXmlDeclNS(int isGeneralTextEntity, const ENCODING *enc, - const char *ptr, const char *end, const char **badPtr, - const char **versionPtr, const char **versionEndPtr, - const char **encodingNamePtr, - const ENCODING **namedEncodingPtr, int *standalonePtr); +int XmlParseXmlDeclNS( + int isGeneralTextEntity, + const ENCODING * enc, + const char * ptr, + const char * end, + const char ** badPtr, + const char ** versionPtr, + const char ** versionEndPtr, + const char ** encodingNamePtr, + const ENCODING ** namedEncodingPtr, + int * standalonePtr); -int XmlInitEncodingNS(INIT_ENCODING *, const ENCODING **, const char *name); -const ENCODING *XmlGetUtf8InternalEncodingNS(void); -const ENCODING *XmlGetUtf16InternalEncodingNS(void); -ENCODING *XmlInitUnknownEncodingNS(void *mem, int *table, CONVERTER convert, - void *userData); +int XmlInitEncodingNS(INIT_ENCODING *, const ENCODING **, const char * name); +const ENCODING * XmlGetUtf8InternalEncodingNS(void); +const ENCODING * XmlGetUtf16InternalEncodingNS(void); +ENCODING * XmlInitUnknownEncodingNS(void * mem, int * table, CONVERTER convert, void * userData); #ifdef __cplusplus } #endif diff --git a/base/poco/XML/src/xmltok_impl.h b/base/poco/XML/src/xmltok_impl.h index 97e222b00c7..63d32e0e35f 100644 --- a/base/poco/XML/src/xmltok_impl.h +++ b/base/poco/XML/src/xmltok_impl.h @@ -31,44 +31,45 @@ USE OR OTHER DEALINGS IN THE SOFTWARE. */ -enum { - BT_NONXML, /* e.g. noncharacter-FFFF */ - BT_MALFORM, /* illegal, with regard to encoding */ - BT_LT, /* less than = "<" */ - BT_AMP, /* ampersand = "&" */ - BT_RSQB, /* right square bracket = "[" */ - BT_LEAD2, /* lead byte of a 2-byte UTF-8 character */ - BT_LEAD3, /* lead byte of a 3-byte UTF-8 character */ - BT_LEAD4, /* lead byte of a 4-byte UTF-8 character */ - BT_TRAIL, /* trailing unit, e.g. second 16-bit unit of a 4-byte char. */ - BT_CR, /* carriage return = "\r" */ - BT_LF, /* line feed = "\n" */ - BT_GT, /* greater than = ">" */ - BT_QUOT, /* quotation character = "\"" */ - BT_APOS, /* aposthrophe = "'" */ - BT_EQUALS, /* equal sign = "=" */ - BT_QUEST, /* question mark = "?" */ - BT_EXCL, /* exclamation mark = "!" */ - BT_SOL, /* solidus, slash = "/" */ - BT_SEMI, /* semicolon = ";" */ - BT_NUM, /* number sign = "#" */ - BT_LSQB, /* left square bracket = "[" */ - BT_S, /* white space, e.g. "\t", " "[, "\r"] */ - BT_NMSTRT, /* non-hex name start letter = "G".."Z" + "g".."z" + "_" */ - BT_COLON, /* colon = ":" */ - BT_HEX, /* hex letter = "A".."F" + "a".."f" */ - BT_DIGIT, /* digit = "0".."9" */ - BT_NAME, /* dot and middle dot = "." + chr(0xb7) */ - BT_MINUS, /* minus = "-" */ - BT_OTHER, /* known not to be a name or name start character */ - BT_NONASCII, /* might be a name or name start character */ - BT_PERCNT, /* percent sign = "%" */ - BT_LPAR, /* left parenthesis = "(" */ - BT_RPAR, /* right parenthesis = "(" */ - BT_AST, /* asterisk = "*" */ - BT_PLUS, /* plus sign = "+" */ - BT_COMMA, /* comma = "," */ - BT_VERBAR /* vertical bar = "|" */ +enum +{ + BT_NONXML, /* e.g. noncharacter-FFFF */ + BT_MALFORM, /* illegal, with regard to encoding */ + BT_LT, /* less than = "<" */ + BT_AMP, /* ampersand = "&" */ + BT_RSQB, /* right square bracket = "[" */ + BT_LEAD2, /* lead byte of a 2-byte UTF-8 character */ + BT_LEAD3, /* lead byte of a 3-byte UTF-8 character */ + BT_LEAD4, /* lead byte of a 4-byte UTF-8 character */ + BT_TRAIL, /* trailing unit, e.g. second 16-bit unit of a 4-byte char. */ + BT_CR, /* carriage return = "\r" */ + BT_LF, /* line feed = "\n" */ + BT_GT, /* greater than = ">" */ + BT_QUOT, /* quotation character = "\"" */ + BT_APOS, /* aposthrophe = "'" */ + BT_EQUALS, /* equal sign = "=" */ + BT_QUEST, /* question mark = "?" */ + BT_EXCL, /* exclamation mark = "!" */ + BT_SOL, /* solidus, slash = "/" */ + BT_SEMI, /* semicolon = ";" */ + BT_NUM, /* number sign = "#" */ + BT_LSQB, /* left square bracket = "[" */ + BT_S, /* white space, e.g. "\t", " "[, "\r"] */ + BT_NMSTRT, /* non-hex name start letter = "G".."Z" + "g".."z" + "_" */ + BT_COLON, /* colon = ":" */ + BT_HEX, /* hex letter = "A".."F" + "a".."f" */ + BT_DIGIT, /* digit = "0".."9" */ + BT_NAME, /* dot and middle dot = "." + chr(0xb7) */ + BT_MINUS, /* minus = "-" */ + BT_OTHER, /* known not to be a name or name start character */ + BT_NONASCII, /* might be a name or name start character */ + BT_PERCNT, /* percent sign = "%" */ + BT_LPAR, /* left parenthesis = "(" */ + BT_RPAR, /* right parenthesis = "(" */ + BT_AST, /* asterisk = "*" */ + BT_PLUS, /* plus sign = "+" */ + BT_COMMA, /* comma = "," */ + BT_VERBAR /* vertical bar = "|" */ }; #include From fff2c09b87ce319c3b9e62c22cdf19a444a4c2fe Mon Sep 17 00:00:00 2001 From: Salvatore Mesoraca Date: Fri, 10 Feb 2023 14:30:55 +0100 Subject: [PATCH 26/75] coordination: do not allow election_timeout_lower_bound_ms > election_timeout_upper_bound_ms --- docs/en/operations/clickhouse-keeper.md | 2 +- src/Coordination/KeeperServer.cpp | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/docs/en/operations/clickhouse-keeper.md b/docs/en/operations/clickhouse-keeper.md index 8f83b7d0bc9..10bad586a54 100644 --- a/docs/en/operations/clickhouse-keeper.md +++ b/docs/en/operations/clickhouse-keeper.md @@ -42,7 +42,7 @@ Internal coordination settings are located in the `.election_timeout_lower_bound_ms.totalMilliseconds(), "election_timeout_lower_bound_ms", log); params.election_timeout_upper_bound_ = getValueOrMaxInt32AndLogWarning( coordination_settings->election_timeout_upper_bound_ms.totalMilliseconds(), "election_timeout_upper_bound_ms", log); + + if (params.election_timeout_lower_bound_ >= params.election_timeout_upper_bound_) + { + LOG_FATAL( + log, + "election_timeout_lower_bound_ms is greater than election_timeout_upper_bound_ms, this would disable leader election " + "completely."); + std::terminate(); + } + params.reserved_log_items_ = getValueOrMaxInt32AndLogWarning(coordination_settings->reserved_log_items, "reserved_log_items", log); params.snapshot_distance_ = getValueOrMaxInt32AndLogWarning(coordination_settings->snapshot_distance, "snapshot_distance", log); From c73a8bded337a06670066f6c940dedb54d112ab8 Mon Sep 17 00:00:00 2001 From: Robert Schulze Date: Mon, 13 Feb 2023 09:20:48 +0000 Subject: [PATCH 27/75] Run clang-format over poco JSON Redis Crypto --- base/poco/Crypto/include/Poco/Crypto/Cipher.h | 217 ++-- .../include/Poco/Crypto/CipherFactory.h | 95 +- .../Crypto/include/Poco/Crypto/CipherImpl.h | 79 +- .../Crypto/include/Poco/Crypto/CipherKey.h | 346 ++--- .../include/Poco/Crypto/CipherKeyImpl.h | 266 ++-- base/poco/Crypto/include/Poco/Crypto/Crypto.h | 250 ++-- .../include/Poco/Crypto/CryptoException.h | 53 +- .../Crypto/include/Poco/Crypto/CryptoStream.h | 285 +++-- .../include/Poco/Crypto/CryptoTransform.h | 117 +- .../Crypto/include/Poco/Crypto/DigestEngine.h | 101 +- .../include/Poco/Crypto/ECDSADigestEngine.h | 142 ++- base/poco/Crypto/include/Poco/Crypto/ECKey.h | 213 ++-- .../Crypto/include/Poco/Crypto/ECKeyImpl.h | 279 ++-- .../poco/Crypto/include/Poco/Crypto/EVPPKey.h | 583 ++++----- .../poco/Crypto/include/Poco/Crypto/KeyPair.h | 207 +-- .../Crypto/include/Poco/Crypto/KeyPairImpl.h | 153 +-- .../include/Poco/Crypto/OpenSSLInitializer.h | 144 +-- .../include/Poco/Crypto/PKCS12Container.h | 205 +-- .../include/Poco/Crypto/RSACipherImpl.h | 99 +- .../include/Poco/Crypto/RSADigestEngine.h | 165 +-- base/poco/Crypto/include/Poco/Crypto/RSAKey.h | 187 ++- .../Crypto/include/Poco/Crypto/RSAKeyImpl.h | 205 +-- .../include/Poco/Crypto/X509Certificate.h | 429 +++---- base/poco/JSON/include/Poco/JSON/Array.h | 853 ++++++------- base/poco/JSON/include/Poco/JSON/Handler.h | 117 +- base/poco/JSON/include/Poco/JSON/JSON.h | 26 +- .../JSON/include/Poco/JSON/JSONException.h | 13 +- base/poco/JSON/include/Poco/JSON/Object.h | 1134 ++++++++--------- .../JSON/include/Poco/JSON/ParseHandler.h | 219 ++-- base/poco/JSON/include/Poco/JSON/Parser.h | 350 ++--- base/poco/JSON/include/Poco/JSON/ParserImpl.h | 329 ++--- .../JSON/include/Poco/JSON/PrintHandler.h | 173 +-- base/poco/JSON/include/Poco/JSON/Query.h | 193 +-- .../poco/JSON/include/Poco/JSON/Stringifier.h | 89 +- base/poco/JSON/include/Poco/JSON/Template.h | 245 ++-- .../JSON/include/Poco/JSON/TemplateCache.h | 149 +-- base/poco/JSON/src/pdjson.h | 119 +- base/poco/Redis/include/Poco/Redis/Array.h | 594 ++++----- .../Redis/include/Poco/Redis/AsyncReader.h | 141 +- base/poco/Redis/include/Poco/Redis/Client.h | 419 +++--- base/poco/Redis/include/Poco/Redis/Command.h | 363 +++--- base/poco/Redis/include/Poco/Redis/Error.h | 124 +- .../poco/Redis/include/Poco/Redis/Exception.h | 15 +- .../Poco/Redis/PoolableConnectionFactory.h | 109 +- base/poco/Redis/include/Poco/Redis/Redis.h | 26 +- .../Redis/include/Poco/Redis/RedisEventArgs.h | 143 ++- .../Redis/include/Poco/Redis/RedisStream.h | 155 +-- base/poco/Redis/include/Poco/Redis/Type.h | 510 ++++---- 48 files changed, 5649 insertions(+), 5779 deletions(-) diff --git a/base/poco/Crypto/include/Poco/Crypto/Cipher.h b/base/poco/Crypto/include/Poco/Crypto/Cipher.h index fbe0c30ae8c..ffd993280c1 100644 --- a/base/poco/Crypto/include/Poco/Crypto/Cipher.h +++ b/base/poco/Crypto/include/Poco/Crypto/Cipher.h @@ -18,121 +18,124 @@ #define Crypto_Cipher_INCLUDED -#include "Poco/Crypto/Crypto.h" -#include "Poco/RefCountedObject.h" -#include "Poco/AutoPtr.h" #include #include #include +#include "Poco/AutoPtr.h" +#include "Poco/Crypto/Crypto.h" +#include "Poco/RefCountedObject.h" -namespace Poco { -namespace Crypto { - - -class CryptoTransform; - - -class Crypto_API Cipher: public Poco::RefCountedObject - /// Represents the abstract base class from which all implementations of - /// symmetric/asymmetric encryption algorithms must inherit. Use the CipherFactory - /// class to obtain an instance of this class: - /// - /// CipherFactory& factory = CipherFactory::defaultFactory(); - /// // Creates a 256-bit AES cipher - /// Cipher* pCipher = factory.createCipher(CipherKey("aes-256")); - /// Cipher* pRSACipher = factory.createCipher(RSAKey(RSAKey::KL_1024, RSAKey::EXP_SMALL)); - /// - /// Check the different Key constructors on how to initialize/create - /// a key. The above example auto-generates random keys. - /// - /// Note that you won't be able to decrypt data encrypted with a random key - /// once the Cipher is destroyed unless you persist the generated key and IV. - /// An example usage for random keys is to encrypt data saved in a temporary - /// file. - /// - /// Once your key is set up, you can use the Cipher object to encrypt or - /// decrypt strings or, in conjunction with a CryptoInputStream or a - /// CryptoOutputStream, to encrypt streams of data. - /// - /// Since encrypted strings will contain arbitrary binary data that will cause - /// problems in applications that are not binary-safe (eg., when sending - /// encrypted data in e-mails), the encryptString() and decryptString() can - /// encode (or decode, respectively) encrypted data using a "transport encoding". - /// Supported encodings are Base64 and BinHex. - /// - /// The following example encrypts and decrypts a string utilizing Base64 - /// encoding: - /// - /// std::string plainText = "This is my secret information"; - /// std::string encrypted = pCipher->encryptString(plainText, Cipher::ENC_BASE64); - /// std::string decrypted = pCipher->decryptString(encrypted, Cipher::ENC_BASE64); - /// - /// In order to encrypt a stream of data (eg. to encrypt files), you can use - /// a CryptoStream: - /// - /// // Create an output stream that will encrypt all data going through it - /// // and write pass it to the underlying file stream. - /// Poco::FileOutputStream sink("encrypted.dat"); - /// CryptoOutputStream encryptor(sink, pCipher->createEncryptor()); - /// - /// Poco::FileInputStream source("source.txt"); - /// Poco::StreamCopier::copyStream(source, encryptor); - /// - /// // Always close output streams to flush all internal buffers - /// encryptor.close(); - /// sink.close(); +namespace Poco +{ +namespace Crypto { -public: - typedef Poco::AutoPtr Ptr; - typedef std::vector ByteVec; - - enum Encoding - /// Transport encoding to use for encryptString() and decryptString(). - { - ENC_NONE = 0x00, /// Plain binary output - ENC_BASE64 = 0x01, /// Base64-encoded output - ENC_BINHEX = 0x02, /// BinHex-encoded output - ENC_BASE64_NO_LF = 0x81, /// Base64-encoded output, no linefeeds - ENC_BINHEX_NO_LF = 0x82 /// BinHex-encoded output, no linefeeds - - }; - - virtual ~Cipher(); - /// Destroys the Cipher. - - virtual const std::string& name() const = 0; - /// Returns the name of the Cipher. - - virtual CryptoTransform* createEncryptor() = 0; - /// Creates an encryptor object to be used with a CryptoStream. - - virtual CryptoTransform* createDecryptor() = 0; - /// Creates a decryptor object to be used with a CryptoStream. - - virtual std::string encryptString(const std::string& str, Encoding encoding = ENC_NONE); - /// Directly encrypt a string and encode it using the given encoding. - - virtual std::string decryptString(const std::string& str, Encoding encoding = ENC_NONE); - /// Directly decrypt a string that is encoded with the given encoding. - - virtual void encrypt(std::istream& source, std::ostream& sink, Encoding encoding = ENC_NONE); - /// Directly encrypts an input stream and encodes it using the given encoding. - - virtual void decrypt(std::istream& source, std::ostream& sink, Encoding encoding = ENC_NONE); - /// Directly decrypt an input stream that is encoded with the given encoding. - -protected: - Cipher(); - /// Creates a new Cipher object. - -private: - Cipher(const Cipher&); - Cipher& operator = (const Cipher&); -}; -} } // namespace Poco::Crypto + class CryptoTransform; + + + class Crypto_API Cipher : public Poco::RefCountedObject + /// Represents the abstract base class from which all implementations of + /// symmetric/asymmetric encryption algorithms must inherit. Use the CipherFactory + /// class to obtain an instance of this class: + /// + /// CipherFactory& factory = CipherFactory::defaultFactory(); + /// // Creates a 256-bit AES cipher + /// Cipher* pCipher = factory.createCipher(CipherKey("aes-256")); + /// Cipher* pRSACipher = factory.createCipher(RSAKey(RSAKey::KL_1024, RSAKey::EXP_SMALL)); + /// + /// Check the different Key constructors on how to initialize/create + /// a key. The above example auto-generates random keys. + /// + /// Note that you won't be able to decrypt data encrypted with a random key + /// once the Cipher is destroyed unless you persist the generated key and IV. + /// An example usage for random keys is to encrypt data saved in a temporary + /// file. + /// + /// Once your key is set up, you can use the Cipher object to encrypt or + /// decrypt strings or, in conjunction with a CryptoInputStream or a + /// CryptoOutputStream, to encrypt streams of data. + /// + /// Since encrypted strings will contain arbitrary binary data that will cause + /// problems in applications that are not binary-safe (eg., when sending + /// encrypted data in e-mails), the encryptString() and decryptString() can + /// encode (or decode, respectively) encrypted data using a "transport encoding". + /// Supported encodings are Base64 and BinHex. + /// + /// The following example encrypts and decrypts a string utilizing Base64 + /// encoding: + /// + /// std::string plainText = "This is my secret information"; + /// std::string encrypted = pCipher->encryptString(plainText, Cipher::ENC_BASE64); + /// std::string decrypted = pCipher->decryptString(encrypted, Cipher::ENC_BASE64); + /// + /// In order to encrypt a stream of data (eg. to encrypt files), you can use + /// a CryptoStream: + /// + /// // Create an output stream that will encrypt all data going through it + /// // and write pass it to the underlying file stream. + /// Poco::FileOutputStream sink("encrypted.dat"); + /// CryptoOutputStream encryptor(sink, pCipher->createEncryptor()); + /// + /// Poco::FileInputStream source("source.txt"); + /// Poco::StreamCopier::copyStream(source, encryptor); + /// + /// // Always close output streams to flush all internal buffers + /// encryptor.close(); + /// sink.close(); + { + public: + typedef Poco::AutoPtr Ptr; + typedef std::vector ByteVec; + + enum Encoding + /// Transport encoding to use for encryptString() and decryptString(). + { + ENC_NONE = 0x00, /// Plain binary output + ENC_BASE64 = 0x01, /// Base64-encoded output + ENC_BINHEX = 0x02, /// BinHex-encoded output + ENC_BASE64_NO_LF = 0x81, /// Base64-encoded output, no linefeeds + ENC_BINHEX_NO_LF = 0x82 /// BinHex-encoded output, no linefeeds + + }; + + virtual ~Cipher(); + /// Destroys the Cipher. + + virtual const std::string & name() const = 0; + /// Returns the name of the Cipher. + + virtual CryptoTransform * createEncryptor() = 0; + /// Creates an encryptor object to be used with a CryptoStream. + + virtual CryptoTransform * createDecryptor() = 0; + /// Creates a decryptor object to be used with a CryptoStream. + + virtual std::string encryptString(const std::string & str, Encoding encoding = ENC_NONE); + /// Directly encrypt a string and encode it using the given encoding. + + virtual std::string decryptString(const std::string & str, Encoding encoding = ENC_NONE); + /// Directly decrypt a string that is encoded with the given encoding. + + virtual void encrypt(std::istream & source, std::ostream & sink, Encoding encoding = ENC_NONE); + /// Directly encrypts an input stream and encodes it using the given encoding. + + virtual void decrypt(std::istream & source, std::ostream & sink, Encoding encoding = ENC_NONE); + /// Directly decrypt an input stream that is encoded with the given encoding. + + protected: + Cipher(); + /// Creates a new Cipher object. + + private: + Cipher(const Cipher &); + Cipher & operator=(const Cipher &); + }; + + +} +} // namespace Poco::Crypto #endif // Crypto_Cipher_INCLUDED diff --git a/base/poco/Crypto/include/Poco/Crypto/CipherFactory.h b/base/poco/Crypto/include/Poco/Crypto/CipherFactory.h index 36aa964a1e6..f32865e3461 100644 --- a/base/poco/Crypto/include/Poco/Crypto/CipherFactory.h +++ b/base/poco/Crypto/include/Poco/Crypto/CipherFactory.h @@ -21,55 +21,58 @@ #include "Poco/Crypto/Crypto.h" -namespace Poco { -namespace Crypto { - - -class Cipher; -class CipherKey; -class RSAKey; - - -class Crypto_API CipherFactory - /// A factory for Cipher objects. See the Cipher class for examples on how to - /// use the CipherFactory. +namespace Poco +{ +namespace Crypto { -public: - CipherFactory(); - /// Creates a new CipherFactory object. - - virtual ~CipherFactory(); - /// Destroys the CipherFactory. - - Cipher* createCipher(const CipherKey& key); - /// Creates a Cipher object for the given Cipher name. Valid cipher - /// names depend on the OpenSSL version the library is linked with; - /// see the output of - /// - /// openssl enc --help - /// - /// for a list of supported block and stream ciphers. - /// - /// Common examples are: - /// - /// * AES: "aes-128", "aes-256" - /// * DES: "des", "des3" - /// * Blowfish: "bf" - - Cipher* createCipher(const RSAKey& key, RSAPaddingMode paddingMode = RSA_PADDING_PKCS1); - /// Creates a RSACipher using the given RSA key and padding mode - /// for public key encryption/private key decryption. - - static CipherFactory& defaultFactory(); - /// Returns the default CipherFactory. - -private: - CipherFactory(const CipherFactory&); - CipherFactory& operator = (const CipherFactory&); -}; -} } // namespace Poco::Crypto + class Cipher; + class CipherKey; + class RSAKey; + + + class Crypto_API CipherFactory + /// A factory for Cipher objects. See the Cipher class for examples on how to + /// use the CipherFactory. + { + public: + CipherFactory(); + /// Creates a new CipherFactory object. + + virtual ~CipherFactory(); + /// Destroys the CipherFactory. + + Cipher * createCipher(const CipherKey & key); + /// Creates a Cipher object for the given Cipher name. Valid cipher + /// names depend on the OpenSSL version the library is linked with; + /// see the output of + /// + /// openssl enc --help + /// + /// for a list of supported block and stream ciphers. + /// + /// Common examples are: + /// + /// * AES: "aes-128", "aes-256" + /// * DES: "des", "des3" + /// * Blowfish: "bf" + + Cipher * createCipher(const RSAKey & key, RSAPaddingMode paddingMode = RSA_PADDING_PKCS1); + /// Creates a RSACipher using the given RSA key and padding mode + /// for public key encryption/private key decryption. + + static CipherFactory & defaultFactory(); + /// Returns the default CipherFactory. + + private: + CipherFactory(const CipherFactory &); + CipherFactory & operator=(const CipherFactory &); + }; + + +} +} // namespace Poco::Crypto #endif // Crypto_CipherFactory_INCLUDED diff --git a/base/poco/Crypto/include/Poco/Crypto/CipherImpl.h b/base/poco/Crypto/include/Poco/Crypto/CipherImpl.h index d6e8e0e79b2..057e77a4cd9 100644 --- a/base/poco/Crypto/include/Poco/Crypto/CipherImpl.h +++ b/base/poco/Crypto/include/Poco/Crypto/CipherImpl.h @@ -18,52 +18,55 @@ #define Crypto_CipherImpl_INCLUDED -#include "Poco/Crypto/Crypto.h" +#include #include "Poco/Crypto/Cipher.h" #include "Poco/Crypto/CipherKey.h" +#include "Poco/Crypto/Crypto.h" #include "Poco/Crypto/OpenSSLInitializer.h" -#include -namespace Poco { -namespace Crypto { - - -class CipherImpl: public Cipher - /// An implementation of the Cipher class for OpenSSL's crypto library. +namespace Poco { -public: - CipherImpl(const CipherKey& key); - /// Creates a new CipherImpl object for the given CipherKey. - - virtual ~CipherImpl(); - /// Destroys the CipherImpl. - - const std::string& name() const; - /// Returns the name of the cipher. - - CryptoTransform* createEncryptor(); - /// Creates an encryptor object. - - CryptoTransform* createDecryptor(); - /// Creates a decryptor object. - -private: - CipherKey _key; - OpenSSLInitializer _openSSLInitializer; -}; - - -// -// Inlines -// -inline const std::string& CipherImpl::name() const +namespace Crypto { - return _key.name(); + + + class CipherImpl : public Cipher + /// An implementation of the Cipher class for OpenSSL's crypto library. + { + public: + CipherImpl(const CipherKey & key); + /// Creates a new CipherImpl object for the given CipherKey. + + virtual ~CipherImpl(); + /// Destroys the CipherImpl. + + const std::string & name() const; + /// Returns the name of the cipher. + + CryptoTransform * createEncryptor(); + /// Creates an encryptor object. + + CryptoTransform * createDecryptor(); + /// Creates a decryptor object. + + private: + CipherKey _key; + OpenSSLInitializer _openSSLInitializer; + }; + + + // + // Inlines + // + inline const std::string & CipherImpl::name() const + { + return _key.name(); + } + + } - - -} } // namespace Poco::Crypto +} // namespace Poco::Crypto #endif // Crypto_CipherImpl_INCLUDED diff --git a/base/poco/Crypto/include/Poco/Crypto/CipherKey.h b/base/poco/Crypto/include/Poco/Crypto/CipherKey.h index b102cc2310b..b39cb1a9294 100644 --- a/base/poco/Crypto/include/Poco/Crypto/CipherKey.h +++ b/base/poco/Crypto/include/Poco/Crypto/CipherKey.h @@ -18,184 +18,186 @@ #define Crypto_CipherKey_INCLUDED -#include "Poco/Crypto/Crypto.h" #include "Poco/Crypto/CipherKeyImpl.h" +#include "Poco/Crypto/Crypto.h" -namespace Poco { -namespace Crypto { - - -class Crypto_API CipherKey - /// CipherKey stores the key information for decryption/encryption of data. - /// To create a random key, using the following code: - /// - /// CipherKey key("aes-256"); - /// - /// Note that you won't be able to decrypt data encrypted with a random key - /// once the Cipher is destroyed unless you persist the generated key and IV. - /// An example usage for random keys is to encrypt data saved in a temporary - /// file. - /// - /// To create a key using a human-readable password - /// string, use the following code. We create a AES Cipher and - /// use a salt value to make the key more robust: - /// - /// std::string password = "secret"; - /// std::string salt("asdff8723lasdf(**923412"); - /// CipherKey key("aes-256", password, salt); - /// - /// You may also control the digest and the number of iterations used to generate the key - /// by specifying the specific values. Here we create a key with the same data as before, - /// except that we use 100 iterations instead of DEFAULT_ITERATION_COUNT, and sha1 instead of - /// the default md5: - /// - /// std::string password = "secret"; - /// std::string salt("asdff8723lasdf(**923412"); - /// std::string digest ("sha1"); - /// CipherKey key("aes-256", password, salt, 100, digest); - /// +namespace Poco { -public: - typedef CipherKeyImpl::Mode Mode; - typedef CipherKeyImpl::ByteVec ByteVec; - - enum - { - DEFAULT_ITERATION_COUNT = 2000 - /// Default iteration count to use with - /// generateKey(). RSA security recommends - /// an iteration count of at least 1000. - }; - - CipherKey(const std::string& name, - const std::string& passphrase, - const std::string& salt = "", - int iterationCount = DEFAULT_ITERATION_COUNT, - const std::string& digest = "md5"); - /// Creates a new CipherKeyImpl object using the given - /// cipher name, passphrase, salt value, iteration count and digest. - - CipherKey(const std::string& name, - const ByteVec& key, - const ByteVec& iv); - /// Creates a new CipherKeyImpl object using the given cipher - /// name, key and initialization vector (IV). - /// - /// The size of the IV must match the cipher's expected - /// IV size (see ivSize()), except for GCM mode, which allows - /// a custom IV size. - - CipherKey(const std::string& name); - /// Creates a new CipherKeyImpl object. Autoinitializes key and - /// initialization vector. - - ~CipherKey(); - /// Destroys the CipherKeyImpl. - - const std::string& name() const; - /// Returns the name of the Cipher. - - int keySize() const; - /// Returns the key size of the Cipher. - - int blockSize() const; - /// Returns the block size of the Cipher. - - int ivSize() const; - /// Returns the IV size of the Cipher. - - Mode mode() const; - /// Returns the Cipher's mode of operation. - - const ByteVec& getKey() const; - /// Returns the key for the Cipher. - - void setKey(const ByteVec& key); - /// Sets the key for the Cipher. - - const ByteVec& getIV() const; - /// Returns the initialization vector (IV) for the Cipher. - - void setIV(const ByteVec& iv); - /// Sets the initialization vector (IV) for the Cipher. - /// - /// The size of the vector must match the cipher's expected - /// IV size (see ivSize()), except for GCM mode, which allows - /// a custom IV size. - - CipherKeyImpl::Ptr impl(); - /// Returns the impl object - -private: - CipherKeyImpl::Ptr _pImpl; -}; - - -// -// inlines -// -inline const std::string& CipherKey::name() const +namespace Crypto { - return _pImpl->name(); + + + class Crypto_API CipherKey + /// CipherKey stores the key information for decryption/encryption of data. + /// To create a random key, using the following code: + /// + /// CipherKey key("aes-256"); + /// + /// Note that you won't be able to decrypt data encrypted with a random key + /// once the Cipher is destroyed unless you persist the generated key and IV. + /// An example usage for random keys is to encrypt data saved in a temporary + /// file. + /// + /// To create a key using a human-readable password + /// string, use the following code. We create a AES Cipher and + /// use a salt value to make the key more robust: + /// + /// std::string password = "secret"; + /// std::string salt("asdff8723lasdf(**923412"); + /// CipherKey key("aes-256", password, salt); + /// + /// You may also control the digest and the number of iterations used to generate the key + /// by specifying the specific values. Here we create a key with the same data as before, + /// except that we use 100 iterations instead of DEFAULT_ITERATION_COUNT, and sha1 instead of + /// the default md5: + /// + /// std::string password = "secret"; + /// std::string salt("asdff8723lasdf(**923412"); + /// std::string digest ("sha1"); + /// CipherKey key("aes-256", password, salt, 100, digest); + /// + { + public: + typedef CipherKeyImpl::Mode Mode; + typedef CipherKeyImpl::ByteVec ByteVec; + + enum + { + DEFAULT_ITERATION_COUNT = 2000 + /// Default iteration count to use with + /// generateKey(). RSA security recommends + /// an iteration count of at least 1000. + }; + + CipherKey( + const std::string & name, + const std::string & passphrase, + const std::string & salt = "", + int iterationCount = DEFAULT_ITERATION_COUNT, + const std::string & digest = "md5"); + /// Creates a new CipherKeyImpl object using the given + /// cipher name, passphrase, salt value, iteration count and digest. + + CipherKey(const std::string & name, const ByteVec & key, const ByteVec & iv); + /// Creates a new CipherKeyImpl object using the given cipher + /// name, key and initialization vector (IV). + /// + /// The size of the IV must match the cipher's expected + /// IV size (see ivSize()), except for GCM mode, which allows + /// a custom IV size. + + CipherKey(const std::string & name); + /// Creates a new CipherKeyImpl object. Autoinitializes key and + /// initialization vector. + + ~CipherKey(); + /// Destroys the CipherKeyImpl. + + const std::string & name() const; + /// Returns the name of the Cipher. + + int keySize() const; + /// Returns the key size of the Cipher. + + int blockSize() const; + /// Returns the block size of the Cipher. + + int ivSize() const; + /// Returns the IV size of the Cipher. + + Mode mode() const; + /// Returns the Cipher's mode of operation. + + const ByteVec & getKey() const; + /// Returns the key for the Cipher. + + void setKey(const ByteVec & key); + /// Sets the key for the Cipher. + + const ByteVec & getIV() const; + /// Returns the initialization vector (IV) for the Cipher. + + void setIV(const ByteVec & iv); + /// Sets the initialization vector (IV) for the Cipher. + /// + /// The size of the vector must match the cipher's expected + /// IV size (see ivSize()), except for GCM mode, which allows + /// a custom IV size. + + CipherKeyImpl::Ptr impl(); + /// Returns the impl object + + private: + CipherKeyImpl::Ptr _pImpl; + }; + + + // + // inlines + // + inline const std::string & CipherKey::name() const + { + return _pImpl->name(); + } + + + inline int CipherKey::keySize() const + { + return _pImpl->keySize(); + } + + + inline int CipherKey::blockSize() const + { + return _pImpl->blockSize(); + } + + + inline int CipherKey::ivSize() const + { + return _pImpl->ivSize(); + } + + + inline CipherKey::Mode CipherKey::mode() const + { + return _pImpl->mode(); + } + + + inline const CipherKey::ByteVec & CipherKey::getKey() const + { + return _pImpl->getKey(); + } + + + inline void CipherKey::setKey(const CipherKey::ByteVec & key) + { + _pImpl->setKey(key); + } + + + inline const CipherKey::ByteVec & CipherKey::getIV() const + { + return _pImpl->getIV(); + } + + + inline void CipherKey::setIV(const CipherKey::ByteVec & iv) + { + _pImpl->setIV(iv); + } + + + inline CipherKeyImpl::Ptr CipherKey::impl() + { + return _pImpl; + } + + } - - -inline int CipherKey::keySize() const -{ - return _pImpl->keySize(); -} - - -inline int CipherKey::blockSize() const -{ - return _pImpl->blockSize(); -} - - -inline int CipherKey::ivSize() const -{ - return _pImpl->ivSize(); -} - - -inline CipherKey::Mode CipherKey::mode() const -{ - return _pImpl->mode(); -} - - -inline const CipherKey::ByteVec& CipherKey::getKey() const -{ - return _pImpl->getKey(); -} - - -inline void CipherKey::setKey(const CipherKey::ByteVec& key) -{ - _pImpl->setKey(key); -} - - -inline const CipherKey::ByteVec& CipherKey::getIV() const -{ - return _pImpl->getIV(); -} - - -inline void CipherKey::setIV(const CipherKey::ByteVec& iv) -{ - _pImpl->setIV(iv); -} - - -inline CipherKeyImpl::Ptr CipherKey::impl() -{ - return _pImpl; -} - - -} } // namespace Poco::Crypto +} // namespace Poco::Crypto #endif // Crypto_CipherKey_INCLUDED diff --git a/base/poco/Crypto/include/Poco/Crypto/CipherKeyImpl.h b/base/poco/Crypto/include/Poco/Crypto/CipherKeyImpl.h index f7807aad9f8..700ae95c892 100644 --- a/base/poco/Crypto/include/Poco/Crypto/CipherKeyImpl.h +++ b/base/poco/Crypto/include/Poco/Crypto/CipherKeyImpl.h @@ -18,151 +18,151 @@ #define Crypto_CipherKeyImpl_INCLUDED +#include +#include "Poco/AutoPtr.h" #include "Poco/Crypto/Crypto.h" #include "Poco/Crypto/OpenSSLInitializer.h" #include "Poco/RefCountedObject.h" -#include "Poco/AutoPtr.h" -#include struct evp_cipher_st; typedef struct evp_cipher_st EVP_CIPHER; -namespace Poco { -namespace Crypto { - - -class CipherKeyImpl: public RefCountedObject - /// An implementation of the CipherKey class for OpenSSL's crypto library. +namespace Poco { -public: - typedef std::vector ByteVec; - typedef Poco::AutoPtr Ptr; - - enum Mode - /// Cipher mode of operation. This mode determines how multiple blocks - /// are connected; this is essential to improve security. - { - MODE_STREAM_CIPHER, /// Stream cipher - MODE_ECB, /// Electronic codebook (plain concatenation) - MODE_CBC, /// Cipher block chaining (default) - MODE_CFB, /// Cipher feedback - MODE_OFB, /// Output feedback - MODE_CTR, /// Counter mode - MODE_GCM, /// Galois/Counter mode - MODE_CCM /// Counter with CBC-MAC - }; - - CipherKeyImpl(const std::string& name, - const std::string& passphrase, - const std::string& salt, - int iterationCount, - const std::string& digest); - /// Creates a new CipherKeyImpl object, using - /// the given cipher name, passphrase, salt value - /// and iteration count. - - CipherKeyImpl(const std::string& name, - const ByteVec& key, - const ByteVec& iv); - /// Creates a new CipherKeyImpl object, using the - /// given cipher name, key and initialization vector. - - CipherKeyImpl(const std::string& name); - /// Creates a new CipherKeyImpl object. Autoinitializes key - /// and initialization vector. - - virtual ~CipherKeyImpl(); - /// Destroys the CipherKeyImpl. - - const std::string& name() const; - /// Returns the name of the Cipher. - - int keySize() const; - /// Returns the key size of the Cipher. - - int blockSize() const; - /// Returns the block size of the Cipher. - - int ivSize() const; - /// Returns the IV size of the Cipher. - - Mode mode() const; - /// Returns the Cipher's mode of operation. - - const ByteVec& getKey() const; - /// Returns the key for the Cipher. - - void setKey(const ByteVec& key); - /// Sets the key for the Cipher. - - const ByteVec& getIV() const; - /// Returns the initialization vector (IV) for the Cipher. - - void setIV(const ByteVec& iv); - /// Sets the initialization vector (IV) for the Cipher. - - const EVP_CIPHER* cipher(); - /// Returns the cipher object - -private: - void generateKey(const std::string& passphrase, - const std::string& salt, - int iterationCount); - /// Generates key and IV from a password and optional salt string. - - void generateKey(); - /// Generates key and IV from random data. - - void getRandomBytes(ByteVec& vec, std::size_t count); - /// Stores random bytes in vec. - -private: - const EVP_CIPHER* _pCipher; - const EVP_MD* _pDigest; - std::string _name; - ByteVec _key; - ByteVec _iv; - OpenSSLInitializer _openSSLInitializer; -}; - - -// -// Inlines -// -inline const std::string& CipherKeyImpl::name() const +namespace Crypto { - return _name; + + + class CipherKeyImpl : public RefCountedObject + /// An implementation of the CipherKey class for OpenSSL's crypto library. + { + public: + typedef std::vector ByteVec; + typedef Poco::AutoPtr Ptr; + + enum Mode + /// Cipher mode of operation. This mode determines how multiple blocks + /// are connected; this is essential to improve security. + { + MODE_STREAM_CIPHER, /// Stream cipher + MODE_ECB, /// Electronic codebook (plain concatenation) + MODE_CBC, /// Cipher block chaining (default) + MODE_CFB, /// Cipher feedback + MODE_OFB, /// Output feedback + MODE_CTR, /// Counter mode + MODE_GCM, /// Galois/Counter mode + MODE_CCM /// Counter with CBC-MAC + }; + + CipherKeyImpl( + const std::string & name, + const std::string & passphrase, + const std::string & salt, + int iterationCount, + const std::string & digest); + /// Creates a new CipherKeyImpl object, using + /// the given cipher name, passphrase, salt value + /// and iteration count. + + CipherKeyImpl(const std::string & name, const ByteVec & key, const ByteVec & iv); + /// Creates a new CipherKeyImpl object, using the + /// given cipher name, key and initialization vector. + + CipherKeyImpl(const std::string & name); + /// Creates a new CipherKeyImpl object. Autoinitializes key + /// and initialization vector. + + virtual ~CipherKeyImpl(); + /// Destroys the CipherKeyImpl. + + const std::string & name() const; + /// Returns the name of the Cipher. + + int keySize() const; + /// Returns the key size of the Cipher. + + int blockSize() const; + /// Returns the block size of the Cipher. + + int ivSize() const; + /// Returns the IV size of the Cipher. + + Mode mode() const; + /// Returns the Cipher's mode of operation. + + const ByteVec & getKey() const; + /// Returns the key for the Cipher. + + void setKey(const ByteVec & key); + /// Sets the key for the Cipher. + + const ByteVec & getIV() const; + /// Returns the initialization vector (IV) for the Cipher. + + void setIV(const ByteVec & iv); + /// Sets the initialization vector (IV) for the Cipher. + + const EVP_CIPHER * cipher(); + /// Returns the cipher object + + private: + void generateKey(const std::string & passphrase, const std::string & salt, int iterationCount); + /// Generates key and IV from a password and optional salt string. + + void generateKey(); + /// Generates key and IV from random data. + + void getRandomBytes(ByteVec & vec, std::size_t count); + /// Stores random bytes in vec. + + private: + const EVP_CIPHER * _pCipher; + const EVP_MD * _pDigest; + std::string _name; + ByteVec _key; + ByteVec _iv; + OpenSSLInitializer _openSSLInitializer; + }; + + + // + // Inlines + // + inline const std::string & CipherKeyImpl::name() const + { + return _name; + } + + + inline const CipherKeyImpl::ByteVec & CipherKeyImpl::getKey() const + { + return _key; + } + + + inline void CipherKeyImpl::setKey(const ByteVec & key) + { + poco_assert(key.size() == static_cast(keySize())); + _key = key; + } + + + inline const CipherKeyImpl::ByteVec & CipherKeyImpl::getIV() const + { + return _iv; + } + + + inline const EVP_CIPHER * CipherKeyImpl::cipher() + { + return _pCipher; + } + + } - - -inline const CipherKeyImpl::ByteVec& CipherKeyImpl::getKey() const -{ - return _key; -} - - -inline void CipherKeyImpl::setKey(const ByteVec& key) -{ - poco_assert(key.size() == static_cast(keySize())); - _key = key; -} - - -inline const CipherKeyImpl::ByteVec& CipherKeyImpl::getIV() const -{ - return _iv; -} - - -inline const EVP_CIPHER* CipherKeyImpl::cipher() -{ - return _pCipher; -} - - -} } // namespace Poco::Crypto +} // namespace Poco::Crypto #endif // Crypto_CipherKeyImpl_INCLUDED diff --git a/base/poco/Crypto/include/Poco/Crypto/Crypto.h b/base/poco/Crypto/include/Poco/Crypto/Crypto.h index d6b3ede65cb..a6b8a5cf22f 100644 --- a/base/poco/Crypto/include/Poco/Crypto/Crypto.h +++ b/base/poco/Crypto/include/Poco/Crypto/Crypto.h @@ -24,39 +24,37 @@ #define POCO_EXTERNAL_OPENSSL_SLPRO 2 -#include "Poco/Foundation.h" #include +#include "Poco/Foundation.h" #ifndef OPENSSL_VERSION_PREREQ - #if defined(OPENSSL_VERSION_MAJOR) && defined(OPENSSL_VERSION_MINOR) - #define OPENSSL_VERSION_PREREQ(maj, min) \ - ((OPENSSL_VERSION_MAJOR << 16) + OPENSSL_VERSION_MINOR >= ((maj) << 16) + (min)) - #else - #define OPENSSL_VERSION_PREREQ(maj, min) \ - (OPENSSL_VERSION_NUMBER >= (((maj) << 28) | ((min) << 20))) - #endif +# if defined(OPENSSL_VERSION_MAJOR) && defined(OPENSSL_VERSION_MINOR) +# define OPENSSL_VERSION_PREREQ(maj, min) ((OPENSSL_VERSION_MAJOR << 16) + OPENSSL_VERSION_MINOR >= ((maj) << 16) + (min)) +# else +# define OPENSSL_VERSION_PREREQ(maj, min) (OPENSSL_VERSION_NUMBER >= (((maj) << 28) | ((min) << 20))) +# endif #endif enum RSAPaddingMode - /// The padding mode used for RSA public key encryption. +/// The padding mode used for RSA public key encryption. { - RSA_PADDING_PKCS1, - /// PKCS #1 v1.5 padding. This currently is the most widely used mode. - - RSA_PADDING_PKCS1_OAEP, - /// EME-OAEP as defined in PKCS #1 v2.0 with SHA-1, MGF1 and an empty - /// encoding parameter. This mode is recommended for all new applications. - - RSA_PADDING_SSLV23, - /// PKCS #1 v1.5 padding with an SSL-specific modification that denotes - /// that the server is SSL3 capable. - - RSA_PADDING_NONE - /// Raw RSA encryption. This mode should only be used to implement cryptographically - /// sound padding modes in the application code. Encrypting user data directly with RSA - /// is insecure. + RSA_PADDING_PKCS1, + /// PKCS #1 v1.5 padding. This currently is the most widely used mode. + + RSA_PADDING_PKCS1_OAEP, + /// EME-OAEP as defined in PKCS #1 v2.0 with SHA-1, MGF1 and an empty + /// encoding parameter. This mode is recommended for all new applications. + + RSA_PADDING_SSLV23, + /// PKCS #1 v1.5 padding with an SSL-specific modification that denotes + /// that the server is SSL3 capable. + + RSA_PADDING_NONE + /// Raw RSA encryption. This mode should only be used to implement cryptographically + /// sound padding modes in the application code. Encrypting user data directly with RSA + /// is insecure. }; @@ -69,22 +67,22 @@ enum RSAPaddingMode // defined with this macro as being exported. // #if defined(_WIN32) - #if defined(POCO_DLL) - #if defined(Crypto_EXPORTS) - #define Crypto_API __declspec(dllexport) - #else - #define Crypto_API __declspec(dllimport) - #endif - #endif +# if defined(POCO_DLL) +# if defined(Crypto_EXPORTS) +# define Crypto_API __declspec(dllexport) +# else +# define Crypto_API __declspec(dllimport) +# endif +# endif #endif #if !defined(Crypto_API) - #if !defined(POCO_NO_GCC_API_ATTRIBUTE) && defined (__GNUC__) && (__GNUC__ >= 4) - #define Crypto_API __attribute__ ((visibility ("default"))) - #else - #define Crypto_API - #endif +# if !defined(POCO_NO_GCC_API_ATTRIBUTE) && defined(__GNUC__) && (__GNUC__ >= 4) +# define Crypto_API __attribute__((visibility("default"))) +# else +# define Crypto_API +# endif #endif @@ -92,104 +90,106 @@ enum RSAPaddingMode // Automatically link Crypto and OpenSSL libraries. // #if defined(_MSC_VER) - #if !defined(POCO_NO_AUTOMATIC_LIBS) - #if defined(POCO_INTERNAL_OPENSSL_MSVC_VER) - #if defined(POCO_EXTERNAL_OPENSSL) - #pragma message("External OpenSSL defined but internal headers used - possible mismatch!") - #endif // POCO_EXTERNAL_OPENSSL - #if !defined(_DEBUG) - #define POCO_DEBUG_SUFFIX "" - #if !defined (_DLL) - #define POCO_STATIC_SUFFIX "mt" - #else // _DLL - #define POCO_STATIC_SUFFIX "" - #endif - #else // _DEBUG - #define POCO_DEBUG_SUFFIX "d" - #if !defined (_DLL) - #define POCO_STATIC_SUFFIX "mt" - #else // _DLL - #define POCO_STATIC_SUFFIX "" - #endif - #endif - #pragma comment(lib, "libcrypto" POCO_STATIC_SUFFIX POCO_DEBUG_SUFFIX ".lib") - #pragma comment(lib, "libssl" POCO_STATIC_SUFFIX POCO_DEBUG_SUFFIX ".lib") - #if !defined(_WIN64) && !defined (_DLL) && \ - (POCO_INTERNAL_OPENSSL_MSVC_VER == 120) && \ - (POCO_MSVC_VERSION < POCO_INTERNAL_OPENSSL_MSVC_VER) - #pragma comment(lib, "libPreVS2013CRT" POCO_STATIC_SUFFIX POCO_DEBUG_SUFFIX ".lib") - #endif - #if !defined (_DLL) && (POCO_MSVS_VERSION >= 2015) - #pragma comment(lib, "legacy_stdio_definitions.lib") - #pragma comment(lib, "legacy_stdio_wide_specifiers.lib") - #endif - #elif defined(POCO_EXTERNAL_OPENSSL) - #if POCO_EXTERNAL_OPENSSL == POCO_EXTERNAL_OPENSSL_SLPRO - #if defined(POCO_DLL) - #if OPENSSL_VERSION_PREREQ(1,1) - #pragma comment(lib, "libcrypto.lib") - #pragma comment(lib, "libssl.lib") - #else - #pragma comment(lib, "libeay32.lib") - #pragma comment(lib, "ssleay32.lib") - #endif - #else - #if OPENSSL_VERSION_PREREQ(1,1) - #if defined(_WIN64) - #pragma comment(lib, "libcrypto64" POCO_LIB_SUFFIX) - #pragma comment(lib, "libssl64" POCO_LIB_SUFFIX) - #else - #pragma comment(lib, "libcrypto32" POCO_LIB_SUFFIX) - #pragma comment(lib, "libssl32" POCO_LIB_SUFFIX) - #endif - #else - #pragma comment(lib, "libeay32" POCO_LIB_SUFFIX) - #pragma comment(lib, "ssleay32" POCO_LIB_SUFFIX) - #endif - #endif - #elif POCO_EXTERNAL_OPENSSL == POCO_EXTERNAL_OPENSSL_DEFAULT - #if OPENSSL_VERSION_PREREQ(1,1) - #pragma comment(lib, "libcrypto.lib") - #pragma comment(lib, "libssl.lib") - #else - #pragma comment(lib, "libeay32.lib") - #pragma comment(lib, "ssleay32.lib") - #endif - #endif - #endif // POCO_INTERNAL_OPENSSL_MSVC_VER - #if !defined(Crypto_EXPORTS) - #pragma comment(lib, "PocoCrypto" POCO_LIB_SUFFIX) - #endif - #endif // POCO_NO_AUTOMATIC_LIBS +# if !defined(POCO_NO_AUTOMATIC_LIBS) +# if defined(POCO_INTERNAL_OPENSSL_MSVC_VER) +# if defined(POCO_EXTERNAL_OPENSSL) +# pragma message("External OpenSSL defined but internal headers used - possible mismatch!") +# endif // POCO_EXTERNAL_OPENSSL +# if !defined(_DEBUG) +# define POCO_DEBUG_SUFFIX "" +# if !defined(_DLL) +# define POCO_STATIC_SUFFIX "mt" +# else // _DLL +# define POCO_STATIC_SUFFIX "" +# endif +# else // _DEBUG +# define POCO_DEBUG_SUFFIX "d" +# if !defined(_DLL) +# define POCO_STATIC_SUFFIX "mt" +# else // _DLL +# define POCO_STATIC_SUFFIX "" +# endif +# endif +# pragma comment(lib, "libcrypto" POCO_STATIC_SUFFIX POCO_DEBUG_SUFFIX ".lib") +# pragma comment(lib, "libssl" POCO_STATIC_SUFFIX POCO_DEBUG_SUFFIX ".lib") +# if !defined(_WIN64) && !defined(_DLL) && (POCO_INTERNAL_OPENSSL_MSVC_VER == 120) \ + && (POCO_MSVC_VERSION < POCO_INTERNAL_OPENSSL_MSVC_VER) +# pragma comment(lib, "libPreVS2013CRT" POCO_STATIC_SUFFIX POCO_DEBUG_SUFFIX ".lib") +# endif +# if !defined(_DLL) && (POCO_MSVS_VERSION >= 2015) +# pragma comment(lib, "legacy_stdio_definitions.lib") +# pragma comment(lib, "legacy_stdio_wide_specifiers.lib") +# endif +# elif defined(POCO_EXTERNAL_OPENSSL) +# if POCO_EXTERNAL_OPENSSL == POCO_EXTERNAL_OPENSSL_SLPRO +# if defined(POCO_DLL) +# if OPENSSL_VERSION_PREREQ(1, 1) +# pragma comment(lib, "libcrypto.lib") +# pragma comment(lib, "libssl.lib") +# else +# pragma comment(lib, "libeay32.lib") +# pragma comment(lib, "ssleay32.lib") +# endif +# else +# if OPENSSL_VERSION_PREREQ(1, 1) +# if defined(_WIN64) +# pragma comment(lib, "libcrypto64" POCO_LIB_SUFFIX) +# pragma comment(lib, "libssl64" POCO_LIB_SUFFIX) +# else +# pragma comment(lib, "libcrypto32" POCO_LIB_SUFFIX) +# pragma comment(lib, "libssl32" POCO_LIB_SUFFIX) +# endif +# else +# pragma comment(lib, "libeay32" POCO_LIB_SUFFIX) +# pragma comment(lib, "ssleay32" POCO_LIB_SUFFIX) +# endif +# endif +# elif POCO_EXTERNAL_OPENSSL == POCO_EXTERNAL_OPENSSL_DEFAULT +# if OPENSSL_VERSION_PREREQ(1, 1) +# pragma comment(lib, "libcrypto.lib") +# pragma comment(lib, "libssl.lib") +# else +# pragma comment(lib, "libeay32.lib") +# pragma comment(lib, "ssleay32.lib") +# endif +# endif +# endif // POCO_INTERNAL_OPENSSL_MSVC_VER +# if !defined(Crypto_EXPORTS) +# pragma comment(lib, "PocoCrypto" POCO_LIB_SUFFIX) +# endif +# endif // POCO_NO_AUTOMATIC_LIBS #endif -namespace Poco { -namespace Crypto { +namespace Poco +{ +namespace Crypto +{ -void Crypto_API initializeCrypto(); - /// Initialize the Crypto library, as well as the underlying OpenSSL - /// libraries, by calling OpenSSLInitializer::initialize(). - /// - /// Should be called before using any class from the Crypto library. - /// The Crypto library will be initialized automatically, through - /// OpenSSLInitializer instances held by various Crypto classes - /// (Cipher, CipherKey, RSAKey, X509Certificate). - /// However, it is recommended to call initializeCrypto() - /// in any case at application startup. - /// - /// Can be called multiple times; however, for every call to - /// initializeCrypto(), a matching call to uninitializeCrypto() - /// must be performed. + void Crypto_API initializeCrypto(); + /// Initialize the Crypto library, as well as the underlying OpenSSL + /// libraries, by calling OpenSSLInitializer::initialize(). + /// + /// Should be called before using any class from the Crypto library. + /// The Crypto library will be initialized automatically, through + /// OpenSSLInitializer instances held by various Crypto classes + /// (Cipher, CipherKey, RSAKey, X509Certificate). + /// However, it is recommended to call initializeCrypto() + /// in any case at application startup. + /// + /// Can be called multiple times; however, for every call to + /// initializeCrypto(), a matching call to uninitializeCrypto() + /// must be performed. -void Crypto_API uninitializeCrypto(); - /// Uninitializes the Crypto library by calling - /// OpenSSLInitializer::uninitialize(). + void Crypto_API uninitializeCrypto(); + /// Uninitializes the Crypto library by calling + /// OpenSSLInitializer::uninitialize(). -} } // namespace Poco::Crypto +} +} // namespace Poco::Crypto #endif // Crypto_Crypto_INCLUDED diff --git a/base/poco/Crypto/include/Poco/Crypto/CryptoException.h b/base/poco/Crypto/include/Poco/Crypto/CryptoException.h index 34c15111e6a..8a2ddd27405 100644 --- a/base/poco/Crypto/include/Poco/Crypto/CryptoException.h +++ b/base/poco/Crypto/include/Poco/Crypto/CryptoException.h @@ -23,34 +23,37 @@ #include "Poco/Exception.h" -namespace Poco { -namespace Crypto { - - -POCO_DECLARE_EXCEPTION(Crypto_API, CryptoException, Poco::Exception) - - -class Crypto_API OpenSSLException : public CryptoException +namespace Poco +{ +namespace Crypto { -public: - OpenSSLException(int code = 0); - OpenSSLException(const std::string& msg, int code = 0); - OpenSSLException(const std::string& msg, const std::string& arg, int code = 0); - OpenSSLException(const std::string& msg, const Poco::Exception& exc, int code = 0); - OpenSSLException(const OpenSSLException& exc); - ~OpenSSLException() throw(); - OpenSSLException& operator = (const OpenSSLException& exc); - const char* name() const throw(); - const char* className() const throw(); - Poco::Exception* clone() const; - void rethrow() const; - -private: - void setExtMessage(); -}; -} } // namespace Poco::Crypto + POCO_DECLARE_EXCEPTION(Crypto_API, CryptoException, Poco::Exception) + + + class Crypto_API OpenSSLException : public CryptoException + { + public: + OpenSSLException(int code = 0); + OpenSSLException(const std::string & msg, int code = 0); + OpenSSLException(const std::string & msg, const std::string & arg, int code = 0); + OpenSSLException(const std::string & msg, const Poco::Exception & exc, int code = 0); + OpenSSLException(const OpenSSLException & exc); + ~OpenSSLException() throw(); + OpenSSLException & operator=(const OpenSSLException & exc); + const char * name() const throw(); + const char * className() const throw(); + Poco::Exception * clone() const; + void rethrow() const; + + private: + void setExtMessage(); + }; + + +} +} // namespace Poco::Crypto #endif // Crypto_CryptoException_INCLUDED diff --git a/base/poco/Crypto/include/Poco/Crypto/CryptoStream.h b/base/poco/Crypto/include/Poco/Crypto/CryptoStream.h index 25a99a4ae58..788b0ab57ce 100644 --- a/base/poco/Crypto/include/Poco/Crypto/CryptoStream.h +++ b/base/poco/Crypto/include/Poco/Crypto/CryptoStream.h @@ -19,174 +19,177 @@ #define Crypto_CryptoStream_INCLUDED -#include "Poco/Crypto/Crypto.h" -#include "Poco/BufferedStreamBuf.h" -#include "Poco/Buffer.h" #include +#include "Poco/Buffer.h" +#include "Poco/BufferedStreamBuf.h" +#include "Poco/Crypto/Crypto.h" -namespace Poco { -namespace Crypto { - - -class CryptoTransform; -class Cipher; - - -class Crypto_API CryptoStreamBuf: public Poco::BufferedStreamBuf - /// This stream buffer performs cryptographic transformation on the data - /// going through it. +namespace Poco { -public: - CryptoStreamBuf(std::istream& istr, CryptoTransform* pTransform, std::streamsize bufferSize = 8192); - CryptoStreamBuf(std::ostream& ostr, CryptoTransform* pTransform, std::streamsize bufferSize = 8192); - - virtual ~CryptoStreamBuf(); - - void close(); - /// Flushes all buffers and finishes the encryption. - -protected: - int readFromDevice(char* buffer, std::streamsize length); - int writeToDevice(const char* buffer, std::streamsize length); - -private: - CryptoTransform* _pTransform; - std::istream* _pIstr; - std::ostream* _pOstr; - bool _eof; - - Poco::Buffer _buffer; - - CryptoStreamBuf(const CryptoStreamBuf&); - CryptoStreamBuf& operator = (const CryptoStreamBuf&); -}; - - -class Crypto_API CryptoIOS: public virtual std::ios - /// The base class for CryptoInputStream and CryptoOutputStream. - /// - /// This class is needed to ensure correct initialization order of the - /// stream buffer and base classes. +namespace Crypto { -public: - CryptoIOS(std::istream& istr, CryptoTransform* pTransform, std::streamsize bufferSize = 8192); - CryptoIOS(std::ostream& ostr, CryptoTransform* pTransform, std::streamsize bufferSize = 8192); - ~CryptoIOS(); - CryptoStreamBuf* rdbuf(); - -protected: - CryptoStreamBuf _buf; -}; -class Crypto_API CryptoInputStream: public CryptoIOS, public std::istream - /// This stream transforms all data passing through it using the given - /// CryptoTransform. - /// - /// Use a CryptoTransform object provided by Cipher::createEncrytor() or - /// Cipher::createDecryptor() to create an encrypting or decrypting stream, - /// respectively. -{ -public: - CryptoInputStream(std::istream& istr, CryptoTransform* pTransform, std::streamsize bufferSize = 8192); - /// Create a new CryptoInputStream object. The CryptoInputStream takes the - /// ownership of the given CryptoTransform object. - - CryptoInputStream(std::istream& istr, Cipher& cipher, std::streamsize bufferSize = 8192); - /// Create a new encrypting CryptoInputStream object using the given cipher. - - ~CryptoInputStream(); - /// Destroys the CryptoInputStream. -}; + class CryptoTransform; + class Cipher; -class Crypto_API CryptoOutputStream: public CryptoIOS, public std::ostream - /// This stream transforms all data passing through it using the given - /// CryptoTransform. - /// - /// Use a CryptoTransform object provided by Cipher::createEncrytor() or - /// Cipher::createDecryptor() to create an encrypting or decrypting stream, - /// respectively. - /// - /// After all data has been passed through the stream, close() must be called - /// to ensure completion of cryptographic transformation. -{ -public: - CryptoOutputStream(std::ostream& ostr, CryptoTransform* pTransform, std::streamsize bufferSize = 8192); - /// Create a new CryptoOutputStream object. The CryptoOutputStream takes the - /// ownership of the given CryptoTransform object. + class Crypto_API CryptoStreamBuf : public Poco::BufferedStreamBuf + /// This stream buffer performs cryptographic transformation on the data + /// going through it. + { + public: + CryptoStreamBuf(std::istream & istr, CryptoTransform * pTransform, std::streamsize bufferSize = 8192); + CryptoStreamBuf(std::ostream & ostr, CryptoTransform * pTransform, std::streamsize bufferSize = 8192); - CryptoOutputStream(std::ostream& ostr, Cipher& cipher, std::streamsize bufferSize = 8192); - /// Create a new decrypting CryptoOutputStream object using the given cipher. + virtual ~CryptoStreamBuf(); - ~CryptoOutputStream(); - /// Destroys the CryptoOutputStream. + void close(); + /// Flushes all buffers and finishes the encryption. - void close(); - /// Flushes all buffers and finishes the encryption. -}; + protected: + int readFromDevice(char * buffer, std::streamsize length); + int writeToDevice(const char * buffer, std::streamsize length); + + private: + CryptoTransform * _pTransform; + std::istream * _pIstr; + std::ostream * _pOstr; + bool _eof; + + Poco::Buffer _buffer; + + CryptoStreamBuf(const CryptoStreamBuf &); + CryptoStreamBuf & operator=(const CryptoStreamBuf &); + }; -class Crypto_API DecryptingInputStream: public CryptoIOS, public std::istream - /// This stream decrypts all data passing through it using the given - /// Cipher. -{ -public: - DecryptingInputStream(std::istream& istr, Cipher& cipher, std::streamsize bufferSize = 8192); - /// Create a new DecryptingInputStream object using the given cipher. + class Crypto_API CryptoIOS : public virtual std::ios + /// The base class for CryptoInputStream and CryptoOutputStream. + /// + /// This class is needed to ensure correct initialization order of the + /// stream buffer and base classes. + { + public: + CryptoIOS(std::istream & istr, CryptoTransform * pTransform, std::streamsize bufferSize = 8192); + CryptoIOS(std::ostream & ostr, CryptoTransform * pTransform, std::streamsize bufferSize = 8192); + ~CryptoIOS(); + CryptoStreamBuf * rdbuf(); - ~DecryptingInputStream(); - /// Destroys the DecryptingInputStream. -}; + protected: + CryptoStreamBuf _buf; + }; -class Crypto_API DecryptingOutputStream: public CryptoIOS, public std::ostream - /// This stream decrypts all data passing through it using the given - /// Cipher. -{ -public: - DecryptingOutputStream(std::ostream& ostr, Cipher& cipher, std::streamsize bufferSize = 8192); - /// Create a new DecryptingOutputStream object using the given cipher. + class Crypto_API CryptoInputStream : public CryptoIOS, public std::istream + /// This stream transforms all data passing through it using the given + /// CryptoTransform. + /// + /// Use a CryptoTransform object provided by Cipher::createEncrytor() or + /// Cipher::createDecryptor() to create an encrypting or decrypting stream, + /// respectively. + { + public: + CryptoInputStream(std::istream & istr, CryptoTransform * pTransform, std::streamsize bufferSize = 8192); + /// Create a new CryptoInputStream object. The CryptoInputStream takes the + /// ownership of the given CryptoTransform object. - ~DecryptingOutputStream(); - /// Destroys the DecryptingOutputStream. + CryptoInputStream(std::istream & istr, Cipher & cipher, std::streamsize bufferSize = 8192); + /// Create a new encrypting CryptoInputStream object using the given cipher. - void close(); - /// Flushes all buffers and finishes the decryption. -}; + ~CryptoInputStream(); + /// Destroys the CryptoInputStream. + }; -class Crypto_API EncryptingInputStream: public CryptoIOS, public std::istream - /// This stream encrypts all data passing through it using the given - /// Cipher. -{ -public: - EncryptingInputStream(std::istream& istr, Cipher& cipher, std::streamsize bufferSize = 8192); - /// Create a new EncryptingInputStream object using the given cipher. + class Crypto_API CryptoOutputStream : public CryptoIOS, public std::ostream + /// This stream transforms all data passing through it using the given + /// CryptoTransform. + /// + /// Use a CryptoTransform object provided by Cipher::createEncrytor() or + /// Cipher::createDecryptor() to create an encrypting or decrypting stream, + /// respectively. + /// + /// After all data has been passed through the stream, close() must be called + /// to ensure completion of cryptographic transformation. + { + public: + CryptoOutputStream(std::ostream & ostr, CryptoTransform * pTransform, std::streamsize bufferSize = 8192); + /// Create a new CryptoOutputStream object. The CryptoOutputStream takes the + /// ownership of the given CryptoTransform object. - ~EncryptingInputStream(); - /// Destroys the EncryptingInputStream. -}; + CryptoOutputStream(std::ostream & ostr, Cipher & cipher, std::streamsize bufferSize = 8192); + /// Create a new decrypting CryptoOutputStream object using the given cipher. + + ~CryptoOutputStream(); + /// Destroys the CryptoOutputStream. + + void close(); + /// Flushes all buffers and finishes the encryption. + }; -class Crypto_API EncryptingOutputStream: public CryptoIOS, public std::ostream - /// This stream encrypts all data passing through it using the given - /// Cipher. -{ -public: - EncryptingOutputStream(std::ostream& ostr, Cipher& cipher, std::streamsize bufferSize = 8192); - /// Create a new EncryptingOutputStream object using the given cipher. + class Crypto_API DecryptingInputStream : public CryptoIOS, public std::istream + /// This stream decrypts all data passing through it using the given + /// Cipher. + { + public: + DecryptingInputStream(std::istream & istr, Cipher & cipher, std::streamsize bufferSize = 8192); + /// Create a new DecryptingInputStream object using the given cipher. - ~EncryptingOutputStream(); - /// Destroys the EncryptingOutputStream. - - void close(); - /// Flushes all buffers and finishes the encryption. -}; + ~DecryptingInputStream(); + /// Destroys the DecryptingInputStream. + }; -} } // namespace Poco::Crypto + class Crypto_API DecryptingOutputStream : public CryptoIOS, public std::ostream + /// This stream decrypts all data passing through it using the given + /// Cipher. + { + public: + DecryptingOutputStream(std::ostream & ostr, Cipher & cipher, std::streamsize bufferSize = 8192); + /// Create a new DecryptingOutputStream object using the given cipher. + + ~DecryptingOutputStream(); + /// Destroys the DecryptingOutputStream. + + void close(); + /// Flushes all buffers and finishes the decryption. + }; + + + class Crypto_API EncryptingInputStream : public CryptoIOS, public std::istream + /// This stream encrypts all data passing through it using the given + /// Cipher. + { + public: + EncryptingInputStream(std::istream & istr, Cipher & cipher, std::streamsize bufferSize = 8192); + /// Create a new EncryptingInputStream object using the given cipher. + + ~EncryptingInputStream(); + /// Destroys the EncryptingInputStream. + }; + + + class Crypto_API EncryptingOutputStream : public CryptoIOS, public std::ostream + /// This stream encrypts all data passing through it using the given + /// Cipher. + { + public: + EncryptingOutputStream(std::ostream & ostr, Cipher & cipher, std::streamsize bufferSize = 8192); + /// Create a new EncryptingOutputStream object using the given cipher. + + ~EncryptingOutputStream(); + /// Destroys the EncryptingOutputStream. + + void close(); + /// Flushes all buffers and finishes the encryption. + }; + + +} +} // namespace Poco::Crypto #endif // Crypto_CryptoStream_INCLUDED diff --git a/base/poco/Crypto/include/Poco/Crypto/CryptoTransform.h b/base/poco/Crypto/include/Poco/Crypto/CryptoTransform.h index 9fa3806c653..7fbcff2b5c3 100644 --- a/base/poco/Crypto/include/Poco/Crypto/CryptoTransform.h +++ b/base/poco/Crypto/include/Poco/Crypto/CryptoTransform.h @@ -18,70 +18,71 @@ #define Crypto_CryptoTransform_INCLUDED -#include "Poco/Crypto/Crypto.h" #include +#include "Poco/Crypto/Crypto.h" -namespace Poco { -namespace Crypto { - - -class Crypto_API CryptoTransform - /// This interface represents the basic operations for cryptographic - /// transformations to be used with a CryptoInputStream or a - /// CryptoOutputStream. - /// - /// Implementations of this class are returned by the Cipher class to - /// perform encryption or decryption of data. +namespace Poco +{ +namespace Crypto { -public: - CryptoTransform(); - /// Creates a new CryptoTransform object. - - virtual ~CryptoTransform(); - /// Destroys the CryptoTransform. - - virtual std::size_t blockSize() const = 0; - /// Returns the block size for this CryptoTransform. - - virtual int setPadding(int padding); - /// Enables or disables padding. By default encryption operations are padded using standard block - /// padding and the padding is checked and removed when decrypting. If the padding parameter is zero then - /// no padding is performed, the total amount of data encrypted or decrypted must then be a multiple of - /// the block size or an error will occur. - - virtual std::string getTag(std::size_t tagSize = 16) = 0; - /// Returns the GCM tag after encrypting using GCM mode. - /// - /// Must be called after finalize(). - - virtual void setTag(const std::string& tag) = 0; - /// Sets the GCM tag for authenticated decryption using GCM mode. - /// - /// Must be set before finalize() is called, otherwise - /// decryption will fail. - - virtual std::streamsize transform( - const unsigned char* input, - std::streamsize inputLength, - unsigned char* output, - std::streamsize outputLength) = 0; - /// Transforms a chunk of data. The inputLength is arbitrary and does not - /// need to be a multiple of the block size. The output buffer has a maximum - /// capacity of the given outputLength that must be at least - /// inputLength + blockSize() - 1 - /// Returns the number of bytes written to the output buffer. - - virtual std::streamsize finalize(unsigned char* output, std::streamsize length) = 0; - /// Finalizes the transformation. The output buffer must contain enough - /// space for at least two blocks, ie. - /// length >= 2*blockSize() - /// must be true. Returns the number of bytes written to the output - /// buffer. -}; -} } // namespace Poco::Crypto + class Crypto_API CryptoTransform + /// This interface represents the basic operations for cryptographic + /// transformations to be used with a CryptoInputStream or a + /// CryptoOutputStream. + /// + /// Implementations of this class are returned by the Cipher class to + /// perform encryption or decryption of data. + { + public: + CryptoTransform(); + /// Creates a new CryptoTransform object. + + virtual ~CryptoTransform(); + /// Destroys the CryptoTransform. + + virtual std::size_t blockSize() const = 0; + /// Returns the block size for this CryptoTransform. + + virtual int setPadding(int padding); + /// Enables or disables padding. By default encryption operations are padded using standard block + /// padding and the padding is checked and removed when decrypting. If the padding parameter is zero then + /// no padding is performed, the total amount of data encrypted or decrypted must then be a multiple of + /// the block size or an error will occur. + + virtual std::string getTag(std::size_t tagSize = 16) = 0; + /// Returns the GCM tag after encrypting using GCM mode. + /// + /// Must be called after finalize(). + + virtual void setTag(const std::string & tag) = 0; + /// Sets the GCM tag for authenticated decryption using GCM mode. + /// + /// Must be set before finalize() is called, otherwise + /// decryption will fail. + + virtual std::streamsize + transform(const unsigned char * input, std::streamsize inputLength, unsigned char * output, std::streamsize outputLength) + = 0; + /// Transforms a chunk of data. The inputLength is arbitrary and does not + /// need to be a multiple of the block size. The output buffer has a maximum + /// capacity of the given outputLength that must be at least + /// inputLength + blockSize() - 1 + /// Returns the number of bytes written to the output buffer. + + virtual std::streamsize finalize(unsigned char * output, std::streamsize length) = 0; + /// Finalizes the transformation. The output buffer must contain enough + /// space for at least two blocks, ie. + /// length >= 2*blockSize() + /// must be true. Returns the number of bytes written to the output + /// buffer. + }; + + +} +} // namespace Poco::Crypto #endif // Crypto_CryptoTransform_INCLUDED diff --git a/base/poco/Crypto/include/Poco/Crypto/DigestEngine.h b/base/poco/Crypto/include/Poco/Crypto/DigestEngine.h index 1c30e769d5f..77a1349f8e2 100644 --- a/base/poco/Crypto/include/Poco/Crypto/DigestEngine.h +++ b/base/poco/Crypto/include/Poco/Crypto/DigestEngine.h @@ -18,63 +18,66 @@ #define Crypto_DigestEngine_INCLUDED +#include #include "Poco/Crypto/Crypto.h" #include "Poco/Crypto/OpenSSLInitializer.h" #include "Poco/DigestEngine.h" -#include -namespace Poco { -namespace Crypto { - - -class Crypto_API DigestEngine: public Poco::DigestEngine - /// This class implements a Poco::DigestEngine for all - /// digest algorithms supported by OpenSSL. +namespace Poco { -public: - DigestEngine(const std::string& name); - /// Creates a DigestEngine using the digest with the given name - /// (e.g., "MD5", "SHA1", "SHA256", "SHA512", etc.). - /// See the OpenSSL documentation for a list of supported digest algorithms. - /// - /// Throws a Poco::NotFoundException if no algorithm with the given name exists. - - ~DigestEngine(); - /// Destroys the DigestEngine. - - const std::string& algorithm() const; - /// Returns the name of the digest algorithm. - - int nid() const; - /// Returns the NID (OpenSSL object identifier) of the digest algorithm. - - // DigestEngine - std::size_t digestLength() const; - void reset(); - const Poco::DigestEngine::Digest& digest(); - -protected: - void updateImpl(const void* data, std::size_t length); - -private: - std::string _name; - EVP_MD_CTX* _pContext; - Poco::DigestEngine::Digest _digest; - OpenSSLInitializer _openSSLInitializer; -}; - - -// -// inlines -// -inline const std::string& DigestEngine::algorithm() const +namespace Crypto { - return _name; + + + class Crypto_API DigestEngine : public Poco::DigestEngine + /// This class implements a Poco::DigestEngine for all + /// digest algorithms supported by OpenSSL. + { + public: + DigestEngine(const std::string & name); + /// Creates a DigestEngine using the digest with the given name + /// (e.g., "MD5", "SHA1", "SHA256", "SHA512", etc.). + /// See the OpenSSL documentation for a list of supported digest algorithms. + /// + /// Throws a Poco::NotFoundException if no algorithm with the given name exists. + + ~DigestEngine(); + /// Destroys the DigestEngine. + + const std::string & algorithm() const; + /// Returns the name of the digest algorithm. + + int nid() const; + /// Returns the NID (OpenSSL object identifier) of the digest algorithm. + + // DigestEngine + std::size_t digestLength() const; + void reset(); + const Poco::DigestEngine::Digest & digest(); + + protected: + void updateImpl(const void * data, std::size_t length); + + private: + std::string _name; + EVP_MD_CTX * _pContext; + Poco::DigestEngine::Digest _digest; + OpenSSLInitializer _openSSLInitializer; + }; + + + // + // inlines + // + inline const std::string & DigestEngine::algorithm() const + { + return _name; + } + + } - - -} } // namespace Poco::Crypto +} // namespace Poco::Crypto #endif // Crypto_DigestEngine_INCLUDED diff --git a/base/poco/Crypto/include/Poco/Crypto/ECDSADigestEngine.h b/base/poco/Crypto/include/Poco/Crypto/ECDSADigestEngine.h index ed6fab442f6..2d0c31ba09c 100644 --- a/base/poco/Crypto/include/Poco/Crypto/ECDSADigestEngine.h +++ b/base/poco/Crypto/include/Poco/Crypto/ECDSADigestEngine.h @@ -19,83 +19,85 @@ #define Crypto_ECDSADigestEngine_INCLUDED -#include "Poco/Crypto/Crypto.h" -#include "Poco/Crypto/ECKey.h" -#include "Poco/DigestEngine.h" -#include "Poco/Crypto/DigestEngine.h" #include #include +#include "Poco/Crypto/Crypto.h" +#include "Poco/Crypto/DigestEngine.h" +#include "Poco/Crypto/ECKey.h" +#include "Poco/DigestEngine.h" -namespace Poco { -namespace Crypto { - - -class Crypto_API ECDSADigestEngine: public Poco::DigestEngine - /// This class implements a Poco::DigestEngine that can be - /// used to compute a secure digital signature. - /// - /// First another Poco::Crypto::DigestEngine is created and - /// used to compute a cryptographic hash of the data to be - /// signed. Then, the hash value is encrypted, using - /// the ECDSA private key. - /// - /// To verify a signature, pass it to the verify() - /// member function. It will decrypt the signature - /// using the ECDSA public key and compare the resulting - /// hash with the actual hash of the data. +namespace Poco +{ +namespace Crypto { -public: - - ECDSADigestEngine(const ECKey& key, const std::string &name); - /// Creates the ECDSADigestEngine with the given ECDSA key, - /// using the hash algorithm with the given name - /// (e.g., "SHA1", "SHA256", "SHA512", etc.). - /// See the OpenSSL documentation for a list of supported digest algorithms. - /// - /// Throws a Poco::NotFoundException if no algorithm with the given name exists. - - ~ECDSADigestEngine(); - /// Destroys the ECDSADigestEngine. - - std::size_t digestLength() const; - /// Returns the length of the digest in bytes. - - void reset(); - /// Resets the engine so that a new - /// digest can be computed. - - const DigestEngine::Digest& digest(); - /// Finishes the computation of the digest - /// (the first time it's called) and - /// returns the message digest. - /// - /// Can be called multiple times. - - const DigestEngine::Digest& signature(); - /// Signs the digest using the ECDSADSA algorithm - /// and the private key (the first time it's - /// called) and returns the result. - /// - /// Can be called multiple times. - - bool verify(const DigestEngine::Digest& signature); - /// Verifies the data against the signature. - /// - /// Returns true if the signature can be verified, false otherwise. - -protected: - void updateImpl(const void* data, std::size_t length); - -private: - ECKey _key; - Poco::Crypto::DigestEngine _engine; - Poco::DigestEngine::Digest _digest; - Poco::DigestEngine::Digest _signature; -}; -} } // namespace Poco::Crypto + class Crypto_API ECDSADigestEngine : public Poco::DigestEngine + /// This class implements a Poco::DigestEngine that can be + /// used to compute a secure digital signature. + /// + /// First another Poco::Crypto::DigestEngine is created and + /// used to compute a cryptographic hash of the data to be + /// signed. Then, the hash value is encrypted, using + /// the ECDSA private key. + /// + /// To verify a signature, pass it to the verify() + /// member function. It will decrypt the signature + /// using the ECDSA public key and compare the resulting + /// hash with the actual hash of the data. + { + public: + ECDSADigestEngine(const ECKey & key, const std::string & name); + /// Creates the ECDSADigestEngine with the given ECDSA key, + /// using the hash algorithm with the given name + /// (e.g., "SHA1", "SHA256", "SHA512", etc.). + /// See the OpenSSL documentation for a list of supported digest algorithms. + /// + /// Throws a Poco::NotFoundException if no algorithm with the given name exists. + + ~ECDSADigestEngine(); + /// Destroys the ECDSADigestEngine. + + std::size_t digestLength() const; + /// Returns the length of the digest in bytes. + + void reset(); + /// Resets the engine so that a new + /// digest can be computed. + + const DigestEngine::Digest & digest(); + /// Finishes the computation of the digest + /// (the first time it's called) and + /// returns the message digest. + /// + /// Can be called multiple times. + + const DigestEngine::Digest & signature(); + /// Signs the digest using the ECDSADSA algorithm + /// and the private key (the first time it's + /// called) and returns the result. + /// + /// Can be called multiple times. + + bool verify(const DigestEngine::Digest & signature); + /// Verifies the data against the signature. + /// + /// Returns true if the signature can be verified, false otherwise. + + protected: + void updateImpl(const void * data, std::size_t length); + + private: + ECKey _key; + Poco::Crypto::DigestEngine _engine; + Poco::DigestEngine::Digest _digest; + Poco::DigestEngine::Digest _signature; + }; + + +} +} // namespace Poco::Crypto #endif // Crypto_ECDSADigestEngine_INCLUDED diff --git a/base/poco/Crypto/include/Poco/Crypto/ECKey.h b/base/poco/Crypto/include/Poco/Crypto/ECKey.h index 15d5401cbcd..babcd814ec9 100644 --- a/base/poco/Crypto/include/Poco/Crypto/ECKey.h +++ b/base/poco/Crypto/include/Poco/Crypto/ECKey.h @@ -20,116 +20,119 @@ #include "Poco/Crypto/Crypto.h" -#include "Poco/Crypto/KeyPair.h" #include "Poco/Crypto/ECKeyImpl.h" +#include "Poco/Crypto/KeyPair.h" -namespace Poco { -namespace Crypto { - - -class X509Certificate; -class PKCS12Container; - - -class Crypto_API ECKey : public KeyPair - /// This class stores an EC key pair, consisting - /// of private and public key. Storage of the private - /// key is optional. - /// - /// If a private key is available, the ECKey can be - /// used for decrypting data (encrypted with the public key) - /// or computing secure digital signatures. +namespace Poco { -public: - ECKey(const EVPPKey& key); - /// Constructs ECKeyImpl by extracting the EC key. - - ECKey(const X509Certificate& cert); - /// Extracts the EC public key from the given certificate. - - ECKey(const PKCS12Container& cert); - /// Extracts the EC private key from the given certificate. - - ECKey(const std::string& eccGroup); - /// Creates the ECKey. Creates a new public/private key pair using the given parameters. - /// Can be used to sign data and verify signatures. - - ECKey(const std::string& publicKeyFile, const std::string& privateKeyFile, const std::string& privateKeyPassphrase = ""); - /// Creates the ECKey, by reading public and private key from the given files and - /// using the given passphrase for the private key. - /// - /// Cannot be used for signing or decryption unless a private key is available. - /// - /// If a private key is specified, you don't need to specify a public key file. - /// OpenSSL will auto-create the public key from the private key. - - ECKey(std::istream* pPublicKeyStream, std::istream* pPrivateKeyStream = 0, const std::string& privateKeyPassphrase = ""); - /// Creates the ECKey, by reading public and private key from the given streams and - /// using the given passphrase for the private key. - /// - /// Cannot be used for signing or decryption unless a private key is available. - /// - /// If a private key is specified, you don't need to specify a public key file. - /// OpenSSL will auto-create the public key from the private key. - - ~ECKey(); - /// Destroys the ECKey. - - ECKeyImpl::Ptr impl() const; - /// Returns the impl object. - - static std::string getCurveName(int nid = -1); - /// Returns elliptical curve name corresponding to - /// the given nid; if nid is not found, returns - /// empty string. - /// - /// If nid is -1, returns first curve name. - /// - /// If no curves are found, returns empty string; - - static int getCurveNID(std::string& name); - /// Returns the NID of the specified curve. - /// - /// If name is empty, returns the first curve NID - /// and updates the name accordingly. - - static bool hasCurve(const std::string& name); - /// Returns true if the named curve is found, - /// false otherwise. - -private: - ECKeyImpl::Ptr _pImpl; -}; - - -// -// inlines -// -inline ECKeyImpl::Ptr ECKey::impl() const +namespace Crypto { - return _pImpl; + + + class X509Certificate; + class PKCS12Container; + + + class Crypto_API ECKey : public KeyPair + /// This class stores an EC key pair, consisting + /// of private and public key. Storage of the private + /// key is optional. + /// + /// If a private key is available, the ECKey can be + /// used for decrypting data (encrypted with the public key) + /// or computing secure digital signatures. + { + public: + ECKey(const EVPPKey & key); + /// Constructs ECKeyImpl by extracting the EC key. + + ECKey(const X509Certificate & cert); + /// Extracts the EC public key from the given certificate. + + ECKey(const PKCS12Container & cert); + /// Extracts the EC private key from the given certificate. + + ECKey(const std::string & eccGroup); + /// Creates the ECKey. Creates a new public/private key pair using the given parameters. + /// Can be used to sign data and verify signatures. + + ECKey(const std::string & publicKeyFile, const std::string & privateKeyFile, const std::string & privateKeyPassphrase = ""); + /// Creates the ECKey, by reading public and private key from the given files and + /// using the given passphrase for the private key. + /// + /// Cannot be used for signing or decryption unless a private key is available. + /// + /// If a private key is specified, you don't need to specify a public key file. + /// OpenSSL will auto-create the public key from the private key. + + ECKey(std::istream * pPublicKeyStream, std::istream * pPrivateKeyStream = 0, const std::string & privateKeyPassphrase = ""); + /// Creates the ECKey, by reading public and private key from the given streams and + /// using the given passphrase for the private key. + /// + /// Cannot be used for signing or decryption unless a private key is available. + /// + /// If a private key is specified, you don't need to specify a public key file. + /// OpenSSL will auto-create the public key from the private key. + + ~ECKey(); + /// Destroys the ECKey. + + ECKeyImpl::Ptr impl() const; + /// Returns the impl object. + + static std::string getCurveName(int nid = -1); + /// Returns elliptical curve name corresponding to + /// the given nid; if nid is not found, returns + /// empty string. + /// + /// If nid is -1, returns first curve name. + /// + /// If no curves are found, returns empty string; + + static int getCurveNID(std::string & name); + /// Returns the NID of the specified curve. + /// + /// If name is empty, returns the first curve NID + /// and updates the name accordingly. + + static bool hasCurve(const std::string & name); + /// Returns true if the named curve is found, + /// false otherwise. + + private: + ECKeyImpl::Ptr _pImpl; + }; + + + // + // inlines + // + inline ECKeyImpl::Ptr ECKey::impl() const + { + return _pImpl; + } + + + inline std::string ECKey::getCurveName(int nid) + { + return ECKeyImpl::getCurveName(nid); + } + + + inline int ECKey::getCurveNID(std::string & name) + { + return ECKeyImpl::getCurveNID(name); + } + + + inline bool ECKey::hasCurve(const std::string & name) + { + return ECKeyImpl::hasCurve(name); + } + + } - - -inline std::string ECKey::getCurveName(int nid) -{ - return ECKeyImpl::getCurveName(nid); -} - - -inline int ECKey::getCurveNID(std::string& name) -{ - return ECKeyImpl::getCurveNID(name); -} - - -inline bool ECKey::hasCurve(const std::string& name) -{ - return ECKeyImpl::hasCurve(name); -} - - -} } // namespace Poco::Crypto +} // namespace Poco::Crypto #endif // Crypto_ECKey_INCLUDED diff --git a/base/poco/Crypto/include/Poco/Crypto/ECKeyImpl.h b/base/poco/Crypto/include/Poco/Crypto/ECKeyImpl.h index 840764304d1..2a72861a84e 100644 --- a/base/poco/Crypto/include/Poco/Crypto/ECKeyImpl.h +++ b/base/poco/Crypto/include/Poco/Crypto/ECKeyImpl.h @@ -19,156 +19,155 @@ #define Crypto_ECKeyImplImpl_INCLUDED +#include +#include +#include +#include +#include +#include "Poco/AutoPtr.h" #include "Poco/Crypto/Crypto.h" #include "Poco/Crypto/EVPPKey.h" #include "Poco/Crypto/KeyPairImpl.h" #include "Poco/Crypto/OpenSSLInitializer.h" #include "Poco/RefCountedObject.h" -#include "Poco/AutoPtr.h" -#include -#include -#include -#include -#include -namespace Poco { -namespace Crypto { - - -class X509Certificate; -class PKCS12Container; - - -class ECKeyImpl: public KeyPairImpl - /// Elliptic Curve key clas implementation. +namespace Poco { -public: - typedef Poco::AutoPtr Ptr; - typedef std::vector ByteVec; - - ECKeyImpl(const EVPPKey& key); - /// Constructs ECKeyImpl by extracting the EC key. - - ECKeyImpl(const X509Certificate& cert); - /// Constructs ECKeyImpl by extracting the EC public key from the given certificate. - - ECKeyImpl(const PKCS12Container& cert); - /// Constructs ECKeyImpl by extracting the EC private key from the given certificate. - - ECKeyImpl(int eccGroup); - /// Creates the ECKey of the specified group. Creates a new public/private keypair using the given parameters. - /// Can be used to sign data and verify signatures. - - ECKeyImpl(const std::string& publicKeyFile, const std::string& privateKeyFile, const std::string& privateKeyPassphrase); - /// Creates the ECKey, by reading public and private key from the given files and - /// using the given passphrase for the private key. Can only by used for signing if - /// a private key is available. - - ECKeyImpl(std::istream* pPublicKeyStream, std::istream* pPrivateKeyStream, const std::string& privateKeyPassphrase); - /// Creates the ECKey. Can only by used for signing if pPrivKey - /// is not null. If a private key file is specified, you don't need to - /// specify a public key file. OpenSSL will auto-create it from the private key. - - ~ECKeyImpl(); - /// Destroys the ECKeyImpl. - - EC_KEY* getECKey(); - /// Returns the OpenSSL EC key. - - const EC_KEY* getECKey() const; - /// Returns the OpenSSL EC key. - - int size() const; - /// Returns the EC key length in bits. - - int groupId() const; - /// Returns the EC key group integer Id. - - std::string groupName() const; - /// Returns the EC key group name. - - void save(const std::string& publicKeyFile, - const std::string& privateKeyFile = "", - const std::string& privateKeyPassphrase = "") const; - /// Exports the public and private keys to the given files. - /// - /// If an empty filename is specified, the corresponding key - /// is not exported. - - void save(std::ostream* pPublicKeyStream, - std::ostream* pPrivateKeyStream = 0, - const std::string& privateKeyPassphrase = "") const; - /// Exports the public and private key to the given streams. - /// - /// If a null pointer is passed for a stream, the corresponding - /// key is not exported. - - static std::string getCurveName(int nid = -1); - /// Returns elliptical curve name corresponding to - /// the given nid; if nid is not found, returns - /// empty string. - /// - /// If nid is -1, returns first curve name. - /// - /// If no curves are found, returns empty string; - - static int getCurveNID(std::string& name); - /// Returns the NID of the specified curve. - /// - /// If name is empty, returns the first curve NID - /// and updates the name accordingly. - - static bool hasCurve(const std::string& name); - /// Returns true if the named curve is found, - /// false otherwise. - -private: - void checkEC(const std::string& method, const std::string& func) const; - void freeEC(); - - EC_KEY* _pEC; -}; - - -// -// inlines -// -inline EC_KEY* ECKeyImpl::getECKey() +namespace Crypto { - return _pEC; + + + class X509Certificate; + class PKCS12Container; + + + class ECKeyImpl : public KeyPairImpl + /// Elliptic Curve key clas implementation. + { + public: + typedef Poco::AutoPtr Ptr; + typedef std::vector ByteVec; + + ECKeyImpl(const EVPPKey & key); + /// Constructs ECKeyImpl by extracting the EC key. + + ECKeyImpl(const X509Certificate & cert); + /// Constructs ECKeyImpl by extracting the EC public key from the given certificate. + + ECKeyImpl(const PKCS12Container & cert); + /// Constructs ECKeyImpl by extracting the EC private key from the given certificate. + + ECKeyImpl(int eccGroup); + /// Creates the ECKey of the specified group. Creates a new public/private keypair using the given parameters. + /// Can be used to sign data and verify signatures. + + ECKeyImpl(const std::string & publicKeyFile, const std::string & privateKeyFile, const std::string & privateKeyPassphrase); + /// Creates the ECKey, by reading public and private key from the given files and + /// using the given passphrase for the private key. Can only by used for signing if + /// a private key is available. + + ECKeyImpl(std::istream * pPublicKeyStream, std::istream * pPrivateKeyStream, const std::string & privateKeyPassphrase); + /// Creates the ECKey. Can only by used for signing if pPrivKey + /// is not null. If a private key file is specified, you don't need to + /// specify a public key file. OpenSSL will auto-create it from the private key. + + ~ECKeyImpl(); + /// Destroys the ECKeyImpl. + + EC_KEY * getECKey(); + /// Returns the OpenSSL EC key. + + const EC_KEY * getECKey() const; + /// Returns the OpenSSL EC key. + + int size() const; + /// Returns the EC key length in bits. + + int groupId() const; + /// Returns the EC key group integer Id. + + std::string groupName() const; + /// Returns the EC key group name. + + void save(const std::string & publicKeyFile, const std::string & privateKeyFile = "", const std::string & privateKeyPassphrase = "") + const; + /// Exports the public and private keys to the given files. + /// + /// If an empty filename is specified, the corresponding key + /// is not exported. + + void + save(std::ostream * pPublicKeyStream, std::ostream * pPrivateKeyStream = 0, const std::string & privateKeyPassphrase = "") const; + /// Exports the public and private key to the given streams. + /// + /// If a null pointer is passed for a stream, the corresponding + /// key is not exported. + + static std::string getCurveName(int nid = -1); + /// Returns elliptical curve name corresponding to + /// the given nid; if nid is not found, returns + /// empty string. + /// + /// If nid is -1, returns first curve name. + /// + /// If no curves are found, returns empty string; + + static int getCurveNID(std::string & name); + /// Returns the NID of the specified curve. + /// + /// If name is empty, returns the first curve NID + /// and updates the name accordingly. + + static bool hasCurve(const std::string & name); + /// Returns true if the named curve is found, + /// false otherwise. + + private: + void checkEC(const std::string & method, const std::string & func) const; + void freeEC(); + + EC_KEY * _pEC; + }; + + + // + // inlines + // + inline EC_KEY * ECKeyImpl::getECKey() + { + return _pEC; + } + + + inline const EC_KEY * ECKeyImpl::getECKey() const + { + return _pEC; + } + + + inline std::string ECKeyImpl::groupName() const + { + return OBJ_nid2sn(groupId()); + } + + + inline void + ECKeyImpl::save(const std::string & publicKeyFile, const std::string & privateKeyFile, const std::string & privateKeyPassphrase) const + { + EVPPKey(_pEC).save(publicKeyFile, privateKeyFile, privateKeyPassphrase); + } + + + inline void + ECKeyImpl::save(std::ostream * pPublicKeyStream, std::ostream * pPrivateKeyStream, const std::string & privateKeyPassphrase) const + { + EVPPKey(_pEC).save(pPublicKeyStream, pPrivateKeyStream, privateKeyPassphrase); + } + + } - - -inline const EC_KEY* ECKeyImpl::getECKey() const -{ - return _pEC; -} - - -inline std::string ECKeyImpl::groupName() const -{ - return OBJ_nid2sn(groupId()); -} - - -inline void ECKeyImpl::save(const std::string& publicKeyFile, - const std::string& privateKeyFile, - const std::string& privateKeyPassphrase) const -{ - EVPPKey(_pEC).save(publicKeyFile, privateKeyFile, privateKeyPassphrase); -} - - -inline void ECKeyImpl::save(std::ostream* pPublicKeyStream, - std::ostream* pPrivateKeyStream, - const std::string& privateKeyPassphrase) const -{ - EVPPKey(_pEC).save(pPublicKeyStream, pPrivateKeyStream, privateKeyPassphrase); -} - - -} } // namespace Poco::Crypto +} // namespace Poco::Crypto #endif // Crypto_ECKeyImplImpl_INCLUDED diff --git a/base/poco/Crypto/include/Poco/Crypto/EVPPKey.h b/base/poco/Crypto/include/Poco/Crypto/EVPPKey.h index 2b0062a3e13..acc79ec92b2 100644 --- a/base/poco/Crypto/include/Poco/Crypto/EVPPKey.h +++ b/base/poco/Crypto/include/Poco/Crypto/EVPPKey.h @@ -19,336 +19,351 @@ #define Crypto_EVPPKeyImpl_INCLUDED +#include +#include +#include +#include +#include +#include #include "Poco/Crypto/Crypto.h" #include "Poco/Crypto/CryptoException.h" #include "Poco/StreamCopier.h" -#include -#include -#include -#include -#include -#include -namespace Poco { -namespace Crypto { - - -class ECKey; -class RSAKey; - - -class Crypto_API EVPPKey - /// Utility class for conversion of native keys to EVP. - /// Currently, only RSA and EC keys are supported. +namespace Poco +{ +namespace Crypto { -public: - explicit EVPPKey(const std::string& ecCurveName); - /// Constructs EVPPKey from ECC curve name. - /// - /// Only EC keys can be wrapped by an EVPPKey - /// created using this constructor. - explicit EVPPKey(const char* ecCurveName); - /// Constructs EVPPKey from ECC curve name. - /// - /// Only EC keys can be wrapped by an EVPPKey - /// created using this constructor. - explicit EVPPKey(EVP_PKEY* pEVPPKey); - /// Constructs EVPPKey from EVP_PKEY pointer. - /// The content behind the supplied pointer is internally duplicated. + class ECKey; + class RSAKey; - template - explicit EVPPKey(K* pKey): _pEVPPKey(EVP_PKEY_new()) - /// Constructs EVPPKey from a "native" OpenSSL (RSA or EC_KEY), - /// or a Poco wrapper (RSAKey, ECKey) key pointer. - { - if (!_pEVPPKey) throw OpenSSLException(); - setKey(pKey); - } - EVPPKey(const std::string& publicKeyFile, const std::string& privateKeyFile, const std::string& privateKeyPassphrase = ""); - /// Creates the EVPPKey, by reading public and private key from the given files and - /// using the given passphrase for the private key. Can only by used for signing if - /// a private key is available. + class Crypto_API EVPPKey + /// Utility class for conversion of native keys to EVP. + /// Currently, only RSA and EC keys are supported. + { + public: + explicit EVPPKey(const std::string & ecCurveName); + /// Constructs EVPPKey from ECC curve name. + /// + /// Only EC keys can be wrapped by an EVPPKey + /// created using this constructor. - EVPPKey(std::istream* pPublicKeyStream, std::istream* pPrivateKeyStream, const std::string& privateKeyPassphrase = ""); - /// Creates the EVPPKey. Can only by used for signing if pPrivKey - /// is not null. If a private key file is specified, you don't need to - /// specify a public key file. OpenSSL will auto-create it from the private key. + explicit EVPPKey(const char * ecCurveName); + /// Constructs EVPPKey from ECC curve name. + /// + /// Only EC keys can be wrapped by an EVPPKey + /// created using this constructor. - EVPPKey(const EVPPKey& other); - /// Copy constructor. + explicit EVPPKey(EVP_PKEY * pEVPPKey); + /// Constructs EVPPKey from EVP_PKEY pointer. + /// The content behind the supplied pointer is internally duplicated. - EVPPKey& operator=(const EVPPKey& other); - /// Assignment operator. + template + explicit EVPPKey(K * pKey) : _pEVPPKey(EVP_PKEY_new()) + /// Constructs EVPPKey from a "native" OpenSSL (RSA or EC_KEY), + /// or a Poco wrapper (RSAKey, ECKey) key pointer. + { + if (!_pEVPPKey) + throw OpenSSLException(); + setKey(pKey); + } + + EVPPKey(const std::string & publicKeyFile, const std::string & privateKeyFile, const std::string & privateKeyPassphrase = ""); + /// Creates the EVPPKey, by reading public and private key from the given files and + /// using the given passphrase for the private key. Can only by used for signing if + /// a private key is available. + + EVPPKey(std::istream * pPublicKeyStream, std::istream * pPrivateKeyStream, const std::string & privateKeyPassphrase = ""); + /// Creates the EVPPKey. Can only by used for signing if pPrivKey + /// is not null. If a private key file is specified, you don't need to + /// specify a public key file. OpenSSL will auto-create it from the private key. + + EVPPKey(const EVPPKey & other); + /// Copy constructor. + + EVPPKey & operator=(const EVPPKey & other); + /// Assignment operator. #ifdef POCO_ENABLE_CPP11 - EVPPKey(EVPPKey&& other); - /// Move constructor. + EVPPKey(EVPPKey && other); + /// Move constructor. - EVPPKey& operator=(EVPPKey&& other); - /// Assignment move operator. + EVPPKey & operator=(EVPPKey && other); + /// Assignment move operator. #endif // POCO_ENABLE_CPP11 - ~EVPPKey(); - /// Destroys the EVPPKey. + ~EVPPKey(); + /// Destroys the EVPPKey. - bool operator == (const EVPPKey& other) const; - /// Comparison operator. - /// Returns true if public key components and parameters - /// of the other key are equal to this key. - /// - /// Works as expected when one key contains only public key, - /// while the other one contains private (thus also public) key. + bool operator==(const EVPPKey & other) const; + /// Comparison operator. + /// Returns true if public key components and parameters + /// of the other key are equal to this key. + /// + /// Works as expected when one key contains only public key, + /// while the other one contains private (thus also public) key. - bool operator != (const EVPPKey& other) const; - /// Comparison operator. - /// Returns true if public key components and parameters - /// of the other key are different from this key. - /// - /// Works as expected when one key contains only public key, - /// while the other one contains private (thus also public) key. + bool operator!=(const EVPPKey & other) const; + /// Comparison operator. + /// Returns true if public key components and parameters + /// of the other key are different from this key. + /// + /// Works as expected when one key contains only public key, + /// while the other one contains private (thus also public) key. - void save(const std::string& publicKeyFile, const std::string& privateKeyFile = "", const std::string& privateKeyPassphrase = "") const; - /// Exports the public and/or private keys to the given files. - /// - /// If an empty filename is specified, the corresponding key - /// is not exported. + void save(const std::string & publicKeyFile, const std::string & privateKeyFile = "", const std::string & privateKeyPassphrase = "") + const; + /// Exports the public and/or private keys to the given files. + /// + /// If an empty filename is specified, the corresponding key + /// is not exported. - void save(std::ostream* pPublicKeyStream, std::ostream* pPrivateKeyStream = 0, const std::string& privateKeyPassphrase = "") const; - /// Exports the public and/or private key to the given streams. - /// - /// If a null pointer is passed for a stream, the corresponding - /// key is not exported. + void + save(std::ostream * pPublicKeyStream, std::ostream * pPrivateKeyStream = 0, const std::string & privateKeyPassphrase = "") const; + /// Exports the public and/or private key to the given streams. + /// + /// If a null pointer is passed for a stream, the corresponding + /// key is not exported. - int type() const; - /// Returns the EVPPKey type NID. + int type() const; + /// Returns the EVPPKey type NID. - bool isSupported(int type) const; - /// Returns true if OpenSSL type is supported + bool isSupported(int type) const; + /// Returns true if OpenSSL type is supported - operator const EVP_PKEY*() const; - /// Returns const pointer to the OpenSSL EVP_PKEY structure. + operator const EVP_PKEY *() const; + /// Returns const pointer to the OpenSSL EVP_PKEY structure. - operator EVP_PKEY*(); - /// Returns pointer to the OpenSSL EVP_PKEY structure. + operator EVP_PKEY *(); + /// Returns pointer to the OpenSSL EVP_PKEY structure. - static EVP_PKEY* duplicate(const EVP_PKEY* pFromKey, EVP_PKEY** pToKey); - /// Duplicates pFromKey into *pToKey and returns - // the pointer to duplicated EVP_PKEY. + static EVP_PKEY * duplicate(const EVP_PKEY * pFromKey, EVP_PKEY ** pToKey); + /// Duplicates pFromKey into *pToKey and returns + // the pointer to duplicated EVP_PKEY. -private: - EVPPKey(); + private: + EVPPKey(); - static int type(const EVP_PKEY* pEVPPKey); - void newECKey(const char* group); - void duplicate(EVP_PKEY* pEVPPKey); + static int type(const EVP_PKEY * pEVPPKey); + void newECKey(const char * group); + void duplicate(EVP_PKEY * pEVPPKey); - void setKey(ECKey* pKey); - void setKey(RSAKey* pKey); - void setKey(EC_KEY* pKey); - void setKey(RSA* pKey); - static int passCB(char* buf, int size, int, void* pass); + void setKey(ECKey * pKey); + void setKey(RSAKey * pKey); + void setKey(EC_KEY * pKey); + void setKey(RSA * pKey); + static int passCB(char * buf, int size, int, void * pass); - typedef EVP_PKEY* (*PEM_read_FILE_Key_fn)(FILE*, EVP_PKEY**, pem_password_cb*, void*); - typedef EVP_PKEY* (*PEM_read_BIO_Key_fn)(BIO*, EVP_PKEY**, pem_password_cb*, void*); - typedef void* (*EVP_PKEY_get_Key_fn)(EVP_PKEY*); + typedef EVP_PKEY * (*PEM_read_FILE_Key_fn)(FILE *, EVP_PKEY **, pem_password_cb *, void *); + typedef EVP_PKEY * (*PEM_read_BIO_Key_fn)(BIO *, EVP_PKEY **, pem_password_cb *, void *); + typedef void * (*EVP_PKEY_get_Key_fn)(EVP_PKEY *); - // The following load*() functions are used by both native and EVP_PKEY type key - // loading from BIO/FILE. - // When used for EVP key loading, getFunc is null (ie. native key is not extracted - // from the loaded EVP_PKEY). - template - static bool loadKey(K** ppKey, - PEM_read_FILE_Key_fn readFunc, - F getFunc, - const std::string& keyFile, - const std::string& pass = "") - { - poco_assert_dbg (((typeid(K*) == typeid(RSA*) || typeid(K*) == typeid(EC_KEY*)) && getFunc) || - ((typeid(K*) == typeid(EVP_PKEY*)) && !getFunc)); - poco_check_ptr (ppKey); - poco_assert_dbg (!*ppKey); + // The following load*() functions are used by both native and EVP_PKEY type key + // loading from BIO/FILE. + // When used for EVP key loading, getFunc is null (ie. native key is not extracted + // from the loaded EVP_PKEY). + template + static bool + loadKey(K ** ppKey, PEM_read_FILE_Key_fn readFunc, F getFunc, const std::string & keyFile, const std::string & pass = "") + { + poco_assert_dbg( + ((typeid(K *) == typeid(RSA *) || typeid(K *) == typeid(EC_KEY *)) && getFunc) + || ((typeid(K *) == typeid(EVP_PKEY *)) && !getFunc)); + poco_check_ptr(ppKey); + poco_assert_dbg(!*ppKey); - FILE* pFile = 0; - if (!keyFile.empty()) - { - if (!getFunc) *ppKey = (K*)EVP_PKEY_new(); - EVP_PKEY* pKey = getFunc ? EVP_PKEY_new() : (EVP_PKEY*)*ppKey; - if (pKey) - { - pFile = fopen(keyFile.c_str(), "r"); - if (pFile) - { - pem_password_cb* pCB = pass.empty() ? (pem_password_cb*)0 : &passCB; - void* pPassword = pass.empty() ? (void*)0 : (void*)pass.c_str(); - if (readFunc(pFile, &pKey, pCB, pPassword)) - { - fclose(pFile); pFile = 0; - if(getFunc) - { - *ppKey = (K*)getFunc(pKey); - EVP_PKEY_free(pKey); - } - else - { - poco_assert_dbg (typeid(K*) == typeid(EVP_PKEY*)); - *ppKey = (K*)pKey; - } - if(!*ppKey) goto error; - return true; - } - goto error; - } - else - { - if (getFunc) EVP_PKEY_free(pKey); - throw IOException("ECKeyImpl, cannot open file", keyFile); - } - } - else goto error; - } - return false; + FILE * pFile = 0; + if (!keyFile.empty()) + { + if (!getFunc) + *ppKey = (K *)EVP_PKEY_new(); + EVP_PKEY * pKey = getFunc ? EVP_PKEY_new() : (EVP_PKEY *)*ppKey; + if (pKey) + { + pFile = fopen(keyFile.c_str(), "r"); + if (pFile) + { + pem_password_cb * pCB = pass.empty() ? (pem_password_cb *)0 : &passCB; + void * pPassword = pass.empty() ? (void *)0 : (void *)pass.c_str(); + if (readFunc(pFile, &pKey, pCB, pPassword)) + { + fclose(pFile); + pFile = 0; + if (getFunc) + { + *ppKey = (K *)getFunc(pKey); + EVP_PKEY_free(pKey); + } + else + { + poco_assert_dbg(typeid(K *) == typeid(EVP_PKEY *)); + *ppKey = (K *)pKey; + } + if (!*ppKey) + goto error; + return true; + } + goto error; + } + else + { + if (getFunc) + EVP_PKEY_free(pKey); + throw IOException("ECKeyImpl, cannot open file", keyFile); + } + } + else + goto error; + } + return false; - error: - if (pFile) fclose(pFile); - throw OpenSSLException("EVPKey::loadKey(string)"); - } + error: + if (pFile) + fclose(pFile); + throw OpenSSLException("EVPKey::loadKey(string)"); + } - template - static bool loadKey(K** ppKey, - PEM_read_BIO_Key_fn readFunc, - F getFunc, - std::istream* pIstr, - const std::string& pass = "") - { - poco_assert_dbg (((typeid(K*) == typeid(RSA*) || typeid(K*) == typeid(EC_KEY*)) && getFunc) || - ((typeid(K*) == typeid(EVP_PKEY*)) && !getFunc)); - poco_check_ptr(ppKey); - poco_assert_dbg(!*ppKey); + template + static bool loadKey(K ** ppKey, PEM_read_BIO_Key_fn readFunc, F getFunc, std::istream * pIstr, const std::string & pass = "") + { + poco_assert_dbg( + ((typeid(K *) == typeid(RSA *) || typeid(K *) == typeid(EC_KEY *)) && getFunc) + || ((typeid(K *) == typeid(EVP_PKEY *)) && !getFunc)); + poco_check_ptr(ppKey); + poco_assert_dbg(!*ppKey); - BIO* pBIO = 0; - if (pIstr) - { - std::ostringstream ostr; - Poco::StreamCopier::copyStream(*pIstr, ostr); - std::string key = ostr.str(); - pBIO = BIO_new_mem_buf(const_cast(key.data()), static_cast(key.size())); - if (pBIO) - { - if (!getFunc) *ppKey = (K*)EVP_PKEY_new(); - EVP_PKEY* pKey = getFunc ? EVP_PKEY_new() : (EVP_PKEY*)*ppKey; - if (pKey) - { - pem_password_cb* pCB = pass.empty() ? (pem_password_cb*)0 : &passCB; - void* pPassword = pass.empty() ? (void*)0 : (void*)pass.c_str(); - if (readFunc(pBIO, &pKey, pCB, pPassword)) - { - BIO_free(pBIO); pBIO = 0; - if (getFunc) - { - *ppKey = (K*)getFunc(pKey); - EVP_PKEY_free(pKey); - } - else - { - poco_assert_dbg (typeid(K*) == typeid(EVP_PKEY*)); - *ppKey = (K*)pKey; - } - if (!*ppKey) goto error; - return true; - } - if (getFunc) EVP_PKEY_free(pKey); - goto error; - } - else goto error; - } - else goto error; - } - return false; + BIO * pBIO = 0; + if (pIstr) + { + std::ostringstream ostr; + Poco::StreamCopier::copyStream(*pIstr, ostr); + std::string key = ostr.str(); + pBIO = BIO_new_mem_buf(const_cast(key.data()), static_cast(key.size())); + if (pBIO) + { + if (!getFunc) + *ppKey = (K *)EVP_PKEY_new(); + EVP_PKEY * pKey = getFunc ? EVP_PKEY_new() : (EVP_PKEY *)*ppKey; + if (pKey) + { + pem_password_cb * pCB = pass.empty() ? (pem_password_cb *)0 : &passCB; + void * pPassword = pass.empty() ? (void *)0 : (void *)pass.c_str(); + if (readFunc(pBIO, &pKey, pCB, pPassword)) + { + BIO_free(pBIO); + pBIO = 0; + if (getFunc) + { + *ppKey = (K *)getFunc(pKey); + EVP_PKEY_free(pKey); + } + else + { + poco_assert_dbg(typeid(K *) == typeid(EVP_PKEY *)); + *ppKey = (K *)pKey; + } + if (!*ppKey) + goto error; + return true; + } + if (getFunc) + EVP_PKEY_free(pKey); + goto error; + } + else + goto error; + } + else + goto error; + } + return false; - error: - if (pBIO) BIO_free(pBIO); - throw OpenSSLException("EVPKey::loadKey(stream)"); - } + error: + if (pBIO) + BIO_free(pBIO); + throw OpenSSLException("EVPKey::loadKey(stream)"); + } - EVP_PKEY* _pEVPPKey; + EVP_PKEY * _pEVPPKey; - friend class ECKeyImpl; - friend class RSAKeyImpl; -}; + friend class ECKeyImpl; + friend class RSAKeyImpl; + }; -// -// inlines -// + // + // inlines + // + + + inline bool EVPPKey::operator==(const EVPPKey & other) const + { + poco_check_ptr(other._pEVPPKey); + poco_check_ptr(_pEVPPKey); + return (1 == EVP_PKEY_cmp(_pEVPPKey, other._pEVPPKey)); + } + + + inline bool EVPPKey::operator!=(const EVPPKey & other) const + { + return !(other == *this); + } + + + inline int EVPPKey::type(const EVP_PKEY * pEVPPKey) + { + if (!pEVPPKey) + return NID_undef; + + return EVP_PKEY_type(EVP_PKEY_id(pEVPPKey)); + } + + + inline int EVPPKey::type() const + { + return type(_pEVPPKey); + } + + + inline bool EVPPKey::isSupported(int type) const + { + return type == EVP_PKEY_EC || type == EVP_PKEY_RSA; + } + + + inline EVPPKey::operator const EVP_PKEY *() const + { + return _pEVPPKey; + } + + + inline EVPPKey::operator EVP_PKEY *() + { + return _pEVPPKey; + } + + + inline void EVPPKey::setKey(EC_KEY * pKey) + { + if (!EVP_PKEY_set1_EC_KEY(_pEVPPKey, pKey)) + throw OpenSSLException(); + } + + + inline void EVPPKey::setKey(RSA * pKey) + { + if (!EVP_PKEY_set1_RSA(_pEVPPKey, pKey)) + throw OpenSSLException(); + } -inline bool EVPPKey::operator == (const EVPPKey& other) const -{ - poco_check_ptr (other._pEVPPKey); - poco_check_ptr (_pEVPPKey); - return (1 == EVP_PKEY_cmp(_pEVPPKey, other._pEVPPKey)); } - - -inline bool EVPPKey::operator != (const EVPPKey& other) const -{ - return !(other == *this); -} - - -inline int EVPPKey::type(const EVP_PKEY* pEVPPKey) -{ - if (!pEVPPKey) return NID_undef; - - return EVP_PKEY_type(EVP_PKEY_id(pEVPPKey)); -} - - -inline int EVPPKey::type() const -{ - return type(_pEVPPKey); -} - - -inline bool EVPPKey::isSupported(int type) const -{ - return type == EVP_PKEY_EC || type == EVP_PKEY_RSA; -} - - -inline EVPPKey::operator const EVP_PKEY*() const -{ - return _pEVPPKey; -} - - -inline EVPPKey::operator EVP_PKEY*() -{ - return _pEVPPKey; -} - - -inline void EVPPKey::setKey(EC_KEY* pKey) -{ - if (!EVP_PKEY_set1_EC_KEY(_pEVPPKey, pKey)) - throw OpenSSLException(); -} - - -inline void EVPPKey::setKey(RSA* pKey) -{ - if (!EVP_PKEY_set1_RSA(_pEVPPKey, pKey)) - throw OpenSSLException(); -} - - -} } // namespace Poco::Crypto +} // namespace Poco::Crypto #endif // Crypto_EVPPKeyImpl_INCLUDED diff --git a/base/poco/Crypto/include/Poco/Crypto/KeyPair.h b/base/poco/Crypto/include/Poco/Crypto/KeyPair.h index b9a705f8f1b..36adbec6a4d 100644 --- a/base/poco/Crypto/include/Poco/Crypto/KeyPair.h +++ b/base/poco/Crypto/include/Poco/Crypto/KeyPair.h @@ -23,111 +23,114 @@ #include "Poco/Crypto/KeyPairImpl.h" -namespace Poco { -namespace Crypto { - - -class X509Certificate; - - -class Crypto_API KeyPair - /// This is a parent class for classes storing a key pair, consisting - /// of private and public key. Storage of the private key is optional. - /// - /// If a private key is available, the KeyPair can be - /// used for decrypting data (encrypted with the public key) - /// or computing secure digital signatures. +namespace Poco { -public: - enum Type - { - KT_RSA = KeyPairImpl::KT_RSA_IMPL, - KT_EC = KeyPairImpl::KT_EC_IMPL - }; - - explicit KeyPair(KeyPairImpl::Ptr pKeyPairImpl = 0); - /// Extracts the RSA public key from the given certificate. - - virtual ~KeyPair(); - /// Destroys the KeyPair. - - virtual int size() const; - /// Returns the RSA modulus size. - - virtual void save(const std::string& publicKeyPairFile, - const std::string& privateKeyPairFile = "", - const std::string& privateKeyPairPassphrase = "") const; - /// Exports the public and private keys to the given files. - /// - /// If an empty filename is specified, the corresponding key - /// is not exported. - - virtual void save(std::ostream* pPublicKeyPairStream, - std::ostream* pPrivateKeyPairStream = 0, - const std::string& privateKeyPairPassphrase = "") const; - /// Exports the public and private key to the given streams. - /// - /// If a null pointer is passed for a stream, the corresponding - /// key is not exported. - - KeyPairImpl::Ptr impl() const; - /// Returns the impl object. - - const std::string& name() const; - /// Returns key pair name - - Type type() const; - /// Returns key pair type - -private: - KeyPairImpl::Ptr _pImpl; -}; - - -// -// inlines -// - -inline int KeyPair::size() const +namespace Crypto { - return _pImpl->size(); + + + class X509Certificate; + + + class Crypto_API KeyPair + /// This is a parent class for classes storing a key pair, consisting + /// of private and public key. Storage of the private key is optional. + /// + /// If a private key is available, the KeyPair can be + /// used for decrypting data (encrypted with the public key) + /// or computing secure digital signatures. + { + public: + enum Type + { + KT_RSA = KeyPairImpl::KT_RSA_IMPL, + KT_EC = KeyPairImpl::KT_EC_IMPL + }; + + explicit KeyPair(KeyPairImpl::Ptr pKeyPairImpl = 0); + /// Extracts the RSA public key from the given certificate. + + virtual ~KeyPair(); + /// Destroys the KeyPair. + + virtual int size() const; + /// Returns the RSA modulus size. + + virtual void save( + const std::string & publicKeyPairFile, + const std::string & privateKeyPairFile = "", + const std::string & privateKeyPairPassphrase = "") const; + /// Exports the public and private keys to the given files. + /// + /// If an empty filename is specified, the corresponding key + /// is not exported. + + virtual void save( + std::ostream * pPublicKeyPairStream, + std::ostream * pPrivateKeyPairStream = 0, + const std::string & privateKeyPairPassphrase = "") const; + /// Exports the public and private key to the given streams. + /// + /// If a null pointer is passed for a stream, the corresponding + /// key is not exported. + + KeyPairImpl::Ptr impl() const; + /// Returns the impl object. + + const std::string & name() const; + /// Returns key pair name + + Type type() const; + /// Returns key pair type + + private: + KeyPairImpl::Ptr _pImpl; + }; + + + // + // inlines + // + + inline int KeyPair::size() const + { + return _pImpl->size(); + } + + + inline void + KeyPair::save(const std::string & publicKeyFile, const std::string & privateKeyFile, const std::string & privateKeyPassphrase) const + { + _pImpl->save(publicKeyFile, privateKeyFile, privateKeyPassphrase); + } + + + inline void + KeyPair::save(std::ostream * pPublicKeyStream, std::ostream * pPrivateKeyStream, const std::string & privateKeyPassphrase) const + { + _pImpl->save(pPublicKeyStream, pPrivateKeyStream, privateKeyPassphrase); + } + + + inline const std::string & KeyPair::name() const + { + return _pImpl->name(); + } + + inline KeyPairImpl::Ptr KeyPair::impl() const + { + return _pImpl; + } + + + inline KeyPair::Type KeyPair::type() const + { + return (KeyPair::Type)impl()->type(); + } + + } - - -inline void KeyPair::save(const std::string& publicKeyFile, - const std::string& privateKeyFile, - const std::string& privateKeyPassphrase) const -{ - _pImpl->save(publicKeyFile, privateKeyFile, privateKeyPassphrase); -} - - -inline void KeyPair::save(std::ostream* pPublicKeyStream, - std::ostream* pPrivateKeyStream, - const std::string& privateKeyPassphrase) const -{ - _pImpl->save(pPublicKeyStream, pPrivateKeyStream, privateKeyPassphrase); -} - - -inline const std::string& KeyPair::name() const -{ - return _pImpl->name(); -} - -inline KeyPairImpl::Ptr KeyPair::impl() const -{ - return _pImpl; -} - - -inline KeyPair::Type KeyPair::type() const -{ - return (KeyPair::Type)impl()->type(); -} - - -} } // namespace Poco::Crypto +} // namespace Poco::Crypto #endif // Crypto_KeyPair_INCLUDED diff --git a/base/poco/Crypto/include/Poco/Crypto/KeyPairImpl.h b/base/poco/Crypto/include/Poco/Crypto/KeyPairImpl.h index e6320df044b..155efd20b9c 100644 --- a/base/poco/Crypto/include/Poco/Crypto/KeyPairImpl.h +++ b/base/poco/Crypto/include/Poco/Crypto/KeyPairImpl.h @@ -19,89 +19,92 @@ #define Crypto_KeyPairImplImpl_INCLUDED +#include +#include +#include "Poco/AutoPtr.h" #include "Poco/Crypto/Crypto.h" #include "Poco/Crypto/OpenSSLInitializer.h" #include "Poco/RefCountedObject.h" -#include "Poco/AutoPtr.h" -#include -#include -namespace Poco { -namespace Crypto { - - -class KeyPairImpl: public Poco::RefCountedObject - /// Class KeyPairImpl +namespace Poco { -public: - enum Type - { - KT_RSA_IMPL = 0, - KT_EC_IMPL - }; - - typedef Poco::AutoPtr Ptr; - typedef std::vector ByteVec; - - KeyPairImpl(const std::string& name, Type type); - /// Create KeyPairImpl with specified type and name. - - virtual ~KeyPairImpl(); - /// Destroys the KeyPairImpl. - - virtual int size() const = 0; - /// Returns the key size. - - virtual void save(const std::string& publicKeyFile, - const std::string& privateKeyFile = "", - const std::string& privateKeyPassphrase = "") const = 0; - /// Exports the public and private keys to the given files. - /// - /// If an empty filename is specified, the corresponding key - /// is not exported. - - virtual void save(std::ostream* pPublicKeyStream, - std::ostream* pPrivateKeyStream = 0, - const std::string& privateKeyPassphrase = "") const = 0; - /// Exports the public and private key to the given streams. - /// - /// If a null pointer is passed for a stream, the corresponding - /// key is not exported. - - const std::string& name() const; - /// Returns key pair name - - Type type() const; - /// Returns key pair type - -private: - KeyPairImpl(); - - std::string _name; - Type _type; - OpenSSLInitializer _openSSLInitializer; -}; - - -// -// inlines -// - - -inline const std::string& KeyPairImpl::name() const +namespace Crypto { - return _name; + + + class KeyPairImpl : public Poco::RefCountedObject + /// Class KeyPairImpl + { + public: + enum Type + { + KT_RSA_IMPL = 0, + KT_EC_IMPL + }; + + typedef Poco::AutoPtr Ptr; + typedef std::vector ByteVec; + + KeyPairImpl(const std::string & name, Type type); + /// Create KeyPairImpl with specified type and name. + + virtual ~KeyPairImpl(); + /// Destroys the KeyPairImpl. + + virtual int size() const = 0; + /// Returns the key size. + + virtual void save( + const std::string & publicKeyFile, + const std::string & privateKeyFile = "", + const std::string & privateKeyPassphrase = "") const = 0; + /// Exports the public and private keys to the given files. + /// + /// If an empty filename is specified, the corresponding key + /// is not exported. + + virtual void save( + std::ostream * pPublicKeyStream, std::ostream * pPrivateKeyStream = 0, const std::string & privateKeyPassphrase = "") const = 0; + /// Exports the public and private key to the given streams. + /// + /// If a null pointer is passed for a stream, the corresponding + /// key is not exported. + + const std::string & name() const; + /// Returns key pair name + + Type type() const; + /// Returns key pair type + + private: + KeyPairImpl(); + + std::string _name; + Type _type; + OpenSSLInitializer _openSSLInitializer; + }; + + + // + // inlines + // + + + inline const std::string & KeyPairImpl::name() const + { + return _name; + } + + + inline KeyPairImpl::Type KeyPairImpl::type() const + { + return _type; + } + + } - - -inline KeyPairImpl::Type KeyPairImpl::type() const -{ - return _type; -} - - -} } // namespace Poco::Crypto +} // namespace Poco::Crypto #endif // Crypto_KeyPairImplImpl_INCLUDED diff --git a/base/poco/Crypto/include/Poco/Crypto/OpenSSLInitializer.h b/base/poco/Crypto/include/Poco/Crypto/OpenSSLInitializer.h index ce822a69710..147cfaeefca 100644 --- a/base/poco/Crypto/include/Poco/Crypto/OpenSSLInitializer.h +++ b/base/poco/Crypto/include/Poco/Crypto/OpenSSLInitializer.h @@ -18,98 +18,100 @@ #define Crypto_OpenSSLInitializer_INCLUDED +#include +#include "Poco/AtomicCounter.h" #include "Poco/Crypto/Crypto.h" #include "Poco/Mutex.h" -#include "Poco/AtomicCounter.h" -#include #if defined(OPENSSL_FIPS) && OPENSSL_VERSION_NUMBER < 0x010001000L -#include +# include #endif -extern "C" +extern "C" { +struct CRYPTO_dynlock_value { - struct CRYPTO_dynlock_value - { - Poco::FastMutex _mutex; - }; -} - - -namespace Poco { -namespace Crypto { - - -class Crypto_API OpenSSLInitializer - /// Initializes the OpenSSL library. - /// - /// The class ensures the earliest initialization and the - /// latest shutdown of the OpenSSL library. -{ -public: - OpenSSLInitializer(); - /// Automatically initialize OpenSSL on startup. - - ~OpenSSLInitializer(); - /// Automatically shut down OpenSSL on exit. - - static void initialize(); - /// Initializes the OpenSSL machinery. - - static void uninitialize(); - /// Shuts down the OpenSSL machinery. - - static bool isFIPSEnabled(); - // Returns true if FIPS mode is enabled, false otherwise. - - static void enableFIPSMode(bool enabled); - // Enable or disable FIPS mode. If FIPS is not available, this method doesn't do anything. - -protected: - enum - { - SEEDSIZE = 256 - }; - - // OpenSSL multithreading support - static void lock(int mode, int n, const char* file, int line); - static unsigned long id(); - static struct CRYPTO_dynlock_value* dynlockCreate(const char* file, int line); - static void dynlock(int mode, struct CRYPTO_dynlock_value* lock, const char* file, int line); - static void dynlockDestroy(struct CRYPTO_dynlock_value* lock, const char* file, int line); - -private: - static Poco::FastMutex* _mutexes; - static Poco::AtomicCounter _rc; + Poco::FastMutex _mutex; }; +} -// -// inlines -// -inline bool OpenSSLInitializer::isFIPSEnabled() +namespace Poco { +namespace Crypto +{ + + + class Crypto_API OpenSSLInitializer + /// Initializes the OpenSSL library. + /// + /// The class ensures the earliest initialization and the + /// latest shutdown of the OpenSSL library. + { + public: + OpenSSLInitializer(); + /// Automatically initialize OpenSSL on startup. + + ~OpenSSLInitializer(); + /// Automatically shut down OpenSSL on exit. + + static void initialize(); + /// Initializes the OpenSSL machinery. + + static void uninitialize(); + /// Shuts down the OpenSSL machinery. + + static bool isFIPSEnabled(); + // Returns true if FIPS mode is enabled, false otherwise. + + static void enableFIPSMode(bool enabled); + // Enable or disable FIPS mode. If FIPS is not available, this method doesn't do anything. + + protected: + enum + { + SEEDSIZE = 256 + }; + + // OpenSSL multithreading support + static void lock(int mode, int n, const char * file, int line); + static unsigned long id(); + static struct CRYPTO_dynlock_value * dynlockCreate(const char * file, int line); + static void dynlock(int mode, struct CRYPTO_dynlock_value * lock, const char * file, int line); + static void dynlockDestroy(struct CRYPTO_dynlock_value * lock, const char * file, int line); + + private: + static Poco::FastMutex * _mutexes; + static Poco::AtomicCounter _rc; + }; + + + // + // inlines + // + inline bool OpenSSLInitializer::isFIPSEnabled() + { #ifdef OPENSSL_FIPS - return FIPS_mode() ? true : false; + return FIPS_mode() ? true : false; #else - return false; + return false; #endif -} + } #ifdef OPENSSL_FIPS -inline void OpenSSLInitializer::enableFIPSMode(bool enabled) -{ - FIPS_mode_set(enabled); -} + inline void OpenSSLInitializer::enableFIPSMode(bool enabled) + { + FIPS_mode_set(enabled); + } #else -inline void OpenSSLInitializer::enableFIPSMode(bool /*enabled*/) -{ -} + inline void OpenSSLInitializer::enableFIPSMode(bool /*enabled*/) + { + } #endif -} } // namespace Poco::Crypto +} +} // namespace Poco::Crypto #endif // Crypto_OpenSSLInitializer_INCLUDED diff --git a/base/poco/Crypto/include/Poco/Crypto/PKCS12Container.h b/base/poco/Crypto/include/Poco/Crypto/PKCS12Container.h index 63cc224d8cc..40baa496827 100644 --- a/base/poco/Crypto/include/Poco/Crypto/PKCS12Container.h +++ b/base/poco/Crypto/include/Poco/Crypto/PKCS12Container.h @@ -18,142 +18,145 @@ #define Crypto_PKCS12Container_INCLUDED +#include +#include +#include #include "Poco/Crypto/Crypto.h" +#include "Poco/Crypto/EVPPKey.h" #include "Poco/Crypto/OpenSSLInitializer.h" #include "Poco/Crypto/X509Certificate.h" -#include "Poco/Crypto/EVPPKey.h" #include "Poco/Path.h" -#include -#include -#include -namespace Poco { -namespace Crypto { - - -class Crypto_API PKCS12Container - /// This class implements PKCS#12 container functionality. +namespace Poco +{ +namespace Crypto { -public: - typedef X509Certificate::List CAList; - typedef std::vector CANameList; - explicit PKCS12Container(std::istream& istr, const std::string& password = ""); - /// Creates the PKCS12Container object from a stream. - explicit PKCS12Container(const std::string& path, const std::string& password = ""); - /// Creates the PKCS12Container object from a file. + class Crypto_API PKCS12Container + /// This class implements PKCS#12 container functionality. + { + public: + typedef X509Certificate::List CAList; + typedef std::vector CANameList; - PKCS12Container(const PKCS12Container& cont); - /// Copy constructor. + explicit PKCS12Container(std::istream & istr, const std::string & password = ""); + /// Creates the PKCS12Container object from a stream. - PKCS12Container& operator = (const PKCS12Container& cont); - /// Assignment operator. + explicit PKCS12Container(const std::string & path, const std::string & password = ""); + /// Creates the PKCS12Container object from a file. + + PKCS12Container(const PKCS12Container & cont); + /// Copy constructor. + + PKCS12Container & operator=(const PKCS12Container & cont); + /// Assignment operator. #ifdef POCO_ENABLE_CPP11 - PKCS12Container(PKCS12Container&& cont); - /// Move constructor. + PKCS12Container(PKCS12Container && cont); + /// Move constructor. - PKCS12Container& operator = (PKCS12Container&& cont); - /// Move assignment operator. + PKCS12Container & operator=(PKCS12Container && cont); + /// Move assignment operator. #endif // POCO_ENABLE_CPP11 - ~PKCS12Container(); - /// Destroys the PKCS12Container. + ~PKCS12Container(); + /// Destroys the PKCS12Container. - bool hasKey() const; - /// Returns true if container contains the key. + bool hasKey() const; + /// Returns true if container contains the key. - EVPPKey getKey() const; - /// Return key as openssl EVP_PKEY wrapper object. + EVPPKey getKey() const; + /// Return key as openssl EVP_PKEY wrapper object. - bool hasX509Certificate() const; - /// Returns true if container has X509 certificate. + bool hasX509Certificate() const; + /// Returns true if container has X509 certificate. - const X509Certificate& getX509Certificate() const; - /// Returns the X509 certificate. - /// Throws NotFoundException if there is no certificate. + const X509Certificate & getX509Certificate() const; + /// Returns the X509 certificate. + /// Throws NotFoundException if there is no certificate. - const CAList& getCACerts() const; - /// Returns the list of CA certificates in this container. + const CAList & getCACerts() const; + /// Returns the list of CA certificates in this container. - const std::string& getFriendlyName() const; - /// Returns the friendly name of the certificate bag. + const std::string & getFriendlyName() const; + /// Returns the friendly name of the certificate bag. - const CANameList& getFriendlyNamesCA() const; - /// Returns a list of CA certificates friendly names. + const CANameList & getFriendlyNamesCA() const; + /// Returns a list of CA certificates friendly names. -private: - void load(PKCS12* pPKCS12, const std::string& password = ""); - std::string extractFriendlyName(X509* pCert); + private: + void load(PKCS12 * pPKCS12, const std::string & password = ""); + std::string extractFriendlyName(X509 * pCert); #ifdef POCO_ENABLE_CPP11 - typedef std::unique_ptr CertPtr; + typedef std::unique_ptr CertPtr; #else - typedef std::auto_ptr CertPtr; + typedef std::auto_ptr CertPtr; #endif // #ifdef POCO_ENABLE_CPP11 - OpenSSLInitializer _openSSLInitializer; - EVP_PKEY* _pKey; - CertPtr _pX509Cert; - CAList _caCertList; - CANameList _caCertNames; - std::string _pkcsFriendlyName; -}; + OpenSSLInitializer _openSSLInitializer; + EVP_PKEY * _pKey; + CertPtr _pX509Cert; + CAList _caCertList; + CANameList _caCertNames; + std::string _pkcsFriendlyName; + }; -// -// inlines -// + // + // inlines + // + + inline bool PKCS12Container::hasX509Certificate() const + { + return _pX509Cert.get() != 0; + } + + + inline const X509Certificate & PKCS12Container::getX509Certificate() const + { + if (!hasX509Certificate()) + throw NotFoundException("PKCS12Container X509 certificate"); + return *_pX509Cert; + } + + + inline const std::string & PKCS12Container::getFriendlyName() const + { + return _pkcsFriendlyName; + } + + + inline const PKCS12Container::CAList & PKCS12Container::getCACerts() const + { + return _caCertList; + } + + + inline const PKCS12Container::CANameList & PKCS12Container::getFriendlyNamesCA() const + { + return _caCertNames; + } + + + inline bool PKCS12Container::hasKey() const + { + return _pKey != 0; + } + + + inline EVPPKey PKCS12Container::getKey() const + { + return EVPPKey(_pKey); + } + -inline bool PKCS12Container::hasX509Certificate() const -{ - return _pX509Cert.get() != 0; } - - -inline const X509Certificate& PKCS12Container::getX509Certificate() const -{ - if (!hasX509Certificate()) - throw NotFoundException("PKCS12Container X509 certificate"); - return *_pX509Cert; -} - - -inline const std::string& PKCS12Container::getFriendlyName() const -{ - return _pkcsFriendlyName; -} - - -inline const PKCS12Container::CAList& PKCS12Container::getCACerts() const -{ - return _caCertList; -} - - -inline const PKCS12Container::CANameList& PKCS12Container::getFriendlyNamesCA() const -{ - return _caCertNames; -} - - -inline bool PKCS12Container::hasKey() const -{ - return _pKey != 0; -} - - -inline EVPPKey PKCS12Container::getKey() const -{ - return EVPPKey(_pKey); -} - - -} } // namespace Poco::Crypto +} // namespace Poco::Crypto #endif // Crypto_PKCS12Container_INCLUDED diff --git a/base/poco/Crypto/include/Poco/Crypto/RSACipherImpl.h b/base/poco/Crypto/include/Poco/Crypto/RSACipherImpl.h index 2ebc38e3b55..c0920b4099a 100644 --- a/base/poco/Crypto/include/Poco/Crypto/RSACipherImpl.h +++ b/base/poco/Crypto/include/Poco/Crypto/RSACipherImpl.h @@ -18,60 +18,63 @@ #define Crypto_RSACipherImpl_INCLUDED -#include "Poco/Crypto/Crypto.h" -#include "Poco/Crypto/Cipher.h" -#include "Poco/Crypto/RSAKey.h" -#include "Poco/Crypto/OpenSSLInitializer.h" #include +#include "Poco/Crypto/Cipher.h" +#include "Poco/Crypto/Crypto.h" +#include "Poco/Crypto/OpenSSLInitializer.h" +#include "Poco/Crypto/RSAKey.h" -namespace Poco { -namespace Crypto { - - -class RSACipherImpl: public Cipher - /// An implementation of the Cipher class for - /// asymmetric (public-private key) encryption - /// based on the the RSA algorithm in OpenSSL's - /// crypto library. - /// - /// Encryption is using the public key, decryption - /// requires the private key. +namespace Poco { -public: - RSACipherImpl(const RSAKey& key, RSAPaddingMode paddingMode); - /// Creates a new RSACipherImpl object for the given RSAKey - /// and using the given padding mode. - - virtual ~RSACipherImpl(); - /// Destroys the RSACipherImpl. - - const std::string& name() const; - /// Returns the name of the Cipher. - - CryptoTransform* createEncryptor(); - /// Creates an encryptor object. - - CryptoTransform* createDecryptor(); - /// Creates a decryptor object. - -private: - RSAKey _key; - RSAPaddingMode _paddingMode; - OpenSSLInitializer _openSSLInitializer; -}; - - -// -// Inlines -// -inline const std::string& RSACipherImpl::name() const +namespace Crypto { - return _key.name(); + + + class RSACipherImpl : public Cipher + /// An implementation of the Cipher class for + /// asymmetric (public-private key) encryption + /// based on the the RSA algorithm in OpenSSL's + /// crypto library. + /// + /// Encryption is using the public key, decryption + /// requires the private key. + { + public: + RSACipherImpl(const RSAKey & key, RSAPaddingMode paddingMode); + /// Creates a new RSACipherImpl object for the given RSAKey + /// and using the given padding mode. + + virtual ~RSACipherImpl(); + /// Destroys the RSACipherImpl. + + const std::string & name() const; + /// Returns the name of the Cipher. + + CryptoTransform * createEncryptor(); + /// Creates an encryptor object. + + CryptoTransform * createDecryptor(); + /// Creates a decryptor object. + + private: + RSAKey _key; + RSAPaddingMode _paddingMode; + OpenSSLInitializer _openSSLInitializer; + }; + + + // + // Inlines + // + inline const std::string & RSACipherImpl::name() const + { + return _key.name(); + } + + } - - -} } // namespace Poco::Crypto +} // namespace Poco::Crypto #endif // Crypto_RSACipherImpl_INCLUDED diff --git a/base/poco/Crypto/include/Poco/Crypto/RSADigestEngine.h b/base/poco/Crypto/include/Poco/Crypto/RSADigestEngine.h index 7c4d3860508..980fae1f0f0 100644 --- a/base/poco/Crypto/include/Poco/Crypto/RSADigestEngine.h +++ b/base/poco/Crypto/include/Poco/Crypto/RSADigestEngine.h @@ -18,94 +18,97 @@ #define Crypto_RSADigestEngine_INCLUDED -#include "Poco/Crypto/Crypto.h" -#include "Poco/Crypto/RSAKey.h" -#include "Poco/DigestEngine.h" -#include "Poco/Crypto/DigestEngine.h" #include #include +#include "Poco/Crypto/Crypto.h" +#include "Poco/Crypto/DigestEngine.h" +#include "Poco/Crypto/RSAKey.h" +#include "Poco/DigestEngine.h" -namespace Poco { -namespace Crypto { - - -class Crypto_API RSADigestEngine: public Poco::DigestEngine - /// This class implements a Poco::DigestEngine that can be - /// used to compute a secure digital signature. - /// - /// First another Poco::Crypto::DigestEngine is created and - /// used to compute a cryptographic hash of the data to be - /// signed. Then, the hash value is encrypted, using - /// the RSA private key. - /// - /// To verify a signature, pass it to the verify() - /// member function. It will decrypt the signature - /// using the RSA public key and compare the resulting - /// hash with the actual hash of the data. +namespace Poco +{ +namespace Crypto { -public: - enum DigestType - { - DIGEST_MD5, - DIGEST_SHA1 - }; - - //@ deprecated - RSADigestEngine(const RSAKey& key, DigestType digestType = DIGEST_SHA1); - /// Creates the RSADigestEngine with the given RSA key, - /// using the MD5 or SHA-1 hash algorithm. - /// Kept for backward compatibility - - RSADigestEngine(const RSAKey& key, const std::string &name); - /// Creates the RSADigestEngine with the given RSA key, - /// using the hash algorithm with the given name - /// (e.g., "MD5", "SHA1", "SHA256", "SHA512", etc.). - /// See the OpenSSL documentation for a list of supported digest algorithms. - /// - /// Throws a Poco::NotFoundException if no algorithm with the given name exists. - - ~RSADigestEngine(); - /// Destroys the RSADigestEngine. - - std::size_t digestLength() const; - /// Returns the length of the digest in bytes. - - void reset(); - /// Resets the engine so that a new - /// digest can be computed. - - const DigestEngine::Digest& digest(); - /// Finishes the computation of the digest - /// (the first time it's called) and - /// returns the message digest. - /// - /// Can be called multiple times. - - const DigestEngine::Digest& signature(); - /// Signs the digest using the RSA algorithm - /// and the private key (the first time it's - /// called) and returns the result. - /// - /// Can be called multiple times. - - bool verify(const DigestEngine::Digest& signature); - /// Verifies the data against the signature. - /// - /// Returns true if the signature can be verified, false otherwise. - -protected: - void updateImpl(const void* data, std::size_t length); - -private: - RSAKey _key; - Poco::Crypto::DigestEngine _engine; - Poco::DigestEngine::Digest _digest; - Poco::DigestEngine::Digest _signature; -}; -} } // namespace Poco::Crypto + class Crypto_API RSADigestEngine : public Poco::DigestEngine + /// This class implements a Poco::DigestEngine that can be + /// used to compute a secure digital signature. + /// + /// First another Poco::Crypto::DigestEngine is created and + /// used to compute a cryptographic hash of the data to be + /// signed. Then, the hash value is encrypted, using + /// the RSA private key. + /// + /// To verify a signature, pass it to the verify() + /// member function. It will decrypt the signature + /// using the RSA public key and compare the resulting + /// hash with the actual hash of the data. + { + public: + enum DigestType + { + DIGEST_MD5, + DIGEST_SHA1 + }; + + //@ deprecated + RSADigestEngine(const RSAKey & key, DigestType digestType = DIGEST_SHA1); + /// Creates the RSADigestEngine with the given RSA key, + /// using the MD5 or SHA-1 hash algorithm. + /// Kept for backward compatibility + + RSADigestEngine(const RSAKey & key, const std::string & name); + /// Creates the RSADigestEngine with the given RSA key, + /// using the hash algorithm with the given name + /// (e.g., "MD5", "SHA1", "SHA256", "SHA512", etc.). + /// See the OpenSSL documentation for a list of supported digest algorithms. + /// + /// Throws a Poco::NotFoundException if no algorithm with the given name exists. + + ~RSADigestEngine(); + /// Destroys the RSADigestEngine. + + std::size_t digestLength() const; + /// Returns the length of the digest in bytes. + + void reset(); + /// Resets the engine so that a new + /// digest can be computed. + + const DigestEngine::Digest & digest(); + /// Finishes the computation of the digest + /// (the first time it's called) and + /// returns the message digest. + /// + /// Can be called multiple times. + + const DigestEngine::Digest & signature(); + /// Signs the digest using the RSA algorithm + /// and the private key (the first time it's + /// called) and returns the result. + /// + /// Can be called multiple times. + + bool verify(const DigestEngine::Digest & signature); + /// Verifies the data against the signature. + /// + /// Returns true if the signature can be verified, false otherwise. + + protected: + void updateImpl(const void * data, std::size_t length); + + private: + RSAKey _key; + Poco::Crypto::DigestEngine _engine; + Poco::DigestEngine::Digest _digest; + Poco::DigestEngine::Digest _signature; + }; + + +} +} // namespace Poco::Crypto #endif // Crypto_RSADigestEngine_INCLUDED diff --git a/base/poco/Crypto/include/Poco/Crypto/RSAKey.h b/base/poco/Crypto/include/Poco/Crypto/RSAKey.h index ad9163ed42f..47a01e15746 100644 --- a/base/poco/Crypto/include/Poco/Crypto/RSAKey.h +++ b/base/poco/Crypto/include/Poco/Crypto/RSAKey.h @@ -23,103 +23,102 @@ #include "Poco/Crypto/RSAKeyImpl.h" -namespace Poco { -namespace Crypto { - - -class X509Certificate; -class PKCS12Container; - - -class Crypto_API RSAKey : public KeyPair - /// This class stores an RSA key pair, consisting - /// of private and public key. Storage of the private - /// key is optional. - /// - /// If a private key is available, the RSAKey can be - /// used for decrypting data (encrypted with the public key) - /// or computing secure digital signatures. +namespace Poco { -public: - enum KeyLength - { - KL_512 = 512, - KL_1024 = 1024, - KL_2048 = 2048, - KL_4096 = 4096 - }; - - enum Exponent - { - EXP_SMALL = 0, - EXP_LARGE - }; - - RSAKey(const EVPPKey& key); - /// Constructs ECKeyImpl by extracting the EC key. - - RSAKey(const X509Certificate& cert); - /// Extracts the RSA public key from the given certificate. - - RSAKey(const PKCS12Container& cert); - /// Extracts the RSA private key from the given certificate. - - RSAKey(KeyLength keyLength, Exponent exp); - /// Creates the RSAKey. Creates a new public/private keypair using the given parameters. - /// Can be used to sign data and verify signatures. - - RSAKey(const std::string& publicKeyFile, - const std::string& privateKeyFile = "", - const std::string& privateKeyPassphrase = ""); - /// Creates the RSAKey, by reading public and private key from the given files and - /// using the given passphrase for the private key. - /// - /// Cannot be used for signing or decryption unless a private key is available. - /// - /// If a private key is specified, you don't need to specify a public key file. - /// OpenSSL will auto-create the public key from the private key. - - RSAKey(std::istream* pPublicKeyStream, - std::istream* pPrivateKeyStream = 0, - const std::string& privateKeyPassphrase = ""); - /// Creates the RSAKey, by reading public and private key from the given streams and - /// using the given passphrase for the private key. - /// - /// Cannot be used for signing or decryption unless a private key is available. - /// - /// If a private key is specified, you don't need to specify a public key file. - /// OpenSSL will auto-create the public key from the private key. - - ~RSAKey(); - /// Destroys the RSAKey. - - RSAKeyImpl::ByteVec modulus() const; - /// Returns the RSA modulus. - - RSAKeyImpl::ByteVec encryptionExponent() const; - /// Returns the RSA encryption exponent. - - RSAKeyImpl::ByteVec decryptionExponent() const; - /// Returns the RSA decryption exponent. - - RSAKeyImpl::Ptr impl() const; - /// Returns the impl object. - -private: - RSAKeyImpl::Ptr _pImpl; -}; - - -// -// inlines -// -inline RSAKeyImpl::Ptr RSAKey::impl() const +namespace Crypto { - return _pImpl; + + + class X509Certificate; + class PKCS12Container; + + + class Crypto_API RSAKey : public KeyPair + /// This class stores an RSA key pair, consisting + /// of private and public key. Storage of the private + /// key is optional. + /// + /// If a private key is available, the RSAKey can be + /// used for decrypting data (encrypted with the public key) + /// or computing secure digital signatures. + { + public: + enum KeyLength + { + KL_512 = 512, + KL_1024 = 1024, + KL_2048 = 2048, + KL_4096 = 4096 + }; + + enum Exponent + { + EXP_SMALL = 0, + EXP_LARGE + }; + + RSAKey(const EVPPKey & key); + /// Constructs ECKeyImpl by extracting the EC key. + + RSAKey(const X509Certificate & cert); + /// Extracts the RSA public key from the given certificate. + + RSAKey(const PKCS12Container & cert); + /// Extracts the RSA private key from the given certificate. + + RSAKey(KeyLength keyLength, Exponent exp); + /// Creates the RSAKey. Creates a new public/private keypair using the given parameters. + /// Can be used to sign data and verify signatures. + + RSAKey(const std::string & publicKeyFile, const std::string & privateKeyFile = "", const std::string & privateKeyPassphrase = ""); + /// Creates the RSAKey, by reading public and private key from the given files and + /// using the given passphrase for the private key. + /// + /// Cannot be used for signing or decryption unless a private key is available. + /// + /// If a private key is specified, you don't need to specify a public key file. + /// OpenSSL will auto-create the public key from the private key. + + RSAKey(std::istream * pPublicKeyStream, std::istream * pPrivateKeyStream = 0, const std::string & privateKeyPassphrase = ""); + /// Creates the RSAKey, by reading public and private key from the given streams and + /// using the given passphrase for the private key. + /// + /// Cannot be used for signing or decryption unless a private key is available. + /// + /// If a private key is specified, you don't need to specify a public key file. + /// OpenSSL will auto-create the public key from the private key. + + ~RSAKey(); + /// Destroys the RSAKey. + + RSAKeyImpl::ByteVec modulus() const; + /// Returns the RSA modulus. + + RSAKeyImpl::ByteVec encryptionExponent() const; + /// Returns the RSA encryption exponent. + + RSAKeyImpl::ByteVec decryptionExponent() const; + /// Returns the RSA decryption exponent. + + RSAKeyImpl::Ptr impl() const; + /// Returns the impl object. + + private: + RSAKeyImpl::Ptr _pImpl; + }; + + + // + // inlines + // + inline RSAKeyImpl::Ptr RSAKey::impl() const + { + return _pImpl; + } + + } - - -} } // namespace Poco::Crypto +} // namespace Poco::Crypto #endif // Crypto_RSAKey_INCLUDED \ No newline at end of file diff --git a/base/poco/Crypto/include/Poco/Crypto/RSAKeyImpl.h b/base/poco/Crypto/include/Poco/Crypto/RSAKeyImpl.h index 035881636b2..4ccbb324c06 100644 --- a/base/poco/Crypto/include/Poco/Crypto/RSAKeyImpl.h +++ b/base/poco/Crypto/include/Poco/Crypto/RSAKeyImpl.h @@ -18,15 +18,15 @@ #define Crypto_RSAKeyImplImpl_INCLUDED +#include +#include +#include +#include "Poco/AutoPtr.h" #include "Poco/Crypto/Crypto.h" #include "Poco/Crypto/EVPPKey.h" #include "Poco/Crypto/KeyPairImpl.h" #include "Poco/Crypto/OpenSSLInitializer.h" #include "Poco/RefCountedObject.h" -#include "Poco/AutoPtr.h" -#include -#include -#include struct bignum_st; @@ -35,107 +35,108 @@ typedef struct bignum_st BIGNUM; typedef struct rsa_st RSA; -namespace Poco { -namespace Crypto { - - -class X509Certificate; -class PKCS12Container; - - -class RSAKeyImpl: public KeyPairImpl - /// class RSAKeyImpl +namespace Poco { -public: - typedef Poco::AutoPtr Ptr; - typedef std::vector ByteVec; - - RSAKeyImpl(const EVPPKey& key); - /// Constructs ECKeyImpl by extracting the EC key. - - RSAKeyImpl(const X509Certificate& cert); - /// Extracts the RSA public key from the given certificate. - - RSAKeyImpl(const PKCS12Container& cert); - /// Extracts the EC private key from the given certificate. - - RSAKeyImpl(int keyLength, unsigned long exponent); - /// Creates the RSAKey. Creates a new public/private keypair using the given parameters. - /// Can be used to sign data and verify signatures. - - RSAKeyImpl(const std::string& publicKeyFile, const std::string& privateKeyFile, const std::string& privateKeyPassphrase); - /// Creates the RSAKey, by reading public and private key from the given files and - /// using the given passphrase for the private key. Can only by used for signing if - /// a private key is available. - - RSAKeyImpl(std::istream* pPublicKeyStream, std::istream* pPrivateKeyStream, const std::string& privateKeyPassphrase); - /// Creates the RSAKey. Can only by used for signing if pPrivKey - /// is not null. If a private key file is specified, you don't need to - /// specify a public key file. OpenSSL will auto-create it from the private key. - - ~RSAKeyImpl(); - /// Destroys the RSAKeyImpl. - - RSA* getRSA(); - /// Returns the OpenSSL RSA object. - - const RSA* getRSA() const; - /// Returns the OpenSSL RSA object. - - int size() const; - /// Returns the RSA modulus size. - - ByteVec modulus() const; - /// Returns the RSA modulus. - - ByteVec encryptionExponent() const; - /// Returns the RSA encryption exponent. - - ByteVec decryptionExponent() const; - /// Returns the RSA decryption exponent. - - void save(const std::string& publicKeyFile, - const std::string& privateKeyFile = "", - const std::string& privateKeyPassphrase = "") const; - /// Exports the public and private keys to the given files. - /// - /// If an empty filename is specified, the corresponding key - /// is not exported. - - void save(std::ostream* pPublicKeyStream, - std::ostream* pPrivateKeyStream = 0, - const std::string& privateKeyPassphrase = "") const; - /// Exports the public and private key to the given streams. - /// - /// If a null pointer is passed for a stream, the corresponding - /// key is not exported. - -private: - RSAKeyImpl(); - - void freeRSA(); - static ByteVec convertToByteVec(const BIGNUM* bn); - - RSA* _pRSA; -}; - - -// -// inlines -// -inline RSA* RSAKeyImpl::getRSA() +namespace Crypto { - return _pRSA; + + + class X509Certificate; + class PKCS12Container; + + + class RSAKeyImpl : public KeyPairImpl + /// class RSAKeyImpl + { + public: + typedef Poco::AutoPtr Ptr; + typedef std::vector ByteVec; + + RSAKeyImpl(const EVPPKey & key); + /// Constructs ECKeyImpl by extracting the EC key. + + RSAKeyImpl(const X509Certificate & cert); + /// Extracts the RSA public key from the given certificate. + + RSAKeyImpl(const PKCS12Container & cert); + /// Extracts the EC private key from the given certificate. + + RSAKeyImpl(int keyLength, unsigned long exponent); + /// Creates the RSAKey. Creates a new public/private keypair using the given parameters. + /// Can be used to sign data and verify signatures. + + RSAKeyImpl(const std::string & publicKeyFile, const std::string & privateKeyFile, const std::string & privateKeyPassphrase); + /// Creates the RSAKey, by reading public and private key from the given files and + /// using the given passphrase for the private key. Can only by used for signing if + /// a private key is available. + + RSAKeyImpl(std::istream * pPublicKeyStream, std::istream * pPrivateKeyStream, const std::string & privateKeyPassphrase); + /// Creates the RSAKey. Can only by used for signing if pPrivKey + /// is not null. If a private key file is specified, you don't need to + /// specify a public key file. OpenSSL will auto-create it from the private key. + + ~RSAKeyImpl(); + /// Destroys the RSAKeyImpl. + + RSA * getRSA(); + /// Returns the OpenSSL RSA object. + + const RSA * getRSA() const; + /// Returns the OpenSSL RSA object. + + int size() const; + /// Returns the RSA modulus size. + + ByteVec modulus() const; + /// Returns the RSA modulus. + + ByteVec encryptionExponent() const; + /// Returns the RSA encryption exponent. + + ByteVec decryptionExponent() const; + /// Returns the RSA decryption exponent. + + void save(const std::string & publicKeyFile, const std::string & privateKeyFile = "", const std::string & privateKeyPassphrase = "") + const; + /// Exports the public and private keys to the given files. + /// + /// If an empty filename is specified, the corresponding key + /// is not exported. + + void + save(std::ostream * pPublicKeyStream, std::ostream * pPrivateKeyStream = 0, const std::string & privateKeyPassphrase = "") const; + /// Exports the public and private key to the given streams. + /// + /// If a null pointer is passed for a stream, the corresponding + /// key is not exported. + + private: + RSAKeyImpl(); + + void freeRSA(); + static ByteVec convertToByteVec(const BIGNUM * bn); + + RSA * _pRSA; + }; + + + // + // inlines + // + inline RSA * RSAKeyImpl::getRSA() + { + return _pRSA; + } + + + inline const RSA * RSAKeyImpl::getRSA() const + { + return _pRSA; + } + + } - - -inline const RSA* RSAKeyImpl::getRSA() const -{ - return _pRSA; -} - - -} } // namespace Poco::Crypto +} // namespace Poco::Crypto #endif // Crypto_RSAKeyImplImpl_INCLUDED \ No newline at end of file diff --git a/base/poco/Crypto/include/Poco/Crypto/X509Certificate.h b/base/poco/Crypto/include/Poco/Crypto/X509Certificate.h index ccdab1ce37e..30147623035 100644 --- a/base/poco/Crypto/include/Poco/Crypto/X509Certificate.h +++ b/base/poco/Crypto/include/Poco/Crypto/X509Certificate.h @@ -18,228 +18,231 @@ #define Crypto_X509Certificate_INCLUDED +#include +#include +#include +#include #include "Poco/Crypto/Crypto.h" #include "Poco/Crypto/OpenSSLInitializer.h" #include "Poco/DateTime.h" #include "Poco/SharedPtr.h" -#include -#include -#include -#include -namespace Poco { -namespace Crypto { - - -class Crypto_API X509Certificate - /// This class represents a X509 Certificate. +namespace Poco { -public: - typedef std::vector List; - - enum NID - /// Name identifier for extracting information from - /// a certificate subject's or issuer's distinguished name. - { - NID_COMMON_NAME = 13, - NID_COUNTRY = 14, - NID_LOCALITY_NAME = 15, - NID_STATE_OR_PROVINCE = 16, - NID_ORGANIZATION_NAME = 17, - NID_ORGANIZATION_UNIT_NAME = 18, - NID_PKCS9_EMAIL_ADDRESS = 48, - NID_SERIAL_NUMBER = 105 - }; - - explicit X509Certificate(std::istream& istr); - /// Creates the X509Certificate object by reading - /// a certificate in PEM format from a stream. - - explicit X509Certificate(const std::string& path); - /// Creates the X509Certificate object by reading - /// a certificate in PEM format from a file. - - explicit X509Certificate(X509* pCert); - /// Creates the X509Certificate from an existing - /// OpenSSL certificate. Ownership is taken of - /// the certificate. - - X509Certificate(X509* pCert, bool shared); - /// Creates the X509Certificate from an existing - /// OpenSSL certificate. Ownership is taken of - /// the certificate. If shared is true, the - /// certificate's reference count is incremented. - - X509Certificate(const X509Certificate& cert); - /// Creates the certificate by copying another one. - - X509Certificate& operator = (const X509Certificate& cert); - /// Assigns a certificate. - - void swap(X509Certificate& cert); - /// Exchanges the certificate with another one. - - ~X509Certificate(); - /// Destroys the X509Certificate. - - long version() const; - /// Returns the version of the certificate. - - const std::string& serialNumber() const; - /// Returns the certificate serial number as a - /// string in decimal encoding. - - const std::string& issuerName() const; - /// Returns the certificate issuer's distinguished name. - - std::string issuerName(NID nid) const; - /// Extracts the information specified by the given - /// NID (name identifier) from the certificate issuer's - /// distinguished name. - - const std::string& subjectName() const; - /// Returns the certificate subject's distinguished name. - - std::string subjectName(NID nid) const; - /// Extracts the information specified by the given - /// NID (name identifier) from the certificate subject's - /// distinguished name. - - std::string commonName() const; - /// Returns the common name stored in the certificate - /// subject's distinguished name. - - void extractNames(std::string& commonName, std::set& domainNames) const; - /// Extracts the common name and the alias domain names from the - /// certificate. - - Poco::DateTime validFrom() const; - /// Returns the date and time the certificate is valid from. - - Poco::DateTime expiresOn() const; - /// Returns the date and time the certificate expires. - - void save(std::ostream& stream) const; - /// Writes the certificate to the given stream. - /// The certificate is written in PEM format. - - void save(const std::string& path) const; - /// Writes the certificate to the file given by path. - /// The certificate is written in PEM format. - - bool issuedBy(const X509Certificate& issuerCertificate) const; - /// Checks whether the certificate has been issued by - /// the issuer given by issuerCertificate. This can be - /// used to validate a certificate chain. - /// - /// Verifies if the certificate has been signed with the - /// issuer's private key, using the public key from the issuer - /// certificate. - /// - /// Returns true if verification against the issuer certificate - /// was successful, false otherwise. - - bool equals(const X509Certificate& otherCertificate) const; - /// Checks whether the certificate is equal to - /// the other certificate, by comparing the hashes - /// of both certificates. - /// - /// Returns true if both certificates are identical, - /// otherwise false. - - const X509* certificate() const; - /// Returns the underlying OpenSSL certificate. - - X509* dup() const; - /// Duplicates and returns the underlying OpenSSL certificate. Note that - /// the caller assumes responsibility for the lifecycle of the created - /// certificate. - - std::string signatureAlgorithm() const; - /// Returns the certificate signature algorithm long name. - - void print(std::ostream& out) const; - /// Prints the certificate information to ostream. - - static List readPEM(const std::string& pemFileName); - /// Reads and returns a list of certificates from - /// the specified PEM file. - - static void writePEM(const std::string& pemFileName, const List& list); - /// Writes the list of certificates to the specified PEM file. - -protected: - void load(std::istream& stream); - /// Loads the certificate from the given stream. The - /// certificate must be in PEM format. - - void load(const std::string& path); - /// Loads the certificate from the given file. The - /// certificate must be in PEM format. - - void init(); - /// Extracts issuer and subject name from the certificate. - -private: - enum - { - NAME_BUFFER_SIZE = 256 - }; - - std::string _issuerName; - std::string _subjectName; - std::string _serialNumber; - X509* _pCert; - OpenSSLInitializer _openSSLInitializer; -}; - - -// -// inlines -// - - -inline long X509Certificate::version() const +namespace Crypto { - // This is defined by standards (X.509 et al) to be - // one less than the certificate version. - // So, eg. a version 3 certificate will return 2. - return X509_get_version(_pCert) + 1; + + + class Crypto_API X509Certificate + /// This class represents a X509 Certificate. + { + public: + typedef std::vector List; + + enum NID + /// Name identifier for extracting information from + /// a certificate subject's or issuer's distinguished name. + { + NID_COMMON_NAME = 13, + NID_COUNTRY = 14, + NID_LOCALITY_NAME = 15, + NID_STATE_OR_PROVINCE = 16, + NID_ORGANIZATION_NAME = 17, + NID_ORGANIZATION_UNIT_NAME = 18, + NID_PKCS9_EMAIL_ADDRESS = 48, + NID_SERIAL_NUMBER = 105 + }; + + explicit X509Certificate(std::istream & istr); + /// Creates the X509Certificate object by reading + /// a certificate in PEM format from a stream. + + explicit X509Certificate(const std::string & path); + /// Creates the X509Certificate object by reading + /// a certificate in PEM format from a file. + + explicit X509Certificate(X509 * pCert); + /// Creates the X509Certificate from an existing + /// OpenSSL certificate. Ownership is taken of + /// the certificate. + + X509Certificate(X509 * pCert, bool shared); + /// Creates the X509Certificate from an existing + /// OpenSSL certificate. Ownership is taken of + /// the certificate. If shared is true, the + /// certificate's reference count is incremented. + + X509Certificate(const X509Certificate & cert); + /// Creates the certificate by copying another one. + + X509Certificate & operator=(const X509Certificate & cert); + /// Assigns a certificate. + + void swap(X509Certificate & cert); + /// Exchanges the certificate with another one. + + ~X509Certificate(); + /// Destroys the X509Certificate. + + long version() const; + /// Returns the version of the certificate. + + const std::string & serialNumber() const; + /// Returns the certificate serial number as a + /// string in decimal encoding. + + const std::string & issuerName() const; + /// Returns the certificate issuer's distinguished name. + + std::string issuerName(NID nid) const; + /// Extracts the information specified by the given + /// NID (name identifier) from the certificate issuer's + /// distinguished name. + + const std::string & subjectName() const; + /// Returns the certificate subject's distinguished name. + + std::string subjectName(NID nid) const; + /// Extracts the information specified by the given + /// NID (name identifier) from the certificate subject's + /// distinguished name. + + std::string commonName() const; + /// Returns the common name stored in the certificate + /// subject's distinguished name. + + void extractNames(std::string & commonName, std::set & domainNames) const; + /// Extracts the common name and the alias domain names from the + /// certificate. + + Poco::DateTime validFrom() const; + /// Returns the date and time the certificate is valid from. + + Poco::DateTime expiresOn() const; + /// Returns the date and time the certificate expires. + + void save(std::ostream & stream) const; + /// Writes the certificate to the given stream. + /// The certificate is written in PEM format. + + void save(const std::string & path) const; + /// Writes the certificate to the file given by path. + /// The certificate is written in PEM format. + + bool issuedBy(const X509Certificate & issuerCertificate) const; + /// Checks whether the certificate has been issued by + /// the issuer given by issuerCertificate. This can be + /// used to validate a certificate chain. + /// + /// Verifies if the certificate has been signed with the + /// issuer's private key, using the public key from the issuer + /// certificate. + /// + /// Returns true if verification against the issuer certificate + /// was successful, false otherwise. + + bool equals(const X509Certificate & otherCertificate) const; + /// Checks whether the certificate is equal to + /// the other certificate, by comparing the hashes + /// of both certificates. + /// + /// Returns true if both certificates are identical, + /// otherwise false. + + const X509 * certificate() const; + /// Returns the underlying OpenSSL certificate. + + X509 * dup() const; + /// Duplicates and returns the underlying OpenSSL certificate. Note that + /// the caller assumes responsibility for the lifecycle of the created + /// certificate. + + std::string signatureAlgorithm() const; + /// Returns the certificate signature algorithm long name. + + void print(std::ostream & out) const; + /// Prints the certificate information to ostream. + + static List readPEM(const std::string & pemFileName); + /// Reads and returns a list of certificates from + /// the specified PEM file. + + static void writePEM(const std::string & pemFileName, const List & list); + /// Writes the list of certificates to the specified PEM file. + + protected: + void load(std::istream & stream); + /// Loads the certificate from the given stream. The + /// certificate must be in PEM format. + + void load(const std::string & path); + /// Loads the certificate from the given file. The + /// certificate must be in PEM format. + + void init(); + /// Extracts issuer and subject name from the certificate. + + private: + enum + { + NAME_BUFFER_SIZE = 256 + }; + + std::string _issuerName; + std::string _subjectName; + std::string _serialNumber; + X509 * _pCert; + OpenSSLInitializer _openSSLInitializer; + }; + + + // + // inlines + // + + + inline long X509Certificate::version() const + { + // This is defined by standards (X.509 et al) to be + // one less than the certificate version. + // So, eg. a version 3 certificate will return 2. + return X509_get_version(_pCert) + 1; + } + + + inline const std::string & X509Certificate::serialNumber() const + { + return _serialNumber; + } + + + inline const std::string & X509Certificate::issuerName() const + { + return _issuerName; + } + + + inline const std::string & X509Certificate::subjectName() const + { + return _subjectName; + } + + + inline const X509 * X509Certificate::certificate() const + { + return _pCert; + } + + + inline X509 * X509Certificate::dup() const + { + return X509_dup(_pCert); + } + + } - - -inline const std::string& X509Certificate::serialNumber() const -{ - return _serialNumber; -} - - -inline const std::string& X509Certificate::issuerName() const -{ - return _issuerName; -} - - -inline const std::string& X509Certificate::subjectName() const -{ - return _subjectName; -} - - -inline const X509* X509Certificate::certificate() const -{ - return _pCert; -} - - -inline X509* X509Certificate::dup() const -{ - return X509_dup(_pCert); -} - - -} } // namespace Poco::Crypto +} // namespace Poco::Crypto #endif // Crypto_X509Certificate_INCLUDED diff --git a/base/poco/JSON/include/Poco/JSON/Array.h b/base/poco/JSON/include/Poco/JSON/Array.h index 6a61ad39c6c..18e2c4715e0 100644 --- a/base/poco/JSON/include/Poco/JSON/Array.h +++ b/base/poco/JSON/include/Poco/JSON/Array.h @@ -18,549 +18,416 @@ #define JSON_Array_INCLUDED +#include +#include +#include "Poco/Dynamic/Var.h" #include "Poco/JSON/JSON.h" #include "Poco/SharedPtr.h" -#include "Poco/Dynamic/Var.h" -#include -#include -namespace Poco { -namespace JSON { - - -class Object; - - -class JSON_API Array - /// Represents a JSON array. Array provides a representation - /// based on shared pointers and optimized for performance. It is possible to - /// convert Array to Poco::Dynamic::Array. Conversion requires copying and therefore - /// has performance penalty; the benefit is in improved syntax, eg: - /// - /// // use pointers to avoid copying - /// using namespace Poco::JSON; - /// std::string json = "[ {\"test\" : 0}, { \"test1\" : [1, 2, 3], \"test2\" : 4 } ]"; - /// Parser parser; - /// Var result = parser.parse(json); - /// Array::Ptr arr = result.extract(); - /// Object::Ptr object = arr->getObject(0); // object == {\"test\" : 0} - /// int i = object->getElement("test"); // i == 0; - /// Object::Ptr subObject = *arr->getObject(1); // subObject == {\"test\" : 0} - /// Array subArr::Ptr = subObject->getArray("test1"); // subArr == [1, 2, 3] - /// i = result = subArr->get(0); // i == 1; - /// - /// // copy/convert to Poco::Dynamic::Array - /// Poco::Dynamic::Array da = *arr; - /// i = da[0]["test"]; // i == 0 - /// i = da[1]["test1"][1]; // i == 2 - /// i = da[1]["test2"]; // i == 4 - /// ---- +namespace Poco +{ +namespace JSON { -public: - typedef std::vector ValueVec; - typedef std::vector::iterator Iterator; - typedef std::vector::const_iterator ConstIterator; - typedef SharedPtr Ptr; - Array(int options = 0); - /// Creates an empty Array. - /// - /// If JSON_ESCAPE_UNICODE is specified, when the object is - /// stringified, all unicode characters will be escaped in the - /// resulting string. - Array(const Array& copy); - /// Creates an Array by copying another one. + class Object; + + + class JSON_API Array + /// Represents a JSON array. Array provides a representation + /// based on shared pointers and optimized for performance. It is possible to + /// convert Array to Poco::Dynamic::Array. Conversion requires copying and therefore + /// has performance penalty; the benefit is in improved syntax, eg: + /// + /// // use pointers to avoid copying + /// using namespace Poco::JSON; + /// std::string json = "[ {\"test\" : 0}, { \"test1\" : [1, 2, 3], \"test2\" : 4 } ]"; + /// Parser parser; + /// Var result = parser.parse(json); + /// Array::Ptr arr = result.extract(); + /// Object::Ptr object = arr->getObject(0); // object == {\"test\" : 0} + /// int i = object->getElement("test"); // i == 0; + /// Object::Ptr subObject = *arr->getObject(1); // subObject == {\"test\" : 0} + /// Array subArr::Ptr = subObject->getArray("test1"); // subArr == [1, 2, 3] + /// i = result = subArr->get(0); // i == 1; + /// + /// // copy/convert to Poco::Dynamic::Array + /// Poco::Dynamic::Array da = *arr; + /// i = da[0]["test"]; // i == 0 + /// i = da[1]["test1"][1]; // i == 2 + /// i = da[1]["test2"]; // i == 4 + /// ---- + { + public: + typedef std::vector ValueVec; + typedef std::vector::iterator Iterator; + typedef std::vector::const_iterator ConstIterator; + typedef SharedPtr Ptr; + + Array(int options = 0); + /// Creates an empty Array. + /// + /// If JSON_ESCAPE_UNICODE is specified, when the object is + /// stringified, all unicode characters will be escaped in the + /// resulting string. + + Array(const Array & copy); + /// Creates an Array by copying another one. #ifdef POCO_ENABLE_CPP11 - Array(Array&& other); - /// Move constructor + Array(Array && other); + /// Move constructor - Array& operator=(Array&& other); - /// Move assignment operator. + Array & operator=(Array && other); + /// Move assignment operator. #endif // POCO_ENABLE_CPP11 - Array& operator=(const Array& other); - /// Assignment operator. + Array & operator=(const Array & other); + /// Assignment operator. - virtual ~Array(); - /// Destroys the Array. + virtual ~Array(); + /// Destroys the Array. - void setEscapeUnicode(bool escape = true); - /// Sets the flag for escaping unicode. + void setEscapeUnicode(bool escape = true); + /// Sets the flag for escaping unicode. - bool getEscapeUnicode() const; - /// Returns the flag for escaping unicode. + bool getEscapeUnicode() const; + /// Returns the flag for escaping unicode. - ValueVec::const_iterator begin() const; - /// Returns the begin iterator for values. + ValueVec::const_iterator begin() const; + /// Returns the begin iterator for values. - ValueVec::const_iterator end() const; - /// Returns the end iterator for values. + ValueVec::const_iterator end() const; + /// Returns the end iterator for values. - Dynamic::Var get(unsigned int index) const; - /// Retrieves the element at the given index. - /// Will return an empty value when the element doesn't exist. + Dynamic::Var get(unsigned int index) const; + /// Retrieves the element at the given index. + /// Will return an empty value when the element doesn't exist. - Array::Ptr getArray(unsigned int index) const; - /// Retrieves an array. When the element is not - /// an Array or doesn't exist, an empty SharedPtr is returned. + Array::Ptr getArray(unsigned int index) const; + /// Retrieves an array. When the element is not + /// an Array or doesn't exist, an empty SharedPtr is returned. - template - T getElement(unsigned int index) const - /// Retrieves an element and tries to convert it to the - /// template type. The convert method of - /// Dynamic is called which can also throw - /// exceptions for invalid values. - /// Note: This will not work for an array or an object. - { - Dynamic::Var value = get(index); - return value.convert(); - } + template + T getElement(unsigned int index) const + /// Retrieves an element and tries to convert it to the + /// template type. The convert method of + /// Dynamic is called which can also throw + /// exceptions for invalid values. + /// Note: This will not work for an array or an object. + { + Dynamic::Var value = get(index); + return value.convert(); + } - SharedPtr getObject(unsigned int index) const; - /// Retrieves an object. When the element is not - /// an object or doesn't exist, an empty SharedPtr is returned. + SharedPtr getObject(unsigned int index) const; + /// Retrieves an object. When the element is not + /// an object or doesn't exist, an empty SharedPtr is returned. - std::size_t size() const; - /// Returns the size of the array. + std::size_t size() const; + /// Returns the size of the array. - bool isArray(unsigned int index) const; - /// Returns true when the element is an array. + bool isArray(unsigned int index) const; + /// Returns true when the element is an array. - bool isArray(const Dynamic::Var& value) const; - /// Returns true when the element is an array. + bool isArray(const Dynamic::Var & value) const; + /// Returns true when the element is an array. - bool isArray(ConstIterator& value) const; - /// Returns true when the element is an array. + bool isArray(ConstIterator & value) const; + /// Returns true when the element is an array. - bool isNull(unsigned int index) const; - /// Returns true when the element is null or - /// when the element doesn't exist. + bool isNull(unsigned int index) const; + /// Returns true when the element is null or + /// when the element doesn't exist. - bool isObject(unsigned int index) const; - /// Returns true when the element is an object. + bool isObject(unsigned int index) const; + /// Returns true when the element is an object. - bool isObject(const Dynamic::Var& value) const; - /// Returns true when the element is an object. + bool isObject(const Dynamic::Var & value) const; + /// Returns true when the element is an object. - bool isObject(ConstIterator& value) const; - /// Returns true when the element is an object. + bool isObject(ConstIterator & value) const; + /// Returns true when the element is an object. - template - T optElement(unsigned int index, const T& def) const - /// Returns the element at the given index. When - /// the element is null, doesn't exist or can't - /// be converted to the given type, the default - /// value will be returned - { - T value = def; - if (index < _values.size()) - { - try - { - value = _values[index].convert(); - } - catch (...) - { - // Default value is returned. - } - } - return value; - } + template + T optElement(unsigned int index, const T & def) const + /// Returns the element at the given index. When + /// the element is null, doesn't exist or can't + /// be converted to the given type, the default + /// value will be returned + { + T value = def; + if (index < _values.size()) + { + try + { + value = _values[index].convert(); + } + catch (...) + { + // Default value is returned. + } + } + return value; + } - void add(const Dynamic::Var& value); - /// Add the given value to the array + void add(const Dynamic::Var & value); + /// Add the given value to the array - void set(unsigned int index, const Dynamic::Var& value); - /// Update the element on the given index to specified value + void set(unsigned int index, const Dynamic::Var & value); + /// Update the element on the given index to specified value - void stringify(std::ostream& out, unsigned int indent = 0, int step = -1) const; - /// Prints the array to out. When indent has zero value, - /// the array will be printed without newline breaks and spaces between elements. + void stringify(std::ostream & out, unsigned int indent = 0, int step = -1) const; + /// Prints the array to out. When indent has zero value, + /// the array will be printed without newline breaks and spaces between elements. - void remove(unsigned int index); - /// Removes the element on the given index. + void remove(unsigned int index); + /// Removes the element on the given index. - operator const Poco::Dynamic::Array& () const; - /// Conversion operator to Dynamic::Array. + operator const Poco::Dynamic::Array &() const; + /// Conversion operator to Dynamic::Array. - static Poco::Dynamic::Array makeArray(const JSON::Array::Ptr& arr); - /// Utility function for creation of array. + static Poco::Dynamic::Array makeArray(const JSON::Array::Ptr & arr); + /// Utility function for creation of array. - void clear(); - /// Clears the contents of the array. + void clear(); + /// Clears the contents of the array. -private: - void resetDynArray() const; + private: + void resetDynArray() const; - typedef SharedPtr ArrayPtr; + typedef SharedPtr ArrayPtr; - ValueVec _values; - mutable ArrayPtr _pArray; - mutable bool _modified; - // Note: - // The reason we have this flag here (rather than as argument to stringify()) - // is because Array can be returned stringified from a Dynamic::Var:toString(), - // so it must know whether to escape unicode or not. - bool _escapeUnicode; -}; + ValueVec _values; + mutable ArrayPtr _pArray; + mutable bool _modified; + // Note: + // The reason we have this flag here (rather than as argument to stringify()) + // is because Array can be returned stringified from a Dynamic::Var:toString(), + // so it must know whether to escape unicode or not. + bool _escapeUnicode; + }; -// -// inlines -// + // + // inlines + // + + inline void Array::setEscapeUnicode(bool escape) + { + _escapeUnicode = escape; + } + + + inline bool Array::getEscapeUnicode() const + { + return _escapeUnicode; + } + + + inline Array::ValueVec::const_iterator Array::begin() const + { + return _values.begin(); + } + + + inline Array::ValueVec::const_iterator Array::end() const + + { + return _values.end(); + } + + + inline std::size_t Array::size() const + { + return static_cast(_values.size()); + } + + + inline bool Array::isArray(unsigned int index) const + { + Dynamic::Var value = get(index); + return isArray(value); + } + + + inline bool Array::isArray(const Dynamic::Var & value) const + { + return value.type() == typeid(Array::Ptr); + } + + + inline bool Array::isArray(ConstIterator & it) const + { + return it != end() && isArray(*it); + } + + + inline void Array::add(const Dynamic::Var & value) + { + _values.push_back(value); + _modified = true; + } + + + inline void Array::set(unsigned int index, const Dynamic::Var & value) + { + if (index >= _values.size()) + _values.resize(index + 1); + _values[index] = value; + _modified = true; + } + + + inline void Array::remove(unsigned int index) + { + _values.erase(_values.begin() + index); + } + -inline void Array::setEscapeUnicode(bool escape) -{ - _escapeUnicode = escape; } +} // namespace Poco::JSON -inline bool Array::getEscapeUnicode() const +namespace Poco { - return _escapeUnicode; +namespace Dynamic +{ + + + template <> + class VarHolderImpl : public VarHolder + { + public: + VarHolderImpl(const JSON::Array::Ptr & val) : _val(val) { } + + ~VarHolderImpl() { } + + const std::type_info & type() const { return typeid(JSON::Array::Ptr); } + + void convert(Int8 &) const { throw BadCastException(); } + + void convert(Int16 &) const { throw BadCastException(); } + + void convert(Int32 &) const { throw BadCastException(); } + + void convert(Int64 &) const { throw BadCastException(); } + + void convert(UInt8 &) const { throw BadCastException(); } + + void convert(UInt16 &) const { throw BadCastException(); } + + void convert(UInt32 &) const { throw BadCastException(); } + + void convert(UInt64 &) const { throw BadCastException(); } + + void convert(bool & value) const { value = !_val.isNull() && _val->size() > 0; } + + void convert(float &) const { throw BadCastException(); } + + void convert(double &) const { throw BadCastException(); } + + void convert(char &) const { throw BadCastException(); } + + void convert(std::string & s) const + { + std::ostringstream oss; + _val->stringify(oss, 2); + s = oss.str(); + } + + void convert(DateTime & /*val*/) const { throw BadCastException("Cannot convert Array to DateTime"); } + + void convert(LocalDateTime & /*ldt*/) const { throw BadCastException("Cannot convert Array to LocalDateTime"); } + + void convert(Timestamp & /*ts*/) const { throw BadCastException("Cannot convert Array to Timestamp"); } + + VarHolder * clone(Placeholder * pVarHolder = 0) const { return cloneHolder(pVarHolder, _val); } + + const JSON::Array::Ptr & value() const { return _val; } + + bool isInteger() const { return false; } + + bool isSigned() const { return false; } + + bool isNumeric() const { return false; } + + bool isString() const { return false; } + + private: + JSON::Array::Ptr _val; + }; + + + template <> + class VarHolderImpl : public VarHolder + { + public: + VarHolderImpl(const JSON::Array & val) : _val(val) { } + + ~VarHolderImpl() { } + + const std::type_info & type() const { return typeid(JSON::Array); } + + void convert(Int8 &) const { throw BadCastException(); } + + void convert(Int16 &) const { throw BadCastException(); } + + void convert(Int32 &) const { throw BadCastException(); } + + void convert(Int64 &) const { throw BadCastException(); } + + void convert(UInt8 &) const { throw BadCastException(); } + + void convert(UInt16 &) const { throw BadCastException(); } + + void convert(UInt32 &) const { throw BadCastException(); } + + void convert(UInt64 &) const { throw BadCastException(); } + + void convert(bool & value) const { value = _val.size() > 0; } + + void convert(float &) const { throw BadCastException(); } + + void convert(double &) const { throw BadCastException(); } + + void convert(char &) const { throw BadCastException(); } + + void convert(std::string & s) const + { + std::ostringstream oss; + _val.stringify(oss, 2); + s = oss.str(); + } + + void convert(DateTime & /*val*/) const { throw BadCastException("Cannot convert Array to DateTime"); } + + void convert(LocalDateTime & /*ldt*/) const { throw BadCastException("Cannot convert Array to LocalDateTime"); } + + void convert(Timestamp & /*ts*/) const { throw BadCastException("Cannot convert Array to Timestamp"); } + + VarHolder * clone(Placeholder * pVarHolder = 0) const { return cloneHolder(pVarHolder, _val); } + + const JSON::Array & value() const { return _val; } + + bool isInteger() const { return false; } + + bool isSigned() const { return false; } + + bool isNumeric() const { return false; } + + bool isString() const { return false; } + + private: + JSON::Array _val; + }; + + } - - -inline Array::ValueVec::const_iterator Array::begin() const -{ - return _values.begin(); -} - - -inline Array::ValueVec::const_iterator Array::end() const - -{ - return _values.end(); -} - - -inline std::size_t Array::size() const -{ - return static_cast(_values.size()); -} - - -inline bool Array::isArray(unsigned int index) const -{ - Dynamic::Var value = get(index); - return isArray(value); -} - - -inline bool Array::isArray(const Dynamic::Var& value) const -{ - return value.type() == typeid(Array::Ptr); -} - - -inline bool Array::isArray(ConstIterator& it) const -{ - return it!= end() && isArray(*it); -} - - -inline void Array::add(const Dynamic::Var& value) -{ - _values.push_back(value); - _modified = true; -} - - -inline void Array::set(unsigned int index, const Dynamic::Var& value) -{ - if (index >= _values.size()) _values.resize(index + 1); - _values[index] = value; - _modified = true; -} - - -inline void Array::remove(unsigned int index) -{ - _values.erase(_values.begin() + index); -} - - -} } // namespace Poco::JSON - - -namespace Poco { -namespace Dynamic { - - -template <> -class VarHolderImpl: public VarHolder -{ -public: - VarHolderImpl(const JSON::Array::Ptr& val): _val(val) - { - } - - ~VarHolderImpl() - { - } - - const std::type_info& type() const - { - return typeid(JSON::Array::Ptr); - } - - void convert(Int8&) const - { - throw BadCastException(); - } - - void convert(Int16&) const - { - throw BadCastException(); - } - - void convert(Int32&) const - { - throw BadCastException(); - } - - void convert(Int64&) const - { - throw BadCastException(); - } - - void convert(UInt8&) const - { - throw BadCastException(); - } - - void convert(UInt16&) const - { - throw BadCastException(); - } - - void convert(UInt32&) const - { - throw BadCastException(); - } - - void convert(UInt64&) const - { - throw BadCastException(); - } - - void convert(bool& value) const - { - value = !_val.isNull() && _val->size() > 0; - } - - void convert(float&) const - { - throw BadCastException(); - } - - void convert(double&) const - { - throw BadCastException(); - } - - void convert(char&) const - { - throw BadCastException(); - } - - void convert(std::string& s) const - { - std::ostringstream oss; - _val->stringify(oss, 2); - s = oss.str(); - } - - void convert(DateTime& /*val*/) const - { - throw BadCastException("Cannot convert Array to DateTime"); - } - - void convert(LocalDateTime& /*ldt*/) const - { - throw BadCastException("Cannot convert Array to LocalDateTime"); - } - - void convert(Timestamp& /*ts*/) const - { - throw BadCastException("Cannot convert Array to Timestamp"); - } - - VarHolder* clone(Placeholder* pVarHolder = 0) const - { - return cloneHolder(pVarHolder, _val); - } - - const JSON::Array::Ptr& value() const - { - return _val; - } - - bool isInteger() const - { - return false; - } - - bool isSigned() const - { - return false; - } - - bool isNumeric() const - { - return false; - } - - bool isString() const - { - return false; - } - -private: - JSON::Array::Ptr _val; -}; - - -template <> -class VarHolderImpl: public VarHolder -{ -public: - VarHolderImpl(const JSON::Array& val): _val(val) - { - } - - ~VarHolderImpl() - { - } - - const std::type_info& type() const - { - return typeid(JSON::Array); - } - - void convert(Int8&) const - { - throw BadCastException(); - } - - void convert(Int16&) const - { - throw BadCastException(); - } - - void convert(Int32&) const - { - throw BadCastException(); - } - - void convert(Int64&) const - { - throw BadCastException(); - } - - void convert(UInt8&) const - { - throw BadCastException(); - } - - void convert(UInt16&) const - { - throw BadCastException(); - } - - void convert(UInt32&) const - { - throw BadCastException(); - } - - void convert(UInt64&) const - { - throw BadCastException(); - } - - void convert(bool& value) const - { - value = _val.size() > 0; - } - - void convert(float&) const - { - throw BadCastException(); - } - - void convert(double&) const - { - throw BadCastException(); - } - - void convert(char&) const - { - throw BadCastException(); - } - - void convert(std::string& s) const - { - std::ostringstream oss; - _val.stringify(oss, 2); - s = oss.str(); - } - - void convert(DateTime& /*val*/) const - { - throw BadCastException("Cannot convert Array to DateTime"); - } - - void convert(LocalDateTime& /*ldt*/) const - { - throw BadCastException("Cannot convert Array to LocalDateTime"); - } - - void convert(Timestamp& /*ts*/) const - { - throw BadCastException("Cannot convert Array to Timestamp"); - } - - VarHolder* clone(Placeholder* pVarHolder = 0) const - { - return cloneHolder(pVarHolder, _val); - } - - const JSON::Array& value() const - { - return _val; - } - - bool isInteger() const - { - return false; - } - - bool isSigned() const - { - return false; - } - - bool isNumeric() const - { - return false; - } - - bool isString() const - { - return false; - } - -private: - JSON::Array _val; -}; - - -} } // namespace Poco::Dynamic +} // namespace Poco::Dynamic #endif // JSON_Array_INCLUDED diff --git a/base/poco/JSON/include/Poco/JSON/Handler.h b/base/poco/JSON/include/Poco/JSON/Handler.h index 8c64f34ff01..f9114a59221 100644 --- a/base/poco/JSON/include/Poco/JSON/Handler.h +++ b/base/poco/JSON/include/Poco/JSON/Handler.h @@ -18,89 +18,92 @@ #define JSON_Handler_INCLUDED +#include "Poco/Dynamic/Struct.h" +#include "Poco/Dynamic/Var.h" #include "Poco/JSON/JSON.h" #include "Poco/SharedPtr.h" -#include "Poco/Dynamic/Var.h" -#include "Poco/Dynamic/Struct.h" -namespace Poco { -namespace JSON { - - -class JSON_API Handler - /// Interface for handling parsing events generated by the JSON Parser. - /// - /// An application can implement a subclass of Handler to implement - /// callback-based parsing of a JSON document, similar to how a SAX - /// parser would handle XML. +namespace Poco +{ +namespace JSON { -public: - typedef SharedPtr Ptr; - Handler(); - /// Creates an empty Handler. - - virtual ~Handler(); - /// Destroys the Handler. - virtual void reset() = 0; - /// Resets the handler state. + class JSON_API Handler + /// Interface for handling parsing events generated by the JSON Parser. + /// + /// An application can implement a subclass of Handler to implement + /// callback-based parsing of a JSON document, similar to how a SAX + /// parser would handle XML. + { + public: + typedef SharedPtr Ptr; - virtual void startObject() = 0; - /// The parser has read a {, meaning a new object will be read. + Handler(); + /// Creates an empty Handler. - virtual void endObject() = 0; - /// The parser has read a }, meaning the object is read. + virtual ~Handler(); + /// Destroys the Handler. - virtual void startArray() = 0; - /// The parser has read a [, meaning a new array will be read. + virtual void reset() = 0; + /// Resets the handler state. - virtual void endArray() = 0; - /// The parser has read a ], meaning the array is read. + virtual void startObject() = 0; + /// The parser has read a {, meaning a new object will be read. - virtual void key(const std::string& k) = 0; - /// A key of an object is read. + virtual void endObject() = 0; + /// The parser has read a }, meaning the object is read. - virtual void null() = 0; - /// A null value is read. + virtual void startArray() = 0; + /// The parser has read a [, meaning a new array will be read. - virtual void value(int v) = 0; - /// An integer value is read. + virtual void endArray() = 0; + /// The parser has read a ], meaning the array is read. - virtual void value(unsigned v) = 0; - /// An unsigned value is read. This will only be triggered if the - /// value cannot fit into a signed int. + virtual void key(const std::string & k) = 0; + /// A key of an object is read. + + virtual void null() = 0; + /// A null value is read. + + virtual void value(int v) = 0; + /// An integer value is read. + + virtual void value(unsigned v) = 0; + /// An unsigned value is read. This will only be triggered if the + /// value cannot fit into a signed int. #if defined(POCO_HAVE_INT64) - virtual void value(Int64 v) = 0; - /// A 64-bit integer value is read. + virtual void value(Int64 v) = 0; + /// A 64-bit integer value is read. - virtual void value(UInt64 v) = 0; - /// An unsigned 64-bit integer value is read. This will only be - /// triggered if the value cannot fit into a signed 64-bit integer. + virtual void value(UInt64 v) = 0; + /// An unsigned 64-bit integer value is read. This will only be + /// triggered if the value cannot fit into a signed 64-bit integer. #endif - virtual void value(const std::string& value) = 0; - /// A string value is read. + virtual void value(const std::string & value) = 0; + /// A string value is read. - virtual void value(double d) = 0; - /// A double value is read. + virtual void value(double d) = 0; + /// A double value is read. - virtual void value(bool b) = 0; - /// A boolean value is read. + virtual void value(bool b) = 0; + /// A boolean value is read. - virtual Poco::Dynamic::Var asVar() const; - /// Returns the result of the parser (an object, array or string), - /// empty Var if there is no result. + virtual Poco::Dynamic::Var asVar() const; + /// Returns the result of the parser (an object, array or string), + /// empty Var if there is no result. - virtual Poco::DynamicStruct asStruct() const; - /// Returns the result of the parser (an object, array or string), - /// empty Var if there is no result. -}; + virtual Poco::DynamicStruct asStruct() const; + /// Returns the result of the parser (an object, array or string), + /// empty Var if there is no result. + }; -} } // namespace Poco::JSON +} +} // namespace Poco::JSON #endif // JSON_Handler_INCLUDED diff --git a/base/poco/JSON/include/Poco/JSON/JSON.h b/base/poco/JSON/include/Poco/JSON/JSON.h index 36d7623756b..f0bef787be0 100644 --- a/base/poco/JSON/include/Poco/JSON/JSON.h +++ b/base/poco/JSON/include/Poco/JSON/JSON.h @@ -32,20 +32,20 @@ // defined with this macro as being exported. // #if defined(_WIN32) && defined(POCO_DLL) - #if defined(JSON_EXPORTS) - #define JSON_API __declspec(dllexport) - #else - #define JSON_API __declspec(dllimport) - #endif +# if defined(JSON_EXPORTS) +# define JSON_API __declspec(dllexport) +# else +# define JSON_API __declspec(dllimport) +# endif #endif #if !defined(JSON_API) - #if !defined(POCO_NO_GCC_API_ATTRIBUTE) && defined (__GNUC__) && (__GNUC__ >= 4) - #define JSON_API __attribute__ ((visibility ("default"))) - #else - #define JSON_API - #endif +# if !defined(POCO_NO_GCC_API_ATTRIBUTE) && defined(__GNUC__) && (__GNUC__ >= 4) +# define JSON_API __attribute__((visibility("default"))) +# else +# define JSON_API +# endif #endif @@ -53,9 +53,9 @@ // Automatically link JSON library. // #if defined(_MSC_VER) - #if !defined(POCO_NO_AUTOMATIC_LIBS) && !defined(JSON_EXPORTS) - #pragma comment(lib, "PocoJSON" POCO_LIB_SUFFIX) - #endif +# if !defined(POCO_NO_AUTOMATIC_LIBS) && !defined(JSON_EXPORTS) +# pragma comment(lib, "PocoJSON" POCO_LIB_SUFFIX) +# endif #endif diff --git a/base/poco/JSON/include/Poco/JSON/JSONException.h b/base/poco/JSON/include/Poco/JSON/JSONException.h index 058d36f0aea..1868c7a54a1 100644 --- a/base/poco/JSON/include/Poco/JSON/JSONException.h +++ b/base/poco/JSON/include/Poco/JSON/JSONException.h @@ -18,18 +18,21 @@ #define JSON_JSONException_INCLUDED -#include "Poco/JSON/JSON.h" #include "Poco/Exception.h" +#include "Poco/JSON/JSON.h" -namespace Poco { -namespace JSON { +namespace Poco +{ +namespace JSON +{ -POCO_DECLARE_EXCEPTION(JSON_API, JSONException, Poco::Exception) + POCO_DECLARE_EXCEPTION(JSON_API, JSONException, Poco::Exception) -} } // namespace Poco::JSON +} +} // namespace Poco::JSON #endif // JSON_JSONException_INCLUDED diff --git a/base/poco/JSON/include/Poco/JSON/Object.h b/base/poco/JSON/include/Poco/JSON/Object.h index f2e8062d343..0d3285b39d9 100644 --- a/base/poco/JSON/include/Poco/JSON/Object.h +++ b/base/poco/JSON/include/Poco/JSON/Object.h @@ -18,698 +18,582 @@ #define JSON_Object_INCLUDED -#include "Poco/JSON/JSON.h" -#include "Poco/JSON/Array.h" -#include "Poco/JSON/Stringifier.h" -#include "Poco/JSONString.h" -#include "Poco/SharedPtr.h" -#include "Poco/Dynamic/Var.h" -#include "Poco/Dynamic/Struct.h" -#include "Poco/Nullable.h" -#include -#include #include #include +#include #include +#include +#include "Poco/Dynamic/Struct.h" +#include "Poco/Dynamic/Var.h" +#include "Poco/JSON/Array.h" +#include "Poco/JSON/JSON.h" +#include "Poco/JSON/Stringifier.h" +#include "Poco/JSONString.h" +#include "Poco/Nullable.h" +#include "Poco/SharedPtr.h" -namespace Poco { -namespace JSON { - - -class JSON_API Object - /// Represents a JSON object. Object provides a representation based on - /// shared pointers and optimized for performance. It is possible to - /// convert Object to DynamicStruct. Conversion requires copying and therefore - /// has performance penalty; the benefit is in improved syntax, eg: - /// - /// std::string json = "{ \"test\" : { \"property\" : \"value\" } }"; - /// Parser parser; - /// Var result = parser.parse(json); - /// - /// // use pointers to avoid copying - /// Object::Ptr object = result.extract(); - /// Var test = object->get("test"); // holds { "property" : "value" } - /// Object::Ptr subObject = test.extract(); - /// test = subObject->get("property"); - /// std::string val = test.toString(); // val holds "value" - /// - /// // copy/convert to Poco::DynamicStruct - /// Poco::DynamicStruct ds = *object; - /// val = ds["test"]["property"]; // val holds "value" - /// +namespace Poco +{ +namespace JSON { -public: - typedef SharedPtr Ptr; - typedef std::map ValueMap; - typedef ValueMap::value_type ValueType; - typedef ValueMap::iterator Iterator; - typedef ValueMap::const_iterator ConstIterator; - typedef std::vector NameList; - explicit Object(int options = 0); - /// Creates an empty Object. - /// - /// If JSON_PRESERVE_KEY_ORDER is specified, the object will - /// preserve the items insertion order. Otherwise, items will be - /// sorted by keys. - /// - /// If JSON_ESCAPE_UNICODE is specified, when the object is - /// stringified, all unicode characters will be escaped in the - /// resulting string. - Object(const Object& copy); - /// Creates an Object by copying another one. - /// - /// Struct is not copied to keep the operation as - /// efficient as possible (when needed, it will be generated upon request). + class JSON_API Object + /// Represents a JSON object. Object provides a representation based on + /// shared pointers and optimized for performance. It is possible to + /// convert Object to DynamicStruct. Conversion requires copying and therefore + /// has performance penalty; the benefit is in improved syntax, eg: + /// + /// std::string json = "{ \"test\" : { \"property\" : \"value\" } }"; + /// Parser parser; + /// Var result = parser.parse(json); + /// + /// // use pointers to avoid copying + /// Object::Ptr object = result.extract(); + /// Var test = object->get("test"); // holds { "property" : "value" } + /// Object::Ptr subObject = test.extract(); + /// test = subObject->get("property"); + /// std::string val = test.toString(); // val holds "value" + /// + /// // copy/convert to Poco::DynamicStruct + /// Poco::DynamicStruct ds = *object; + /// val = ds["test"]["property"]; // val holds "value" + /// + { + public: + typedef SharedPtr Ptr; + typedef std::map ValueMap; + typedef ValueMap::value_type ValueType; + typedef ValueMap::iterator Iterator; + typedef ValueMap::const_iterator ConstIterator; + typedef std::vector NameList; + + explicit Object(int options = 0); + /// Creates an empty Object. + /// + /// If JSON_PRESERVE_KEY_ORDER is specified, the object will + /// preserve the items insertion order. Otherwise, items will be + /// sorted by keys. + /// + /// If JSON_ESCAPE_UNICODE is specified, when the object is + /// stringified, all unicode characters will be escaped in the + /// resulting string. + + Object(const Object & copy); + /// Creates an Object by copying another one. + /// + /// Struct is not copied to keep the operation as + /// efficient as possible (when needed, it will be generated upon request). #ifdef POCO_ENABLE_CPP11 - Object(Object&& other); - /// Move constructor + Object(Object && other); + /// Move constructor - Object &operator =(Object &&other); - // Move assignment operator + Object & operator=(Object && other); + // Move assignment operator #endif // POCO_ENABLE_CPP11 - virtual ~Object(); - /// Destroys the Object. + virtual ~Object(); + /// Destroys the Object. - Object &operator =(const Object &other); - // Assignment operator + Object & operator=(const Object & other); + // Assignment operator - void setEscapeUnicode(bool escape = true); - /// Sets the flag for escaping unicode. + void setEscapeUnicode(bool escape = true); + /// Sets the flag for escaping unicode. - bool getEscapeUnicode() const; - /// Returns the flag for escaping unicode. + bool getEscapeUnicode() const; + /// Returns the flag for escaping unicode. - Iterator begin(); - /// Returns begin iterator for values. + Iterator begin(); + /// Returns begin iterator for values. - ConstIterator begin() const; - /// Returns const begin iterator for values. + ConstIterator begin() const; + /// Returns const begin iterator for values. - Iterator end(); - /// Returns end iterator for values. + Iterator end(); + /// Returns end iterator for values. - ConstIterator end() const; - /// Returns const end iterator for values. + ConstIterator end() const; + /// Returns const end iterator for values. - Dynamic::Var get(const std::string& key) const; - /// Retrieves a property. An empty value is - /// returned when the property doesn't exist. + Dynamic::Var get(const std::string & key) const; + /// Retrieves a property. An empty value is + /// returned when the property doesn't exist. - Array::Ptr getArray(const std::string& key) const; - /// Returns a SharedPtr to an array when the property - /// is an array. An empty SharedPtr is returned when - /// the element doesn't exist or is not an array. + Array::Ptr getArray(const std::string & key) const; + /// Returns a SharedPtr to an array when the property + /// is an array. An empty SharedPtr is returned when + /// the element doesn't exist or is not an array. - Object::Ptr getObject(const std::string& key) const; - /// Returns a SharedPtr to an object when the property - /// is an object. An empty SharedPtr is returned when - /// the property doesn't exist or is not an object + Object::Ptr getObject(const std::string & key) const; + /// Returns a SharedPtr to an object when the property + /// is an object. An empty SharedPtr is returned when + /// the property doesn't exist or is not an object - template - T getValue(const std::string& key) const - /// Retrieves the property with the given name and will - /// try to convert the value to the given template type. - /// The convert() method of Var is called - /// which can also throw exceptions for invalid values. - /// Note: This will not work for an array or an object. - { - Dynamic::Var value = get(key); - return value.convert(); - } + template + T getValue(const std::string & key) const + /// Retrieves the property with the given name and will + /// try to convert the value to the given template type. + /// The convert() method of Var is called + /// which can also throw exceptions for invalid values. + /// Note: This will not work for an array or an object. + { + Dynamic::Var value = get(key); + return value.convert(); + } - template - Poco::Nullable getNullableValue(const std::string& key) const - /// Retrieves the property with the given name and will - /// try to convert the value to the given template type. - /// - /// The convert method of Var is called - /// which can also throw exceptions for invalid values. - /// Note: This will not work for an array or an object. - { - if (isNull(key)) - return Poco::Nullable(); + template + Poco::Nullable getNullableValue(const std::string & key) const + /// Retrieves the property with the given name and will + /// try to convert the value to the given template type. + /// + /// The convert method of Var is called + /// which can also throw exceptions for invalid values. + /// Note: This will not work for an array or an object. + { + if (isNull(key)) + return Poco::Nullable(); - Dynamic::Var value = get(key); - return value.convert(); - } + Dynamic::Var value = get(key); + return value.convert(); + } - void getNames(NameList& names) const; - /// Fills the supplied vector with all property names. + void getNames(NameList & names) const; + /// Fills the supplied vector with all property names. - NameList getNames() const; - /// Returns all property names. + NameList getNames() const; + /// Returns all property names. - bool has(const std::string& key) const; - /// Returns true when the given property exists. + bool has(const std::string & key) const; + /// Returns true when the given property exists. - bool isArray(const std::string& key) const; - /// Returns true when the given property contains an array. + bool isArray(const std::string & key) const; + /// Returns true when the given property contains an array. - bool isArray(ConstIterator& it) const; - /// Returns true when the given property contains an array. + bool isArray(ConstIterator & it) const; + /// Returns true when the given property contains an array. - bool isNull(const std::string& key) const; - /// Returns true when the given property contains a null value. + bool isNull(const std::string & key) const; + /// Returns true when the given property contains a null value. - bool isObject(const std::string& key) const; - /// Returns true when the given property contains an object. + bool isObject(const std::string & key) const; + /// Returns true when the given property contains an object. - bool isObject(ConstIterator& it) const; - /// Returns true when the given property contains an object. + bool isObject(ConstIterator & it) const; + /// Returns true when the given property contains an object. - template - T optValue(const std::string& key, const T& def) const - /// Returns the value of a property when the property exists - /// and can be converted to the given type. Otherwise - /// def will be returned. - { - T value = def; - ValueMap::const_iterator it = _values.find(key); - if (it != _values.end() && ! it->second.isEmpty()) - { - try - { - value = it->second.convert(); - } - catch (...) - { - // The default value will be returned - } - } - return value; - } + template + T optValue(const std::string & key, const T & def) const + /// Returns the value of a property when the property exists + /// and can be converted to the given type. Otherwise + /// def will be returned. + { + T value = def; + ValueMap::const_iterator it = _values.find(key); + if (it != _values.end() && !it->second.isEmpty()) + { + try + { + value = it->second.convert(); + } + catch (...) + { + // The default value will be returned + } + } + return value; + } - std::size_t size() const; - /// Returns the number of properties. + std::size_t size() const; + /// Returns the number of properties. - void set(const std::string& key, const Dynamic::Var& value); - /// Sets a new value. + void set(const std::string & key, const Dynamic::Var & value); + /// Sets a new value. - void stringify(std::ostream& out, unsigned int indent = 0, int step = -1) const; - /// Prints the object to out stream. - /// - /// When indent is 0, the object will be printed on a single - /// line without indentation. + void stringify(std::ostream & out, unsigned int indent = 0, int step = -1) const; + /// Prints the object to out stream. + /// + /// When indent is 0, the object will be printed on a single + /// line without indentation. - void remove(const std::string& key); - /// Removes the property with the given key. + void remove(const std::string & key); + /// Removes the property with the given key. - static Poco::DynamicStruct makeStruct(const Object::Ptr& obj); - /// Utility function for creation of struct. + static Poco::DynamicStruct makeStruct(const Object::Ptr & obj); + /// Utility function for creation of struct. - operator const Poco::DynamicStruct& () const; - /// Cast operator to Poco::DynamiStruct. + operator const Poco::DynamicStruct &() const; + /// Cast operator to Poco::DynamiStruct. - void clear(); - /// Clears the contents of the object. - /// - /// Insertion order preservation property is left intact. + void clear(); + /// Clears the contents of the object. + /// + /// Insertion order preservation property is left intact. -private: - typedef std::deque KeyList; - typedef Poco::DynamicStruct::Ptr StructPtr; + private: + typedef std::deque KeyList; + typedef Poco::DynamicStruct::Ptr StructPtr; - void resetDynStruct() const; - void syncKeys(const KeyList& keys); + void resetDynStruct() const; + void syncKeys(const KeyList & keys); - template - void doStringify(const C& container, std::ostream& out, unsigned int indent, unsigned int step) const - { - int options = Poco::JSON_WRAP_STRINGS; - options |= _escapeUnicode ? Poco::JSON_ESCAPE_UNICODE : 0; + template + void doStringify(const C & container, std::ostream & out, unsigned int indent, unsigned int step) const + { + int options = Poco::JSON_WRAP_STRINGS; + options |= _escapeUnicode ? Poco::JSON_ESCAPE_UNICODE : 0; - out << '{'; + out << '{'; - if (indent > 0) out << std::endl; + if (indent > 0) + out << std::endl; - typename C::const_iterator it = container.begin(); - typename C::const_iterator end = container.end(); - for (; it != end;) - { - for (unsigned int i = 0; i < indent; i++) out << ' '; + typename C::const_iterator it = container.begin(); + typename C::const_iterator end = container.end(); + for (; it != end;) + { + for (unsigned int i = 0; i < indent; i++) + out << ' '; - Stringifier::stringify(getKey(it), out, indent, step, options); - out << ((indent > 0) ? " : " : ":"); + Stringifier::stringify(getKey(it), out, indent, step, options); + out << ((indent > 0) ? " : " : ":"); - Stringifier::stringify(getValue(it), out, indent + step, step, options); + Stringifier::stringify(getValue(it), out, indent + step, step, options); - if (++it != container.end()) out << ','; + if (++it != container.end()) + out << ','; - if (step > 0) out << std::endl; - } + if (step > 0) + out << std::endl; + } - if (indent >= step) indent -= step; + if (indent >= step) + indent -= step; - for (unsigned int i = 0; i < indent; i++) out << ' '; + for (unsigned int i = 0; i < indent; i++) + out << ' '; - out << '}'; - } + out << '}'; + } - const std::string& getKey(ValueMap::const_iterator& it) const; - const Dynamic::Var& getValue(ValueMap::const_iterator& it) const; - const std::string& getKey(KeyList::const_iterator& it) const; - const Dynamic::Var& getValue(KeyList::const_iterator& it) const; + const std::string & getKey(ValueMap::const_iterator & it) const; + const Dynamic::Var & getValue(ValueMap::const_iterator & it) const; + const std::string & getKey(KeyList::const_iterator & it) const; + const Dynamic::Var & getValue(KeyList::const_iterator & it) const; - ValueMap _values; - KeyList _keys; - bool _preserveInsOrder; - // Note: - // The reason for this flag (rather than as argument to stringify()) is - // because Object can be returned stringified from Dynamic::Var::toString(), - // so it must know whether to escape unicode or not. - bool _escapeUnicode; - mutable StructPtr _pStruct; - mutable bool _modified; -}; + ValueMap _values; + KeyList _keys; + bool _preserveInsOrder; + // Note: + // The reason for this flag (rather than as argument to stringify()) is + // because Object can be returned stringified from Dynamic::Var::toString(), + // so it must know whether to escape unicode or not. + bool _escapeUnicode; + mutable StructPtr _pStruct; + mutable bool _modified; + }; -// -// inlines -// + // + // inlines + // + + inline void Object::setEscapeUnicode(bool escape) + { + _escapeUnicode = escape; + } + + + inline bool Object::getEscapeUnicode() const + { + return _escapeUnicode; + } + + + inline Object::Iterator Object::begin() + { + return _values.begin(); + } + + + inline Object::ConstIterator Object::begin() const + { + return _values.begin(); + } + + + inline Object::Iterator Object::end() + { + return _values.end(); + } + + + inline Object::ConstIterator Object::end() const + { + return _values.end(); + } + + + inline bool Object::has(const std::string & key) const + { + ValueMap::const_iterator it = _values.find(key); + return it != _values.end(); + } + + + inline bool Object::isArray(const std::string & key) const + { + ValueMap::const_iterator it = _values.find(key); + return isArray(it); + } + + + inline bool Object::isArray(ConstIterator & it) const + { + return it != _values.end() && (it->second.type() == typeid(Array::Ptr) || it->second.type() == typeid(Array)); + } + + + inline bool Object::isNull(const std::string & key) const + { + ValueMap::const_iterator it = _values.find(key); + return it == _values.end() || it->second.isEmpty(); + } + + + inline bool Object::isObject(const std::string & key) const + { + ValueMap::const_iterator it = _values.find(key); + return isObject(it); + } + + + inline bool Object::isObject(ConstIterator & it) const + { + return it != _values.end() && (it->second.type() == typeid(Object::Ptr) || it->second.type() == typeid(Object)); + } + + + inline std::size_t Object::size() const + { + return static_cast(_values.size()); + } + + + inline void Object::remove(const std::string & key) + { + _values.erase(key); + if (_preserveInsOrder) + { + KeyList::iterator it = _keys.begin(); + KeyList::iterator end = _keys.end(); + for (; it != end; ++it) + { + if (key == (*it)->first) + { + _keys.erase(it); + break; + } + } + } + _modified = true; + } + + + inline const std::string & Object::getKey(ValueMap::const_iterator & it) const + { + return it->first; + } + + + inline const Dynamic::Var & Object::getValue(ValueMap::const_iterator & it) const + { + return it->second; + } + + + inline const Dynamic::Var & Object::getValue(KeyList::const_iterator & it) const + { + ValueMap::const_iterator itv = _values.find((*it)->first); + if (itv != _values.end()) + return itv->second; + else + throw Poco::NotFoundException(); + } + -inline void Object::setEscapeUnicode(bool escape) -{ - _escapeUnicode = escape; } +} // namespace Poco::JSON -inline bool Object::getEscapeUnicode() const +namespace Poco { - return _escapeUnicode; +namespace Dynamic +{ + + + template <> + class VarHolderImpl : public VarHolder + { + public: + VarHolderImpl(const JSON::Object::Ptr & val) : _val(val) { } + + ~VarHolderImpl() { } + + const std::type_info & type() const { return typeid(JSON::Object::Ptr); } + + void convert(Int8 &) const { throw BadCastException(); } + + void convert(Int16 &) const { throw BadCastException(); } + + void convert(Int32 &) const { throw BadCastException(); } + + void convert(Int64 &) const { throw BadCastException(); } + + void convert(UInt8 &) const { throw BadCastException(); } + + void convert(UInt16 &) const { throw BadCastException(); } + + void convert(UInt32 &) const { throw BadCastException(); } + + void convert(UInt64 &) const { throw BadCastException(); } + + void convert(bool & value) const { value = !_val.isNull() && _val->size() > 0; } + + void convert(float &) const { throw BadCastException(); } + + void convert(double &) const { throw BadCastException(); } + + void convert(char &) const { throw BadCastException(); } + + void convert(std::string & s) const + { + std::ostringstream oss; + _val->stringify(oss, 2); + s = oss.str(); + } + + void convert(DateTime & /*val*/) const + { + //TODO: val = _val; + throw NotImplementedException("Conversion not implemented: JSON:Object => DateTime"); + } + + void convert(LocalDateTime & /*ldt*/) const + { + //TODO: ldt = _val.timestamp(); + throw NotImplementedException("Conversion not implemented: JSON:Object => LocalDateTime"); + } + + void convert(Timestamp & /*ts*/) const + { + //TODO: ts = _val.timestamp(); + throw NotImplementedException("Conversion not implemented: JSON:Object => Timestamp"); + } + + VarHolder * clone(Placeholder * pVarHolder = 0) const { return cloneHolder(pVarHolder, _val); } + + const JSON::Object::Ptr & value() const { return _val; } + + bool isArray() const { return false; } + + bool isInteger() const { return false; } + + bool isSigned() const { return false; } + + bool isNumeric() const { return false; } + + bool isString() const { return false; } + + private: + JSON::Object::Ptr _val; + }; + + + template <> + class VarHolderImpl : public VarHolder + { + public: + VarHolderImpl(const JSON::Object & val) : _val(val) { } + + ~VarHolderImpl() { } + + const std::type_info & type() const { return typeid(JSON::Object); } + + void convert(Int8 &) const { throw BadCastException(); } + + void convert(Int16 &) const { throw BadCastException(); } + + void convert(Int32 &) const { throw BadCastException(); } + + void convert(Int64 &) const { throw BadCastException(); } + + void convert(UInt8 &) const { throw BadCastException(); } + + void convert(UInt16 &) const { throw BadCastException(); } + + void convert(UInt32 &) const { throw BadCastException(); } + + void convert(UInt64 &) const { throw BadCastException(); } + + void convert(bool & value) const { value = _val.size() > 0; } + + void convert(float &) const { throw BadCastException(); } + + void convert(double &) const { throw BadCastException(); } + + void convert(char &) const { throw BadCastException(); } + + void convert(std::string & s) const + { + std::ostringstream oss; + _val.stringify(oss, 2); + s = oss.str(); + } + + void convert(DateTime & /*val*/) const + { + //TODO: val = _val; + throw NotImplementedException("Conversion not implemented: JSON:Object => DateTime"); + } + + void convert(LocalDateTime & /*ldt*/) const + { + //TODO: ldt = _val.timestamp(); + throw NotImplementedException("Conversion not implemented: JSON:Object => LocalDateTime"); + } + + void convert(Timestamp & /*ts*/) const + { + //TODO: ts = _val.timestamp(); + throw NotImplementedException("Conversion not implemented: JSON:Object => Timestamp"); + } + + VarHolder * clone(Placeholder * pVarHolder = 0) const { return cloneHolder(pVarHolder, _val); } + + const JSON::Object & value() const { return _val; } + + bool isArray() const { return false; } + + bool isInteger() const { return false; } + + bool isSigned() const { return false; } + + bool isNumeric() const { return false; } + + bool isString() const { return false; } + + private: + JSON::Object _val; + }; + + } - - -inline Object::Iterator Object::begin() -{ - return _values.begin(); -} - - -inline Object::ConstIterator Object::begin() const -{ - return _values.begin(); -} - - -inline Object::Iterator Object::end() -{ - return _values.end(); -} - - -inline Object::ConstIterator Object::end() const -{ - return _values.end(); -} - - -inline bool Object::has(const std::string& key) const -{ - ValueMap::const_iterator it = _values.find(key); - return it != _values.end(); -} - - -inline bool Object::isArray(const std::string& key) const -{ - ValueMap::const_iterator it = _values.find(key); - return isArray(it); -} - - -inline bool Object::isArray(ConstIterator& it) const -{ - return it != _values.end() && (it->second.type() == typeid(Array::Ptr) || it->second.type() == typeid(Array)); -} - - -inline bool Object::isNull(const std::string& key) const -{ - ValueMap::const_iterator it = _values.find(key); - return it == _values.end() || it->second.isEmpty(); -} - - -inline bool Object::isObject(const std::string& key) const -{ - ValueMap::const_iterator it = _values.find(key); - return isObject(it); -} - - -inline bool Object::isObject(ConstIterator& it) const -{ - return it != _values.end() && (it->second.type() == typeid(Object::Ptr) || it->second.type() == typeid(Object)); -} - - -inline std::size_t Object::size() const -{ - return static_cast(_values.size()); -} - - -inline void Object::remove(const std::string& key) -{ - _values.erase(key); - if (_preserveInsOrder) - { - KeyList::iterator it = _keys.begin(); - KeyList::iterator end = _keys.end(); - for (; it != end; ++it) - { - if (key == (*it)->first) - { - _keys.erase(it); - break; - } - } - } - _modified = true; -} - - -inline const std::string& Object::getKey(ValueMap::const_iterator& it) const -{ - return it->first; -} - - -inline const Dynamic::Var& Object::getValue(ValueMap::const_iterator& it) const -{ - return it->second; -} - - -inline const Dynamic::Var& Object::getValue(KeyList::const_iterator& it) const -{ - ValueMap::const_iterator itv = _values.find((*it)->first); - if (itv != _values.end()) - return itv->second; - else - throw Poco::NotFoundException(); -} - - -} } // namespace Poco::JSON - - -namespace Poco { -namespace Dynamic { - - -template <> -class VarHolderImpl: public VarHolder -{ -public: - VarHolderImpl(const JSON::Object::Ptr& val): _val(val) - { - } - - ~VarHolderImpl() - { - } - - const std::type_info& type() const - { - return typeid(JSON::Object::Ptr); - } - - void convert(Int8&) const - { - throw BadCastException(); - } - - void convert(Int16&) const - { - throw BadCastException(); - } - - void convert(Int32&) const - { - throw BadCastException(); - } - - void convert(Int64&) const - { - throw BadCastException(); - } - - void convert(UInt8&) const - { - throw BadCastException(); - } - - void convert(UInt16&) const - { - throw BadCastException(); - } - - void convert(UInt32&) const - { - throw BadCastException(); - } - - void convert(UInt64&) const - { - throw BadCastException(); - } - - void convert(bool& value) const - { - value = !_val.isNull() && _val->size() > 0; - } - - void convert(float&) const - { - throw BadCastException(); - } - - void convert(double&) const - { - throw BadCastException(); - } - - void convert(char&) const - { - throw BadCastException(); - } - - void convert(std::string& s) const - { - std::ostringstream oss; - _val->stringify(oss, 2); - s = oss.str(); - } - - void convert(DateTime& /*val*/) const - { - //TODO: val = _val; - throw NotImplementedException("Conversion not implemented: JSON:Object => DateTime"); - } - - void convert(LocalDateTime& /*ldt*/) const - { - //TODO: ldt = _val.timestamp(); - throw NotImplementedException("Conversion not implemented: JSON:Object => LocalDateTime"); - } - - void convert(Timestamp& /*ts*/) const - { - //TODO: ts = _val.timestamp(); - throw NotImplementedException("Conversion not implemented: JSON:Object => Timestamp"); - } - - VarHolder* clone(Placeholder* pVarHolder = 0) const - { - return cloneHolder(pVarHolder, _val); - } - - const JSON::Object::Ptr& value() const - { - return _val; - } - - bool isArray() const - { - return false; - } - - bool isInteger() const - { - return false; - } - - bool isSigned() const - { - return false; - } - - bool isNumeric() const - { - return false; - } - - bool isString() const - { - return false; - } - -private: - JSON::Object::Ptr _val; -}; - - -template <> -class VarHolderImpl: public VarHolder -{ -public: - VarHolderImpl(const JSON::Object& val): _val(val) - { - } - - ~VarHolderImpl() - { - } - - const std::type_info& type() const - { - return typeid(JSON::Object); - } - - void convert(Int8&) const - { - throw BadCastException(); - } - - void convert(Int16&) const - { - throw BadCastException(); - } - - void convert(Int32&) const - { - throw BadCastException(); - } - - void convert(Int64&) const - { - throw BadCastException(); - } - - void convert(UInt8&) const - { - throw BadCastException(); - } - - void convert(UInt16&) const - { - throw BadCastException(); - } - - void convert(UInt32&) const - { - throw BadCastException(); - } - - void convert(UInt64&) const - { - throw BadCastException(); - } - - void convert(bool& value) const - { - value = _val.size() > 0; - } - - void convert(float&) const - { - throw BadCastException(); - } - - void convert(double&) const - { - throw BadCastException(); - } - - void convert(char&) const - { - throw BadCastException(); - } - - void convert(std::string& s) const - { - std::ostringstream oss; - _val.stringify(oss, 2); - s = oss.str(); - } - - void convert(DateTime& /*val*/) const - { - //TODO: val = _val; - throw NotImplementedException("Conversion not implemented: JSON:Object => DateTime"); - } - - void convert(LocalDateTime& /*ldt*/) const - { - //TODO: ldt = _val.timestamp(); - throw NotImplementedException("Conversion not implemented: JSON:Object => LocalDateTime"); - } - - void convert(Timestamp& /*ts*/) const - { - //TODO: ts = _val.timestamp(); - throw NotImplementedException("Conversion not implemented: JSON:Object => Timestamp"); - } - - VarHolder* clone(Placeholder* pVarHolder = 0) const - { - return cloneHolder(pVarHolder, _val); - } - - const JSON::Object& value() const - { - return _val; - } - - bool isArray() const - { - return false; - } - - bool isInteger() const - { - return false; - } - - bool isSigned() const - { - return false; - } - - bool isNumeric() const - { - return false; - } - - bool isString() const - { - return false; - } - -private: - JSON::Object _val; -}; - - -} } // namespace Poco::Dynamic +} // namespace Poco::Dynamic #endif // JSON_Object_INCLUDED diff --git a/base/poco/JSON/include/Poco/JSON/ParseHandler.h b/base/poco/JSON/include/Poco/JSON/ParseHandler.h index 98cd69ed89d..4669dc8638f 100644 --- a/base/poco/JSON/include/Poco/JSON/ParseHandler.h +++ b/base/poco/JSON/include/Poco/JSON/ParseHandler.h @@ -18,152 +18,155 @@ #define JSON_ParseHandler_INCLUDED -#include "Poco/JSON/Handler.h" #include +#include "Poco/JSON/Handler.h" -namespace Poco { -namespace JSON { - - -class JSON_API ParseHandler: public Handler - /// ParseHandler is the default handler for the JSON Parser. - /// - /// This handler will construct an Object or Array based - /// on the handlers called by the Parser. +namespace Poco +{ +namespace JSON { -public: - ParseHandler(bool preserveObjectOrder = false); - /// Creates the ParseHandler. - /// - /// If preserveObjectOrder is true, the order of properties - /// inside objects is preserved. Otherwise, items - /// will be sorted by keys. - virtual ~ParseHandler(); - /// Destroys the ParseHandler. - virtual void reset(); - /// Resets the handler state. - - void startObject(); - /// Handles a '{'; a new object is started. + class JSON_API ParseHandler : public Handler + /// ParseHandler is the default handler for the JSON Parser. + /// + /// This handler will construct an Object or Array based + /// on the handlers called by the Parser. + { + public: + ParseHandler(bool preserveObjectOrder = false); + /// Creates the ParseHandler. + /// + /// If preserveObjectOrder is true, the order of properties + /// inside objects is preserved. Otherwise, items + /// will be sorted by keys. - void endObject(); - /// Handles a '}'; the object is closed. + virtual ~ParseHandler(); + /// Destroys the ParseHandler. - void startArray(); - /// Handles a '['; a new array is started. + virtual void reset(); + /// Resets the handler state. - void endArray(); - /// Handles a ']'; the array is closed. + void startObject(); + /// Handles a '{'; a new object is started. - void key(const std::string& k); - /// A key is read + void endObject(); + /// Handles a '}'; the object is closed. - Dynamic::Var asVar() const; - /// Returns the result of the parser (an object or an array). + void startArray(); + /// Handles a '['; a new array is started. - virtual void value(int v); - /// An integer value is read + void endArray(); + /// Handles a ']'; the array is closed. - virtual void value(unsigned v); - /// An unsigned value is read. This will only be triggered if the - /// value cannot fit into a signed int. + void key(const std::string & k); + /// A key is read + + Dynamic::Var asVar() const; + /// Returns the result of the parser (an object or an array). + + virtual void value(int v); + /// An integer value is read + + virtual void value(unsigned v); + /// An unsigned value is read. This will only be triggered if the + /// value cannot fit into a signed int. #if defined(POCO_HAVE_INT64) - virtual void value(Int64 v); - /// A 64-bit integer value is read + virtual void value(Int64 v); + /// A 64-bit integer value is read - virtual void value(UInt64 v); - /// An unsigned 64-bit integer value is read. This will only be - /// triggered if the value cannot fit into a signed 64-bit integer. + virtual void value(UInt64 v); + /// An unsigned 64-bit integer value is read. This will only be + /// triggered if the value cannot fit into a signed 64-bit integer. #endif - virtual void value(const std::string& s); - /// A string value is read. + virtual void value(const std::string & s); + /// A string value is read. - virtual void value(double d); - /// A double value is read. + virtual void value(double d); + /// A double value is read. - virtual void value(bool b); - /// A boolean value is read. + virtual void value(bool b); + /// A boolean value is read. - virtual void null(); - /// A null value is read. + virtual void null(); + /// A null value is read. -private: - void setValue(const Poco::Dynamic::Var& value); - typedef std::stack Stack; + private: + void setValue(const Poco::Dynamic::Var & value); + typedef std::stack Stack; - Stack _stack; - std::string _key; - Dynamic::Var _result; - bool _preserveObjectOrder; -}; + Stack _stack; + std::string _key; + Dynamic::Var _result; + bool _preserveObjectOrder; + }; -// -// inlines -// -inline Dynamic::Var ParseHandler::asVar() const -{ - return _result; -} + // + // inlines + // + inline Dynamic::Var ParseHandler::asVar() const + { + return _result; + } -inline void ParseHandler::value(int v) -{ - setValue(v); -} + inline void ParseHandler::value(int v) + { + setValue(v); + } -inline void ParseHandler::value(unsigned v) -{ - setValue(v); -} + inline void ParseHandler::value(unsigned v) + { + setValue(v); + } #if defined(POCO_HAVE_INT64) -inline void ParseHandler::value(Int64 v) -{ - setValue(v); -} + inline void ParseHandler::value(Int64 v) + { + setValue(v); + } -inline void ParseHandler::value(UInt64 v) -{ - setValue(v); -} + inline void ParseHandler::value(UInt64 v) + { + setValue(v); + } #endif -inline void ParseHandler::value(const std::string& s) -{ - setValue(s); + inline void ParseHandler::value(const std::string & s) + { + setValue(s); + } + + + inline void ParseHandler::value(double d) + { + setValue(d); + } + + + inline void ParseHandler::value(bool b) + { + setValue(b); + } + + + inline void ParseHandler::null() + { + Poco::Dynamic::Var empty; + setValue(empty); + } + + } - - -inline void ParseHandler::value(double d) -{ - setValue(d); -} - - -inline void ParseHandler::value(bool b) -{ - setValue(b); -} - - -inline void ParseHandler::null() -{ - Poco::Dynamic::Var empty; - setValue(empty); -} - - -} } // namespace Poco::JSON +} // namespace Poco::JSON #endif // JSON_ParseHandler_INCLUDED diff --git a/base/poco/JSON/include/Poco/JSON/Parser.h b/base/poco/JSON/include/Poco/JSON/Parser.h index 592ddabc320..9a20032603e 100644 --- a/base/poco/JSON/include/Poco/JSON/Parser.h +++ b/base/poco/JSON/include/Poco/JSON/Parser.h @@ -18,186 +18,188 @@ #define JSON_JSONParser_INCLUDED -#include "Poco/JSON/JSON.h" -#include "Poco/JSON/ParserImpl.h" -#include "Poco/JSON/Object.h" -#include "Poco/JSON/Array.h" -#include "Poco/JSON/ParseHandler.h" -#include "Poco/JSON/JSONException.h" -#include "Poco/UTF8Encoding.h" -#include "Poco/Dynamic/Var.h" #include +#include "Poco/Dynamic/Var.h" +#include "Poco/JSON/Array.h" +#include "Poco/JSON/JSON.h" +#include "Poco/JSON/JSONException.h" +#include "Poco/JSON/Object.h" +#include "Poco/JSON/ParseHandler.h" +#include "Poco/JSON/ParserImpl.h" +#include "Poco/UTF8Encoding.h" -namespace Poco { -namespace JSON { - - -class JSON_API Parser: private ParserImpl - /// A parser for reading RFC 4627 compliant JSON from strings or streams. - /// - /// Simple usage example: - /// - /// std::string json = "{ \"name\" : \"Franky\", \"children\" : [ \"Jonas\", \"Ellen\" ] }"; - /// Parser parser; - /// Var result = parser.parse(json); - /// // ... use result (see next example) - /// parser.reset(); - /// std::ostringstream ostr; - /// PrintHandler::Ptr pHandler = new PrintHandler(ostr); - /// parser.setHandler(pHandler); - /// parser.parse(json); // ostr.str() == json - /// ---- - /// - /// The result of parsing a valid JSON document will be either an Object - /// or an Array. Therefore the result of parse() is a Poco::Dynamic::Var - /// containing a Poco::SharedPtr to an Object or Array instance. - /// - /// Example: - /// - /// std::string json = "{ \"name\" : \"Franky\", \"children\" : [ \"Jonas\", \"Ellen\" ] }"; - /// Parser parser; - /// Var result = parser.parse(json); - /// Object::Ptr object = result.extract(); - /// std::string name = object.getValue("name"); - /// Array::Ptr children = object.getArray("children"); - /// ---- +namespace Poco { -public: - - Parser(const Handler::Ptr& pHandler = new ParseHandler, std::size_t bufSize = JSON_PARSE_BUFFER_SIZE); - /// Creates JSON Parser, using the given Handler and buffer size. - - virtual ~Parser(); - /// Destroys JSON Parser. - - void reset(); - /// Resets the parser. - - void setAllowComments(bool comments); - /// Allow or disallow comments. By default, comments are not allowed. - - bool getAllowComments() const; - /// Returns true if comments are allowed, false otherwise. - /// - /// By default, comments are not allowed. - - void setAllowNullByte(bool nullByte); - /// Allow or disallow null byte in strings. - /// - /// By default, null byte is allowed. - - bool getAllowNullByte() const; - /// Returns true if null byte is allowed, false otherwise. - /// - /// By default, null bytes are allowed. - - void setDepth(std::size_t depth); - /// Sets the allowed JSON depth. - - std::size_t getDepth() const; - /// Returns the allowed JSON depth. - - Dynamic::Var parse(const std::string& json); - /// Parses JSON from a string. - - Dynamic::Var parse(std::istream& in); - /// Parses JSON from an input stream. - - void setHandler(const Handler::Ptr& pHandler); - /// Set the Handler. - - const Handler::Ptr& getHandler(); - /// Returns the Handler. - - Dynamic::Var asVar() const; - /// Returns the result of parsing; - - Dynamic::Var result() const; - /// Returns the result of parsing as Dynamic::Var; - -private: - Parser(const Parser&); - Parser& operator = (const Parser&); -}; - - -// -// inlines -// -inline void Parser::setAllowComments(bool comments) +namespace JSON { - setAllowCommentsImpl(comments); + + + class JSON_API Parser : private ParserImpl + /// A parser for reading RFC 4627 compliant JSON from strings or streams. + /// + /// Simple usage example: + /// + /// std::string json = "{ \"name\" : \"Franky\", \"children\" : [ \"Jonas\", \"Ellen\" ] }"; + /// Parser parser; + /// Var result = parser.parse(json); + /// // ... use result (see next example) + /// parser.reset(); + /// std::ostringstream ostr; + /// PrintHandler::Ptr pHandler = new PrintHandler(ostr); + /// parser.setHandler(pHandler); + /// parser.parse(json); // ostr.str() == json + /// ---- + /// + /// The result of parsing a valid JSON document will be either an Object + /// or an Array. Therefore the result of parse() is a Poco::Dynamic::Var + /// containing a Poco::SharedPtr to an Object or Array instance. + /// + /// Example: + /// + /// std::string json = "{ \"name\" : \"Franky\", \"children\" : [ \"Jonas\", \"Ellen\" ] }"; + /// Parser parser; + /// Var result = parser.parse(json); + /// Object::Ptr object = result.extract(); + /// std::string name = object.getValue("name"); + /// Array::Ptr children = object.getArray("children"); + /// ---- + { + public: + Parser(const Handler::Ptr & pHandler = new ParseHandler, std::size_t bufSize = JSON_PARSE_BUFFER_SIZE); + /// Creates JSON Parser, using the given Handler and buffer size. + + virtual ~Parser(); + /// Destroys JSON Parser. + + void reset(); + /// Resets the parser. + + void setAllowComments(bool comments); + /// Allow or disallow comments. By default, comments are not allowed. + + bool getAllowComments() const; + /// Returns true if comments are allowed, false otherwise. + /// + /// By default, comments are not allowed. + + void setAllowNullByte(bool nullByte); + /// Allow or disallow null byte in strings. + /// + /// By default, null byte is allowed. + + bool getAllowNullByte() const; + /// Returns true if null byte is allowed, false otherwise. + /// + /// By default, null bytes are allowed. + + void setDepth(std::size_t depth); + /// Sets the allowed JSON depth. + + std::size_t getDepth() const; + /// Returns the allowed JSON depth. + + Dynamic::Var parse(const std::string & json); + /// Parses JSON from a string. + + Dynamic::Var parse(std::istream & in); + /// Parses JSON from an input stream. + + void setHandler(const Handler::Ptr & pHandler); + /// Set the Handler. + + const Handler::Ptr & getHandler(); + /// Returns the Handler. + + Dynamic::Var asVar() const; + /// Returns the result of parsing; + + Dynamic::Var result() const; + /// Returns the result of parsing as Dynamic::Var; + + private: + Parser(const Parser &); + Parser & operator=(const Parser &); + }; + + + // + // inlines + // + inline void Parser::setAllowComments(bool comments) + { + setAllowCommentsImpl(comments); + } + + + inline bool Parser::getAllowComments() const + { + return getAllowCommentsImpl(); + } + + + inline void Parser::setAllowNullByte(bool nullByte) + { + setAllowNullByteImpl(nullByte); + } + + + inline bool Parser::getAllowNullByte() const + { + return getAllowNullByteImpl(); + } + + + inline void Parser::setDepth(std::size_t depth) + { + setDepthImpl(depth); + } + + + inline std::size_t Parser::getDepth() const + { + return getDepthImpl(); + } + + + inline const Handler::Ptr & Parser::getHandler() + { + return getHandlerImpl(); + } + + + inline Dynamic::Var Parser::result() const + { + return resultImpl(); + } + + + inline Dynamic::Var Parser::asVar() const + { + return asVarImpl(); + } + + + inline void Parser::reset() + { + resetImpl(); + } + + + inline Dynamic::Var Parser::parse(const std::string & json) + { + return parseImpl(json); + } + + + inline Dynamic::Var Parser::parse(std::istream & in) + { + return parseImpl(in); + } + + } - - -inline bool Parser::getAllowComments() const -{ - return getAllowCommentsImpl(); -} - - -inline void Parser::setAllowNullByte(bool nullByte) -{ - setAllowNullByteImpl(nullByte); -} - - -inline bool Parser::getAllowNullByte() const -{ - return getAllowNullByteImpl(); -} - - -inline void Parser::setDepth(std::size_t depth) -{ - setDepthImpl(depth); -} - - -inline std::size_t Parser::getDepth() const -{ - return getDepthImpl(); -} - - -inline const Handler::Ptr& Parser::getHandler() -{ - return getHandlerImpl(); -} - - -inline Dynamic::Var Parser::result() const -{ - return resultImpl(); -} - - -inline Dynamic::Var Parser::asVar() const -{ - return asVarImpl(); -} - - -inline void Parser::reset() -{ - resetImpl(); -} - - -inline Dynamic::Var Parser::parse(const std::string& json) -{ - return parseImpl(json); -} - - -inline Dynamic::Var Parser::parse(std::istream& in) -{ - return parseImpl(in); -} - - -} } // namespace Poco::JSON +} // namespace Poco::JSON #endif // JSON_JSONParser_INCLUDED diff --git a/base/poco/JSON/include/Poco/JSON/ParserImpl.h b/base/poco/JSON/include/Poco/JSON/ParserImpl.h index dd92fe84e67..7a8ea647180 100644 --- a/base/poco/JSON/include/Poco/JSON/ParserImpl.h +++ b/base/poco/JSON/include/Poco/JSON/ParserImpl.h @@ -18,177 +18,182 @@ #define JSON_JSONParserImpl_INCLUDED -#include "Poco/JSON/JSON.h" -#include "Poco/JSON/Object.h" -#include "Poco/JSON/Array.h" -#include "Poco/JSON/ParseHandler.h" -#include "Poco/JSON/JSONException.h" -#include "Poco/UTF8Encoding.h" -#include "Poco/Dynamic/Var.h" #include +#include "Poco/Dynamic/Var.h" +#include "Poco/JSON/Array.h" +#include "Poco/JSON/JSON.h" +#include "Poco/JSON/JSONException.h" +#include "Poco/JSON/Object.h" +#include "Poco/JSON/ParseHandler.h" +#include "Poco/UTF8Encoding.h" struct json_stream; -namespace Poco { -namespace JSON { - - -class JSON_API ParserImpl +namespace Poco { -protected: - static const std::size_t JSON_PARSE_BUFFER_SIZE = 4096; - static const std::size_t JSON_PARSER_STACK_SIZE = 128; - static const int JSON_UNLIMITED_DEPTH = -1; - - ParserImpl(const Handler::Ptr& pHandler = new ParseHandler, std::size_t bufSize = JSON_PARSE_BUFFER_SIZE); - /// Creates JSON ParserImpl, using the given Handler and buffer size. - - virtual ~ParserImpl(); - /// Destroys JSON ParserImpl. - - void resetImpl(); - /// Resets the parser. - - void setAllowCommentsImpl(bool comments); - /// Allow or disallow comments. By default, comments are not allowed. - - bool getAllowCommentsImpl() const; - /// Returns true if comments are allowed, false otherwise. - /// - /// By default, comments are not allowed. - - void setAllowNullByteImpl(bool nullByte); - /// Allow or disallow null byte in strings. - /// - /// By default, null byte is allowed. - - bool getAllowNullByteImpl() const; - /// Returns true if null byte is allowed, false otherwise. - /// - /// By default, null bytes are allowed. - - void setDepthImpl(std::size_t depth); - /// Sets the allowed JSON depth. - - std::size_t getDepthImpl() const; - /// Returns the allowed JSON depth. - - Dynamic::Var parseImpl(const std::string& json); - /// Parses JSON from a string. - - Dynamic::Var parseImpl(std::istream& in); - /// Parses JSON from an input stream. - - void setHandlerImpl(const Handler::Ptr& pHandler); - /// Set the Handler. - - const Handler::Ptr& getHandlerImpl(); - /// Returns the Handler. - - Dynamic::Var asVarImpl() const; - /// Returns the result of parsing; - - Dynamic::Var resultImpl() const; - /// Returns the result of parsing as Dynamic::Var; - -private: - ParserImpl(const ParserImpl&); - ParserImpl& operator =(const ParserImpl&); - - void handleArray(); - void handleObject(); - void handle(); - void handle(const std::string& json); - void stripComments(std::string& json); - bool checkError(); - - struct json_stream* _pJSON; - Handler::Ptr _pHandler; - int _depth; - char _decimalPoint; - bool _allowNullByte; - bool _allowComments; -}; - - -// -// inlines -// - -inline void ParserImpl::resetImpl() +namespace JSON { - // currently, json stream is opened and closed on every parse request - // (perhaps there is some optimization room?) - //json_reset(&_json); - if (_pHandler) _pHandler->reset(); + + + class JSON_API ParserImpl + { + protected: + static const std::size_t JSON_PARSE_BUFFER_SIZE = 4096; + static const std::size_t JSON_PARSER_STACK_SIZE = 128; + static const int JSON_UNLIMITED_DEPTH = -1; + + ParserImpl(const Handler::Ptr & pHandler = new ParseHandler, std::size_t bufSize = JSON_PARSE_BUFFER_SIZE); + /// Creates JSON ParserImpl, using the given Handler and buffer size. + + virtual ~ParserImpl(); + /// Destroys JSON ParserImpl. + + void resetImpl(); + /// Resets the parser. + + void setAllowCommentsImpl(bool comments); + /// Allow or disallow comments. By default, comments are not allowed. + + bool getAllowCommentsImpl() const; + /// Returns true if comments are allowed, false otherwise. + /// + /// By default, comments are not allowed. + + void setAllowNullByteImpl(bool nullByte); + /// Allow or disallow null byte in strings. + /// + /// By default, null byte is allowed. + + bool getAllowNullByteImpl() const; + /// Returns true if null byte is allowed, false otherwise. + /// + /// By default, null bytes are allowed. + + void setDepthImpl(std::size_t depth); + /// Sets the allowed JSON depth. + + std::size_t getDepthImpl() const; + /// Returns the allowed JSON depth. + + Dynamic::Var parseImpl(const std::string & json); + /// Parses JSON from a string. + + Dynamic::Var parseImpl(std::istream & in); + /// Parses JSON from an input stream. + + void setHandlerImpl(const Handler::Ptr & pHandler); + /// Set the Handler. + + const Handler::Ptr & getHandlerImpl(); + /// Returns the Handler. + + Dynamic::Var asVarImpl() const; + /// Returns the result of parsing; + + Dynamic::Var resultImpl() const; + /// Returns the result of parsing as Dynamic::Var; + + private: + ParserImpl(const ParserImpl &); + ParserImpl & operator=(const ParserImpl &); + + void handleArray(); + void handleObject(); + void handle(); + void handle(const std::string & json); + void stripComments(std::string & json); + bool checkError(); + + struct json_stream * _pJSON; + Handler::Ptr _pHandler; + int _depth; + char _decimalPoint; + bool _allowNullByte; + bool _allowComments; + }; + + + // + // inlines + // + + inline void ParserImpl::resetImpl() + { + // currently, json stream is opened and closed on every parse request + // (perhaps there is some optimization room?) + //json_reset(&_json); + if (_pHandler) + _pHandler->reset(); + } + + + inline void ParserImpl::setAllowCommentsImpl(bool comments) + { + _allowComments = comments; + } + + + inline bool ParserImpl::getAllowCommentsImpl() const + { + return _allowComments; + } + + + inline void ParserImpl::setAllowNullByteImpl(bool nullByte) + { + _allowNullByte = nullByte; + } + + + inline bool ParserImpl::getAllowNullByteImpl() const + { + return _allowNullByte; + } + + + inline void ParserImpl::setDepthImpl(std::size_t depth) + { + _depth = static_cast(depth); + } + + + inline std::size_t ParserImpl::getDepthImpl() const + { + return static_cast(_depth); + } + + + inline void ParserImpl::setHandlerImpl(const Handler::Ptr & pHandler) + { + _pHandler = pHandler; + } + + + inline const Handler::Ptr & ParserImpl::getHandlerImpl() + { + return _pHandler; + } + + + inline Dynamic::Var ParserImpl::resultImpl() const + { + return asVarImpl(); + } + + + inline Dynamic::Var ParserImpl::asVarImpl() const + { + if (_pHandler) + return _pHandler->asVar(); + + return Dynamic::Var(); + } + + } - - -inline void ParserImpl::setAllowCommentsImpl(bool comments) -{ - _allowComments = comments; -} - - -inline bool ParserImpl::getAllowCommentsImpl() const -{ - return _allowComments; -} - - -inline void ParserImpl::setAllowNullByteImpl(bool nullByte) -{ - _allowNullByte = nullByte; -} - - -inline bool ParserImpl::getAllowNullByteImpl() const -{ - return _allowNullByte; -} - - -inline void ParserImpl::setDepthImpl(std::size_t depth) -{ - _depth = static_cast(depth); -} - - -inline std::size_t ParserImpl::getDepthImpl() const -{ - return static_cast(_depth); -} - - -inline void ParserImpl::setHandlerImpl(const Handler::Ptr& pHandler) -{ - _pHandler = pHandler; -} - - -inline const Handler::Ptr& ParserImpl::getHandlerImpl() -{ - return _pHandler; -} - - -inline Dynamic::Var ParserImpl::resultImpl() const -{ - return asVarImpl(); -} - - -inline Dynamic::Var ParserImpl::asVarImpl() const -{ - if (_pHandler) return _pHandler->asVar(); - - return Dynamic::Var(); -} - - -} } // namespace Poco::JSON +} // namespace Poco::JSON #endif // JSON_JSONParserImpl_INCLUDED diff --git a/base/poco/JSON/include/Poco/JSON/PrintHandler.h b/base/poco/JSON/include/Poco/JSON/PrintHandler.h index 620dc52a9a1..34a991653ba 100644 --- a/base/poco/JSON/include/Poco/JSON/PrintHandler.h +++ b/base/poco/JSON/include/Poco/JSON/PrintHandler.h @@ -18,122 +18,125 @@ #define JSON_PrintHandler_INCLUDED -#include "Poco/JSON/JSON.h" #include "Poco/JSON/Handler.h" +#include "Poco/JSON/JSON.h" #include "Poco/JSONString.h" -namespace Poco { -namespace JSON { - - -class JSON_API PrintHandler: public Handler - /// PrintHandler formats and prints the JSON object - /// to either user-provided std::ostream or standard output. - /// If indent is zero, the output is a condensed JSON string, - /// otherwise, the proper indentation is applied to elements. +namespace Poco +{ +namespace JSON { -public: - typedef SharedPtr Ptr; - static const unsigned JSON_PRINT_FLAT = 0; - PrintHandler(unsigned indent = 0, int options = Poco::JSON_WRAP_STRINGS); - /// Creates the PrintHandler. + class JSON_API PrintHandler : public Handler + /// PrintHandler formats and prints the JSON object + /// to either user-provided std::ostream or standard output. + /// If indent is zero, the output is a condensed JSON string, + /// otherwise, the proper indentation is applied to elements. + { + public: + typedef SharedPtr Ptr; - PrintHandler(std::ostream& out, unsigned indent = 0, int options = Poco::JSON_WRAP_STRINGS); - /// Creates the PrintHandler. + static const unsigned JSON_PRINT_FLAT = 0; - ~PrintHandler(); - /// Destroys the PrintHandler. + PrintHandler(unsigned indent = 0, int options = Poco::JSON_WRAP_STRINGS); + /// Creates the PrintHandler. - void reset(); - /// Resets the handler state. + PrintHandler(std::ostream & out, unsigned indent = 0, int options = Poco::JSON_WRAP_STRINGS); + /// Creates the PrintHandler. - void startObject(); - /// The parser has read a '{'; a new object is started. - /// If indent is greater than zero, a newline will be appended. + ~PrintHandler(); + /// Destroys the PrintHandler. - void endObject(); - /// The parser has read a '}'; the object is closed. + void reset(); + /// Resets the handler state. - void startArray(); - /// The parser has read a [; a new array will be started. - /// If indent is greater than zero, a newline will be appended. + void startObject(); + /// The parser has read a '{'; a new object is started. + /// If indent is greater than zero, a newline will be appended. - void endArray(); - /// The parser has read a ]; the array is closed. + void endObject(); + /// The parser has read a '}'; the object is closed. - void key(const std::string& k); - /// A key of an object is read; it will be written to the output, - /// followed by a ':'. If indent is greater than zero, the colon - /// is padded by a space before and after. + void startArray(); + /// The parser has read a [; a new array will be started. + /// If indent is greater than zero, a newline will be appended. - void null(); - /// A null value is read; "null" will be written to the output. + void endArray(); + /// The parser has read a ]; the array is closed. - void value(int v); - /// An integer value is read. + void key(const std::string & k); + /// A key of an object is read; it will be written to the output, + /// followed by a ':'. If indent is greater than zero, the colon + /// is padded by a space before and after. + + void null(); + /// A null value is read; "null" will be written to the output. + + void value(int v); + /// An integer value is read. + + void value(unsigned v); + /// An unsigned value is read. This will only be triggered if the + /// value cannot fit into a signed int. - void value(unsigned v); - /// An unsigned value is read. This will only be triggered if the - /// value cannot fit into a signed int. - #if defined(POCO_HAVE_INT64) - void value(Int64 v); - /// A 64-bit integer value is read; it will be written to the output. + void value(Int64 v); + /// A 64-bit integer value is read; it will be written to the output. - void value(UInt64 v); - /// An unsigned 64-bit integer value is read; it will be written to the output. + void value(UInt64 v); + /// An unsigned 64-bit integer value is read; it will be written to the output. #endif - void value(const std::string& value); - /// A string value is read; it will be formatted and written to the output. + void value(const std::string & value); + /// A string value is read; it will be formatted and written to the output. - void value(double d); - /// A double value is read; it will be written to the output. + void value(double d); + /// A double value is read; it will be written to the output. - void value(bool b); - /// A boolean value is read; it will be written to the output. + void value(bool b); + /// A boolean value is read; it will be written to the output. - void comma(); - /// A comma is read; it will be written to the output as "true" or "false". + void comma(); + /// A comma is read; it will be written to the output as "true" or "false". - void setIndent(unsigned indent); - /// Sets indentation. + void setIndent(unsigned indent); + /// Sets indentation. -private: - const char* endLine() const; - unsigned indent(); - bool printFlat() const; - void arrayValue(); - bool array() const; + private: + const char * endLine() const; + unsigned indent(); + bool printFlat() const; + void arrayValue(); + bool array() const; - std::ostream& _out; - unsigned _indent; - std::string _tab; - int _array; - bool _objStart; - int _options; -}; + std::ostream & _out; + unsigned _indent; + std::string _tab; + int _array; + bool _objStart; + int _options; + }; + + + // + // inlines + // + inline void PrintHandler::setIndent(unsigned indent) + { + _indent = indent; + } + + + inline bool PrintHandler::array() const + { + return _array > 0; + } -// -// inlines -// -inline void PrintHandler::setIndent(unsigned indent) -{ - _indent = indent; } - - -inline bool PrintHandler::array() const -{ - return _array > 0; -} - - -} } // namespace Poco::JSON +} // namespace Poco::JSON #endif // JSON_PrintHandler_INCLUDED diff --git a/base/poco/JSON/include/Poco/JSON/Query.h b/base/poco/JSON/include/Poco/JSON/Query.h index c639a3d7dd9..1b1a95da58c 100644 --- a/base/poco/JSON/include/Poco/JSON/Query.h +++ b/base/poco/JSON/include/Poco/JSON/Query.h @@ -18,108 +18,111 @@ #define JSON_JSONQuery_INCLUDED +#include "Poco/JSON/Array.h" #include "Poco/JSON/JSON.h" #include "Poco/JSON/Object.h" -#include "Poco/JSON/Array.h" -namespace Poco { -namespace JSON { - - -class JSON_API Query - /// Class that can be used to search for a value in a JSON object or array. +namespace Poco +{ +namespace JSON { -public: - Query(const Dynamic::Var& source); - /// Creates a Query/ - /// - /// Source must be JSON Object, Array, Object::Ptr, - /// Array::Ptr or empty Var. Any other type will trigger throwing of - /// InvalidArgumentException. - /// - /// Creating Query holding Ptr will typically result in faster - /// performance. - - virtual ~Query(); - /// Destroys the Query. - - Object::Ptr findObject(const std::string& path) const; - /// Search for an object. - /// - /// When the object can't be found, a zero Ptr is returned; - /// otherwise, a shared pointer to internally held object - /// is returned. - /// If object (as opposed to a pointer to object) is held - /// internally, a shared pointer to new (heap-allocated) Object is - /// returned; this may be expensive operation. - - Object& findObject(const std::string& path, Object& obj) const; - /// Search for an object. - /// - /// If object is found, it is assigned to the - /// Object through the reference passed in. When the object can't be - /// found, the provided Object is emptied and returned. - - Array::Ptr findArray(const std::string& path) const; - /// Search for an array. - /// - /// When the array can't be found, a zero Ptr is returned; - /// otherwise, a shared pointer to internally held array - /// is returned. - /// If array (as opposed to a pointer to array) is held - /// internally, a shared pointer to new (heap-allocated) Object is - /// returned; this may be expensive operation. - - Array& findArray(const std::string& path, Array& obj) const; - /// Search for an array. - /// - /// If array is found, it is assigned to the - /// Object through the reference passed in. When the array can't be - /// found, the provided Object is emptied and returned. - - Dynamic::Var find(const std::string& path) const; - /// Searches a value. - /// - /// Example: "person.children[0].name" will return the - /// the name of the first child. When the value can't be found - /// an empty value is returned. - - template - T findValue(const std::string& path, const T& def) const - /// Searches for a value will convert it to the given type. - /// When the value can't be found or has an invalid type - /// the default value will be returned. - { - T result = def; - Dynamic::Var value = find(path); - if (!value.isEmpty()) - { - try - { - result = value.convert(); - } - catch (...) - { - } - } - return result; - } - - std::string findValue(const char* path, const char* def) const - /// Searches for a value will convert it to the given type. - /// When the value can't be found or has an invalid type - /// the default value will be returned. - { - return findValue(path, def); - } - -private: - Dynamic::Var _source; -}; -} } // namespace Poco::JSON + class JSON_API Query + /// Class that can be used to search for a value in a JSON object or array. + { + public: + Query(const Dynamic::Var & source); + /// Creates a Query/ + /// + /// Source must be JSON Object, Array, Object::Ptr, + /// Array::Ptr or empty Var. Any other type will trigger throwing of + /// InvalidArgumentException. + /// + /// Creating Query holding Ptr will typically result in faster + /// performance. + + virtual ~Query(); + /// Destroys the Query. + + Object::Ptr findObject(const std::string & path) const; + /// Search for an object. + /// + /// When the object can't be found, a zero Ptr is returned; + /// otherwise, a shared pointer to internally held object + /// is returned. + /// If object (as opposed to a pointer to object) is held + /// internally, a shared pointer to new (heap-allocated) Object is + /// returned; this may be expensive operation. + + Object & findObject(const std::string & path, Object & obj) const; + /// Search for an object. + /// + /// If object is found, it is assigned to the + /// Object through the reference passed in. When the object can't be + /// found, the provided Object is emptied and returned. + + Array::Ptr findArray(const std::string & path) const; + /// Search for an array. + /// + /// When the array can't be found, a zero Ptr is returned; + /// otherwise, a shared pointer to internally held array + /// is returned. + /// If array (as opposed to a pointer to array) is held + /// internally, a shared pointer to new (heap-allocated) Object is + /// returned; this may be expensive operation. + + Array & findArray(const std::string & path, Array & obj) const; + /// Search for an array. + /// + /// If array is found, it is assigned to the + /// Object through the reference passed in. When the array can't be + /// found, the provided Object is emptied and returned. + + Dynamic::Var find(const std::string & path) const; + /// Searches a value. + /// + /// Example: "person.children[0].name" will return the + /// the name of the first child. When the value can't be found + /// an empty value is returned. + + template + T findValue(const std::string & path, const T & def) const + /// Searches for a value will convert it to the given type. + /// When the value can't be found or has an invalid type + /// the default value will be returned. + { + T result = def; + Dynamic::Var value = find(path); + if (!value.isEmpty()) + { + try + { + result = value.convert(); + } + catch (...) + { + } + } + return result; + } + + std::string findValue(const char * path, const char * def) const + /// Searches for a value will convert it to the given type. + /// When the value can't be found or has an invalid type + /// the default value will be returned. + { + return findValue(path, def); + } + + private: + Dynamic::Var _source; + }; + + +} +} // namespace Poco::JSON #endif // JSON_JSONQuery_INCLUDED diff --git a/base/poco/JSON/include/Poco/JSON/Stringifier.h b/base/poco/JSON/include/Poco/JSON/Stringifier.h index 8e3303becff..1df2dd38bf9 100644 --- a/base/poco/JSON/include/Poco/JSON/Stringifier.h +++ b/base/poco/JSON/include/Poco/JSON/Stringifier.h @@ -18,56 +18,59 @@ #define JSON_JSONStringifier_INCLUDED +#include +#include "Poco/Dynamic/Var.h" #include "Poco/JSON/JSON.h" #include "Poco/JSONString.h" -#include "Poco/Dynamic/Var.h" -#include -namespace Poco { -namespace JSON { - - -class JSON_API Stringifier - /// Helper class for creating a string from a JSON object or array. +namespace Poco { -public: - static void condense(const Dynamic::Var& any, std::ostream& out, int options = Poco::JSON_WRAP_STRINGS); - /// Writes a condensed string representation of the value to the output stream while preserving - /// the insertion order. - /// - /// If JSON_ESCAPE_UNICODE is in options, all unicode characters will be escaped, otherwise - /// only the compulsory ones. - /// - /// This is just a "shortcut" to stringify(any, out) with name indicating the function effect. - - static void stringify(const Dynamic::Var& any, std::ostream& out, - unsigned int indent = 0, int step = -1, int options = Poco::JSON_WRAP_STRINGS); - /// Writes a string representation of the value to the output stream. - /// - /// When indent is 0, the string will be created as small as possible. - /// Indentation is increased/decreased using number of spaces defined in step. - /// The default value -1 for step indicates that step will be equal to the - /// indent size. - /// - /// If JSON_ESCAPE_UNICODE is in options, all unicode characters will be escaped, otherwise - /// only the compulsory ones. - - static void formatString(const std::string& value, std::ostream& out, int options = Poco::JSON_WRAP_STRINGS); - /// Formats the JSON string and streams it into ostream. - /// - /// If JSON_ESCAPE_UNICODE is in options, all unicode characters will be escaped, otherwise - /// only the compulsory ones. -}; - - -inline void Stringifier::condense(const Dynamic::Var& any, std::ostream& out, int options) +namespace JSON { - stringify(any, out, 0, -1, options); + + + class JSON_API Stringifier + /// Helper class for creating a string from a JSON object or array. + { + public: + static void condense(const Dynamic::Var & any, std::ostream & out, int options = Poco::JSON_WRAP_STRINGS); + /// Writes a condensed string representation of the value to the output stream while preserving + /// the insertion order. + /// + /// If JSON_ESCAPE_UNICODE is in options, all unicode characters will be escaped, otherwise + /// only the compulsory ones. + /// + /// This is just a "shortcut" to stringify(any, out) with name indicating the function effect. + + static void stringify( + const Dynamic::Var & any, std::ostream & out, unsigned int indent = 0, int step = -1, int options = Poco::JSON_WRAP_STRINGS); + /// Writes a string representation of the value to the output stream. + /// + /// When indent is 0, the string will be created as small as possible. + /// Indentation is increased/decreased using number of spaces defined in step. + /// The default value -1 for step indicates that step will be equal to the + /// indent size. + /// + /// If JSON_ESCAPE_UNICODE is in options, all unicode characters will be escaped, otherwise + /// only the compulsory ones. + + static void formatString(const std::string & value, std::ostream & out, int options = Poco::JSON_WRAP_STRINGS); + /// Formats the JSON string and streams it into ostream. + /// + /// If JSON_ESCAPE_UNICODE is in options, all unicode characters will be escaped, otherwise + /// only the compulsory ones. + }; + + + inline void Stringifier::condense(const Dynamic::Var & any, std::ostream & out, int options) + { + stringify(any, out, 0, -1, options); + } + + } - - -} } // namespace Poco::JSON +} // namespace Poco::JSON #endif // JSON_JSONStringifier_INCLUDED diff --git a/base/poco/JSON/include/Poco/JSON/Template.h b/base/poco/JSON/include/Poco/JSON/Template.h index 7e8ac51e034..b9ca25d616f 100644 --- a/base/poco/JSON/include/Poco/JSON/Template.h +++ b/base/poco/JSON/include/Poco/JSON/Template.h @@ -18,134 +18,137 @@ #define JSON_JSONTemplate_INCLUDED -#include "Poco/JSON/JSON.h" -#include "Poco/Dynamic/Var.h" -#include "Poco/SharedPtr.h" -#include "Poco/Path.h" -#include "Poco/Timestamp.h" #include #include +#include "Poco/Dynamic/Var.h" +#include "Poco/JSON/JSON.h" +#include "Poco/Path.h" +#include "Poco/SharedPtr.h" +#include "Poco/Timestamp.h" -namespace Poco { -namespace JSON { - - -class MultiPart; - - -POCO_DECLARE_EXCEPTION(JSON_API, JSONTemplateException, Poco::Exception) - - -class JSON_API Template - /// Template is a template engine which uses JSON as input - /// for generating output. There are commands for - /// looping over JSON arrays, include other templates, - /// conditional output, etc. - /// - /// All text is send to the outputstream. A command is placed - /// between - /// - /// ---- - /// - /// These are the available commands: - /// - /// - /// ---- - /// The result of the query is send to the output stream - /// This command can also be written as - /// - /// - /// ---- - /// When the result of query is true, all the text between - /// if and else (or endif when there is no else) is send to the - /// output stream. When the result of query is false, all the text - /// between else and endif is send to the output stream. An empty - /// object, an empty array or a null value is considered as a false value. - /// For numbers a zero is false. An empty String is also false. - /// - /// - /// ---- - /// This can be used to check the existence of the value. - /// Use this for example when a zero value is ok (which returns false for . - /// - /// - /// ---- - /// The result of the query must be an array. For each element - /// in the array the text between for and endfor is send to the - /// output stream. The active element is stored in the variable. - /// - /// - /// ---- - /// Includes a template. When the filename is relative it will try - /// to resolve the filename against the active template. When this - /// file doesn't exist, it can still be found when the JSONTemplateCache - /// is used. - /// - /// A query is passed to Poco::JSON::Query to get the value. +namespace Poco { -public: - typedef SharedPtr