diff options
Diffstat (limited to 'python')
222 files changed, 9895 insertions, 8325 deletions
diff --git a/python/BuildInstructionsLinuxOSX.md b/python/BuildInstructionsLinuxOSX.md index a3756e1f0b2..dad1e2ef772 100644 --- a/python/BuildInstructionsLinuxOSX.md +++ b/python/BuildInstructionsLinuxOSX.md @@ -18,25 +18,18 @@ Ice for Python supports Python versions 2.6, 2.7, and 3.5. Note however that your Python installation must have been built with a C++ compiler that is compatible with the one used to build Ice for C++. -### Ice Development Kit +## Building the Python Extension -You will need the Ice development kit for C++, which you can install as a binary -distribution or compile from source yourself. +The build of Ice for Python requires to first build Ice for C++ in the `cpp` +subdirectory. -## Building the Python Extension +Edit `config/Make.rules` to establish your build configuration. The comments in +the file provide more information. Change to the Ice for Python source subdirectory: $ cd python -If you have not built Ice for C++ in the `cpp` subdirectory, set `ICE_HOME` to -the directory of your Ice for C++ installation. For example: - - $ export ICE_HOME=/opt/Ice - -Edit `config/Make.rules`, modify the installation prefix (if necessary), and -review the comments describing the `PYTHON_VERSION` variable. - Execute `python -V` to verify that the correct Python interpreter is in your executable search path. @@ -63,4 +56,4 @@ If everything worked out, you should see lots of `ok` messages. In case of a failure, the tests abort with `failed`. [1]: https://zeroc.com/download.html -[2]: https://doc.zeroc.com/display/Ice36/Supported+Platforms+for+Ice+3.6.3 +[2]: https://doc.zeroc.com/display/Ice37/Supported+Platforms+for+Ice+3.7.0 diff --git a/python/BuildInstructionsWindows.md b/python/BuildInstructionsWindows.md index fc49bac1c0b..21e3630db9c 100644 --- a/python/BuildInstructionsWindows.md +++ b/python/BuildInstructionsWindows.md @@ -12,53 +12,81 @@ Ice for Python is expected to build and run properly on Windows and was extensively tested using the operating systems and compiler versions listed for our [supported platforms][2]. +The build requires the [Ice Builder for Visual Studio][8], you must install +version 4.2.0 or greater to build Ice. + ### Python Versions -Ice for Python supports Python versions 2.6, 2.7, and 3.5. Note however that -your Python installation must have been built with a C++ compiler that is +Ice for Python supports Python versions 2.6, 2.7, 3.3, 3.4 or 3.5. Note however +that your Python installation must have been built with a C++ compiler that is compatible with the one used to build Ice for C++. -### Ice Development Kit - -You will need the Ice development kit for C++, which you can install as a binary -distribution or compile from source yourself. - ## Building the Python Extension The Python interpreter is readily available on Windows platforms. You can build it yourself using Microsoft Visual C++, or obtain a binary distribution from the Python web site. The Python 3.5.x binary distribution is compiled with Visual -C++ 14, Python 3.4.x and Python 2.7.x are compiled with Visual C++ 10, you should -compile the Ice extension with the same Visual C++ version that your Python binary -distribution was compiled. +C++ 14, Python 3.4.x and Python 2.7.x are compiled with Visual C++ 10, you +should compile the Ice extension with the same Visual C++ version that your +Python binary distribution was compiled. -Open a command prompt that supports command-line compilation with Visual C++. -For example, you can execute the Visual C++ batch file `vcvars32.bat` to -configure your environment. Alternatively, you can start a Visual Studio Command -Prompt by selecting the appropriate entry from the Visual Studio program group -in your Start menu. +Using the first configurations produces 32-bit binaries, while the second +configurations produce 64-bit binaries. Change to the Ice for Python source subdirectory: > cd python -If you have not built Ice for C++ from the `cpp` subdirectory, set `ICE_HOME` -to the directory of your Ice for C++ installation. For example: +You must built Ice for C++ from the `cpp` subdirectory, if you have not done so +review cpp\BuildInstructionsWindows.md first. + +Building the extension: + + > MSbuild msbuild\ice.proj + +This will build the extension in `Release` configuration and using the command +prompt default platform, for `x64` platform the extension will be placed in +`python\x64\Release\IcePy.pyd` and for `Win32` platform the extension will be +paced in `python\Win32\Release\IcePy.pyd`. + +If you want to build a debug version of the extension you can to so by setting +the MSBuild `Configuration` property to `Debug`: + + > MSbuild msbuild\ice.proj /p:Configuration=Debug - > set ICE_HOME=C:\Ice +The debug version of the extension for `x64` platform will be placed in +`python\x64\Debug\IcePy_d.pyd` and for `Win32` platform it will be placed in +`python\Win32\Debug\IcePy_d.pyd`. -Edit `config\Make.rules.mak` and review the settings. In particular you must set -`CPP_COMPILER` to the appropriate compiler. +> *For Debug builds a debug version of the Python interpreter must be installed.* -Run nmake: +The supported values for the `Configuration` property are `Debug` and `Release`. - > nmake /f Makefile.mak +If you wan to build the extension for other platform that the command prompt +default platform, you need to set the MSbuild `Platform` property, the supported +values for this property are `Win32` and `x64`. -Upon completion, the Ice extension is created as `python\IcePy.pyd`. +The following command will build the extension `x64` platform binaries with +`Release` configuration: -> *Normally you should build with `OPTIMIZE=yes`. If you wish to build a debug -version of the Ice extension, set `OPTIMIZE=no`. In this case, you will also -need to build a debug version of the Python interpreter from sources.* + > MSbuild msbuild\ice.proj /p:Configuration=Release /p:Platform=x64 + +And the next command will build the extension `Win32` platform binaries with +`Release` configuration: + + > MSbuild msbuild\ice.proj /p:Configuration=Release /p:Platform=Win32 + +> *When using the MSBuild Platform property the build platform doesn't depend on +the command prompt default platform* + +The build will use a default Python location defined in +`python\msbuild\ice.props`, it can be override by setting the `PythonHome` +MSBuild property. + +The following command will use Python installation from `C:\Python35-AMD64` +instead of the default location: + + > MSbuild msbuild\ice.proj /p:Configuration=Release /p:Platform=x64 /p:PythonHome=C:\Python35-AMD64 ## Configuring your Environment for Python @@ -69,16 +97,17 @@ setting the `PYTHONPATH` environment variable to contain the necessary subdirectory. For example, if the Ice for Python extension is installed in `C:\Ice`, you could configure your environment as follows: - > set PYTHONPATH=C:\Ice\python + > set PYTHONPATH=C:\Ice\python;C:\Ice\python\Win32\Release + ## Running the Python Tests After a successful build, you can run the tests as follows: - $ python allTests.py + $ python allTests.py --mode=Release --x86 If everything worked out, you should see lots of `ok` messages. In case of a failure, the tests abort with `failed`. [1]: https://zeroc.com/download.html -[2]: https://doc.zeroc.com/display/Ice36/Supported+Platforms+for+Ice+3.6.3 +[2]: https://doc.zeroc.com/display/Ice37/Supported+Platforms+for+Ice+3.7.0 diff --git a/python/Makefile b/python/Makefile index a462a7da71f..3a6c1fd4074 100644 --- a/python/Makefile +++ b/python/Makefile @@ -7,35 +7,43 @@ # # ********************************************************************** -top_srcdir = . +top_srcdir := .. +lang_srcdir := $(top_srcdir)/$(notdir $(patsubst %/,%,$(dir $(abspath $(lastword $(MAKEFILE_LIST)))))) ifeq ($(PYTHON),) PYTHON = python endif +ifeq ($(filter all python,$(ICE_BIN_DIST)),) + include $(top_srcdir)/config/Make.rules -SUBDIRS = modules python - -INSTALL_SUBDIRS = $(install_pythondir) $(install_libdir) - -install:: install-common - @for subdir in $(INSTALL_SUBDIRS); \ - do \ - if test ! -d $(DESTDIR)$$subdir ; \ - then \ - echo "Creating $(DESTDIR)$$subdir..." ; \ - mkdir -p $(DESTDIR)$$subdir ; \ - chmod a+rx $(DESTDIR)$$subdir ; \ - fi ; \ - done - -$(EVERYTHING):: - @for subdir in $(SUBDIRS); \ - do \ - echo "making $@ in $$subdir"; \ - ( cd $$subdir && $(MAKE) $@ ) || exit 1; \ - done - -test:: - @$(PYTHON) $(top_srcdir)/allTests.py +# +# Load C++ dependencies +# +$(eval $(call load-dependencies,$(addprefix $(top_srcdir)/cpp/src/,Ice IceSSL IceLocatorDiscovery IceDiscovery))) + +# +# Load python rules after loading C++ dependencies +# +include $(lang_srcdir)/config/Make.rules + +# +# Load Makefile.mk fragments +# +include $(shell find $(lang_srcdir) -name Makefile.mk) + +# +# Make the projects (this expands all the build configuration and defines rules for all +# the components). +# +$(call make-projects,$(projects)) + +# +# We use a separate Makefile for building the python packages because their building +# requires .NOTPARALLEL +# +all generate-srcs clean distclean install:: + +$(Q)$(MAKE) -C python $@ + +endif diff --git a/python/Makefile.mak b/python/Makefile.mak deleted file mode 100644 index 8d50b4ebe51..00000000000 --- a/python/Makefile.mak +++ /dev/null @@ -1,32 +0,0 @@ -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -top_srcdir = . - -!include $(top_srcdir)\config\Make.rules.mak - -SUBDIRS = modules python - -install:: install-common - @if not exist "$(install_pythondir)" \ - @echo "Creating $(install_pythondir)..." && \ - $(MKDIR) "$(install_pythondir)" - -$(EVERYTHING_EXCEPT_INSTALL):: - @for %i in ( $(SUBDIRS) ) do \ - @echo "making $@ in %i" && \ - cmd /c "cd %i && $(MAKE) -nologo -f Makefile.mak $@" || exit 1 - -install:: - @for %i in ( modules python ) do \ - @echo "making $@ in %i" && \ - cmd /c "cd %i && $(MAKE) -nologo -f Makefile.mak $@" || exit 1 - -test:: - @python $(top_srcdir)/allTests.py diff --git a/python/allTests.py b/python/allTests.py index 6d9e4148a3d..18df973cab0 100755 --- a/python/allTests.py +++ b/python/allTests.py @@ -8,53 +8,9 @@ # # ********************************************************************** -import os, sys, re, getopt +import os, sys +sys.path.append(os.path.join(os.path.dirname(__file__), "..", "scripts")) -path = [ ".", "..", "../..", "../../..", "../../../.." ] -head = os.path.dirname(sys.argv[0]) -if len(head) > 0: - path = [os.path.join(head, p) for p in path] -path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ] -if len(path) == 0: - raise RuntimeError("can't find toplevel directory!") -sys.path.append(os.path.join(path[0], "scripts")) -import TestUtil +from Util import runTestsWithPath -# -# List of all basic tests. -# -tests = [ - ("Slice/keyword", ["once"]), - ("Slice/structure", ["once"]), - ("Slice/macros", ["once"]), - ("Slice/import", ["once"]), - ("Slice/unicodePaths", ["once"]), - ("Ice/adapterDeactivation", ["core"]), - ("Ice/binding", ["core"]), - ("Ice/exceptions", ["core"]), - ("Ice/facets", ["core"]), - ("Ice/faultTolerance", ["core"]), - ("Ice/info", ["core", "noipv6", "nocompress"]), - ("Ice/inheritance", ["core"]), - ("Ice/location", ["core"]), - ("Ice/objects", ["core"]), - ("Ice/proxy", ["core"]), - ("Ice/properties", ["once"]), - ("Ice/operations", ["core"]), - ("Ice/slicing/exceptions", ["core"]), - ("Ice/slicing/objects", ["core"]), - ("Ice/custom", ["core"]), - ("Ice/checksum", ["core"]), - ("Ice/timeout", ["core", "nocompress"]), - ("Ice/servantLocator", ["core"]), - ("Ice/blobject", ["core"]), - ("Ice/defaultServant", ["core"]), - ("Ice/defaultValue", ["core"]), - ("Ice/ami", ["core", "nocompress"]), - ("Ice/optional", ["core"]), - ("Ice/enums", ["core"]), - ("Ice/acm", ["core"]) - ] - -if __name__ == "__main__": - TestUtil.run(tests) +runTestsWithPath(__file__)
\ No newline at end of file diff --git a/python/config/Ice.Python.props b/python/config/Ice.Python.props new file mode 100644 index 00000000000..3a617ef81e4 --- /dev/null +++ b/python/config/Ice.Python.props @@ -0,0 +1,7 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup Condition="'$(Configuration)' == ''"> + <Configuration>Debug</Configuration> + </PropertyGroup> + <Import Project="$(MSBuildThisFileDirectory)..\..\cpp\config\ice.cpp.props" /> +</Project> diff --git a/python/config/Make.rules b/python/config/Make.rules index 042a591ff6e..b7f6dbfade0 100644 --- a/python/config/Make.rules +++ b/python/config/Make.rules @@ -8,193 +8,89 @@ # ********************************************************************** # -# Select an installation base directory. The directory will be created -# if it does not exist. +# If multiple versions of Python are installed and you want a specific +# version to be used for building the Ice extension, set PYTHON to the +# location of the python interpreter. # -prefix ?= /opt/Ice-$(VERSION) +PYTHON ?= python -# -# The "root directory" for runpath embedded in executables. Can be set -# to change the runpath added to Ice executables. The default is -# platform dependent (Linux only, on OS X the embedded runpath is always -# based on @loader_path). -# -#embedded_runpath_prefix ?= /opt/Ice-$(VERSION_MAJOR).$(VERSION_MINOR) +# ---------------------------------------------------------------------- +# Don't change anything below this line! +# ---------------------------------------------------------------------- -# -# Define embedded_runpath as no if you don't want any RPATH added to -# the executables (Linux only, on OS X we always add a runpath). -# -embedded_runpath ?= yes +-include $(lang_srcdir)/config/Make.rules.$(os) -# -# Define OPTIMIZE as yes if you want to build with optimization. -# Otherwise the Ice extension is built with debug information. -# +python-call = $(shell $(PYTHON) -c "import sys; import distutils.sysconfig as ds; sys.stdout.write($1)") -#OPTIMIZE = yes +PYTHON_VERSION ?= python$(PYTHON_BASE_VERSION) +PYTHON_BASE_VERSION ?= $(call python-call,ds.get_python_version()) +PYTHON_INCLUDE_DIR ?= $(call python-call,ds.get_python_inc()) +PYTHON_LIB_DIR ?= $(call python-call,ds.get_config_var('LIBPL')) +PYTHON_LIB_SUFFIX ?= $(call python-call,sys.__dict__['abiflags'] if 'abiflags' in sys.__dict__ else '') +PYTHON_LIB_NAME ?= $(PYTHON_VERSION)$(PYTHON_LIB_SUFFIX) -# -# Define LP64 as yes if you want to build in 64 bit mode on a platform -# that supports both 32 and 64 bit. -# -#LP64 := yes +python_cppflags := -I$(PYTHON_INCLUDE_DIR) +python_ldflags := -L$(PYTHON_LIB_DIR) -l$(PYTHON_LIB_NAME) # -# The values below can be overridden by defining them as environment -# variables. +# Python installation directory # +install_pythondir = $(if $(usr_dir_install),$(shell $(PYTHON) $(lang_srcdir)/config/install_dir),$(prefix)/python) # -# If multiple versions of Python are installed and you want a specific -# version used for building the Ice extension, then set PYTHON to -# the specific to the location of the python interpreter. +# Rules to build a python module. We just compute the name of the python module +# and delegate to make-shared-module. # -PYTHON ?= python - -PYTHON_VERSION ?= python$(shell $(PYTHON) -c "import sys; import distutils.sysconfig as ds; sys.stdout.write(ds.get_python_version())") - -PYTHON_BASE_VERSION ?= $(shell $(PYTHON) -c "import sys; import distutils.sysconfig as ds; sys.stdout.write(ds.get_python_version())") +mkpymodulename ?= $(patsubst lib%,%,$(call mkshlibname,$(1))) +make-shared-python-module = $(call make-shared-module,$(call mkpymodulename,$1),$2,$3,$4,$5,$6,$7,$8,$9) +get-shared-python-module-targets = $(call get-shared-module-targets,$(call mkpymodulename,$1),$2,$3,$4) +install-shared-python-module = $(call install-shared-module,$(call mkpymodulename,$1),$2,$3,$4,$5) -PYTHON_INCLUDE_DIR ?= $(shell $(PYTHON) -c "import sys; import distutils.sysconfig as ds; sys.stdout.write(ds.get_python_inc())") +$(DESTDIR)$(install_pythondir): + $(Q)$(MKDIR) -p $@ +installdirs += $(install_pythondir) -PYTHON_LIB_DIR ?= $(shell $(PYTHON) -c "import sys; import distutils.sysconfig as ds; sys.stdout.write(ds.get_config_var('LIBPL'))") - -PYTHON_LIB_SUFFIX ?= $(shell $(PYTHON) -c "import sys; sys.stdout.write(sys.__dict__['abiflags'] if 'abiflags' in sys.__dict__ else '')") - -PYTHON_LIB_NAME ?= $(PYTHON_VERSION)$(PYTHON_LIB_SUFFIX) - -PYTHON_FLAGS ?= -I$(PYTHON_INCLUDE_DIR) -PYTHON_LIBS ?= -L$(PYTHON_LIB_DIR) -l$(PYTHON_LIB_NAME) - -# -# The build architectures for gcc based builds. The format of these -# build flags are OS dependent. For example, under OS X to build -# binaries which support both i386 and x86_64 you would use "-arch -# i386 -arch x86_64". The default is OS version dependent. Be aware -# that this value may conflict with the setting of LP64 above. # -#CXXARCHFLAGS = -arch i386 -arch x86_64 - -# ---------------------------------------------------------------------- -# Don't change anything below this line! -# ---------------------------------------------------------------------- - +# $(call make-python-package,$1=slicedir,$2=generateddir,$3=package,$4=sliceflags) # -# Common definitions +# Compile slice files from $(slicedir)/<package> to python/<package>. # -ice_language = python -ice_require_cpp = yes +define make-python-package -ifeq ($(shell test -f $(top_srcdir)/config/Make.common.rules && echo 0),0) - include $(top_srcdir)/config/Make.common.rules -else - include $(top_srcdir)/../config/Make.common.rules -endif +$2/$3/.depend/%.ice.d: | $2/$3/.depend ; -install_bindir = $(prefix)/$(binsubdir) +$2/$3/.depend: + $(Q)$(MKDIR) -p $$@ -# -# Platform specific definitions -# -ifeq ($(shell test -f $(top_srcdir)/config/Make.rules.$(UNAME) && echo 0),0) - include $(top_srcdir)/config/Make.rules.$(UNAME) -else - include $(top_srcdir)/../cpp/config/Make.rules.$(UNAME) -endif +.PRECIOUS: $2/$3/.depend/%.ice.d -libdir = $(top_srcdir)/python - -ifndef usr_dir_install - install_pythondir = $(prefix)/python - install_libdir = $(prefix)/python -else - # - # The install_dir script says where python wants site-packages installed. - # - install_pythondir = $(shell $(PYTHON) $(top_srcdir)/config/install_dir) - install_libdir = $(install_pythondir) +ifeq ($(filter %clean,$(MAKECMDGOALS)),) + # Include the dependencies + -include $(addprefix $2/.depend/,$(call source-to-dependency,$(wildcard $1/$3/*.ice))) endif -ifeq ($(UNAME),SunOS) - ifeq ($(LP64),yes) - libdir = $(top_srcdir)/python$(lp64suffix) - install_libdir = $(prefix)/python$(lp64suffix) - endif -endif +$$(eval $$(call make-python-slice,$1,$2,$3,,$4)) -ifdef ice_src_dist - ICE_LIB_DIR = -L$(ice_cpp_dir)/$(libsubdir) - ICE_FLAGS = -I$(ice_cpp_dir)/include -else - ICE_LIB_DIR = -L$(ice_dir)/$(libsubdir) - ICE_FLAGS = -I$(ice_dir)/include -endif -ICE_LIBS = $(ICE_LIB_DIR) -lIceSSL -lIce -lSlice -lIceUtil +distclean clean:: + $(E) "Cleaning package $3" + $(Q)$(RM) -r $2/$3/.depend + $(Q)$(if $(findstring --no-package,$4),,$(RM) $2/$3/.__init__.py) + $(Q)$(RM) $(patsubst $1/$3/%.ice,$2/$3_%_ice.py,$(wildcard $1/$3/*.ice)) -CPPFLAGS = -ICECPPFLAGS = -I$(slicedir) -SLICE2PYFLAGS = $(ICECPPFLAGS) -LDFLAGS = $(LDPLATFORMFLAGS) $(CXXFLAGS) -L$(libdir) +generate-srcs srcs all:: $(patsubst $1/$3/%.ice,$2/$3_%_ice.py,$(wildcard $1/$3/*.ice)) -ifeq ($(MAKEDEPENDFLAGS),) - MAKEDEPENDFLAGS := -MMD -endif +$$(eval $$(call install-data-files,$(patsubst $1/$3/%.ice,$2/$3_%_ice.py,$(wildcard $1/$3/*.ice)),$2,$(install_pythondir),install)) -ifdef ice_src_dist - SLICE2PY = $(PYTHON) $(top_srcdir)/config/s2py.py - SLICEPARSERLIB = $(ice_cpp_dir)/$(libsubdir)/$(call mklibfilename,Slice,$(VERSION)) - ifeq ($(wildcard $(SLICEPARSERLIB)),) - SLICEPARSERLIB = $(ice_cpp_dir)/$(lib64subdir)/$(call mklibfilename,Slice,$(VERSION)) - endif -else - ifeq ($(UNAME),Darwin) - SLICE2PY = /usr/local/bin/slice2py - else - SLICE2PY = $(shell $(PYTHON) -c "import os, sys, slice2py; sys.stdout.write(os.path.normpath(os.path.join(slice2py.__file__, '..', '..', '..', '..', 'bin', 'slice2py')))") - endif - SLICEPARSERLIB = -endif +endef # -# A Python extension library cannot have a "lib" prefix, so Python-specific -# functions are defined that strip "lib" from the regular library name. +# $(call make-python-slice,$1=slicedir,$2=generateddir,$3=package,$4=file,$5=sliceflags) # -ifndef mkpylibfilename - mkpylibfilename = $(subst dy,dylib,$(subst lib,,$(call mklibfilename,$(1),$(2)))) -endif -ifndef mkpysoname - mkpysoname = $(subst dy,dylib,$(subst lib,,$(call mksoname,$(1),$(2)))) -endif -ifndef mkpylibname - mkpylibname = $(subst dy,dylib,$(subst lib,,$(call mklibname,$(1)))) -endif - -EVERYTHING = all depend clean install - -.SUFFIXES: -.SUFFIXES: .cpp .o .py - -all:: $(SRCS) - -%_ice.py: $(slicedir)/%.ice - rm -f $(*F).py - $(SLICE2PY) $(SLICE2PYFLAGS) $< - @mkdir -p .depend - @$(SLICE2PY) $(SLICE2PYFLAGS) $< > .depend/$(*F).ice.d - -.cpp.o: - @mkdir -p .depend - $(CXX) -c $(CPPFLAGS) $(CXXFLAGS) $(MAKEDEPENDFLAGS) $< -MF .depend/$(*F).d - -clean:: - -rm -f $(TARGETS) - -rm -f core *.o *.pyc *.bak - -rm -rf __pycache__ - -rm -rf .depend - -all:: $(SRCS) $(TARGETS) +define make-python-slice -include $(wildcard .depend/*.d) +$2/$3_$(or $4,%)_ice.py: $1/$3/$(or $4,%).ice $2/$3/.depend/$(or $4,%).ice.d $(slice2py_path) + $(E) "Compiling $$<" + $(Q)$(slice2py_path) -I$1 --output-dir $2 $5 --depend $$< > $2/$3/.depend/$(or $4,$$(*F)).ice.d + $(Q)$(slice2py_path) -I$1 --output-dir $2 --prefix $3_ --checksum $5 $$< -install:: +endef diff --git a/python/config/Make.rules.AIX b/python/config/Make.rules.AIX index da68b973066..2a3f9d19841 100644 --- a/python/config/Make.rules.AIX +++ b/python/config/Make.rules.AIX @@ -7,19 +7,6 @@ # # ********************************************************************** -# -# This file is itself included by Make.rules -# - -include $(top_srcdir)/../cpp/config/Make.rules.$(UNAME) - -# -# Need .so for Python extension -# -# Note: Python also loads the extension in IcePy.a if IcePy.so points to it -# - -mkpylibfilename = $(1).so -mkylibname = $(1).so +# $(call mkshlib,$1=target,$2=objects,$3=libname,$4=version,$5=soversion,$6=ldflags,$7=platform) +mkshlib = $(or $($7_cxx),$(CXX)) -qmkshrobj -o $1 $2 $6 -mkshlib = $(CXX) -qmkshrobj $(LDFLAGS) -o $(1) $(3) $(4) diff --git a/python/config/Make.rules.Darwin b/python/config/Make.rules.Darwin deleted file mode 100644 index 48adf60ff2c..00000000000 --- a/python/config/Make.rules.Darwin +++ /dev/null @@ -1,48 +0,0 @@ -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -# -# This file is included by Make.rules when uname is Darwin. -# - -include $(top_srcdir)/../cpp/config/Make.rules.$(UNAME) - -shlibldflags += $(LDEXEFLAGS) - -mksoname = $(if $(2),lib$(1).$(2).so,lib$(1).so) -mklibname = lib$(1).so - -mkshlib = $(CXX) -dynamiclib $(shlibldflags) -o $(1) -install_name @rpath/$(2) $(3) $(4) - -ifneq ($(STATICLIBS),yes) - # - # Set RPATH to the cpp/lib directory or Ice installation lib directory. Note that unlike Linux - # platforms, we always set the RPATH for source builds on OS X. This is required because we - # can no longer rely on DYLD_LIBRARY_PATH on El Capitan. The RPATH is updated when the library - # is installed (see cpp/config/Make.rules.Darwin). - # - ifdef ice_src_dist - RPATH_DIR = @loader_path/../../cpp/$(libsubdir) - else - RPATH_DIR = $(ice_dir)/$(libsubdir) - endif - - # - # Update the RPATH to the installation lib directory when installing a library instead - # of relying on the RPATH set during the build (which isn't correct anymore for the - # installation directly layout). - # - ifneq ($(embedded_runpath_prefix),) - installlib += ; install_name_tool -rpath $(RPATH_DIR) $(embedded_runpath_prefix)/lib $(1)/$(3) - else ifdef usr_dir_install - installlib += ; install_name_tool -delete_rpath $(RPATH_DIR) $(1)/$(3) - else ifdef ice_src_dist - installlib += ; install_name_tool -rpath $(RPATH_DIR) @loader_path/../$(libsubdir) $(1)/$(3) - endif -endif diff --git a/python/config/Make.rules.Linux b/python/config/Make.rules.Linux deleted file mode 100644 index 55751adce83..00000000000 --- a/python/config/Make.rules.Linux +++ /dev/null @@ -1,27 +0,0 @@ -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -# -# This file is itself included by Make.rules -# - -include $(top_srcdir)/../cpp/config/Make.rules.$(UNAME) - -ifeq ($(CXX),g++) - ifeq ($(OPTIMIZE),yes) - # - # Necessary to avoid warnings for Python < 3.x - # - ifneq ($(findstring $(PYTHON_BASE_VERSION),2.6 2.7),) - CXXFLAGS += -fno-strict-aliasing - endif - endif -endif - -mkshlib = $(CXX) -shared $(LDFLAGS) $(LDEXEFLAGS) -o $(1) -Wl,-h,$(2) $(3) $(4) -lpthread diff --git a/python/config/Make.rules.mak b/python/config/Make.rules.mak deleted file mode 100644 index ef5617062fd..00000000000 --- a/python/config/Make.rules.mak +++ /dev/null @@ -1,151 +0,0 @@ -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -# -# Select an installation base directory. The directory will be created -# if it does not exist. -# - -!if "$(PREFIX)" == "" -prefix = C:\Ice-$(VERSION) -!else -prefix = $(PREFIX) -!endif - -# -# Define OPTIMIZE as yes if you want to build with optimization. -# Otherwise the Ice extension is built with debug information. -# - -OPTIMIZE = yes - -# -# Specify your C++ compiler, or leave unset for auto-detection. The -# only value currently supported to build IcePy is VC100. -# -#CPP_COMPILER = VCxxx - -# -# Set PYTHON_HOME to your Python installation directory. -# -!if "$(PYTHON_HOME)" == "" -PYTHON_HOME = C:\Python34 -!endif - -# ---------------------------------------------------------------------- -# Don't change anything below this line! -# ---------------------------------------------------------------------- - -# -# Common definitions -# -ice_language = python -ice_require_cpp = yes - -!if exist ($(top_srcdir)\..\config\Make.common.rules.mak) -!include $(top_srcdir)\..\config\Make.common.rules.mak -!else -!include $(top_srcdir)\config\Make.common.rules.mak -!endif - -libdir = $(top_srcdir)\python -install_pythondir = $(prefix)\python$(x64suffix) -install_libdir = $(prefix)\python$(x64suffix) - -!include $(top_srcdir)\..\cpp\config\Make.rules.msvc - -libsuff = $(x64suffix) - -!if "$(OPTIMIZE)" != "yes" -LIBSUFFIX = $(LIBSUFFIX)d -PYLIBSUFFIX = _$(LIBSUFFIX) -RCFLAGS = -D_DEBUG -!endif - -# -# Import libraries are located automatically -# -ICE_LIBS = - -!if "$(ice_src_dist)" != "" -ICE_CPPFLAGS = -I"$(ice_cpp_dir)\include" -!if "$(ice_cpp_dir)" == "$(ice_dir)\cpp" -ICE_LDFLAGS = /LIBPATH:"$(ice_cpp_dir)\lib" -!else -ICE_LDFLAGS = /LIBPATH:"$(ice_cpp_dir)\lib$(libsuff)" -!endif -!else -ICE_CPPFLAGS = -I"$(ice_dir)\include" -ICE_LDFLAGS = /LIBPATH:"$(ice_dir)\lib$(libsuff)" -!endif - -slicedir = $(ice_dir)\slice - -PYTHON_CPPFLAGS = -I"$(PYTHON_HOME)\include" -PYTHON_LDFLAGS = /LIBPATH:"$(PYTHON_HOME)\libs" - -ICECPPFLAGS = -I"$(slicedir)" -SLICE2PYFLAGS = $(ICECPPFLAGS) - -!if "$(ice_src_dist)" != "" -SLICE2PY = $(PYTHON_HOME)\python $(top_srcdir)\config\s2py.py -SLICEPARSERLIB = $(ice_cpp_dir)\lib\slice.lib -!if !exist ("$(SLICEPARSERLIB)") -SLICEPARSERLIB = $(ice_cpp_dir)\lib\sliced.lib -!endif -!else -SLICE2PY = $(PYTHON_HOME)\Scripts\slice2py.exe -SLICEPARSERLIB = $(PYTHON_HOME)\Scripts\slice2py.exe -!endif - -MT = mt.exe - -EVERYTHING = all clean install depend -EVERYTHING_EXCEPT_INSTALL = all clean depend - -.SUFFIXES: -.SUFFIXES: .cpp .obj .py .res .rc .d .ice - -DEPEND_DIR = .depend.mak - -depend:: - -!if exist(.depend.mak) -!include .depend.mak -!endif - -!if "$(OBJS)" != "" -depend:: - @del /q .depend.mak - -OBJS_DEPEND = $(OBJS:.obj=.d) -OBJS_DEPEND = $(OBJS_DEPEND:.\=.depend.mak\) - -depend:: $(OBJS_DEPEND) - -!endif - -.cpp{$(DEPEND_DIR)}.d: - @echo Generating dependencies for $< - @$(CXX) /E $(CPPFLAGS) $(CXXFLAGS) /showIncludes $< 1>$(*F).i 2>$(*F).d && \ - cscript /NoLogo $(top_srcdir)\..\config\makedepend.vbs $(*F).cpp $(top_srcdir) - @del /q $(*F).d $(*F).i - -.cpp.obj:: - $(CXX) /c $(CPPFLAGS) $(CXXFLAGS) $< - -.rc.res: - rc $(RCFLAGS) $< - -clean:: - del /q $(TARGETS) *.obj *.pyc *.bak - -all:: $(SRCS) $(TARGETS) - -install:: diff --git a/python/config/s2py.py b/python/config/s2py.py index 82872c5de63..a28e9c35c2c 100755 --- a/python/config/s2py.py +++ b/python/config/s2py.py @@ -9,15 +9,16 @@ # ********************************************************************** import sys, os, platform -sys.path.insert(1, os.path.join(os.path.dirname(sys.argv[0]), "..", "python")) + +basepath = os.path.dirname(os.path.realpath(__file__)) if sys.platform == "win32": - os.putenv("PATH", "{0};{1};{2}".format( - os.getenv('PATH'), - os.path.join(os.path.dirname(sys.argv[0]), "..", "..", "cpp", "bin"), - os.path.join(os.path.dirname(sys.argv[0]), "..", "..", "cpp", "third-party-packages", - "bzip2.v100" if sys.version_info < (3,5) else "bzip2.v140", "build", "native", "bin", - "Win32" if "32bit" in platform.architecture() else "x64", "Release"))) + platformName = "Win32" if "32bit" in platform.architecture() else "x64" + configurationName = os.getenv("CPP_CONFIGURATION", "Release") + sys.path.insert(1, os.path.join(basepath, "..", "python", platformName, configurationName)) + os.putenv("PATH", os.path.join(basepath, "..", "..", "cpp", "bin", platformName, configurationName)) +else: + sys.path.insert(1, os.path.join(basepath, "..", "python")) import IcePy diff --git a/python/modules/IcePy/.depend.mak b/python/modules/IcePy/.depend.mak deleted file mode 100644 index f4834457aa7..00000000000 --- a/python/modules/IcePy/.depend.mak +++ /dev/null @@ -1,1550 +0,0 @@ - -BatchRequestInterceptor.obj: \ - BatchRequestInterceptor.cpp \ - "$(ice_cpp_dir)\include\IceUtil\Config.h" \ - "BatchRequestInterceptor.h" \ - "Config.h" \ - "Util.h" \ - "$(ice_cpp_dir)\include\Ice\BuiltinSequences.h" \ - "$(ice_cpp_dir)\include\IceUtil\PushDisableWarnings.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyF.h" \ - "$(ice_cpp_dir)\include\IceUtil\Shared.h" \ - "$(ice_cpp_dir)\include\IceUtil\Atomic.h" \ - "$(ice_cpp_dir)\include\Ice\Config.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyHandle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Handle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\Handle.h" \ - "$(ice_cpp_dir)\include\Ice\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\Format.h" \ - "$(ice_cpp_dir)\include\Ice\StreamF.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObject.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\StreamHelpers.h" \ - "$(ice_cpp_dir)\include\IceUtil\ScopedArray.h" \ - "$(ice_cpp_dir)\include\IceUtil\Iterator.h" \ - "$(ice_cpp_dir)\include\IceUtil\Optional.h" \ - "$(ice_cpp_dir)\include\IceUtil\UndefSysMacros.h" \ - "$(ice_cpp_dir)\include\IceUtil\PopDisableWarnings.h" \ - "$(ice_cpp_dir)\include\Ice\Current.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectAdapterF.h" \ - "$(ice_cpp_dir)\include\Ice\ConnectionF.h" \ - "$(ice_cpp_dir)\include\Ice\Identity.h" \ - "$(ice_cpp_dir)\include\Ice\Version.h" \ - "$(ice_cpp_dir)\include\Ice\BatchRequestInterceptor.h" \ - "Proxy.h" \ - "$(ice_cpp_dir)\include\Ice\CommunicatorF.h" \ - "Thread.h" \ - "$(ice_cpp_dir)\include\Ice\Initialize.h" \ - "$(ice_cpp_dir)\include\IceUtil\Timer.h" \ - "$(ice_cpp_dir)\include\IceUtil\Thread.h" \ - "$(ice_cpp_dir)\include\IceUtil\Mutex.h" \ - "$(ice_cpp_dir)\include\IceUtil\Lock.h" \ - "$(ice_cpp_dir)\include\IceUtil\ThreadException.h" \ - "$(ice_cpp_dir)\include\IceUtil\Time.h" \ - "$(ice_cpp_dir)\include\IceUtil\MutexProtocol.h" \ - "$(ice_cpp_dir)\include\IceUtil\Monitor.h" \ - "$(ice_cpp_dir)\include\IceUtil\Cond.h" \ - "$(ice_cpp_dir)\include\Ice\PropertiesF.h" \ - "$(ice_cpp_dir)\include\Ice\Proxy.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyFactoryF.h" \ - "$(ice_cpp_dir)\include\Ice\ConnectionIF.h" \ - "$(ice_cpp_dir)\include\Ice\RequestHandlerF.h" \ - "$(ice_cpp_dir)\include\Ice\EndpointF.h" \ - "$(ice_cpp_dir)\include\Ice\EndpointTypes.h" \ - "$(ice_cpp_dir)\include\Ice\ReferenceF.h" \ - "$(ice_cpp_dir)\include\Ice\BatchRequestQueueF.h" \ - "$(ice_cpp_dir)\include\Ice\AsyncResult.h" \ - "$(ice_cpp_dir)\include\IceUtil\UniquePtr.h" \ - "$(ice_cpp_dir)\include\Ice\InstanceF.h" \ - "$(ice_cpp_dir)\include\Ice\AsyncResultF.h" \ - "$(ice_cpp_dir)\include\Ice\ObserverHelper.h" \ - "$(ice_cpp_dir)\include\Ice\Instrumentation.h" \ - "$(ice_cpp_dir)\include\Ice\BasicStream.h" \ - "$(ice_cpp_dir)\include\IceUtil\StringConverter.h" \ - "$(ice_cpp_dir)\include\Ice\Object.h" \ - "$(ice_cpp_dir)\include\Ice\IncomingAsyncF.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectFactoryF.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectFactoryManagerF.h" \ - "$(ice_cpp_dir)\include\Ice\Buffer.h" \ - "$(ice_cpp_dir)\include\Ice\Protocol.h" \ - "$(ice_cpp_dir)\include\Ice\SlicedDataF.h" \ - "$(ice_cpp_dir)\include\Ice\UserExceptionFactory.h" \ - "$(ice_cpp_dir)\include\Ice\FactoryTable.h" \ - "$(ice_cpp_dir)\include\Ice\LoggerF.h" \ - "$(ice_cpp_dir)\include\Ice\InstrumentationF.h" \ - "$(ice_cpp_dir)\include\Ice\Dispatcher.h" \ - "$(ice_cpp_dir)\include\Ice\Plugin.h" \ - -Communicator.obj: \ - Communicator.cpp \ - "$(ice_cpp_dir)\include\IceUtil\Config.h" \ - "$(ice_cpp_dir)\include\IceUtil\DisableWarnings.h" \ - "Communicator.h" \ - "Config.h" \ - "$(ice_cpp_dir)\include\Ice\CommunicatorF.h" \ - "$(ice_cpp_dir)\include\IceUtil\PushDisableWarnings.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyF.h" \ - "$(ice_cpp_dir)\include\IceUtil\Shared.h" \ - "$(ice_cpp_dir)\include\IceUtil\Atomic.h" \ - "$(ice_cpp_dir)\include\Ice\Config.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyHandle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Handle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\Handle.h" \ - "$(ice_cpp_dir)\include\Ice\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\Format.h" \ - "$(ice_cpp_dir)\include\Ice\StreamF.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObject.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\StreamHelpers.h" \ - "$(ice_cpp_dir)\include\IceUtil\ScopedArray.h" \ - "$(ice_cpp_dir)\include\IceUtil\Iterator.h" \ - "$(ice_cpp_dir)\include\IceUtil\Optional.h" \ - "$(ice_cpp_dir)\include\IceUtil\UndefSysMacros.h" \ - "$(ice_cpp_dir)\include\IceUtil\PopDisableWarnings.h" \ - "BatchRequestInterceptor.h" \ - "Util.h" \ - "$(ice_cpp_dir)\include\Ice\BuiltinSequences.h" \ - "$(ice_cpp_dir)\include\Ice\Current.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectAdapterF.h" \ - "$(ice_cpp_dir)\include\Ice\ConnectionF.h" \ - "$(ice_cpp_dir)\include\Ice\Identity.h" \ - "$(ice_cpp_dir)\include\Ice\Version.h" \ - "$(ice_cpp_dir)\include\Ice\BatchRequestInterceptor.h" \ - "ImplicitContext.h" \ - "$(ice_cpp_dir)\include\Ice\ImplicitContext.h" \ - "$(ice_cpp_dir)\include\Ice\LocalException.h" \ - "Logger.h" \ - "$(ice_cpp_dir)\include\Ice\Logger.h" \ - "ObjectAdapter.h" \ - "ObjectFactory.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectFactory.h" \ - "$(ice_cpp_dir)\include\IceUtil\Mutex.h" \ - "$(ice_cpp_dir)\include\IceUtil\Lock.h" \ - "$(ice_cpp_dir)\include\IceUtil\ThreadException.h" \ - "$(ice_cpp_dir)\include\IceUtil\Time.h" \ - "$(ice_cpp_dir)\include\IceUtil\MutexProtocol.h" \ - "Operation.h" \ - "$(ice_cpp_dir)\include\Ice\Object.h" \ - "$(ice_cpp_dir)\include\Ice\IncomingAsyncF.h" \ - "$(ice_cpp_dir)\include\Ice\AsyncResultF.h" \ - "Properties.h" \ - "$(ice_cpp_dir)\include\Ice\PropertiesF.h" \ - "$(ice_cpp_dir)\include\Ice\Proxy.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyFactoryF.h" \ - "$(ice_cpp_dir)\include\Ice\ConnectionIF.h" \ - "$(ice_cpp_dir)\include\Ice\RequestHandlerF.h" \ - "$(ice_cpp_dir)\include\Ice\EndpointF.h" \ - "$(ice_cpp_dir)\include\Ice\EndpointTypes.h" \ - "$(ice_cpp_dir)\include\Ice\ReferenceF.h" \ - "$(ice_cpp_dir)\include\Ice\BatchRequestQueueF.h" \ - "$(ice_cpp_dir)\include\Ice\AsyncResult.h" \ - "$(ice_cpp_dir)\include\IceUtil\Monitor.h" \ - "$(ice_cpp_dir)\include\IceUtil\Cond.h" \ - "$(ice_cpp_dir)\include\IceUtil\UniquePtr.h" \ - "$(ice_cpp_dir)\include\Ice\InstanceF.h" \ - "$(ice_cpp_dir)\include\Ice\ObserverHelper.h" \ - "$(ice_cpp_dir)\include\Ice\Instrumentation.h" \ - "$(ice_cpp_dir)\include\Ice\BasicStream.h" \ - "$(ice_cpp_dir)\include\IceUtil\StringConverter.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectFactoryF.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectFactoryManagerF.h" \ - "$(ice_cpp_dir)\include\Ice\Buffer.h" \ - "$(ice_cpp_dir)\include\Ice\Protocol.h" \ - "$(ice_cpp_dir)\include\Ice\SlicedDataF.h" \ - "$(ice_cpp_dir)\include\Ice\UserExceptionFactory.h" \ - "$(ice_cpp_dir)\include\Ice\FactoryTable.h" \ - "PropertiesAdmin.h" \ - "$(ice_cpp_dir)\include\Ice\NativePropertiesAdmin.h" \ - "$(ice_cpp_dir)\include\Ice\PropertiesAdmin.h" \ - "$(ice_cpp_dir)\include\Ice\GCObject.h" \ - "$(ice_cpp_dir)\include\IceUtil\MutexPtrLock.h" \ - "$(ice_cpp_dir)\include\Ice\Incoming.h" \ - "$(ice_cpp_dir)\include\Ice\ServantLocatorF.h" \ - "$(ice_cpp_dir)\include\Ice\ServantManagerF.h" \ - "$(ice_cpp_dir)\include\Ice\ResponseHandlerF.h" \ - "$(ice_cpp_dir)\include\Ice\IncomingAsync.h" \ - "Proxy.h" \ - "Thread.h" \ - "$(ice_cpp_dir)\include\Ice\Initialize.h" \ - "$(ice_cpp_dir)\include\IceUtil\Timer.h" \ - "$(ice_cpp_dir)\include\IceUtil\Thread.h" \ - "$(ice_cpp_dir)\include\Ice\LoggerF.h" \ - "$(ice_cpp_dir)\include\Ice\InstrumentationF.h" \ - "$(ice_cpp_dir)\include\Ice\Dispatcher.h" \ - "$(ice_cpp_dir)\include\Ice\Plugin.h" \ - "Types.h" \ - "$(ice_cpp_dir)\include\Ice\Stream.h" \ - "$(ice_cpp_dir)\include\IceUtil\OutputUtil.h" \ - "$(ice_cpp_dir)\include\Ice\CommunicatorAsync.h" \ - "$(ice_cpp_dir)\include\Ice\Communicator.h" \ - "$(ice_cpp_dir)\include\Ice\RouterF.h" \ - "$(ice_cpp_dir)\include\Ice\LocatorF.h" \ - "$(ice_cpp_dir)\include\Ice\PluginF.h" \ - "$(ice_cpp_dir)\include\Ice\ImplicitContextF.h" \ - "$(ice_cpp_dir)\include\Ice\Properties.h" \ - "$(ice_cpp_dir)\include\Ice\FacetMap.h" \ - "$(ice_cpp_dir)\include\Ice\Locator.h" \ - "$(ice_cpp_dir)\include\Ice\FactoryTableInit.h" \ - "$(ice_cpp_dir)\include\Ice\DefaultObjectFactory.h" \ - "$(ice_cpp_dir)\include\Ice\ProcessF.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectAdapter.h" \ - "$(ice_cpp_dir)\include\Ice\Endpoint.h" \ - "$(ice_cpp_dir)\include\Ice\Router.h" \ - -Connection.obj: \ - Connection.cpp \ - "$(ice_cpp_dir)\include\IceUtil\Config.h" \ - "Connection.h" \ - "Config.h" \ - "$(ice_cpp_dir)\include\Ice\ConnectionF.h" \ - "$(ice_cpp_dir)\include\IceUtil\PushDisableWarnings.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyF.h" \ - "$(ice_cpp_dir)\include\IceUtil\Shared.h" \ - "$(ice_cpp_dir)\include\IceUtil\Atomic.h" \ - "$(ice_cpp_dir)\include\Ice\Config.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyHandle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Handle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\Handle.h" \ - "$(ice_cpp_dir)\include\Ice\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\Format.h" \ - "$(ice_cpp_dir)\include\Ice\StreamF.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObject.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\StreamHelpers.h" \ - "$(ice_cpp_dir)\include\IceUtil\ScopedArray.h" \ - "$(ice_cpp_dir)\include\IceUtil\Iterator.h" \ - "$(ice_cpp_dir)\include\IceUtil\Optional.h" \ - "$(ice_cpp_dir)\include\IceUtil\UndefSysMacros.h" \ - "$(ice_cpp_dir)\include\IceUtil\PopDisableWarnings.h" \ - "$(ice_cpp_dir)\include\Ice\CommunicatorF.h" \ - "Communicator.h" \ - "ConnectionInfo.h" \ - "$(ice_cpp_dir)\include\Ice\Connection.h" \ - "$(ice_cpp_dir)\include\Ice\Proxy.h" \ - "$(ice_cpp_dir)\include\IceUtil\Mutex.h" \ - "$(ice_cpp_dir)\include\IceUtil\Lock.h" \ - "$(ice_cpp_dir)\include\IceUtil\ThreadException.h" \ - "$(ice_cpp_dir)\include\IceUtil\Time.h" \ - "$(ice_cpp_dir)\include\IceUtil\MutexProtocol.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyFactoryF.h" \ - "$(ice_cpp_dir)\include\Ice\ConnectionIF.h" \ - "$(ice_cpp_dir)\include\Ice\RequestHandlerF.h" \ - "$(ice_cpp_dir)\include\Ice\EndpointF.h" \ - "$(ice_cpp_dir)\include\Ice\EndpointTypes.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectAdapterF.h" \ - "$(ice_cpp_dir)\include\Ice\ReferenceF.h" \ - "$(ice_cpp_dir)\include\Ice\BatchRequestQueueF.h" \ - "$(ice_cpp_dir)\include\Ice\AsyncResult.h" \ - "$(ice_cpp_dir)\include\IceUtil\Monitor.h" \ - "$(ice_cpp_dir)\include\IceUtil\Cond.h" \ - "$(ice_cpp_dir)\include\IceUtil\UniquePtr.h" \ - "$(ice_cpp_dir)\include\Ice\InstanceF.h" \ - "$(ice_cpp_dir)\include\Ice\AsyncResultF.h" \ - "$(ice_cpp_dir)\include\Ice\ObserverHelper.h" \ - "$(ice_cpp_dir)\include\Ice\Instrumentation.h" \ - "$(ice_cpp_dir)\include\Ice\Current.h" \ - "$(ice_cpp_dir)\include\Ice\Identity.h" \ - "$(ice_cpp_dir)\include\Ice\Version.h" \ - "$(ice_cpp_dir)\include\Ice\BasicStream.h" \ - "$(ice_cpp_dir)\include\IceUtil\StringConverter.h" \ - "$(ice_cpp_dir)\include\Ice\Object.h" \ - "$(ice_cpp_dir)\include\Ice\IncomingAsyncF.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectFactoryF.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectFactoryManagerF.h" \ - "$(ice_cpp_dir)\include\Ice\Buffer.h" \ - "$(ice_cpp_dir)\include\Ice\Protocol.h" \ - "$(ice_cpp_dir)\include\Ice\SlicedDataF.h" \ - "$(ice_cpp_dir)\include\Ice\UserExceptionFactory.h" \ - "$(ice_cpp_dir)\include\Ice\FactoryTable.h" \ - "$(ice_cpp_dir)\include\Ice\Endpoint.h" \ - "$(ice_cpp_dir)\include\Ice\BuiltinSequences.h" \ - "Endpoint.h" \ - "ObjectAdapter.h" \ - "Operation.h" \ - "Proxy.h" \ - "Thread.h" \ - "Util.h" \ - "$(ice_cpp_dir)\include\Ice\Initialize.h" \ - "$(ice_cpp_dir)\include\IceUtil\Timer.h" \ - "$(ice_cpp_dir)\include\IceUtil\Thread.h" \ - "$(ice_cpp_dir)\include\Ice\PropertiesF.h" \ - "$(ice_cpp_dir)\include\Ice\LoggerF.h" \ - "$(ice_cpp_dir)\include\Ice\InstrumentationF.h" \ - "$(ice_cpp_dir)\include\Ice\Dispatcher.h" \ - "$(ice_cpp_dir)\include\Ice\Plugin.h" \ - "$(ice_cpp_dir)\include\Ice\BatchRequestInterceptor.h" \ - "Types.h" \ - "$(ice_cpp_dir)\include\Ice\Stream.h" \ - "$(ice_cpp_dir)\include\IceUtil\OutputUtil.h" \ - "$(ice_cpp_dir)\include\Ice\ConnectionAsync.h" \ - -ConnectionInfo.obj: \ - ConnectionInfo.cpp \ - "$(ice_cpp_dir)\include\IceUtil\Config.h" \ - "ConnectionInfo.h" \ - "Config.h" \ - "$(ice_cpp_dir)\include\Ice\Connection.h" \ - "$(ice_cpp_dir)\include\IceUtil\PushDisableWarnings.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyF.h" \ - "$(ice_cpp_dir)\include\IceUtil\Shared.h" \ - "$(ice_cpp_dir)\include\IceUtil\Atomic.h" \ - "$(ice_cpp_dir)\include\Ice\Config.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyHandle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Handle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\Handle.h" \ - "$(ice_cpp_dir)\include\Ice\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\Format.h" \ - "$(ice_cpp_dir)\include\Ice\StreamF.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObject.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\StreamHelpers.h" \ - "$(ice_cpp_dir)\include\IceUtil\ScopedArray.h" \ - "$(ice_cpp_dir)\include\IceUtil\Iterator.h" \ - "$(ice_cpp_dir)\include\Ice\Proxy.h" \ - "$(ice_cpp_dir)\include\IceUtil\Mutex.h" \ - "$(ice_cpp_dir)\include\IceUtil\Lock.h" \ - "$(ice_cpp_dir)\include\IceUtil\ThreadException.h" \ - "$(ice_cpp_dir)\include\IceUtil\Time.h" \ - "$(ice_cpp_dir)\include\IceUtil\MutexProtocol.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyFactoryF.h" \ - "$(ice_cpp_dir)\include\Ice\ConnectionIF.h" \ - "$(ice_cpp_dir)\include\Ice\RequestHandlerF.h" \ - "$(ice_cpp_dir)\include\Ice\EndpointF.h" \ - "$(ice_cpp_dir)\include\IceUtil\Optional.h" \ - "$(ice_cpp_dir)\include\IceUtil\UndefSysMacros.h" \ - "$(ice_cpp_dir)\include\IceUtil\PopDisableWarnings.h" \ - "$(ice_cpp_dir)\include\Ice\EndpointTypes.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectAdapterF.h" \ - "$(ice_cpp_dir)\include\Ice\ReferenceF.h" \ - "$(ice_cpp_dir)\include\Ice\BatchRequestQueueF.h" \ - "$(ice_cpp_dir)\include\Ice\AsyncResult.h" \ - "$(ice_cpp_dir)\include\IceUtil\Monitor.h" \ - "$(ice_cpp_dir)\include\IceUtil\Cond.h" \ - "$(ice_cpp_dir)\include\IceUtil\UniquePtr.h" \ - "$(ice_cpp_dir)\include\Ice\CommunicatorF.h" \ - "$(ice_cpp_dir)\include\Ice\ConnectionF.h" \ - "$(ice_cpp_dir)\include\Ice\InstanceF.h" \ - "$(ice_cpp_dir)\include\Ice\AsyncResultF.h" \ - "$(ice_cpp_dir)\include\Ice\ObserverHelper.h" \ - "$(ice_cpp_dir)\include\Ice\Instrumentation.h" \ - "$(ice_cpp_dir)\include\Ice\Current.h" \ - "$(ice_cpp_dir)\include\Ice\Identity.h" \ - "$(ice_cpp_dir)\include\Ice\Version.h" \ - "$(ice_cpp_dir)\include\Ice\BasicStream.h" \ - "$(ice_cpp_dir)\include\IceUtil\StringConverter.h" \ - "$(ice_cpp_dir)\include\Ice\Object.h" \ - "$(ice_cpp_dir)\include\Ice\IncomingAsyncF.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectFactoryF.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectFactoryManagerF.h" \ - "$(ice_cpp_dir)\include\Ice\Buffer.h" \ - "$(ice_cpp_dir)\include\Ice\Protocol.h" \ - "$(ice_cpp_dir)\include\Ice\SlicedDataF.h" \ - "$(ice_cpp_dir)\include\Ice\UserExceptionFactory.h" \ - "$(ice_cpp_dir)\include\Ice\FactoryTable.h" \ - "$(ice_cpp_dir)\include\Ice\Endpoint.h" \ - "$(ice_cpp_dir)\include\Ice\BuiltinSequences.h" \ - "EndpointInfo.h" \ - "Util.h" \ - -Current.obj: \ - Current.cpp \ - "$(ice_cpp_dir)\include\IceUtil\Config.h" \ - "Current.h" \ - "Config.h" \ - "$(ice_cpp_dir)\include\Ice\Current.h" \ - "$(ice_cpp_dir)\include\IceUtil\PushDisableWarnings.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyF.h" \ - "$(ice_cpp_dir)\include\IceUtil\Shared.h" \ - "$(ice_cpp_dir)\include\IceUtil\Atomic.h" \ - "$(ice_cpp_dir)\include\Ice\Config.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyHandle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Handle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\Handle.h" \ - "$(ice_cpp_dir)\include\Ice\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\Format.h" \ - "$(ice_cpp_dir)\include\Ice\StreamF.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObject.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\StreamHelpers.h" \ - "$(ice_cpp_dir)\include\IceUtil\ScopedArray.h" \ - "$(ice_cpp_dir)\include\IceUtil\Iterator.h" \ - "$(ice_cpp_dir)\include\IceUtil\Optional.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectAdapterF.h" \ - "$(ice_cpp_dir)\include\IceUtil\UndefSysMacros.h" \ - "$(ice_cpp_dir)\include\IceUtil\PopDisableWarnings.h" \ - "$(ice_cpp_dir)\include\Ice\ConnectionF.h" \ - "$(ice_cpp_dir)\include\Ice\Identity.h" \ - "$(ice_cpp_dir)\include\Ice\Version.h" \ - "Connection.h" \ - "$(ice_cpp_dir)\include\Ice\CommunicatorF.h" \ - "ObjectAdapter.h" \ - "Util.h" \ - "$(ice_cpp_dir)\include\Ice\BuiltinSequences.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectAdapter.h" \ - "$(ice_cpp_dir)\include\Ice\Proxy.h" \ - "$(ice_cpp_dir)\include\IceUtil\Mutex.h" \ - "$(ice_cpp_dir)\include\IceUtil\Lock.h" \ - "$(ice_cpp_dir)\include\IceUtil\ThreadException.h" \ - "$(ice_cpp_dir)\include\IceUtil\Time.h" \ - "$(ice_cpp_dir)\include\IceUtil\MutexProtocol.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyFactoryF.h" \ - "$(ice_cpp_dir)\include\Ice\ConnectionIF.h" \ - "$(ice_cpp_dir)\include\Ice\RequestHandlerF.h" \ - "$(ice_cpp_dir)\include\Ice\EndpointF.h" \ - "$(ice_cpp_dir)\include\Ice\EndpointTypes.h" \ - "$(ice_cpp_dir)\include\Ice\ReferenceF.h" \ - "$(ice_cpp_dir)\include\Ice\BatchRequestQueueF.h" \ - "$(ice_cpp_dir)\include\Ice\AsyncResult.h" \ - "$(ice_cpp_dir)\include\IceUtil\Monitor.h" \ - "$(ice_cpp_dir)\include\IceUtil\Cond.h" \ - "$(ice_cpp_dir)\include\IceUtil\UniquePtr.h" \ - "$(ice_cpp_dir)\include\Ice\InstanceF.h" \ - "$(ice_cpp_dir)\include\Ice\AsyncResultF.h" \ - "$(ice_cpp_dir)\include\Ice\ObserverHelper.h" \ - "$(ice_cpp_dir)\include\Ice\Instrumentation.h" \ - "$(ice_cpp_dir)\include\Ice\BasicStream.h" \ - "$(ice_cpp_dir)\include\IceUtil\StringConverter.h" \ - "$(ice_cpp_dir)\include\Ice\Object.h" \ - "$(ice_cpp_dir)\include\Ice\IncomingAsyncF.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectFactoryF.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectFactoryManagerF.h" \ - "$(ice_cpp_dir)\include\Ice\Buffer.h" \ - "$(ice_cpp_dir)\include\Ice\Protocol.h" \ - "$(ice_cpp_dir)\include\Ice\SlicedDataF.h" \ - "$(ice_cpp_dir)\include\Ice\UserExceptionFactory.h" \ - "$(ice_cpp_dir)\include\Ice\FactoryTable.h" \ - "$(ice_cpp_dir)\include\Ice\ServantLocatorF.h" \ - "$(ice_cpp_dir)\include\Ice\LocatorF.h" \ - "$(ice_cpp_dir)\include\Ice\FacetMap.h" \ - "$(ice_cpp_dir)\include\Ice\Endpoint.h" \ - -Endpoint.obj: \ - Endpoint.cpp \ - "$(ice_cpp_dir)\include\IceUtil\Config.h" \ - "Endpoint.h" \ - "Config.h" \ - "$(ice_cpp_dir)\include\Ice\Endpoint.h" \ - "$(ice_cpp_dir)\include\IceUtil\PushDisableWarnings.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyF.h" \ - "$(ice_cpp_dir)\include\IceUtil\Shared.h" \ - "$(ice_cpp_dir)\include\IceUtil\Atomic.h" \ - "$(ice_cpp_dir)\include\Ice\Config.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyHandle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Handle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\Handle.h" \ - "$(ice_cpp_dir)\include\Ice\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\Format.h" \ - "$(ice_cpp_dir)\include\Ice\StreamF.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObject.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\StreamHelpers.h" \ - "$(ice_cpp_dir)\include\IceUtil\ScopedArray.h" \ - "$(ice_cpp_dir)\include\IceUtil\Iterator.h" \ - "$(ice_cpp_dir)\include\IceUtil\Optional.h" \ - "$(ice_cpp_dir)\include\Ice\Version.h" \ - "$(ice_cpp_dir)\include\IceUtil\UndefSysMacros.h" \ - "$(ice_cpp_dir)\include\IceUtil\PopDisableWarnings.h" \ - "$(ice_cpp_dir)\include\Ice\BuiltinSequences.h" \ - "$(ice_cpp_dir)\include\Ice\EndpointF.h" \ - "EndpointInfo.h" \ - "Util.h" \ - "$(ice_cpp_dir)\include\Ice\Current.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectAdapterF.h" \ - "$(ice_cpp_dir)\include\Ice\ConnectionF.h" \ - "$(ice_cpp_dir)\include\Ice\Identity.h" \ - -EndpointInfo.obj: \ - EndpointInfo.cpp \ - "$(ice_cpp_dir)\include\IceUtil\Config.h" \ - "EndpointInfo.h" \ - "Config.h" \ - "$(ice_cpp_dir)\include\Ice\Endpoint.h" \ - "$(ice_cpp_dir)\include\IceUtil\PushDisableWarnings.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyF.h" \ - "$(ice_cpp_dir)\include\IceUtil\Shared.h" \ - "$(ice_cpp_dir)\include\IceUtil\Atomic.h" \ - "$(ice_cpp_dir)\include\Ice\Config.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyHandle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Handle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\Handle.h" \ - "$(ice_cpp_dir)\include\Ice\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\Format.h" \ - "$(ice_cpp_dir)\include\Ice\StreamF.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObject.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\StreamHelpers.h" \ - "$(ice_cpp_dir)\include\IceUtil\ScopedArray.h" \ - "$(ice_cpp_dir)\include\IceUtil\Iterator.h" \ - "$(ice_cpp_dir)\include\IceUtil\Optional.h" \ - "$(ice_cpp_dir)\include\Ice\Version.h" \ - "$(ice_cpp_dir)\include\IceUtil\UndefSysMacros.h" \ - "$(ice_cpp_dir)\include\IceUtil\PopDisableWarnings.h" \ - "$(ice_cpp_dir)\include\Ice\BuiltinSequences.h" \ - "$(ice_cpp_dir)\include\Ice\EndpointF.h" \ - "Util.h" \ - "$(ice_cpp_dir)\include\Ice\Current.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectAdapterF.h" \ - "$(ice_cpp_dir)\include\Ice\ConnectionF.h" \ - "$(ice_cpp_dir)\include\Ice\Identity.h" \ - -ImplicitContext.obj: \ - ImplicitContext.cpp \ - "$(ice_cpp_dir)\include\IceUtil\Config.h" \ - "ImplicitContext.h" \ - "Config.h" \ - "$(ice_cpp_dir)\include\Ice\ImplicitContext.h" \ - "$(ice_cpp_dir)\include\IceUtil\PushDisableWarnings.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyF.h" \ - "$(ice_cpp_dir)\include\IceUtil\Shared.h" \ - "$(ice_cpp_dir)\include\IceUtil\Atomic.h" \ - "$(ice_cpp_dir)\include\Ice\Config.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyHandle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Handle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\Handle.h" \ - "$(ice_cpp_dir)\include\Ice\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\Format.h" \ - "$(ice_cpp_dir)\include\Ice\StreamF.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObject.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\StreamHelpers.h" \ - "$(ice_cpp_dir)\include\IceUtil\ScopedArray.h" \ - "$(ice_cpp_dir)\include\IceUtil\Iterator.h" \ - "$(ice_cpp_dir)\include\IceUtil\Optional.h" \ - "$(ice_cpp_dir)\include\Ice\LocalException.h" \ - "$(ice_cpp_dir)\include\Ice\Identity.h" \ - "$(ice_cpp_dir)\include\IceUtil\UndefSysMacros.h" \ - "$(ice_cpp_dir)\include\IceUtil\PopDisableWarnings.h" \ - "$(ice_cpp_dir)\include\Ice\Version.h" \ - "$(ice_cpp_dir)\include\Ice\BuiltinSequences.h" \ - "$(ice_cpp_dir)\include\Ice\Current.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectAdapterF.h" \ - "$(ice_cpp_dir)\include\Ice\ConnectionF.h" \ - "ObjectAdapter.h" \ - "Proxy.h" \ - "$(ice_cpp_dir)\include\Ice\CommunicatorF.h" \ - "Util.h" \ - -Init.obj: \ - Init.cpp \ - "$(ice_cpp_dir)\include\IceUtil\Config.h" \ - "BatchRequestInterceptor.h" \ - "Config.h" \ - "Util.h" \ - "$(ice_cpp_dir)\include\Ice\BuiltinSequences.h" \ - "$(ice_cpp_dir)\include\IceUtil\PushDisableWarnings.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyF.h" \ - "$(ice_cpp_dir)\include\IceUtil\Shared.h" \ - "$(ice_cpp_dir)\include\IceUtil\Atomic.h" \ - "$(ice_cpp_dir)\include\Ice\Config.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyHandle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Handle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\Handle.h" \ - "$(ice_cpp_dir)\include\Ice\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\Format.h" \ - "$(ice_cpp_dir)\include\Ice\StreamF.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObject.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\StreamHelpers.h" \ - "$(ice_cpp_dir)\include\IceUtil\ScopedArray.h" \ - "$(ice_cpp_dir)\include\IceUtil\Iterator.h" \ - "$(ice_cpp_dir)\include\IceUtil\Optional.h" \ - "$(ice_cpp_dir)\include\IceUtil\UndefSysMacros.h" \ - "$(ice_cpp_dir)\include\IceUtil\PopDisableWarnings.h" \ - "$(ice_cpp_dir)\include\Ice\Current.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectAdapterF.h" \ - "$(ice_cpp_dir)\include\Ice\ConnectionF.h" \ - "$(ice_cpp_dir)\include\Ice\Identity.h" \ - "$(ice_cpp_dir)\include\Ice\Version.h" \ - "$(ice_cpp_dir)\include\Ice\BatchRequestInterceptor.h" \ - "Communicator.h" \ - "$(ice_cpp_dir)\include\Ice\CommunicatorF.h" \ - "Connection.h" \ - "ConnectionInfo.h" \ - "$(ice_cpp_dir)\include\Ice\Connection.h" \ - "$(ice_cpp_dir)\include\Ice\Proxy.h" \ - "$(ice_cpp_dir)\include\IceUtil\Mutex.h" \ - "$(ice_cpp_dir)\include\IceUtil\Lock.h" \ - "$(ice_cpp_dir)\include\IceUtil\ThreadException.h" \ - "$(ice_cpp_dir)\include\IceUtil\Time.h" \ - "$(ice_cpp_dir)\include\IceUtil\MutexProtocol.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyFactoryF.h" \ - "$(ice_cpp_dir)\include\Ice\ConnectionIF.h" \ - "$(ice_cpp_dir)\include\Ice\RequestHandlerF.h" \ - "$(ice_cpp_dir)\include\Ice\EndpointF.h" \ - "$(ice_cpp_dir)\include\Ice\EndpointTypes.h" \ - "$(ice_cpp_dir)\include\Ice\ReferenceF.h" \ - "$(ice_cpp_dir)\include\Ice\BatchRequestQueueF.h" \ - "$(ice_cpp_dir)\include\Ice\AsyncResult.h" \ - "$(ice_cpp_dir)\include\IceUtil\Monitor.h" \ - "$(ice_cpp_dir)\include\IceUtil\Cond.h" \ - "$(ice_cpp_dir)\include\IceUtil\UniquePtr.h" \ - "$(ice_cpp_dir)\include\Ice\InstanceF.h" \ - "$(ice_cpp_dir)\include\Ice\AsyncResultF.h" \ - "$(ice_cpp_dir)\include\Ice\ObserverHelper.h" \ - "$(ice_cpp_dir)\include\Ice\Instrumentation.h" \ - "$(ice_cpp_dir)\include\Ice\BasicStream.h" \ - "$(ice_cpp_dir)\include\IceUtil\StringConverter.h" \ - "$(ice_cpp_dir)\include\Ice\Object.h" \ - "$(ice_cpp_dir)\include\Ice\IncomingAsyncF.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectFactoryF.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectFactoryManagerF.h" \ - "$(ice_cpp_dir)\include\Ice\Buffer.h" \ - "$(ice_cpp_dir)\include\Ice\Protocol.h" \ - "$(ice_cpp_dir)\include\Ice\SlicedDataF.h" \ - "$(ice_cpp_dir)\include\Ice\UserExceptionFactory.h" \ - "$(ice_cpp_dir)\include\Ice\FactoryTable.h" \ - "$(ice_cpp_dir)\include\Ice\Endpoint.h" \ - "Current.h" \ - "Endpoint.h" \ - "EndpointInfo.h" \ - "ImplicitContext.h" \ - "$(ice_cpp_dir)\include\Ice\ImplicitContext.h" \ - "$(ice_cpp_dir)\include\Ice\LocalException.h" \ - "Logger.h" \ - "$(ice_cpp_dir)\include\Ice\Logger.h" \ - "ObjectAdapter.h" \ - "Operation.h" \ - "Properties.h" \ - "$(ice_cpp_dir)\include\Ice\PropertiesF.h" \ - "PropertiesAdmin.h" \ - "$(ice_cpp_dir)\include\Ice\NativePropertiesAdmin.h" \ - "$(ice_cpp_dir)\include\Ice\PropertiesAdmin.h" \ - "$(ice_cpp_dir)\include\Ice\GCObject.h" \ - "$(ice_cpp_dir)\include\IceUtil\MutexPtrLock.h" \ - "$(ice_cpp_dir)\include\Ice\Incoming.h" \ - "$(ice_cpp_dir)\include\Ice\ServantLocatorF.h" \ - "$(ice_cpp_dir)\include\Ice\ServantManagerF.h" \ - "$(ice_cpp_dir)\include\Ice\ResponseHandlerF.h" \ - "$(ice_cpp_dir)\include\Ice\IncomingAsync.h" \ - "Proxy.h" \ - "Slice.h" \ - "Types.h" \ - "$(ice_cpp_dir)\include\Ice\Stream.h" \ - "$(ice_cpp_dir)\include\IceUtil\OutputUtil.h" \ - "$(ice_cpp_dir)\include\Ice\Initialize.h" \ - "$(ice_cpp_dir)\include\IceUtil\Timer.h" \ - "$(ice_cpp_dir)\include\IceUtil\Thread.h" \ - "$(ice_cpp_dir)\include\Ice\LoggerF.h" \ - "$(ice_cpp_dir)\include\Ice\InstrumentationF.h" \ - "$(ice_cpp_dir)\include\Ice\Dispatcher.h" \ - "$(ice_cpp_dir)\include\Ice\Plugin.h" \ - -Logger.obj: \ - Logger.cpp \ - "$(ice_cpp_dir)\include\IceUtil\Config.h" \ - "Logger.h" \ - "Config.h" \ - "Util.h" \ - "$(ice_cpp_dir)\include\Ice\BuiltinSequences.h" \ - "$(ice_cpp_dir)\include\IceUtil\PushDisableWarnings.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyF.h" \ - "$(ice_cpp_dir)\include\IceUtil\Shared.h" \ - "$(ice_cpp_dir)\include\IceUtil\Atomic.h" \ - "$(ice_cpp_dir)\include\Ice\Config.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyHandle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Handle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\Handle.h" \ - "$(ice_cpp_dir)\include\Ice\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\Format.h" \ - "$(ice_cpp_dir)\include\Ice\StreamF.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObject.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\StreamHelpers.h" \ - "$(ice_cpp_dir)\include\IceUtil\ScopedArray.h" \ - "$(ice_cpp_dir)\include\IceUtil\Iterator.h" \ - "$(ice_cpp_dir)\include\IceUtil\Optional.h" \ - "$(ice_cpp_dir)\include\IceUtil\UndefSysMacros.h" \ - "$(ice_cpp_dir)\include\IceUtil\PopDisableWarnings.h" \ - "$(ice_cpp_dir)\include\Ice\Current.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectAdapterF.h" \ - "$(ice_cpp_dir)\include\Ice\ConnectionF.h" \ - "$(ice_cpp_dir)\include\Ice\Identity.h" \ - "$(ice_cpp_dir)\include\Ice\Version.h" \ - "$(ice_cpp_dir)\include\Ice\Logger.h" \ - "Thread.h" \ - "$(ice_cpp_dir)\include\Ice\Initialize.h" \ - "$(ice_cpp_dir)\include\IceUtil\Timer.h" \ - "$(ice_cpp_dir)\include\IceUtil\Thread.h" \ - "$(ice_cpp_dir)\include\IceUtil\Mutex.h" \ - "$(ice_cpp_dir)\include\IceUtil\Lock.h" \ - "$(ice_cpp_dir)\include\IceUtil\ThreadException.h" \ - "$(ice_cpp_dir)\include\IceUtil\Time.h" \ - "$(ice_cpp_dir)\include\IceUtil\MutexProtocol.h" \ - "$(ice_cpp_dir)\include\IceUtil\Monitor.h" \ - "$(ice_cpp_dir)\include\IceUtil\Cond.h" \ - "$(ice_cpp_dir)\include\Ice\CommunicatorF.h" \ - "$(ice_cpp_dir)\include\Ice\PropertiesF.h" \ - "$(ice_cpp_dir)\include\Ice\Proxy.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyFactoryF.h" \ - "$(ice_cpp_dir)\include\Ice\ConnectionIF.h" \ - "$(ice_cpp_dir)\include\Ice\RequestHandlerF.h" \ - "$(ice_cpp_dir)\include\Ice\EndpointF.h" \ - "$(ice_cpp_dir)\include\Ice\EndpointTypes.h" \ - "$(ice_cpp_dir)\include\Ice\ReferenceF.h" \ - "$(ice_cpp_dir)\include\Ice\BatchRequestQueueF.h" \ - "$(ice_cpp_dir)\include\Ice\AsyncResult.h" \ - "$(ice_cpp_dir)\include\IceUtil\UniquePtr.h" \ - "$(ice_cpp_dir)\include\Ice\InstanceF.h" \ - "$(ice_cpp_dir)\include\Ice\AsyncResultF.h" \ - "$(ice_cpp_dir)\include\Ice\ObserverHelper.h" \ - "$(ice_cpp_dir)\include\Ice\Instrumentation.h" \ - "$(ice_cpp_dir)\include\Ice\BasicStream.h" \ - "$(ice_cpp_dir)\include\IceUtil\StringConverter.h" \ - "$(ice_cpp_dir)\include\Ice\Object.h" \ - "$(ice_cpp_dir)\include\Ice\IncomingAsyncF.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectFactoryF.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectFactoryManagerF.h" \ - "$(ice_cpp_dir)\include\Ice\Buffer.h" \ - "$(ice_cpp_dir)\include\Ice\Protocol.h" \ - "$(ice_cpp_dir)\include\Ice\SlicedDataF.h" \ - "$(ice_cpp_dir)\include\Ice\UserExceptionFactory.h" \ - "$(ice_cpp_dir)\include\Ice\FactoryTable.h" \ - "$(ice_cpp_dir)\include\Ice\LoggerF.h" \ - "$(ice_cpp_dir)\include\Ice\InstrumentationF.h" \ - "$(ice_cpp_dir)\include\Ice\Dispatcher.h" \ - "$(ice_cpp_dir)\include\Ice\Plugin.h" \ - "$(ice_cpp_dir)\include\Ice\BatchRequestInterceptor.h" \ - -ObjectAdapter.obj: \ - ObjectAdapter.cpp \ - "$(ice_cpp_dir)\include\IceUtil\Config.h" \ - "ObjectAdapter.h" \ - "Config.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectAdapterF.h" \ - "$(ice_cpp_dir)\include\IceUtil\PushDisableWarnings.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyF.h" \ - "$(ice_cpp_dir)\include\IceUtil\Shared.h" \ - "$(ice_cpp_dir)\include\IceUtil\Atomic.h" \ - "$(ice_cpp_dir)\include\Ice\Config.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyHandle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Handle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\Handle.h" \ - "$(ice_cpp_dir)\include\Ice\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\Format.h" \ - "$(ice_cpp_dir)\include\Ice\StreamF.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObject.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\StreamHelpers.h" \ - "$(ice_cpp_dir)\include\IceUtil\ScopedArray.h" \ - "$(ice_cpp_dir)\include\IceUtil\Iterator.h" \ - "$(ice_cpp_dir)\include\IceUtil\Optional.h" \ - "$(ice_cpp_dir)\include\IceUtil\UndefSysMacros.h" \ - "$(ice_cpp_dir)\include\IceUtil\PopDisableWarnings.h" \ - "Communicator.h" \ - "$(ice_cpp_dir)\include\Ice\CommunicatorF.h" \ - "Current.h" \ - "$(ice_cpp_dir)\include\Ice\Current.h" \ - "$(ice_cpp_dir)\include\Ice\ConnectionF.h" \ - "$(ice_cpp_dir)\include\Ice\Identity.h" \ - "$(ice_cpp_dir)\include\Ice\Version.h" \ - "Endpoint.h" \ - "$(ice_cpp_dir)\include\Ice\Endpoint.h" \ - "$(ice_cpp_dir)\include\Ice\BuiltinSequences.h" \ - "$(ice_cpp_dir)\include\Ice\EndpointF.h" \ - "Operation.h" \ - "$(ice_cpp_dir)\include\Ice\Object.h" \ - "$(ice_cpp_dir)\include\IceUtil\Mutex.h" \ - "$(ice_cpp_dir)\include\IceUtil\Lock.h" \ - "$(ice_cpp_dir)\include\IceUtil\ThreadException.h" \ - "$(ice_cpp_dir)\include\IceUtil\Time.h" \ - "$(ice_cpp_dir)\include\IceUtil\MutexProtocol.h" \ - "$(ice_cpp_dir)\include\Ice\IncomingAsyncF.h" \ - "$(ice_cpp_dir)\include\Ice\AsyncResultF.h" \ - "Proxy.h" \ - "Thread.h" \ - "Util.h" \ - "$(ice_cpp_dir)\include\Ice\Initialize.h" \ - "$(ice_cpp_dir)\include\IceUtil\Timer.h" \ - "$(ice_cpp_dir)\include\IceUtil\Thread.h" \ - "$(ice_cpp_dir)\include\IceUtil\Monitor.h" \ - "$(ice_cpp_dir)\include\IceUtil\Cond.h" \ - "$(ice_cpp_dir)\include\Ice\PropertiesF.h" \ - "$(ice_cpp_dir)\include\Ice\Proxy.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyFactoryF.h" \ - "$(ice_cpp_dir)\include\Ice\ConnectionIF.h" \ - "$(ice_cpp_dir)\include\Ice\RequestHandlerF.h" \ - "$(ice_cpp_dir)\include\Ice\EndpointTypes.h" \ - "$(ice_cpp_dir)\include\Ice\ReferenceF.h" \ - "$(ice_cpp_dir)\include\Ice\BatchRequestQueueF.h" \ - "$(ice_cpp_dir)\include\Ice\AsyncResult.h" \ - "$(ice_cpp_dir)\include\IceUtil\UniquePtr.h" \ - "$(ice_cpp_dir)\include\Ice\InstanceF.h" \ - "$(ice_cpp_dir)\include\Ice\ObserverHelper.h" \ - "$(ice_cpp_dir)\include\Ice\Instrumentation.h" \ - "$(ice_cpp_dir)\include\Ice\BasicStream.h" \ - "$(ice_cpp_dir)\include\IceUtil\StringConverter.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectFactoryF.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectFactoryManagerF.h" \ - "$(ice_cpp_dir)\include\Ice\Buffer.h" \ - "$(ice_cpp_dir)\include\Ice\Protocol.h" \ - "$(ice_cpp_dir)\include\Ice\SlicedDataF.h" \ - "$(ice_cpp_dir)\include\Ice\UserExceptionFactory.h" \ - "$(ice_cpp_dir)\include\Ice\FactoryTable.h" \ - "$(ice_cpp_dir)\include\Ice\LoggerF.h" \ - "$(ice_cpp_dir)\include\Ice\InstrumentationF.h" \ - "$(ice_cpp_dir)\include\Ice\Dispatcher.h" \ - "$(ice_cpp_dir)\include\Ice\Plugin.h" \ - "$(ice_cpp_dir)\include\Ice\BatchRequestInterceptor.h" \ - "Types.h" \ - "$(ice_cpp_dir)\include\Ice\Stream.h" \ - "$(ice_cpp_dir)\include\IceUtil\OutputUtil.h" \ - "$(ice_cpp_dir)\include\Ice\Communicator.h" \ - "$(ice_cpp_dir)\include\Ice\GCObject.h" \ - "$(ice_cpp_dir)\include\IceUtil\MutexPtrLock.h" \ - "$(ice_cpp_dir)\include\Ice\Incoming.h" \ - "$(ice_cpp_dir)\include\Ice\ServantLocatorF.h" \ - "$(ice_cpp_dir)\include\Ice\ServantManagerF.h" \ - "$(ice_cpp_dir)\include\Ice\ResponseHandlerF.h" \ - "$(ice_cpp_dir)\include\Ice\IncomingAsync.h" \ - "$(ice_cpp_dir)\include\Ice\RouterF.h" \ - "$(ice_cpp_dir)\include\Ice\LocatorF.h" \ - "$(ice_cpp_dir)\include\Ice\PluginF.h" \ - "$(ice_cpp_dir)\include\Ice\ImplicitContextF.h" \ - "$(ice_cpp_dir)\include\Ice\Properties.h" \ - "$(ice_cpp_dir)\include\Ice\PropertiesAdmin.h" \ - "$(ice_cpp_dir)\include\Ice\FacetMap.h" \ - "$(ice_cpp_dir)\include\Ice\LocalException.h" \ - "$(ice_cpp_dir)\include\Ice\Locator.h" \ - "$(ice_cpp_dir)\include\Ice\FactoryTableInit.h" \ - "$(ice_cpp_dir)\include\Ice\DefaultObjectFactory.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectFactory.h" \ - "$(ice_cpp_dir)\include\Ice\ProcessF.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectAdapter.h" \ - "$(ice_cpp_dir)\include\Ice\Router.h" \ - "$(ice_cpp_dir)\include\Ice\ServantLocator.h" \ - -ObjectFactory.obj: \ - ObjectFactory.cpp \ - "$(ice_cpp_dir)\include\IceUtil\Config.h" \ - "ObjectFactory.h" \ - "Config.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectF.h" \ - "$(ice_cpp_dir)\include\IceUtil\Shared.h" \ - "$(ice_cpp_dir)\include\IceUtil\Atomic.h" \ - "$(ice_cpp_dir)\include\Ice\Handle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Handle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\Config.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectFactory.h" \ - "$(ice_cpp_dir)\include\IceUtil\PushDisableWarnings.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyF.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyHandle.h" \ - "$(ice_cpp_dir)\include\Ice\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\Format.h" \ - "$(ice_cpp_dir)\include\Ice\StreamF.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObject.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\StreamHelpers.h" \ - "$(ice_cpp_dir)\include\IceUtil\ScopedArray.h" \ - "$(ice_cpp_dir)\include\IceUtil\Iterator.h" \ - "$(ice_cpp_dir)\include\IceUtil\Optional.h" \ - "$(ice_cpp_dir)\include\IceUtil\UndefSysMacros.h" \ - "$(ice_cpp_dir)\include\IceUtil\PopDisableWarnings.h" \ - "$(ice_cpp_dir)\include\IceUtil\Mutex.h" \ - "$(ice_cpp_dir)\include\IceUtil\Lock.h" \ - "$(ice_cpp_dir)\include\IceUtil\ThreadException.h" \ - "$(ice_cpp_dir)\include\IceUtil\Time.h" \ - "$(ice_cpp_dir)\include\IceUtil\MutexProtocol.h" \ - "Thread.h" \ - "Util.h" \ - "$(ice_cpp_dir)\include\Ice\BuiltinSequences.h" \ - "$(ice_cpp_dir)\include\Ice\Current.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectAdapterF.h" \ - "$(ice_cpp_dir)\include\Ice\ConnectionF.h" \ - "$(ice_cpp_dir)\include\Ice\Identity.h" \ - "$(ice_cpp_dir)\include\Ice\Version.h" \ - "$(ice_cpp_dir)\include\Ice\Initialize.h" \ - "$(ice_cpp_dir)\include\IceUtil\Timer.h" \ - "$(ice_cpp_dir)\include\IceUtil\Thread.h" \ - "$(ice_cpp_dir)\include\IceUtil\Monitor.h" \ - "$(ice_cpp_dir)\include\IceUtil\Cond.h" \ - "$(ice_cpp_dir)\include\Ice\CommunicatorF.h" \ - "$(ice_cpp_dir)\include\Ice\PropertiesF.h" \ - "$(ice_cpp_dir)\include\Ice\Proxy.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyFactoryF.h" \ - "$(ice_cpp_dir)\include\Ice\ConnectionIF.h" \ - "$(ice_cpp_dir)\include\Ice\RequestHandlerF.h" \ - "$(ice_cpp_dir)\include\Ice\EndpointF.h" \ - "$(ice_cpp_dir)\include\Ice\EndpointTypes.h" \ - "$(ice_cpp_dir)\include\Ice\ReferenceF.h" \ - "$(ice_cpp_dir)\include\Ice\BatchRequestQueueF.h" \ - "$(ice_cpp_dir)\include\Ice\AsyncResult.h" \ - "$(ice_cpp_dir)\include\IceUtil\UniquePtr.h" \ - "$(ice_cpp_dir)\include\Ice\InstanceF.h" \ - "$(ice_cpp_dir)\include\Ice\AsyncResultF.h" \ - "$(ice_cpp_dir)\include\Ice\ObserverHelper.h" \ - "$(ice_cpp_dir)\include\Ice\Instrumentation.h" \ - "$(ice_cpp_dir)\include\Ice\BasicStream.h" \ - "$(ice_cpp_dir)\include\IceUtil\StringConverter.h" \ - "$(ice_cpp_dir)\include\Ice\Object.h" \ - "$(ice_cpp_dir)\include\Ice\IncomingAsyncF.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectFactoryF.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectFactoryManagerF.h" \ - "$(ice_cpp_dir)\include\Ice\Buffer.h" \ - "$(ice_cpp_dir)\include\Ice\Protocol.h" \ - "$(ice_cpp_dir)\include\Ice\SlicedDataF.h" \ - "$(ice_cpp_dir)\include\Ice\UserExceptionFactory.h" \ - "$(ice_cpp_dir)\include\Ice\FactoryTable.h" \ - "$(ice_cpp_dir)\include\Ice\LoggerF.h" \ - "$(ice_cpp_dir)\include\Ice\InstrumentationF.h" \ - "$(ice_cpp_dir)\include\Ice\Dispatcher.h" \ - "$(ice_cpp_dir)\include\Ice\Plugin.h" \ - "$(ice_cpp_dir)\include\Ice\BatchRequestInterceptor.h" \ - "Types.h" \ - "$(ice_cpp_dir)\include\Ice\Stream.h" \ - "$(ice_cpp_dir)\include\IceUtil\OutputUtil.h" \ - "$(ice_cpp_dir)\include\Ice\LocalException.h" \ - -Operation.obj: \ - Operation.cpp \ - "$(ice_cpp_dir)\include\IceUtil\Config.h" \ - "Operation.h" \ - "Config.h" \ - "$(ice_cpp_dir)\include\Ice\Current.h" \ - "$(ice_cpp_dir)\include\IceUtil\PushDisableWarnings.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyF.h" \ - "$(ice_cpp_dir)\include\IceUtil\Shared.h" \ - "$(ice_cpp_dir)\include\IceUtil\Atomic.h" \ - "$(ice_cpp_dir)\include\Ice\Config.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyHandle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Handle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\Handle.h" \ - "$(ice_cpp_dir)\include\Ice\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\Format.h" \ - "$(ice_cpp_dir)\include\Ice\StreamF.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObject.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\StreamHelpers.h" \ - "$(ice_cpp_dir)\include\IceUtil\ScopedArray.h" \ - "$(ice_cpp_dir)\include\IceUtil\Iterator.h" \ - "$(ice_cpp_dir)\include\IceUtil\Optional.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectAdapterF.h" \ - "$(ice_cpp_dir)\include\IceUtil\UndefSysMacros.h" \ - "$(ice_cpp_dir)\include\IceUtil\PopDisableWarnings.h" \ - "$(ice_cpp_dir)\include\Ice\ConnectionF.h" \ - "$(ice_cpp_dir)\include\Ice\Identity.h" \ - "$(ice_cpp_dir)\include\Ice\Version.h" \ - "$(ice_cpp_dir)\include\Ice\Object.h" \ - "$(ice_cpp_dir)\include\IceUtil\Mutex.h" \ - "$(ice_cpp_dir)\include\IceUtil\Lock.h" \ - "$(ice_cpp_dir)\include\IceUtil\ThreadException.h" \ - "$(ice_cpp_dir)\include\IceUtil\Time.h" \ - "$(ice_cpp_dir)\include\IceUtil\MutexProtocol.h" \ - "$(ice_cpp_dir)\include\Ice\IncomingAsyncF.h" \ - "$(ice_cpp_dir)\include\Ice\AsyncResultF.h" \ - "$(ice_cpp_dir)\include\Ice\CommunicatorF.h" \ - "Communicator.h" \ - "Current.h" \ - "Proxy.h" \ - "Thread.h" \ - "Util.h" \ - "$(ice_cpp_dir)\include\Ice\BuiltinSequences.h" \ - "$(ice_cpp_dir)\include\Ice\Initialize.h" \ - "$(ice_cpp_dir)\include\IceUtil\Timer.h" \ - "$(ice_cpp_dir)\include\IceUtil\Thread.h" \ - "$(ice_cpp_dir)\include\IceUtil\Monitor.h" \ - "$(ice_cpp_dir)\include\IceUtil\Cond.h" \ - "$(ice_cpp_dir)\include\Ice\PropertiesF.h" \ - "$(ice_cpp_dir)\include\Ice\Proxy.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyFactoryF.h" \ - "$(ice_cpp_dir)\include\Ice\ConnectionIF.h" \ - "$(ice_cpp_dir)\include\Ice\RequestHandlerF.h" \ - "$(ice_cpp_dir)\include\Ice\EndpointF.h" \ - "$(ice_cpp_dir)\include\Ice\EndpointTypes.h" \ - "$(ice_cpp_dir)\include\Ice\ReferenceF.h" \ - "$(ice_cpp_dir)\include\Ice\BatchRequestQueueF.h" \ - "$(ice_cpp_dir)\include\Ice\AsyncResult.h" \ - "$(ice_cpp_dir)\include\IceUtil\UniquePtr.h" \ - "$(ice_cpp_dir)\include\Ice\InstanceF.h" \ - "$(ice_cpp_dir)\include\Ice\ObserverHelper.h" \ - "$(ice_cpp_dir)\include\Ice\Instrumentation.h" \ - "$(ice_cpp_dir)\include\Ice\BasicStream.h" \ - "$(ice_cpp_dir)\include\IceUtil\StringConverter.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectFactoryF.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectFactoryManagerF.h" \ - "$(ice_cpp_dir)\include\Ice\Buffer.h" \ - "$(ice_cpp_dir)\include\Ice\Protocol.h" \ - "$(ice_cpp_dir)\include\Ice\SlicedDataF.h" \ - "$(ice_cpp_dir)\include\Ice\UserExceptionFactory.h" \ - "$(ice_cpp_dir)\include\Ice\FactoryTable.h" \ - "$(ice_cpp_dir)\include\Ice\LoggerF.h" \ - "$(ice_cpp_dir)\include\Ice\InstrumentationF.h" \ - "$(ice_cpp_dir)\include\Ice\Dispatcher.h" \ - "$(ice_cpp_dir)\include\Ice\Plugin.h" \ - "$(ice_cpp_dir)\include\Ice\BatchRequestInterceptor.h" \ - "Types.h" \ - "$(ice_cpp_dir)\include\Ice\Stream.h" \ - "$(ice_cpp_dir)\include\IceUtil\OutputUtil.h" \ - "Connection.h" \ - "$(ice_cpp_dir)\include\Ice\Communicator.h" \ - "$(ice_cpp_dir)\include\Ice\GCObject.h" \ - "$(ice_cpp_dir)\include\IceUtil\MutexPtrLock.h" \ - "$(ice_cpp_dir)\include\Ice\Incoming.h" \ - "$(ice_cpp_dir)\include\Ice\ServantLocatorF.h" \ - "$(ice_cpp_dir)\include\Ice\ServantManagerF.h" \ - "$(ice_cpp_dir)\include\Ice\ResponseHandlerF.h" \ - "$(ice_cpp_dir)\include\Ice\IncomingAsync.h" \ - "$(ice_cpp_dir)\include\Ice\RouterF.h" \ - "$(ice_cpp_dir)\include\Ice\LocatorF.h" \ - "$(ice_cpp_dir)\include\Ice\PluginF.h" \ - "$(ice_cpp_dir)\include\Ice\ImplicitContextF.h" \ - "$(ice_cpp_dir)\include\Ice\Properties.h" \ - "$(ice_cpp_dir)\include\Ice\PropertiesAdmin.h" \ - "$(ice_cpp_dir)\include\Ice\FacetMap.h" \ - "$(ice_cpp_dir)\include\Ice\LocalException.h" \ - "$(ice_cpp_dir)\include\Ice\Logger.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectAdapter.h" \ - "$(ice_cpp_dir)\include\Ice\Endpoint.h" \ - "$(ice_cpp_dir)\include\Slice\PythonUtil.h" \ - "$(ice_cpp_dir)\include\Slice\Parser.h" \ - -Properties.obj: \ - Properties.cpp \ - "$(ice_cpp_dir)\include\IceUtil\Config.h" \ - "Properties.h" \ - "Config.h" \ - "$(ice_cpp_dir)\include\Ice\PropertiesF.h" \ - "$(ice_cpp_dir)\include\IceUtil\PushDisableWarnings.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyF.h" \ - "$(ice_cpp_dir)\include\IceUtil\Shared.h" \ - "$(ice_cpp_dir)\include\IceUtil\Atomic.h" \ - "$(ice_cpp_dir)\include\Ice\Config.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyHandle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Handle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\Handle.h" \ - "$(ice_cpp_dir)\include\Ice\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\Format.h" \ - "$(ice_cpp_dir)\include\Ice\StreamF.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObject.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\StreamHelpers.h" \ - "$(ice_cpp_dir)\include\IceUtil\ScopedArray.h" \ - "$(ice_cpp_dir)\include\IceUtil\Iterator.h" \ - "$(ice_cpp_dir)\include\Ice\Proxy.h" \ - "$(ice_cpp_dir)\include\IceUtil\Mutex.h" \ - "$(ice_cpp_dir)\include\IceUtil\Lock.h" \ - "$(ice_cpp_dir)\include\IceUtil\ThreadException.h" \ - "$(ice_cpp_dir)\include\IceUtil\Time.h" \ - "$(ice_cpp_dir)\include\IceUtil\MutexProtocol.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyFactoryF.h" \ - "$(ice_cpp_dir)\include\Ice\ConnectionIF.h" \ - "$(ice_cpp_dir)\include\Ice\RequestHandlerF.h" \ - "$(ice_cpp_dir)\include\Ice\EndpointF.h" \ - "$(ice_cpp_dir)\include\IceUtil\Optional.h" \ - "$(ice_cpp_dir)\include\IceUtil\UndefSysMacros.h" \ - "$(ice_cpp_dir)\include\IceUtil\PopDisableWarnings.h" \ - "$(ice_cpp_dir)\include\Ice\EndpointTypes.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectAdapterF.h" \ - "$(ice_cpp_dir)\include\Ice\ReferenceF.h" \ - "$(ice_cpp_dir)\include\Ice\BatchRequestQueueF.h" \ - "$(ice_cpp_dir)\include\Ice\AsyncResult.h" \ - "$(ice_cpp_dir)\include\IceUtil\Monitor.h" \ - "$(ice_cpp_dir)\include\IceUtil\Cond.h" \ - "$(ice_cpp_dir)\include\IceUtil\UniquePtr.h" \ - "$(ice_cpp_dir)\include\Ice\CommunicatorF.h" \ - "$(ice_cpp_dir)\include\Ice\ConnectionF.h" \ - "$(ice_cpp_dir)\include\Ice\InstanceF.h" \ - "$(ice_cpp_dir)\include\Ice\AsyncResultF.h" \ - "$(ice_cpp_dir)\include\Ice\ObserverHelper.h" \ - "$(ice_cpp_dir)\include\Ice\Instrumentation.h" \ - "$(ice_cpp_dir)\include\Ice\Current.h" \ - "$(ice_cpp_dir)\include\Ice\Identity.h" \ - "$(ice_cpp_dir)\include\Ice\Version.h" \ - "$(ice_cpp_dir)\include\Ice\BasicStream.h" \ - "$(ice_cpp_dir)\include\IceUtil\StringConverter.h" \ - "$(ice_cpp_dir)\include\Ice\Object.h" \ - "$(ice_cpp_dir)\include\Ice\IncomingAsyncF.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectFactoryF.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectFactoryManagerF.h" \ - "$(ice_cpp_dir)\include\Ice\Buffer.h" \ - "$(ice_cpp_dir)\include\Ice\Protocol.h" \ - "$(ice_cpp_dir)\include\Ice\SlicedDataF.h" \ - "$(ice_cpp_dir)\include\Ice\UserExceptionFactory.h" \ - "$(ice_cpp_dir)\include\Ice\FactoryTable.h" \ - "Util.h" \ - "$(ice_cpp_dir)\include\Ice\BuiltinSequences.h" \ - "$(ice_cpp_dir)\include\Ice\Initialize.h" \ - "$(ice_cpp_dir)\include\IceUtil\Timer.h" \ - "$(ice_cpp_dir)\include\IceUtil\Thread.h" \ - "$(ice_cpp_dir)\include\Ice\LoggerF.h" \ - "$(ice_cpp_dir)\include\Ice\InstrumentationF.h" \ - "$(ice_cpp_dir)\include\Ice\Dispatcher.h" \ - "$(ice_cpp_dir)\include\Ice\Plugin.h" \ - "$(ice_cpp_dir)\include\Ice\BatchRequestInterceptor.h" \ - "$(ice_cpp_dir)\include\Ice\Properties.h" \ - "$(ice_cpp_dir)\include\Ice\GCObject.h" \ - "$(ice_cpp_dir)\include\IceUtil\MutexPtrLock.h" \ - "$(ice_cpp_dir)\include\Ice\Incoming.h" \ - "$(ice_cpp_dir)\include\Ice\ServantLocatorF.h" \ - "$(ice_cpp_dir)\include\Ice\ServantManagerF.h" \ - "$(ice_cpp_dir)\include\Ice\ResponseHandlerF.h" \ - "$(ice_cpp_dir)\include\Ice\IncomingAsync.h" \ - "$(ice_cpp_dir)\include\Ice\PropertiesAdmin.h" \ - -PropertiesAdmin.obj: \ - PropertiesAdmin.cpp \ - "$(ice_cpp_dir)\include\IceUtil\Config.h" \ - "$(ice_cpp_dir)\include\IceUtil\DisableWarnings.h" \ - "PropertiesAdmin.h" \ - "Config.h" \ - "$(ice_cpp_dir)\include\Ice\NativePropertiesAdmin.h" \ - "$(ice_cpp_dir)\include\Ice\PropertiesAdmin.h" \ - "$(ice_cpp_dir)\include\IceUtil\PushDisableWarnings.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyF.h" \ - "$(ice_cpp_dir)\include\IceUtil\Shared.h" \ - "$(ice_cpp_dir)\include\IceUtil\Atomic.h" \ - "$(ice_cpp_dir)\include\Ice\Config.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyHandle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Handle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\Handle.h" \ - "$(ice_cpp_dir)\include\Ice\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\Format.h" \ - "$(ice_cpp_dir)\include\Ice\StreamF.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObject.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\StreamHelpers.h" \ - "$(ice_cpp_dir)\include\IceUtil\ScopedArray.h" \ - "$(ice_cpp_dir)\include\IceUtil\Iterator.h" \ - "$(ice_cpp_dir)\include\Ice\Proxy.h" \ - "$(ice_cpp_dir)\include\IceUtil\Mutex.h" \ - "$(ice_cpp_dir)\include\IceUtil\Lock.h" \ - "$(ice_cpp_dir)\include\IceUtil\ThreadException.h" \ - "$(ice_cpp_dir)\include\IceUtil\Time.h" \ - "$(ice_cpp_dir)\include\IceUtil\MutexProtocol.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyFactoryF.h" \ - "$(ice_cpp_dir)\include\Ice\ConnectionIF.h" \ - "$(ice_cpp_dir)\include\Ice\RequestHandlerF.h" \ - "$(ice_cpp_dir)\include\Ice\EndpointF.h" \ - "$(ice_cpp_dir)\include\IceUtil\Optional.h" \ - "$(ice_cpp_dir)\include\IceUtil\UndefSysMacros.h" \ - "$(ice_cpp_dir)\include\IceUtil\PopDisableWarnings.h" \ - "$(ice_cpp_dir)\include\Ice\EndpointTypes.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectAdapterF.h" \ - "$(ice_cpp_dir)\include\Ice\ReferenceF.h" \ - "$(ice_cpp_dir)\include\Ice\BatchRequestQueueF.h" \ - "$(ice_cpp_dir)\include\Ice\AsyncResult.h" \ - "$(ice_cpp_dir)\include\IceUtil\Monitor.h" \ - "$(ice_cpp_dir)\include\IceUtil\Cond.h" \ - "$(ice_cpp_dir)\include\IceUtil\UniquePtr.h" \ - "$(ice_cpp_dir)\include\Ice\CommunicatorF.h" \ - "$(ice_cpp_dir)\include\Ice\ConnectionF.h" \ - "$(ice_cpp_dir)\include\Ice\InstanceF.h" \ - "$(ice_cpp_dir)\include\Ice\AsyncResultF.h" \ - "$(ice_cpp_dir)\include\Ice\ObserverHelper.h" \ - "$(ice_cpp_dir)\include\Ice\Instrumentation.h" \ - "$(ice_cpp_dir)\include\Ice\Current.h" \ - "$(ice_cpp_dir)\include\Ice\Identity.h" \ - "$(ice_cpp_dir)\include\Ice\Version.h" \ - "$(ice_cpp_dir)\include\Ice\BasicStream.h" \ - "$(ice_cpp_dir)\include\IceUtil\StringConverter.h" \ - "$(ice_cpp_dir)\include\Ice\Object.h" \ - "$(ice_cpp_dir)\include\Ice\IncomingAsyncF.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectFactoryF.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectFactoryManagerF.h" \ - "$(ice_cpp_dir)\include\Ice\Buffer.h" \ - "$(ice_cpp_dir)\include\Ice\Protocol.h" \ - "$(ice_cpp_dir)\include\Ice\SlicedDataF.h" \ - "$(ice_cpp_dir)\include\Ice\UserExceptionFactory.h" \ - "$(ice_cpp_dir)\include\Ice\FactoryTable.h" \ - "$(ice_cpp_dir)\include\Ice\GCObject.h" \ - "$(ice_cpp_dir)\include\IceUtil\MutexPtrLock.h" \ - "$(ice_cpp_dir)\include\Ice\Incoming.h" \ - "$(ice_cpp_dir)\include\Ice\ServantLocatorF.h" \ - "$(ice_cpp_dir)\include\Ice\ServantManagerF.h" \ - "$(ice_cpp_dir)\include\Ice\ResponseHandlerF.h" \ - "$(ice_cpp_dir)\include\Ice\IncomingAsync.h" \ - "$(ice_cpp_dir)\include\Ice\BuiltinSequences.h" \ - "Util.h" \ - "Thread.h" \ - "$(ice_cpp_dir)\include\Ice\Initialize.h" \ - "$(ice_cpp_dir)\include\IceUtil\Timer.h" \ - "$(ice_cpp_dir)\include\IceUtil\Thread.h" \ - "$(ice_cpp_dir)\include\Ice\PropertiesF.h" \ - "$(ice_cpp_dir)\include\Ice\LoggerF.h" \ - "$(ice_cpp_dir)\include\Ice\InstrumentationF.h" \ - "$(ice_cpp_dir)\include\Ice\Dispatcher.h" \ - "$(ice_cpp_dir)\include\Ice\Plugin.h" \ - "$(ice_cpp_dir)\include\Ice\BatchRequestInterceptor.h" \ - "Types.h" \ - "$(ice_cpp_dir)\include\Ice\Stream.h" \ - "$(ice_cpp_dir)\include\IceUtil\OutputUtil.h" \ - -Proxy.obj: \ - Proxy.cpp \ - "$(ice_cpp_dir)\include\IceUtil\DisableWarnings.h" \ - "$(ice_cpp_dir)\include\IceUtil\Config.h" \ - "Proxy.h" \ - "Config.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyF.h" \ - "$(ice_cpp_dir)\include\IceUtil\Shared.h" \ - "$(ice_cpp_dir)\include\IceUtil\Atomic.h" \ - "$(ice_cpp_dir)\include\Ice\Config.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyHandle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Handle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\CommunicatorF.h" \ - "$(ice_cpp_dir)\include\IceUtil\PushDisableWarnings.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\Handle.h" \ - "$(ice_cpp_dir)\include\Ice\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\Format.h" \ - "$(ice_cpp_dir)\include\Ice\StreamF.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObject.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\StreamHelpers.h" \ - "$(ice_cpp_dir)\include\IceUtil\ScopedArray.h" \ - "$(ice_cpp_dir)\include\IceUtil\Iterator.h" \ - "$(ice_cpp_dir)\include\IceUtil\Optional.h" \ - "$(ice_cpp_dir)\include\IceUtil\UndefSysMacros.h" \ - "$(ice_cpp_dir)\include\IceUtil\PopDisableWarnings.h" \ - "Communicator.h" \ - "Connection.h" \ - "$(ice_cpp_dir)\include\Ice\ConnectionF.h" \ - "Endpoint.h" \ - "$(ice_cpp_dir)\include\Ice\Endpoint.h" \ - "$(ice_cpp_dir)\include\Ice\Version.h" \ - "$(ice_cpp_dir)\include\Ice\BuiltinSequences.h" \ - "$(ice_cpp_dir)\include\Ice\EndpointF.h" \ - "Operation.h" \ - "$(ice_cpp_dir)\include\Ice\Current.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectAdapterF.h" \ - "$(ice_cpp_dir)\include\Ice\Identity.h" \ - "$(ice_cpp_dir)\include\Ice\Object.h" \ - "$(ice_cpp_dir)\include\IceUtil\Mutex.h" \ - "$(ice_cpp_dir)\include\IceUtil\Lock.h" \ - "$(ice_cpp_dir)\include\IceUtil\ThreadException.h" \ - "$(ice_cpp_dir)\include\IceUtil\Time.h" \ - "$(ice_cpp_dir)\include\IceUtil\MutexProtocol.h" \ - "$(ice_cpp_dir)\include\Ice\IncomingAsyncF.h" \ - "$(ice_cpp_dir)\include\Ice\AsyncResultF.h" \ - "Thread.h" \ - "Util.h" \ - "$(ice_cpp_dir)\include\Ice\Initialize.h" \ - "$(ice_cpp_dir)\include\IceUtil\Timer.h" \ - "$(ice_cpp_dir)\include\IceUtil\Thread.h" \ - "$(ice_cpp_dir)\include\IceUtil\Monitor.h" \ - "$(ice_cpp_dir)\include\IceUtil\Cond.h" \ - "$(ice_cpp_dir)\include\Ice\PropertiesF.h" \ - "$(ice_cpp_dir)\include\Ice\Proxy.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyFactoryF.h" \ - "$(ice_cpp_dir)\include\Ice\ConnectionIF.h" \ - "$(ice_cpp_dir)\include\Ice\RequestHandlerF.h" \ - "$(ice_cpp_dir)\include\Ice\EndpointTypes.h" \ - "$(ice_cpp_dir)\include\Ice\ReferenceF.h" \ - "$(ice_cpp_dir)\include\Ice\BatchRequestQueueF.h" \ - "$(ice_cpp_dir)\include\Ice\AsyncResult.h" \ - "$(ice_cpp_dir)\include\IceUtil\UniquePtr.h" \ - "$(ice_cpp_dir)\include\Ice\InstanceF.h" \ - "$(ice_cpp_dir)\include\Ice\ObserverHelper.h" \ - "$(ice_cpp_dir)\include\Ice\Instrumentation.h" \ - "$(ice_cpp_dir)\include\Ice\BasicStream.h" \ - "$(ice_cpp_dir)\include\IceUtil\StringConverter.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectFactoryF.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectFactoryManagerF.h" \ - "$(ice_cpp_dir)\include\Ice\Buffer.h" \ - "$(ice_cpp_dir)\include\Ice\Protocol.h" \ - "$(ice_cpp_dir)\include\Ice\SlicedDataF.h" \ - "$(ice_cpp_dir)\include\Ice\UserExceptionFactory.h" \ - "$(ice_cpp_dir)\include\Ice\FactoryTable.h" \ - "$(ice_cpp_dir)\include\Ice\LoggerF.h" \ - "$(ice_cpp_dir)\include\Ice\InstrumentationF.h" \ - "$(ice_cpp_dir)\include\Ice\Dispatcher.h" \ - "$(ice_cpp_dir)\include\Ice\Plugin.h" \ - "$(ice_cpp_dir)\include\Ice\BatchRequestInterceptor.h" \ - "$(ice_cpp_dir)\include\Ice\Communicator.h" \ - "$(ice_cpp_dir)\include\Ice\GCObject.h" \ - "$(ice_cpp_dir)\include\IceUtil\MutexPtrLock.h" \ - "$(ice_cpp_dir)\include\Ice\Incoming.h" \ - "$(ice_cpp_dir)\include\Ice\ServantLocatorF.h" \ - "$(ice_cpp_dir)\include\Ice\ServantManagerF.h" \ - "$(ice_cpp_dir)\include\Ice\ResponseHandlerF.h" \ - "$(ice_cpp_dir)\include\Ice\IncomingAsync.h" \ - "$(ice_cpp_dir)\include\Ice\RouterF.h" \ - "$(ice_cpp_dir)\include\Ice\LocatorF.h" \ - "$(ice_cpp_dir)\include\Ice\PluginF.h" \ - "$(ice_cpp_dir)\include\Ice\ImplicitContextF.h" \ - "$(ice_cpp_dir)\include\Ice\Properties.h" \ - "$(ice_cpp_dir)\include\Ice\PropertiesAdmin.h" \ - "$(ice_cpp_dir)\include\Ice\FacetMap.h" \ - "$(ice_cpp_dir)\include\Ice\LocalException.h" \ - "$(ice_cpp_dir)\include\Ice\Locator.h" \ - "$(ice_cpp_dir)\include\Ice\FactoryTableInit.h" \ - "$(ice_cpp_dir)\include\Ice\DefaultObjectFactory.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectFactory.h" \ - "$(ice_cpp_dir)\include\Ice\ProcessF.h" \ - "$(ice_cpp_dir)\include\Ice\Router.h" \ - -Slice.obj: \ - Slice.cpp \ - "$(ice_cpp_dir)\include\IceUtil\Config.h" \ - "Slice.h" \ - "Config.h" \ - "Util.h" \ - "$(ice_cpp_dir)\include\Ice\BuiltinSequences.h" \ - "$(ice_cpp_dir)\include\IceUtil\PushDisableWarnings.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyF.h" \ - "$(ice_cpp_dir)\include\IceUtil\Shared.h" \ - "$(ice_cpp_dir)\include\IceUtil\Atomic.h" \ - "$(ice_cpp_dir)\include\Ice\Config.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyHandle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Handle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\Handle.h" \ - "$(ice_cpp_dir)\include\Ice\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\Format.h" \ - "$(ice_cpp_dir)\include\Ice\StreamF.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObject.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\StreamHelpers.h" \ - "$(ice_cpp_dir)\include\IceUtil\ScopedArray.h" \ - "$(ice_cpp_dir)\include\IceUtil\Iterator.h" \ - "$(ice_cpp_dir)\include\IceUtil\Optional.h" \ - "$(ice_cpp_dir)\include\IceUtil\UndefSysMacros.h" \ - "$(ice_cpp_dir)\include\IceUtil\PopDisableWarnings.h" \ - "$(ice_cpp_dir)\include\Ice\Current.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectAdapterF.h" \ - "$(ice_cpp_dir)\include\Ice\ConnectionF.h" \ - "$(ice_cpp_dir)\include\Ice\Identity.h" \ - "$(ice_cpp_dir)\include\Ice\Version.h" \ - "$(ice_cpp_dir)\include\Slice\Preprocessor.h" \ - "$(ice_cpp_dir)\include\Slice\PythonUtil.h" \ - "$(ice_cpp_dir)\include\Slice\Parser.h" \ - "$(ice_cpp_dir)\include\IceUtil\OutputUtil.h" \ - "$(ice_cpp_dir)\include\Slice\Util.h" \ - "$(ice_cpp_dir)\include\IceUtil\Options.h" \ - "$(ice_cpp_dir)\include\IceUtil\RecMutex.h" \ - "$(ice_cpp_dir)\include\IceUtil\Lock.h" \ - "$(ice_cpp_dir)\include\IceUtil\ThreadException.h" \ - "$(ice_cpp_dir)\include\IceUtil\Time.h" \ - "$(ice_cpp_dir)\include\IceUtil\MutexProtocol.h" \ - -Thread.obj: \ - Thread.cpp \ - "$(ice_cpp_dir)\include\IceUtil\Config.h" \ - "Thread.h" \ - "Config.h" \ - "Util.h" \ - "$(ice_cpp_dir)\include\Ice\BuiltinSequences.h" \ - "$(ice_cpp_dir)\include\IceUtil\PushDisableWarnings.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyF.h" \ - "$(ice_cpp_dir)\include\IceUtil\Shared.h" \ - "$(ice_cpp_dir)\include\IceUtil\Atomic.h" \ - "$(ice_cpp_dir)\include\Ice\Config.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyHandle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Handle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\Handle.h" \ - "$(ice_cpp_dir)\include\Ice\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\Format.h" \ - "$(ice_cpp_dir)\include\Ice\StreamF.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObject.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\StreamHelpers.h" \ - "$(ice_cpp_dir)\include\IceUtil\ScopedArray.h" \ - "$(ice_cpp_dir)\include\IceUtil\Iterator.h" \ - "$(ice_cpp_dir)\include\IceUtil\Optional.h" \ - "$(ice_cpp_dir)\include\IceUtil\UndefSysMacros.h" \ - "$(ice_cpp_dir)\include\IceUtil\PopDisableWarnings.h" \ - "$(ice_cpp_dir)\include\Ice\Current.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectAdapterF.h" \ - "$(ice_cpp_dir)\include\Ice\ConnectionF.h" \ - "$(ice_cpp_dir)\include\Ice\Identity.h" \ - "$(ice_cpp_dir)\include\Ice\Version.h" \ - "$(ice_cpp_dir)\include\Ice\Initialize.h" \ - "$(ice_cpp_dir)\include\IceUtil\Timer.h" \ - "$(ice_cpp_dir)\include\IceUtil\Thread.h" \ - "$(ice_cpp_dir)\include\IceUtil\Mutex.h" \ - "$(ice_cpp_dir)\include\IceUtil\Lock.h" \ - "$(ice_cpp_dir)\include\IceUtil\ThreadException.h" \ - "$(ice_cpp_dir)\include\IceUtil\Time.h" \ - "$(ice_cpp_dir)\include\IceUtil\MutexProtocol.h" \ - "$(ice_cpp_dir)\include\IceUtil\Monitor.h" \ - "$(ice_cpp_dir)\include\IceUtil\Cond.h" \ - "$(ice_cpp_dir)\include\Ice\CommunicatorF.h" \ - "$(ice_cpp_dir)\include\Ice\PropertiesF.h" \ - "$(ice_cpp_dir)\include\Ice\Proxy.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyFactoryF.h" \ - "$(ice_cpp_dir)\include\Ice\ConnectionIF.h" \ - "$(ice_cpp_dir)\include\Ice\RequestHandlerF.h" \ - "$(ice_cpp_dir)\include\Ice\EndpointF.h" \ - "$(ice_cpp_dir)\include\Ice\EndpointTypes.h" \ - "$(ice_cpp_dir)\include\Ice\ReferenceF.h" \ - "$(ice_cpp_dir)\include\Ice\BatchRequestQueueF.h" \ - "$(ice_cpp_dir)\include\Ice\AsyncResult.h" \ - "$(ice_cpp_dir)\include\IceUtil\UniquePtr.h" \ - "$(ice_cpp_dir)\include\Ice\InstanceF.h" \ - "$(ice_cpp_dir)\include\Ice\AsyncResultF.h" \ - "$(ice_cpp_dir)\include\Ice\ObserverHelper.h" \ - "$(ice_cpp_dir)\include\Ice\Instrumentation.h" \ - "$(ice_cpp_dir)\include\Ice\BasicStream.h" \ - "$(ice_cpp_dir)\include\IceUtil\StringConverter.h" \ - "$(ice_cpp_dir)\include\Ice\Object.h" \ - "$(ice_cpp_dir)\include\Ice\IncomingAsyncF.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectFactoryF.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectFactoryManagerF.h" \ - "$(ice_cpp_dir)\include\Ice\Buffer.h" \ - "$(ice_cpp_dir)\include\Ice\Protocol.h" \ - "$(ice_cpp_dir)\include\Ice\SlicedDataF.h" \ - "$(ice_cpp_dir)\include\Ice\UserExceptionFactory.h" \ - "$(ice_cpp_dir)\include\Ice\FactoryTable.h" \ - "$(ice_cpp_dir)\include\Ice\LoggerF.h" \ - "$(ice_cpp_dir)\include\Ice\InstrumentationF.h" \ - "$(ice_cpp_dir)\include\Ice\Dispatcher.h" \ - "$(ice_cpp_dir)\include\Ice\Plugin.h" \ - "$(ice_cpp_dir)\include\Ice\BatchRequestInterceptor.h" \ - -Types.obj: \ - Types.cpp \ - "$(ice_cpp_dir)\include\IceUtil\Config.h" \ - "Types.h" \ - "Config.h" \ - "Util.h" \ - "$(ice_cpp_dir)\include\Ice\BuiltinSequences.h" \ - "$(ice_cpp_dir)\include\IceUtil\PushDisableWarnings.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyF.h" \ - "$(ice_cpp_dir)\include\IceUtil\Shared.h" \ - "$(ice_cpp_dir)\include\IceUtil\Atomic.h" \ - "$(ice_cpp_dir)\include\Ice\Config.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyHandle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Handle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\Handle.h" \ - "$(ice_cpp_dir)\include\Ice\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\Format.h" \ - "$(ice_cpp_dir)\include\Ice\StreamF.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObject.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\StreamHelpers.h" \ - "$(ice_cpp_dir)\include\IceUtil\ScopedArray.h" \ - "$(ice_cpp_dir)\include\IceUtil\Iterator.h" \ - "$(ice_cpp_dir)\include\IceUtil\Optional.h" \ - "$(ice_cpp_dir)\include\IceUtil\UndefSysMacros.h" \ - "$(ice_cpp_dir)\include\IceUtil\PopDisableWarnings.h" \ - "$(ice_cpp_dir)\include\Ice\Current.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectAdapterF.h" \ - "$(ice_cpp_dir)\include\Ice\ConnectionF.h" \ - "$(ice_cpp_dir)\include\Ice\Identity.h" \ - "$(ice_cpp_dir)\include\Ice\Version.h" \ - "$(ice_cpp_dir)\include\Ice\Stream.h" \ - "$(ice_cpp_dir)\include\Ice\CommunicatorF.h" \ - "$(ice_cpp_dir)\include\Ice\Object.h" \ - "$(ice_cpp_dir)\include\IceUtil\Mutex.h" \ - "$(ice_cpp_dir)\include\IceUtil\Lock.h" \ - "$(ice_cpp_dir)\include\IceUtil\ThreadException.h" \ - "$(ice_cpp_dir)\include\IceUtil\Time.h" \ - "$(ice_cpp_dir)\include\IceUtil\MutexProtocol.h" \ - "$(ice_cpp_dir)\include\Ice\IncomingAsyncF.h" \ - "$(ice_cpp_dir)\include\Ice\Proxy.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyFactoryF.h" \ - "$(ice_cpp_dir)\include\Ice\ConnectionIF.h" \ - "$(ice_cpp_dir)\include\Ice\RequestHandlerF.h" \ - "$(ice_cpp_dir)\include\Ice\EndpointF.h" \ - "$(ice_cpp_dir)\include\Ice\EndpointTypes.h" \ - "$(ice_cpp_dir)\include\Ice\ReferenceF.h" \ - "$(ice_cpp_dir)\include\Ice\BatchRequestQueueF.h" \ - "$(ice_cpp_dir)\include\Ice\AsyncResult.h" \ - "$(ice_cpp_dir)\include\IceUtil\Monitor.h" \ - "$(ice_cpp_dir)\include\IceUtil\Cond.h" \ - "$(ice_cpp_dir)\include\IceUtil\UniquePtr.h" \ - "$(ice_cpp_dir)\include\Ice\InstanceF.h" \ - "$(ice_cpp_dir)\include\Ice\AsyncResultF.h" \ - "$(ice_cpp_dir)\include\Ice\ObserverHelper.h" \ - "$(ice_cpp_dir)\include\Ice\Instrumentation.h" \ - "$(ice_cpp_dir)\include\Ice\BasicStream.h" \ - "$(ice_cpp_dir)\include\IceUtil\StringConverter.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectFactoryF.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectFactoryManagerF.h" \ - "$(ice_cpp_dir)\include\Ice\Buffer.h" \ - "$(ice_cpp_dir)\include\Ice\Protocol.h" \ - "$(ice_cpp_dir)\include\Ice\SlicedDataF.h" \ - "$(ice_cpp_dir)\include\Ice\UserExceptionFactory.h" \ - "$(ice_cpp_dir)\include\Ice\FactoryTable.h" \ - "$(ice_cpp_dir)\include\IceUtil\OutputUtil.h" \ - "Current.h" \ - "Proxy.h" \ - "Thread.h" \ - "$(ice_cpp_dir)\include\Ice\Initialize.h" \ - "$(ice_cpp_dir)\include\IceUtil\Timer.h" \ - "$(ice_cpp_dir)\include\IceUtil\Thread.h" \ - "$(ice_cpp_dir)\include\Ice\PropertiesF.h" \ - "$(ice_cpp_dir)\include\Ice\LoggerF.h" \ - "$(ice_cpp_dir)\include\Ice\InstrumentationF.h" \ - "$(ice_cpp_dir)\include\Ice\Dispatcher.h" \ - "$(ice_cpp_dir)\include\Ice\Plugin.h" \ - "$(ice_cpp_dir)\include\Ice\BatchRequestInterceptor.h" \ - "$(ice_cpp_dir)\include\IceUtil\InputUtil.h" \ - "$(ice_cpp_dir)\include\Ice\LocalException.h" \ - "$(ice_cpp_dir)\include\Ice\SlicedData.h" \ - "$(ice_cpp_dir)\include\Ice\GCObject.h" \ - "$(ice_cpp_dir)\include\IceUtil\MutexPtrLock.h" \ - -Util.obj: \ - Util.cpp \ - "$(ice_cpp_dir)\include\IceUtil\Config.h" \ - "Util.h" \ - "Config.h" \ - "$(ice_cpp_dir)\include\Ice\BuiltinSequences.h" \ - "$(ice_cpp_dir)\include\IceUtil\PushDisableWarnings.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyF.h" \ - "$(ice_cpp_dir)\include\IceUtil\Shared.h" \ - "$(ice_cpp_dir)\include\IceUtil\Atomic.h" \ - "$(ice_cpp_dir)\include\Ice\Config.h" \ - "$(ice_cpp_dir)\include\Ice\ProxyHandle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Handle.h" \ - "$(ice_cpp_dir)\include\IceUtil\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\Handle.h" \ - "$(ice_cpp_dir)\include\Ice\Exception.h" \ - "$(ice_cpp_dir)\include\Ice\Format.h" \ - "$(ice_cpp_dir)\include\Ice\StreamF.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObject.h" \ - "$(ice_cpp_dir)\include\Ice\LocalObjectF.h" \ - "$(ice_cpp_dir)\include\Ice\StreamHelpers.h" \ - "$(ice_cpp_dir)\include\IceUtil\ScopedArray.h" \ - "$(ice_cpp_dir)\include\IceUtil\Iterator.h" \ - "$(ice_cpp_dir)\include\IceUtil\Optional.h" \ - "$(ice_cpp_dir)\include\IceUtil\UndefSysMacros.h" \ - "$(ice_cpp_dir)\include\IceUtil\PopDisableWarnings.h" \ - "$(ice_cpp_dir)\include\Ice\Current.h" \ - "$(ice_cpp_dir)\include\Ice\ObjectAdapterF.h" \ - "$(ice_cpp_dir)\include\Ice\ConnectionF.h" \ - "$(ice_cpp_dir)\include\Ice\Identity.h" \ - "$(ice_cpp_dir)\include\Ice\Version.h" \ - "$(ice_cpp_dir)\include\IceUtil\DisableWarnings.h" \ - "$(ice_cpp_dir)\include\Ice\LocalException.h" \ - "$(ice_cpp_dir)\include\Ice\Protocol.h" \ - "$(ice_cpp_dir)\include\IceUtil\UUID.h" \ - "$(ice_cpp_dir)\include\Slice\PythonUtil.h" \ - "$(ice_cpp_dir)\include\Slice\Parser.h" \ - "$(ice_cpp_dir)\include\IceUtil\OutputUtil.h" \ diff --git a/python/modules/IcePy/Communicator.cpp b/python/modules/IcePy/Communicator.cpp index eafa723a57c..63d19e7634d 100644 --- a/python/modules/IcePy/Communicator.cpp +++ b/python/modules/IcePy/Communicator.cpp @@ -16,7 +16,6 @@ #include <ImplicitContext.h> #include <Logger.h> #include <ObjectAdapter.h> -#include <ObjectFactory.h> #include <Operation.h> #include <Properties.h> #include <PropertiesAdmin.h> @@ -24,6 +23,8 @@ #include <Thread.h> #include <Types.h> #include <Util.h> +#include <ValueFactoryManager.h> +#include <Ice/ValueFactory.h> #include <Ice/Initialize.h> #include <Ice/CommunicatorAsync.h> #include <Ice/LocalException.h> @@ -141,12 +142,14 @@ communicatorInit(CommunicatorObject* self, PyObject* args, PyObject* /*kwds*/) bool hasArgs = argList != 0; Ice::InitializationData data; + if(initData) { PyObjectHandle properties = PyObject_GetAttrString(initData, STRCAST("properties")); PyObjectHandle logger = PyObject_GetAttrString(initData, STRCAST("logger")); PyObjectHandle threadHook = PyObject_GetAttrString(initData, STRCAST("threadHook")); PyObjectHandle batchRequestInterceptor = PyObject_GetAttrString(initData, STRCAST("batchRequestInterceptor")); + PyErr_Clear(); // PyObject_GetAttrString sets an error on failure. if(properties.get() && properties.get() != Py_None) @@ -175,6 +178,11 @@ communicatorInit(CommunicatorObject* self, PyObject* args, PyObject* /*kwds*/) } } + // + // We always supply our own implementation of ValueFactoryManager. + // + data.valueFactoryManager = new ValueFactoryManager; + try { if(argList) @@ -253,8 +261,6 @@ communicatorInit(CommunicatorObject* self, PyObject* args, PyObject* /*kwds*/) delete[] argv; self->communicator = new Ice::CommunicatorPtr(communicator); - ObjectFactoryPtr factory = new ObjectFactory; - (*self->communicator)->addObjectFactory(factory, ""); CommunicatorMap::iterator p = _communicatorMap.find(communicator); if(p != _communicatorMap.end()) @@ -301,6 +307,10 @@ static PyObject* communicatorDestroy(CommunicatorObject* self) { assert(self->communicator); + + ValueFactoryManagerPtr vfm = ValueFactoryManagerPtr::dynamicCast((*self->communicator)->getValueFactoryManager()); + assert(vfm); + try { AllowThreads allowThreads; // Release Python's global interpreter lock to avoid a potential deadlock. @@ -309,17 +319,25 @@ communicatorDestroy(CommunicatorObject* self) catch(const Ice::Exception& ex) { setPythonException(ex); - return 0; } + vfm->destroy(); + // // Break cyclic reference between this object and its Python wrapper. // Py_XDECREF(self->wrapper); self->wrapper = 0; - Py_INCREF(Py_None); - return Py_None; + if(PyErr_Occurred()) + { + return 0; + } + else + { + Py_INCREF(Py_None); + return Py_None; + } } #ifdef WIN32 @@ -683,13 +701,24 @@ communicatorIdentityToString(CommunicatorObject* self, PyObject* args) extern "C" #endif static PyObject* -communicatorFlushBatchRequests(CommunicatorObject* self) +communicatorFlushBatchRequests(CommunicatorObject* self, PyObject* args) { + PyObject* compressBatchType = lookupType("Ice.CompressBatch"); + PyObject* compressBatch; + if(!PyArg_ParseTuple(args, STRCAST("O!"), compressBatchType, &compressBatch)) + { + return 0; + } + + PyObjectHandle v = PyObject_GetAttrString(compressBatch, STRCAST("_value")); + assert(v.get()); + Ice::CompressBatch cb = static_cast<Ice::CompressBatch>(PyLong_AsLong(v.get())); + assert(self->communicator); try { AllowThreads allowThreads; // Release Python's global interpreter lock to avoid a potential deadlock. - (*self->communicator)->flushBatchRequests(); + (*self->communicator)->flushBatchRequests(cb); } catch(const Ice::Exception& ex) { @@ -705,23 +734,88 @@ communicatorFlushBatchRequests(CommunicatorObject* self) extern "C" #endif static PyObject* +communicatorFlushBatchRequestsAsync(CommunicatorObject* self, PyObject* args, PyObject* /*kwds*/) +{ + PyObject* compressBatchType = lookupType("Ice.CompressBatch"); + PyObject* compressBatch; + if(!PyArg_ParseTuple(args, STRCAST("O!"), compressBatchType, &compressBatch)) + { + return 0; + } + + PyObjectHandle v = PyObject_GetAttrString(compressBatch, STRCAST("_value")); + assert(v.get()); + Ice::CompressBatch cb = static_cast<Ice::CompressBatch>(PyLong_AsLong(v.get())); + + assert(self->communicator); + const string op = "flushBatchRequests"; + + FlushAsyncCallbackPtr d = new FlushAsyncCallback(op); + Ice::Callback_Communicator_flushBatchRequestsPtr callback = + Ice::newCallback_Communicator_flushBatchRequests(d, &FlushAsyncCallback::exception, &FlushAsyncCallback::sent); + + Ice::AsyncResultPtr result; + + try + { + AllowThreads allowThreads; // Release Python's global interpreter lock during remote invocations. + + result = (*self->communicator)->begin_flushBatchRequests(cb, callback); + } + catch(const Ice::Exception& ex) + { + setPythonException(ex); + return 0; + } + + PyObjectHandle asyncResultObj = createAsyncResult(result, 0, 0, self->wrapper); + if(!asyncResultObj.get()) + { + return 0; + } + + PyObjectHandle future = createFuture(op, asyncResultObj.get()); + if(!future.get()) + { + return 0; + } + d->setFuture(future.get()); + return future.release(); +} + +#ifdef WIN32 +extern "C" +#endif +static PyObject* communicatorBeginFlushBatchRequests(CommunicatorObject* self, PyObject* args, PyObject* kwds) { assert(self->communicator); static char* argNames[] = { + const_cast<char*>("compress"), const_cast<char*>("_ex"), const_cast<char*>("_sent"), 0 }; + PyObject* compressBatch; PyObject* ex = Py_None; PyObject* sent = Py_None; - if(!PyArg_ParseTupleAndKeywords(args, kwds, STRCAST("|OO"), argNames, &ex, &sent)) + if(!PyArg_ParseTupleAndKeywords(args, kwds, STRCAST("O|OO"), argNames, &compressBatch, &ex, &sent)) + { + return 0; + } + + PyObject* compressBatchType = lookupType("Ice.CompressBatch"); + if(!PyObject_IsInstance(compressBatch, reinterpret_cast<PyObject*>(compressBatchType))) { return 0; } + PyObjectHandle v = PyObject_GetAttrString(compressBatch, STRCAST("_value")); + assert(v.get()); + Ice::CompressBatch cb = static_cast<Ice::CompressBatch>(PyLong_AsLong(v.get())); + if(ex == Py_None) { ex = 0; @@ -738,11 +832,11 @@ communicatorBeginFlushBatchRequests(CommunicatorObject* self, PyObject* args, Py return 0; } - Ice::Callback_Communicator_flushBatchRequestsPtr cb; + Ice::Callback_Communicator_flushBatchRequestsPtr callback; if(ex || sent) { FlushCallbackPtr d = new FlushCallback(ex, sent, "flushBatchRequests"); - cb = Ice::newCallback_Communicator_flushBatchRequests(d, &FlushCallback::exception, &FlushCallback::sent); + callback = Ice::newCallback_Communicator_flushBatchRequests(d, &FlushCallback::exception, &FlushCallback::sent); } Ice::AsyncResultPtr result; @@ -750,13 +844,13 @@ communicatorBeginFlushBatchRequests(CommunicatorObject* self, PyObject* args, Py { AllowThreads allowThreads; // Release Python's global interpreter lock during remote invocations. - if(cb) + if(callback) { - result = (*self->communicator)->begin_flushBatchRequests(cb); + result = (*self->communicator)->begin_flushBatchRequests(cb, callback); } else { - result = (*self->communicator)->begin_flushBatchRequests(); + result = (*self->communicator)->begin_flushBatchRequests(cb); } } catch(const Ice::Exception& ex) @@ -1168,12 +1262,16 @@ extern "C" static PyObject* communicatorAddObjectFactory(CommunicatorObject* self, PyObject* args) { - PyObject* factoryType = lookupType("Ice.ObjectFactory"); - assert(factoryType); + PyObject* objectFactoryType = lookupType("Ice.ObjectFactory"); + assert(objectFactoryType); + PyObject* valueFactoryType = lookupType("types.FunctionType"); + assert(valueFactoryType); - PyObject* factory; + PyObject* objectFactory; PyObject* strObj; - if(!PyArg_ParseTuple(args, STRCAST("O!O"), factoryType, &factory, &strObj)) + PyObject* valueFactory; + if(!PyArg_ParseTuple(args, STRCAST("O!OO!"), objectFactoryType, &objectFactory, &strObj, valueFactoryType, + &valueFactory)) { return 0; } @@ -1184,11 +1282,12 @@ communicatorAddObjectFactory(CommunicatorObject* self, PyObject* args) return 0; } - ObjectFactoryPtr pof; + ValueFactoryManagerPtr vfm = ValueFactoryManagerPtr::dynamicCast((*self->communicator)->getValueFactoryManager()); + assert(vfm); + try { - pof = ObjectFactoryPtr::dynamicCast((*self->communicator)->findObjectFactory("")); - assert(pof); + vfm->add(valueFactory, objectFactory, id); } catch(const Ice::Exception& ex) { @@ -1197,11 +1296,6 @@ communicatorAddObjectFactory(CommunicatorObject* self, PyObject* args) } - if(!pof->add(factory, id)) - { - return 0; - } - Py_INCREF(Py_None); return Py_None; } @@ -1224,19 +1318,21 @@ communicatorFindObjectFactory(CommunicatorObject* self, PyObject* args) return 0; } - ObjectFactoryPtr pof; - try - { - pof = ObjectFactoryPtr::dynamicCast((*self->communicator)->findObjectFactory("")); - assert(pof); - } - catch(const Ice::Exception& ex) - { - setPythonException(ex); - return 0; - } + ValueFactoryManagerPtr vfm = ValueFactoryManagerPtr::dynamicCast((*self->communicator)->getValueFactoryManager()); + assert(vfm); - return pof->find(id); + return vfm->findObjectFactory(id); +} + +#ifdef WIN32 +extern "C" +#endif +static PyObject* +communicatorGetValueFactoryManager(CommunicatorObject* self) +{ + ValueFactoryManagerPtr vfm = ValueFactoryManagerPtr::dynamicCast((*self->communicator)->getValueFactoryManager()); + + return vfm->getObject(); } #ifdef WIN32 @@ -1570,6 +1666,8 @@ static PyMethodDef CommunicatorMethods[] = PyDoc_STR(STRCAST("addObjectFactory(factory, id) -> None")) }, { STRCAST("findObjectFactory"), reinterpret_cast<PyCFunction>(communicatorFindObjectFactory), METH_VARARGS, PyDoc_STR(STRCAST("findObjectFactory(id) -> Ice.ObjectFactory")) }, + { STRCAST("getValueFactoryManager"), reinterpret_cast<PyCFunction>(communicatorGetValueFactoryManager), METH_NOARGS, + PyDoc_STR(STRCAST("getValueFactoryManager() -> Ice.ValueFactoryManager")) }, { STRCAST("getImplicitContext"), reinterpret_cast<PyCFunction>(communicatorGetImplicitContext), METH_NOARGS, PyDoc_STR(STRCAST("getImplicitContext() -> Ice.ImplicitContext")) }, { STRCAST("getProperties"), reinterpret_cast<PyCFunction>(communicatorGetProperties), METH_NOARGS, @@ -1584,11 +1682,13 @@ static PyMethodDef CommunicatorMethods[] = PyDoc_STR(STRCAST("getDefaultLocator() -> proxy")) }, { STRCAST("setDefaultLocator"), reinterpret_cast<PyCFunction>(communicatorSetDefaultLocator), METH_VARARGS, PyDoc_STR(STRCAST("setDefaultLocator(proxy) -> None")) }, - { STRCAST("flushBatchRequests"), reinterpret_cast<PyCFunction>(communicatorFlushBatchRequests), METH_NOARGS, - PyDoc_STR(STRCAST("flushBatchRequests() -> None")) }, + { STRCAST("flushBatchRequests"), reinterpret_cast<PyCFunction>(communicatorFlushBatchRequests), METH_VARARGS, + PyDoc_STR(STRCAST("flushBatchRequests(compress) -> None")) }, + { STRCAST("flushBatchRequestsAsync"), reinterpret_cast<PyCFunction>(communicatorFlushBatchRequestsAsync), + METH_VARARGS, PyDoc_STR(STRCAST("flushBatchRequestsAsync(compress) -> Ice.Future")) }, { STRCAST("begin_flushBatchRequests"), reinterpret_cast<PyCFunction>(communicatorBeginFlushBatchRequests), METH_VARARGS | METH_KEYWORDS, - PyDoc_STR(STRCAST("begin_flushBatchRequests([_ex][, _sent]) -> Ice.AsyncResult")) }, + PyDoc_STR(STRCAST("begin_flushBatchRequests(compress[, _ex][, _sent]) -> Ice.AsyncResult")) }, { STRCAST("end_flushBatchRequests"), reinterpret_cast<PyCFunction>(communicatorEndFlushBatchRequests), METH_VARARGS, PyDoc_STR(STRCAST("end_flushBatchRequests(Ice.AsyncResult) -> None")) }, { STRCAST("createAdmin"), reinterpret_cast<PyCFunction>(communicatorCreateAdmin), METH_VARARGS, @@ -1712,25 +1812,51 @@ IcePy::getCommunicatorWrapper(const Ice::CommunicatorPtr& communicator) CommunicatorMap::iterator p = _communicatorMap.find(communicator); assert(p != _communicatorMap.end()); CommunicatorObject* obj = reinterpret_cast<CommunicatorObject*>(p->second); - Py_INCREF(obj->wrapper); - return obj->wrapper; + if(obj->wrapper) + { + Py_INCREF(obj->wrapper); + return obj->wrapper; + } + else + { + // + // Communicator must have been destroyed already. + // + Py_INCREF(Py_None); + return Py_None; + } } extern "C" PyObject* -IcePy_identityToString(PyObject* /*self*/, PyObject* obj) +IcePy_identityToString(PyObject* /*self*/, PyObject* args) { + PyObject* identityType = lookupType("Ice.Identity"); + PyObject* obj; + PyObject* mode = 0; + if(!PyArg_ParseTuple(args, STRCAST("O!O"), identityType, &obj, &mode)) + { + return 0; + } + Ice::Identity id; if(!getIdentity(obj, id)) { return 0; } - + + Ice::ToStringMode toStringMode = Ice::Unicode; + if(mode != Py_None && PyObject_HasAttrString(mode, STRCAST("value"))) + { + PyObjectHandle modeValue = PyObject_GetAttrString(mode, STRCAST("value")); + toStringMode = static_cast<Ice::ToStringMode>(PyLong_AsLong(modeValue.get())); + } + string str; try { - str = Ice::identityToString(id); + str = identityToString(id, toStringMode); } catch(const Ice::Exception& ex) { diff --git a/python/modules/IcePy/Connection.cpp b/python/modules/IcePy/Connection.cpp index 2ae2deb93e5..2950fc87717 100644 --- a/python/modules/IcePy/Connection.cpp +++ b/python/modules/IcePy/Connection.cpp @@ -37,18 +37,18 @@ struct ConnectionObject Ice::CommunicatorPtr* communicator; }; -class ConnectionCallbackI : public Ice::ConnectionCallback +class CloseCallbackWrapper : public Ice::CloseCallback { public: - ConnectionCallbackI(PyObject* cb, PyObject* con) : + CloseCallbackWrapper(PyObject* cb, PyObject* con) : _cb(cb), _con(con) { Py_INCREF(cb); Py_INCREF(con); } - virtual ~ConnectionCallbackI() + virtual ~CloseCallbackWrapper() { AdoptThread adoptThread; // Ensure the current thread is able to call into Python. @@ -56,58 +56,156 @@ public: Py_DECREF(_con); } - virtual void heartbeat(const Ice::ConnectionPtr& con) + virtual void closed(const Ice::ConnectionPtr& con) { - invoke("heartbeat", con); + invoke(con); } - virtual void closed(const Ice::ConnectionPtr& con) +private: + + void invoke(const Ice::ConnectionPtr& con) + { + AdoptThread adoptThread; // Ensure the current thread is able to call into Python. +#ifndef NDEBUG + ConnectionObject* c = reinterpret_cast<ConnectionObject*>(_con); + assert(con == *(c->connection)); +#endif + + PyObjectHandle args = Py_BuildValue(STRCAST("(O)"), _con); + assert(_cb); + PyObjectHandle tmp = PyObject_Call(_cb, args.get(), 0); + if(PyErr_Occurred()) + { + PyException ex; // Retrieve it before another Python API call clears it. + + // + // A callback that calls sys.exit() will raise the SystemExit exception. + // This is normally caught by the interpreter, causing it to exit. + // However, we have no way to pass this exception to the interpreter, + // so we act on it directly. + // + ex.checkSystemExit(); + + ex.raise(); + } + } + + PyObject* _cb; + PyObject* _con; +}; + +class HeartbeatCallbackWrapper : public Ice::HeartbeatCallback +{ +public: + + HeartbeatCallbackWrapper(PyObject* cb, PyObject* con) : + _cb(cb), _con(con) { - invoke("closed", con); + Py_INCREF(cb); + Py_INCREF(con); + } + + virtual ~HeartbeatCallbackWrapper() + { + AdoptThread adoptThread; // Ensure the current thread is able to call into Python. + + Py_DECREF(_cb); + Py_DECREF(_con); + } + + virtual void heartbeat(const Ice::ConnectionPtr& con) + { + invoke(con); } private: - void invoke(const string& methodName, const Ice::ConnectionPtr& con) + void invoke(const Ice::ConnectionPtr& con) { AdoptThread adoptThread; // Ensure the current thread is able to call into Python. #ifndef NDEBUG ConnectionObject* c = reinterpret_cast<ConnectionObject*>(_con); assert(con == *(c->connection)); #endif - if(!PyObject_HasAttrString(_cb, STRCAST(methodName.c_str()))) + + PyObjectHandle args = Py_BuildValue(STRCAST("(O)"), _con); + assert(_cb); + PyObjectHandle tmp = PyObject_Call(_cb, args.get(), 0); + if(PyErr_Occurred()) { - ostringstream ostr; - ostr << "connection callback object does not define " << methodName << "()"; - string str = ostr.str(); - PyErr_Warn(PyExc_RuntimeWarning, const_cast<char*>(str.c_str())); + PyException ex; // Retrieve it before another Python API call clears it. + + // + // A callback that calls sys.exit() will raise the SystemExit exception. + // This is normally caught by the interpreter, causing it to exit. + // However, we have no way to pass this exception to the interpreter, + // so we act on it directly. + // + ex.checkSystemExit(); + + ex.raise(); } - else + } + + PyObject* _cb; + PyObject* _con; +}; + +class HeartbeatAsyncCallback : public IceUtil::Shared +{ +public: + + HeartbeatAsyncCallback(PyObject* ex, PyObject* sent, const string& op) : + _ex(ex), _sent(sent), _op(op) + { + assert(_ex); + Py_INCREF(_ex); + Py_XINCREF(_sent); + } + + ~HeartbeatAsyncCallback() + { + AdoptThread adoptThread; // Ensure the current thread is able to call into Python. + + Py_DECREF(_ex); + Py_XDECREF(_sent); + } + + void exception(const Ice::Exception& ex) + { + AdoptThread adoptThread; // Ensure the current thread is able to call into Python. + + PyObjectHandle exh = convertException(ex); + assert(exh.get()); + PyObjectHandle args = Py_BuildValue(STRCAST("(O)"), exh.get()); + PyObjectHandle tmp = PyObject_Call(_ex, args.get(), 0); + if(PyErr_Occurred()) + { + throwPythonException(); // Callback raised an exception. + } + } + + void sent(bool sentSynchronously) + { + if(_sent) { - PyObjectHandle args = Py_BuildValue(STRCAST("(O)"), _con); - PyObjectHandle method = PyObject_GetAttrString(_cb, STRCAST(methodName.c_str())); - assert(method.get()); - PyObjectHandle tmp = PyObject_Call(method.get(), args.get(), 0); + AdoptThread adoptThread; // Ensure the current thread is able to call into Python. + PyObjectHandle args = Py_BuildValue(STRCAST("(O)"), sentSynchronously ? getTrue() : getFalse()); + PyObjectHandle tmp = PyObject_Call(_sent, args.get(), 0); if(PyErr_Occurred()) { - PyException ex; // Retrieve it before another Python API call clears it. - - // - // A callback that calls sys.exit() will raise the SystemExit exception. - // This is normally caught by the interpreter, causing it to exit. - // However, we have no way to pass this exception to the interpreter, - // so we act on it directly. - // - ex.checkSystemExit(); - - ex.raise(); + throwPythonException(); // Callback raised an exception. } } } - PyObject* _cb; - PyObject* _con; +protected: + + PyObject* _ex; + PyObject* _sent; + std::string _op; }; +typedef IceUtil::Handle<HeartbeatAsyncCallback> HeartbeatAsyncCallbackPtr; } @@ -190,9 +288,7 @@ connectionCompare(ConnectionObject* c1, PyObject* other, int op) } } - PyObject* r = result ? getTrue() : getFalse(); - Py_INCREF(r); - return r; + return result ? incTrue() : incFalse(); } #ifdef WIN32 @@ -201,17 +297,22 @@ extern "C" static PyObject* connectionClose(ConnectionObject* self, PyObject* args) { - int force; - if(!PyArg_ParseTuple(args, STRCAST("i"), &force)) + PyObject* closeType = lookupType("Ice.ConnectionClose"); + PyObject* mode; + if(!PyArg_ParseTuple(args, STRCAST("O!"), closeType, &mode)) { return 0; } + PyObjectHandle v = PyObject_GetAttrString(mode, STRCAST("_value")); + assert(v.get()); + Ice::ConnectionClose cc = static_cast<Ice::ConnectionClose>(PyLong_AsLong(v.get())); + assert(self->connection); try { AllowThreads allowThreads; // Release Python's global interpreter lock during blocking invocations. - (*self->connection)->close(force > 0); + (*self->connection)->close(cc); } catch(const Ice::Exception& ex) { @@ -317,13 +418,24 @@ connectionGetAdapter(ConnectionObject* self) extern "C" #endif static PyObject* -connectionFlushBatchRequests(ConnectionObject* self) +connectionFlushBatchRequests(ConnectionObject* self, PyObject* args) { + PyObject* compressBatchType = lookupType("Ice.CompressBatch"); + PyObject* compressBatch; + if(!PyArg_ParseTuple(args, STRCAST("O!"), compressBatchType, &compressBatch)) + { + return 0; + } + + PyObjectHandle v = PyObject_GetAttrString(compressBatch, STRCAST("_value")); + assert(v.get()); + Ice::CompressBatch cb = static_cast<Ice::CompressBatch>(PyLong_AsLong(v.get())); + assert(self->connection); try { AllowThreads allowThreads; // Release Python's global interpreter lock during remote invocations. - (*self->connection)->flushBatchRequests(); + (*self->connection)->flushBatchRequests(cb); } catch(const Ice::Exception& ex) { @@ -339,23 +451,90 @@ connectionFlushBatchRequests(ConnectionObject* self) extern "C" #endif static PyObject* +connectionFlushBatchRequestsAsync(ConnectionObject* self, PyObject* args, PyObject* /*kwds*/) +{ + PyObject* compressBatchType = lookupType("Ice.CompressBatch"); + PyObject* compressBatch; + if(!PyArg_ParseTuple(args, STRCAST("O!"), compressBatchType, &compressBatch)) + { + return 0; + } + + PyObjectHandle v = PyObject_GetAttrString(compressBatch, STRCAST("_value")); + assert(v.get()); + Ice::CompressBatch cb = static_cast<Ice::CompressBatch>(PyLong_AsLong(v.get())); + + assert(self->connection); + const string op = "flushBatchRequests"; + + FlushAsyncCallbackPtr d = new FlushAsyncCallback(op); + Ice::Callback_Connection_flushBatchRequestsPtr callback = + Ice::newCallback_Connection_flushBatchRequests(d, &FlushAsyncCallback::exception, &FlushAsyncCallback::sent); + + Ice::AsyncResultPtr result; + + try + { + AllowThreads allowThreads; // Release Python's global interpreter lock during remote invocations. + + result = (*self->connection)->begin_flushBatchRequests(cb, callback); + } + catch(const Ice::Exception& ex) + { + setPythonException(ex); + return 0; + } + + PyObjectHandle communicatorObj = getCommunicatorWrapper(*self->communicator); + PyObjectHandle asyncResultObj = + createAsyncResult(result, 0, reinterpret_cast<PyObject*>(self), communicatorObj.get()); + if(!asyncResultObj.get()) + { + return 0; + } + + PyObjectHandle future = createFuture(op, asyncResultObj.get()); + if(!future.get()) + { + return 0; + } + d->setFuture(future.get()); + return future.release(); +} + +#ifdef WIN32 +extern "C" +#endif +static PyObject* connectionBeginFlushBatchRequests(ConnectionObject* self, PyObject* args, PyObject* kwds) { assert(self->connection); static char* argNames[] = { + const_cast<char*>("compress"), const_cast<char*>("_ex"), const_cast<char*>("_sent"), 0 }; + PyObject* compressBatch; PyObject* ex = Py_None; PyObject* sent = Py_None; - if(!PyArg_ParseTupleAndKeywords(args, kwds, STRCAST("|OO"), argNames, &ex, &sent)) + if(!PyArg_ParseTupleAndKeywords(args, kwds, STRCAST("O|OO"), argNames, &compressBatch, &ex, &sent)) { return 0; } + PyObject* compressBatchType = lookupType("Ice.CompressBatch"); + if(!PyObject_IsInstance(compressBatch, reinterpret_cast<PyObject*>(compressBatchType))) + { + return 0; + } + + PyObjectHandle v = PyObject_GetAttrString(compressBatch, STRCAST("_value")); + assert(v.get()); + Ice::CompressBatch cb = static_cast<Ice::CompressBatch>(PyLong_AsLong(v.get())); + if(ex == Py_None) { ex = 0; @@ -372,11 +551,11 @@ connectionBeginFlushBatchRequests(ConnectionObject* self, PyObject* args, PyObje return 0; } - Ice::Callback_Connection_flushBatchRequestsPtr cb; + Ice::Callback_Connection_flushBatchRequestsPtr callback; if(ex || sent) { FlushCallbackPtr d = new FlushCallback(ex, sent, "flushBatchRequests"); - cb = Ice::newCallback_Connection_flushBatchRequests(d, &FlushCallback::exception, &FlushCallback::sent); + callback = Ice::newCallback_Connection_flushBatchRequests(d, &FlushCallback::exception, &FlushCallback::sent); } Ice::AsyncResultPtr result; @@ -384,13 +563,13 @@ connectionBeginFlushBatchRequests(ConnectionObject* self, PyObject* args, PyObje { AllowThreads allowThreads; // Release Python's global interpreter lock during remote invocations. - if(cb) + if(callback) { - result = (*self->connection)->begin_flushBatchRequests(cb); + result = (*self->connection)->begin_flushBatchRequests(cb, callback); } else { - result = (*self->connection)->begin_flushBatchRequests(); + result = (*self->connection)->begin_flushBatchRequests(cb); } } catch(const Ice::Exception& ex) @@ -437,22 +616,174 @@ connectionEndFlushBatchRequests(ConnectionObject* self, PyObject* args) extern "C" #endif static PyObject* -connectionSetCallback(ConnectionObject* self, PyObject* args) +connectionSetCloseCallback(ConnectionObject* self, PyObject* args) { assert(self->connection); - PyObject* callbackType = lookupType("Ice.ConnectionCallback"); + PyObject* callbackType = lookupType("types.FunctionType"); PyObject* cb; if(!PyArg_ParseTuple(args, STRCAST("O!"), callbackType, &cb)) { return 0; } - Ice::ConnectionCallbackPtr wrapper = new ConnectionCallbackI(cb, reinterpret_cast<PyObject*>(self)); + Ice::CloseCallbackPtr wrapper = new CloseCallbackWrapper(cb, reinterpret_cast<PyObject*>(self)); try { AllowThreads allowThreads; // Release Python's global interpreter lock during blocking invocations. - (*self->connection)->setCallback(wrapper); + (*self->connection)->setCloseCallback(wrapper); + } + catch(const Ice::Exception& ex) + { + setPythonException(ex); + return 0; + } + + Py_INCREF(Py_None); + return Py_None; +} + +#ifdef WIN32 +extern "C" +#endif +static PyObject* +connectionSetHeartbeatCallback(ConnectionObject* self, PyObject* args) +{ + assert(self->connection); + + PyObject* callbackType = lookupType("types.FunctionType"); + PyObject* cb; + if(!PyArg_ParseTuple(args, STRCAST("O!"), callbackType, &cb)) + { + return 0; + } + + Ice::HeartbeatCallbackPtr wrapper = new HeartbeatCallbackWrapper(cb, reinterpret_cast<PyObject*>(self)); + try + { + AllowThreads allowThreads; // Release Python's global interpreter lock during blocking invocations. + (*self->connection)->setHeartbeatCallback(wrapper); + } + catch(const Ice::Exception& ex) + { + setPythonException(ex); + return 0; + } + + Py_INCREF(Py_None); + return Py_None; +} + +#ifdef WIN32 +extern "C" +#endif +static PyObject* +connectionHeartbeat(ConnectionObject* self) +{ + assert(self->connection); + try + { + AllowThreads allowThreads; // Release Python's global interpreter lock during remote invocations. + (*self->connection)->heartbeat(); + } + catch(const Ice::Exception& ex) + { + setPythonException(ex); + return 0; + } + + Py_INCREF(Py_None); + return Py_None; +} + +#ifdef WIN32 +extern "C" +#endif +static PyObject* +connectionBeginHeartbeat(ConnectionObject* self, PyObject* args, PyObject* kwds) +{ + assert(self->connection); + + static char* argNames[] = + { + const_cast<char*>("_ex"), + const_cast<char*>("_sent"), + 0 + }; + PyObject* ex = Py_None; + PyObject* sent = Py_None; + if(!PyArg_ParseTupleAndKeywords(args, kwds, STRCAST("|OO"), argNames, &ex, &sent)) + { + return 0; + } + + if(ex == Py_None) + { + ex = 0; + } + if(sent == Py_None) + { + sent = 0; + } + + if(!ex && sent) + { + PyErr_Format(PyExc_RuntimeError, + STRCAST("exception callback must also be provided when sent callback is used")); + return 0; + } + + Ice::Callback_Connection_heartbeatPtr cb; + if(ex || sent) + { + HeartbeatAsyncCallbackPtr d = new HeartbeatAsyncCallback(ex, sent, "heartbeat"); + cb = Ice::newCallback_Connection_heartbeat(d, &HeartbeatAsyncCallback::exception, + &HeartbeatAsyncCallback::sent); + } + + Ice::AsyncResultPtr result; + try + { + AllowThreads allowThreads; // Release Python's global interpreter lock during remote invocations. + + if(cb) + { + result = (*self->connection)->begin_heartbeat(cb); + } + else + { + result = (*self->connection)->begin_heartbeat(); + } + } + catch(const Ice::Exception& ex) + { + setPythonException(ex); + return 0; + } + + PyObjectHandle communicator = getCommunicatorWrapper(*self->communicator); + return createAsyncResult(result, 0, reinterpret_cast<PyObject*>(self), communicator.get()); +} + +#ifdef WIN32 +extern "C" +#endif +static PyObject* +connectionEndHeartbeat(ConnectionObject* self, PyObject* args) +{ + assert(self->connection); + + PyObject* result; + if(!PyArg_ParseTuple(args, STRCAST("O!"), &AsyncResultType, &result)) + { + return 0; + } + + Ice::AsyncResultPtr r = getAsyncResult(result); + try + { + AllowThreads allowThreads; // Release Python's global interpreter lock during blocking invocations. + (*self->connection)->end_flushBatchRequests(r); } catch(const Ice::Exception& ex) { @@ -738,24 +1069,55 @@ connectionSetBufferSize(ConnectionObject* self, PyObject* args) return Py_None; } +#ifdef WIN32 +extern "C" +#endif +static PyObject* +connectionThrowException(ConnectionObject* self) +{ + assert(self->connection); + try + { + (*self->connection)->throwException(); + } + catch(const Ice::Exception& ex) + { + setPythonException(ex); + return 0; + } + + Py_INCREF(Py_None); + return Py_None; +} + static PyMethodDef ConnectionMethods[] = { { STRCAST("close"), reinterpret_cast<PyCFunction>(connectionClose), METH_VARARGS, - PyDoc_STR(STRCAST("close(bool) -> None")) }, + PyDoc_STR(STRCAST("close(Ice.ConnectionClose) -> None")) }, { STRCAST("createProxy"), reinterpret_cast<PyCFunction>(connectionCreateProxy), METH_VARARGS, PyDoc_STR(STRCAST("createProxy(Ice.Identity) -> Ice.ObjectPrx")) }, { STRCAST("setAdapter"), reinterpret_cast<PyCFunction>(connectionSetAdapter), METH_VARARGS, PyDoc_STR(STRCAST("setAdapter(Ice.ObjectAdapter) -> None")) }, { STRCAST("getAdapter"), reinterpret_cast<PyCFunction>(connectionGetAdapter), METH_NOARGS, PyDoc_STR(STRCAST("getAdapter() -> Ice.ObjectAdapter")) }, - { STRCAST("flushBatchRequests"), reinterpret_cast<PyCFunction>(connectionFlushBatchRequests), METH_NOARGS, - PyDoc_STR(STRCAST("flushBatchRequests() -> None")) }, + { STRCAST("flushBatchRequests"), reinterpret_cast<PyCFunction>(connectionFlushBatchRequests), METH_VARARGS, + PyDoc_STR(STRCAST("flushBatchRequests(Ice.CompressBatch) -> None")) }, + { STRCAST("flushBatchRequestsAsync"), reinterpret_cast<PyCFunction>(connectionFlushBatchRequestsAsync), + METH_VARARGS, PyDoc_STR(STRCAST("flushBatchRequestsAsync(Ice.CompressBatch) -> Ice.Future")) }, { STRCAST("begin_flushBatchRequests"), reinterpret_cast<PyCFunction>(connectionBeginFlushBatchRequests), - METH_VARARGS | METH_KEYWORDS, PyDoc_STR(STRCAST("begin_flushBatchRequests([_ex][, _sent]) -> Ice.AsyncResult")) }, + METH_VARARGS | METH_KEYWORDS, PyDoc_STR(STRCAST("begin_flushBatchRequests(Ice.CompressBatch, [_ex][, _sent]) -> Ice.AsyncResult")) }, { STRCAST("end_flushBatchRequests"), reinterpret_cast<PyCFunction>(connectionEndFlushBatchRequests), METH_VARARGS, PyDoc_STR(STRCAST("end_flushBatchRequests(Ice.AsyncResult) -> None")) }, - { STRCAST("setCallback"), reinterpret_cast<PyCFunction>(connectionSetCallback), METH_VARARGS, - PyDoc_STR(STRCAST("setCallback(Ice.ConnectionCallback) -> None")) }, + { STRCAST("setCloseCallback"), reinterpret_cast<PyCFunction>(connectionSetCloseCallback), METH_VARARGS, + PyDoc_STR(STRCAST("setCloseCallback(Ice.CloseCallback) -> None")) }, + { STRCAST("setHeartbeatCallback"), reinterpret_cast<PyCFunction>(connectionSetHeartbeatCallback), METH_VARARGS, + PyDoc_STR(STRCAST("setHeartbeatCallback(Ice.HeartbeatCallback) -> None")) }, + { STRCAST("heartbeat"), reinterpret_cast<PyCFunction>(connectionHeartbeat), METH_NOARGS, + PyDoc_STR(STRCAST("heartbeat() -> None")) }, + { STRCAST("begin_heartbeat"), reinterpret_cast<PyCFunction>(connectionBeginHeartbeat), + METH_VARARGS | METH_KEYWORDS, PyDoc_STR(STRCAST("begin_heartbeat([_ex][, _sent]) -> Ice.AsyncResult")) }, + { STRCAST("end_heartbeat"), reinterpret_cast<PyCFunction>(connectionEndHeartbeat), METH_VARARGS, + PyDoc_STR(STRCAST("end_heartbeat(Ice.AsyncResult) -> None")) }, { STRCAST("setACM"), reinterpret_cast<PyCFunction>(connectionSetACM), METH_VARARGS, PyDoc_STR(STRCAST("setACM(int, Ice.ACMClose, Ice.ACMHeartbeat) -> None")) }, { STRCAST("getACM"), reinterpret_cast<PyCFunction>(connectionGetACM), METH_NOARGS, @@ -772,6 +1134,8 @@ static PyMethodDef ConnectionMethods[] = PyDoc_STR(STRCAST("getEndpoint() -> Ice.Endpoint")) }, { STRCAST("setBufferSize"), reinterpret_cast<PyCFunction>(connectionSetBufferSize), METH_VARARGS, PyDoc_STR(STRCAST("setBufferSize(int, int) -> None")) }, + { STRCAST("throwException"), reinterpret_cast<PyCFunction>(connectionThrowException), METH_NOARGS, + PyDoc_STR(STRCAST("throwException() -> None")) }, { 0, 0 } /* sentinel */ }; diff --git a/python/modules/IcePy/ConnectionInfo.cpp b/python/modules/IcePy/ConnectionInfo.cpp index 387032ab965..27edce314d3 100644 --- a/python/modules/IcePy/ConnectionInfo.cpp +++ b/python/modules/IcePy/ConnectionInfo.cpp @@ -54,38 +54,27 @@ connectionInfoDealloc(ConnectionInfoObject* self) extern "C" #endif static PyObject* -connectionInfoGetIncoming(ConnectionInfoObject* self) -{ - PyObject* result = (*self->connectionInfo)->incoming ? getTrue() : getFalse(); - Py_INCREF(result); - return result; -} - -#ifdef WIN32 -extern "C" -#endif -static PyObject* -connectionInfoGetAdapterName(ConnectionInfoObject* self) +connectionInfoGetUnderlying(ConnectionInfoObject* self) { - return createString((*self->connectionInfo)->adapterName); + return createConnectionInfo((*self->connectionInfo)->underlying); } #ifdef WIN32 extern "C" #endif static PyObject* -connectionInfoGetRcvSize(ConnectionInfoObject* self) +connectionInfoGetIncoming(ConnectionInfoObject* self) { - return PyLong_FromLong((*self->connectionInfo)->rcvSize); + return (*self->connectionInfo)->incoming ? incTrue() : incFalse(); } #ifdef WIN32 extern "C" #endif static PyObject* -connectionInfoGetSndSize(ConnectionInfoObject* self) +connectionInfoGetAdapterName(ConnectionInfoObject* self) { - return PyLong_FromLong((*self->connectionInfo)->sndSize); + return createString((*self->connectionInfo)->adapterName); } #ifdef WIN32 @@ -136,6 +125,28 @@ ipConnectionInfoGetRemotePort(ConnectionInfoObject* self) extern "C" #endif static PyObject* +tcpConnectionInfoGetRcvSize(ConnectionInfoObject* self) +{ + Ice::TCPConnectionInfoPtr info = Ice::TCPConnectionInfoPtr::dynamicCast(*self->connectionInfo); + assert(info); + return PyLong_FromLong(info->rcvSize); +} + +#ifdef WIN32 +extern "C" +#endif +static PyObject* +tcpConnectionInfoGetSndSize(ConnectionInfoObject* self) +{ + Ice::TCPConnectionInfoPtr info = Ice::TCPConnectionInfoPtr::dynamicCast(*self->connectionInfo); + assert(info); + return PyLong_FromLong(info->sndSize); +} + +#ifdef WIN32 +extern "C" +#endif +static PyObject* udpConnectionInfoGetMcastAddress(ConnectionInfoObject* self) { Ice::UDPConnectionInfoPtr info = Ice::UDPConnectionInfoPtr::dynamicCast(*self->connectionInfo); @@ -158,6 +169,28 @@ udpConnectionInfoGetMcastPort(ConnectionInfoObject* self, void* member) extern "C" #endif static PyObject* +udpConnectionInfoGetRcvSize(ConnectionInfoObject* self) +{ + Ice::UDPConnectionInfoPtr info = Ice::UDPConnectionInfoPtr::dynamicCast(*self->connectionInfo); + assert(info); + return PyLong_FromLong(info->rcvSize); +} + +#ifdef WIN32 +extern "C" +#endif +static PyObject* +udpConnectionInfoGetSndSize(ConnectionInfoObject* self) +{ + Ice::UDPConnectionInfoPtr info = Ice::UDPConnectionInfoPtr::dynamicCast(*self->connectionInfo); + assert(info); + return PyLong_FromLong(info->sndSize); +} + +#ifdef WIN32 +extern "C" +#endif +static PyObject* wsConnectionInfoGetHeaders(ConnectionInfoObject* self) { Ice::WSConnectionInfoPtr info = Ice::WSConnectionInfoPtr::dynamicCast(*self->connectionInfo); @@ -212,47 +245,17 @@ sslConnectionInfoGetVerified(ConnectionInfoObject* self) { IceSSL::ConnectionInfoPtr info = IceSSL::ConnectionInfoPtr::dynamicCast(*self->connectionInfo); assert(info); - PyObject* result = info->incoming ? getTrue() : getFalse(); - Py_INCREF(result); - return result; -} - -#ifdef WIN32 -extern "C" -#endif -static PyObject* -wssConnectionInfoGetHeaders(ConnectionInfoObject* self) -{ - IceSSL::WSSConnectionInfoPtr info = IceSSL::WSSConnectionInfoPtr::dynamicCast(*self->connectionInfo); - assert(info); - - PyObjectHandle result = PyDict_New(); - if(result.get()) - { - for(Ice::HeaderDict::iterator p = info->headers.begin(); p != info->headers.end(); ++p) - { - PyObjectHandle key = createString(p->first); - PyObjectHandle val = createString(p->second); - if(!val.get() || PyDict_SetItem(result.get(), key.get(), val.get()) < 0) - { - return 0; - } - } - } - - return result.release(); + return info->incoming ? incTrue() : incFalse(); } static PyGetSetDef ConnectionInfoGetters[] = { + { STRCAST("underlying"), reinterpret_cast<getter>(connectionInfoGetUnderlying), 0, + PyDoc_STR(STRCAST("get underlying connection information")), 0 }, { STRCAST("incoming"), reinterpret_cast<getter>(connectionInfoGetIncoming), 0, PyDoc_STR(STRCAST("whether connection is incoming")), 0 }, { STRCAST("adapterName"), reinterpret_cast<getter>(connectionInfoGetAdapterName), 0, PyDoc_STR(STRCAST("adapter associated the connection")), 0 }, - { STRCAST("rcvSize"), reinterpret_cast<getter>(connectionInfoGetRcvSize), 0, - PyDoc_STR(STRCAST("receive buffer size")), 0 }, - { STRCAST("sndSize"), reinterpret_cast<getter>(connectionInfoGetSndSize), 0, - PyDoc_STR(STRCAST("send buffer size")), 0 }, { 0, 0 } /* sentinel */ }; @@ -269,12 +272,25 @@ static PyGetSetDef IPConnectionInfoGetters[] = { 0, 0 } /* sentinel */ }; +static PyGetSetDef TCPConnectionInfoGetters[] = +{ + { STRCAST("rcvSize"), reinterpret_cast<getter>(tcpConnectionInfoGetRcvSize), 0, + PyDoc_STR(STRCAST("receive buffer size")), 0 }, + { STRCAST("sndSize"), reinterpret_cast<getter>(tcpConnectionInfoGetSndSize), 0, + PyDoc_STR(STRCAST("send buffer size")), 0 }, + { 0, 0 } /* sentinel */ +}; + static PyGetSetDef UDPConnectionInfoGetters[] = { { STRCAST("mcastAddress"), reinterpret_cast<getter>(udpConnectionInfoGetMcastAddress), 0, PyDoc_STR(STRCAST("multicast address")), 0 }, { STRCAST("mcastPort"), reinterpret_cast<getter>(udpConnectionInfoGetMcastPort), 0, PyDoc_STR(STRCAST("multicast port")), 0 }, + { STRCAST("rcvSize"), reinterpret_cast<getter>(udpConnectionInfoGetRcvSize), 0, + PyDoc_STR(STRCAST("receive buffer size")), 0 }, + { STRCAST("sndSize"), reinterpret_cast<getter>(udpConnectionInfoGetSndSize), 0, + PyDoc_STR(STRCAST("send buffer size")), 0 }, { 0, 0 } /* sentinel */ }; @@ -296,13 +312,6 @@ static PyGetSetDef SSLConnectionInfoGetters[] = { 0, 0 } /* sentinel */ }; -static PyGetSetDef WSSConnectionInfoGetters[] = -{ - { STRCAST("headers"), reinterpret_cast<getter>(wssConnectionInfoGetHeaders), 0, - PyDoc_STR(STRCAST("request headers")), 0 }, - { 0, 0 } /* sentinel */ -}; - namespace IcePy { @@ -434,7 +443,7 @@ PyTypeObject TCPConnectionInfoType = 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ - 0, /* tp_getset */ + TCPConnectionInfoGetters, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ @@ -588,53 +597,6 @@ PyTypeObject SSLConnectionInfoType = 0, /* tp_is_gc */ }; -PyTypeObject WSSConnectionInfoType = -{ - /* The ob_type field must be initialized in the module init function - * to be portable to Windows without using C++. */ - PyVarObject_HEAD_INIT(0, 0) - STRCAST("IcePy.WSSConnectionInfo"),/* tp_name */ - sizeof(ConnectionInfoObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)connectionInfoDealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - WSSConnectionInfoGetters, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - (newfunc)connectionInfoNew, /* tp_new */ - 0, /* tp_free */ - 0, /* tp_is_gc */ -}; - } bool @@ -683,7 +645,7 @@ IcePy::initConnectionInfo(PyObject* module) return false; } - WSConnectionInfoType.tp_base = &IPConnectionInfoType; // Force inheritance from IPConnectionType. + WSConnectionInfoType.tp_base = &ConnectionInfoType; // Force inheritance from IPConnectionType. if(PyType_Ready(&WSConnectionInfoType) < 0) { return false; @@ -694,7 +656,7 @@ IcePy::initConnectionInfo(PyObject* module) return false; } - SSLConnectionInfoType.tp_base = &IPConnectionInfoType; // Force inheritance from IPConnectionInfoType. + SSLConnectionInfoType.tp_base = &ConnectionInfoType; // Force inheritance from IPConnectionInfoType. if(PyType_Ready(&SSLConnectionInfoType) < 0) { return false; @@ -705,17 +667,6 @@ IcePy::initConnectionInfo(PyObject* module) return false; } - WSSConnectionInfoType.tp_base = &SSLConnectionInfoType; // Force inheritance from IPConnectionType. - if(PyType_Ready(&WSSConnectionInfoType) < 0) - { - return false; - } - type = &WSSConnectionInfoType; // Necessary to prevent GCC's strict-alias warnings. - if(PyModule_AddObject(module, STRCAST("WSSConnectionInfo"), reinterpret_cast<PyObject*>(type)) < 0) - { - return false; - } - return true; } @@ -730,6 +681,12 @@ IcePy::getConnectionInfo(PyObject* obj) PyObject* IcePy::createConnectionInfo(const Ice::ConnectionInfoPtr& connectionInfo) { + if(!connectionInfo) + { + Py_INCREF(Py_None); + return Py_None; + } + PyTypeObject* type; if(Ice::WSConnectionInfoPtr::dynamicCast(connectionInfo)) { @@ -743,10 +700,6 @@ IcePy::createConnectionInfo(const Ice::ConnectionInfoPtr& connectionInfo) { type = &UDPConnectionInfoType; } - else if(IceSSL::WSSConnectionInfoPtr::dynamicCast(connectionInfo)) - { - type = &WSSConnectionInfoType; - } else if(IceSSL::ConnectionInfoPtr::dynamicCast(connectionInfo)) { type = &SSLConnectionInfoType; diff --git a/python/modules/IcePy/Endpoint.cpp b/python/modules/IcePy/Endpoint.cpp index 7088b84e9a6..43b92900d42 100644 --- a/python/modules/IcePy/Endpoint.cpp +++ b/python/modules/IcePy/Endpoint.cpp @@ -99,9 +99,7 @@ endpointCompare(EndpointObject* p1, PyObject* other, int op) } } - PyObject* r = result ? getTrue() : getFalse(); - Py_INCREF(r); - return r; + return result ? incTrue() : incFalse(); } #ifdef WIN32 @@ -254,3 +252,27 @@ IcePy::createEndpoint(const Ice::EndpointPtr& endpoint) obj->endpoint = new Ice::EndpointPtr(endpoint); return (PyObject*)obj; } + +bool +IcePy::toEndpointSeq(PyObject* endpoints, Ice::EndpointSeq& seq) +{ + Py_ssize_t sz = PySequence_Fast_GET_SIZE(endpoints); + for(Py_ssize_t i = 0; i < sz; ++i) + { + PyObject* p = PySequence_Fast_GET_ITEM(endpoints, i); + PyTypeObject* type = &EndpointType; // Necessary to prevent GCC's strict-alias warnings. + if(!PyObject_IsInstance(p, reinterpret_cast<PyObject*>(type))) + { + PyErr_Format(PyExc_ValueError, STRCAST("expected element of type Ice.Endpoint")); + return false; + } + Ice::EndpointPtr endp = getEndpoint(p); + if(!endp) + { + return false; + } + seq.push_back(endp); + } + + return true; +} diff --git a/python/modules/IcePy/Endpoint.h b/python/modules/IcePy/Endpoint.h index 8545ad4b76d..88d43207d01 100644 --- a/python/modules/IcePy/Endpoint.h +++ b/python/modules/IcePy/Endpoint.h @@ -23,6 +23,8 @@ bool initEndpoint(PyObject*); PyObject* createEndpoint(const Ice::EndpointPtr&); Ice::EndpointPtr getEndpoint(PyObject*); +bool toEndpointSeq(PyObject*, Ice::EndpointSeq&); + } #endif diff --git a/python/modules/IcePy/EndpointInfo.cpp b/python/modules/IcePy/EndpointInfo.cpp index 9fa036071c5..246b555f80c 100644 --- a/python/modules/IcePy/EndpointInfo.cpp +++ b/python/modules/IcePy/EndpointInfo.cpp @@ -124,6 +124,15 @@ endpointInfoSecure(EndpointInfoObject* self) extern "C" #endif static PyObject* +endpointInfoGetUnderlying(EndpointInfoObject* self) +{ + return createEndpointInfo((*self->endpointInfo)->underlying); +} + +#ifdef WIN32 +extern "C" +#endif +static PyObject* endpointInfoGetTimeout(EndpointInfoObject* self) { return PyLong_FromLong((*self->endpointInfo)->timeout); @@ -135,9 +144,7 @@ extern "C" static PyObject* endpointInfoGetCompress(EndpointInfoObject* self) { - PyObject* result = (*self->endpointInfo)->compress ? getTrue() : getFalse(); - Py_INCREF(result); - return result; + return (*self->endpointInfo)->compress ? incTrue() : incFalse(); } #ifdef WIN32 @@ -210,17 +217,6 @@ wsEndpointInfoGetResource(EndpointInfoObject* self) extern "C" #endif static PyObject* -wssEndpointInfoGetResource(EndpointInfoObject* self) -{ - IceSSL::WSSEndpointInfoPtr info = IceSSL::WSSEndpointInfoPtr::dynamicCast(*self->endpointInfo); - assert(info); - return createString(info->resource); -} - -#ifdef WIN32 -extern "C" -#endif -static PyObject* opaqueEndpointInfoGetRawBytes(EndpointInfoObject* self) { Ice::OpaqueEndpointInfoPtr info = Ice::OpaqueEndpointInfoPtr::dynamicCast(*self->endpointInfo); @@ -258,6 +254,8 @@ static PyMethodDef EndpointInfoMethods[] = static PyGetSetDef EndpointInfoGetters[] = { + { STRCAST("underlying"), reinterpret_cast<getter>(endpointInfoGetUnderlying), 0, + PyDoc_STR(STRCAST("underling endpoint information")), 0 }, { STRCAST("timeout"), reinterpret_cast<getter>(endpointInfoGetTimeout), 0, PyDoc_STR(STRCAST("timeout in milliseconds")), 0 }, { STRCAST("compress"), reinterpret_cast<getter>(endpointInfoGetCompress), 0, @@ -292,13 +290,6 @@ static PyGetSetDef WSEndpointInfoGetters[] = { 0, 0 } /* sentinel */ }; -static PyGetSetDef WSSEndpointInfoGetters[] = -{ - { STRCAST("resource"), reinterpret_cast<getter>(wssEndpointInfoGetResource), 0, - PyDoc_STR(STRCAST("resource")), 0 }, - { 0, 0 } /* sentinel */ -}; - static PyGetSetDef OpaqueEndpointInfoGetters[] = { { STRCAST("rawBytes"), reinterpret_cast<getter>(opaqueEndpointInfoGetRawBytes), 0, @@ -363,7 +354,7 @@ PyTypeObject IPEndpointInfoType = /* The ob_type field must be initialized in the module init function * to be portable to Windows without using C++. */ PyVarObject_HEAD_INIT(0, 0) - STRCAST("IcePy.IPEndpointInfo"), /* tp_name */ + STRCAST(".IPEndpointInfo"), /* tp_name */ sizeof(EndpointInfoObject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ @@ -593,53 +584,6 @@ PyTypeObject SSLEndpointInfoType = 0, /* tp_is_gc */ }; -PyTypeObject WSSEndpointInfoType = -{ - /* The ob_type field must be initialized in the module init function - * to be portable to Windows without using C++. */ - PyVarObject_HEAD_INIT(0, 0) - STRCAST("IcePy.WSSEndpointInfo"), /* tp_name */ - sizeof(EndpointInfoObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - reinterpret_cast<destructor>(endpointInfoDealloc), /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - WSSEndpointInfoGetters, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - reinterpret_cast<newfunc>(endpointInfoNew), /* tp_new */ - 0, /* tp_free */ - 0, /* tp_is_gc */ -}; - PyTypeObject OpaqueEndpointInfoType = { /* The ob_type field must be initialized in the module init function @@ -735,7 +679,7 @@ IcePy::initEndpointInfo(PyObject* module) return false; } - WSEndpointInfoType.tp_base = &IPEndpointInfoType; // Force inheritance from IPEndpointType. + WSEndpointInfoType.tp_base = &EndpointInfoType; // Force inheritance from IPEndpointType. if(PyType_Ready(&WSEndpointInfoType) < 0) { return false; @@ -746,7 +690,7 @@ IcePy::initEndpointInfo(PyObject* module) return false; } - SSLEndpointInfoType.tp_base = &IPEndpointInfoType; // Force inheritance from IPEndpointInfoType. + SSLEndpointInfoType.tp_base = &EndpointInfoType; // Force inheritance from IPEndpointInfoType. if(PyType_Ready(&SSLEndpointInfoType) < 0) { return false; @@ -757,17 +701,6 @@ IcePy::initEndpointInfo(PyObject* module) return false; } - WSSEndpointInfoType.tp_base = &SSLEndpointInfoType; // Force inheritance from SSLEndpointInfoType. - if(PyType_Ready(&WSSEndpointInfoType) < 0) - { - return false; - } - type = &WSSEndpointInfoType; // Necessary to prevent GCC's strict-alias warnings. - if(PyModule_AddObject(module, STRCAST("WSSEndpointInfo"), reinterpret_cast<PyObject*>(type)) < 0) - { - return false; - } - OpaqueEndpointInfoType.tp_base = &EndpointInfoType; // Force inheritance from EndpointType. if(PyType_Ready(&OpaqueEndpointInfoType) < 0) { @@ -793,6 +726,12 @@ IcePy::getEndpointInfo(PyObject* obj) PyObject* IcePy::createEndpointInfo(const Ice::EndpointInfoPtr& endpointInfo) { + if(!endpointInfo) + { + Py_INCREF(Py_None); + return Py_None; + } + PyTypeObject* type; if(Ice::WSEndpointInfoPtr::dynamicCast(endpointInfo)) { @@ -806,10 +745,6 @@ IcePy::createEndpointInfo(const Ice::EndpointInfoPtr& endpointInfo) { type = &UDPEndpointInfoType; } - else if(IceSSL::WSSEndpointInfoPtr::dynamicCast(endpointInfo)) - { - type = &WSSEndpointInfoType; - } else if(IceSSL::EndpointInfoPtr::dynamicCast(endpointInfo)) { type = &SSLEndpointInfoType; @@ -824,7 +759,6 @@ IcePy::createEndpointInfo(const Ice::EndpointInfoPtr& endpointInfo) } else { - std::cout << "CREATE" << std::endl; type = &EndpointInfoType; } diff --git a/python/modules/IcePy/IcePy.rc b/python/modules/IcePy/IcePy.rc deleted file mode 100644 index f15140944dc..00000000000 --- a/python/modules/IcePy/IcePy.rc +++ /dev/null @@ -1,38 +0,0 @@ -#include "winver.h" - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 3,6,3,0 - PRODUCTVERSION 3,6,3,0 - FILEFLAGSMASK VS_FFI_FILEFLAGSMASK -#ifdef _DEBUG - FILEFLAGS VS_FF_DEBUG - #define INTERNALNAME "IcePy_d\0" - #define ORIGINALFILENAME "IcePy_d.pyd\0" -#else - FILEFLAGS 0x0L - #define INTERNALNAME "IcePy\0" - #define ORIGINALFILENAME "IcePy.pyd\0" -#endif - FILEOS 0x4L - FILETYPE VFT_DLL - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904e4" - BEGIN - VALUE "CompanyName", "ZeroC, Inc.\0" - VALUE "FileDescription", "Ice for Python Extension\0" - VALUE "FileVersion", "3.6.3\0" - VALUE "InternalName", INTERNALNAME - VALUE "LegalCopyright", "Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved.\0" - VALUE "OriginalFilename", ORIGINALFILENAME - VALUE "ProductName", "Ice\0" - VALUE "ProductVersion", "3.6.3\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1252 - END -END diff --git a/python/modules/IcePy/ImplicitContext.cpp b/python/modules/IcePy/ImplicitContext.cpp index 9821429461a..3edb3c55ec5 100644 --- a/python/modules/IcePy/ImplicitContext.cpp +++ b/python/modules/IcePy/ImplicitContext.cpp @@ -108,9 +108,7 @@ implicitContextCompare(ImplicitContextObject* c1, PyObject* other, int op) } } - PyObject* r = result ? getTrue() : getFalse(); - Py_INCREF(r); - return r; + return result ? incTrue() : incFalse(); } #ifdef WIN32 diff --git a/python/modules/IcePy/Init.cpp b/python/modules/IcePy/Init.cpp index f87d25236c6..35caf6a9e15 100644 --- a/python/modules/IcePy/Init.cpp +++ b/python/modules/IcePy/Init.cpp @@ -26,7 +26,9 @@ #include <Proxy.h> #include <Slice.h> #include <Types.h> +#include <ValueFactoryManager.h> #include <Ice/Initialize.h> +#include <Ice/RegisterPlugins.h> using namespace std; using namespace IcePy; @@ -59,8 +61,8 @@ static PyMethodDef methods[] = PyDoc_STR(STRCAST("createProperties([args]) -> Ice.Properties")) }, { STRCAST("stringToIdentity"), reinterpret_cast<PyCFunction>(IcePy_stringToIdentity), METH_O, PyDoc_STR(STRCAST("stringToIdentity(string) -> Ice.Identity")) }, - { STRCAST("identityToString"), reinterpret_cast<PyCFunction>(IcePy_identityToString), METH_O, - PyDoc_STR(STRCAST("identityToString(Ice.Identity) -> string")) }, + { STRCAST("identityToString"), reinterpret_cast<PyCFunction>(IcePy_identityToString), METH_VARARGS, + PyDoc_STR(STRCAST("identityToString(Ice.Identity, Ice.ToStringMode) -> string")) }, { STRCAST("getProcessLogger"), reinterpret_cast<PyCFunction>(IcePy_getProcessLogger), METH_NOARGS, PyDoc_STR(STRCAST("getProcessLogger() -> Ice.Logger")) }, { STRCAST("setProcessLogger"), reinterpret_cast<PyCFunction>(IcePy_setProcessLogger), METH_VARARGS, @@ -83,6 +85,10 @@ static PyMethodDef methods[] = PyDoc_STR(STRCAST("internal function")) }, { STRCAST("defineClass"), reinterpret_cast<PyCFunction>(IcePy_defineClass), METH_VARARGS, PyDoc_STR(STRCAST("internal function")) }, + { STRCAST("declareValue"), reinterpret_cast<PyCFunction>(IcePy_declareValue), METH_VARARGS, + PyDoc_STR(STRCAST("internal function")) }, + { STRCAST("defineValue"), reinterpret_cast<PyCFunction>(IcePy_defineValue), METH_VARARGS, + PyDoc_STR(STRCAST("internal function")) }, { STRCAST("defineException"), reinterpret_cast<PyCFunction>(IcePy_defineException), METH_VARARGS, PyDoc_STR(STRCAST("internal function")) }, { STRCAST("stringify"), reinterpret_cast<PyCFunction>(IcePy_stringify), METH_VARARGS, @@ -109,10 +115,10 @@ static struct PyModuleDef iceModule = "The Internet Communications Engine.", -1, methods, - NULL, - NULL, - NULL, - NULL + ICE_NULLPTR, + ICE_NULLPTR, + ICE_NULLPTR, + ICE_NULLPTR }; #else @@ -123,15 +129,6 @@ PyDoc_STRVAR(moduleDoc, "The Internet Communications Engine."); #endif -#ifdef ICE_STATIC_LIBS -extern "C" -{ -Ice::Plugin* createIceSSL(const Ice::CommunicatorPtr&, const std::string&, const Ice::StringSeq&); -Ice::Plugin* createIceDiscovery(const Ice::CommunicatorPtr&, const string&, const Ice::StringSeq&); -Ice::Plugin* createIceLocatorDiscovery(const Ice::CommunicatorPtr&, const string&, const Ice::StringSeq&); -} -#endif - #if defined(__GNUC__) && PY_VERSION_HEX >= 0x03000000 extern "C" __attribute__((visibility ("default"))) PyObject * #elif defined(_WIN32) // On Windows, PyMoDINIT_FUNC already defines dllexport @@ -147,12 +144,9 @@ initIcePy(void) { PyObject* module; -#ifdef ICE_STATIC_LIBS - // Register the plugins manually if we're building with static libraries. - Ice::registerPluginFactory("IceSSL", createIceSSL, false); - Ice::registerPluginFactory("IceDiscovery", createIceDiscovery, false); - Ice::registerPluginFactory("IceLocatorDiscovery", createIceLocatorDiscovery, false); -#endif + Ice::registerIceSSL(false); + Ice::registerIceDiscovery(false); + Ice::registerIceLocatorDiscovery(false); // // Notify Python that we are a multi-threaded extension. @@ -234,6 +228,10 @@ initIcePy(void) { INIT_RETURN; } + if(!initValueFactoryManager(module)) + { + INIT_RETURN; + } #if PY_VERSION_HEX >= 0x03000000 return module; diff --git a/python/modules/IcePy/Makefile b/python/modules/IcePy/Makefile deleted file mode 100644 index 30f9492ddac..00000000000 --- a/python/modules/IcePy/Makefile +++ /dev/null @@ -1,58 +0,0 @@ -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -top_srcdir = ../.. - -LIBFILENAME = $(call mkpylibfilename,IcePy,$(VERSION)) -SONAME = $(call mkpysoname,IcePy,$(SOVERSION)) -LIBNAME = $(call mkpylibname,IcePy) - -TARGETS = $(call mklibtargets,$(libdir)/$(LIBFILENAME),$(libdir)/$(SONAME),$(libdir)/$(LIBNAME)) - -OBJS = BatchRequestInterceptor.o \ - Communicator.o \ - Connection.o \ - ConnectionInfo.o \ - Current.o \ - Endpoint.o \ - EndpointInfo.o \ - ImplicitContext.o \ - Init.o \ - Logger.o \ - ObjectAdapter.o \ - ObjectFactory.o \ - Operation.o \ - Properties.o \ - PropertiesAdmin.o \ - Proxy.o \ - Slice.o \ - Thread.o \ - Types.o \ - Util.o - -include $(top_srcdir)/config/Make.rules - -CPPFLAGS := -I. $(CPPFLAGS) $(ICE_FLAGS) $(PYTHON_FLAGS) - -LINKWITH := $(ICE_LIBS) $(PYTHON_LIBS) $(CXXLIBS) - -$(libdir)/$(LIBFILENAME): $(OBJS) - rm -f $@ - $(call mkshlib,$@,$(SONAME),$(OBJS),$(LINKWITH)) - -$(libdir)/$(SONAME): $(libdir)/$(LIBFILENAME) - rm -f $@ - ln -s $(LIBFILENAME) $@ - -$(libdir)/$(LIBNAME): $(libdir)/$(SONAME) - rm -f $@ - ln -s $(SONAME) $@ - -install:: all - $(call installlib,$(DESTDIR)$(install_libdir),$(libdir),$(LIBFILENAME),$(SONAME),$(LIBNAME)) diff --git a/python/modules/IcePy/Makefile.mak b/python/modules/IcePy/Makefile.mak deleted file mode 100644 index ff8184c741c..00000000000 --- a/python/modules/IcePy/Makefile.mak +++ /dev/null @@ -1,77 +0,0 @@ -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -top_srcdir = ..\.. - -LIBNAME = IcePy$(PYLIBSUFFIX).lib -DLLNAME = $(top_srcdir)\python\IcePy$(PYLIBSUFFIX).pyd - -TARGETS = $(LIBNAME) $(DLLNAME) - -OBJS = .\BatchRequestInterceptor.obj \ - .\Communicator.obj \ - .\Connection.obj \ - .\ConnectionInfo.obj \ - .\Current.obj \ - .\Endpoint.obj \ - .\EndpointInfo.obj \ - .\ImplicitContext.obj \ - .\Init.obj \ - .\Logger.obj \ - .\ObjectAdapter.obj \ - .\ObjectFactory.obj \ - .\Operation.obj \ - .\Properties.obj \ - .\PropertiesAdmin.obj \ - .\Proxy.obj \ - .\Slice.obj \ - .\Thread.obj \ - .\Types.obj \ - .\Util.obj - -# -# Get Make.common.rules.mak to determine CPP_COMPILER by setting it to 'auto' -# -CPP_COMPILER=auto - -!include $(top_srcdir)\config\Make.rules.mak - -!if ([$(PYTHON_HOME)\python.exe -c "import sys;print(sys.version_info >= (3, 5))" | findstr "True" > nul] == 0) -REQUIRED_COMPILER = VC140 -!else -REQUIRED_COMPILER = VC100 -!endif - -# -# Ensure we are using the right compiler -# -!if "$(CPP_COMPILER)" != "$(REQUIRED_COMPILER)" -!error Invalid CPP_COMPILER setting: $(CPP_COMPILER). Must be set to $(REQUIRED_COMPILER). -!endif - -CPPFLAGS = -I. $(CPPFLAGS) $(ICE_CPPFLAGS) $(PYTHON_CPPFLAGS) -DWIN32_LEAN_AND_MEAN - -LINKWITH = $(ICE_LIBS) $(PYTHON_LIBS) $(CXXLIBS) - -$(LIBNAME): $(DLLNAME) - -$(DLLNAME): $(OBJS) IcePy.res - $(LINK) $(PYTHON_LDFLAGS) $(ICE_LDFLAGS) $(LD_DLLFLAGS) $(PDBFLAGS) $(OBJS) \ - $(PREOUT)$@ $(PRELIBS)$(LINKWITH) IcePy.res - move $(@:.pyd=.lib) $(LIBNAME) - @if exist $@.manifest echo ^ ^ ^ Embedding manifest using $(MT) && \ - $(MT) -nologo -manifest $@.manifest -outputresource:$@;#2 && del /q $@.manifest - @if exist $(@:.pyd=.exp) del /q $(@:.pyd=.exp) - - -clean:: - -del /q IcePy.res - -install:: all - copy $(DLLNAME) "$(install_libdir)" diff --git a/python/modules/IcePy/Makefile.mk b/python/modules/IcePy/Makefile.mk new file mode 100644 index 00000000000..a5115f92838 --- /dev/null +++ b/python/modules/IcePy/Makefile.mk @@ -0,0 +1,34 @@ +# ********************************************************************** +# +# Copyright (c) 2003-2016 ZeroC, Inc. All rights reserved. +# +# This copy of Ice is licensed to you under the terms described in the +# ICE_LICENSE file included in this distribution. +# +# ********************************************************************** + +$(project)_libraries := IcePy + +IcePy_target := python-module +IcePy_targetname := IcePy +IcePy_targetdir := $(lang_srcdir)/python +IcePy_installdir := $(install_pythondir) +IcePy_cppflags := -I$(project) -I$(top_srcdir)/cpp/include -I$(top_srcdir)/cpp/include/generated \ + -I$(top_srcdir)/cpp/src $(python_cppflags) +IcePy_ldflags := $(python_ldflags) +IcePy_dependencies := IceDiscovery IceLocatorDiscovery IceSSL Ice +IcePy_libs := mcpp +IcePy_extra_sources := $(filter-out %Util.cpp %Ruby.cpp,\ + $(wildcard $(top_srcdir)/cpp/src/Slice/*.cpp)) \ + $(top_srcdir)/cpp/src/Slice/SliceUtil.cpp \ + $(top_srcdir)/cpp/src/Slice/PythonUtil.cpp \ + $(top_srcdir)/cpp/src/Slice/StringLiteralUtil.cpp \ + +# +# On the default platform, always write the module in the python directory. +# +$(foreach p,$(supported-platforms),$(eval $$p_targetdir[IcePy] := /$$p)) +$(firstword $(supported-platforms))_targetdir[IcePy] := + +projects += $(project) +srcs:: $(project) diff --git a/python/modules/IcePy/ObjectAdapter.cpp b/python/modules/IcePy/ObjectAdapter.cpp index 3b58d327aa3..07877369274 100644 --- a/python/modules/IcePy/ObjectAdapter.cpp +++ b/python/modules/IcePy/ObjectAdapter.cpp @@ -164,7 +164,7 @@ IcePy::ServantLocatorWrapper::locate(const Ice::Current& current, Ice::LocalObje PyObject* userExceptionType = lookupType("Ice.UserException"); if(PyObject_IsInstance(ex.ex.get(), userExceptionType)) { - throw ExceptionWriter(current.adapter->getCommunicator(), ex.ex); + throw ExceptionWriter(ex.ex); } ex.raise(); @@ -181,7 +181,7 @@ IcePy::ServantLocatorWrapper::locate(const Ice::Current& current, Ice::LocalObje { if(PyTuple_GET_SIZE(res.get()) > 2) { - PyErr_Warn(PyExc_RuntimeWarning, STRCAST("invalid return value for ServantLocator::locate")); + PyErr_WarnEx(PyExc_RuntimeWarning, STRCAST("invalid return value for ServantLocator::locate"), 1); return 0; } servantObj = PyTuple_GET_ITEM(res.get(), 0); @@ -200,7 +200,7 @@ IcePy::ServantLocatorWrapper::locate(const Ice::Current& current, Ice::LocalObje // if(!PyObject_IsInstance(servantObj, _objectType)) { - PyErr_Warn(PyExc_RuntimeWarning, STRCAST("return value of ServantLocator::locate is not an Ice object")); + PyErr_WarnEx(PyExc_RuntimeWarning, STRCAST("return value of ServantLocator::locate is not an Ice object"), 1); return 0; } @@ -243,7 +243,7 @@ IcePy::ServantLocatorWrapper::finished(const Ice::Current& current, const Ice::O PyObject* userExceptionType = lookupType("Ice.UserException"); if(PyObject_IsInstance(ex.ex.get(), userExceptionType)) { - throw ExceptionWriter(current.adapter->getCommunicator(), ex.ex); + throw ExceptionWriter(ex.ex); } ex.raise(); @@ -563,7 +563,7 @@ adapterWaitForDeactivate(ObjectAdapterObject* self, PyObject* args) self->deactivateThread = new AdapterInvokeThreadPtr(t); t->start(); } - + while(!self->deactivated) { bool done; @@ -571,7 +571,7 @@ adapterWaitForDeactivate(ObjectAdapterObject* self, PyObject* args) AllowThreads allowThreads; // Release Python's global interpreter lock during blocking calls. done = (*self->deactivateMonitor).timedWait(IceUtil::Time::milliSeconds(timeout)); } - + if(!done) { PyRETURN_FALSE; @@ -1541,8 +1541,42 @@ adapterGetLocator(ObjectAdapterObject* self) PyObject* locatorProxyType = lookupType("Ice.LocatorPrx"); assert(locatorProxyType); return createProxy(locator, (*self->adapter)->getCommunicator(), locatorProxyType); -} +} + +#ifdef WIN32 +extern "C" +#endif +static PyObject* +adapterGetEndpoints(ObjectAdapterObject* self) +{ + assert(self->adapter); + + Ice::EndpointSeq endpoints; + try + { + endpoints = (*self->adapter)->getEndpoints(); + } + catch(const Ice::Exception& ex) + { + setPythonException(ex); + return 0; + } + int count = static_cast<int>(endpoints.size()); + PyObjectHandle result = PyTuple_New(count); + int i = 0; + for(Ice::EndpointSeq::const_iterator p = endpoints.begin(); p != endpoints.end(); ++p, ++i) + { + PyObjectHandle endp = createEndpoint(*p); + if(!endp.get()) + { + return 0; + } + PyTuple_SET_ITEM(result.get(), i, endp.release()); // PyTuple_SET_ITEM steals a reference. + } + + return result.release(); +} #ifdef WIN32 extern "C" @@ -1570,20 +1604,20 @@ adapterRefreshPublishedEndpoints(ObjectAdapterObject* self) extern "C" #endif static PyObject* -adapterGetEndpoints(ObjectAdapterObject* self) +adapterGetPublishedEndpoints(ObjectAdapterObject* self) { assert(self->adapter); Ice::EndpointSeq endpoints; try { - endpoints = (*self->adapter)->getEndpoints(); + endpoints = (*self->adapter)->getPublishedEndpoints(); } catch(const Ice::Exception& ex) { setPythonException(ex); return 0; - } + } int count = static_cast<int>(endpoints.size()); PyObjectHandle result = PyTuple_New(count); @@ -1603,39 +1637,46 @@ adapterGetEndpoints(ObjectAdapterObject* self) #ifdef WIN32 extern "C" -#endif +#endif static PyObject* -adapterGetPublishedEndpoints(ObjectAdapterObject* self) +adapterSetPublishedEndpoints(ObjectAdapterObject* self, PyObject* args) { assert(self->adapter); - - Ice::EndpointSeq endpoints; - try - { - endpoints = (*self->adapter)->getPublishedEndpoints(); - } - catch(const Ice::Exception& ex) - { - setPythonException(ex); + + PyObject* endpoints; + if(!PyArg_ParseTuple(args, STRCAST("O"), &endpoints)) + { return 0; } - int count = static_cast<int>(endpoints.size()); - PyObjectHandle result = PyTuple_New(count); - int i = 0; - for(Ice::EndpointSeq::const_iterator p = endpoints.begin(); p != endpoints.end(); ++p, ++i) + if(!PyTuple_Check(endpoints) && !PyList_Check(endpoints)) { - PyObjectHandle endp = createEndpoint(*p); - if(!endp.get()) - { - return 0; - } - PyTuple_SET_ITEM(result.get(), i, endp.release()); // PyTuple_SET_ITEM steals a reference. + PyErr_Format(PyExc_ValueError, STRCAST("argument must be a tuple or list")); + return 0; } - return result.release(); + Ice::EndpointSeq seq; + if(!toEndpointSeq(endpoints, seq)) + { + return 0; + } + + try + { + AllowThreads allowThreads; // Release Python's global interpreter lock during blocking calls. + (*self->adapter)->setPublishedEndpoints(seq); + } + catch(const Ice::Exception& ex) + { + setPythonException(ex); + return 0; + } + + Py_INCREF(Py_None); + return Py_None; } + static PyMethodDef AdapterMethods[] = { { STRCAST("getName"), reinterpret_cast<PyCFunction>(adapterGetName), METH_NOARGS, @@ -1699,13 +1740,15 @@ static PyMethodDef AdapterMethods[] = { STRCAST("setLocator"), reinterpret_cast<PyCFunction>(adapterSetLocator), METH_VARARGS, PyDoc_STR(STRCAST("setLocator(proxy) -> None")) }, { STRCAST("getLocator"), reinterpret_cast<PyCFunction>(adapterGetLocator), METH_NOARGS, - PyDoc_STR(STRCAST("getLocator() -> Ice.LocatorPrx")) }, - { STRCAST("refreshPublishedEndpoints"), reinterpret_cast<PyCFunction>(adapterRefreshPublishedEndpoints), METH_NOARGS, - PyDoc_STR(STRCAST("refreshPublishedEndpoints() -> None")) }, + PyDoc_STR(STRCAST("getLocator() -> Ice.LocatorPrx")) }, { STRCAST("getEndpoints"), reinterpret_cast<PyCFunction>(adapterGetEndpoints), METH_NOARGS, PyDoc_STR(STRCAST("getEndpoints() -> None")) }, + { STRCAST("refreshPublishedEndpoints"), reinterpret_cast<PyCFunction>(adapterRefreshPublishedEndpoints), METH_NOARGS, + PyDoc_STR(STRCAST("refreshPublishedEndpoints() -> None")) }, { STRCAST("getPublishedEndpoints"), reinterpret_cast<PyCFunction>(adapterGetPublishedEndpoints), METH_NOARGS, PyDoc_STR(STRCAST("getPublishedEndpoints() -> None")) }, + { STRCAST("setPublishedEndpoints"), reinterpret_cast<PyCFunction>(adapterSetPublishedEndpoints), METH_VARARGS, + PyDoc_STR(STRCAST("setPublishedEndpoints(endpoints) -> None")) }, { 0, 0 } /* sentinel */ }; diff --git a/python/modules/IcePy/ObjectFactory.cpp b/python/modules/IcePy/ObjectFactory.cpp deleted file mode 100644 index 64903b33049..00000000000 --- a/python/modules/IcePy/ObjectFactory.cpp +++ /dev/null @@ -1,196 +0,0 @@ -// ********************************************************************** -// -// Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -// -// This copy of Ice is licensed to you under the terms described in the -// ICE_LICENSE file included in this distribution. -// -// ********************************************************************** - -#ifdef _WIN32 -# include <IceUtil/Config.h> -#endif -#include <ObjectFactory.h> -#include <Thread.h> -#include <Types.h> -#include <Util.h> -#include <Ice/LocalException.h> - -using namespace std; -using namespace IcePy; - -IcePy::ObjectFactory::ObjectFactory() -{ -} - -IcePy::ObjectFactory::~ObjectFactory() -{ - assert(_factoryMap.empty()); -} - -Ice::ObjectPtr -IcePy::ObjectFactory::create(const string& id) -{ - PyObject* factory = 0; - - // - // Check if the application has registered a factory for this id. - // - { - Lock sync(*this); - - FactoryMap::iterator p = _factoryMap.find(id); - if(p != _factoryMap.end()) - { - factory = p->second; - } - } - - // - // Get the type information. - // - ClassInfoPtr info; - if(id == Ice::Object::ice_staticId()) - { - // - // When the ID is that of Ice::Object, it indicates that the stream has not - // found a factory and is providing us an opportunity to preserve the object. - // - info = lookupClassInfo("::Ice::UnknownSlicedObject"); - } - else - { - info = lookupClassInfo(id); - } - - if(!info) - { - return 0; - } - - if(factory) - { - // - // Invoke the create method on the Python factory object. - // - PyObjectHandle obj = PyObject_CallMethod(factory, STRCAST("create"), STRCAST("s"), id.c_str()); - if(!obj.get()) - { - assert(PyErr_Occurred()); - throw AbortMarshaling(); - } - if(obj.get() == Py_None) - { - return 0; - } - return new ObjectReader(obj.get(), info); - } - - // - // If the requested type is an abstract class, then we give up. - // - if(info->isAbstract) - { - return 0; - } - - // - // Instantiate the object. - // - PyTypeObject* type = reinterpret_cast<PyTypeObject*>(info->pythonType.get()); - PyObjectHandle args = PyTuple_New(0); - PyObjectHandle obj = type->tp_new(type, args.get(), 0); - if(!obj.get()) - { - assert(PyErr_Occurred()); - throw AbortMarshaling(); - } - - return new ObjectReader(obj.get(), info); -} - -void -IcePy::ObjectFactory::destroy() -{ - FactoryMap factories; - - { - Lock sync(*this); - factories = _factoryMap; - _factoryMap.clear(); - } - - // - // We release the GIL before calling communicator->destroy(), so we must - // reacquire it before calling back into Python. - // - AdoptThread adoptThread; - - for(FactoryMap::iterator p = factories.begin(); p != factories.end(); ++p) - { - // - // Invoke the destroy method on each registered Python factory. - // - PyObjectHandle obj = PyObject_CallMethod(p->second, STRCAST("destroy"), 0); - PyErr_Clear(); // Ignore errors. - Py_DECREF(p->second); - } -} - -bool -IcePy::ObjectFactory::add(PyObject* factory, const string& id) -{ - Lock sync(*this); - - FactoryMap::iterator p = _factoryMap.find(id); - if(p != _factoryMap.end()) - { - Ice::AlreadyRegisteredException ex(__FILE__, __LINE__); - ex.kindOfObject = "object factory"; - ex.id = id; - setPythonException(ex); - return false; - } - - _factoryMap.insert(FactoryMap::value_type(id, factory)); - Py_INCREF(factory); - - return true; -} - -bool -IcePy::ObjectFactory::remove(const string& id) -{ - Lock sync(*this); - - FactoryMap::iterator p = _factoryMap.find(id); - if(p == _factoryMap.end()) - { - Ice::NotRegisteredException ex(__FILE__, __LINE__); - ex.kindOfObject = "object factory"; - ex.id = id; - setPythonException(ex); - return false; - } - - Py_DECREF(p->second); - _factoryMap.erase(p); - - return true; -} - -PyObject* -IcePy::ObjectFactory::find(const string& id) -{ - Lock sync(*this); - - FactoryMap::iterator p = _factoryMap.find(id); - if(p == _factoryMap.end()) - { - Py_INCREF(Py_None); - return Py_None; - } - - Py_INCREF(p->second); - return p->second; -} diff --git a/python/modules/IcePy/ObjectFactory.h b/python/modules/IcePy/ObjectFactory.h deleted file mode 100644 index d032108fe06..00000000000 --- a/python/modules/IcePy/ObjectFactory.h +++ /dev/null @@ -1,50 +0,0 @@ -// ********************************************************************** -// -// Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -// -// This copy of Ice is licensed to you under the terms described in the -// ICE_LICENSE file included in this distribution. -// -// ********************************************************************** - -#ifndef ICEPY_OBJECT_FACTORY_H -#define ICEPY_OBJECT_FACTORY_H - -#include <Config.h> -#include <Ice/ObjectF.h> -#include <Ice/ObjectFactory.h> -#include <IceUtil/Mutex.h> - -namespace IcePy -{ - -// -// Each communicator registers an instance of ObjectFactory as its -// default object factory. This instance delegates to registered Python -// objects, and instantiates concrete classes when no factory is present. -// -class ObjectFactory : public Ice::ObjectFactory, public IceUtil::Mutex -{ -public: - - ObjectFactory(); - ~ObjectFactory(); - - virtual Ice::ObjectPtr create(const std::string&); - - virtual void destroy(); - - bool add(PyObject*, const std::string&); - bool remove(const std::string&); - PyObject* find(const std::string&); - -private: - - typedef std::map<std::string, PyObject*> FactoryMap; - FactoryMap _factoryMap; -}; -typedef IceUtil::Handle<ObjectFactory> ObjectFactoryPtr; - -} - -#endif diff --git a/python/modules/IcePy/Operation.cpp b/python/modules/IcePy/Operation.cpp index 0eef27793d0..5db4ab9e41c 100644 --- a/python/modules/IcePy/Operation.cpp +++ b/python/modules/IcePy/Operation.cpp @@ -27,6 +27,7 @@ #include <Ice/AsyncResult.h> #include <Ice/Properties.h> #include <Ice/Proxy.h> +#include <IceUtil/Time.h> #include <Slice/PythonUtil.h> using namespace std; @@ -104,50 +105,44 @@ public: protected: - Ice::ObjectPrx _prx; -}; -typedef IceUtil::Handle<Invocation> InvocationPtr; - -// -// TypedInvocation uses the information in the given Operation to validate, marshal, and unmarshal -// parameters and exceptions. -// -class TypedInvocation : virtual public Invocation -{ -public: + // + // Helpers for typed invocations. + // - TypedInvocation(const Ice::ObjectPrx&, const OperationPtr&); + enum MappingType { SyncMapping, AsyncMapping, NewAsyncMapping }; -protected: + bool prepareRequest(const OperationPtr&, PyObject*, MappingType, Ice::OutputStream*, + pair<const Ice::Byte*, const Ice::Byte*>&); + PyObject* unmarshalResults(const OperationPtr&, const pair<const Ice::Byte*, const Ice::Byte*>&); + PyObject* unmarshalException(const OperationPtr&, const pair<const Ice::Byte*, const Ice::Byte*>&); + bool validateException(const OperationPtr&, PyObject*) const; + void checkTwowayOnly(const OperationPtr&, const Ice::ObjectPrx&) const; - OperationPtr _op; + Ice::ObjectPrx _prx; Ice::CommunicatorPtr _communicator; - - enum MappingType { SyncMapping, AsyncMapping, OldAsyncMapping }; - - bool prepareRequest(PyObject*, MappingType, Ice::OutputStreamPtr&, pair<const Ice::Byte*, const Ice::Byte*>&); - PyObject* unmarshalResults(const pair<const Ice::Byte*, const Ice::Byte*>&); - PyObject* unmarshalException(const pair<const Ice::Byte*, const Ice::Byte*>&); - bool validateException(PyObject*) const; - void checkTwowayOnly(const Ice::ObjectPrx&) const; }; +typedef IceUtil::Handle<Invocation> InvocationPtr; // // Synchronous typed invocation. // -class SyncTypedInvocation : virtual public TypedInvocation +class SyncTypedInvocation : public Invocation { public: SyncTypedInvocation(const Ice::ObjectPrx&, const OperationPtr&); virtual PyObject* invoke(PyObject*, PyObject* = 0); + +private: + + OperationPtr _op; }; // // Asynchronous typed invocation. // -class AsyncTypedInvocation : virtual public TypedInvocation +class AsyncTypedInvocation : public Invocation { public: @@ -163,10 +158,11 @@ public: void exception(const Ice::Exception&); void sent(bool); -protected: +private: void checkAsyncTwowayOnly(const Ice::ObjectPrx&) const; + OperationPtr _op; PyObject* _pyProxy; PyObject* _response; PyObject* _ex; @@ -175,14 +171,14 @@ protected: typedef IceUtil::Handle<AsyncTypedInvocation> AsyncTypedInvocationPtr; // -// Old-style asynchronous typed invocation. +// Asynchronous invocation with futures. // -class OldAsyncTypedInvocation : virtual public TypedInvocation +class NewAsyncInvocation : public Invocation { public: - OldAsyncTypedInvocation(const Ice::ObjectPrx&, const OperationPtr&); - ~OldAsyncTypedInvocation(); + NewAsyncInvocation(const Ice::ObjectPrx&, PyObject*, const string&); + ~NewAsyncInvocation(); virtual PyObject* invoke(PyObject*, PyObject* = 0); @@ -192,13 +188,47 @@ public: protected: - PyObject* _callback; + virtual Ice::AsyncResultPtr handleInvoke(PyObject*, PyObject*) = 0; + virtual void handleResponse(PyObject*, bool, const pair<const Ice::Byte*, const Ice::Byte*>&) = 0; + + PyObject* _pyProxy; + string _operation; + bool _twoway; + bool _sent; + bool _sentSynchronously; + bool _done; + PyObject* _future; + bool _ok; + vector<Ice::Byte> _results; + PyObject* _exception; +}; +typedef IceUtil::Handle<NewAsyncInvocation> NewAsyncInvocationPtr; + +// +// New-style asynchronous typed invocation. +// +class NewAsyncTypedInvocation : public NewAsyncInvocation +{ +public: + + NewAsyncTypedInvocation(const Ice::ObjectPrx&, PyObject*, const OperationPtr&); + +protected: + + virtual Ice::AsyncResultPtr handleInvoke(PyObject*, PyObject*); + virtual void handleResponse(PyObject*, bool, const pair<const Ice::Byte*, const Ice::Byte*>&); + +private: + + void checkAsyncTwowayOnly(const Ice::ObjectPrx&) const; + + OperationPtr _op; }; // // Synchronous blobject invocation. // -class SyncBlobjectInvocation : virtual public Invocation +class SyncBlobjectInvocation : public Invocation { public: @@ -210,7 +240,7 @@ public: // // Asynchronous blobject invocation. // -class AsyncBlobjectInvocation : virtual public Invocation +class AsyncBlobjectInvocation : public Invocation { public: @@ -235,82 +265,83 @@ protected: typedef IceUtil::Handle<AsyncBlobjectInvocation> AsyncBlobjectInvocationPtr; // -// Old-style asynchronous blobject invocation. +// New-style asynchronous blobject invocation. // -class OldAsyncBlobjectInvocation : virtual public Invocation +class NewAsyncBlobjectInvocation : public NewAsyncInvocation { public: - OldAsyncBlobjectInvocation(const Ice::ObjectPrx&); - ~OldAsyncBlobjectInvocation(); - - virtual PyObject* invoke(PyObject*, PyObject* = 0); - - void response(bool, const pair<const Ice::Byte*, const Ice::Byte*>&); - void exception(const Ice::Exception&); - void sent(bool); + NewAsyncBlobjectInvocation(const Ice::ObjectPrx&, PyObject*); protected: + virtual Ice::AsyncResultPtr handleInvoke(PyObject*, PyObject*); + virtual void handleResponse(PyObject*, bool, const pair<const Ice::Byte*, const Ice::Byte*>&); + string _op; - PyObject* _callback; }; // // The base class for server-side upcalls. // -class Upcall : virtual public IceUtil::Shared +class Upcall : public IceUtil::Shared { public: virtual void dispatch(PyObject*, const pair<const Ice::Byte*, const Ice::Byte*>&, const Ice::Current&) = 0; - virtual void response(PyObject*, const Ice::EncodingVersion&) = 0; - virtual void exception(PyException&, const Ice::EncodingVersion&) = 0; + virtual void response(PyObject*) = 0; + virtual void exception(PyException&) = 0; + virtual void exception(const Ice::Exception&) = 0; + +protected: + + void dispatchImpl(PyObject*, const string&, PyObject*, const Ice::Current&); }; typedef IceUtil::Handle<Upcall> UpcallPtr; // -// TypedInvocation uses the information in the given Operation to validate, marshal, and unmarshal +// TypedUpcall uses the information in the given Operation to validate, marshal, and unmarshal // parameters and exceptions. // -class TypedUpcall : virtual public Upcall +class TypedUpcall; +typedef IceUtil::Handle<TypedUpcall> TypedUpcallPtr; + +class TypedUpcall : public Upcall { public: TypedUpcall(const OperationPtr&, const Ice::AMD_Object_ice_invokePtr&, const Ice::CommunicatorPtr&); virtual void dispatch(PyObject*, const pair<const Ice::Byte*, const Ice::Byte*>&, const Ice::Current&); - virtual void response(PyObject*, const Ice::EncodingVersion&); - virtual void exception(PyException&, const Ice::EncodingVersion&); + virtual void response(PyObject*); + virtual void exception(PyException&); + virtual void exception(const Ice::Exception&); private: - bool validateException(PyObject*) const; - OperationPtr _op; Ice::AMD_Object_ice_invokePtr _callback; Ice::CommunicatorPtr _communicator; - bool _finished; + Ice::EncodingVersion _encoding; }; // // Upcall for blobject servants. // -class BlobjectUpcall : virtual public Upcall +class BlobjectUpcall : public Upcall { public: - BlobjectUpcall(bool, const Ice::AMD_Object_ice_invokePtr&); + BlobjectUpcall(const Ice::AMD_Object_ice_invokePtr&); virtual void dispatch(PyObject*, const pair<const Ice::Byte*, const Ice::Byte*>&, const Ice::Current&); - virtual void response(PyObject*, const Ice::EncodingVersion&); - virtual void exception(PyException&, const Ice::EncodingVersion&); + virtual void response(PyObject*); + virtual void exception(PyException&); + virtual void exception(const Ice::Exception&); private: - bool _amd; Ice::AMD_Object_ice_invokePtr _callback; - bool _finished; }; // @@ -341,15 +372,11 @@ class BlobjectServantWrapper : public ServantWrapper { public: - BlobjectServantWrapper(PyObject*, bool); + BlobjectServantWrapper(PyObject*); virtual void ice_invoke_async(const Ice::AMD_Object_ice_invokePtr&, const pair<const Ice::Byte*, const Ice::Byte*>&, const Ice::Current&); - -private: - - bool _amd; }; struct OperationObject @@ -358,11 +385,19 @@ struct OperationObject OperationPtr* op; }; -struct AMDCallbackObject +struct DoneCallbackObject +{ + PyObject_HEAD + UpcallPtr* upcall; +#if PY_VERSION_HEX >= 0x03050000 + PyObject* coroutine; +#endif +}; + +struct DispatchCallbackObject { PyObject_HEAD UpcallPtr* upcall; - Ice::EncodingVersion encoding; }; struct AsyncResultObject @@ -376,29 +411,19 @@ struct AsyncResultObject }; extern PyTypeObject OperationType; -extern PyTypeObject AMDCallbackType; -class UserExceptionReaderFactoryI : public Ice::UserExceptionReaderFactory +class UserExceptionFactory : public Ice::UserExceptionFactory { public: - UserExceptionReaderFactoryI(const Ice::CommunicatorPtr& communicator) : - _communicator(communicator) - { - } - - virtual void createAndThrow(const string& id) const + virtual void createAndThrow(const string& id) { ExceptionInfoPtr info = lookupExceptionInfo(id); if(info) { - throw ExceptionReader(_communicator, info); + throw ExceptionReader(info); } } - -private: - - const Ice::CommunicatorPtr _communicator; }; } @@ -435,8 +460,7 @@ handleException() void callException(PyObject* method, PyObject* ex) { - PyObjectHandle args = Py_BuildValue(STRCAST("(O)"), ex); - PyObjectHandle tmp = PyObject_Call(method, args.get(), 0); + PyObjectHandle tmp = callMethod(method, ex); if(PyErr_Occurred()) { handleException(); // Callback raised an exception. @@ -452,61 +476,20 @@ callException(PyObject* method, const Ice::Exception& ex) } void -callException(PyObject* callback, const string& op, const string& method, PyObject* ex) -{ - if(!PyObject_HasAttrString(callback, STRCAST(method.c_str()))) - { - ostringstream ostr; - ostr << "AMI callback object for operation `" << op << "' does not define " << method << "()"; - string str = ostr.str(); - PyErr_Warn(PyExc_RuntimeWarning, const_cast<char*>(str.c_str())); - } - else - { - PyObjectHandle m = PyObject_GetAttrString(callback, STRCAST(method.c_str())); - assert(m.get()); - callException(m.get(), ex); - } -} - -void -callException(PyObject* callback, const string& op, const string& method, const Ice::Exception& ex) -{ - PyObjectHandle exh = convertException(ex); - assert(exh.get()); - callException(callback, op, method, exh.get()); -} - -void callSent(PyObject* method, bool sentSynchronously, bool passArg) { - PyObjectHandle args; + PyObject* arg = 0; if(passArg) { - args = Py_BuildValue(STRCAST("(O)"), sentSynchronously ? getTrue() : getFalse()); + arg = sentSynchronously ? getTrue() : getFalse(); } - else - { - args = PyTuple_New(0); - } - PyObjectHandle tmp = PyObject_Call(method, args.get(), 0); + PyObjectHandle tmp = callMethod(method, arg); if(PyErr_Occurred()) { handleException(); // Callback raised an exception. } } -void -callSent(PyObject* callback, const string& method, bool sentSynchronously, bool passArg) -{ - if(PyObject_HasAttrString(callback, STRCAST(method.c_str()))) - { - PyObjectHandle m = PyObject_GetAttrString(callback, STRCAST(method.c_str())); - assert(m.get()); - callSent(m.get(), sentSynchronously, passArg); - } -} - } #ifdef WIN32 @@ -592,17 +575,15 @@ extern "C" static PyObject* operationInvokeAsync(OperationObject* self, PyObject* args) { - PyObject* pyProxy; + PyObject* proxy; PyObject* opArgs; - if(!PyArg_ParseTuple(args, STRCAST("O!O!"), &ProxyType, &pyProxy, &PyTuple_Type, &opArgs)) + if(!PyArg_ParseTuple(args, STRCAST("O!O!"), &ProxyType, &proxy, &PyTuple_Type, &opArgs)) { return 0; } - Ice::ObjectPrx prx = getProxy(pyProxy); - assert(self->op); - - InvocationPtr i = new OldAsyncTypedInvocation(prx, *self->op); + Ice::ObjectPrx p = getProxy(proxy); + InvocationPtr i = new NewAsyncTypedInvocation(p, proxy, *self->op); return i->invoke(opArgs); } @@ -665,26 +646,28 @@ operationDeprecate(OperationObject* self, PyObject* args) assert(self->op); (*self->op)->deprecate(msg); - Py_INCREF(Py_None); - return Py_None; + return incRef(Py_None); } // -// AMDCallback operations +// DoneCallback operations // #ifdef WIN32 extern "C" #endif -static AMDCallbackObject* -amdCallbackNew(PyTypeObject* type, PyObject* /*args*/, PyObject* /*kwds*/) +static DoneCallbackObject* +doneCallbackNew(PyTypeObject* type, PyObject* /*args*/, PyObject* /*kwds*/) { - AMDCallbackObject* self = reinterpret_cast<AMDCallbackObject*>(type->tp_alloc(type, 0)); + DoneCallbackObject* self = reinterpret_cast<DoneCallbackObject*>(type->tp_alloc(type, 0)); if(!self) { return 0; } self->upcall = 0; +#if PY_VERSION_HEX >= 0x03050000 + self->coroutine = 0; +#endif return self; } @@ -692,9 +675,12 @@ amdCallbackNew(PyTypeObject* type, PyObject* /*args*/, PyObject* /*kwds*/) extern "C" #endif static void -amdCallbackDealloc(AMDCallbackObject* self) +doneCallbackDealloc(DoneCallbackObject* self) { delete self->upcall; +#if PY_VERSION_HEX >= 0x03050000 + Py_XDECREF(self->coroutine); +#endif Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self)); } @@ -702,12 +688,32 @@ amdCallbackDealloc(AMDCallbackObject* self) extern "C" #endif static PyObject* -amdCallbackIceResponse(AMDCallbackObject* self, PyObject* args) +doneCallbackInvoke(DoneCallbackObject* self, PyObject* args) { + PyObject* future = 0; + if(!PyArg_ParseTuple(args, STRCAST("O"), &future)) + { + return 0; + } + try { assert(self->upcall); - (*self->upcall)->response(args, self->encoding); + + PyObjectHandle resultMethod = PyObject_GetAttrString(future, STRCAST("result")); + assert(resultMethod.get()); + PyObjectHandle empty = PyTuple_New(0); + PyObjectHandle result = PyObject_Call(resultMethod.get(), empty.get(), 0); + + if(PyErr_Occurred()) + { + PyException ex; + (*self->upcall)->exception(ex); + } + else + { + (*self->upcall)->response(result.get()); + } } catch(...) { @@ -717,33 +723,83 @@ amdCallbackIceResponse(AMDCallbackObject* self, PyObject* args) assert(false); } - Py_INCREF(Py_None); - return Py_None; + return incRef(Py_None); +} + +// +// DispatchCallbackObject operations +// + +#ifdef WIN32 +extern "C" +#endif +static DispatchCallbackObject* +dispatchCallbackNew(PyTypeObject* type, PyObject* /*args*/, PyObject* /*kwds*/) +{ + DispatchCallbackObject* self = reinterpret_cast<DispatchCallbackObject*>(type->tp_alloc(type, 0)); + if(!self) + { + return 0; + } + self->upcall = 0; + return self; +} + +#ifdef WIN32 +extern "C" +#endif +static void +dispatchCallbackDealloc(DispatchCallbackObject* self) +{ + delete self->upcall; + Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self)); } #ifdef WIN32 extern "C" #endif static PyObject* -amdCallbackIceException(AMDCallbackObject* self, PyObject* args) +dispatchCallbackResponse(DispatchCallbackObject* self, PyObject* args) { - PyObject* ex; - if(!PyArg_ParseTuple(args, STRCAST("O"), &ex)) + PyObject* result = 0; + if(!PyArg_ParseTuple(args, STRCAST("O"), &result)) { return 0; } - if(!PyObject_IsInstance(ex, PyExc_Exception)) + try + { + assert(self->upcall); + (*self->upcall)->response(result); + } + catch(...) + { + // + // No exceptions should propagate to Python. + // + assert(false); + } + + return incRef(Py_None); +} + +#ifdef WIN32 +extern "C" +#endif +static PyObject* +dispatchCallbackException(DispatchCallbackObject* self, PyObject* args) +{ + PyObject* ex = 0; + if(!PyArg_ParseTuple(args, STRCAST("O"), &ex)) { - PyErr_Format(PyExc_TypeError, "ice_exception argument is not an exception"); return 0; } try { assert(self->upcall); - PyException pye(ex); // No traceback information available. - (*self->upcall)->exception(pye, self->encoding); + PyException pyex(ex); + (*self->upcall)->exception(pyex); } catch(...) { @@ -753,8 +809,7 @@ amdCallbackIceException(AMDCallbackObject* self, PyObject* args) assert(false); } - Py_INCREF(Py_None); - return Py_None; + return incRef(Py_None); } // @@ -802,12 +857,10 @@ asyncResultGetCommunicator(AsyncResultObject* self) { if(self->communicator) { - Py_INCREF(self->communicator); - return self->communicator; + return incRef(self->communicator); } - Py_INCREF(Py_None); - return Py_None; + return incRef(Py_None); } #ifdef WIN32 @@ -825,8 +878,7 @@ asyncResultCancel(AsyncResultObject* self) assert(false); } - Py_INCREF(Py_None); - return Py_None; + return incRef(Py_None); } #ifdef WIN32 @@ -837,12 +889,10 @@ asyncResultGetConnection(AsyncResultObject* self) { if(self->connection) { - Py_INCREF(self->connection); - return self->connection; + return incRef(self->connection); } - Py_INCREF(Py_None); - return Py_None; + return incRef(Py_None); } #ifdef WIN32 @@ -853,12 +903,10 @@ asyncResultGetProxy(AsyncResultObject* self) { if(self->proxy) { - Py_INCREF(self->proxy); - return self->proxy; + return incRef(self->proxy); } - Py_INCREF(Py_None); - return Py_None; + return incRef(Py_None); } #ifdef WIN32 @@ -899,8 +947,7 @@ asyncResultWaitForCompleted(AsyncResultObject* self) assert(false); } - Py_INCREF(Py_None); - return Py_None; + return incRef(Py_None); } #ifdef WIN32 @@ -941,8 +988,7 @@ asyncResultWaitForSent(AsyncResultObject* self) assert(false); } - Py_INCREF(Py_None); - return Py_None; + return incRef(Py_None); } #ifdef WIN32 @@ -966,8 +1012,7 @@ asyncResultThrowLocalException(AsyncResultObject* self) assert(false); } - Py_INCREF(Py_None); - return Py_None; + return incRef(Py_None); } #ifdef WIN32 @@ -1028,6 +1073,72 @@ asyncResultGetOperation(AsyncResultObject* self) return createString(op); } +#ifdef WIN32 +extern "C" +#endif +static PyObject* +asyncResultCallLater(AsyncResultObject* self, PyObject* args) +{ + PyObject* callback; + if(!PyArg_ParseTuple(args, STRCAST("O"), &callback)) + { + return 0; + } + + if(!PyCallable_Check(callback)) + { + PyErr_Format(PyExc_ValueError, STRCAST("invalid argument passed to callLater")); + return 0; + } + + class CallbackI : public Ice::AsyncResult::Callback + { + public: + + CallbackI(PyObject* callback) : + _callback(incRef(callback)) + { + } + + ~CallbackI() + { + AdoptThread adoptThread; // Ensure the current thread is able to call into Python. + + Py_DECREF(_callback); + } + + virtual void run() + { + AdoptThread adoptThread; // Ensure the current thread is able to call into Python. + + PyObjectHandle args = PyTuple_New(0); + assert(args.get()); + PyObjectHandle tmp = PyObject_Call(_callback, args.get(), 0); + PyErr_Clear(); + } + + private: + + PyObject* _callback; + }; + + try + { + (*self->result)->scheduleCallback(new CallbackI(callback)); + } + catch(const Ice::CommunicatorDestroyedException& ex) + { + setPythonException(ex); + return 0; + } + catch(...) + { + assert(false); + } + + return incRef(Py_None); +} + // // ParamInfo implementation. // @@ -1036,8 +1147,7 @@ IcePy::ParamInfo::unmarshaled(PyObject* val, PyObject* target, void* closure) { assert(PyTuple_Check(target)); Py_ssize_t i = reinterpret_cast<Py_ssize_t>(closure); - PyTuple_SET_ITEM(target, i, val); - Py_INCREF(val); // PyTuple_SET_ITEM steals a reference. + PyTuple_SET_ITEM(target, i, incRef(val)); // PyTuple_SET_ITEM steals a reference. } // @@ -1066,14 +1176,7 @@ IcePy::Operation::Operation(const char* n, PyObject* m, PyObject* sm, int amdFla // amd // amd = amdFlag ? true : false; - if(amd) - { - dispatchName = name + "_async"; - } - else - { - dispatchName = fixIdent(name); - } + dispatchName = fixIdent(name); // Use the same dispatch name regardless of AMD. // // format @@ -1263,11 +1366,18 @@ static PyMethodDef OperationMethods[] = { 0, 0 } /* sentinel */ }; -static PyMethodDef AMDCallbackMethods[] = +static PyMethodDef DoneCallbackMethods[] = { - { STRCAST("ice_response"), reinterpret_cast<PyCFunction>(amdCallbackIceResponse), METH_VARARGS, + { STRCAST("invoke"), reinterpret_cast<PyCFunction>(doneCallbackInvoke), METH_VARARGS, PyDoc_STR(STRCAST("internal function")) }, - { STRCAST("ice_exception"), reinterpret_cast<PyCFunction>(amdCallbackIceException), METH_VARARGS, + { 0, 0 } /* sentinel */ +}; + +static PyMethodDef DispatchCallbackMethods[] = +{ + { STRCAST("response"), reinterpret_cast<PyCFunction>(dispatchCallbackResponse), METH_VARARGS, + PyDoc_STR(STRCAST("internal function")) }, + { STRCAST("exception"), reinterpret_cast<PyCFunction>(dispatchCallbackException), METH_VARARGS, PyDoc_STR(STRCAST("internal function")) }, { 0, 0 } /* sentinel */ }; @@ -1296,6 +1406,8 @@ static PyMethodDef AsyncResultMethods[] = PyDoc_STR(STRCAST("returns true if the request was sent synchronously")) }, { STRCAST("getOperation"), reinterpret_cast<PyCFunction>(asyncResultGetOperation), METH_NOARGS, PyDoc_STR(STRCAST("returns the name of the operation")) }, + { STRCAST("callLater"), reinterpret_cast<PyCFunction>(asyncResultCallLater), METH_VARARGS, + PyDoc_STR(STRCAST("internal function")) }, { 0, 0 } /* sentinel */ }; @@ -1349,16 +1461,63 @@ PyTypeObject OperationType = 0, /* tp_is_gc */ }; -PyTypeObject AMDCallbackType = +static PyTypeObject DoneCallbackType = +{ + /* The ob_type field must be initialized in the module init function + * to be portable to Windows without using C++. */ + PyVarObject_HEAD_INIT(0, 0) + STRCAST("IcePy.DoneCallback"), /* tp_name */ + sizeof(DoneCallbackObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + reinterpret_cast<destructor>(doneCallbackDealloc), /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + DoneCallbackMethods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + reinterpret_cast<newfunc>(doneCallbackNew), /* tp_new */ + 0, /* tp_free */ + 0, /* tp_is_gc */ +}; + +static PyTypeObject DispatchCallbackType = { /* The ob_type field must be initialized in the module init function * to be portable to Windows without using C++. */ PyVarObject_HEAD_INIT(0, 0) - STRCAST("IcePy.AMDCallback"), /* tp_name */ - sizeof(AMDCallbackObject), /* tp_basicsize */ + STRCAST("IcePy.Dispatch"), /* tp_name */ + sizeof(DispatchCallbackObject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ - reinterpret_cast<destructor>(amdCallbackDealloc), /* tp_dealloc */ + reinterpret_cast<destructor>(dispatchCallbackDealloc), /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ @@ -1381,7 +1540,7 @@ PyTypeObject AMDCallbackType = 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ - AMDCallbackMethods, /* tp_methods */ + DispatchCallbackMethods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ @@ -1391,7 +1550,7 @@ PyTypeObject AMDCallbackType = 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ - reinterpret_cast<newfunc>(amdCallbackNew), /* tp_new */ + reinterpret_cast<newfunc>(dispatchCallbackNew), /* tp_new */ 0, /* tp_free */ 0, /* tp_is_gc */ }; @@ -1458,12 +1617,22 @@ IcePy::initOperation(PyObject* module) return false; } - if(PyType_Ready(&AMDCallbackType) < 0) + if(PyType_Ready(&DoneCallbackType) < 0) { return false; } - PyTypeObject* cbType = &AMDCallbackType; // Necessary to prevent GCC's strict-alias warnings. - if(PyModule_AddObject(module, STRCAST("AMDCallback"), reinterpret_cast<PyObject*>(cbType)) < 0) + PyTypeObject* cbType = &DoneCallbackType; // Necessary to prevent GCC's strict-alias warnings. + if(PyModule_AddObject(module, STRCAST("DoneCallback"), reinterpret_cast<PyObject*>(cbType)) < 0) + { + return false; + } + + if(PyType_Ready(&DispatchCallbackType) < 0) + { + return false; + } + PyTypeObject* dispatchType = &DispatchCallbackType; // Necessary to prevent GCC's strict-alias warnings. + if(PyModule_AddObject(module, STRCAST("DispatchCallback"), reinterpret_cast<PyObject*>(dispatchType)) < 0) { return false; } @@ -1485,21 +1654,13 @@ IcePy::initOperation(PyObject* module) // Invocation // IcePy::Invocation::Invocation(const Ice::ObjectPrx& prx) : - _prx(prx) -{ -} - -// -// TypedInvocation -// -IcePy::TypedInvocation::TypedInvocation(const Ice::ObjectPrx& prx, const OperationPtr& op) : - Invocation(prx), _op(op), _communicator(prx->ice_getCommunicator()) + _prx(prx), _communicator(prx->ice_getCommunicator()) { } bool -IcePy::TypedInvocation::prepareRequest(PyObject* args, MappingType mapping, Ice::OutputStreamPtr& os, - pair<const Ice::Byte*, const Ice::Byte*>& params) +IcePy::Invocation::prepareRequest(const OperationPtr& op, PyObject* args, MappingType mapping, Ice::OutputStream* os, + pair<const Ice::Byte*, const Ice::Byte*>& params) { assert(PyTuple_Check(args)); params.first = params.second = static_cast<const Ice::Byte*>(0); @@ -1508,36 +1669,35 @@ IcePy::TypedInvocation::prepareRequest(PyObject* args, MappingType mapping, Ice: // Validate the number of arguments. // Py_ssize_t argc = PyTuple_GET_SIZE(args); - Py_ssize_t paramCount = static_cast<Py_ssize_t>(_op->inParams.size()); + Py_ssize_t paramCount = static_cast<Py_ssize_t>(op->inParams.size()); if(argc != paramCount) { string opName; - if(mapping == OldAsyncMapping) + if(mapping == NewAsyncMapping) { - opName = _op->name + "_async"; + opName = op->name + "Async"; } else if(mapping == AsyncMapping) { - opName = "begin_" + _op->name; + opName = "begin_" + op->name; } else { - opName = fixIdent(_op->name); + opName = fixIdent(op->name); } PyErr_Format(PyExc_RuntimeError, STRCAST("%s expects %d in parameters"), opName.c_str(), static_cast<int>(paramCount)); return false; } - if(!_op->inParams.empty()) + if(!op->inParams.empty()) { try { // // Marshal the in parameters. // - os = Ice::createOutputStream(_communicator); - os->startEncapsulation(_prx->ice_getEncodingVersion(), _op->format); + os->startEncapsulation(_prx->ice_getEncodingVersion(), op->format); ObjectMap objectMap; ParamInfoList::iterator p; @@ -1545,28 +1705,27 @@ IcePy::TypedInvocation::prepareRequest(PyObject* args, MappingType mapping, Ice: // // Validate the supplied arguments. // - for(p = _op->inParams.begin(); p != _op->inParams.end(); ++p) + for(p = op->inParams.begin(); p != op->inParams.end(); ++p) { ParamInfoPtr info = *p; PyObject* arg = PyTuple_GET_ITEM(args, info->pos); if((!info->optional || arg != Unset) && !info->type->validate(arg)) { string name; - if(mapping == OldAsyncMapping) + if(mapping == NewAsyncMapping) { - name = _op->name + "_async"; + name = op->name + "Async"; } else if(mapping == AsyncMapping) { - name = "begin_" + _op->name; + name = "begin_" + op->name; } else { - name = fixIdent(_op->name); + name = fixIdent(op->name); } PyErr_Format(PyExc_ValueError, STRCAST("invalid value for argument %d in operation `%s'"), - mapping == OldAsyncMapping ? info->pos + 2 : info->pos + 1, - const_cast<char*>(name.c_str())); + info->pos + 1, const_cast<char*>(name.c_str())); return false; } } @@ -1574,7 +1733,7 @@ IcePy::TypedInvocation::prepareRequest(PyObject* args, MappingType mapping, Ice: // // Marshal the required parameters. // - for(p = _op->inParams.begin(); p != _op->inParams.end(); ++p) + for(p = op->inParams.begin(); p != op->inParams.end(); ++p) { ParamInfoPtr info = *p; if(!info->optional) @@ -1587,7 +1746,7 @@ IcePy::TypedInvocation::prepareRequest(PyObject* args, MappingType mapping, Ice: // // Marshal the optional parameters. // - for(p = _op->optionalInParams.begin(); p != _op->optionalInParams.end(); ++p) + for(p = op->optionalInParams.begin(); p != op->optionalInParams.end(); ++p) { ParamInfoPtr info = *p; PyObject* arg = PyTuple_GET_ITEM(args, info->pos); @@ -1597,9 +1756,9 @@ IcePy::TypedInvocation::prepareRequest(PyObject* args, MappingType mapping, Ice: } } - if(_op->sendsClasses) + if(op->sendsClasses) { - os->writePendingObjects(); + os->writePendingValues(); } os->endEncapsulation(); @@ -1621,10 +1780,10 @@ IcePy::TypedInvocation::prepareRequest(PyObject* args, MappingType mapping, Ice: } PyObject* -IcePy::TypedInvocation::unmarshalResults(const pair<const Ice::Byte*, const Ice::Byte*>& bytes) +IcePy::Invocation::unmarshalResults(const OperationPtr& op, const pair<const Ice::Byte*, const Ice::Byte*>& bytes) { - Py_ssize_t numResults = static_cast<Py_ssize_t>(_op->outParams.size()); - if(_op->returnType) + Py_ssize_t numResults = static_cast<Py_ssize_t>(op->outParams.size()); + if(op->returnType) { numResults++; } @@ -1632,112 +1791,110 @@ IcePy::TypedInvocation::unmarshalResults(const pair<const Ice::Byte*, const Ice: PyObjectHandle results = PyTuple_New(numResults); if(results.get() && numResults > 0) { - Ice::InputStreamPtr is = Ice::wrapInputStream(_communicator, bytes); + Ice::InputStream is(_communicator, bytes); // - // Store a pointer to a local SlicedDataUtil object as the stream's closure. + // Store a pointer to a local StreamUtil object as the stream's closure. // This is necessary to support object unmarshaling (see ObjectReader). // - SlicedDataUtil util; - assert(!is->closure()); - is->closure(&util); + StreamUtil util; + assert(!is.getClosure()); + is.setClosure(&util); - is->startEncapsulation(); + is.startEncapsulation(); ParamInfoList::iterator p; // // Unmarshal the required out parameters. // - for(p = _op->outParams.begin(); p != _op->outParams.end(); ++p) + for(p = op->outParams.begin(); p != op->outParams.end(); ++p) { ParamInfoPtr info = *p; if(!info->optional) { void* closure = reinterpret_cast<void*>(static_cast<Py_ssize_t>(info->pos)); - info->type->unmarshal(is, info, results.get(), closure, false, &info->metaData); + info->type->unmarshal(&is, info, results.get(), closure, false, &info->metaData); } } // // Unmarshal the required return value, if any. // - if(_op->returnType && !_op->returnType->optional) + if(op->returnType && !op->returnType->optional) { - assert(_op->returnType->pos == 0); - void* closure = reinterpret_cast<void*>(static_cast<Py_ssize_t>(_op->returnType->pos)); - _op->returnType->type->unmarshal(is, _op->returnType, results.get(), closure, false, &_op->metaData); + assert(op->returnType->pos == 0); + void* closure = reinterpret_cast<void*>(static_cast<Py_ssize_t>(op->returnType->pos)); + op->returnType->type->unmarshal(&is, op->returnType, results.get(), closure, false, &op->metaData); } // // Unmarshal the optional results. This includes an optional return value. // - for(p = _op->optionalOutParams.begin(); p != _op->optionalOutParams.end(); ++p) + for(p = op->optionalOutParams.begin(); p != op->optionalOutParams.end(); ++p) { ParamInfoPtr info = *p; - if(is->readOptional(info->tag, info->type->optionalFormat())) + if(is.readOptional(info->tag, info->type->optionalFormat())) { void* closure = reinterpret_cast<void*>(static_cast<Py_ssize_t>(info->pos)); - info->type->unmarshal(is, info, results.get(), closure, true, &info->metaData); + info->type->unmarshal(&is, info, results.get(), closure, true, &info->metaData); } else { - PyTuple_SET_ITEM(results.get(), info->pos, Unset); - Py_INCREF(Unset); // PyTuple_SET_ITEM steals a reference. + PyTuple_SET_ITEM(results.get(), info->pos, incRef(Unset)); // PyTuple_SET_ITEM steals a reference. } } - if(_op->returnsClasses) + if(op->returnsClasses) { - is->readPendingObjects(); + is.readPendingValues(); } - is->endEncapsulation(); + is.endEncapsulation(); - util.update(); + util.updateSlicedData(); } return results.release(); } PyObject* -IcePy::TypedInvocation::unmarshalException(const pair<const Ice::Byte*, const Ice::Byte*>& bytes) +IcePy::Invocation::unmarshalException(const OperationPtr& op, const pair<const Ice::Byte*, const Ice::Byte*>& bytes) { - Ice::InputStreamPtr is = Ice::wrapInputStream(_communicator, bytes); + Ice::InputStream is(_communicator, bytes); // - // Store a pointer to a local SlicedDataUtil object as the stream's closure. + // Store a pointer to a local StreamUtil object as the stream's closure. // This is necessary to support object unmarshaling (see ObjectReader). // - SlicedDataUtil util; - assert(!is->closure()); - is->closure(&util); + StreamUtil util; + assert(!is.getClosure()); + is.setClosure(&util); - is->startEncapsulation(); + is.startEncapsulation(); try { - Ice::UserExceptionReaderFactoryPtr factory = new UserExceptionReaderFactoryI(_communicator); - is->throwException(factory); + Ice::UserExceptionFactoryPtr factory = new UserExceptionFactory; + is.throwException(factory); } catch(const ExceptionReader& r) { - is->endEncapsulation(); + is.endEncapsulation(); PyObject* ex = r.getException(); - if(validateException(ex)) + if(validateException(op, ex)) { - util.update(); + util.updateSlicedData(); Ice::SlicedDataPtr slicedData = r.getSlicedData(); if(slicedData) { - SlicedDataUtil::setMember(ex, slicedData); + StreamUtil::setSlicedDataMember(ex, slicedData); } - Py_INCREF(ex); - return ex; + return incRef(ex); } else { @@ -1767,9 +1924,9 @@ IcePy::TypedInvocation::unmarshalException(const pair<const Ice::Byte*, const Ic } bool -IcePy::TypedInvocation::validateException(PyObject* ex) const +IcePy::Invocation::validateException(const OperationPtr& op, PyObject* ex) const { - for(ExceptionInfoList::const_iterator p = _op->exceptions.begin(); p != _op->exceptions.end(); ++p) + for(ExceptionInfoList::const_iterator p = op->exceptions.begin(); p != op->exceptions.end(); ++p) { if(PyObject_IsInstance(ex, (*p)->pythonType.get())) { @@ -1781,12 +1938,12 @@ IcePy::TypedInvocation::validateException(PyObject* ex) const } void -IcePy::TypedInvocation::checkTwowayOnly(const Ice::ObjectPrx& proxy) const +IcePy::Invocation::checkTwowayOnly(const OperationPtr& op, const Ice::ObjectPrx& proxy) const { - if((_op->returnType != 0 || !_op->outParams.empty() || !_op->exceptions.empty()) && !proxy->ice_isTwoway()) + if((op->returnType != 0 || !op->outParams.empty() || !op->exceptions.empty()) && !proxy->ice_isTwoway()) { Ice::TwowayOnlyException ex(__FILE__, __LINE__); - ex.operation = _op->name; + ex.operation = op->name; throw ex; } } @@ -1795,7 +1952,7 @@ IcePy::TypedInvocation::checkTwowayOnly(const Ice::ObjectPrx& proxy) const // SyncTypedInvocation // IcePy::SyncTypedInvocation::SyncTypedInvocation(const Ice::ObjectPrx& prx, const OperationPtr& op) : - Invocation(prx), TypedInvocation(prx, op) + Invocation(prx), _op(op) { } @@ -1811,16 +1968,16 @@ IcePy::SyncTypedInvocation::invoke(PyObject* args, PyObject* /* kwds */) // // Marshal the input parameters to a byte sequence. // - Ice::OutputStreamPtr os; + Ice::OutputStream os(_communicator); pair<const Ice::Byte*, const Ice::Byte*> params; - if(!prepareRequest(pyparams, SyncMapping, os, params)) + if(!prepareRequest(_op, pyparams, SyncMapping, &os, params)) { return 0; } try { - checkTwowayOnly(_prx); + checkTwowayOnly(_op, _prx); // // Invoke the operation. @@ -1870,7 +2027,7 @@ IcePy::SyncTypedInvocation::invoke(PyObject* args, PyObject* /* kwds */) rb.first = &result[0]; rb.second = &result[0] + result.size(); } - PyObjectHandle ex = unmarshalException(rb); + PyObjectHandle ex = unmarshalException(_op, rb); // // Set the Python exception. @@ -1891,7 +2048,7 @@ IcePy::SyncTypedInvocation::invoke(PyObject* args, PyObject* /* kwds */) rb.first = &result[0]; rb.second = &result[0] + result.size(); } - PyObjectHandle results = unmarshalResults(rb); + PyObjectHandle results = unmarshalResults(_op, rb); if(!results.get()) { return 0; @@ -1910,8 +2067,7 @@ IcePy::SyncTypedInvocation::invoke(PyObject* args, PyObject* /* kwds */) } else { - Py_INCREF(ret); - return ret; + return incRef(ret); } } } @@ -1928,8 +2084,7 @@ IcePy::SyncTypedInvocation::invoke(PyObject* args, PyObject* /* kwds */) return 0; } - Py_INCREF(Py_None); - return Py_None; + return incRef(Py_None); } // @@ -1937,7 +2092,7 @@ IcePy::SyncTypedInvocation::invoke(PyObject* args, PyObject* /* kwds */) // IcePy::AsyncTypedInvocation::AsyncTypedInvocation(const Ice::ObjectPrx& prx, PyObject* pyProxy, const OperationPtr& op) : - Invocation(prx), TypedInvocation(prx, op), _pyProxy(pyProxy), _response(0), _ex(0), _sent(0) + Invocation(prx), _op(op), _pyProxy(pyProxy), _response(0), _ex(0), _sent(0) { Py_INCREF(_pyProxy); } @@ -1965,8 +2120,7 @@ IcePy::AsyncTypedInvocation::invoke(PyObject* args, PyObject* /* kwds */) callable = PyTuple_GET_ITEM(args, 1); if(PyCallable_Check(callable)) { - _response = callable; - Py_INCREF(_response); + _response = incRef(callable); } else if(callable != Py_None) { @@ -1977,8 +2131,7 @@ IcePy::AsyncTypedInvocation::invoke(PyObject* args, PyObject* /* kwds */) callable = PyTuple_GET_ITEM(args, 2); if(PyCallable_Check(callable)) { - _ex = callable; - Py_INCREF(_ex); + _ex = incRef(callable); } else if(callable != Py_None) { @@ -1989,8 +2142,7 @@ IcePy::AsyncTypedInvocation::invoke(PyObject* args, PyObject* /* kwds */) callable = PyTuple_GET_ITEM(args, 3); if(PyCallable_Check(callable)) { - _sent = callable; - Py_INCREF(_sent); + _sent = incRef(callable); } else if(callable != Py_None) { @@ -2015,9 +2167,9 @@ IcePy::AsyncTypedInvocation::invoke(PyObject* args, PyObject* /* kwds */) // // Marshal the input parameters to a byte sequence. // - Ice::OutputStreamPtr os; + Ice::OutputStream os(_communicator); pair<const Ice::Byte*, const Ice::Byte*> params; - if(!prepareRequest(pyparams, AsyncMapping, os, params)) + if(!prepareRequest(_op, pyparams, AsyncMapping, &os, params)) { return 0; } @@ -2101,8 +2253,7 @@ IcePy::AsyncTypedInvocation::invoke(PyObject* args, PyObject* /* kwds */) } obj->result = new Ice::AsyncResultPtr(result); obj->invocation = new InvocationPtr(this); - obj->proxy = _pyProxy; - Py_INCREF(obj->proxy); + obj->proxy = incRef(_pyProxy); obj->communicator = getCommunicatorWrapper(_communicator); return reinterpret_cast<PyObject*>(obj); } @@ -2123,7 +2274,7 @@ IcePy::AsyncTypedInvocation::end(const Ice::ObjectPrx& proxy, const OperationPtr { AllowThreads allowThreads; // Release Python's global interpreter lock during blocking operations. - ok = proxy->___end_ice_invoke(results, r); + ok = proxy->_iceI_end_ice_invoke(results, r); } if(ok) @@ -2131,7 +2282,7 @@ IcePy::AsyncTypedInvocation::end(const Ice::ObjectPrx& proxy, const OperationPtr // // Unmarshal the results. // - PyObjectHandle args = unmarshalResults(results); + PyObjectHandle args = unmarshalResults(_op, results); if(args.get()) { // @@ -2141,14 +2292,12 @@ IcePy::AsyncTypedInvocation::end(const Ice::ObjectPrx& proxy, const OperationPtr assert(PyTuple_Check(args.get())); if(PyTuple_GET_SIZE(args.get()) == 0) { - Py_INCREF(Py_None); - return Py_None; + return incRef(Py_None); } else if(PyTuple_GET_SIZE(args.get()) == 1) { PyObject* res = PyTuple_GET_ITEM(args.get(), 0); - Py_INCREF(res); - return res; + return incRef(res); } else { @@ -2158,7 +2307,7 @@ IcePy::AsyncTypedInvocation::end(const Ice::ObjectPrx& proxy, const OperationPtr } else { - PyObjectHandle ex = unmarshalException(results); + PyObjectHandle ex = unmarshalException(_op, results); setPythonException(ex.get()); } } @@ -2202,7 +2351,7 @@ IcePy::AsyncTypedInvocation::response(bool ok, const pair<const Ice::Byte*, cons PyObjectHandle args; try { - args = unmarshalResults(results); + args = unmarshalResults(_op, results); if(!args.get()) { assert(PyErr_Occurred()); @@ -2227,7 +2376,7 @@ IcePy::AsyncTypedInvocation::response(bool ok, const pair<const Ice::Byte*, cons else { assert(_ex); - PyObjectHandle ex = unmarshalException(results); + PyObjectHandle ex = unmarshalException(_op, results); callException(_ex, ex.get()); } } @@ -2272,114 +2421,344 @@ IcePy::AsyncTypedInvocation::checkAsyncTwowayOnly(const Ice::ObjectPrx& proxy) c } // -// OldAsyncTypedInvocation +// NewAsyncInvocation // -IcePy::OldAsyncTypedInvocation::OldAsyncTypedInvocation(const Ice::ObjectPrx& prx, const OperationPtr& op) - : Invocation(prx), TypedInvocation(prx, op), _callback(0) +IcePy::NewAsyncInvocation::NewAsyncInvocation(const Ice::ObjectPrx& prx, PyObject* pyProxy, const string& operation) + : Invocation(prx), _pyProxy(pyProxy), _operation(operation), _twoway(prx->ice_isTwoway()), _sent(false), + _sentSynchronously(false), _done(false), _future(0), _ok(false), _exception(0) { + Py_INCREF(_pyProxy); } -IcePy::OldAsyncTypedInvocation::~OldAsyncTypedInvocation() +IcePy::NewAsyncInvocation::~NewAsyncInvocation() { AdoptThread adoptThread; // Ensure the current thread is able to call into Python. - Py_XDECREF(_callback); + Py_DECREF(_pyProxy); + Py_XDECREF(_future); + Py_XDECREF(_exception); } PyObject* -IcePy::OldAsyncTypedInvocation::invoke(PyObject* args, PyObject* /* kwds */) +IcePy::NewAsyncInvocation::invoke(PyObject* args, PyObject* kwds) { - assert(PyTuple_Check(args)); - assert(PyTuple_GET_SIZE(args) == 3); // Format is (callback, (params...), context|None) - _callback = PyTuple_GET_ITEM(args, 0); - Py_INCREF(_callback); - PyObject* pyparams = PyTuple_GET_ITEM(args, 1); - assert(PyTuple_Check(pyparams)); - PyObject* pyctx = PyTuple_GET_ITEM(args, 2); - // - // Marshal the input parameters to a byte sequence. + // Called from Python code, so the GIL is already acquired. // - Ice::OutputStreamPtr os; - pair<const Ice::Byte*, const Ice::Byte*> params; - if(!prepareRequest(pyparams, OldAsyncMapping, os, params)) + + Ice::AsyncResultPtr result; + + try + { + result = handleInvoke(args, kwds); + } + catch(const Ice::CommunicatorDestroyedException& ex) + { + // + // CommunicatorDestroyedException can propagate directly. + // + setPythonException(ex); + return 0; + } + catch(const IceUtil::IllegalArgumentException& ex) + { + // + // IllegalArgumentException can propagate directly. + // (Raised by checkAsyncTwowayOnly) + // + PyErr_Format(PyExc_RuntimeError, "%s", STRCAST(ex.reason().c_str())); + return 0; + } + catch(const Ice::Exception&) + { + // + // No other exceptions should be raised by begin_ice_invoke. + // + assert(false); + } + + if(PyErr_Occurred()) { return 0; } - bool sentSynchronously = false; - try + assert(result); + + PyObjectHandle communicatorObj = getCommunicatorWrapper(_communicator); + PyObjectHandle asyncResultObj; + + // + // Pass the AsyncResult object to the future. Note that this creates a circular reference. + // Don't do this for batch invocations because there is no opportunity to break the circular + // reference. + // + if(!_prx->ice_isBatchOneway() && !_prx->ice_isBatchDatagram()) { - checkTwowayOnly(_prx); + asyncResultObj = createAsyncResult(result, _pyProxy, 0, communicatorObj.get()); + if(!asyncResultObj.get()) + { + return 0; + } + } - Ice::Callback_Object_ice_invokePtr cb = - Ice::newCallback_Object_ice_invoke(this, &OldAsyncTypedInvocation::response, - &OldAsyncTypedInvocation::exception, &OldAsyncTypedInvocation::sent); + // + // NOTE: Any time we call into interpreted Python code there's a chance that another thread will be + // allowed to run! + // - Ice::AsyncResultPtr result; + PyObjectHandle future = createFuture(_operation, asyncResultObj.get()); // Calls into Python code. + if(!future.get()) + { + return 0; + } - // - // Invoke the operation asynchronously. - // - if(pyctx != Py_None) + // + // Check if any callbacks have been invoked already. + // + + if(_sent) + { + PyObjectHandle tmp = callMethod(future.get(), "set_sent", _sentSynchronously ? getTrue() : getFalse()); + if(PyErr_Occurred()) { - Ice::Context ctx; + return 0; + } - if(!PyDict_Check(pyctx)) + if(!_twoway) + { + // + // For a oneway/datagram invocation, we consider it complete when sent. + // + tmp = callMethod(future.get(), "set_result", Py_None); + if(PyErr_Occurred()) { - PyErr_Format(PyExc_ValueError, STRCAST("context argument must be None or a dictionary")); return 0; } + } + } - if(!dictionaryToContext(pyctx, ctx)) + if(_done) + { + if(_exception) + { + PyObjectHandle tmp = callMethod(future.get(), "set_exception", _exception); + if(PyErr_Occurred()) { return 0; } - - AllowThreads allowThreads; // Release Python's global interpreter lock during remote invocations. - result = _prx->begin_ice_invoke(_op->name, _op->sendMode, params, ctx, cb); } else { - AllowThreads allowThreads; // Release Python's global interpreter lock during remote invocations. - result = _prx->begin_ice_invoke(_op->name, _op->sendMode, params, cb); + // + // Delegate to the subclass. + // + pair<const Ice::Byte*, const Ice::Byte*> p(&_results[0], &_results[0] + _results.size()); + handleResponse(future.get(), _ok, p); + if(PyErr_Occurred()) + { + return 0; + } } - - sentSynchronously = result->sentSynchronously(); } - catch(const Ice::CommunicatorDestroyedException& ex) + + _future = future.release(); + return incRef(_future); +} + +void +IcePy::NewAsyncInvocation::response(bool ok, const pair<const Ice::Byte*, const Ice::Byte*>& results) +{ + AdoptThread adoptThread; // Ensure the current thread is able to call into Python. + + if(!_future) { // - // CommunicatorDestroyedException can propagate directly. + // The future hasn't been created yet, which means invoke() is still running. Save the results for later. // - setPythonException(ex); - return 0; + _ok = ok; + vector<Ice::Byte> v(results.first, results.second); + _results.swap(v); + _done = true; + return; + } + + PyObjectHandle future = _future; // Steals a reference. + + if(_sent) + { + _future = 0; // Break cyclic dependency. } - catch(const Ice::TwowayOnlyException& ex) + else { + assert(!_done); + // - // Raised by checkTwowayOnly. + // The sent callback will release our reference. // - callException(_callback, _op->name, "ice_exception", ex); + Py_INCREF(_future); } - catch(const Ice::Exception&) + + _done = true; + + // + // Delegate to the subclass. + // + handleResponse(future.get(), ok, results); + if(PyErr_Occurred()) + { + handleException(); + } +} + +void +IcePy::NewAsyncInvocation::exception(const Ice::Exception& ex) +{ + AdoptThread adoptThread; // Ensure the current thread is able to call into Python. + + if(!_future) { // - // No other exceptions should be raised by begin_ice_invoke. + // The future hasn't been created yet, which means invoke() is still running. Save the exception for later. // - assert(false); + _exception = convertException(ex); + _done = true; + return; } - PyRETURN_BOOL(sentSynchronously); + PyObjectHandle future = _future; // Steals a reference. + _future = 0; // Break cyclic dependency. + _done = true; + + PyObjectHandle exh = convertException(ex); + assert(exh.get()); + PyObjectHandle tmp = callMethod(future.get(), "set_exception", exh.get()); + if(PyErr_Occurred()) + { + handleException(); + } } void -IcePy::OldAsyncTypedInvocation::response(bool ok, const pair<const Ice::Byte*, const Ice::Byte*>& results) +IcePy::NewAsyncInvocation::sent(bool sentSynchronously) { AdoptThread adoptThread; // Ensure the current thread is able to call into Python. - assert(_callback); + if(!_future) + { + // + // The future hasn't been created yet, which means invoke() is still running. + // + _sent = true; + _sentSynchronously = sentSynchronously; + return; + } + + PyObjectHandle future = _future; + + if(_done || !_twoway) + { + _future = 0; // Break cyclic dependency. + } + else + { + _sent = true; + + // + // The reference to _future will be released in response() or exception(). + // + Py_INCREF(_future); + } + + PyObjectHandle tmp = callMethod(future.get(), "set_sent", sentSynchronously ? getTrue() : getFalse()); + if(PyErr_Occurred()) + { + handleException(); + } + + if(!_twoway) + { + // + // For a oneway/datagram invocation, we consider it complete when sent. + // + tmp = callMethod(future.get(), "set_result", Py_None); + if(PyErr_Occurred()) + { + handleException(); + } + } +} + +// +// NewAsyncTypedInvocation +// +IcePy::NewAsyncTypedInvocation::NewAsyncTypedInvocation(const Ice::ObjectPrx& prx, PyObject* pyProxy, + const OperationPtr& op) + : NewAsyncInvocation(prx, pyProxy, op->name), _op(op) +{ +} + +Ice::AsyncResultPtr +IcePy::NewAsyncTypedInvocation::handleInvoke(PyObject* args, PyObject* /* kwds */) +{ + // + // Called from Python code, so the GIL is already acquired. + // + + assert(PyTuple_Check(args)); + assert(PyTuple_GET_SIZE(args) == 2); // Format is ((params...), context|None) + PyObject* pyparams = PyTuple_GET_ITEM(args, 0); + assert(PyTuple_Check(pyparams)); + PyObject* pyctx = PyTuple_GET_ITEM(args, 1); + + // + // Marshal the input parameters to a byte sequence. + // + Ice::OutputStream os(_communicator); + pair<const Ice::Byte*, const Ice::Byte*> params; + if(!prepareRequest(_op, pyparams, NewAsyncMapping, &os, params)) + { + return 0; + } + + checkAsyncTwowayOnly(_prx); + + NewAsyncInvocationPtr self = this; + Ice::Callback_Object_ice_invokePtr cb = + Ice::newCallback_Object_ice_invoke(self, &NewAsyncInvocation::response, &NewAsyncInvocation::exception, + &NewAsyncInvocation::sent); + // + // Invoke the operation asynchronously. + // + if(pyctx != Py_None) + { + Ice::Context ctx; + + if(!PyDict_Check(pyctx)) + { + PyErr_Format(PyExc_ValueError, STRCAST("context argument must be None or a dictionary")); + return 0; + } + + if(!dictionaryToContext(pyctx, ctx)) + { + return 0; + } + + AllowThreads allowThreads; // Release Python's global interpreter lock during remote invocations. + return _prx->begin_ice_invoke(_op->name, _op->sendMode, params, ctx, cb); + } + else + { + AllowThreads allowThreads; // Release Python's global interpreter lock during remote invocations. + return _prx->begin_ice_invoke(_op->name, _op->sendMode, params, cb); + } +} + +void +IcePy::NewAsyncTypedInvocation::handleResponse(PyObject* future, bool ok, + const pair<const Ice::Byte*, const Ice::Byte*>& results) +{ try { if(ok) @@ -2388,69 +2767,70 @@ IcePy::OldAsyncTypedInvocation::response(bool ok, const pair<const Ice::Byte*, c // Unmarshal the results. // PyObjectHandle args; + try { - args = unmarshalResults(results); + args = unmarshalResults(_op, results); if(!args.get()) { assert(PyErr_Occurred()); - PyErr_Print(); return; } } catch(const Ice::Exception& ex) { - callException(_callback, _op->name, "ice_exception", ex); + PyObjectHandle exh = convertException(ex); + assert(exh.get()); + PyObjectHandle tmp = callMethod(future, "set_exception", exh.get()); + PyErr_Clear(); return; } - const string methodName = "ice_response"; - if(!PyObject_HasAttrString(_callback, STRCAST(methodName.c_str()))) + // + // The future's result is always one value: + // + // - If the operation has no out parameters, the result is None + // - If the operation returns one value, the result is the value + // - If the operation returns multiple values, the result is a tuple containing the values + // + PyObjectHandle r; + if(PyTuple_GET_SIZE(args.get()) == 0) { - ostringstream ostr; - ostr << "AMI callback object for operation `" << _op->name << "' does not define " << methodName - << "()"; - string str = ostr.str(); - PyErr_Warn(PyExc_RuntimeWarning, const_cast<char*>(str.c_str())); + r = incRef(Py_None); + } + else if(PyTuple_GET_SIZE(args.get()) == 1) + { + r = incRef(PyTuple_GET_ITEM(args.get(), 0)); // PyTuple_GET_ITEM steals a reference. } else { - PyObjectHandle method = PyObject_GetAttrString(_callback, STRCAST(methodName.c_str())); - assert(method.get()); - PyObjectHandle tmp = PyObject_Call(method.get(), args.get(), 0); - if(PyErr_Occurred()) - { - handleException(); // Callback raised an exception. - } + r = args; } + + PyObjectHandle tmp = callMethod(future, "set_result", r.get()); + PyErr_Clear(); } else { - PyObjectHandle ex = unmarshalException(results); - callException(_callback, _op->name, "ice_exception", ex.get()); + PyObjectHandle ex = unmarshalException(_op, results); + PyObjectHandle tmp = callMethod(future, "set_exception", ex.get()); + PyErr_Clear(); } } catch(const AbortMarshaling&) { assert(PyErr_Occurred()); - PyErr_Print(); } } void -IcePy::OldAsyncTypedInvocation::exception(const Ice::Exception& ex) -{ - AdoptThread adoptThread; // Ensure the current thread is able to call into Python. - - callException(_callback, _op->name, "ice_exception", ex); -} - -void -IcePy::OldAsyncTypedInvocation::sent(bool) +IcePy::NewAsyncTypedInvocation::checkAsyncTwowayOnly(const Ice::ObjectPrx& proxy) const { - AdoptThread adoptThread; // Ensure the current thread is able to call into Python. - - callSent(_callback, "ice_sent", false, false); + if((_op->returnType != 0 || !_op->outParams.empty() || !_op->exceptions.empty()) && !proxy->ice_isTwoway()) + { + throw IceUtil::IllegalArgumentException(__FILE__, __LINE__, + "`" + _op->name + "' can only be called with a twoway proxy"); + } } // @@ -2580,8 +2960,7 @@ IcePy::SyncBlobjectInvocation::invoke(PyObject* args, PyObject* /* kwds */) } #endif - PyTuple_SET_ITEM(result.get(), 1, op.get()); - op.release(); // PyTuple_SET_ITEM steals a reference. + PyTuple_SET_ITEM(result.get(), 1, op.release()); // PyTuple_SET_ITEM steals a reference. return result.release(); } @@ -2622,7 +3001,7 @@ IcePy::AsyncBlobjectInvocation::invoke(PyObject* args, PyObject* kwds) const_cast<char*>("_response"), const_cast<char*>("_ex"), const_cast<char*>("_sent"), - const_cast<char*>("_ctx"), + const_cast<char*>("context"), 0 }; char* operation; @@ -2655,8 +3034,7 @@ IcePy::AsyncBlobjectInvocation::invoke(PyObject* args, PyObject* kwds) if(PyCallable_Check(response)) { - _response = response; - Py_INCREF(_response); + _response = incRef(response); } else if(response != Py_None) { @@ -2666,8 +3044,7 @@ IcePy::AsyncBlobjectInvocation::invoke(PyObject* args, PyObject* kwds) if(PyCallable_Check(ex)) { - _ex = ex; - Py_INCREF(_ex); + _ex = incRef(ex); } else if(ex != Py_None) { @@ -2677,8 +3054,7 @@ IcePy::AsyncBlobjectInvocation::invoke(PyObject* args, PyObject* kwds) if(PyCallable_Check(sent)) { - _sent = sent; - Py_INCREF(_sent); + _sent = incRef(sent); } else if(sent != Py_None) { @@ -2790,8 +3166,7 @@ IcePy::AsyncBlobjectInvocation::invoke(PyObject* args, PyObject* kwds) } obj->result = new Ice::AsyncResultPtr(result); obj->invocation = new InvocationPtr(this); - obj->proxy = _pyProxy; - Py_INCREF(obj->proxy); + obj->proxy = incRef(_pyProxy); obj->communicator = getCommunicatorWrapper(_prx->ice_getCommunicator()); return reinterpret_cast<PyObject*>(obj); } @@ -2806,7 +3181,7 @@ IcePy::AsyncBlobjectInvocation::end(const Ice::ObjectPrx& proxy, const Ice::Asyn { AllowThreads allowThreads; // Release Python's global interpreter lock during blocking operations. - ok = proxy->___end_ice_invoke(results, r); + ok = proxy->_iceI_end_ice_invoke(results, r); } // @@ -2855,8 +3230,7 @@ IcePy::AsyncBlobjectInvocation::end(const Ice::ObjectPrx& proxy, const Ice::Asyn memcpy(buf, results.first, sz); #endif - PyTuple_SET_ITEM(args.get(), 1, op.get()); - op.release(); // PyTuple_SET_ITEM steals a reference. + PyTuple_SET_ITEM(args.get(), 1, op.release()); // PyTuple_SET_ITEM steals a reference. return args.release(); } @@ -2938,8 +3312,7 @@ IcePy::AsyncBlobjectInvocation::response(bool ok, const pair<const Ice::Byte*, c memcpy(buf, results.first, sz); #endif - PyTuple_SET_ITEM(args.get(), 1, op.get()); - op.release(); // PyTuple_SET_ITEM steals a reference. + PyTuple_SET_ITEM(args.get(), 1, op.release()); // PyTuple_SET_ITEM steals a reference. PyObjectHandle tmp = PyObject_Call(_response, args.get(), 0); if(PyErr_Occurred()) @@ -2968,22 +3341,15 @@ IcePy::AsyncBlobjectInvocation::sent(bool sentSynchronously) } // -// OldAsyncBlobjectInvocation +// NewAsyncBlobjectInvocation // -IcePy::OldAsyncBlobjectInvocation::OldAsyncBlobjectInvocation(const Ice::ObjectPrx& prx) : - Invocation(prx), _callback(0) +IcePy::NewAsyncBlobjectInvocation::NewAsyncBlobjectInvocation(const Ice::ObjectPrx& prx, PyObject* pyProxy) : + NewAsyncInvocation(prx, pyProxy, "ice_invoke") { } -IcePy::OldAsyncBlobjectInvocation::~OldAsyncBlobjectInvocation() -{ - AdoptThread adoptThread; // Ensure the current thread is able to call into Python. - - Py_XDECREF(_callback); -} - -PyObject* -IcePy::OldAsyncBlobjectInvocation::invoke(PyObject* args, PyObject* /* kwds */) +Ice::AsyncResultPtr +IcePy::NewAsyncBlobjectInvocation::handleInvoke(PyObject* args, PyObject* /* kwds */) { char* operation; PyObject* mode; @@ -2991,20 +3357,19 @@ IcePy::OldAsyncBlobjectInvocation::invoke(PyObject* args, PyObject* /* kwds */) PyObject* operationModeType = lookupType("Ice.OperationMode"); PyObject* ctx = 0; #if PY_VERSION_HEX >= 0x03000000 - if(!PyArg_ParseTuple(args, STRCAST("OsO!O!|O"), &_callback, &operation, operationModeType, &mode, + if(!PyArg_ParseTuple(args, STRCAST("sO!O!|O"), &operation, operationModeType, &mode, &PyBytes_Type, &inParams, &ctx)) { return 0; } #else - if(!PyArg_ParseTuple(args, STRCAST("OsO!O!|O"), &_callback, &operation, operationModeType, &mode, + if(!PyArg_ParseTuple(args, STRCAST("sO!O!|O"), &operation, operationModeType, &mode, &PyBuffer_Type, &inParams, &ctx)) { return 0; } #endif - Py_INCREF(_callback); _op = operation; PyObjectHandle modeValue = PyObject_GetAttrString(mode, STRCAST("value")); @@ -3036,159 +3401,170 @@ IcePy::OldAsyncBlobjectInvocation::invoke(PyObject* args, PyObject* /* kwds */) } #endif - bool sentSynchronously = false; - try - { - Ice::AsyncResultPtr result; - Ice::Callback_Object_ice_invokePtr cb = - Ice::newCallback_Object_ice_invoke(this, &OldAsyncBlobjectInvocation::response, - &OldAsyncBlobjectInvocation::exception, - &OldAsyncBlobjectInvocation::sent); - - if(ctx == 0 || ctx == Py_None) - { - AllowThreads allowThreads; // Release Python's global interpreter lock during remote invocations. - result = _prx->begin_ice_invoke(operation, sendMode, in, cb); - } - else - { - Ice::Context context; - if(!dictionaryToContext(ctx, context)) - { - return 0; - } - - AllowThreads allowThreads; // Release Python's global interpreter lock during remote invocations. - result = _prx->begin_ice_invoke(operation, sendMode, in, context, cb); - } + NewAsyncInvocationPtr self = this; + Ice::Callback_Object_ice_invokePtr cb = + Ice::newCallback_Object_ice_invoke(self, &NewAsyncInvocation::response, &NewAsyncInvocation::exception, + &NewAsyncInvocation::sent); - sentSynchronously = result->sentSynchronously(); - } - catch(const Ice::CommunicatorDestroyedException& ex) + if(ctx == 0 || ctx == Py_None) { // - // CommunicatorDestroyedException is the only exception that can propagate directly. + // Don't release the GIL here. We want other threads to block until we've had a chance + // to create the future. // - setPythonException(ex); - return 0; + //AllowThreads allowThreads; // Release Python's global interpreter lock during remote invocations. + return _prx->begin_ice_invoke(operation, sendMode, in, cb); } - catch(const Ice::Exception&) + else { + Ice::Context context; + if(!dictionaryToContext(ctx, context)) + { + return 0; + } + // - // No other exceptions should be raised by begin_ice_invoke. + // Don't release the GIL here. We want other threads to block until we've had a chance + // to create the future. // - assert(false); + //AllowThreads allowThreads; // Release Python's global interpreter lock during remote invocations. + return _prx->begin_ice_invoke(operation, sendMode, in, context, cb); } - - PyRETURN_BOOL(sentSynchronously); } void -IcePy::OldAsyncBlobjectInvocation::response(bool ok, const pair<const Ice::Byte*, const Ice::Byte*>& results) +IcePy::NewAsyncBlobjectInvocation::handleResponse(PyObject* future, bool ok, + const pair<const Ice::Byte*, const Ice::Byte*>& results) { - AdoptThread adoptThread; // Ensure the current thread is able to call into Python. - - try + // + // Prepare the args as a tuple of the bool and out param buffer. + // + PyObjectHandle args = PyTuple_New(2); + if(!args.get()) { - // - // Prepare the args as a tuple of the bool and out param buffer. - // - PyObjectHandle args = PyTuple_New(2); - if(!args.get()) - { - assert(PyErr_Occurred()); - PyErr_Print(); - return; - } + assert(PyErr_Occurred()); + PyErr_Print(); + return; + } - PyTuple_SET_ITEM(args.get(), 0, ok ? incTrue() : incFalse()); + PyTuple_SET_ITEM(args.get(), 0, ok ? incTrue() : incFalse()); #if PY_VERSION_HEX >= 0x03000000 - Py_ssize_t sz = results.second - results.first; - PyObjectHandle op; - if(sz == 0) - { - op = PyBytes_FromString(""); - } - else - { - op = PyBytes_FromStringAndSize(reinterpret_cast<const char*>(results.first), sz); - } - if(!op.get()) - { - assert(PyErr_Occurred()); - PyErr_Print(); - return; - } + Py_ssize_t sz = results.second - results.first; + PyObjectHandle op; + if(sz == 0) + { + op = PyBytes_FromString(""); + } + else + { + op = PyBytes_FromStringAndSize(reinterpret_cast<const char*>(results.first), sz); + } + if(!op.get()) + { + assert(PyErr_Occurred()); + PyErr_Print(); + return; + } #else - // - // Create the output buffer and copy in the outParams. - // - PyObjectHandle op = PyBuffer_New(results.second - results.first); - if(!op.get()) - { - assert(PyErr_Occurred()); - PyErr_Print(); - return; - } + // + // Create the output buffer and copy in the outParams. + // + PyObjectHandle op = PyBuffer_New(results.second - results.first); + if(!op.get()) + { + assert(PyErr_Occurred()); + PyErr_Print(); + return; + } - void* buf; - Py_ssize_t sz; - if(PyObject_AsWriteBuffer(op.get(), &buf, &sz)) - { - assert(PyErr_Occurred()); - PyErr_Print(); - return; - } - assert(sz == results.second - results.first); - memcpy(buf, results.first, sz); + void* buf; + Py_ssize_t sz; + if(PyObject_AsWriteBuffer(op.get(), &buf, &sz)) + { + assert(PyErr_Occurred()); + PyErr_Print(); + return; + } + assert(sz == results.second - results.first); + memcpy(buf, results.first, sz); #endif - PyTuple_SET_ITEM(args.get(), 1, op.get()); - op.release(); // PyTuple_SET_ITEM steals a reference. + PyTuple_SET_ITEM(args.get(), 1, op.release()); // PyTuple_SET_ITEM steals a reference. - const string methodName = "ice_response"; - if(!PyObject_HasAttrString(_callback, STRCAST(methodName.c_str()))) - { - ostringstream ostr; - ostr << "AMI callback object for operation `ice_invoke_async' does not define " << methodName << "()"; - string str = ostr.str(); - PyErr_Warn(PyExc_RuntimeWarning, const_cast<char*>(str.c_str())); - } - else - { - PyObjectHandle method = PyObject_GetAttrString(_callback, STRCAST(methodName.c_str())); - assert(method.get()); - PyObjectHandle tmp = PyObject_Call(method.get(), args.get(), 0); - if(PyErr_Occurred()) - { - handleException(); // Callback raised an exception. - } - } + PyObjectHandle tmp = callMethod(future, "set_result", args.get()); + PyErr_Clear(); +} + +// +// Upcall +// +void +Upcall::dispatchImpl(PyObject* servant, const string& dispatchName, PyObject* args, const Ice::Current& current) +{ + Ice::CommunicatorPtr communicator = current.adapter->getCommunicator(); + + // + // Find the servant method for the operation. Use dispatchName here, not current.operation. + // + PyObjectHandle servantMethod = PyObject_GetAttrString(servant, const_cast<char*>(dispatchName.c_str())); + if(!servantMethod.get()) + { + ostringstream ostr; + ostr << "servant for identity " << communicator->identityToString(current.id) + << " does not define operation `" << dispatchName << "'"; + string str = ostr.str(); + PyErr_WarnEx(PyExc_RuntimeWarning, const_cast<char*>(str.c_str()), 1); + Ice::UnknownException ex(__FILE__, __LINE__); + ex.unknown = str; + throw ex; } - catch(const Ice::Exception& ex) + + // + // Get the _iceDispatch method. The _iceDispatch method will invoke the servant method and pass it the arguments. + // + PyObjectHandle dispatchMethod = PyObject_GetAttrString(servant, STRCAST("_iceDispatch")); + if(!dispatchMethod.get()) { ostringstream ostr; - ostr << "Exception raised by AMI callback for operation `ice_invoke_async':" << ex; + ostr << "_iceDispatch method not found for identity " << communicator->identityToString(current.id) + << " and operation `" << dispatchName << "'"; string str = ostr.str(); - PyErr_Warn(PyExc_RuntimeWarning, const_cast<char*>(str.c_str())); + PyErr_WarnEx(PyExc_RuntimeWarning, const_cast<char*>(str.c_str()), 1); + Ice::UnknownException ex(__FILE__, __LINE__); + ex.unknown = str; + throw ex; } -} -void -IcePy::OldAsyncBlobjectInvocation::exception(const Ice::Exception& ex) -{ - AdoptThread adoptThread; // Ensure the current thread is able to call into Python. + PyObjectHandle dispatchArgs = PyTuple_New(3); + if(!dispatchArgs.get()) + { + throwPythonException(); + } - callException(_callback, "ice_invoke", "ice_exception", ex); -} + DispatchCallbackObject* callback = dispatchCallbackNew(&DispatchCallbackType, 0, 0); + if(!callback) + { + throwPythonException(); + } + callback->upcall = new UpcallPtr(this); + PyTuple_SET_ITEM(dispatchArgs.get(), 0, reinterpret_cast<PyObject*>(callback)); // Steals a reference. + PyTuple_SET_ITEM(dispatchArgs.get(), 1, servantMethod.release()); // Steals a reference. + PyTuple_SET_ITEM(dispatchArgs.get(), 2, incRef(args)); // Steals a reference. -void -IcePy::OldAsyncBlobjectInvocation::sent(bool) -{ - AdoptThread adoptThread; // Ensure the current thread is able to call into Python. + // + // Ignore the return value of _iceDispatch -- it will use the dispatch callback. + // + PyObjectHandle ignore = PyObject_Call(dispatchMethod.get(), dispatchArgs.get(), 0); - callSent(_callback, "ice_sent", false, false); + // + // Check for exceptions. + // + if(PyErr_Occurred()) + { + PyException ex; // Retrieve it before another Python API call clears it. + exception(ex); + } } // @@ -3196,7 +3572,7 @@ IcePy::OldAsyncBlobjectInvocation::sent(bool) // IcePy::TypedUpcall::TypedUpcall(const OperationPtr& op, const Ice::AMD_Object_ice_invokePtr& callback, const Ice::CommunicatorPtr& communicator) : - _op(op), _callback(callback), _communicator(communicator), _finished(false) + _op(op), _callback(callback), _communicator(communicator) { } @@ -3204,19 +3580,14 @@ void IcePy::TypedUpcall::dispatch(PyObject* servant, const pair<const Ice::Byte*, const Ice::Byte*>& inBytes, const Ice::Current& current) { + _encoding = current.encoding; + // // Unmarshal the in parameters. We have to leave room in the arguments for a trailing // Ice::Current object. // Py_ssize_t count = static_cast<Py_ssize_t>(_op->inParams.size()) + 1; - Py_ssize_t offset = 0; - if(_op->amd) - { - ++count; // Leave room for a leading AMD callback argument. - offset = 1; - } - PyObjectHandle args = PyTuple_New(count); if(!args.get()) { @@ -3225,19 +3596,19 @@ IcePy::TypedUpcall::dispatch(PyObject* servant, const pair<const Ice::Byte*, con if(!_op->inParams.empty()) { - Ice::InputStreamPtr is = Ice::wrapInputStream(_communicator, inBytes); + Ice::InputStream is(_communicator, inBytes); // - // Store a pointer to a local SlicedDataUtil object as the stream's closure. + // Store a pointer to a local StreamUtil object as the stream's closure. // This is necessary to support object unmarshaling (see ObjectReader). // - SlicedDataUtil util; - assert(!is->closure()); - is->closure(&util); + StreamUtil util; + assert(!is.getClosure()); + is.setClosure(&util); try { - is->startEncapsulation(); + is.startEncapsulation(); ParamInfoList::iterator p; @@ -3249,8 +3620,8 @@ IcePy::TypedUpcall::dispatch(PyObject* servant, const pair<const Ice::Byte*, con ParamInfoPtr info = *p; if(!info->optional) { - void* closure = reinterpret_cast<void*>(info->pos + offset); - info->type->unmarshal(is, info, args.get(), closure, false, &info->metaData); + void* closure = reinterpret_cast<void*>(info->pos); + info->type->unmarshal(&is, info, args.get(), closure, false, &info->metaData); } } @@ -3260,26 +3631,25 @@ IcePy::TypedUpcall::dispatch(PyObject* servant, const pair<const Ice::Byte*, con for(p = _op->optionalInParams.begin(); p != _op->optionalInParams.end(); ++p) { ParamInfoPtr info = *p; - if(is->readOptional(info->tag, info->type->optionalFormat())) + if(is.readOptional(info->tag, info->type->optionalFormat())) { - void* closure = reinterpret_cast<void*>(info->pos + offset); - info->type->unmarshal(is, info, args.get(), closure, true, &info->metaData); + void* closure = reinterpret_cast<void*>(info->pos); + info->type->unmarshal(&is, info, args.get(), closure, true, &info->metaData); } else { - PyTuple_SET_ITEM(args.get(), info->pos + offset, Unset); - Py_INCREF(Unset); // PyTuple_SET_ITEM steals a reference. + PyTuple_SET_ITEM(args.get(), info->pos, incRef(Unset)); // PyTuple_SET_ITEM steals a reference. } } if(_op->sendsClasses) { - is->readPendingObjects(); + is.readPendingValues(); } - is->endEncapsulation(); + is.endEncapsulation(); - util.update(); + util.updateSlicedData(); } catch(const AbortMarshaling&) { @@ -3291,202 +3661,149 @@ IcePy::TypedUpcall::dispatch(PyObject* servant, const pair<const Ice::Byte*, con // Create an object to represent Ice::Current. We need to append this to the argument tuple. // PyObjectHandle curr = createCurrent(current); - PyTuple_SET_ITEM(args.get(), PyTuple_GET_SIZE(args.get()) - 1, curr.get()); - curr.release(); // PyTuple_SET_ITEM steals a reference. - - if(_op->amd) - { - // - // Create the callback object and pass it as the first argument. - // - AMDCallbackObject* obj = amdCallbackNew(&AMDCallbackType, 0, 0); - if(!obj) - { - throwPythonException(); - } - obj->upcall = new UpcallPtr(this); - obj->encoding = current.encoding; - PyTuple_SET_ITEM(args.get(), 0, (PyObject*)obj); // PyTuple_SET_ITEM steals a reference. - } - - // - // Dispatch the operation. Use _dispatchName here, not current.operation. - // - PyObjectHandle method = PyObject_GetAttrString(servant, const_cast<char*>(_op->dispatchName.c_str())); - if(!method.get()) - { - ostringstream ostr; - ostr << "servant for identity " << _communicator->identityToString(current.id) - << " does not define operation `" << _op->dispatchName << "'"; - string str = ostr.str(); - PyErr_Warn(PyExc_RuntimeWarning, const_cast<char*>(str.c_str())); - Ice::UnknownException ex(__FILE__, __LINE__); - ex.unknown = str; - throw ex; - } - - PyObjectHandle result = PyObject_Call(method.get(), args.get(), 0); - - // - // Check for exceptions. - // - if(PyErr_Occurred()) - { - PyException ex; // Retrieve it before another Python API call clears it. - exception(ex, current.encoding); - return; - } + PyTuple_SET_ITEM(args.get(), PyTuple_GET_SIZE(args.get()) - 1, + curr.release()); // PyTuple_SET_ITEM steals a reference. - if(!_op->amd) - { - response(result.get(), current.encoding); - } + dispatchImpl(servant, _op->dispatchName, args.get(), current); } void -IcePy::TypedUpcall::response(PyObject* args, const Ice::EncodingVersion& encoding) +IcePy::TypedUpcall::response(PyObject* result) { - if(_finished) + try { // - // This method could be called more than once if the application calls - // ice_response multiple times. We ignore subsequent calls. + // Marshal the results. If there is more than one value to be returned, then they must be + // returned in a tuple of the form (result, outParam1, ...). // - return; - } - _finished = true; + Py_ssize_t numResults = static_cast<Py_ssize_t>(_op->outParams.size()); + if(_op->returnType) + { + numResults++; + } + + if(numResults > 1 && (!PyTuple_Check(result) || PyTuple_GET_SIZE(result) != numResults)) + { + ostringstream ostr; + ostr << "operation `" << fixIdent(_op->name) << "' should return a tuple of length " << numResults; + string str = ostr.str(); + PyErr_WarnEx(PyExc_RuntimeWarning, const_cast<char*>(str.c_str()), 1); + throw Ice::MarshalException(__FILE__, __LINE__); + } - try - { // - // Marshal the results. If there is more than one value to be returned, then they must be - // returned in a tuple of the form (result, outParam1, ...). + // Normalize the result value. When there are multiple result values, result is already a tuple. + // Otherwise, we create a tuple to make the code a little simpler. // - Ice::OutputStreamPtr os = Ice::createOutputStream(_communicator); - try + PyObjectHandle t; + if(numResults > 1) + { + t = incRef(result); + } + else { - Py_ssize_t numResults = static_cast<Py_ssize_t>(_op->outParams.size()); - if(_op->returnType) + t = PyTuple_New(1); + if(!t.get()) { - numResults++; + throw AbortMarshaling(); } + PyTuple_SET_ITEM(t.get(), 0, incRef(result)); + } + + ObjectMap objectMap; + ParamInfoList::iterator p; - if(numResults > 1 && (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) != numResults)) + // + // Validate the results. + // + for(p = _op->outParams.begin(); p != _op->outParams.end(); ++p) + { + ParamInfoPtr info = *p; + PyObject* arg = PyTuple_GET_ITEM(t.get(), info->pos); + if((!info->optional || arg != Unset) && !info->type->validate(arg)) { + // TODO: Provide the parameter name instead? ostringstream ostr; - ostr << "operation `" << fixIdent(_op->name) << "' should return a tuple of length " << numResults; + ostr << "invalid value for out argument " << (info->pos + 1) << " in operation `" + << _op->dispatchName << "'"; string str = ostr.str(); - PyErr_Warn(PyExc_RuntimeWarning, const_cast<char*>(str.c_str())); + PyErr_WarnEx(PyExc_RuntimeWarning, const_cast<char*>(str.c_str()), 1); throw Ice::MarshalException(__FILE__, __LINE__); } - - // - // Normalize the args value. For an AMD operation, or when there are multiple - // result values, args is already a tuple. Otherwise, we create a tuple to - // make the code a little simpler. - // - PyObjectHandle t; - if(_op->amd || numResults > 1) - { - t = args; - } - else + } + if(_op->returnType) + { + PyObject* res = PyTuple_GET_ITEM(t.get(), 0); + if((!_op->returnType->optional || res != Unset) && !_op->returnType->type->validate(res)) { - t = PyTuple_New(1); - if(!t.get()) - { - throw AbortMarshaling(); - } - PyTuple_SET_ITEM(t.get(), 0, args); + ostringstream ostr; + ostr << "invalid return value for operation `" << _op->dispatchName << "'"; + string str = ostr.str(); + PyErr_WarnEx(PyExc_RuntimeWarning, const_cast<char*>(str.c_str()), 1); + throw Ice::MarshalException(__FILE__, __LINE__); } - Py_INCREF(args); - - os->startEncapsulation(encoding, _op->format); + } - ObjectMap objectMap; - ParamInfoList::iterator p; + Ice::OutputStream os(_communicator); + os.startEncapsulation(_encoding, _op->format); - // - // Validate the results. - // - for(p = _op->outParams.begin(); p != _op->outParams.end(); ++p) + // + // Marshal the required out parameters. + // + for(p = _op->outParams.begin(); p != _op->outParams.end(); ++p) + { + ParamInfoPtr info = *p; + if(!info->optional) { - ParamInfoPtr info = *p; PyObject* arg = PyTuple_GET_ITEM(t.get(), info->pos); - if((!info->optional || arg != Unset) && !info->type->validate(arg)) - { - // TODO: Provide the parameter name instead? - ostringstream ostr; - ostr << "invalid value for out argument " << (info->pos + 1) << " in operation `" - << _op->dispatchName << "'"; - string str = ostr.str(); - PyErr_Warn(PyExc_RuntimeWarning, const_cast<char*>(str.c_str())); - throw Ice::MarshalException(__FILE__, __LINE__); - } - } - if(_op->returnType) - { - PyObject* res = PyTuple_GET_ITEM(t.get(), 0); - if((!_op->returnType->optional || res != Unset) && !_op->returnType->type->validate(res)) - { - ostringstream ostr; - ostr << "invalid return value for operation `" << _op->dispatchName << "'"; - string str = ostr.str(); - PyErr_Warn(PyExc_RuntimeWarning, const_cast<char*>(str.c_str())); - throw Ice::MarshalException(__FILE__, __LINE__); - } - } - - // - // Marshal the required out parameters. - // - for(p = _op->outParams.begin(); p != _op->outParams.end(); ++p) - { - ParamInfoPtr info = *p; - if(!info->optional) - { - PyObject* arg = PyTuple_GET_ITEM(t.get(), info->pos); - info->type->marshal(arg, os, &objectMap, false, &info->metaData); - } + info->type->marshal(arg, &os, &objectMap, false, &info->metaData); } + } - // - // Marshal the required return value, if any. - // - if(_op->returnType && !_op->returnType->optional) - { - PyObject* res = PyTuple_GET_ITEM(t.get(), 0); - _op->returnType->type->marshal(res, os, &objectMap, false, &_op->metaData); - } + // + // Marshal the required return value, if any. + // + if(_op->returnType && !_op->returnType->optional) + { + PyObject* res = PyTuple_GET_ITEM(t.get(), 0); + _op->returnType->type->marshal(res, &os, &objectMap, false, &_op->metaData); + } - // - // Marshal the optional results. - // - for(p = _op->optionalOutParams.begin(); p != _op->optionalOutParams.end(); ++p) + // + // Marshal the optional results. + // + for(p = _op->optionalOutParams.begin(); p != _op->optionalOutParams.end(); ++p) + { + ParamInfoPtr info = *p; + PyObject* arg = PyTuple_GET_ITEM(t.get(), info->pos); + if(arg != Unset && os.writeOptional(info->tag, info->type->optionalFormat())) { - ParamInfoPtr info = *p; - PyObject* arg = PyTuple_GET_ITEM(t.get(), info->pos); - if(arg != Unset && os->writeOptional(info->tag, info->type->optionalFormat())) - { - info->type->marshal(arg, os, &objectMap, true, &info->metaData); - } + info->type->marshal(arg, &os, &objectMap, true, &info->metaData); } + } - if(_op->returnsClasses) - { - os->writePendingObjects(); - } + if(_op->returnsClasses) + { + os.writePendingValues(); + } - os->endEncapsulation(); + os.endEncapsulation(); - AllowThreads allowThreads; // Release Python's global interpreter lock during blocking calls. - _callback->ice_response(true, os->finished()); - } - catch(const AbortMarshaling&) + AllowThreads allowThreads; // Release Python's global interpreter lock during blocking calls. + _callback->ice_response(true, os.finished()); + } + catch(const AbortMarshaling&) + { + try { throwPythonException(); } + catch(const Ice::Exception& ex) + { + AllowThreads allowThreads; // Release Python's global interpreter lock during blocking calls. + _callback->ice_exception(ex); + } } catch(const Ice::Exception& ex) { @@ -3496,19 +3813,8 @@ IcePy::TypedUpcall::response(PyObject* args, const Ice::EncodingVersion& encodin } void -IcePy::TypedUpcall::exception(PyException& ex, const Ice::EncodingVersion& encoding) +IcePy::TypedUpcall::exception(PyException& ex) { - if(_finished) - { - // - // An asynchronous response or exception has already been sent. We just - // raise an exception and let the C++ run time handle it. - // - ex.raise(); - } - - _finished = true; - try { try @@ -3526,29 +3832,23 @@ IcePy::TypedUpcall::exception(PyException& ex, const Ice::EncodingVersion& encod if(PyObject_IsInstance(ex.ex.get(), userExceptionType)) { // - // Get the exception's type and verify that it is legal to be thrown from this operation. + // Get the exception's type. // PyObjectHandle iceType = PyObject_GetAttrString(ex.ex.get(), STRCAST("_ice_type")); assert(iceType.get()); ExceptionInfoPtr info = ExceptionInfoPtr::dynamicCast(getException(iceType.get())); assert(info); - if(!validateException(ex.ex.get())) - { - ex.raise(); // Raises UnknownUserException. - } - else - { - Ice::OutputStreamPtr os = Ice::createOutputStream(_communicator); - os->startEncapsulation(encoding, _op->format); - ExceptionWriter writer(_communicator, ex.ex, info); - os->writeException(writer); + Ice::OutputStream os(_communicator); + os.startEncapsulation(_encoding, _op->format); - os->endEncapsulation(); + ExceptionWriter writer(ex.ex, info); + os.writeException(writer); - AllowThreads allowThreads; // Release Python's global interpreter lock during blocking calls. - _callback->ice_response(false, os->finished()); - } + os.endEncapsulation(); + + AllowThreads allowThreads; // Release Python's global interpreter lock during blocking calls. + _callback->ice_response(false, os.finished()); } else { @@ -3562,30 +3862,22 @@ IcePy::TypedUpcall::exception(PyException& ex, const Ice::EncodingVersion& encod } catch(const Ice::Exception& ex) { - AllowThreads allowThreads; // Release Python's global interpreter lock during blocking calls. - _callback->ice_exception(ex); + exception(ex); } } -bool -IcePy::TypedUpcall::validateException(PyObject* ex) const +void +IcePy::TypedUpcall::exception(const Ice::Exception& ex) { - for(ExceptionInfoList::const_iterator p = _op->exceptions.begin(); p != _op->exceptions.end(); ++p) - { - if(PyObject_IsInstance(ex, (*p)->pythonType.get())) - { - return true; - } - } - - return false; + AllowThreads allowThreads; // Release Python's global interpreter lock during blocking calls. + _callback->ice_exception(ex); } // // BlobjectUpcall // -IcePy::BlobjectUpcall::BlobjectUpcall(bool amd, const Ice::AMD_Object_ice_invokePtr& callback) : - _amd(amd), _callback(callback), _finished(false) +IcePy::BlobjectUpcall::BlobjectUpcall(const Ice::AMD_Object_ice_invokePtr& callback) : + _callback(callback) { } @@ -3598,11 +3890,6 @@ IcePy::BlobjectUpcall::dispatch(PyObject* servant, const pair<const Ice::Byte*, Py_ssize_t count = 2; // First is the inParams, second is the Ice::Current object. Py_ssize_t start = 0; - if(_amd) - { - ++count; // Leave room for a leading AMD callback argument. - start = 1; - } PyObjectHandle args = PyTuple_New(count); if(!args.get()) @@ -3623,186 +3910,113 @@ IcePy::BlobjectUpcall::dispatch(PyObject* servant, const pair<const Ice::Byte*, } #else // - // If using AMD we need to copy the bytes since the bytes may be - // accessed after this method is over, otherwise - // PyBuffer_FromMemory can be used which doesn't do a copy. + // Make a copy of the bytes since the bytes may be accessed after this method is over. // - if(!_amd) + ip = PyBuffer_New(inBytes.second - inBytes.first); + if(!ip.get()) { - ip = PyBuffer_FromMemory((void*)inBytes.first, inBytes.second - inBytes.first); - if(!ip.get()) - { - throwPythonException(); - } + throwPythonException(); } - else + void* buf; + Py_ssize_t sz; + if(PyObject_AsWriteBuffer(ip.get(), &buf, &sz)) { - ip = PyBuffer_New(inBytes.second - inBytes.first); - if(!ip.get()) - { - throwPythonException(); - } - void* buf; - Py_ssize_t sz; - if(PyObject_AsWriteBuffer(ip.get(), &buf, &sz)) - { - throwPythonException(); - } - assert(sz == inBytes.second - inBytes.first); - memcpy(buf, inBytes.first, sz); + throwPythonException(); } + assert(sz == inBytes.second - inBytes.first); + memcpy(buf, inBytes.first, sz); #endif - PyTuple_SET_ITEM(args.get(), start, ip.get()); + PyTuple_SET_ITEM(args.get(), start, ip.release()); // PyTuple_SET_ITEM steals a reference. ++start; - ip.release(); // PyTuple_SET_ITEM steals a reference. // // Create an object to represent Ice::Current. We need to append // this to the argument tuple. // PyObjectHandle curr = createCurrent(current); - PyTuple_SET_ITEM(args.get(), start, curr.get()); - curr.release(); // PyTuple_SET_ITEM steals a reference. + PyTuple_SET_ITEM(args.get(), start, curr.release()); // PyTuple_SET_ITEM steals a reference. - string dispatchName = "ice_invoke"; - if(_amd) - { - dispatchName += "_async"; - // - // Create the callback object and pass it as the first argument. - // - AMDCallbackObject* obj = amdCallbackNew(&AMDCallbackType, 0, 0); - if(!obj) - { - throwPythonException(); - } - obj->upcall = new UpcallPtr(this); - obj->encoding = current.encoding; - PyTuple_SET_ITEM(args.get(), 0, (PyObject*)obj); // PyTuple_SET_ITEM steals a reference. - } - - // - // Dispatch the operation. - // - PyObjectHandle method = PyObject_GetAttrString(servant, const_cast<char*>(dispatchName.c_str())); - if(!method.get()) - { - ostringstream ostr; - ostr << "servant for identity " << communicator->identityToString(current.id) - << " does not define operation `" << dispatchName << "'"; - string str = ostr.str(); - PyErr_Warn(PyExc_RuntimeWarning, const_cast<char*>(str.c_str())); - Ice::UnknownException ex(__FILE__, __LINE__); - ex.unknown = str; - throw ex; - } - - PyObjectHandle result = PyObject_Call(method.get(), args.get(), 0); - - // - // Check for exceptions. - // - if(PyErr_Occurred()) - { - PyException ex; // Retrieve it before another Python API call clears it. - exception(ex, current.encoding); - return; - } - - if(!_amd) - { - response(result.get(), current.encoding); - } + dispatchImpl(servant, "ice_invoke", args.get(), current); } void -IcePy::BlobjectUpcall::response(PyObject* args, const Ice::EncodingVersion&) +IcePy::BlobjectUpcall::response(PyObject* result) { - if(_finished) + try { // - // This method could be called more than once if the application calls - // ice_response multiple times. We ignore subsequent calls. + // The result is a tuple of (bool, results). // - return; - } + if(!PyTuple_Check(result) || PyTuple_GET_SIZE(result) != 2) + { + string str = "operation `ice_invoke' should return a tuple of length 2"; + PyErr_WarnEx(PyExc_RuntimeWarning, const_cast<char*>(str.c_str()), 1); + throw Ice::MarshalException(__FILE__, __LINE__); + } - _finished = true; + PyObject* arg = PyTuple_GET_ITEM(result, 0); + bool isTrue = PyObject_IsTrue(arg) == 1; - // - // The return value is a tuple of (bool, results). - // - if(!PyTuple_Check(args) || PyTuple_GET_SIZE(args) != 2) - { - ostringstream ostr; - string name = "ice_invoke"; - if(_amd) + arg = PyTuple_GET_ITEM(result, 1); + +#if PY_VERSION_HEX >= 0x03000000 + if(!PyBytes_Check(arg)) { - name += "_async"; + ostringstream ostr; + ostr << "invalid return value for operation `ice_invoke'"; + string str = ostr.str(); + PyErr_WarnEx(PyExc_RuntimeWarning, const_cast<char*>(str.c_str()), 1); + throw Ice::MarshalException(__FILE__, __LINE__); } - ostr << "operation `" << name << "' should return a tuple of length 2"; - string str = ostr.str(); - PyErr_Warn(PyExc_RuntimeWarning, const_cast<char*>(str.c_str())); - throw Ice::MarshalException(__FILE__, __LINE__); - } - PyObject* arg = PyTuple_GET_ITEM(args, 0); - bool isTrue = PyObject_IsTrue(arg) == 1; + Py_ssize_t sz = PyBytes_GET_SIZE(arg); + pair<const ::Ice::Byte*, const ::Ice::Byte*> r(static_cast<const Ice::Byte*>(0), + static_cast<const Ice::Byte*>(0)); + if(sz > 0) + { + r.first = reinterpret_cast<Ice::Byte*>(PyBytes_AS_STRING(arg)); + r.second = r.first + sz; + } +#else + if(!PyBuffer_Check(arg)) + { + ostringstream ostr; + ostr << "invalid return value for operation `ice_invoke'"; + string str = ostr.str(); + PyErr_WarnEx(PyExc_RuntimeWarning, const_cast<char*>(str.c_str()), 1); + throw Ice::MarshalException(__FILE__, __LINE__); + } - arg = PyTuple_GET_ITEM(args, 1); + char* charBuf = 0; + Py_ssize_t sz = arg->ob_type->tp_as_buffer->bf_getcharbuffer(arg, 0, &charBuf); + const Ice::Byte* mem = reinterpret_cast<const Ice::Byte*>(charBuf); + const pair<const ::Ice::Byte*, const ::Ice::Byte*> r(mem, mem + sz); +#endif -#if PY_VERSION_HEX >= 0x03000000 - if(!PyBytes_Check(arg)) - { - ostringstream ostr; - ostr << "invalid return value for operation `ice_invoke'"; - string str = ostr.str(); - PyErr_Warn(PyExc_RuntimeWarning, const_cast<char*>(str.c_str())); - throw Ice::MarshalException(__FILE__, __LINE__); + AllowThreads allowThreads; // Release Python's global interpreter lock during blocking calls. + _callback->ice_response(isTrue, r); } - - Py_ssize_t sz = PyBytes_GET_SIZE(arg); - pair<const ::Ice::Byte*, const ::Ice::Byte*> r(static_cast<const Ice::Byte*>(0),static_cast<const Ice::Byte*>(0)); - if(sz > 0) + catch(const AbortMarshaling&) { - r.first = reinterpret_cast<Ice::Byte*>(PyBytes_AS_STRING(arg)); - r.second = r.first + sz; + try + { + throwPythonException(); + } + catch(const Ice::Exception& ex) + { + exception(ex); + } } -#else - if(!PyBuffer_Check(arg)) + catch(const Ice::Exception& ex) { - ostringstream ostr; - ostr << "invalid return value for operation `ice_invoke'"; - string str = ostr.str(); - PyErr_Warn(PyExc_RuntimeWarning, const_cast<char*>(str.c_str())); - throw Ice::MarshalException(__FILE__, __LINE__); + exception(ex); } - - char* charBuf = 0; - Py_ssize_t sz = arg->ob_type->tp_as_buffer->bf_getcharbuffer(arg, 0, &charBuf); - const Ice::Byte* mem = reinterpret_cast<const Ice::Byte*>(charBuf); - const pair<const ::Ice::Byte*, const ::Ice::Byte*> r(mem, mem + sz); -#endif - - AllowThreads allowThreads; // Release Python's global interpreter lock during blocking calls. - _callback->ice_response(isTrue, r); } void -IcePy::BlobjectUpcall::exception(PyException& ex, const Ice::EncodingVersion&) +IcePy::BlobjectUpcall::exception(PyException& ex) { - if(_finished) - { - // - // An asynchronous response or exception has already been sent. We just - // raise an exception and let the C++ run time handle it. - // - ex.raise(); - } - - _finished = true; - try { // @@ -3817,11 +4031,17 @@ IcePy::BlobjectUpcall::exception(PyException& ex, const Ice::EncodingVersion&) } catch(const Ice::Exception& ex) { - AllowThreads allowThreads; // Release Python's global interpreter lock during blocking calls. - _callback->ice_exception(ex); + exception(ex); } } +void +IcePy::BlobjectUpcall::exception(const Ice::Exception& ex) +{ + AllowThreads allowThreads; // Release Python's global interpreter lock during blocking calls. + _callback->ice_exception(ex); +} + PyObject* IcePy::invokeBuiltin(PyObject* proxy, const string& builtin, PyObject* args) { @@ -3840,6 +4060,23 @@ IcePy::invokeBuiltin(PyObject* proxy, const string& builtin, PyObject* args) } PyObject* +IcePy::invokeBuiltinAsync(PyObject* proxy, const string& builtin, PyObject* args) +{ + string name = "_op_" + builtin; + PyObject* objectType = lookupType("Ice.Object"); + assert(objectType); + PyObjectHandle obj = PyObject_GetAttrString(objectType, STRCAST(name.c_str())); + assert(obj.get()); + + OperationPtr op = getOperation(obj.get()); + assert(op); + + Ice::ObjectPrx p = getProxy(proxy); + InvocationPtr i = new NewAsyncTypedInvocation(p, proxy, op); + return i->invoke(args); +} + +PyObject* IcePy::beginBuiltin(PyObject* proxy, const string& builtin, PyObject* args) { string name = "_op_" + builtin; @@ -3898,7 +4135,7 @@ PyObject* IcePy::iceInvokeAsync(PyObject* proxy, PyObject* args) { Ice::ObjectPrx p = getProxy(proxy); - InvocationPtr i = new OldAsyncBlobjectInvocation(p); + InvocationPtr i = new NewAsyncBlobjectInvocation(p, proxy); return i->invoke(args); } @@ -3940,12 +4177,9 @@ IcePy::createAsyncResult(const Ice::AsyncResultPtr& r, PyObject* proxy, PyObject return 0; } obj->result = new Ice::AsyncResultPtr(r); - obj->proxy = proxy; - Py_XINCREF(obj->proxy); - obj->connection = connection; - Py_XINCREF(obj->connection); - obj->communicator = communicator; - Py_XINCREF(obj->communicator); + obj->proxy = incRef(proxy); + obj->connection = incRef(connection); + obj->communicator = incRef(communicator); return reinterpret_cast<PyObject*>(obj); } @@ -3957,6 +4191,9 @@ IcePy::getAsyncResult(PyObject* p) return *obj->result; } +// +// FlushCallback +// IcePy::FlushCallback::FlushCallback(PyObject* ex, PyObject* sent, const string& op) : _ex(ex), _sent(sent), _op(op) { @@ -3991,6 +4228,100 @@ IcePy::FlushCallback::sent(bool sentSynchronously) } } +IcePy::FlushAsyncCallback::FlushAsyncCallback(const string& op) : + _op(op), _future(0), _sent(false), _sentSynchronously(false), _exception(0) +{ +} + +IcePy::FlushAsyncCallback::~FlushAsyncCallback() +{ + AdoptThread adoptThread; // Ensure the current thread is able to call into Python. + + Py_XDECREF(_future); + Py_XDECREF(_exception); +} + +void +IcePy::FlushAsyncCallback::setFuture(PyObject* future) +{ + // + // Called with the GIL locked. + // + + // + // Check if any callbacks have been invoked already. + // + if(_exception) + { + PyObjectHandle tmp = callMethod(future, "set_exception", _exception); + PyErr_Clear(); + } + else if(_sent) + { + PyObjectHandle tmp = callMethod(future, "set_sent", _sentSynchronously ? getTrue() : getFalse()); + PyErr_Clear(); + // + // We consider the invocation complete when sent. + // + tmp = callMethod(future, "set_result", Py_None); + PyErr_Clear(); + } + else + { + _future = incRef(future); + } +} + +void +IcePy::FlushAsyncCallback::exception(const Ice::Exception& ex) +{ + AdoptThread adoptThread; // Ensure the current thread is able to call into Python. + + if(!_future) + { + // + // The future hasn't been set yet, which means the request is still being invoked. Save the results for later. + // + _exception = convertException(ex); + return; + } + + PyObjectHandle exh = convertException(ex); + assert(exh.get()); + PyObjectHandle tmp = callMethod(_future, "set_exception", exh.get()); + PyErr_Clear(); + + Py_DECREF(_future); // Break cyclic dependency. + _future = 0; +} + +void +IcePy::FlushAsyncCallback::sent(bool sentSynchronously) +{ + AdoptThread adoptThread; // Ensure the current thread is able to call into Python. + + if(!_future) + { + // + // The future hasn't been set yet, which means the request is still being invoked. Save the results for later. + // + _sent = true; + _sentSynchronously = sentSynchronously; + return; + } + + PyObjectHandle tmp = callMethod(_future, "set_sent", _sentSynchronously ? getTrue() : getFalse()); + PyErr_Clear(); + // + // We consider the invocation complete when sent. + // + tmp = callMethod(_future, "set_result", Py_None); + PyErr_Clear(); + + Py_DECREF(_future); // Break cyclic dependency. + _future = 0; +} + IcePy::GetConnectionCallback::GetConnectionCallback(const Ice::CommunicatorPtr& communicator, PyObject* response, PyObject* ex, const string& op) : _communicator(communicator), _response(response), _ex(ex), _op(op) @@ -4030,6 +4361,92 @@ IcePy::GetConnectionCallback::exception(const Ice::Exception& ex) callException(_ex, ex); } +IcePy::GetConnectionAsyncCallback::GetConnectionAsyncCallback(const Ice::CommunicatorPtr& communicator, + const string& op) : + _communicator(communicator), _op(op), _future(0), _exception(0) +{ +} + +IcePy::GetConnectionAsyncCallback::~GetConnectionAsyncCallback() +{ + AdoptThread adoptThread; // Ensure the current thread is able to call into Python. + + Py_XDECREF(_future); + Py_XDECREF(_exception); +} + +void +IcePy::GetConnectionAsyncCallback::setFuture(PyObject* future) +{ + // + // Called with the GIL locked. + // + + // + // Check if any callbacks have been invoked already. + // + if(_connection) + { + PyObjectHandle pyConn = createConnection(_connection, _communicator); + assert(pyConn.get()); + PyObjectHandle tmp = callMethod(future, "set_result", pyConn.get()); + PyErr_Clear(); + } + else if(_exception) + { + PyObjectHandle tmp = callMethod(future, "set_exception", _exception); + PyErr_Clear(); + } + else + { + _future = incRef(future); + } +} + +void +IcePy::GetConnectionAsyncCallback::response(const Ice::ConnectionPtr& conn) +{ + AdoptThread adoptThread; // Ensure the current thread is able to call into Python. + + if(!_future) + { + // + // The future hasn't been set yet, which means the request is still being invoked. Save the results for later. + // + _connection = conn; + return; + } + + PyObjectHandle pyConn = createConnection(conn, _communicator); + PyObjectHandle tmp = callMethod(_future, "set_result", pyConn.get()); + PyErr_Clear(); + + Py_DECREF(_future); // Break cyclic dependency. + _future = 0; +} + +void +IcePy::GetConnectionAsyncCallback::exception(const Ice::Exception& ex) +{ + AdoptThread adoptThread; // Ensure the current thread is able to call into Python. + + if(!_future) + { + // + // The future hasn't been set yet, which means the request is still being invoked. Save the results for later. + // + _exception = convertException(ex); + return; + } + + PyObjectHandle exh = convertException(ex); + PyObjectHandle tmp = callMethod(_future, "set_exception", exh.get()); + PyErr_Clear(); + + Py_DECREF(_future); // Break cyclic dependency. + _future = 0; +} + // // ServantWrapper implementation. // @@ -4119,7 +4536,7 @@ IcePy::TypedServantWrapper::ice_invoke_async(const Ice::AMD_Object_ice_invokePtr // if(!op->pseudoOp) { - __checkMode(op->mode, current.mode); + _iceCheckMode(op->mode, current.mode); } UpcallPtr up = new TypedUpcall(op, cb, current.adapter->getCommunicator()); @@ -4135,8 +4552,8 @@ IcePy::TypedServantWrapper::ice_invoke_async(const Ice::AMD_Object_ice_invokePtr // // BlobjectServantWrapper implementation. // -IcePy::BlobjectServantWrapper::BlobjectServantWrapper(PyObject* servant, bool amd) : - ServantWrapper(servant), _amd(amd) +IcePy::BlobjectServantWrapper::BlobjectServantWrapper(PyObject* servant) : + ServantWrapper(servant) { } @@ -4149,7 +4566,7 @@ IcePy::BlobjectServantWrapper::ice_invoke_async(const Ice::AMD_Object_ice_invoke try { - UpcallPtr up = new BlobjectUpcall(_amd, cb); + UpcallPtr up = new BlobjectUpcall(cb); up->dispatch(_servant, inParams, current); } catch(const Ice::Exception& ex) @@ -4167,12 +4584,59 @@ IcePy::createServantWrapper(PyObject* servant) PyObject* blobjectAsyncType = lookupType("Ice.BlobjectAsync"); if(PyObject_IsInstance(servant, blobjectType)) { - return new BlobjectServantWrapper(servant, false); + return new BlobjectServantWrapper(servant); } else if(PyObject_IsInstance(servant, blobjectAsyncType)) { - return new BlobjectServantWrapper(servant, true); + return new BlobjectServantWrapper(servant); } return new TypedServantWrapper(servant); } + +PyObject* +IcePy::createFuture() +{ + PyObject* futureType = lookupType("Ice.Future"); + assert(futureType); + PyObjectHandle args = PyTuple_New(0); + if(!args.get()) + { + return 0; + } + PyTypeObject* type = reinterpret_cast<PyTypeObject*>(futureType); + PyObject* future = type->tp_new(type, args.get(), 0); + if(!future) + { + return 0; + } + type->tp_init(future, args.get(), 0); // Call the constructor + return future; +} + +PyObject* +IcePy::createFuture(const string& operation, PyObject* asyncResult) +{ + if(!asyncResult) // Can be nil for batch invocations. + { + asyncResult = Py_None; + } + + PyObject* futureType = lookupType("Ice.InvocationFuture"); + assert(futureType); + PyObjectHandle args = PyTuple_New(2); + if(!args.get()) + { + return 0; + } + PyTuple_SET_ITEM(args.get(), 0, createString(operation)); + PyTuple_SET_ITEM(args.get(), 1, incRef(asyncResult)); + PyTypeObject* type = reinterpret_cast<PyTypeObject*>(futureType); + PyObject* future = type->tp_new(type, args.get(), 0); + if(!future) + { + return 0; + } + type->tp_init(future, args.get(), 0); // Call the constructor + return future; +} diff --git a/python/modules/IcePy/Operation.h b/python/modules/IcePy/Operation.h index 93b3eb725a6..82438902436 100644 --- a/python/modules/IcePy/Operation.h +++ b/python/modules/IcePy/Operation.h @@ -15,6 +15,8 @@ #include <Ice/Object.h> #include <Ice/AsyncResultF.h> #include <Ice/CommunicatorF.h> +#include <IceUtil/Monitor.h> +#include <Util.h> namespace IcePy { @@ -25,6 +27,7 @@ bool initOperation(PyObject*); // Builtin operations. // PyObject* invokeBuiltin(PyObject*, const std::string&, PyObject*); +PyObject* invokeBuiltinAsync(PyObject*, const std::string&, PyObject*); PyObject* beginBuiltin(PyObject*, const std::string&, PyObject*); PyObject* endBuiltin(PyObject*, const std::string&, PyObject*); @@ -63,6 +66,31 @@ protected: typedef IceUtil::Handle<GetConnectionCallback> GetConnectionCallbackPtr; // +// Used as the callback for getConnectionAsync operation. +// +class GetConnectionAsyncCallback : public IceUtil::Shared +{ +public: + + GetConnectionAsyncCallback(const Ice::CommunicatorPtr&, const std::string&); + ~GetConnectionAsyncCallback(); + + void setFuture(PyObject*); + + void response(const Ice::ConnectionPtr&); + void exception(const Ice::Exception&); + +protected: + + Ice::CommunicatorPtr _communicator; + std::string _op; + PyObject* _future; + Ice::ConnectionPtr _connection; + PyObject* _exception; +}; +typedef IceUtil::Handle<GetConnectionAsyncCallback> GetConnectionAsyncCallbackPtr; + +// // Used as the callback for the various flushBatchRequest operations. // class FlushCallback : public IceUtil::Shared @@ -84,6 +112,31 @@ protected: typedef IceUtil::Handle<FlushCallback> FlushCallbackPtr; // +// Used as the callback for the various flushBatchRequestAsync operations. +// +class FlushAsyncCallback : public IceUtil::Shared +{ +public: + + FlushAsyncCallback(const std::string&); + ~FlushAsyncCallback(); + + void setFuture(PyObject*); + + void exception(const Ice::Exception&); + void sent(bool); + +protected: + + std::string _op; + PyObject* _future; + bool _sent; + bool _sentSynchronously; + PyObject* _exception; +}; +typedef IceUtil::Handle<FlushAsyncCallback> FlushAsyncCallbackPtr; + +// // ServantWrapper handles dispatching to a Python servant. // class ServantWrapper : public Ice::BlobjectArrayAsync @@ -103,6 +156,9 @@ typedef IceUtil::Handle<ServantWrapper> ServantWrapperPtr; ServantWrapperPtr createServantWrapper(PyObject*); +PyObject* createFuture(); +PyObject* createFuture(const std::string&, PyObject*); + } #endif diff --git a/python/modules/IcePy/Proxy.cpp b/python/modules/IcePy/Proxy.cpp index 072d845f5e0..c3fa273fa47 100644 --- a/python/modules/IcePy/Proxy.cpp +++ b/python/modules/IcePy/Proxy.cpp @@ -145,9 +145,7 @@ proxyCompare(ProxyObject* p1, PyObject* other, int op) } } - PyObject* r = result ? getTrue() : getFalse(); - Py_INCREF(r); - return r; + return result ? incTrue() : incFalse(); } #ifdef WIN32 @@ -166,7 +164,7 @@ extern "C" static long proxyHash(ProxyObject* self) { - return static_cast<long>((*self->proxy)->__hash()); + return static_cast<long>((*self->proxy)->_hash()); } #ifdef WIN32 @@ -203,6 +201,27 @@ proxyIceIsA(ProxyObject* self, PyObject* args) extern "C" #endif static PyObject* +proxyIceIsAAsync(ProxyObject* self, PyObject* args) +{ + PyObject* type; + PyObject* ctx = Py_None; + if(!PyArg_ParseTuple(args, STRCAST("O|O!"), &type, &PyDict_Type, &ctx)) + { + return 0; + } + + // + // We need to reformat the arguments to match what is used by the generated code: ((params...), ctx|None) + // + PyObjectHandle newArgs = Py_BuildValue(STRCAST("((O), O)"), type, ctx); + + return invokeBuiltinAsync(reinterpret_cast<PyObject*>(self), "ice_isA", newArgs.get()); +} + +#ifdef WIN32 +extern "C" +#endif +static PyObject* proxyBeginIceIsA(ProxyObject* self, PyObject* args, PyObject* kwds) { static char* argNames[] = @@ -211,7 +230,7 @@ proxyBeginIceIsA(ProxyObject* self, PyObject* args, PyObject* kwds) const_cast<char*>("_response"), const_cast<char*>("_ex"), const_cast<char*>("_sent"), - const_cast<char*>("_ctx"), + const_cast<char*>("context"), 0 }; PyObject* type; @@ -267,6 +286,26 @@ proxyIcePing(ProxyObject* self, PyObject* args) extern "C" #endif static PyObject* +proxyIcePingAsync(ProxyObject* self, PyObject* args) +{ + PyObject* ctx = Py_None; + if(!PyArg_ParseTuple(args, STRCAST("|O!"), &PyDict_Type, &ctx)) + { + return 0; + } + + // + // We need to reformat the arguments to match what is used by the generated code: ((params...), ctx|None) + // + PyObjectHandle newArgs = Py_BuildValue(STRCAST("((), O)"), ctx); + + return invokeBuiltinAsync(reinterpret_cast<PyObject*>(self), "ice_ping", newArgs.get()); +} + +#ifdef WIN32 +extern "C" +#endif +static PyObject* proxyBeginIcePing(ProxyObject* self, PyObject* args, PyObject* kwds) { static char* argNames[] = @@ -274,7 +313,7 @@ proxyBeginIcePing(ProxyObject* self, PyObject* args, PyObject* kwds) const_cast<char*>("_response"), const_cast<char*>("_ex"), const_cast<char*>("_sent"), - const_cast<char*>("_ctx"), + const_cast<char*>("context"), 0 }; PyObject* response = Py_None; @@ -329,6 +368,26 @@ proxyIceIds(ProxyObject* self, PyObject* args) extern "C" #endif static PyObject* +proxyIceIdsAsync(ProxyObject* self, PyObject* args) +{ + PyObject* ctx = Py_None; + if(!PyArg_ParseTuple(args, STRCAST("|O!"), &PyDict_Type, &ctx)) + { + return 0; + } + + // + // We need to reformat the arguments to match what is used by the generated code: ((params...), ctx|None) + // + PyObjectHandle newArgs = Py_BuildValue(STRCAST("((), O)"), ctx); + + return invokeBuiltinAsync(reinterpret_cast<PyObject*>(self), "ice_ids", newArgs.get()); +} + +#ifdef WIN32 +extern "C" +#endif +static PyObject* proxyBeginIceIds(ProxyObject* self, PyObject* args, PyObject* kwds) { static char* argNames[] = @@ -336,7 +395,7 @@ proxyBeginIceIds(ProxyObject* self, PyObject* args, PyObject* kwds) const_cast<char*>("_response"), const_cast<char*>("_ex"), const_cast<char*>("_sent"), - const_cast<char*>("_ctx"), + const_cast<char*>("context"), 0 }; PyObject* response = Py_None; @@ -391,6 +450,26 @@ proxyIceId(ProxyObject* self, PyObject* args) extern "C" #endif static PyObject* +proxyIceIdAsync(ProxyObject* self, PyObject* args) +{ + PyObject* ctx = Py_None; + if(!PyArg_ParseTuple(args, STRCAST("|O!"), &PyDict_Type, &ctx)) + { + return 0; + } + + // + // We need to reformat the arguments to match what is used by the generated code: ((params...), ctx|None) + // + PyObjectHandle newArgs = Py_BuildValue(STRCAST("((), O)"), ctx); + + return invokeBuiltinAsync(reinterpret_cast<PyObject*>(self), "ice_id", newArgs.get()); +} + +#ifdef WIN32 +extern "C" +#endif +static PyObject* proxyBeginIceId(ProxyObject* self, PyObject* args, PyObject* kwds) { static char* argNames[] = @@ -398,7 +477,7 @@ proxyBeginIceId(ProxyObject* self, PyObject* args, PyObject* kwds) const_cast<char*>("_response"), const_cast<char*>("_ex"), const_cast<char*>("_sent"), - const_cast<char*>("_ctx"), + const_cast<char*>("context"), 0 }; PyObject* response = Py_None; @@ -716,22 +795,9 @@ proxyIceEndpoints(ProxyObject* self, PyObject* args) assert(self->proxy); Ice::EndpointSeq seq; - Py_ssize_t sz = PySequence_Fast_GET_SIZE(endpoints); - for(Py_ssize_t i = 0; i < sz; ++i) + if(!toEndpointSeq(endpoints, seq)) { - PyObject* p = PySequence_Fast_GET_ITEM(endpoints, i); - PyTypeObject* type = &EndpointType; // Necessary to prevent GCC's strict-alias warnings. - if(!PyObject_IsInstance(p, reinterpret_cast<PyObject*>(type))) - { - PyErr_Format(PyExc_ValueError, STRCAST("expected element of type Ice.Endpoint")); - return 0; - } - Ice::EndpointPtr endp = getEndpoint(p); - if(!endp) - { - return 0; - } - seq.push_back(endp); + return 0; } Ice::ObjectPrx newProxy; @@ -1598,8 +1664,8 @@ proxyIceTimeout(ProxyObject* self, PyObject* args) } catch(const IceUtil::IllegalArgumentException& ex) { - PyErr_Format(PyExc_RuntimeError, "%s", STRCAST(ex.reason().c_str())); - return 0; + PyErr_Format(PyExc_RuntimeError, "%s", STRCAST(ex.reason().c_str())); + return 0; } catch(const Ice::Exception& ex) { @@ -1735,6 +1801,51 @@ proxyIceGetConnection(ProxyObject* self) extern "C" #endif static PyObject* +proxyIceGetConnectionAsync(ProxyObject* self, PyObject* /*args*/, PyObject* /*kwds*/) +{ + assert(self->proxy); + const string op = "ice_getConnection"; + + GetConnectionAsyncCallbackPtr d = new GetConnectionAsyncCallback(*self->communicator, op); + Ice::Callback_Object_ice_getConnectionPtr cb = + Ice::newCallback_Object_ice_getConnection(d, &GetConnectionAsyncCallback::response, + &GetConnectionAsyncCallback::exception); + + Ice::AsyncResultPtr result; + + try + { + AllowThreads allowThreads; // Release Python's global interpreter lock during remote invocations. + + result = (*self->proxy)->begin_ice_getConnection(cb); + } + catch(const Ice::Exception& ex) + { + setPythonException(ex); + return 0; + } + + PyObjectHandle communicatorObj = getCommunicatorWrapper(*self->communicator); + PyObjectHandle asyncResultObj = + createAsyncResult(result, reinterpret_cast<PyObject*>(self), 0, communicatorObj.get()); + if(!asyncResultObj.get()) + { + return 0; + } + + PyObjectHandle future = createFuture(op, asyncResultObj.get()); + if(!future.get()) + { + return 0; + } + d->setFuture(future.get()); + return future.release(); +} + +#ifdef WIN32 +extern "C" +#endif +static PyObject* proxyBeginIceGetConnection(ProxyObject* self, PyObject* args, PyObject* kwds) { assert(self->proxy); @@ -1896,6 +2007,50 @@ proxyIceFlushBatchRequests(ProxyObject* self) extern "C" #endif static PyObject* +proxyIceFlushBatchRequestsAsync(ProxyObject* self, PyObject* /*args*/, PyObject* /*kwds*/) +{ + assert(self->proxy); + const string op = "ice_flushBatchRequests"; + + FlushAsyncCallbackPtr d = new FlushAsyncCallback(op); + Ice::Callback_Object_ice_flushBatchRequestsPtr cb = + Ice::newCallback_Object_ice_flushBatchRequests(d, &FlushAsyncCallback::exception, &FlushAsyncCallback::sent); + + Ice::AsyncResultPtr result; + + try + { + AllowThreads allowThreads; // Release Python's global interpreter lock during remote invocations. + + result = (*self->proxy)->begin_ice_flushBatchRequests(cb); + } + catch(const Ice::Exception& ex) + { + setPythonException(ex); + return 0; + } + + PyObjectHandle communicatorObj = getCommunicatorWrapper(*self->communicator); + PyObjectHandle asyncResultObj = + createAsyncResult(result, reinterpret_cast<PyObject*>(self), 0, communicatorObj.get()); + if(!asyncResultObj.get()) + { + return 0; + } + + PyObjectHandle future = createFuture(op, asyncResultObj.get()); + if(!future.get()) + { + return 0; + } + d->setFuture(future.get()); + return future.release(); +} + +#ifdef WIN32 +extern "C" +#endif +static PyObject* proxyBeginIceFlushBatchRequests(ProxyObject* self, PyObject* args, PyObject* kwds) { assert(self->proxy); @@ -2032,7 +2187,7 @@ AMI_Object_ice_flushBatchRequestsI::exception(const Ice::Exception& ex) ostringstream ostr; ostr << "AMI callback object for ice_flushBatchRequests does not define " << methodName << "()"; string str = ostr.str(); - PyErr_Warn(PyExc_RuntimeWarning, const_cast<char*>(str.c_str())); + PyErr_WarnEx(PyExc_RuntimeWarning, const_cast<char*>(str.c_str()), 1); } else { @@ -2083,6 +2238,15 @@ proxyIceInvoke(ProxyObject* self, PyObject* args) extern "C" #endif static PyObject* +proxyIceInvokeAsync(ProxyObject* self, PyObject* args, PyObject* /*kwds*/) +{ + return iceInvokeAsync(reinterpret_cast<PyObject*>(self), args); +} + +#ifdef WIN32 +extern "C" +#endif +static PyObject* proxyBeginIceInvoke(ProxyObject* self, PyObject* args, PyObject* kwds) { return beginIceInvoke(reinterpret_cast<PyObject*>(self), args, kwds); @@ -2160,9 +2324,9 @@ proxyIceCheckedCast(PyObject* type, PyObject* args) // PyObject* obj; char* id; - PyObject* facetOrCtx = 0; + PyObject* facetOrContext = 0; PyObject* ctx = 0; - if(!PyArg_ParseTuple(args, STRCAST("OsOO"), &obj, &id, &facetOrCtx, &ctx)) + if(!PyArg_ParseTuple(args, STRCAST("OsOO"), &obj, &id, &facetOrContext, &ctx)) { return 0; } @@ -2181,20 +2345,20 @@ proxyIceCheckedCast(PyObject* type, PyObject* args) PyObject* facet = 0; - if(checkString(facetOrCtx)) + if(checkString(facetOrContext)) { - facet = facetOrCtx; + facet = facetOrContext; } - else if(PyDict_Check(facetOrCtx)) + else if(PyDict_Check(facetOrContext)) { if(ctx != Py_None) { PyErr_Format(PyExc_ValueError, STRCAST("facet argument to checkedCast must be a string")); return 0; } - ctx = facetOrCtx; + ctx = facetOrContext; } - else if(facetOrCtx != Py_None) + else if(facetOrContext != Py_None) { PyErr_Format(PyExc_ValueError, STRCAST("second argument to checkedCast must be a facet or context")); return 0; @@ -2391,26 +2555,34 @@ static PyMethodDef ProxyMethods[] = PyDoc_STR(STRCAST("ice_toString() -> string")) }, { STRCAST("ice_isA"), reinterpret_cast<PyCFunction>(proxyIceIsA), METH_VARARGS, PyDoc_STR(STRCAST("ice_isA(type, [ctx]) -> bool")) }, + { STRCAST("ice_isAAsync"), reinterpret_cast<PyCFunction>(proxyIceIsAAsync), METH_VARARGS, + PyDoc_STR(STRCAST("ice_isAAsync(type, [ctx]) -> Ice.Future")) }, { STRCAST("begin_ice_isA"), reinterpret_cast<PyCFunction>(proxyBeginIceIsA), METH_VARARGS | METH_KEYWORDS, - PyDoc_STR(STRCAST("begin_ice_isA(type[, _response][, _ex][, _sent][, _ctx]) -> Ice.AsyncResult")) }, + PyDoc_STR(STRCAST("begin_ice_isA(type[, _response][, _ex][, _sent][, context]) -> Ice.AsyncResult")) }, { STRCAST("end_ice_isA"), reinterpret_cast<PyCFunction>(proxyEndIceIsA), METH_VARARGS, PyDoc_STR(STRCAST("end_ice_isA(Ice.AsyncResult) -> bool")) }, { STRCAST("ice_ping"), reinterpret_cast<PyCFunction>(proxyIcePing), METH_VARARGS, PyDoc_STR(STRCAST("ice_ping([ctx]) -> None")) }, + { STRCAST("ice_pingAsync"), reinterpret_cast<PyCFunction>(proxyIcePingAsync), METH_VARARGS, + PyDoc_STR(STRCAST("ice_pingAsync([ctx]) -> Ice.Future")) }, { STRCAST("begin_ice_ping"), reinterpret_cast<PyCFunction>(proxyBeginIcePing), METH_VARARGS | METH_KEYWORDS, - PyDoc_STR(STRCAST("begin_ice_ping([_response][, _ex][, _sent][, _ctx]) -> Ice.AsyncResult")) }, + PyDoc_STR(STRCAST("begin_ice_ping([_response][, _ex][, _sent][, context]) -> Ice.AsyncResult")) }, { STRCAST("end_ice_ping"), reinterpret_cast<PyCFunction>(proxyEndIcePing), METH_VARARGS, PyDoc_STR(STRCAST("end_ice_ping(Ice.AsyncResult) -> None")) }, { STRCAST("ice_ids"), reinterpret_cast<PyCFunction>(proxyIceIds), METH_VARARGS, PyDoc_STR(STRCAST("ice_ids([ctx]) -> list")) }, + { STRCAST("ice_idsAsync"), reinterpret_cast<PyCFunction>(proxyIceIdsAsync), METH_VARARGS, + PyDoc_STR(STRCAST("ice_idsAsync([ctx]) -> Ice.Future")) }, { STRCAST("begin_ice_ids"), reinterpret_cast<PyCFunction>(proxyBeginIceIds), METH_VARARGS | METH_KEYWORDS, - PyDoc_STR(STRCAST("begin_ice_ids([_response][, _ex][, _sent][, _ctx]) -> Ice.AsyncResult")) }, + PyDoc_STR(STRCAST("begin_ice_ids([_response][, _ex][, _sent][, context]) -> Ice.AsyncResult")) }, { STRCAST("end_ice_ids"), reinterpret_cast<PyCFunction>(proxyEndIceIds), METH_VARARGS, PyDoc_STR(STRCAST("end_ice_ids(Ice.AsyncResult) -> list")) }, { STRCAST("ice_id"), reinterpret_cast<PyCFunction>(proxyIceId), METH_VARARGS, PyDoc_STR(STRCAST("ice_id([ctx]) -> string")) }, + { STRCAST("ice_idAsync"), reinterpret_cast<PyCFunction>(proxyIceIdAsync), METH_VARARGS, + PyDoc_STR(STRCAST("ice_idAsync([ctx]) -> Ice.Future")) }, { STRCAST("begin_ice_id"), reinterpret_cast<PyCFunction>(proxyBeginIceId), METH_VARARGS | METH_KEYWORDS, - PyDoc_STR(STRCAST("begin_ice_id([_response][, _ex][, _sent][, _ctx]) -> Ice.AsyncResult")) }, + PyDoc_STR(STRCAST("begin_ice_id([_response][, _ex][, _sent][, context]) -> Ice.AsyncResult")) }, { STRCAST("end_ice_id"), reinterpret_cast<PyCFunction>(proxyEndIceId), METH_VARARGS, PyDoc_STR(STRCAST("end_ice_id(Ice.AsyncResult) -> string")) }, { STRCAST("ice_getIdentity"), reinterpret_cast<PyCFunction>(proxyIceGetIdentity), METH_NOARGS, @@ -2503,6 +2675,8 @@ static PyMethodDef ProxyMethods[] = PyDoc_STR(STRCAST("ice_connectionId(string) -> Ice.ObjectPrx")) }, { STRCAST("ice_getConnection"), reinterpret_cast<PyCFunction>(proxyIceGetConnection), METH_NOARGS, PyDoc_STR(STRCAST("ice_getConnection() -> Ice.Connection")) }, + { STRCAST("ice_getConnectionAsync"), reinterpret_cast<PyCFunction>(proxyIceGetConnectionAsync), + METH_NOARGS, PyDoc_STR(STRCAST("ice_getConnectionAsync() -> Ice.Future")) }, { STRCAST("begin_ice_getConnection"), reinterpret_cast<PyCFunction>(proxyBeginIceGetConnection), METH_VARARGS | METH_KEYWORDS, PyDoc_STR(STRCAST("begin_ice_getConnection([_response][, _ex]) -> Ice.AsyncResult")) }, { STRCAST("end_ice_getConnection"), reinterpret_cast<PyCFunction>(proxyEndIceGetConnection), METH_VARARGS, @@ -2511,18 +2685,22 @@ static PyMethodDef ProxyMethods[] = PyDoc_STR(STRCAST("ice_getCachedConnection() -> Ice.Connection")) }, { STRCAST("ice_flushBatchRequests"), reinterpret_cast<PyCFunction>(proxyIceFlushBatchRequests), METH_NOARGS, PyDoc_STR(STRCAST("ice_flushBatchRequests() -> void")) }, + { STRCAST("ice_flushBatchRequestsAsync"), reinterpret_cast<PyCFunction>(proxyIceFlushBatchRequestsAsync), + METH_NOARGS, PyDoc_STR(STRCAST("ice_flushBatchRequestsAsync() -> Ice.Future")) }, { STRCAST("begin_ice_flushBatchRequests"), reinterpret_cast<PyCFunction>(proxyBeginIceFlushBatchRequests), METH_VARARGS | METH_KEYWORDS, PyDoc_STR(STRCAST("begin_ice_flushBatchRequests([_ex][, _sent]) -> Ice.AsyncResult")) }, { STRCAST("end_ice_flushBatchRequests"), reinterpret_cast<PyCFunction>(proxyEndIceFlushBatchRequests), METH_VARARGS, PyDoc_STR(STRCAST("end_ice_flushBatchRequests(Ice.AsyncResult) -> void")) }, { STRCAST("ice_invoke"), reinterpret_cast<PyCFunction>(proxyIceInvoke), METH_VARARGS, PyDoc_STR(STRCAST("ice_invoke(operation, mode, inParams) -> bool, outParams")) }, + { STRCAST("ice_invokeAsync"), reinterpret_cast<PyCFunction>(proxyIceInvokeAsync), METH_VARARGS | METH_KEYWORDS, + PyDoc_STR(STRCAST("ice_invokeAsync(op, mode, inParams[, context]) -> Ice.Future")) }, { STRCAST("begin_ice_invoke"), reinterpret_cast<PyCFunction>(proxyBeginIceInvoke), METH_VARARGS | METH_KEYWORDS, - PyDoc_STR(STRCAST("begin_ice_invoke(op, mode, inParams[, _response][, _ex][, _sent][, _ctx]) -> Ice.AsyncResult")) }, + PyDoc_STR(STRCAST("begin_ice_invoke(op, mode, inParams[, _response][, _ex][, _sent][, context]) -> Ice.AsyncResult")) }, { STRCAST("end_ice_invoke"), reinterpret_cast<PyCFunction>(proxyEndIceInvoke), METH_VARARGS, PyDoc_STR(STRCAST("end_ice_invoke(Ice.AsyncResult) -> (bool, results)")) }, { STRCAST("ice_checkedCast"), reinterpret_cast<PyCFunction>(proxyIceCheckedCast), METH_VARARGS | METH_CLASS, - PyDoc_STR(STRCAST("ice_checkedCast(proxy, id[, facetOrCtx[, ctx]]) -> proxy")) }, + PyDoc_STR(STRCAST("ice_checkedCast(proxy, id[, facetOrContext[, context]]) -> proxy")) }, { STRCAST("ice_uncheckedCast"), reinterpret_cast<PyCFunction>(proxyIceUncheckedCast), METH_VARARGS | METH_CLASS, PyDoc_STR(STRCAST("ice_uncheckedCast(proxy) -> proxy")) }, { STRCAST("checkedCast"), reinterpret_cast<PyCFunction>(proxyCheckedCast), METH_VARARGS | METH_STATIC, diff --git a/python/modules/IcePy/Slice.cpp b/python/modules/IcePy/Slice.cpp index ed1e4155758..b87d7970d4a 100644 --- a/python/modules/IcePy/Slice.cpp +++ b/python/modules/IcePy/Slice.cpp @@ -16,6 +16,7 @@ #include <Slice/PythonUtil.h> #include <Slice/Util.h> #include <IceUtil/Options.h> +#include <IceUtil/ConsoleUtil.h> // // Python headers needed for PyEval_EvalCode. @@ -27,6 +28,7 @@ using namespace std; using namespace IcePy; using namespace Slice; using namespace Slice::Python; +using namespace IceUtilInternal; extern "C" PyObject* @@ -161,8 +163,10 @@ IcePy_loadSlice(PyObject* /*self*/, PyObject* args) ostringstream codeStream; IceUtilInternal::Output out(codeStream); out.setUseTab(false); + // - // Python magic comment to set the file encoding, it must be first or second line + // Emit a Python magic comment to set the file encoding. + // It must be the first or second line. // out << "# -*- coding: utf-8 -*-\n"; generate(u, all, checksum, includePaths, out); @@ -231,22 +235,22 @@ IcePy_compile(PyObject* /*self*/, PyObject* args) } catch(const std::exception& ex) { - getErrorStream() << argSeq[0] << ": error:" << ex.what() << endl; + consoleErr << argSeq[0] << ": error:" << ex.what() << endl; rc = EXIT_FAILURE; } catch(const std::string& msg) { - getErrorStream() << argSeq[0] << ": error:" << msg << endl; + consoleErr << argSeq[0] << ": error:" << msg << endl; rc = EXIT_FAILURE; } catch(const char* msg) { - getErrorStream() << argSeq[0] << ": error:" << msg << endl; + consoleErr << argSeq[0] << ": error:" << msg << endl; rc = EXIT_FAILURE; } catch(...) { - getErrorStream() << argSeq[0] << ": error:" << "unknown exception" << endl; + consoleErr << argSeq[0] << ": error:" << "unknown exception" << endl; rc = EXIT_FAILURE; } diff --git a/python/modules/IcePy/Types.cpp b/python/modules/IcePy/Types.cpp index f2072b87825..f01eaf22ac5 100644 --- a/python/modules/IcePy/Types.cpp +++ b/python/modules/IcePy/Types.cpp @@ -17,7 +17,9 @@ #include <Util.h> #include <IceUtil/InputUtil.h> #include <IceUtil/ScopedArray.h> +#include <Ice/InputStream.h> #include <Ice/LocalException.h> +#include <Ice/OutputStream.h> #include <Ice/SlicedData.h> #include <list> @@ -31,7 +33,10 @@ using namespace IceUtilInternal; typedef map<string, ClassInfoPtr> ClassInfoMap; static ClassInfoMap _classInfoMap; -typedef map<Ice::Int, ClassInfoPtr> CompactIdMap; +typedef map<string, ValueInfoPtr> ValueInfoMap; +static ValueInfoMap _valueInfoMap; + +typedef map<Ice::Int, ValueInfoPtr> CompactIdMap; static CompactIdMap _compactIdMap; typedef map<string, ProxyInfoPtr> ProxyInfoMap; @@ -51,23 +56,6 @@ public: }; static InfoMapDestroyer infoMapDestroyer; -class ReadObjectCallback : public Ice::ReadObjectCallback -{ -public: - - ReadObjectCallback(const ClassInfoPtr&, const UnmarshalCallbackPtr&, PyObject*, void*); - ~ReadObjectCallback(); - - virtual void invoke(const ::Ice::ObjectPtr&); - -private: - - ClassInfoPtr _info; - UnmarshalCallbackPtr _cb; - PyObject* _target; - void* _closure; -}; - struct TypeInfoObject { PyObject_HEAD @@ -84,7 +72,7 @@ extern PyTypeObject TypeInfoType; extern PyTypeObject ExceptionInfoType; bool -writeString(PyObject* p, const Ice::OutputStreamPtr& os) +writeString(PyObject* p, Ice::OutputStream* os) { if(p == Py_None) { @@ -224,6 +212,26 @@ addClassInfo(const string& id, const ClassInfoPtr& info) } // +// addValueInfo() +// +static void +addValueInfo(const string& id, const ValueInfoPtr& info) +{ + // + // Do not assert. An application may load statically- + // translated definitions and then dynamically load + // duplicate definitions. + // +// assert(_valueInfoMap.find(id) == _valueInfoMap.end()); + ValueInfoMap::iterator p = _valueInfoMap.find(id); + if(p != _valueInfoMap.end()) + { + _valueInfoMap.erase(p); + } + _valueInfoMap.insert(ValueInfoMap::value_type(id, info)); +} + +// // addProxyInfo() // static void @@ -273,16 +281,16 @@ addExceptionInfo(const string& id, const ExceptionInfoPtr& info) } // -// SlicedDataUtil implementation +// StreamUtil implementation // -PyObject* IcePy::SlicedDataUtil::_slicedDataType = 0; -PyObject* IcePy::SlicedDataUtil::_sliceInfoType = 0; +PyObject* IcePy::StreamUtil::_slicedDataType = 0; +PyObject* IcePy::StreamUtil::_sliceInfoType = 0; -IcePy::SlicedDataUtil::SlicedDataUtil() +IcePy::StreamUtil::StreamUtil() { } -IcePy::SlicedDataUtil::~SlicedDataUtil() +IcePy::StreamUtil::~StreamUtil() { // // Make sure we break any cycles among the ObjectReaders in preserved slices. @@ -293,35 +301,41 @@ IcePy::SlicedDataUtil::~SlicedDataUtil() for(Ice::SliceInfoSeq::const_iterator q = slicedData->slices.begin(); q != slicedData->slices.end(); ++q) { // - // Don't just call (*q)->objects.clear(), as releasing references - // to the objects could have unexpected side effects. We exchange + // Don't just call (*q)->instances.clear(), as releasing references + // to the instances could have unexpected side effects. We exchange // the vector into a temporary and then let the temporary fall out // of scope. // vector<Ice::ObjectPtr> tmp; - tmp.swap((*q)->objects); + tmp.swap((*q)->instances); } } } void -IcePy::SlicedDataUtil::add(const ObjectReaderPtr& reader) +IcePy::StreamUtil::add(const ReadObjectCallbackPtr& callback) +{ + _callbacks.push_back(callback); +} + +void +IcePy::StreamUtil::add(const ObjectReaderPtr& reader) { assert(reader->getSlicedData()); _readers.insert(reader); } void -IcePy::SlicedDataUtil::update() +IcePy::StreamUtil::updateSlicedData() { for(set<ObjectReaderPtr>::iterator p = _readers.begin(); p != _readers.end(); ++p) { - setMember((*p)->getObject(), (*p)->getSlicedData()); + setSlicedDataMember((*p)->getObject(), (*p)->getSlicedData()); } } void -IcePy::SlicedDataUtil::setMember(PyObject* obj, const Ice::SlicedDataPtr& slicedData) +IcePy::StreamUtil::setSlicedDataMember(PyObject* obj, const Ice::SlicedDataPtr& slicedData) { // // Create a Python equivalent of the SlicedData object. @@ -430,27 +444,27 @@ IcePy::SlicedDataUtil::setMember(PyObject* obj, const Ice::SlicedDataPtr& sliced } // - // objects + // instances // - PyObjectHandle objects = PyTuple_New((*p)->objects.size()); - if(!objects.get() || PyObject_SetAttrString(slice.get(), STRCAST("objects"), objects.get()) < 0) + PyObjectHandle instances = PyTuple_New((*p)->instances.size()); + if(!instances.get() || PyObject_SetAttrString(slice.get(), STRCAST("instances"), instances.get()) < 0) { assert(PyErr_Occurred()); throw AbortMarshaling(); } int j = 0; - for(vector<Ice::ObjectPtr>::iterator q = (*p)->objects.begin(); q != (*p)->objects.end(); ++q) + for(vector<Ice::ObjectPtr>::iterator q = (*p)->instances.begin(); q != (*p)->instances.end(); ++q) { // - // Each element in the objects list is an instance of ObjectReader that wraps a Python object. + // Each element in the instances list is an instance of ObjectReader that wraps a Python object. // assert(*q); ObjectReaderPtr r = ObjectReaderPtr::dynamicCast(*q); assert(r); PyObject* obj = r->getObject(); assert(obj != Py_None); // Should be non-nil. - PyTuple_SET_ITEM(objects.get(), j++, obj); + PyTuple_SET_ITEM(instances.get(), j++, obj); Py_INCREF(obj); // PyTuple_SET_ITEM steals a reference. } @@ -487,7 +501,7 @@ IcePy::SlicedDataUtil::setMember(PyObject* obj, const Ice::SlicedDataPtr& sliced // named _ice_slicedData which is an instance of the Python class Ice.SlicedData. // Ice::SlicedDataPtr -IcePy::SlicedDataUtil::getMember(PyObject* obj, ObjectMap* objectMap) +IcePy::StreamUtil::getSlicedDataMember(PyObject* obj, ObjectMap* objectMap) { Ice::SlicedDataPtr slicedData; @@ -537,20 +551,20 @@ IcePy::SlicedDataUtil::getMember(PyObject* obj, ObjectMap* objectMap) vector<Ice::Byte> vtmp(reinterpret_cast<Ice::Byte*>(str), reinterpret_cast<Ice::Byte*>(str + strsz)); info->bytes.swap(vtmp); - PyObjectHandle objects = PyObject_GetAttrString(s.get(), STRCAST("objects")); - assert(objects.get()); - assert(PyTuple_Check(objects.get())); - Py_ssize_t osz = PyTuple_GET_SIZE(objects.get()); + PyObjectHandle instances = PyObject_GetAttrString(s.get(), STRCAST("instances")); + assert(instances.get()); + assert(PyTuple_Check(instances.get())); + Py_ssize_t osz = PyTuple_GET_SIZE(instances.get()); for(Py_ssize_t j = 0; j < osz; ++j) { - PyObject* o = PyTuple_GET_ITEM(objects.get(), j); + PyObject* o = PyTuple_GET_ITEM(instances.get(), j); Ice::ObjectPtr writer; ObjectMap::iterator i = objectMap->find(o); if(i == objectMap->end()) { - writer = new ObjectWriter(o, objectMap); + writer = new ObjectWriter(o, objectMap, 0); objectMap->insert(ObjectMap::value_type(o, writer)); } else @@ -558,7 +572,7 @@ IcePy::SlicedDataUtil::getMember(PyObject* obj, ObjectMap* objectMap) writer = i->second; } - info->objects.push_back(writer); + info->instances.push_back(writer); } PyObjectHandle hasOptionalMembers = PyObject_GetAttrString(s.get(), STRCAST("hasOptionalMembers")); @@ -837,7 +851,7 @@ IcePy::PrimitiveInfo::optionalFormat() const } void -IcePy::PrimitiveInfo::marshal(PyObject* p, const Ice::OutputStreamPtr& os, ObjectMap*, bool, const Ice::StringSeq*) +IcePy::PrimitiveInfo::marshal(PyObject* p, Ice::OutputStream* os, ObjectMap*, bool, const Ice::StringSeq*) { switch(kind) { @@ -917,7 +931,7 @@ IcePy::PrimitiveInfo::marshal(PyObject* p, const Ice::OutputStreamPtr& os, Objec } void -IcePy::PrimitiveInfo::unmarshal(const Ice::InputStreamPtr& is, const UnmarshalCallbackPtr& cb, PyObject* target, +IcePy::PrimitiveInfo::unmarshal(Ice::InputStream* is, const UnmarshalCallbackPtr& cb, PyObject* target, void* closure, bool, const Ice::StringSeq*) { switch(kind) @@ -1078,7 +1092,7 @@ IcePy::EnumInfo::optionalFormat() const } void -IcePy::EnumInfo::marshal(PyObject* p, const Ice::OutputStreamPtr& os, ObjectMap*, bool optional, const Ice::StringSeq*) +IcePy::EnumInfo::marshal(PyObject* p, Ice::OutputStream* os, ObjectMap*, bool optional, const Ice::StringSeq*) { // // Validate value. @@ -1094,7 +1108,7 @@ IcePy::EnumInfo::marshal(PyObject* p, const Ice::OutputStreamPtr& os, ObjectMap* } void -IcePy::EnumInfo::unmarshal(const Ice::InputStreamPtr& is, const UnmarshalCallbackPtr& cb, PyObject* target, +IcePy::EnumInfo::unmarshal(Ice::InputStream* is, const UnmarshalCallbackPtr& cb, PyObject* target, void* closure, bool, const Ice::StringSeq*) { Ice::Int val = is->readEnum(maxValue); @@ -1194,7 +1208,7 @@ convertDataMembers(PyObject* members, DataMemberList& reqMembers, DataMemberList { PyObject* m = PyTuple_GET_ITEM(members, i); assert(PyTuple_Check(m)); - assert(PyTuple_GET_SIZE(m) == allowOptional ? 5 : 3); + assert(PyTuple_GET_SIZE(m) == (allowOptional ? 5 : 3)); PyObject* name = PyTuple_GET_ITEM(m, 0); // Member name. assert(checkString(name)); @@ -1332,7 +1346,7 @@ IcePy::StructInfo::usesClasses() const } void -IcePy::StructInfo::marshal(PyObject* p, const Ice::OutputStreamPtr& os, ObjectMap* objectMap, bool optional, +IcePy::StructInfo::marshal(PyObject* p, Ice::OutputStream* os, ObjectMap* objectMap, bool optional, const Ice::StringSeq*) { assert(p == Py_None || PyObject_IsInstance(p, pythonType.get()) == 1); // validate() should have caught this. @@ -1389,7 +1403,7 @@ IcePy::StructInfo::marshal(PyObject* p, const Ice::OutputStreamPtr& os, ObjectMa } void -IcePy::StructInfo::unmarshal(const Ice::InputStreamPtr& is, const UnmarshalCallbackPtr& cb, PyObject* target, +IcePy::StructInfo::unmarshal(Ice::InputStream* is, const UnmarshalCallbackPtr& cb, PyObject* target, void* closure, bool optional, const Ice::StringSeq*) { PyObjectHandle p = instantiate(pythonType.get()); @@ -1533,7 +1547,7 @@ IcePy::SequenceInfo::usesClasses() const } void -IcePy::SequenceInfo::marshal(PyObject* p, const Ice::OutputStreamPtr& os, ObjectMap* objectMap, bool optional, +IcePy::SequenceInfo::marshal(PyObject* p, Ice::OutputStream* os, ObjectMap* objectMap, bool optional, const Ice::StringSeq* metaData) { PrimitiveInfoPtr pi = PrimitiveInfoPtr::dynamicCast(elementType); @@ -1632,7 +1646,7 @@ IcePy::SequenceInfo::marshal(PyObject* p, const Ice::OutputStreamPtr& os, Object } void -IcePy::SequenceInfo::unmarshal(const Ice::InputStreamPtr& is, const UnmarshalCallbackPtr& cb, PyObject* target, +IcePy::SequenceInfo::unmarshal(Ice::InputStream* is, const UnmarshalCallbackPtr& cb, PyObject* target, void* closure, bool optional, const Ice::StringSeq* metaData) { if(optional) @@ -1777,7 +1791,7 @@ IcePy::SequenceInfo::getSequence(const PrimitiveInfoPtr& pi, PyObject* p) } void -IcePy::SequenceInfo::marshalPrimitiveSequence(const PrimitiveInfoPtr& pi, PyObject* p, const Ice::OutputStreamPtr& os) +IcePy::SequenceInfo::marshalPrimitiveSequence(const PrimitiveInfoPtr& pi, PyObject* p, Ice::OutputStream* os) { // // For most types, we accept an object that implements the buffer protocol @@ -2080,7 +2094,7 @@ IcePy::SequenceInfo::marshalPrimitiveSequence(const PrimitiveInfoPtr& pi, PyObje } void -IcePy::SequenceInfo::unmarshalPrimitiveSequence(const PrimitiveInfoPtr& pi, const Ice::InputStreamPtr& is, +IcePy::SequenceInfo::unmarshalPrimitiveSequence(const PrimitiveInfoPtr& pi, Ice::InputStream* is, const UnmarshalCallbackPtr& cb, PyObject* target, void* closure, const SequenceMappingPtr& sm) { @@ -2434,7 +2448,7 @@ IcePy::CustomInfo::usesClasses() const } void -IcePy::CustomInfo::marshal(PyObject* p, const Ice::OutputStreamPtr& os, ObjectMap* objectMap, bool, +IcePy::CustomInfo::marshal(PyObject* p, Ice::OutputStream* os, ObjectMap* objectMap, bool, const Ice::StringSeq* metaData) { assert(PyObject_IsInstance(p, pythonType.get()) == 1); // validate() should have caught this. @@ -2469,7 +2483,7 @@ IcePy::CustomInfo::marshal(PyObject* p, const Ice::OutputStreamPtr& os, ObjectMa } void -IcePy::CustomInfo::unmarshal(const Ice::InputStreamPtr& is, const UnmarshalCallbackPtr& cb, PyObject* target, +IcePy::CustomInfo::unmarshal(Ice::InputStream* is, const UnmarshalCallbackPtr& cb, PyObject* target, void* closure, bool, const Ice::StringSeq* metaData) { // @@ -2606,7 +2620,7 @@ IcePy::DictionaryInfo::usesClasses() const } void -IcePy::DictionaryInfo::marshal(PyObject* p, const Ice::OutputStreamPtr& os, ObjectMap* objectMap, bool optional, +IcePy::DictionaryInfo::marshal(PyObject* p, Ice::OutputStream* os, ObjectMap* objectMap, bool optional, const Ice::StringSeq*) { if(p != Py_None && !PyDict_Check(p)) @@ -2666,7 +2680,7 @@ IcePy::DictionaryInfo::marshal(PyObject* p, const Ice::OutputStreamPtr& os, Obje } void -IcePy::DictionaryInfo::unmarshal(const Ice::InputStreamPtr& is, const UnmarshalCallbackPtr& cb, PyObject* target, +IcePy::DictionaryInfo::unmarshal(Ice::InputStream* is, const UnmarshalCallbackPtr& cb, PyObject* target, void* closure, bool optional, const Ice::StringSeq*) { if(optional) @@ -2799,21 +2813,16 @@ IcePy::DictionaryInfo::destroy() // ClassInfo implementation. // IcePy::ClassInfo::ClassInfo(const string& ident) : - id(ident), compactId(-1), isAbstract(false), preserve(false), defined(false) + id(ident), defined(false) { const_cast<PyObjectHandle&>(typeObj) = createType(this); } void -IcePy::ClassInfo::define(PyObject* t, int compact, bool abstr, bool pres, PyObject* b, PyObject* i, PyObject* m) +IcePy::ClassInfo::define(PyObject* t, PyObject* b, PyObject* i) { assert(PyType_Check(t)); assert(PyTuple_Check(i)); - assert(PyTuple_Check(m)); - - const_cast<int&>(compactId) = compact; - const_cast<bool&>(isAbstract) = abstr; - const_cast<bool&>(preserve) = pres; if(b != Py_None) { @@ -2831,8 +2840,6 @@ IcePy::ClassInfo::define(PyObject* t, int compact, bool abstr, bool pres, PyObje const_cast<ClassInfoList&>(interfaces).push_back(iface); } - convertDataMembers(m, const_cast<DataMemberList&>(members), const_cast<DataMemberList&>(optionalMembers), true); - const_cast<PyObjectHandle&>(pythonType) = t; Py_INCREF(t); @@ -2848,12 +2855,14 @@ IcePy::ClassInfo::getId() const bool IcePy::ClassInfo::validate(PyObject* val) { - return val == Py_None || PyObject_IsInstance(val, pythonType.get()) == 1; + assert(false); + return true; } bool IcePy::ClassInfo::variableLength() const { + assert(false); return true; } @@ -2876,7 +2885,145 @@ IcePy::ClassInfo::usesClasses() const } void -IcePy::ClassInfo::marshal(PyObject* p, const Ice::OutputStreamPtr& os, ObjectMap* objectMap, bool, +IcePy::ClassInfo::marshal(PyObject* p, Ice::OutputStream* os, ObjectMap* objectMap, bool, + const Ice::StringSeq*) +{ + assert(false); + throw AbortMarshaling(); +} + +void +IcePy::ClassInfo::unmarshal(Ice::InputStream* is, const UnmarshalCallbackPtr& cb, PyObject* target, + void* closure, bool, const Ice::StringSeq*) +{ + assert(false); + throw AbortMarshaling(); +} + +void +IcePy::ClassInfo::print(PyObject* value, IceUtilInternal::Output& out, PrintObjectHistory* history) +{ + if(!validate(value)) + { + out << "<invalid value - expected " << id << ">"; + return; + } + + if(value == Py_None) + { + out << "<nil>"; + } + else + { + map<PyObject*, int>::iterator q = history->objects.find(value); + if(q != history->objects.end()) + { + out << "<object #" << q->second << ">"; + } + else + { + PyObjectHandle iceType = PyObject_GetAttrString(value, STRCAST("_ice_type")); + ClassInfoPtr info; + if(!iceType.get()) + { + // + // The _ice_type attribute will be missing in an instance of LocalObject + // that does not derive from a user-defined type. + // + assert(id == "::Ice::LocalObject"); + info = this; + } + else + { + info = ClassInfoPtr::dynamicCast(getType(iceType.get())); + assert(info); + } + out << "object #" << history->index << " (" << info->id << ')'; + history->objects.insert(map<PyObject*, int>::value_type(value, history->index)); + ++history->index; + } + } +} + +void +IcePy::ClassInfo::destroy() +{ + const_cast<ClassInfoPtr&>(base) = 0; + const_cast<ClassInfoList&>(interfaces).clear(); + const_cast<PyObjectHandle&>(typeObj) = 0; // Break circular reference. +} + +// +// ValueInfo implementation. +// +IcePy::ValueInfo::ValueInfo(const string& ident) : + id(ident), compactId(-1), preserve(false), interface(false), defined(false) +{ + const_cast<PyObjectHandle&>(typeObj) = createType(this); +} + +void +IcePy::ValueInfo::define(PyObject* t, int compact, bool pres, bool intf, PyObject* b, PyObject* m) +{ + assert(PyType_Check(t)); + assert(PyTuple_Check(m)); + + const_cast<int&>(compactId) = compact; + const_cast<bool&>(preserve) = pres; + const_cast<bool&>(interface) = intf; + + if(b != Py_None) + { + const_cast<ValueInfoPtr&>(base) = ValueInfoPtr::dynamicCast(getType(b)); + assert(base); + } + + convertDataMembers(m, const_cast<DataMemberList&>(members), const_cast<DataMemberList&>(optionalMembers), true); + + const_cast<PyObjectHandle&>(pythonType) = t; + Py_INCREF(t); + + const_cast<bool&>(defined) = true; +} + +string +IcePy::ValueInfo::getId() const +{ + return id; +} + +bool +IcePy::ValueInfo::validate(PyObject* val) +{ + return val == Py_None || PyObject_IsInstance(val, pythonType.get()) == 1; +} + +bool +IcePy::ValueInfo::variableLength() const +{ + return true; +} + +int +IcePy::ValueInfo::wireSize() const +{ + return 1; +} + +Ice::OptionalFormat +IcePy::ValueInfo::optionalFormat() const +{ + return Ice::OptionalFormatClass; +} + +bool +IcePy::ValueInfo::usesClasses() const +{ + return true; +} + +void +IcePy::ValueInfo::marshal(PyObject* p, Ice::OutputStream* os, ObjectMap* objectMap, bool, const Ice::StringSeq*) { if(!pythonType.get()) @@ -2887,7 +3034,8 @@ IcePy::ClassInfo::marshal(PyObject* p, const Ice::OutputStreamPtr& os, ObjectMap if(p == Py_None) { - os->writeObject(0); + Ice::ObjectPtr nil; + os->write(nil); return; } @@ -2908,7 +3056,7 @@ IcePy::ClassInfo::marshal(PyObject* p, const Ice::OutputStreamPtr& os, ObjectMap ObjectMap::iterator q = objectMap->find(p); if(q == objectMap->end()) { - writer = new ObjectWriter(p, objectMap); + writer = new ObjectWriter(p, objectMap, this); objectMap->insert(ObjectMap::value_type(p, writer)); } else @@ -2919,11 +3067,24 @@ IcePy::ClassInfo::marshal(PyObject* p, const Ice::OutputStreamPtr& os, ObjectMap // // Give the writer to the stream. The stream will eventually call write() on it. // - os->writeObject(writer); + os->write(writer); +} + +namespace +{ + +void +patchObject(void* addr, const Ice::ObjectPtr& v) +{ + ReadObjectCallback* cb = static_cast<ReadObjectCallback*>(addr); + assert(cb); + cb->invoke(v); +} + } void -IcePy::ClassInfo::unmarshal(const Ice::InputStreamPtr& is, const UnmarshalCallbackPtr& cb, PyObject* target, +IcePy::ValueInfo::unmarshal(Ice::InputStream* is, const UnmarshalCallbackPtr& cb, PyObject* target, void* closure, bool, const Ice::StringSeq*) { if(!pythonType.get()) @@ -2932,11 +3093,20 @@ IcePy::ClassInfo::unmarshal(const Ice::InputStreamPtr& is, const UnmarshalCallba throw AbortMarshaling(); } - is->readObject(new ReadObjectCallback(this, cb, target, closure)); + // + // This callback is notified when the Slice value is actually read. The StreamUtil object + // attached to the stream keeps a reference to the callback object to ensure it lives + // long enough. + // + ReadObjectCallbackPtr rocb = new ReadObjectCallback(this, cb, target, closure); + StreamUtil* util = reinterpret_cast<StreamUtil*>(is->getClosure()); + assert(util); + util->add(rocb); + is->read(patchObject, rocb.get()); } void -IcePy::ClassInfo::print(PyObject* value, IceUtilInternal::Output& out, PrintObjectHistory* history) +IcePy::ValueInfo::print(PyObject* value, IceUtilInternal::Output& out, PrintObjectHistory* history) { if(!validate(value)) { @@ -2958,7 +3128,7 @@ IcePy::ClassInfo::print(PyObject* value, IceUtilInternal::Output& out, PrintObje else { PyObjectHandle iceType = PyObject_GetAttrString(value, STRCAST("_ice_type")); - ClassInfoPtr info; + ValueInfoPtr info; if(!iceType.get()) { // @@ -2970,7 +3140,7 @@ IcePy::ClassInfo::print(PyObject* value, IceUtilInternal::Output& out, PrintObje } else { - info = ClassInfoPtr::dynamicCast(getType(iceType.get())); + info = ValueInfoPtr::dynamicCast(getType(iceType.get())); assert(info); } out << "object #" << history->index << " (" << info->id << ')'; @@ -2984,10 +3154,9 @@ IcePy::ClassInfo::print(PyObject* value, IceUtilInternal::Output& out, PrintObje } void -IcePy::ClassInfo::destroy() +IcePy::ValueInfo::destroy() { - const_cast<ClassInfoPtr&>(base) = 0; - const_cast<ClassInfoList&>(interfaces).clear(); + const_cast<ValueInfoPtr&>(base) = 0; if(!members.empty()) { DataMemberList ml = members; @@ -3001,7 +3170,7 @@ IcePy::ClassInfo::destroy() } void -IcePy::ClassInfo::printMembers(PyObject* value, IceUtilInternal::Output& out, PrintObjectHistory* history) +IcePy::ValueInfo::printMembers(PyObject* value, IceUtilInternal::Output& out, PrintObjectHistory* history) { if(base) { @@ -3094,7 +3263,7 @@ IcePy::ProxyInfo::optionalFormat() const } void -IcePy::ProxyInfo::marshal(PyObject* p, const Ice::OutputStreamPtr& os, ObjectMap*, bool optional, const Ice::StringSeq*) +IcePy::ProxyInfo::marshal(PyObject* p, Ice::OutputStream* os, ObjectMap*, bool optional, const Ice::StringSeq*) { Ice::OutputStream::size_type sizePos = 0; if(optional) @@ -3122,7 +3291,7 @@ IcePy::ProxyInfo::marshal(PyObject* p, const Ice::OutputStreamPtr& os, ObjectMap } void -IcePy::ProxyInfo::unmarshal(const Ice::InputStreamPtr& is, const UnmarshalCallbackPtr& cb, PyObject* target, +IcePy::ProxyInfo::unmarshal(Ice::InputStream* is, const UnmarshalCallbackPtr& cb, PyObject* target, void* closure, bool optional, const Ice::StringSeq*) { if(optional) @@ -3145,7 +3314,7 @@ IcePy::ProxyInfo::unmarshal(const Ice::InputStreamPtr& is, const UnmarshalCallba throw AbortMarshaling(); } - PyObjectHandle p = createProxy(proxy, is->communicator(), pythonType.get()); + PyObjectHandle p = createProxy(proxy, proxy->ice_getCommunicator(), pythonType.get()); cb->unmarshaled(p.get(), target, closure); } @@ -3183,19 +3352,21 @@ IcePy::ProxyInfo::destroy() // // ObjectWriter implementation. // -IcePy::ObjectWriter::ObjectWriter(PyObject* object, ObjectMap* objectMap) : - _object(object), _map(objectMap) +IcePy::ObjectWriter::ObjectWriter(PyObject* object, ObjectMap* objectMap, const ValueInfoPtr& formal) : + _object(object), _map(objectMap), _formal(formal) { Py_INCREF(_object); - - PyObjectHandle iceType = PyObject_GetAttrString(object, STRCAST("_ice_type")); - if(!iceType.get()) + if(!_formal || !_formal->interface) { - assert(PyErr_Occurred()); - throw AbortMarshaling(); + PyObjectHandle iceType = PyObject_GetAttrString(object, STRCAST("_ice_type")); + if(!iceType.get()) + { + assert(PyErr_Occurred()); + throw AbortMarshaling(); + } + _info = ValueInfoPtr::dynamicCast(getType(iceType.get())); + assert(_info); } - _info = ClassInfoPtr::dynamicCast(getType(iceType.get())); - assert(_info); } IcePy::ObjectWriter::~ObjectWriter() @@ -3218,41 +3389,62 @@ IcePy::ObjectWriter::ice_preMarshal() } void -IcePy::ObjectWriter::write(const Ice::OutputStreamPtr& os) const +IcePy::ObjectWriter::_iceWrite(Ice::OutputStream* os) const { Ice::SlicedDataPtr slicedData; - if(_info->preserve) + if(_info && _info->preserve) { // // Retrieve the SlicedData object that we stored as a hidden member of the Python object. // - slicedData = SlicedDataUtil::getMember(_object, const_cast<ObjectMap*>(_map)); + slicedData = StreamUtil::getSlicedDataMember(_object, const_cast<ObjectMap*>(_map)); } - os->startObject(slicedData); + os->startValue(slicedData); - if(_info->id != "::Ice::UnknownSlicedObject") + if(_formal && _formal->interface) { - ClassInfoPtr info = _info; - while(info) + PyObjectHandle ret = PyObject_CallMethod(_object, STRCAST("ice_id"), 0); + if(!ret.get()) + { + assert(PyErr_Occurred()); + throw AbortMarshaling(); + } + string id = getString(ret.get()); + os->startSlice(id, -1, true); + os->endSlice(); + } + else + { + if(_info->id != "::Ice::UnknownSlicedValue") { - os->startSlice(info->id, info->compactId, !info->base); + ValueInfoPtr info = _info; + while(info) + { + os->startSlice(info->id, info->compactId, !info->base); - writeMembers(os, info->members); - writeMembers(os, info->optionalMembers); // The optional members have already been sorted by tag. + writeMembers(os, info->members); + writeMembers(os, info->optionalMembers); // The optional members have already been sorted by tag. - os->endSlice(); + os->endSlice(); - info = info->base; + info = info->base; + } } } - os->endObject(); + os->endValue(); } void -IcePy::ObjectWriter::writeMembers(const Ice::OutputStreamPtr& os, const DataMemberList& members) const +IcePy::ObjectWriter::_iceRead(Ice::InputStream*) +{ + assert(false); +} + +void +IcePy::ObjectWriter::writeMembers(Ice::OutputStream* os, const DataMemberList& members) const { for(DataMemberList::const_iterator q = members.begin(); q != members.end(); ++q) { @@ -3295,7 +3487,7 @@ IcePy::ObjectWriter::writeMembers(const Ice::OutputStreamPtr& os, const DataMemb // // ObjectReader implementation. // -IcePy::ObjectReader::ObjectReader(PyObject* object, const ClassInfoPtr& info) : +IcePy::ObjectReader::ObjectReader(PyObject* object, const ValueInfoPtr& info) : _object(object), _info(info) { Py_INCREF(_object); @@ -3321,18 +3513,24 @@ IcePy::ObjectReader::ice_postUnmarshal() } void -IcePy::ObjectReader::read(const Ice::InputStreamPtr& is) +IcePy::ObjectReader::_iceWrite(Ice::OutputStream*) const { - is->startObject(); + assert(false); +} - const bool unknown = _info->id == "::Ice::UnknownSlicedObject"; +void +IcePy::ObjectReader::_iceRead(Ice::InputStream* is) +{ + is->startValue(); + + const bool unknown = _info->id == "::Ice::UnknownSlicedValue"; // // Unmarshal the slices of a user-defined class. // if(!unknown && _info->id != Ice::Object::ice_staticId()) { - ClassInfoPtr info = _info; + ValueInfoPtr info = _info; while(info) { is->startSlice(); @@ -3368,11 +3566,11 @@ IcePy::ObjectReader::read(const Ice::InputStreamPtr& is) } } - _slicedData = is->endObject(_info->preserve); + _slicedData = is->endValue(_info->preserve); if(_slicedData) { - SlicedDataUtil* util = reinterpret_cast<SlicedDataUtil*>(is->closure()); + StreamUtil* util = reinterpret_cast<StreamUtil*>(is->getClosure()); assert(util); util->add(this); @@ -3393,7 +3591,7 @@ IcePy::ObjectReader::read(const Ice::InputStreamPtr& is) } } -ClassInfoPtr +ValueInfoPtr IcePy::ObjectReader::getInfo() const { return _info; @@ -3428,6 +3626,12 @@ IcePy::InfoMapDestroyer::~InfoMapDestroyer() p->second->destroy(); } } + { + for(ValueInfoMap::iterator p = _valueInfoMap.begin(); p != _valueInfoMap.end(); ++p) + { + p->second->destroy(); + } + } _compactIdMap.clear(); _exceptionInfoMap.clear(); } @@ -3435,7 +3639,7 @@ IcePy::InfoMapDestroyer::~InfoMapDestroyer() // // ReadObjectCallback implementation. // -IcePy::ReadObjectCallback::ReadObjectCallback(const ClassInfoPtr& info, const UnmarshalCallbackPtr& cb, +IcePy::ReadObjectCallback::ReadObjectCallback(const ValueInfoPtr& info, const UnmarshalCallbackPtr& cb, PyObject* target, void* closure) : _info(info), _cb(cb), _target(target), _closure(closure) { @@ -3480,7 +3684,7 @@ IcePy::ReadObjectCallback::invoke(const Ice::ObjectPtr& p) // ExceptionInfo implementation. // void -IcePy::ExceptionInfo::marshal(PyObject* p, const Ice::OutputStreamPtr& os, ObjectMap* objectMap) +IcePy::ExceptionInfo::marshal(PyObject* p, Ice::OutputStream* os, ObjectMap* objectMap) { if(!PyObject_IsInstance(p, pythonType.get())) { @@ -3495,7 +3699,7 @@ IcePy::ExceptionInfo::marshal(PyObject* p, const Ice::OutputStreamPtr& os, Objec // // Retrieve the SlicedData object that we stored as a hidden member of the Python object. // - slicedData = SlicedDataUtil::getMember(p, objectMap); + slicedData = StreamUtil::getSlicedDataMember(p, objectMap); } os->startException(slicedData); @@ -3517,7 +3721,7 @@ IcePy::ExceptionInfo::marshal(PyObject* p, const Ice::OutputStreamPtr& os, Objec } void -IcePy::ExceptionInfo::writeMembers(PyObject* p, const Ice::OutputStreamPtr& os, const DataMemberList& members, +IcePy::ExceptionInfo::writeMembers(PyObject* p, Ice::OutputStream* os, const DataMemberList& members, ObjectMap* objectMap) const { for(DataMemberList::const_iterator q = members.begin(); q != members.end(); ++q) @@ -3559,7 +3763,7 @@ IcePy::ExceptionInfo::writeMembers(PyObject* p, const Ice::OutputStreamPtr& os, } PyObject* -IcePy::ExceptionInfo::unmarshal(const Ice::InputStreamPtr& is) +IcePy::ExceptionInfo::unmarshal(Ice::InputStream* is) { PyObjectHandle p = createExceptionInstance(pythonType.get()); @@ -3669,9 +3873,8 @@ IcePy::ExceptionInfo::printMembers(PyObject* value, IceUtilInternal::Output& out // // ExceptionWriter implementation. // -IcePy::ExceptionWriter::ExceptionWriter(const Ice::CommunicatorPtr& communicator, const PyObjectHandle& ex, - const ExceptionInfoPtr& info) : - Ice::UserExceptionWriter(communicator), _ex(ex), _info(info) +IcePy::ExceptionWriter::ExceptionWriter(const PyObjectHandle& ex, const ExceptionInfoPtr& info) : + _ex(ex), _info(info) { if(!info) { @@ -3689,31 +3892,19 @@ IcePy::ExceptionWriter::~ExceptionWriter() throw() _ex = 0; } -void -IcePy::ExceptionWriter::write(const Ice::OutputStreamPtr& os) const -{ - AdoptThread adoptThread; // Ensure the current thread is able to call into Python. - - _info->marshal(_ex.get(), os, const_cast<ObjectMap*>(&_objects)); -} - -bool -IcePy::ExceptionWriter::usesClasses() const -{ - return _info->usesClasses; -} - string -IcePy::ExceptionWriter::ice_name() const +IcePy::ExceptionWriter::ice_id() const { return _info->id; } +#ifndef ICE_CPP11_MAPPING Ice::UserException* IcePy::ExceptionWriter::ice_clone() const { return new ExceptionWriter(*this); } +#endif void IcePy::ExceptionWriter::ice_throw() const @@ -3721,51 +3912,54 @@ IcePy::ExceptionWriter::ice_throw() const throw *this; } -// -// ExceptionReader implementation. -// -IcePy::ExceptionReader::ExceptionReader(const Ice::CommunicatorPtr& communicator, const ExceptionInfoPtr& info) : - Ice::UserExceptionReader(communicator), _info(info) -{ -} - -IcePy::ExceptionReader::~ExceptionReader() throw() +void +IcePy::ExceptionWriter::_write(Ice::OutputStream* os) const { AdoptThread adoptThread; // Ensure the current thread is able to call into Python. - _ex = 0; + _info->marshal(_ex.get(), os, const_cast<ObjectMap*>(&_objects)); } void -IcePy::ExceptionReader::read(const Ice::InputStreamPtr& is) const +IcePy::ExceptionWriter::_read(Ice::InputStream*) { - AdoptThread adoptThread; // Ensure the current thread is able to call into Python. - - is->startException(); - - const_cast<PyObjectHandle&>(_ex) = _info->unmarshal(is); - - const_cast<Ice::SlicedDataPtr&>(_slicedData) = is->endException(_info->preserve); } bool -IcePy::ExceptionReader::usesClasses() const +IcePy::ExceptionWriter::_usesClasses() const { return _info->usesClasses; } +// +// ExceptionReader implementation. +// +IcePy::ExceptionReader::ExceptionReader(const ExceptionInfoPtr& info) : + _info(info) +{ +} + +IcePy::ExceptionReader::~ExceptionReader() throw() +{ + AdoptThread adoptThread; // Ensure the current thread is able to call into Python. + + _ex = 0; +} + string -IcePy::ExceptionReader::ice_name() const +IcePy::ExceptionReader::ice_id() const { return _info->id; } +#ifndef ICE_CPP11_MAPPING Ice::UserException* IcePy::ExceptionReader::ice_clone() const { assert(false); return 0; } +#endif void IcePy::ExceptionReader::ice_throw() const @@ -3773,6 +3967,30 @@ IcePy::ExceptionReader::ice_throw() const throw *this; } +void +IcePy::ExceptionReader::_write(Ice::OutputStream*) const +{ + assert(false); +} + +void +IcePy::ExceptionReader::_read(Ice::InputStream* is) +{ + AdoptThread adoptThread; // Ensure the current thread is able to call into Python. + + is->startException(); + + const_cast<PyObjectHandle&>(_ex) = _info->unmarshal(is); + + const_cast<Ice::SlicedDataPtr&>(_slicedData) = is->endException(_info->preserve); +} + +bool +IcePy::ExceptionReader::_usesClasses() const +{ + return _info->usesClasses; +} + PyObject* IcePy::ExceptionReader::getException() const { @@ -3814,6 +4032,20 @@ IcePy::lookupClassInfo(const string& id) } // +// lookupClassInfo() +// +IcePy::ValueInfoPtr +IcePy::lookupValueInfo(const string& id) +{ + ValueInfoMap::iterator p = _valueInfoMap.find(id); + if(p != _valueInfoMap.end()) + { + return p->second; + } + return 0; +} + +// // lookupExceptionInfo() // IcePy::ExceptionInfoPtr @@ -4310,15 +4542,10 @@ IcePy_defineClass(PyObject*, PyObject* args) { char* id; PyObject* type; - int compactId; PyObject* meta; // Not currently used. - int isAbstract; - int preserve; PyObject* base; PyObject* interfaces; - PyObject* members; - if(!PyArg_ParseTuple(args, STRCAST("sOiOiiOOO"), &id, &type, &compactId, &meta, &isAbstract, &preserve, &base, - &interfaces, &members)) + if(!PyArg_ParseTuple(args, STRCAST("sOOOO"), &id, &type, &meta, &base, &interfaces)) { return 0; } @@ -4337,15 +4564,76 @@ IcePy_defineClass(PyObject*, PyObject* args) addClassInfo(id, info); } - info->define(type, compactId, isAbstract ? true : false, preserve ? true : false, base, interfaces, members); + info->define(type, base, interfaces); + + Py_INCREF(info->typeObj.get()); + return info->typeObj.get(); +} - CompactIdMap::iterator q = _compactIdMap.find(info->compactId); - if(q != _compactIdMap.end()) +extern "C" +PyObject* +IcePy_declareValue(PyObject*, PyObject* args) +{ + char* id; + if(!PyArg_ParseTuple(args, STRCAST("s"), &id)) { - _compactIdMap.erase(q); + return 0; } - _compactIdMap.insert(CompactIdMap::value_type(info->compactId, info)); + ValueInfoPtr info = lookupValueInfo(id); + if(!info) + { + info = new ValueInfo(id); + addValueInfo(id, info); + } + + Py_INCREF(info->typeObj.get()); + return info->typeObj.get(); +} + +extern "C" +PyObject* +IcePy_defineValue(PyObject*, PyObject* args) +{ + char* id; + PyObject* type; + int compactId; + PyObject* meta; // Not currently used. + int preserve; + int interface; + PyObject* base; + PyObject* members; + if(!PyArg_ParseTuple(args, STRCAST("sOiOiiOO"), &id, &type, &compactId, &meta, &preserve, &interface, &base, + &members)) + { + return 0; + } + + assert(PyTuple_Check(meta)); + + // + // A ClassInfo object will already exist for this id if a forward declaration + // was encountered, or if the Slice definition is being reloaded. In the latter + // case, we act as if it hasn't been defined yet. + // + ValueInfoPtr info = lookupValueInfo(id); + if(!info || info->defined) + { + info = new ValueInfo(id); + addValueInfo(id, info); + } + + info->define(type, compactId, preserve ? true : false, interface ? true : false, base, members); + + if(info->compactId != -1) + { + CompactIdMap::iterator q = _compactIdMap.find(info->compactId); + if(q != _compactIdMap.end()) + { + _compactIdMap.erase(q); + } + _compactIdMap.insert(CompactIdMap::value_type(info->compactId, info)); + } Py_INCREF(info->typeObj.get()); return info->typeObj.get(); } diff --git a/python/modules/IcePy/Types.h b/python/modules/IcePy/Types.h index a19b0d69459..eb122bc6171 100644 --- a/python/modules/IcePy/Types.h +++ b/python/modules/IcePy/Types.h @@ -12,7 +12,9 @@ #include <Config.h> #include <Util.h> -#include <Ice/Stream.h> +#include <Ice/FactoryTable.h> +#include <Ice/Object.h> +#include <Ice/SlicedDataF.h> #include <IceUtil/OutputUtil.h> #include <set> @@ -28,6 +30,10 @@ class ClassInfo; typedef IceUtil::Handle<ClassInfo> ClassInfoPtr; typedef std::vector<ClassInfoPtr> ClassInfoList; + +class ValueInfo; +typedef IceUtil::Handle<ValueInfo> ValueInfoPtr; + // // This class is raised as an exception when object marshaling needs to be aborted. // @@ -41,37 +47,6 @@ class ObjectReader; typedef IceUtil::Handle<ObjectReader> ObjectReaderPtr; // -// This class keeps track of Python objects (instances of Slice classes -// and exceptions) that have preserved slices. -// -class SlicedDataUtil -{ -public: - - SlicedDataUtil(); - ~SlicedDataUtil(); - - void add(const ObjectReaderPtr&); - - void update(); - - static void setMember(PyObject*, const Ice::SlicedDataPtr&); - static Ice::SlicedDataPtr getMember(PyObject*, ObjectMap*); - -private: - - std::set<ObjectReaderPtr> _readers; - static PyObject* _slicedDataType; - static PyObject* _sliceInfoType; -}; - -struct PrintObjectHistory -{ - int index; - std::map<PyObject*, int> objects; -}; - -// // The delayed nature of class unmarshaling in the Ice protocol requires us to // handle unmarshaling using a callback strategy. An instance of UnmarshalCallback // is supplied to each type's unmarshal() member function. For all types except @@ -95,6 +70,71 @@ public: typedef IceUtil::Handle<UnmarshalCallback> UnmarshalCallbackPtr; // +// ReadObjectCallback retains all of the information necessary to store an unmarshaled +// Slice value as a Python object. +// +class ReadObjectCallback : public IceUtil::Shared +{ +public: + + ReadObjectCallback(const ValueInfoPtr&, const UnmarshalCallbackPtr&, PyObject*, void*); + ~ReadObjectCallback(); + + void invoke(const ::Ice::ObjectPtr&); + +private: + + ValueInfoPtr _info; + UnmarshalCallbackPtr _cb; + PyObject* _target; + void* _closure; +}; +typedef IceUtil::Handle<ReadObjectCallback> ReadObjectCallbackPtr; + +// +// This class assists during unmarshaling of Slice classes and exceptions. +// We attach an instance to a stream. +// +class StreamUtil +{ +public: + + StreamUtil(); + ~StreamUtil(); + + // + // Keep a reference to a ReadObjectCallback for patching purposes. + // + void add(const ReadObjectCallbackPtr&); + + // + // Keep track of object instances that have preserved slices. + // + void add(const ObjectReaderPtr&); + + // + // Updated the sliced data information for all stored object instances. + // + void updateSlicedData(); + + static void setSlicedDataMember(PyObject*, const Ice::SlicedDataPtr&); + static Ice::SlicedDataPtr getSlicedDataMember(PyObject*, ObjectMap*); + +private: + + std::vector<ReadObjectCallbackPtr> _callbacks; + std::set<ObjectReaderPtr> _readers; + static PyObject* _slicedDataType; + static PyObject* _sliceInfoType; +}; + +struct PrintObjectHistory +{ + int index; + std::map<PyObject*, int> objects; +}; + +// // Base class for type information. // class TypeInfo : public UnmarshalCallback @@ -125,8 +165,8 @@ public: // The marshal and unmarshal functions can raise Ice exceptions, and may raise // AbortMarshaling if an error occurs. // - virtual void marshal(PyObject*, const Ice::OutputStreamPtr&, ObjectMap*, bool, const Ice::StringSeq* = 0) = 0; - virtual void unmarshal(const Ice::InputStreamPtr&, const UnmarshalCallbackPtr&, PyObject*, void*, bool, + virtual void marshal(PyObject*, Ice::OutputStream*, ObjectMap*, bool, const Ice::StringSeq* = 0) = 0; + virtual void unmarshal(Ice::InputStream*, const UnmarshalCallbackPtr&, PyObject*, void*, bool, const Ice::StringSeq* = 0) = 0; virtual void print(PyObject*, IceUtilInternal::Output&, PrintObjectHistory*) = 0; @@ -162,8 +202,8 @@ public: virtual int wireSize() const; virtual Ice::OptionalFormat optionalFormat() const; - virtual void marshal(PyObject*, const Ice::OutputStreamPtr&, ObjectMap*, bool, const Ice::StringSeq* = 0); - virtual void unmarshal(const Ice::InputStreamPtr&, const UnmarshalCallbackPtr&, PyObject*, void*, bool, + virtual void marshal(PyObject*, Ice::OutputStream*, ObjectMap*, bool, const Ice::StringSeq* = 0); + virtual void unmarshal(Ice::InputStream*, const UnmarshalCallbackPtr&, PyObject*, void*, bool, const Ice::StringSeq* = 0); virtual void print(PyObject*, IceUtilInternal::Output&, PrintObjectHistory*); @@ -191,8 +231,8 @@ public: virtual int wireSize() const; virtual Ice::OptionalFormat optionalFormat() const; - virtual void marshal(PyObject*, const Ice::OutputStreamPtr&, ObjectMap*, bool, const Ice::StringSeq* = 0); - virtual void unmarshal(const Ice::InputStreamPtr&, const UnmarshalCallbackPtr&, PyObject*, void*, bool, + virtual void marshal(PyObject*, Ice::OutputStream*, ObjectMap*, bool, const Ice::StringSeq* = 0); + virtual void unmarshal(Ice::InputStream*, const UnmarshalCallbackPtr&, PyObject*, void*, bool, const Ice::StringSeq* = 0); virtual void print(PyObject*, IceUtilInternal::Output&, PrintObjectHistory*); @@ -241,8 +281,8 @@ public: virtual bool usesClasses() const; - virtual void marshal(PyObject*, const Ice::OutputStreamPtr&, ObjectMap*, bool, const Ice::StringSeq* = 0); - virtual void unmarshal(const Ice::InputStreamPtr&, const UnmarshalCallbackPtr&, PyObject*, void*, bool, + virtual void marshal(PyObject*, Ice::OutputStream*, ObjectMap*, bool, const Ice::StringSeq* = 0); + virtual void unmarshal(Ice::InputStream*, const UnmarshalCallbackPtr&, PyObject*, void*, bool, const Ice::StringSeq* = 0); virtual void print(PyObject*, IceUtilInternal::Output&, PrintObjectHistory*); @@ -282,8 +322,8 @@ public: virtual bool usesClasses() const; - virtual void marshal(PyObject*, const Ice::OutputStreamPtr&, ObjectMap*, bool, const Ice::StringSeq* = 0); - virtual void unmarshal(const Ice::InputStreamPtr&, const UnmarshalCallbackPtr&, PyObject*, void*, bool, + virtual void marshal(PyObject*, Ice::OutputStream*, ObjectMap*, bool, const Ice::StringSeq* = 0); + virtual void unmarshal(Ice::InputStream*, const UnmarshalCallbackPtr&, PyObject*, void*, bool, const Ice::StringSeq* = 0); virtual void print(PyObject*, IceUtilInternal::Output&, PrintObjectHistory*); @@ -311,8 +351,8 @@ private: typedef IceUtil::Handle<SequenceMapping> SequenceMappingPtr; PyObject* getSequence(const PrimitiveInfoPtr&, PyObject*); - void marshalPrimitiveSequence(const PrimitiveInfoPtr&, PyObject*, const Ice::OutputStreamPtr&); - void unmarshalPrimitiveSequence(const PrimitiveInfoPtr&, const Ice::InputStreamPtr&, const UnmarshalCallbackPtr&, + void marshalPrimitiveSequence(const PrimitiveInfoPtr&, PyObject*, Ice::OutputStream*); + void unmarshalPrimitiveSequence(const PrimitiveInfoPtr&, Ice::InputStream*, const UnmarshalCallbackPtr&, PyObject*, void*, const SequenceMappingPtr&); public: @@ -342,8 +382,8 @@ public: virtual bool usesClasses() const; - virtual void marshal(PyObject*, const Ice::OutputStreamPtr&, ObjectMap*, bool, const Ice::StringSeq* = 0); - virtual void unmarshal(const Ice::InputStreamPtr&, const UnmarshalCallbackPtr&, PyObject*, void*, bool, + virtual void marshal(PyObject*, Ice::OutputStream*, ObjectMap*, bool, const Ice::StringSeq* = 0); + virtual void unmarshal(Ice::InputStream*, const UnmarshalCallbackPtr&, PyObject*, void*, bool, const Ice::StringSeq* = 0); virtual void print(PyObject*, IceUtilInternal::Output&, PrintObjectHistory*); @@ -374,8 +414,8 @@ public: virtual bool usesClasses() const; - virtual void marshal(PyObject*, const Ice::OutputStreamPtr&, ObjectMap*, bool, const Ice::StringSeq* = 0); - virtual void unmarshal(const Ice::InputStreamPtr&, const UnmarshalCallbackPtr&, PyObject*, void*, bool, + virtual void marshal(PyObject*, Ice::OutputStream*, ObjectMap*, bool, const Ice::StringSeq* = 0); + virtual void unmarshal(Ice::InputStream*, const UnmarshalCallbackPtr&, PyObject*, void*, bool, const Ice::StringSeq* = 0); virtual void unmarshaled(PyObject*, PyObject*, void*); @@ -412,7 +452,45 @@ public: ClassInfo(const std::string&); - void define(PyObject*, int, bool, bool, PyObject*, PyObject*, PyObject*); + void define(PyObject*, PyObject*, PyObject*); + + virtual std::string getId() const; + + virtual bool validate(PyObject*); + + virtual bool variableLength() const; + virtual int wireSize() const; + virtual Ice::OptionalFormat optionalFormat() const; + + virtual bool usesClasses() const; + + virtual void marshal(PyObject*, Ice::OutputStream*, ObjectMap*, bool, const Ice::StringSeq* = 0); + virtual void unmarshal(Ice::InputStream*, const UnmarshalCallbackPtr&, PyObject*, void*, bool, + const Ice::StringSeq* = 0); + + virtual void print(PyObject*, IceUtilInternal::Output&, PrintObjectHistory*); + + virtual void destroy(); + + const std::string id; + const ClassInfoPtr base; + const ClassInfoList interfaces; + const PyObjectHandle pythonType; + const PyObjectHandle typeObj; + const bool defined; +}; + +// +// Value type information +// + +class ValueInfo : public TypeInfo +{ +public: + + ValueInfo(const std::string&); + + void define(PyObject*, int, bool, bool, PyObject*, PyObject*); virtual std::string getId() const; @@ -424,8 +502,8 @@ public: virtual bool usesClasses() const; - virtual void marshal(PyObject*, const Ice::OutputStreamPtr&, ObjectMap*, bool, const Ice::StringSeq* = 0); - virtual void unmarshal(const Ice::InputStreamPtr&, const UnmarshalCallbackPtr&, PyObject*, void*, bool, + virtual void marshal(PyObject*, Ice::OutputStream*, ObjectMap*, bool, const Ice::StringSeq* = 0); + virtual void unmarshal(Ice::InputStream*, const UnmarshalCallbackPtr&, PyObject*, void*, bool, const Ice::StringSeq* = 0); virtual void print(PyObject*, IceUtilInternal::Output&, PrintObjectHistory*); @@ -436,10 +514,9 @@ public: const std::string id; const Ice::Int compactId; - const bool isAbstract; const bool preserve; - const ClassInfoPtr base; - const ClassInfoList interfaces; + const bool interface; + const ValueInfoPtr base; const DataMemberList members; const DataMemberList optionalMembers; const PyObjectHandle pythonType; @@ -466,8 +543,8 @@ public: virtual int wireSize() const; virtual Ice::OptionalFormat optionalFormat() const; - virtual void marshal(PyObject*, const Ice::OutputStreamPtr&, ObjectMap*, bool, const Ice::StringSeq* = 0); - virtual void unmarshal(const Ice::InputStreamPtr&, const UnmarshalCallbackPtr&, PyObject*, void*, bool, + virtual void marshal(PyObject*, Ice::OutputStream*, ObjectMap*, bool, const Ice::StringSeq* = 0); + virtual void unmarshal(Ice::InputStream*, const UnmarshalCallbackPtr&, PyObject*, void*, bool, const Ice::StringSeq* = 0); virtual void print(PyObject*, IceUtilInternal::Output&, PrintObjectHistory*); @@ -487,8 +564,8 @@ class ExceptionInfo : public IceUtil::Shared { public: - void marshal(PyObject*, const Ice::OutputStreamPtr&, ObjectMap*); - PyObject* unmarshal(const Ice::InputStreamPtr&); + void marshal(PyObject*, Ice::OutputStream*, ObjectMap*); + PyObject* unmarshal(Ice::InputStream*); void print(PyObject*, IceUtilInternal::Output&); void printMembers(PyObject*, IceUtilInternal::Output&, PrintObjectHistory*); @@ -503,47 +580,50 @@ public: private: - void writeMembers(PyObject*, const Ice::OutputStreamPtr&, const DataMemberList&, ObjectMap*) const; + void writeMembers(PyObject*, Ice::OutputStream*, const DataMemberList&, ObjectMap*) const; }; // // ObjectWriter wraps a Python object for marshaling. // -class ObjectWriter : public Ice::ObjectWriter +class ObjectWriter : public Ice::Object { public: - ObjectWriter(PyObject*, ObjectMap*); + ObjectWriter(PyObject*, ObjectMap*, const ValueInfoPtr&); ~ObjectWriter(); virtual void ice_preMarshal(); - virtual void write(const Ice::OutputStreamPtr&) const; + virtual void _iceWrite(Ice::OutputStream*) const; + virtual void _iceRead(Ice::InputStream*); private: - void writeMembers(const Ice::OutputStreamPtr&, const DataMemberList&) const; + void writeMembers(Ice::OutputStream*, const DataMemberList&) const; PyObject* _object; ObjectMap* _map; - ClassInfoPtr _info; + ValueInfoPtr _info; + ValueInfoPtr _formal; }; // // ObjectReader unmarshals the state of an Ice object. // -class ObjectReader : public Ice::ObjectReader +class ObjectReader : public Ice::Object { public: - ObjectReader(PyObject*, const ClassInfoPtr&); + ObjectReader(PyObject*, const ValueInfoPtr&); ~ObjectReader(); virtual void ice_postUnmarshal(); - virtual void read(const Ice::InputStreamPtr&); + virtual void _iceWrite(Ice::OutputStream*) const; + virtual void _iceRead(Ice::InputStream*); - virtual ClassInfoPtr getInfo() const; + virtual ValueInfoPtr getInfo() const; PyObject* getObject() const; // Borrowed reference. @@ -552,27 +632,36 @@ public: private: PyObject* _object; - ClassInfoPtr _info; + ValueInfoPtr _info; Ice::SlicedDataPtr _slicedData; }; // // ExceptionWriter wraps a Python user exception for marshaling. // -class ExceptionWriter : public Ice::UserExceptionWriter +class ExceptionWriter : public Ice::UserException { public: - ExceptionWriter(const Ice::CommunicatorPtr&, const PyObjectHandle&, const ExceptionInfoPtr& = 0); + ExceptionWriter(const PyObjectHandle&, const ExceptionInfoPtr& = 0); ~ExceptionWriter() throw(); - virtual void write(const Ice::OutputStreamPtr&) const; - virtual bool usesClasses() const; - - virtual std::string ice_name() const; + virtual std::string ice_id() const; +#ifndef ICE_CPP11_MAPPING virtual Ice::UserException* ice_clone() const; +#endif virtual void ice_throw() const; + virtual void _write(Ice::OutputStream*) const; + virtual void _read(Ice::InputStream*); + + virtual bool _usesClasses() const; + +protected: + + virtual void _writeImpl(Ice::OutputStream*) const {} + virtual void _readImpl(Ice::InputStream*) {} + private: PyObjectHandle _ex; @@ -583,24 +672,33 @@ private: // // ExceptionReader creates a Python user exception and unmarshals it. // -class ExceptionReader : public Ice::UserExceptionReader +class ExceptionReader : public Ice::UserException { public: - ExceptionReader(const Ice::CommunicatorPtr&, const ExceptionInfoPtr&); + ExceptionReader(const ExceptionInfoPtr&); ~ExceptionReader() throw(); - virtual void read(const Ice::InputStreamPtr&) const; - virtual bool usesClasses() const; - - virtual std::string ice_name() const; + virtual std::string ice_id() const; +#ifndef ICE_CPP11_MAPPING virtual Ice::UserException* ice_clone() const; +#endif virtual void ice_throw() const; + virtual void _write(Ice::OutputStream*) const; + virtual void _read(Ice::InputStream*); + + virtual bool _usesClasses() const; + PyObject* getException() const; // Borrowed reference. Ice::SlicedDataPtr getSlicedData() const; +protected: + + virtual void _writeImpl(Ice::OutputStream*) const {} + virtual void _readImpl(Ice::InputStream*) {} + private: ExceptionInfoPtr _info; @@ -616,6 +714,7 @@ public: }; ClassInfoPtr lookupClassInfo(const std::string&); +ValueInfoPtr lookupValueInfo(const std::string&); ExceptionInfoPtr lookupExceptionInfo(const std::string&); extern PyObject* Unset; @@ -639,6 +738,8 @@ extern "C" PyObject* IcePy_declareProxy(PyObject*, PyObject*); extern "C" PyObject* IcePy_defineProxy(PyObject*, PyObject*); extern "C" PyObject* IcePy_declareClass(PyObject*, PyObject*); extern "C" PyObject* IcePy_defineClass(PyObject*, PyObject*); +extern "C" PyObject* IcePy_declareValue(PyObject*, PyObject*); +extern "C" PyObject* IcePy_defineValue(PyObject*, PyObject*); extern "C" PyObject* IcePy_defineException(PyObject*, PyObject*); extern "C" PyObject* IcePy_stringify(PyObject*, PyObject*); extern "C" PyObject* IcePy_stringifyException(PyObject*, PyObject*); diff --git a/python/modules/IcePy/Util.cpp b/python/modules/IcePy/Util.cpp index f67fe318646..d1c92adee65 100644 --- a/python/modules/IcePy/Util.cpp +++ b/python/modules/IcePy/Util.cpp @@ -14,7 +14,7 @@ #include <IceUtil/DisableWarnings.h> #include <Ice/LocalException.h> #include <Ice/Protocol.h> -#include <IceUtil/UUID.h> +#include <Ice/UUID.h> #include <Slice/PythonUtil.h> #include <compile.h> #include <frameobject.h> @@ -118,13 +118,13 @@ versionToString(PyObject* args, const char* type) PyObject* p; if(!PyArg_ParseTuple(args, STRCAST("O!"), versionType, &p)) { - return NULL; + return ICE_NULLPTR; } T v; if(!getVersion<T>(p, v, type)) { - return NULL; + return ICE_NULLPTR; } string s; @@ -135,7 +135,7 @@ versionToString(PyObject* args, const char* type) catch(const Ice::Exception& ex) { IcePy::setPythonException(ex); - return NULL; + return ICE_NULLPTR; } return createString(s); } @@ -146,7 +146,7 @@ stringToVersion(PyObject* args, const char* type) char* str; if(!PyArg_ParseTuple(args, STRCAST("s"), &str)) { - return NULL; + return ICE_NULLPTR; } T v; @@ -157,7 +157,7 @@ stringToVersion(PyObject* args, const char* type) catch(const Ice::Exception& ex) { IcePy::setPythonException(ex); - return NULL; + return ICE_NULLPTR; } return createVersion<T>(v, type); @@ -311,7 +311,7 @@ IcePy::PyException::raise() } else { - PyObjectHandle name = PyObject_CallMethod(ex.get(), STRCAST("ice_name"), 0); + PyObjectHandle name = PyObject_CallMethod(ex.get(), STRCAST("ice_id"), 0); PyErr_Clear(); if(!name.get()) { @@ -468,11 +468,12 @@ IcePy::PyException::getTraceback() PyObjectHandle str = createString("traceback"); PyObjectHandle mod = PyImport_Import(str.get()); assert(mod.get()); // Unable to import traceback module - Python installation error? - PyObject* d = PyModule_GetDict(mod.get()); - PyObject* func = PyDict_GetItemString(d, "format_exception"); + PyObject* func = PyDict_GetItemString(PyModule_GetDict(mod.get()), "format_exception"); assert(func); // traceback.format_exception must be present. PyObjectHandle args = Py_BuildValue("(OOO)", _type.get(), ex.get(), _tb.get()); + assert(args.get()); PyObjectHandle list = PyObject_CallObject(func, args.get()); + assert(list.get()); string result; for(Py_ssize_t i = 0; i < PyList_GET_SIZE(list.get()); ++i) @@ -818,7 +819,7 @@ convertLocalException(const Ice::LocalException& ex, PyObject* p) m = IcePy::createEncodingVersion(e.supported); PyObject_SetAttrString(p, STRCAST("supported"), m.get()); } - catch(const Ice::NoObjectFactoryException& e) + catch(const Ice::NoValueFactoryException& e) { IcePy::PyObjectHandle m; m = IcePy::createString(e.reason); @@ -856,6 +857,10 @@ convertLocalException(const Ice::LocalException& ex, PyObject* p) IcePy::PyObjectHandle m = IcePy::createString(e.reason); PyObject_SetAttrString(p, STRCAST("reason"), m.get()); } + catch(const Ice::ConnectionManuallyClosedException& e) + { + PyObject_SetAttrString(p, STRCAST("graceful"), e.graceful ? IcePy::getTrue() : IcePy::getFalse()); + } catch(const Ice::LocalException&) { // @@ -880,7 +885,7 @@ IcePy::convertException(const Ice::Exception& ex) } catch(const Ice::LocalException& e) { - type = lookupType(scopedToName(e.ice_name())); + type = lookupType(scopedToName(e.ice_id())); if(type) { p = createExceptionInstance(type); @@ -1090,6 +1095,60 @@ IcePy::getEncodingVersion(PyObject* args, Ice::EncodingVersion& v) return true; } +PyObject* +IcePy::callMethod(PyObject* obj, const string& name, PyObject* arg1, PyObject* arg2) +{ + PyObjectHandle method = PyObject_GetAttrString(obj, const_cast<char*>(name.c_str())); + if(!method.get()) + { + return 0; + } + return callMethod(method.get(), arg1, arg2); +} + +PyObject* +IcePy::callMethod(PyObject* method, PyObject* arg1, PyObject* arg2) +{ + PyObjectHandle args; + if(arg1 && arg2) + { + args = PyTuple_New(2); + if(!args.get()) + { + return 0; + } + PyTuple_SET_ITEM(args.get(), 0, incRef(arg1)); + PyTuple_SET_ITEM(args.get(), 1, incRef(arg2)); + } + else if(arg1) + { + args = PyTuple_New(1); + if(!args.get()) + { + return 0; + } + PyTuple_SET_ITEM(args.get(), 0, incRef(arg1)); + } + else if(arg2) + { + args = PyTuple_New(1); + if(!args.get()) + { + return 0; + } + PyTuple_SET_ITEM(args.get(), 0, incRef(arg2)); + } + else + { + args = PyTuple_New(0); + if(!args.get()) + { + return 0; + } + } + return PyObject_Call(method, args.get(), 0); +} + extern "C" PyObject* IcePy_stringVersion(PyObject* /*self*/) @@ -1158,6 +1217,6 @@ extern "C" PyObject* IcePy_generateUUID(PyObject* /*self*/) { - string uuid = IceUtil::generateUUID(); + string uuid = Ice::generateUUID(); return IcePy::createString(uuid); } diff --git a/python/modules/IcePy/Util.h b/python/modules/IcePy/Util.h index 44318844b69..744a21fa6e2 100644 --- a/python/modules/IcePy/Util.h +++ b/python/modules/IcePy/Util.h @@ -16,7 +16,7 @@ #include <Ice/Exception.h> // -// These macros replace Py_RETURN_FALSE and Py_RETURN TRUE. We use these +// These macros replace Py_RETURN_FALSE and Py_RETURN_TRUE. We use these // instead of the standard ones in order to avoid GCC warnings about // strict aliasing and type punning. // @@ -28,6 +28,12 @@ namespace IcePy { +inline PyObject* incRef(PyObject* obj) +{ + Py_XINCREF(obj); + return obj; +} + // // This should be used instead of Py_False to avoid GCC compiler warnings. // @@ -58,16 +64,12 @@ inline PyObject* getTrue() inline PyObject* incFalse() { - PyObject* f = getFalse(); - Py_INCREF(f); - return f; + return incRef(getFalse()); } inline PyObject* incTrue() { - PyObject* t = getTrue(); - Py_INCREF(t); - return t; + return incRef(getTrue()); } // @@ -262,6 +264,12 @@ PyObject* createEncodingVersion(const Ice::EncodingVersion&); // bool getEncodingVersion(PyObject*, Ice::EncodingVersion&); +// +// Call a Python method. +// +PyObject* callMethod(PyObject*, const std::string&, PyObject* = 0, PyObject* = 0); +PyObject* callMethod(PyObject*, PyObject* = 0, PyObject* = 0); + } extern "C" PyObject* IcePy_stringVersion(PyObject*); diff --git a/python/modules/IcePy/ValueFactoryManager.cpp b/python/modules/IcePy/ValueFactoryManager.cpp new file mode 100644 index 00000000000..b2bc743a525 --- /dev/null +++ b/python/modules/IcePy/ValueFactoryManager.cpp @@ -0,0 +1,519 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2016 ZeroC, Inc. All rights reserved. +// +// This copy of Ice is licensed to you under the terms described in the +// ICE_LICENSE file included in this distribution. +// +// ********************************************************************** + +#ifdef _WIN32 +# include <IceUtil/Config.h> +#endif +#include <ValueFactoryManager.h> +#include <Thread.h> +#include <Types.h> +#include <Ice/LocalException.h> + +using namespace std; +using namespace IcePy; + +namespace IcePy +{ + +struct ValueFactoryManagerObject +{ + PyObject_HEAD + ValueFactoryManagerPtr* vfm; +}; + +} + +namespace +{ + +ValueInfoPtr +getValueInfo(const string& id) +{ + return id == Ice::Object::ice_staticId() ? lookupValueInfo("::Ice::UnknownSlicedValue") : lookupValueInfo(id); +} + +} + +IcePy::ValueFactoryManager::ValueFactoryManager() +{ + // + // Create a Python wrapper around this object. Note that this is cyclic - we clear the + // reference in destroy(). + // + ValueFactoryManagerObject* obj = reinterpret_cast<ValueFactoryManagerObject*>( + ValueFactoryManagerType.tp_alloc(&ValueFactoryManagerType, 0)); + assert(obj); + obj->vfm = new ValueFactoryManagerPtr(this); + _self = reinterpret_cast<PyObject*>(obj); + + _defaultFactory = new DefaultValueFactory; +} + +IcePy::ValueFactoryManager::~ValueFactoryManager() +{ + AdoptThread adoptThread; // Ensure the current thread is able to call into Python. + Py_XDECREF(_self); +} + +void +IcePy::ValueFactoryManager::add(const Ice::ValueFactoryPtr& f, const string& id) +{ + Lock lock(*this); + + if(id.empty()) + { + if(_defaultFactory->getDelegate()) + { + throw Ice::AlreadyRegisteredException(__FILE__, __LINE__, "value factory", id); + } + + _defaultFactory->setDelegate(f); + } + else + { + FactoryMap::iterator p = _factories.find(id); + if(p != _factories.end()) + { + throw Ice::AlreadyRegisteredException(__FILE__, __LINE__, "value factory", id); + } + + _factories.insert(FactoryMap::value_type(id, f)); + } +} + +Ice::ValueFactoryPtr +IcePy::ValueFactoryManager::find(const string& id) const +{ + Lock lock(*this); + + if(id.empty()) + { + return _defaultFactory; + } + + FactoryMap::const_iterator p = _factories.find(id); + if(p != _factories.end()) + { + return p->second; + } + + return 0; +} + +void +IcePy::ValueFactoryManager::add(PyObject* valueFactory, PyObject* objectFactory, const string& id) +{ + try + { + add(new FactoryWrapper(valueFactory, objectFactory), id); + } + catch(const Ice::Exception& ex) + { + setPythonException(ex); + } +} + +PyObject* +IcePy::ValueFactoryManager::findValueFactory(const string& id) const +{ + Ice::ValueFactoryPtr f = find(id); + if(f) + { + FactoryWrapperPtr w = FactoryWrapperPtr::dynamicCast(f); + if(w) + { + return w->getValueFactory(); + } + } + + Py_INCREF(Py_None); + return Py_None; +} + +PyObject* +IcePy::ValueFactoryManager::findObjectFactory(const string& id) const +{ + Ice::ValueFactoryPtr f = find(id); + if(f) + { + FactoryWrapperPtr w = FactoryWrapperPtr::dynamicCast(f); + if(w) + { + return w->getObjectFactory(); + } + } + + Py_INCREF(Py_None); + return Py_None; +} + +PyObject* +IcePy::ValueFactoryManager::getObject() const +{ + Py_INCREF(_self); + return _self; +} + +void +IcePy::ValueFactoryManager::destroy() +{ + AdoptThread adoptThread; // Ensure the current thread is able to call into Python. + + FactoryMap factories; + + { + Lock lock(*this); + if(_self == 0) + { + // + // Nothing to do if already destroyed (this can occur if communicator destroy is called multiple times) + // + return; + } + // + // Break the cyclic reference. + // + Py_DECREF(_self); + _self = 0; + + factories.swap(_factories); + } + + for(FactoryMap::iterator p = factories.begin(); p != factories.end(); ++p) + { + FactoryWrapperPtr w = FactoryWrapperPtr::dynamicCast(p->second); + if(w) + { + w->destroy(); + } + } + + _defaultFactory->destroy(); +} + +IcePy::FactoryWrapper::FactoryWrapper(PyObject* valueFactory, PyObject* objectFactory) : + _valueFactory(valueFactory), + _objectFactory(objectFactory) +{ + Py_INCREF(_valueFactory); + Py_INCREF(_objectFactory); + assert(_valueFactory != Py_None); // This should always be present. +} + +IcePy::FactoryWrapper::~FactoryWrapper() +{ + Py_DECREF(_valueFactory); + Py_DECREF(_objectFactory); +} + +Ice::ValuePtr +IcePy::FactoryWrapper::create(const string& id) +{ + AdoptThread adoptThread; // Ensure the current thread is able to call into Python. + + // + // Get the type information. + // + ValueInfoPtr info = getValueInfo(id); + + if(!info) + { + return 0; + } + + PyObjectHandle obj = PyObject_CallFunction(_valueFactory, STRCAST("s"), id.c_str()); + + if(!obj.get()) + { + assert(PyErr_Occurred()); + throw AbortMarshaling(); + } + + if(obj.get() == Py_None) + { + return 0; + } + + return new ObjectReader(obj.get(), info); +} + +PyObject* +IcePy::FactoryWrapper::getValueFactory() const +{ + Py_INCREF(_valueFactory); + return _valueFactory; +} + +PyObject* +IcePy::FactoryWrapper::getObjectFactory() const +{ + Py_INCREF(_objectFactory); + return _objectFactory; +} + +void +IcePy::FactoryWrapper::destroy() +{ + if(_objectFactory != Py_None) + { + PyObjectHandle obj = PyObject_CallMethod(_objectFactory, STRCAST("destroy"), 0); + PyErr_Clear(); // Ignore errors. + } +} + +Ice::ValuePtr +IcePy::DefaultValueFactory::create(const string& id) +{ + AdoptThread adoptThread; // Ensure the current thread is able to call into Python. + + Ice::ValuePtr v; + + // + // Give the application-provided default factory a chance to create the object first. + // + if(_delegate) + { + v = _delegate->create(id); + if(v) + { + return v; + } + } + + // + // Get the type information. + // + ValueInfoPtr info = getValueInfo(id); + + if(!info) + { + return 0; + } + + // + // Instantiate the object. + // + PyTypeObject* type = reinterpret_cast<PyTypeObject*>(info->pythonType.get()); + PyObjectHandle args = PyTuple_New(0); + PyObjectHandle obj = type->tp_new(type, args.get(), 0); + if(!obj.get()) + { + assert(PyErr_Occurred()); + throw AbortMarshaling(); + } + + return new ObjectReader(obj.get(), info); +} + +void +IcePy::DefaultValueFactory::setDelegate(const Ice::ValueFactoryPtr& d) +{ + _delegate = d; +} + +PyObject* +IcePy::DefaultValueFactory::getValueFactory() const +{ + if(_delegate) + { + FactoryWrapperPtr w = FactoryWrapperPtr::dynamicCast(_delegate); + if(w) + { + return w->getValueFactory(); + } + } + + Py_INCREF(Py_None); + return Py_None; +} + +PyObject* +IcePy::DefaultValueFactory::getObjectFactory() const +{ + if(_delegate) + { + FactoryWrapperPtr w = FactoryWrapperPtr::dynamicCast(_delegate); + if(w) + { + return w->getObjectFactory(); + } + } + + Py_INCREF(Py_None); + return Py_None; +} + +void +IcePy::DefaultValueFactory::destroy() +{ + if(_delegate) + { + FactoryWrapperPtr w = FactoryWrapperPtr::dynamicCast(_delegate); + if(w) + { + w->destroy(); + } + } + + _delegate = 0; +} + +#ifdef WIN32 +extern "C" +#endif +static ValueFactoryManagerObject* +valueFactoryManagerNew(PyTypeObject* /*type*/, PyObject* /*args*/, PyObject* /*kwds*/) +{ + PyErr_Format(PyExc_RuntimeError, STRCAST("Do not instantiate this object directly")); + return 0; +} + +#ifdef WIN32 +extern "C" +#endif +static void +valueFactoryManagerDealloc(ValueFactoryManagerObject* self) +{ + delete self->vfm; + Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self)); +} + +#ifdef WIN32 +extern "C" +#endif +static PyObject* +valueFactoryManagerAdd(ValueFactoryManagerObject* self, PyObject* args) +{ + assert(self->vfm); + + PyObject* factoryType = lookupType("types.FunctionType"); + assert(factoryType); + + PyObject* factory; + PyObject* idObj; + if(!PyArg_ParseTuple(args, STRCAST("O!O"), factoryType, &factory, &idObj)) + { + return 0; + } + + string id; + if(!getStringArg(idObj, "id", id)) + { + return 0; + } + + (*self->vfm)->add(factory, Py_None, id); + if(PyErr_Occurred()) + { + return 0; + } + + Py_INCREF(Py_None); + return Py_None; +} + +#ifdef WIN32 +extern "C" +#endif +static PyObject* +valueFactoryManagerFind(ValueFactoryManagerObject* self, PyObject* args) +{ + assert(self->vfm); + + PyObject* idObj; + if(!PyArg_ParseTuple(args, STRCAST("O"), &idObj)) + { + return 0; + } + + string id; + if(!getStringArg(idObj, "id", id)) + { + return 0; + } + + return (*self->vfm)->findValueFactory(id); +} + +static PyMethodDef ValueFactoryManagerMethods[] = +{ + { STRCAST("add"), reinterpret_cast<PyCFunction>(valueFactoryManagerAdd), METH_VARARGS, + PyDoc_STR(STRCAST("add(factory, id) -> None")) }, + { STRCAST("find"), reinterpret_cast<PyCFunction>(valueFactoryManagerFind), METH_VARARGS, + PyDoc_STR(STRCAST("find(id) -> function")) }, + { 0, 0 } /* sentinel */ +}; + +namespace IcePy +{ + +PyTypeObject ValueFactoryManagerType = +{ + /* The ob_type field must be initialized in the module init function + * to be portable to Windows without using C++. */ + PyVarObject_HEAD_INIT(0, 0) + STRCAST("IcePy.ValueFactoryManager"), /* tp_name */ + sizeof(ValueFactoryManagerObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + reinterpret_cast<destructor>(valueFactoryManagerDealloc), /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + ValueFactoryManagerMethods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + reinterpret_cast<newfunc>(valueFactoryManagerNew), /* tp_new */ + 0, /* tp_free */ + 0, /* tp_is_gc */ +}; + +} + +bool +IcePy::initValueFactoryManager(PyObject* module) +{ + if(PyType_Ready(&ValueFactoryManagerType) < 0) + { + return false; + } + PyTypeObject* type = &ValueFactoryManagerType; // Necessary to prevent GCC's strict-alias warnings. + if(PyModule_AddObject(module, STRCAST("ValueFactoryManager"), reinterpret_cast<PyObject*>(type)) < 0) + { + return false; + } + + return true; +} diff --git a/python/modules/IcePy/ValueFactoryManager.h b/python/modules/IcePy/ValueFactoryManager.h new file mode 100644 index 00000000000..d9948e45e1e --- /dev/null +++ b/python/modules/IcePy/ValueFactoryManager.h @@ -0,0 +1,95 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2016 ZeroC, Inc. All rights reserved. +// +// This copy of Ice is licensed to you under the terms described in the +// ICE_LICENSE file included in this distribution. +// +// ********************************************************************** + +#ifndef ICEPY_VALUE_FACTORY_MANAGER_H +#define ICEPY_VALUE_FACTORY_MANAGER_H + +#include <Config.h> +#include <Ice/ValueFactory.h> +#include <IceUtil/Mutex.h> + +namespace IcePy +{ + +extern PyTypeObject ValueFactoryManagerType; + +bool initValueFactoryManager(PyObject*); + +class FactoryWrapper : public Ice::ValueFactory +{ +public: + + FactoryWrapper(PyObject*, PyObject*); + ~FactoryWrapper(); + + virtual Ice::ValuePtr create(const std::string&); + + PyObject* getValueFactory() const; + PyObject* getObjectFactory() const; + + void destroy(); + +protected: + + PyObject* _valueFactory; + PyObject* _objectFactory; +}; +typedef IceUtil::Handle<FactoryWrapper> FactoryWrapperPtr; + +class DefaultValueFactory : public Ice::ValueFactory +{ +public: + + virtual Ice::ValuePtr create(const std::string&); + + void setDelegate(const Ice::ValueFactoryPtr&); + Ice::ValueFactoryPtr getDelegate() const { return _delegate; } + + PyObject* getValueFactory() const; + PyObject* getObjectFactory() const; + + void destroy(); + +private: + + Ice::ValueFactoryPtr _delegate; +}; +typedef IceUtil::Handle<DefaultValueFactory> DefaultValueFactoryPtr; + +class ValueFactoryManager : public Ice::ValueFactoryManager, public IceUtil::Mutex +{ +public: + + ValueFactoryManager(); + ~ValueFactoryManager(); + + virtual void add(const Ice::ValueFactoryPtr&, const std::string&); + virtual Ice::ValueFactoryPtr find(const std::string&) const; + + virtual void add(PyObject*, PyObject*, const std::string&); + PyObject* findValueFactory(const std::string&) const; + PyObject* findObjectFactory(const std::string&) const; + + PyObject* getObject() const; + + void destroy(); + +private: + + typedef std::map<std::string, Ice::ValueFactoryPtr> FactoryMap; + + PyObject* _self; + FactoryMap _factories; + DefaultValueFactoryPtr _defaultFactory; +}; +typedef IceUtil::Handle<ValueFactoryManager> ValueFactoryManagerPtr; + +} + +#endif diff --git a/python/modules/IcePy/msbuild/icepy.vcxproj b/python/modules/IcePy/msbuild/icepy.vcxproj new file mode 100644 index 00000000000..587128955a0 --- /dev/null +++ b/python/modules/IcePy/msbuild/icepy.vcxproj @@ -0,0 +1,186 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <ItemGroup Label="ProjectConfigurations"> + <ProjectConfiguration Include="Debug|Win32"> + <Configuration>Debug</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|Win32"> + <Configuration>Release</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Debug|x64"> + <Configuration>Debug</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|x64"> + <Configuration>Release</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + </ItemGroup> + <ItemGroup> + <ClCompile Include="..\..\..\..\cpp\src\Slice\Checksum.cpp" /> + <ClCompile Include="..\..\..\..\cpp\src\Slice\FileTracker.cpp" /> + <ClCompile Include="..\..\..\..\cpp\src\Slice\Grammar.cpp" /> + <ClCompile Include="..\..\..\..\cpp\src\Slice\MD5.cpp" /> + <ClCompile Include="..\..\..\..\cpp\src\Slice\MD5I.cpp" /> + <ClCompile Include="..\..\..\..\cpp\src\Slice\Parser.cpp" /> + <ClCompile Include="..\..\..\..\cpp\src\Slice\Preprocessor.cpp" /> + <ClCompile Include="..\..\..\..\cpp\src\Slice\Python.cpp" /> + <ClCompile Include="..\..\..\..\cpp\src\Slice\PythonUtil.cpp" /> + <ClCompile Include="..\..\..\..\cpp\src\Slice\Scanner.cpp" /> + <ClCompile Include="..\..\..\..\cpp\src\Slice\SliceUtil.cpp" /> + <ClCompile Include="..\..\..\..\cpp\src\Slice\StringLiteralUtil.cpp" /> + <ClCompile Include="..\BatchRequestInterceptor.cpp" /> + <ClCompile Include="..\Communicator.cpp" /> + <ClCompile Include="..\Connection.cpp" /> + <ClCompile Include="..\ConnectionInfo.cpp" /> + <ClCompile Include="..\Current.cpp" /> + <ClCompile Include="..\Endpoint.cpp" /> + <ClCompile Include="..\EndpointInfo.cpp" /> + <ClCompile Include="..\ImplicitContext.cpp" /> + <ClCompile Include="..\Init.cpp" /> + <ClCompile Include="..\Logger.cpp" /> + <ClCompile Include="..\ObjectAdapter.cpp" /> + <ClCompile Include="..\Operation.cpp" /> + <ClCompile Include="..\Properties.cpp" /> + <ClCompile Include="..\PropertiesAdmin.cpp" /> + <ClCompile Include="..\Proxy.cpp" /> + <ClCompile Include="..\Slice.cpp" /> + <ClCompile Include="..\Thread.cpp" /> + <ClCompile Include="..\Types.cpp" /> + <ClCompile Include="..\Util.cpp" /> + <ClCompile Include="..\ValueFactoryManager.cpp" /> + </ItemGroup> + <ItemGroup> + <ClInclude Include="..\BatchRequestInterceptor.h" /> + <ClInclude Include="..\Communicator.h" /> + <ClInclude Include="..\Config.h" /> + <ClInclude Include="..\Connection.h" /> + <ClInclude Include="..\ConnectionInfo.h" /> + <ClInclude Include="..\Current.h" /> + <ClInclude Include="..\Endpoint.h" /> + <ClInclude Include="..\EndpointInfo.h" /> + <ClInclude Include="..\ImplicitContext.h" /> + <ClInclude Include="..\Logger.h" /> + <ClInclude Include="..\ObjectAdapter.h" /> + <ClInclude Include="..\Operation.h" /> + <ClInclude Include="..\Properties.h" /> + <ClInclude Include="..\PropertiesAdmin.h" /> + <ClInclude Include="..\Proxy.h" /> + <ClInclude Include="..\Slice.h" /> + <ClInclude Include="..\Thread.h" /> + <ClInclude Include="..\Types.h" /> + <ClInclude Include="..\Util.h" /> + <ClInclude Include="..\ValueFactoryManager.h" /> + </ItemGroup> + <ItemGroup> + <ResourceCompile Include="..\IcePy.rc" /> + </ItemGroup> + <ItemGroup> + <None Include="packages.config" /> + </ItemGroup> + <PropertyGroup Label="Globals"> + <ProjectGuid>{18BF13D3-85D3-43A5-8C96-E52EB0672F72}</ProjectGuid> + <RootNamespace>IceGrid</RootNamespace> + <WindowsTargetPlatformVersion>8.1</WindowsTargetPlatformVersion> + </PropertyGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> + <ConfigurationType>DynamicLibrary</ConfigurationType> + <UseDebugLibraries>true</UseDebugLibraries> + <PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> + <ConfigurationType>DynamicLibrary</ConfigurationType> + <UseDebugLibraries>false</UseDebugLibraries> + <PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration"> + <ConfigurationType>DynamicLibrary</ConfigurationType> + <UseDebugLibraries>true</UseDebugLibraries> + <PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> + <ConfigurationType>DynamicLibrary</ConfigurationType> + <UseDebugLibraries>false</UseDebugLibraries> + <PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset> + </PropertyGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> + <ImportGroup Label="ExtensionSettings"> + </ImportGroup> + <ImportGroup Label="Shared"> + </ImportGroup> + <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + <Import Project="..\..\..\msbuild\ice.props" /> + </ImportGroup> + <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + <Import Project="..\..\..\msbuild\ice.props" /> + </ImportGroup> + <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + <Import Project="..\..\..\msbuild\ice.props" /> + </ImportGroup> + <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + <Import Project="..\..\..\msbuild\ice.props" /> + </ImportGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <TargetName>IcePy_d</TargetName> + <OutDir>..\..\..\python\$(Platform)\$(Configuration)\</OutDir> + <TargetExt>.pyd</TargetExt> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <TargetName>IcePy_d</TargetName> + <OutDir>..\..\..\python\$(Platform)\$(Configuration)\</OutDir> + <TargetExt>.pyd</TargetExt> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <TargetName>IcePy</TargetName> + <OutDir>..\..\..\python\$(Platform)\$(Configuration)\</OutDir> + <TargetExt>.pyd</TargetExt> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <TargetName>IcePy</TargetName> + <OutDir>..\..\..\python\$(Platform)\$(Configuration)\</OutDir> + <TargetExt>.pyd</TargetExt> + </PropertyGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <ClCompile> + <DisableSpecificWarnings>4302;4311;4312;%(DisableSpecificWarnings)</DisableSpecificWarnings> + </ClCompile> + <Link> + <ImportLibrary /> + </Link> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <ClCompile> + <DisableSpecificWarnings>4302;4311;4312;%(DisableSpecificWarnings)</DisableSpecificWarnings> + </ClCompile> + <Link> + <ImportLibrary /> + </Link> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <Link> + <ImportLibrary /> + </Link> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <Link> + <ImportLibrary /> + </Link> + </ItemDefinitionGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> + <ImportGroup Label="ExtensionTargets"> + <Import Project="..\..\..\msbuild\packages\mcpp.v140.2.7.2.12\build\native\mcpp.v140.targets" Condition="Exists('..\..\..\msbuild\packages\mcpp.v140.2.7.2.12\build\native\mcpp.v140.targets')" /> + </ImportGroup> + <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild"> + <PropertyGroup> + <ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText> + </PropertyGroup> + <Error Condition="!Exists('..\..\..\msbuild\packages\mcpp.v140.2.7.2.12\build\native\mcpp.v140.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\..\..\msbuild\packages\mcpp.v140.2.7.2.12\build\native\mcpp.v140.targets'))" /> + </Target> +</Project>
\ No newline at end of file diff --git a/python/modules/IcePy/msbuild/icepy.vcxproj.filters b/python/modules/IcePy/msbuild/icepy.vcxproj.filters new file mode 100644 index 00000000000..2cf60c9c6f2 --- /dev/null +++ b/python/modules/IcePy/msbuild/icepy.vcxproj.filters @@ -0,0 +1,180 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <ItemGroup> + <Filter Include="Header Files"> + <UniqueIdentifier>{2a1af2ab-9818-4227-b57f-db37b32a9941}</UniqueIdentifier> + </Filter> + <Filter Include="Source Files"> + <UniqueIdentifier>{3e5dc6c2-9411-433a-ba20-c111abd667fc}</UniqueIdentifier> + </Filter> + <Filter Include="Resource Files"> + <UniqueIdentifier>{31c6127f-d193-46d6-9917-45e2099d36ca}</UniqueIdentifier> + </Filter> + </ItemGroup> + <ItemGroup> + <ClCompile Include="..\BatchRequestInterceptor.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="..\Communicator.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="..\Connection.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="..\ConnectionInfo.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="..\Current.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="..\Endpoint.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="..\EndpointInfo.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="..\ImplicitContext.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="..\Init.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="..\Logger.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="..\ObjectAdapter.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="..\Operation.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="..\Properties.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="..\PropertiesAdmin.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="..\Proxy.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="..\Slice.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="..\Thread.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="..\Types.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="..\Util.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="..\ValueFactoryManager.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="..\..\..\..\cpp\src\Slice\FileTracker.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="..\..\..\..\cpp\src\Slice\Grammar.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="..\..\..\..\cpp\src\Slice\MD5.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="..\..\..\..\cpp\src\Slice\Parser.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="..\..\..\..\cpp\src\Slice\Preprocessor.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="..\..\..\..\cpp\src\Slice\Python.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="..\..\..\..\cpp\src\Slice\PythonUtil.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="..\..\..\..\cpp\src\Slice\Scanner.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="..\..\..\..\cpp\src\Slice\SliceUtil.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="..\..\..\..\cpp\src\Slice\MD5I.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="..\..\..\..\cpp\src\Slice\Checksum.cpp"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="..\..\..\..\cpp\src\Slice\StringLiteralUtil.cpp" /> + </ItemGroup> + <ItemGroup> + <ClInclude Include="..\BatchRequestInterceptor.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="..\Communicator.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="..\Config.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="..\Connection.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="..\ConnectionInfo.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="..\Current.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="..\Endpoint.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="..\EndpointInfo.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="..\ImplicitContext.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="..\Logger.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="..\ObjectAdapter.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="..\Operation.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="..\Properties.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="..\Proxy.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="..\Slice.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="..\Thread.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="..\Types.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="..\Util.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="..\ValueFactoryManager.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="..\PropertiesAdmin.h"> + <Filter>Header Files</Filter> + </ClInclude> + </ItemGroup> + <ItemGroup> + <ResourceCompile Include="..\IcePy.rc"> + <Filter>Resource Files</Filter> + </ResourceCompile> + </ItemGroup> + <ItemGroup> + <None Include="packages.config" /> + </ItemGroup> +</Project>
\ No newline at end of file diff --git a/python/modules/IcePy/msbuild/packages.config b/python/modules/IcePy/msbuild/packages.config new file mode 100644 index 00000000000..ffe2f9f42ee --- /dev/null +++ b/python/modules/IcePy/msbuild/packages.config @@ -0,0 +1,4 @@ +<?xml version="1.0" encoding="utf-8"?> +<packages> + <package id="mcpp.v140" version="2.7.2.12" targetFramework="native" /> +</packages>
\ No newline at end of file diff --git a/python/modules/Makefile b/python/modules/Makefile deleted file mode 100644 index c221dd9e0e0..00000000000 --- a/python/modules/Makefile +++ /dev/null @@ -1,21 +0,0 @@ -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -top_srcdir = .. - -include $(top_srcdir)/config/Make.rules - -SUBDIRS = IcePy - -$(EVERYTHING):: - @for subdir in $(SUBDIRS); \ - do \ - echo "making $@ in $$subdir"; \ - ( cd $$subdir && $(MAKE) $@ ) || exit 1; \ - done diff --git a/python/modules/Makefile.mak b/python/modules/Makefile.mak deleted file mode 100644 index f98481bdfca..00000000000 --- a/python/modules/Makefile.mak +++ /dev/null @@ -1,19 +0,0 @@ -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -top_srcdir = .. - -!include $(top_srcdir)\config\Make.rules.mak - -SUBDIRS = IcePy - -$(EVERYTHING):: - @for %i in ( $(SUBDIRS) ) do \ - @echo "making $@ in %i" && \ - cmd /c "cd %i && $(MAKE) -nologo -f Makefile.mak $@" || exit 1 diff --git a/python/msbuild/ice.proj b/python/msbuild/ice.proj new file mode 100644 index 00000000000..c7974915aac --- /dev/null +++ b/python/msbuild/ice.proj @@ -0,0 +1,61 @@ +<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup Condition="'$(Configuration)' == ''"> + <Configuration>Debug</Configuration> + </PropertyGroup> + + <PropertyGroup Condition="'$(Platform)' == ''"> + <Platform>Win32</Platform> + </PropertyGroup> + + <Import Project="$(MSBuildThisFileDirectory)\..\..\config\Ice.common.targets" /> + + <!-- Restore Nuget packages --> + <Target Name="NugetRestore" DependsOnTargets="GetNuget"> + <Exec Command="$(NugetExe) restore $(MSBuildThisFileDirectory)ice.sln"/> + </Target> + + <Choose> + <!-- + If BuildAllConfigurations is set to yes we build all configurations that are + part of the binary distribution, otherwise we just build the specific platform + and configuration. + --> + <When Condition="'$(BuildAllConfigurations)' == 'yes'"> + <ItemGroup> + <DistProjects Include="ice.sln"> + <Properties>Configuration=Release;Platform=Win32</Properties> + </DistProjects> + <DistProjects Include="ice.sln"> + <Properties>Configuration=Release;Platform=x64</Properties> + </DistProjects> + <DistProjects Include="..\python\**\msbuild\*.proj"> + <Properties>Configuration=Release;Platform=Win32</Properties> + </DistProjects> + </ItemGroup> + </When> + <Otherwise> + <ItemGroup> + <DistProjects Include="ice.sln"> + <Properties>Configuration=$(Configuration);Platform=$(Platform)</Properties> + </DistProjects> + + <DistProjects Include="..\python\**\msbuild\*.proj"> + <Properties>Configuration=$(Configuration);Platform=$(Platform)</Properties> + </DistProjects> + </ItemGroup> + </Otherwise> + </Choose> + + <Target Name="Build" DependsOnTargets="NugetRestore"> + <MSBuild Projects="@(DistProjects)" + BuildInParallel="false" + Properties="%(Properties)" /> + </Target> + + <Target Name="Clean"> + <MSBuild Projects="@(DistProjects)" + BuildInParallel="true" + Properties="%(Properties)" + Targets="Clean" /> + </Target> +</Project> diff --git a/python/msbuild/ice.props b/python/msbuild/ice.props new file mode 100644 index 00000000000..5f77bc5d73f --- /dev/null +++ b/python/msbuild/ice.props @@ -0,0 +1,31 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup> + <Ice_LanguageMapping>python</Ice_LanguageMapping> + </PropertyGroup> + <Import Project="..\..\cpp\msbuild\Ice.Cpp98.props" /> + <PropertyGroup Label="UserMacros" Condition="'$(Platform)'=='Win32'"> + <PythonHome>C:\Python35</PythonHome> + </PropertyGroup> + <PropertyGroup Label="UserMacros" Condition="'$(Platform)'=='x64'"> + <PythonHome>C:\Python35-amd64</PythonHome> + </PropertyGroup> + <PropertyGroup> + <IceBuilderInstallDir>$([MSBuild]::GetRegistryValue('HKEY_CURRENT_USER\SOFTWARE\ZeroC\IceBuilder', 'InstallDir.$(VisualStudioVersion)'))</IceBuilderInstallDir> + <IceBuilderPythonProps>$(IceBuilderInstallDir)\Resources\IceBuilder.Python.props</IceBuilderPythonProps> + <IceBuilderPythonTargets>$(IceBuilderInstallDir)\Resources\IceBuilder.Python.targets</IceBuilderPythonTargets> + </PropertyGroup> + <ItemGroup> + <BuildMacro Include="PythonHome"> + <Value>$(PythonHome)</Value> + </BuildMacro> + </ItemGroup> + <ItemDefinitionGroup> + <ClCompile> + <AdditionalIncludeDirectories>..;$(PythonHome)\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> + </ClCompile> + <Link> + <AdditionalLibraryDirectories>$(PythonHome)\libs;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> + </Link> + </ItemDefinitionGroup> +</Project> diff --git a/python/msbuild/ice.sln b/python/msbuild/ice.sln new file mode 100644 index 00000000000..f44e96846b5 --- /dev/null +++ b/python/msbuild/ice.sln @@ -0,0 +1,28 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.24720.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "icepy", "..\modules\IcePy\msbuild\icepy.vcxproj", "{18BF13D3-85D3-43A5-8C96-E52EB0672F72}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {18BF13D3-85D3-43A5-8C96-E52EB0672F72}.Debug|Win32.ActiveCfg = Debug|Win32 + {18BF13D3-85D3-43A5-8C96-E52EB0672F72}.Debug|Win32.Build.0 = Debug|Win32 + {18BF13D3-85D3-43A5-8C96-E52EB0672F72}.Debug|x64.ActiveCfg = Debug|x64 + {18BF13D3-85D3-43A5-8C96-E52EB0672F72}.Debug|x64.Build.0 = Debug|x64 + {18BF13D3-85D3-43A5-8C96-E52EB0672F72}.Release|Win32.ActiveCfg = Release|Win32 + {18BF13D3-85D3-43A5-8C96-E52EB0672F72}.Release|Win32.Build.0 = Release|Win32 + {18BF13D3-85D3-43A5-8C96-E52EB0672F72}.Release|x64.ActiveCfg = Release|x64 + {18BF13D3-85D3-43A5-8C96-E52EB0672F72}.Release|x64.Build.0 = Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/python/msbuild/ice.tests.props b/python/msbuild/ice.tests.props new file mode 100644 index 00000000000..865fd71b364 --- /dev/null +++ b/python/msbuild/ice.tests.props @@ -0,0 +1,11 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup Condition="'$(UseBinDist)' != 'yes' and '$(ICE_HOME)' == ''"> + <IceHome>$(MSBuildThisFileDirectory)..\..</IceHome> + </PropertyGroup> + <PropertyGroup Label="IceBuilder"> + <IceBuilderOutputDir>..</IceBuilderOutputDir> + </PropertyGroup> + <Target Name="Build"/> + <Target Name="Clean"/> +</Project> diff --git a/python/python/.depend.mak b/python/python/.depend.mak deleted file mode 100644 index e46e1645583..00000000000 --- a/python/python/.depend.mak +++ /dev/null @@ -1,331 +0,0 @@ - -Ice_BuiltinSequences_ice.py: \ - "$(slicedir)\Ice\BuiltinSequences.ice" - -Ice_Communicator_ice.py: \ - "$(slicedir)\Ice\Communicator.ice" \ - "$(slicedir)/Ice/LoggerF.ice" \ - "$(slicedir)/Ice/InstrumentationF.ice" \ - "$(slicedir)/Ice/ObjectAdapterF.ice" \ - "$(slicedir)/Ice/ObjectFactoryF.ice" \ - "$(slicedir)/Ice/RouterF.ice" \ - "$(slicedir)/Ice/LocatorF.ice" \ - "$(slicedir)/Ice/PluginF.ice" \ - "$(slicedir)/Ice/ImplicitContextF.ice" \ - "$(slicedir)/Ice/Current.ice" \ - "$(slicedir)/Ice/ConnectionF.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Ice/Version.ice" \ - "$(slicedir)/Ice/Properties.ice" \ - "$(slicedir)/Ice/PropertiesAdmin.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" \ - "$(slicedir)/Ice/FacetMap.ice" - -Ice_CommunicatorF_ice.py: \ - "$(slicedir)\Ice\CommunicatorF.ice" - -Ice_Connection_ice.py: \ - "$(slicedir)\Ice\Connection.ice" \ - "$(slicedir)/Ice/ObjectAdapterF.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Ice/Endpoint.ice" \ - "$(slicedir)/Ice/Version.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" \ - "$(slicedir)/Ice/EndpointF.ice" - -Ice_ConnectionF_ice.py: \ - "$(slicedir)\Ice\ConnectionF.ice" - -Ice_Current_ice.py: \ - "$(slicedir)\Ice\Current.ice" \ - "$(slicedir)/Ice/ObjectAdapterF.ice" \ - "$(slicedir)/Ice/ConnectionF.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Ice/Version.ice" - -Ice_Endpoint_ice.py: \ - "$(slicedir)\Ice\Endpoint.ice" \ - "$(slicedir)/Ice/Version.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" \ - "$(slicedir)/Ice/EndpointF.ice" - -Ice_EndpointF_ice.py: \ - "$(slicedir)\Ice\EndpointF.ice" - -Ice_EndpointTypes_ice.py: \ - "$(slicedir)\Ice\EndpointTypes.ice" - -Ice_FacetMap_ice.py: \ - "$(slicedir)\Ice\FacetMap.ice" - -Ice_Identity_ice.py: \ - "$(slicedir)\Ice\Identity.ice" - -Ice_ImplicitContext_ice.py: \ - "$(slicedir)\Ice\ImplicitContext.ice" \ - "$(slicedir)/Ice/LocalException.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Ice/Version.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" \ - "$(slicedir)/Ice/Current.ice" \ - "$(slicedir)/Ice/ObjectAdapterF.ice" \ - "$(slicedir)/Ice/ConnectionF.ice" - -Ice_ImplicitContextF_ice.py: \ - "$(slicedir)\Ice\ImplicitContextF.ice" - -Ice_Instrumentation_ice.py: \ - "$(slicedir)\Ice\Instrumentation.ice" \ - "$(slicedir)/Ice/EndpointF.ice" \ - "$(slicedir)/Ice/ConnectionF.ice" \ - "$(slicedir)/Ice/Current.ice" \ - "$(slicedir)/Ice/ObjectAdapterF.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Ice/Version.ice" - -Ice_InstrumentationF_ice.py: \ - "$(slicedir)\Ice\InstrumentationF.ice" - -Ice_LocalException_ice.py: \ - "$(slicedir)\Ice\LocalException.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Ice/Version.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" - -Ice_Locator_ice.py: \ - "$(slicedir)\Ice\Locator.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Ice/ProcessF.ice" - -Ice_LocatorF_ice.py: \ - "$(slicedir)\Ice\LocatorF.ice" - -Ice_Logger_ice.py: \ - "$(slicedir)\Ice\Logger.ice" - -Ice_LoggerF_ice.py: \ - "$(slicedir)\Ice\LoggerF.ice" - -Ice_Metrics_ice.py: \ - "$(slicedir)\Ice\Metrics.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" - -Ice_ObjectAdapter_ice.py: \ - "$(slicedir)\Ice\ObjectAdapter.ice" \ - "$(slicedir)/Ice/CommunicatorF.ice" \ - "$(slicedir)/Ice/ServantLocatorF.ice" \ - "$(slicedir)/Ice/LocatorF.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Ice/FacetMap.ice" \ - "$(slicedir)/Ice/Endpoint.ice" \ - "$(slicedir)/Ice/Version.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" \ - "$(slicedir)/Ice/EndpointF.ice" - -Ice_ObjectAdapterF_ice.py: \ - "$(slicedir)\Ice\ObjectAdapterF.ice" - -Ice_ObjectFactory_ice.py: \ - "$(slicedir)\Ice\ObjectFactory.ice" - -Ice_ObjectFactoryF_ice.py: \ - "$(slicedir)\Ice\ObjectFactoryF.ice" - -Ice_Plugin_ice.py: \ - "$(slicedir)\Ice\Plugin.ice" \ - "$(slicedir)/Ice/LoggerF.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" - -Ice_PluginF_ice.py: \ - "$(slicedir)\Ice\PluginF.ice" - -Ice_Process_ice.py: \ - "$(slicedir)\Ice\Process.ice" - -Ice_ProcessF_ice.py: \ - "$(slicedir)\Ice\ProcessF.ice" - -Ice_Properties_ice.py: \ - "$(slicedir)\Ice\Properties.ice" \ - "$(slicedir)/Ice/PropertiesAdmin.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" - -Ice_PropertiesAdmin_ice.py: \ - "$(slicedir)\Ice\PropertiesAdmin.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" - -Ice_PropertiesF_ice.py: \ - "$(slicedir)\Ice\PropertiesF.ice" - -Ice_Router_ice.py: \ - "$(slicedir)\Ice\Router.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" - -Ice_RouterF_ice.py: \ - "$(slicedir)\Ice\RouterF.ice" - -Ice_ServantLocator_ice.py: \ - "$(slicedir)\Ice\ServantLocator.ice" \ - "$(slicedir)/Ice/ObjectAdapterF.ice" \ - "$(slicedir)/Ice/Current.ice" \ - "$(slicedir)/Ice/ConnectionF.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Ice/Version.ice" - -Ice_ServantLocatorF_ice.py: \ - "$(slicedir)\Ice\ServantLocatorF.ice" - -Ice_SliceChecksumDict_ice.py: \ - "$(slicedir)\Ice\SliceChecksumDict.ice" - -Ice_Version_ice.py: \ - "$(slicedir)\Ice\Version.ice" - -Glacier2_Metrics_ice.py: \ - "$(slicedir)\Glacier2\Metrics.ice" \ - "$(slicedir)/Ice/Metrics.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" - -Glacier2_PermissionsVerifier_ice.py: \ - "$(slicedir)\Glacier2\PermissionsVerifier.ice" \ - "$(slicedir)/Glacier2/SSLInfo.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" - -Glacier2_PermissionsVerifierF_ice.py: \ - "$(slicedir)\Glacier2\PermissionsVerifierF.ice" - -Glacier2_Router_ice.py: \ - "$(slicedir)\Glacier2\Router.ice" \ - "$(slicedir)/Ice/Router.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" \ - "$(slicedir)/Glacier2/Session.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Glacier2/SSLInfo.ice" \ - "$(slicedir)/Glacier2/PermissionsVerifier.ice" - -Glacier2_RouterF_ice.py: \ - "$(slicedir)\Glacier2\RouterF.ice" - -Glacier2_Session_ice.py: \ - "$(slicedir)\Glacier2\Session.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Glacier2/SSLInfo.ice" - -Glacier2_SSLInfo_ice.py: \ - "$(slicedir)\Glacier2\SSLInfo.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" - -IceBox_IceBox_ice.py: \ - "$(slicedir)\IceBox\IceBox.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" \ - "$(slicedir)/Ice/CommunicatorF.ice" \ - "$(slicedir)/Ice/PropertiesF.ice" \ - "$(slicedir)/Ice/SliceChecksumDict.ice" - -IceGrid_Admin_ice.py: \ - "$(slicedir)\IceGrid\Admin.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" \ - "$(slicedir)/Ice/Properties.ice" \ - "$(slicedir)/Ice/PropertiesAdmin.ice" \ - "$(slicedir)/Ice/SliceChecksumDict.ice" \ - "$(slicedir)/Glacier2/Session.ice" \ - "$(slicedir)/Glacier2/SSLInfo.ice" \ - "$(slicedir)/IceGrid/Exception.ice" \ - "$(slicedir)/IceGrid/Descriptor.ice" - -IceGrid_Descriptor_ice.py: \ - "$(slicedir)\IceGrid\Descriptor.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" - -IceGrid_Exception_ice.py: \ - "$(slicedir)\IceGrid\Exception.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" - -IceGrid_FileParser_ice.py: \ - "$(slicedir)\IceGrid\FileParser.ice" \ - "$(slicedir)/IceGrid/Admin.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" \ - "$(slicedir)/Ice/Properties.ice" \ - "$(slicedir)/Ice/PropertiesAdmin.ice" \ - "$(slicedir)/Ice/SliceChecksumDict.ice" \ - "$(slicedir)/Glacier2/Session.ice" \ - "$(slicedir)/Glacier2/SSLInfo.ice" \ - "$(slicedir)/IceGrid/Exception.ice" \ - "$(slicedir)/IceGrid/Descriptor.ice" - -IceGrid_Locator_ice.py: \ - "$(slicedir)\IceGrid\Locator.ice" \ - "$(slicedir)/Ice/Locator.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Ice/ProcessF.ice" - -IceGrid_Observer_ice.py: \ - "$(slicedir)\IceGrid\Observer.ice" \ - "$(slicedir)/Glacier2/Session.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Glacier2/SSLInfo.ice" \ - "$(slicedir)/IceGrid/Exception.ice" \ - "$(slicedir)/IceGrid/Descriptor.ice" \ - "$(slicedir)/IceGrid/Admin.ice" \ - "$(slicedir)/Ice/Properties.ice" \ - "$(slicedir)/Ice/PropertiesAdmin.ice" \ - "$(slicedir)/Ice/SliceChecksumDict.ice" - -IceGrid_Query_ice.py: \ - "$(slicedir)\IceGrid\Query.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" \ - "$(slicedir)/IceGrid/Exception.ice" - -IceGrid_Registry_ice.py: \ - "$(slicedir)\IceGrid\Registry.ice" \ - "$(slicedir)/IceGrid/Exception.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" \ - "$(slicedir)/IceGrid/Session.ice" \ - "$(slicedir)/Glacier2/Session.ice" \ - "$(slicedir)/Glacier2/SSLInfo.ice" \ - "$(slicedir)/IceGrid/Admin.ice" \ - "$(slicedir)/Ice/Properties.ice" \ - "$(slicedir)/Ice/PropertiesAdmin.ice" \ - "$(slicedir)/Ice/SliceChecksumDict.ice" \ - "$(slicedir)/IceGrid/Descriptor.ice" - -IceGrid_Session_ice.py: \ - "$(slicedir)\IceGrid\Session.ice" \ - "$(slicedir)/Glacier2/Session.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Glacier2/SSLInfo.ice" \ - "$(slicedir)/IceGrid/Exception.ice" - -IceGrid_UserAccountMapper_ice.py: \ - "$(slicedir)\IceGrid\UserAccountMapper.ice" - -IcePatch2_FileInfo_ice.py: \ - "$(slicedir)\IcePatch2\FileInfo.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" - -IcePatch2_FileServer_ice.py: \ - "$(slicedir)\IcePatch2\FileServer.ice" \ - "$(slicedir)/IcePatch2/FileInfo.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" - -IceStorm_Metrics_ice.py: \ - "$(slicedir)\IceStorm\Metrics.ice" \ - "$(slicedir)/Ice/Metrics.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" - -IceStorm_IceStorm_ice.py: \ - "$(slicedir)\IceStorm\IceStorm.ice" \ - "$(slicedir)/Ice/Identity.ice" \ - "$(slicedir)/Ice/SliceChecksumDict.ice" \ - "$(slicedir)/IceStorm/Metrics.ice" \ - "$(slicedir)/Ice/Metrics.ice" \ - "$(slicedir)/Ice/BuiltinSequences.ice" diff --git a/python/python/64/.gitignore b/python/python/64/.gitignore deleted file mode 100644 index 39af5887579..00000000000 --- a/python/python/64/.gitignore +++ /dev/null @@ -1 +0,0 @@ -# Dummy file, so that git retains this otherwise empty directory. diff --git a/python/python/Glacier2.py b/python/python/Glacier2.py index 0ab5fc9699c..63402962fbf 100644 --- a/python/python/Glacier2.py +++ b/python/python/Glacier2.py @@ -33,17 +33,6 @@ class RestartSessionException(Exception): def __init__(self): pass -class ConnectionCallbackI(Ice.ConnectionCallback): - def __init__(self, app): - self._app = app - - def heartbeat(self, conn): - pass - - def closed(self, conn): - self._app.sessionDestroyed() - - class Application(Ice.Application): def __init__(self, signalPolicy=0): # HandleSignals=0 @@ -150,7 +139,7 @@ Application.NoSignalHandling. connection = Application._router.ice_getCachedConnection() assert(connection) connection.setACM(acmTimeout, Ice.Unset, Ice.ACMHeartbeat.HeartbeatAlways) - connection.setCallback(ConnectionCallbackI(self)) + connection.setCloseCallback(lambda conn: self.sessionDestroyed()) Application._category = Application._router.getCategoryForClient() status = self.runWithSession(args) diff --git a/python/python/Glacier2/msbuild/glacier2.proj b/python/python/Glacier2/msbuild/glacier2.proj new file mode 100644 index 00000000000..e6eff151b49 --- /dev/null +++ b/python/python/Glacier2/msbuild/glacier2.proj @@ -0,0 +1,24 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup Label="IceBuilder"> + <IceBuilderAllowIcePrefix>true</IceBuilderAllowIcePrefix> + <IceBuilderPrefix>Glacier2_</IceBuilderPrefix> + <IceBuilderOutputDir>..\..</IceBuilderOutputDir> + <IceBuilderNoPackage>yes</IceBuilderNoPackage> + <IceBuilderDependFile>$(MSBuildProjectDirectory)\IceBuilder.d</IceBuilderDependFile> + <IceBuilderCommandLog>$(MSBuildProjectDirectory)\IceBuilder.command.log</IceBuilderCommandLog> + </PropertyGroup> + <Import Project="..\..\..\msbuild\ice.props" /> + <Import Project="$(IceBuilderPythonProps)" Condition="Exists('$(IceBuilderPythonProps)')"/> + <ItemGroup> + <IceBuilder Include="..\..\..\..\slice\Glacier2\PermissionsVerifier.ice" /> + <IceBuilder Include="..\..\..\..\slice\Glacier2\PermissionsVerifierF.ice" /> + <IceBuilder Include="..\..\..\..\slice\Glacier2\Router.ice" /> + <IceBuilder Include="..\..\..\..\slice\Glacier2\RouterF.ice" /> + <IceBuilder Include="..\..\..\..\slice\Glacier2\Session.ice" /> + <IceBuilder Include="..\..\..\..\slice\Glacier2\SSLInfo.ice" /> + </ItemGroup> + <Target Name="Build"/> + <Target Name="Clean"/> + <Import Project="$(IceBuilderPythonTargets)" Condition="Exists('$(IceBuilderPythonTargets)')"/> +</Project> diff --git a/python/python/Ice.py b/python/python/Ice.py index 1ace24e3cf7..f999ea54da7 100644 --- a/python/python/Ice.py +++ b/python/python/Ice.py @@ -11,7 +11,7 @@ Ice module """ -import sys, string, imp, os, threading, warnings, datetime +import sys, string, imp, os, threading, warnings, datetime, logging, time, inspect # # RTTI problems can occur in C++ code unless we modify Python's dlopen flags. @@ -76,6 +76,211 @@ loadSlice = IcePy.loadSlice AsyncResult = IcePy.AsyncResult Unset = IcePy.Unset +def Python35(): + return sys.version_info[:2] >= (3, 5) + +if Python35(): + from IceFuture import FutureBase, wrap_future +else: + FutureBase = object + +class Future(FutureBase): + def __init__(self): + self._result = None + self._exception = None + self._condition = threading.Condition() + self._doneCallbacks = [] + self._state = Future.StateRunning + + def cancel(self): + callbacks = [] + with self._condition: + if self._state == Future.StateDone: + return False + + if self._state == Future.StateCancelled: + return True + + self._state = Future.StateCancelled + callbacks = self._doneCallbacks + self._doneCallbacks = [] + self._condition.notify_all() + + self._callCallbacks(callbacks) + + return True + + def cancelled(self): + with self._condition: + return self._state == Future.StateCancelled + + def running(self): + with self._condition: + return self._state == Future.StateRunning + + def done(self): + with self._condition: + return self._state in [Future.StateCancelled, Future.StateDone] + + def add_done_callback(self, fn): + with self._condition: + if self._state == Future.StateRunning: + self._doneCallbacks.append(fn) + return + fn(self) + + def result(self, timeout=None): + with self._condition: + if not self._wait(timeout, lambda: self._state == Future.StateRunning): + raise TimeoutException() + if self._state == Future.StateCancelled: + raise InvocationCanceledException() + elif self._exception: + raise self._exception + else: + return self._result + + def exception(self, timeout=None): + with self._condition: + if not self._wait(timeout, lambda: self._state == Future.StateRunning): + raise TimeoutException() + if self._state == Future.StateCancelled: + raise InvocationCanceledException() + else: + return self._exception + + def set_result(self, result): + callbacks = [] + with self._condition: + if self._state != Future.StateRunning: + return + self._result = result + self._state = Future.StateDone + callbacks = self._doneCallbacks + self._doneCallbacks = [] + self._condition.notify_all() + + self._callCallbacks(callbacks) + + def set_exception(self, ex): + callbacks = [] + with self._condition: + if self._state != Future.StateRunning: + return + self._exception = ex + self._state = Future.StateDone + callbacks = self._doneCallbacks + self._doneCallbacks = [] + self._condition.notify_all() + + self._callCallbacks(callbacks) + + @staticmethod + def completed(result): + f = Future() + f.set_result(result) + return f + + def _wait(self, timeout, testFn=None): + # Must be called with _condition acquired + + while testFn(): + if timeout: + start = time.time() + self._condition.wait(timeout) + # Subtract the elapsed time so far from the timeout + timeout -= (time.time() - start) + if timeout <= 0: + return False + else: + self._condition.wait() + + return True + + def _callCallbacks(self, callbacks): + for callback in callbacks: + try: + callback(self) + except: + logging.getLogger("Ice.Future").exception('callback raised exception') + + StateRunning = 'running' + StateCancelled = 'cancelled' + StateDone = 'done' + +class InvocationFuture(Future): + def __init__(self, operation, asyncResult): + Future.__init__(self) + self._operation = operation + self._asyncResult = asyncResult # May be None for a batch invocation. + self._sent = False + self._sentSynchronously = False + self._sentCallbacks = [] + + def cancel(self): + if self._asyncResult: + self._asyncResult.cancel() + return Future.cancel(self) + + def is_sent(self): + with self._condition: + return self._sent + + def is_sent_synchronously(self): + with self._condition: + return self._sentSynchronously + + def add_sent_callback(self, fn): + with self._condition: + if not self._sent: + self._sentCallbacks.append(fn) + return + if self._sentSynchronously or not self._asyncResult: + fn(self, self._sentSynchronously) + else: + self._asyncResult.callLater(lambda: fn(self, self._sentSynchronously)) + + def sent(self, timeout=None): + with self._condition: + if not self._wait(timeout, lambda: not self._sent): + raise TimeoutException() + if self._state == Future.StateCancelled: + raise InvocationCanceledException() + elif self._exception: + raise self._exception + else: + return self._sentSynchronously + + def set_sent(self, sentSynchronously): + callbacks = [] + with self._condition: + if self._sent: + return + + self._sent = True + self._sentSynchronously = sentSynchronously + callbacks = self._sentCallbacks + self._sentCallbacks = [] + self._condition.notify_all() + + for callback in callbacks: + try: + callback(self, sentSynchronously) + except Exception: + logging.getLogger("Ice.Future").exception('callback raised exception') + + def operation(self): + return self._operation + + def proxy(self): + return None if not self._asyncResult else self._asyncResult.getProxy() + + def connection(self): + return None if not self._asyncResult else self._asyncResult.getConnection() + + def communicator(self): + return None if not self._asyncResult else self._asyncResult.getCommunicator() + # # This value is used as the default value for struct types in the constructors # of user-defined types. It allows us to determine whether the application has @@ -86,6 +291,40 @@ _struct_marker = object() # # Core Ice types. # +class Value(object): + def ice_id(): + '''Obtains the type id corresponding to the most-derived Slice +interface supported by the target object. +Returns: + The type id. +''' + return '::Ice::Object' + + @staticmethod + def ice_staticId(): + '''Obtains the type id of this Slice class or interface. +Returns: + The type id. +''' + return '::Ice::Object' + + # + # Do not define these here. They will be invoked if defined by a subclass. + # + #def ice_preMarshal(self): + # pass + # + #def ice_postUnmarshal(self): + # pass + +class InterfaceByValue(Value): + + def __init__(self, id): + self.id = id + + def ice_id(self): + return self.id + class Object(object): def ice_isA(self, id, current=None): '''Determines whether the target object supports the interface denoted @@ -117,28 +356,53 @@ Returns: ''' return '::Ice::Object' + @staticmethod def ice_staticId(): '''Obtains the type id of this Slice class or interface. Returns: The type id. ''' return '::Ice::Object' - ice_staticId = staticmethod(ice_staticId) - # - # Do not define these here. They will be invoked if defined by a subclass. - # - #def ice_preMarshal(self): - # pass - # - #def ice_postUnmarshal(self): - # pass + def _iceDispatch(self, cb, method, args): + # Invoke the given servant method. Exceptions can propagate to the caller. + result = method(*args) + + # Check for a future. + if isinstance(result, Future) or callable(getattr(result, "add_done_callback", None)): + def handler(future): + try: + cb.response(future.result()) + except: + cb.exception(sys.exc_info()[1]) + result.add_done_callback(handler) + elif Python35() and inspect.iscoroutine(result): # The iscoroutine() function was added in Python 3.5. + self._iceDispatchCoroutine(cb, result) + else: + cb.response(result) -# -# LocalObject is deprecated; use the Python base 'object' type instead. -# -class LocalObject(object): - pass + def _iceDispatchCoroutine(self, cb, coro, value=None, exception=None): + try: + if exception: + result = coro.throw(exception) + else: + result = coro.send(value) + + # Calling 'await <future>' will return the future. Check if we've received a future. + if isinstance(result, Future) or callable(getattr(result, "add_done_callback", None)): + def handler(future): + try: + self._iceDispatchCoroutine(cb, coro, value=future.result()) + except: + self._iceDispatchCoroutine(cb, coro, exception=sys.exc_info()[1]) + result.add_done_callback(handler) + else: + raise RuntimeError('unexpected value of type ' + str(type(result)) + ' provided by coroutine') + except StopIteration as ex: + # StopIteration is raised when the coroutine completes. + cb.response(ex.value) + except: + cb.exception(sys.exc_info()[1]) class Blobject(Object): '''Special-purpose servant base class that allows a subclass to @@ -178,7 +442,11 @@ class Exception(Exception): # Derives from built-in base 'Exception' class. def ice_name(self): '''Returns the type name of this exception.''' - return self._ice_name + return self.ice_id()[2:] + + def ice_id(self): + '''Returns the type id of this exception.''' + return self._ice_id class LocalException(Exception): '''The base class for all Ice run-time exceptions.''' @@ -268,7 +536,7 @@ class SliceInfo(object): # typeId - string # compactId - int # bytes - string - # objects - tuple of Ice.Object + # objects - tuple of Ice.Value pass # @@ -283,7 +551,7 @@ class PropertiesAdminUpdateCallback(object): def updated(self, props): pass -class UnknownSlicedObject(Object): +class UnknownSlicedValue(Value): # # Members: # @@ -415,6 +683,7 @@ FormatType.SlicedFormat = FormatType(2) # Forward declarations. # IcePy._t_Object = IcePy.declareClass('::Ice::Object') +IcePy._t_Value = IcePy.declareValue('::Ice::Object') IcePy._t_ObjectPrx = IcePy.declareProxy('::Ice::Object') IcePy._t_LocalObject = IcePy.declareClass('::Ice::LocalObject') @@ -435,8 +704,8 @@ sliceChecksums = {} # Import generated Ice modules. # import Ice_BuiltinSequences_ice -import Ice_Communicator_ice import Ice_Current_ice +import Ice_Communicator_ice import Ice_ImplicitContext_ice import Ice_Endpoint_ice import Ice_EndpointTypes_ice @@ -446,6 +715,7 @@ import Ice_Locator_ice import Ice_Logger_ice import Ice_ObjectAdapter_ice import Ice_ObjectFactory_ice +import Ice_ValueFactory_ice import Ice_Process_ice import Ice_Properties_ice import Ice_RemoteLogger_ice @@ -473,7 +743,6 @@ del OpaqueEndpointInfo OpaqueEndpointInfo = IcePy.OpaqueEndpointInfo SSLEndpointInfo = IcePy.SSLEndpointInfo -WSSEndpointInfo = IcePy.WSSEndpointInfo # # Replace ConnectionInfo with our implementation. @@ -490,7 +759,6 @@ del WSConnectionInfo WSConnectionInfo = IcePy.WSConnectionInfo SSLConnectionInfo = IcePy.SSLConnectionInfo -WSSConnectionInfo = IcePy.WSSConnectionInfo class ThreadNotification(object): '''Base class for thread notification callbacks. A subclass must @@ -560,6 +828,7 @@ threadHook: An object that implements ThreadNotification. self.logger = None self.threadHook = None self.batchRequestInterceptor = None + self.valueFactoryManager = None # # Communicator wrapper. @@ -569,6 +838,12 @@ class CommunicatorI(Communicator): self._impl = impl impl._setWrapper(self) + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + self._impl.destroy() + def destroy(self): self._impl.destroy() @@ -618,11 +893,15 @@ class CommunicatorI(Communicator): return ObjectAdapterI(adapter) def addObjectFactory(self, factory, id): - self._impl.addObjectFactory(factory, id) + # The extension implementation requires an extra argument that is a value factory + self._impl.addObjectFactory(factory, id, lambda s, factory=factory: factory.create(s)) def findObjectFactory(self, id): return self._impl.findObjectFactory(id) + def getValueFactoryManager(self): + return self._impl.getValueFactoryManager() + def getImplicitContext(self): context = self._impl.getImplicitContext() if context == None: @@ -659,11 +938,14 @@ class CommunicatorI(Communicator): def getPluginManager(self): raise RuntimeError("operation `getPluginManager' not implemented") - def flushBatchRequests(self): - self._impl.flushBatchRequests() + def flushBatchRequests(self, compress): + self._impl.flushBatchRequests(compress) + + def flushBatchRequestsAsync(self, compress): + return self._impl.flushBatchRequestsAsync(compress) - def begin_flushBatchRequests(self, _ex=None, _sent=None): - return self._impl.begin_flushBatchRequests(_ex, _sent) + def begin_flushBatchRequests(self, compress, _ex=None, _sent=None): + return self._impl.begin_flushBatchRequests(compress, _ex, _sent) def end_flushBatchRequests(self, r): return self._impl.end_flushBatchRequests(r) @@ -708,8 +990,8 @@ the list that were recognized by the Ice run time. # # Ice.identityToString # -def identityToString(id): - return IcePy.identityToString(id) +def identityToString(id, toStringMode=None): + return IcePy.identityToString(id, toStringMode) # # Ice.stringToIdentity @@ -833,15 +1115,18 @@ class ObjectAdapterI(ObjectAdapter): def getLocator(self): return self._impl.getLocator() - def refreshPublishedEndpoints(self): - self._impl.refreshPublishedEndpoints() - def getEndpoints(self): return self._impl.getEndpoints() + def refreshPublishedEndpoints(self): + self._impl.refreshPublishedEndpoints() + def getPublishedEndpoints(self): return self._impl.getPublishedEndpoints() + def setPublishedEndpoints(self, newEndpoints): + self._impl.setPublishedEndpoints(newEndpoints) + # # Logger wrapper. # @@ -1493,7 +1778,8 @@ signal, or False otherwise.''' # # Define Ice::Object and Ice::ObjectPrx. # -IcePy._t_Object = IcePy.defineClass('::Ice::Object', Object, -1, (), False, False, None, (), ()) +IcePy._t_Object = IcePy.defineClass('::Ice::Object', Object, (), None, ()) +IcePy._t_Value = IcePy.defineValue('::Ice::Object', Value, -1, (), False, False, None, ()) IcePy._t_ObjectPrx = IcePy.defineProxy('::Ice::Object', ObjectPrx) Object._ice_type = IcePy._t_Object @@ -1502,10 +1788,10 @@ Object._op_ice_ping = IcePy.Operation('ice_ping', OperationMode.Idempotent, Oper Object._op_ice_ids = IcePy.Operation('ice_ids', OperationMode.Idempotent, OperationMode.Nonmutating, False, None, (), (), (), ((), _t_StringSeq, False, 0), ()) Object._op_ice_id = IcePy.Operation('ice_id', OperationMode.Idempotent, OperationMode.Nonmutating, False, None, (), (), (), ((), IcePy._t_string, False, 0), ()) -IcePy._t_LocalObject = IcePy.defineClass('::Ice::LocalObject', object, -1, (), False, False, None, (), ()) +IcePy._t_LocalObject = IcePy.defineValue('::Ice::LocalObject', object, -1, (), False, False, None, ()) -IcePy._t_UnknownSlicedObject = IcePy.defineClass('::Ice::UnknownSlicedObject', UnknownSlicedObject, -1, (), False, True, None, (), ()) -UnknownSlicedObject._ice_type = IcePy._t_UnknownSlicedObject +IcePy._t_UnknownSlicedValue = IcePy.defineValue('::Ice::UnknownSlicedValue', UnknownSlicedValue, -1, (), True, False, None, ()) +UnknownSlicedValue._ice_type = IcePy._t_UnknownSlicedValue # # Annotate some exceptions. diff --git a/python/python/Ice/msbuild/ice.proj b/python/python/Ice/msbuild/ice.proj new file mode 100644 index 00000000000..282bf52a515 --- /dev/null +++ b/python/python/Ice/msbuild/ice.proj @@ -0,0 +1,58 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + + <PropertyGroup Label="IceBuilder"> + <IceBuilderAllowIcePrefix>true</IceBuilderAllowIcePrefix> + <IceBuilderPrefix>Ice_</IceBuilderPrefix> + <IceBuilderOutputDir>..\..</IceBuilderOutputDir> + <IceBuilderNoPackage>yes</IceBuilderNoPackage> + <IceBuilderDependFile>$(MSBuildProjectDirectory)\IceBuilder.d</IceBuilderDependFile> + <IceBuilderCommandLog>$(MSBuildProjectDirectory)\IceBuilder.command.log</IceBuilderCommandLog> + </PropertyGroup> + <Import Project="..\..\..\msbuild\ice.props" /> + <Import Project="$(IceBuilderPythonProps)" Condition="Exists('$(IceBuilderPythonProps)')"/> + + <ItemGroup> + <IceBuilder Include="..\..\..\..\slice\Ice\BuiltinSequences.ice" /> + <IceBuilder Include="..\..\..\..\slice\Ice\Communicator.ice" /> + <IceBuilder Include="..\..\..\..\slice\Ice\CommunicatorF.ice" /> + <IceBuilder Include="..\..\..\..\slice\Ice\Connection.ice" /> + <IceBuilder Include="..\..\..\..\slice\Ice\ConnectionF.ice" /> + <IceBuilder Include="..\..\..\..\slice\Ice\Current.ice" /> + <IceBuilder Include="..\..\..\..\slice\Ice\Endpoint.ice" /> + <IceBuilder Include="..\..\..\..\slice\Ice\EndpointF.ice" /> + <IceBuilder Include="..\..\..\..\slice\Ice\EndpointTypes.ice" /> + <IceBuilder Include="..\..\..\..\slice\Ice\FacetMap.ice" /> + <IceBuilder Include="..\..\..\..\slice\Ice\Identity.ice" /> + <IceBuilder Include="..\..\..\..\slice\Ice\ImplicitContext.ice" /> + <IceBuilder Include="..\..\..\..\slice\Ice\ImplicitContextF.ice" /> + <IceBuilder Include="..\..\..\..\slice\Ice\Instrumentation.ice" /> + <IceBuilder Include="..\..\..\..\slice\Ice\InstrumentationF.ice" /> + <IceBuilder Include="..\..\..\..\slice\Ice\LocalException.ice" /> + <IceBuilder Include="..\..\..\..\slice\Ice\Locator.ice" /> + <IceBuilder Include="..\..\..\..\slice\Ice\LocatorF.ice" /> + <IceBuilder Include="..\..\..\..\slice\Ice\Logger.ice" /> + <IceBuilder Include="..\..\..\..\slice\Ice\LoggerF.ice" /> + <IceBuilder Include="..\..\..\..\slice\Ice\ObjectAdapter.ice" /> + <IceBuilder Include="..\..\..\..\slice\Ice\ObjectAdapterF.ice" /> + <IceBuilder Include="..\..\..\..\slice\Ice\ObjectFactory.ice" /> + <IceBuilder Include="..\..\..\..\slice\Ice\Plugin.ice" /> + <IceBuilder Include="..\..\..\..\slice\Ice\PluginF.ice" /> + <IceBuilder Include="..\..\..\..\slice\Ice\Process.ice" /> + <IceBuilder Include="..\..\..\..\slice\Ice\ProcessF.ice" /> + <IceBuilder Include="..\..\..\..\slice\Ice\Properties.ice" /> + <IceBuilder Include="..\..\..\..\slice\Ice\PropertiesAdmin.ice" /> + <IceBuilder Include="..\..\..\..\slice\Ice\PropertiesF.ice" /> + <IceBuilder Include="..\..\..\..\slice\Ice\RemoteLogger.ice" /> + <IceBuilder Include="..\..\..\..\slice\Ice\Router.ice" /> + <IceBuilder Include="..\..\..\..\slice\Ice\RouterF.ice" /> + <IceBuilder Include="..\..\..\..\slice\Ice\ServantLocator.ice" /> + <IceBuilder Include="..\..\..\..\slice\Ice\ServantLocatorF.ice" /> + <IceBuilder Include="..\..\..\..\slice\Ice\SliceChecksumDict.ice" /> + <IceBuilder Include="..\..\..\..\slice\Ice\ValueFactory.ice" /> + <IceBuilder Include="..\..\..\..\slice\Ice\Version.ice" /> + </ItemGroup> + <Target Name="Build"/> + <Target Name="Clean"/> + <Import Project="$(IceBuilderPythonTargets)" Condition="Exists('$(IceBuilderPythonTargets)')"/> +</Project> diff --git a/python/python/IceBox/msbuild/icebox.proj b/python/python/IceBox/msbuild/icebox.proj new file mode 100644 index 00000000000..83c41eebf1e --- /dev/null +++ b/python/python/IceBox/msbuild/icebox.proj @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup Label="IceBuilder"> + <IceBuilderAllowIcePrefix>true</IceBuilderAllowIcePrefix> + <IceBuilderPrefix>IceBox_</IceBuilderPrefix> + <IceBuilderOutputDir>..\..</IceBuilderOutputDir> + <IceBuilderDependFile>$(MSBuildProjectDirectory)\IceBuilder.d</IceBuilderDependFile> + <IceBuilderCommandLog>$(MSBuildProjectDirectory)\IceBuilder.command.log</IceBuilderCommandLog> + </PropertyGroup> + <Import Project="..\..\..\msbuild\ice.props" /> + <Import Project="$(IceBuilderPythonProps)" Condition="Exists('$(IceBuilderPythonProps)')"/> + <ItemGroup> + <IceBuilder Include="..\..\..\..\slice\IceBox\IceBox.ice" /> + </ItemGroup> + <Target Name="Build"/> + <Target Name="Clean"/> + <Import Project="$(IceBuilderPythonTargets)" Condition="Exists('$(IceBuilderPythonTargets)')"/> +</Project> diff --git a/python/python/IceFuture.py b/python/python/IceFuture.py new file mode 100644 index 00000000000..c79c5b8d512 --- /dev/null +++ b/python/python/IceFuture.py @@ -0,0 +1,48 @@ +# ********************************************************************** +# +# Copyright (c) 2003-2016 ZeroC, Inc. All rights reserved. +# +# This copy of Ice is licensed to you under the terms described in the +# ICE_LICENSE file included in this distribution. +# +# ********************************************************************** + +# +# This file should only be used in Python >= 3.5. +# + +import asyncio + +# +# This class defines an __await__ method so that coroutines can call 'await <future>'. +# +# Python 2.x rejects this code with a syntax error because a return statement is not allowed in a generator. +# +class FutureBase(object): + def __await__(self): + if not self.done(): + yield self + return self.result() + +def wrap_future(future, *, loop=None): + '''Wrap Ice.Future object into an asyncio.Future.''' + if isinstance(future, asyncio.Future): + return future + + assert isinstance(future, FutureBase), 'Ice.Future is expected, got {!r}'.format(future) + + if loop is None: + loop = asyncio.get_event_loop() + + af = loop.create_future() + + def callback(): + if future.cancelled(): + af.cancel() + elif future.exception(): + af.set_exception(future.exception()) + else: + af.set_result(future.result()) + + future.add_done_callback(lambda f: loop.call_soon_threadsafe(callback)) + return af diff --git a/python/python/IceGrid/msbuild/icegrid.proj b/python/python/IceGrid/msbuild/icegrid.proj new file mode 100644 index 00000000000..c97521a17cf --- /dev/null +++ b/python/python/IceGrid/msbuild/icegrid.proj @@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup Label="IceBuilder"> + <IceBuilderAllowIcePrefix>true</IceBuilderAllowIcePrefix> + <IceBuilderPrefix>IceGrid_</IceBuilderPrefix> + <IceBuilderOutputDir>..\..</IceBuilderOutputDir> + <IceBuilderDependFile>$(MSBuildProjectDirectory)\IceBuilder.d</IceBuilderDependFile> + <IceBuilderCommandLog>$(MSBuildProjectDirectory)\IceBuilder.command.log</IceBuilderCommandLog> + </PropertyGroup> + <Import Project="..\..\..\msbuild\ice.props" /> + <Import Project="$(IceBuilderPythonProps)" /> + <ItemGroup> + <IceBuilder Include="..\..\..\..\slice\IceGrid\Admin.ice" /> + <IceBuilder Include="..\..\..\..\slice\IceGrid\Descriptor.ice" /> + <IceBuilder Include="..\..\..\..\slice\IceGrid\Exception.ice" /> + <IceBuilder Include="..\..\..\..\slice\IceGrid\FileParser.ice" /> + <IceBuilder Include="..\..\..\..\slice\IceGrid\Registry.ice" /> + <IceBuilder Include="..\..\..\..\slice\IceGrid\Session.ice" /> + <IceBuilder Include="..\..\..\..\slice\IceGrid\UserAccountMapper.ice" /> + </ItemGroup> + + <Target Name="Build"/> + <Target Name="Clean"/> + <Import Project="$(IceBuilderPythonTargets)" /> +</Project> diff --git a/python/python/IceMX/msbuild/glacier2.proj b/python/python/IceMX/msbuild/glacier2.proj new file mode 100644 index 00000000000..b8d9ece2b4f --- /dev/null +++ b/python/python/IceMX/msbuild/glacier2.proj @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup Label="IceBuilder"> + <IceBuilderAllowIcePrefix>true</IceBuilderAllowIcePrefix> + <IceBuilderPrefix>Glacier2_</IceBuilderPrefix> + <IceBuilderOutputDir>..\..</IceBuilderOutputDir> + <IceBuilderDependFile>$(MSBuildProjectDirectory)\glacier2\IceBuilder.d</IceBuilderDependFile> + <IceBuilderCommandLog>$(MSBuildProjectDirectory)\glacier2\IceBuilder.command.log</IceBuilderCommandLog> + </PropertyGroup> + <Import Project="..\..\..\msbuild\ice.props" /> + <Import Project="$(IceBuilderPythonProps)" /> + <ItemGroup> + <IceBuilder Include="..\..\..\..\slice\Glacier2\Metrics.ice" /> + </ItemGroup> + <Target Name="Build"/> + <Target Name="Clean"/> + <Import Project="$(IceBuilderPythonTargets)" /> +</Project> diff --git a/python/python/IceMX/msbuild/ice.proj b/python/python/IceMX/msbuild/ice.proj new file mode 100644 index 00000000000..61d1d021d18 --- /dev/null +++ b/python/python/IceMX/msbuild/ice.proj @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup Label="IceBuilder"> + <IceBuilderAllowIcePrefix>true</IceBuilderAllowIcePrefix> + <IceBuilderPrefix>Ice_</IceBuilderPrefix> + <IceBuilderOutputDir>..\..</IceBuilderOutputDir> + <IceBuilderDependFile>$(MSBuildProjectDirectory)\ice\IceBuilder.d</IceBuilderDependFile> + <IceBuilderCommandLog>$(MSBuildProjectDirectory)\ice\IceBuilder.command.log</IceBuilderCommandLog> + </PropertyGroup> + <Import Project="..\..\..\msbuild\ice.props" /> + <Import Project="$(IceBuilderPythonProps)" /> + <ItemGroup> + <IceBuilder Include="..\..\..\..\slice\Ice\Metrics.ice" /> + </ItemGroup> + <Target Name="Build"/> + <Target Name="Clean"/> + <Import Project="$(IceBuilderPythonTargets)" /> +</Project> diff --git a/python/python/IceMX/msbuild/icestorm.proj b/python/python/IceMX/msbuild/icestorm.proj new file mode 100644 index 00000000000..4dc8eb0d5d3 --- /dev/null +++ b/python/python/IceMX/msbuild/icestorm.proj @@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup Label="Globals"> + <IceBuilderPythonProps Condition="!Exists('$(IceBuilderPythonProps)')">$([System.IO.Directory]::GetFiles('$(LocalAppData)\Microsoft\VisualStudio\$(VisualStudioVersion)\Extensions', 'IceBuilder.Python.props', SearchOption.AllDirectories))</IceBuilderPythonProps> + <IceBuilderPythonTargets Condition="!Exists('$(IceBuilderPythonTargets)')">$([System.IO.Directory]::GetFiles('$(LocalAppData)\Microsoft\VisualStudio\$(VisualStudioVersion)\Extensions', 'IceBuilder.Python.targets', SearchOption.AllDirectories))</IceBuilderPythonTargets> + <IntDir>$(MSbuildThisFileDirectory)$(Configuration)\$(Platform)\icestorm</IntDir> + <IceBuilderDependFile>$(IntDir)\IceBuilder.d</IceBuilderDependFile> + <IceBuilderCommandLog>$(IntDir)\IceBuilder.command.log</IceBuilderCommandLog> + </PropertyGroup> + <Import Project="..\..\..\msbuild\ice.props" /> + <Import Project="$(IceBuilderPythonProps)" /> + <ItemGroup> + <IceBuilder Include="..\..\..\..\slice\IceStorm\Metrics.ice" /> + </ItemGroup> + <PropertyGroup Label="IceBuilder"> + <IceBuilderAllowIcePrefix>true</IceBuilderAllowIcePrefix> + <IceBuilderPrefix>IceStorm_</IceBuilderPrefix> + <IceBuilderOutputDir>..\..</IceBuilderOutputDir> + <IceBuilderDependFile>$(MSBuildProjectDirectory)\icestorm\IceBuilder.d</IceBuilderDependFile> + <IceBuilderCommandLog>$(MSBuildProjectDirectory)\icestorm\IceBuilder.command.log</IceBuilderCommandLog> + </PropertyGroup> + <Target Name="Build"/> + <Target Name="Clean"/> + <Import Project="$(IceBuilderPythonTargets)" /> +</Project> diff --git a/python/python/IcePatch2/msbuild/icepatch2.proj b/python/python/IcePatch2/msbuild/icepatch2.proj new file mode 100644 index 00000000000..038105f4df1 --- /dev/null +++ b/python/python/IcePatch2/msbuild/icepatch2.proj @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup Label="IceBuilder"> + <IceBuilderAllowIcePrefix>true</IceBuilderAllowIcePrefix> + <IceBuilderPrefix>IcePatch2_</IceBuilderPrefix> + <IceBuilderOutputDir>..\..</IceBuilderOutputDir> + <IceBuilderDependFile>$(MSBuildProjectDirectory)\IceBuilder.d</IceBuilderDependFile> + <IceBuilderCommandLog>$(MSBuildProjectDirectory)\IceBuilder.command.log</IceBuilderCommandLog> + </PropertyGroup> + <Import Project="..\..\..\msbuild\ice.props" /> + <Import Project="$(IceBuilderPythonProps)" /> + <ItemGroup> + <IceBuilder Include="..\..\..\..\slice\IcePatch2\FileServer.ice" /> + <IceBuilder Include="..\..\..\..\slice\IcePatch2\FileInfo.ice" /> + </ItemGroup> + <Target Name="Build"/> + <Target Name="Clean"/> + <Import Project="$(IceBuilderPythonTargets)" /> +</Project> diff --git a/python/python/IceStorm/msbuild/icestorm.proj b/python/python/IceStorm/msbuild/icestorm.proj new file mode 100644 index 00000000000..9d46163bc28 --- /dev/null +++ b/python/python/IceStorm/msbuild/icestorm.proj @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup Label="IceBuilder"> + <IceBuilderAllowIcePrefix>true</IceBuilderAllowIcePrefix> + <IceBuilderPrefix>IceStorm_</IceBuilderPrefix> + <IceBuilderOutputDir>..\..</IceBuilderOutputDir> + <IceBuilderDependFile>$(MSBuildProjectDirectory)\IceBuilder.d</IceBuilderDependFile> + <IceBuilderCommandLog>$(MSBuildProjectDirectory)\IceBuilder.command.log</IceBuilderCommandLog> + </PropertyGroup> + <Import Project="..\..\..\msbuild\ice.props" /> + <Import Project="$(IceBuilderPythonProps)" /> + <ItemGroup> + <IceBuilder Include="..\..\..\..\slice\IceStorm\IceStorm.ice" /> + </ItemGroup> + <Target Name="Build"/> + <Target Name="Clean"/> + <Import Project="$(IceBuilderPythonTargets)" /> +</Project> diff --git a/python/python/Makefile b/python/python/Makefile index 78c407aa413..0fe37aa6a6b 100644 --- a/python/python/Makefile +++ b/python/python/Makefile @@ -7,150 +7,32 @@ # # ********************************************************************** -top_srcdir = .. +top_srcdir := ../.. +lang_srcdir := $(top_srcdir)/python include $(top_srcdir)/config/Make.rules +include $(lang_srcdir)/config/Make.rules # -# Parallel builds are not supported because multiple executions of slice2py could -# attempt to modify the __init__.py file simultaneously. +# Load C++ dependencies # -.NOTPARALLEL: - -ICE_SRCS = Ice_BuiltinSequences_ice.py \ - Ice_Communicator_ice.py \ - Ice_CommunicatorF_ice.py \ - Ice_Connection_ice.py \ - Ice_ConnectionF_ice.py \ - Ice_Current_ice.py \ - Ice_Endpoint_ice.py \ - Ice_EndpointF_ice.py \ - Ice_EndpointTypes_ice.py \ - Ice_FacetMap_ice.py \ - Ice_Identity_ice.py \ - Ice_ImplicitContext_ice.py \ - Ice_ImplicitContextF_ice.py \ - Ice_Instrumentation_ice.py \ - Ice_InstrumentationF_ice.py \ - Ice_LocalException_ice.py \ - Ice_Locator_ice.py \ - Ice_LocatorF_ice.py \ - Ice_Logger_ice.py \ - Ice_LoggerF_ice.py \ - Ice_Metrics_ice.py \ - Ice_ObjectAdapter_ice.py \ - Ice_ObjectAdapterF_ice.py \ - Ice_ObjectFactory_ice.py \ - Ice_ObjectFactoryF_ice.py \ - Ice_Plugin_ice.py \ - Ice_PluginF_ice.py \ - Ice_Process_ice.py \ - Ice_ProcessF_ice.py \ - Ice_Properties_ice.py \ - Ice_PropertiesAdmin_ice.py \ - Ice_PropertiesF_ice.py \ - Ice_RemoteLogger_ice.py \ - Ice_Router_ice.py \ - Ice_RouterF_ice.py \ - Ice_ServantLocator_ice.py \ - Ice_ServantLocatorF_ice.py \ - Ice_SliceChecksumDict_ice.py \ - Ice_Version_ice.py - -GLACIER2_SRCS = Glacier2_Metrics_ice.py \ - Glacier2_PermissionsVerifier_ice.py \ - Glacier2_PermissionsVerifierF_ice.py \ - Glacier2_Router_ice.py \ - Glacier2_RouterF_ice.py \ - Glacier2_Session_ice.py \ - Glacier2_SSLInfo_ice.py - -ICEBOX_SRCS = IceBox_IceBox_ice.py - -ICEGRID_SRCS = IceGrid_Admin_ice.py \ - IceGrid_Descriptor_ice.py \ - IceGrid_Exception_ice.py \ - IceGrid_FileParser_ice.py \ - IceGrid_Locator_ice.py \ - IceGrid_Observer_ice.py \ - IceGrid_Query_ice.py \ - IceGrid_Registry_ice.py \ - IceGrid_Session_ice.py \ - IceGrid_UserAccountMapper_ice.py - -ICEPATCH2_SRCS = IcePatch2_FileInfo_ice.py \ - IcePatch2_FileServer_ice.py - -ICESTORM_SRCS = IceStorm_IceStorm_ice.py \ - IceStorm_Metrics_ice.py - -ALL_SRCS = $(ICE_SRCS) \ - $(GLACIER2_SRCS) \ - $(ICEBOX_SRCS) \ - $(ICEGRID_SRCS) \ - $(ICEPATCH2_SRCS) \ - $(ICESTORM_SRCS) - -ICE_SLICE = $(patsubst Ice_%_ice.py,$(slicedir)/Ice/%.ice,$(ICE_SRCS)) -GLACIER2_SLICE = $(patsubst Glacier2_%_ice.py,$(slicedir)/Glacier2/%.ice,$(GLACIER2_SRCS)) -ICEBOX_SLICE = $(patsubst IceBox_%_ice.py,$(slicedir)/IceBox/%.ice,$(ICEBOX_SRCS)) -ICEGRID_SLICE = $(patsubst IceGrid_%_ice.py,$(slicedir)/IceGrid/%.ice,$(ICEGRID_SRCS)) -ICEPATCH2_SLICE = $(patsubst IcePatch2_%_ice.py,$(slicedir)/IcePatch2/%.ice,$(ICEPATCH2_SRCS)) -ICESTORM_SLICE = $(patsubst IceStorm_%_ice.py,$(slicedir)/IceStorm/%.ice,$(ICESTORM_SRCS)) +$(eval $(call load-translator-dependencies,$(top_srcdir)/cpp/src/slice2py)) -PACKAGES = IceBox IceGrid IcePatch2 IceStorm IceMX - -all:: $(ALL_SRCS) - -SLICE2PYFLAGS += --ice - -Ice_%_ice.py: $(slicedir)/Ice/%.ice $(SLICEPARSERLIB) - $(SLICE2PY) --prefix Ice_ --no-package $(SLICE2PYFLAGS) $< - @mkdir -p .depend - @$(SLICE2PY) --prefix Ice_ --no-package $(SLICE2PYFLAGS) --depend $< > .depend/$(*F).ice.d - -Ice_Metrics_ice.py: $(slicedir)/Ice/Metrics.ice $(SLICEPARSERLIB) - $(SLICE2PY) --prefix Ice_ --checksum $(SLICE2PYFLAGS) $< - @mkdir -p .depend - @$(SLICE2PY) --prefix Ice_ --checksum $(SLICE2PYFLAGS) --depend $< > .depend/$(*F).ice.d - -Glacier2_%_ice.py: $(slicedir)/Glacier2/%.ice $(SLICEPARSERLIB) - $(SLICE2PY) --prefix Glacier2_ --no-package --checksum $(SLICE2PYFLAGS) $< - @mkdir -p .depend - @$(SLICE2PY) --prefix Glacier2_ --no-package --checksum $(SLICE2PYFLAGS) --depend $< > .depend/$(*F).ice.d - -Glacier2_Metrics_ice.py: $(slicedir)/Glacier2/Metrics.ice $(SLICEPARSERLIB) - $(SLICE2PY) --prefix Glacier2_ --checksum $(SLICE2PYFLAGS) $< - @mkdir -p .depend - @$(SLICE2PY) --prefix Glacier2_ --checksum $(SLICE2PYFLAGS) --depend $< > .depend/$(*F).ice.d - -IceBox_%_ice.py: $(slicedir)/IceBox/%.ice $(SLICEPARSERLIB) - $(SLICE2PY) --prefix IceBox_ --checksum $(SLICE2PYFLAGS) $< - @mkdir -p .depend - @$(SLICE2PY) --prefix IceBox_ --checksum $(SLICE2PYFLAGS) --depend $< > .depend/$(*F).ice.d - -IceGrid_%_ice.py: $(slicedir)/IceGrid/%.ice $(SLICEPARSERLIB) - $(SLICE2PY) --prefix IceGrid_ --checksum $(SLICE2PYFLAGS) $< - @mkdir -p .depend - @$(SLICE2PY) --prefix IceGrid_ --checksum $(SLICE2PYFLAGS) --depend $< > .depend/$(*F).ice.d +.NOTPARALLEL: -IcePatch2_%_ice.py: $(slicedir)/IcePatch2/%.ice $(SLICEPARSERLIB) - $(SLICE2PY) --prefix IcePatch2_ --checksum $(SLICE2PYFLAGS) $< - @mkdir -p .depend - @$(SLICE2PY) --prefix IcePatch2_ --checksum $(SLICE2PYFLAGS) --depend $< > .depend/$(*F).ice.d +install:: | $(DESTDIR)$(install_pythondir) + $(E) "Installing generated code" + $(Q)$(INSTALL) *.py $(DESTDIR)$(install_pythondir) -IceStorm_%_ice.py: $(slicedir)/IceStorm/%.ice $(SLICEPARSERLIB) - $(SLICE2PY) --prefix IceStorm_ --checksum $(SLICE2PYFLAGS) $< - @mkdir -p .depend - @$(SLICE2PY) --prefix IceStorm_ --checksum $(SLICE2PYFLAGS) --depend $< > .depend/$(*F).ice.d +$(eval $(call make-python-package,$(slicedir),$(lang_srcdir)/python,Ice,--no-package)) +$(eval $(call make-python-package,$(slicedir),$(lang_srcdir)/python,Glacier2,--no-package)) +$(eval $(call make-python-package,$(slicedir),$(lang_srcdir)/python,IceBox)) +$(eval $(call make-python-package,$(slicedir),$(lang_srcdir)/python,IceGrid)) +$(eval $(call make-python-package,$(slicedir),$(lang_srcdir)/python,IcePatch2)) +$(eval $(call make-python-package,$(slicedir),$(lang_srcdir)/python,IceStorm)) -install:: $(ALL_SRCS) - @echo "Installing generated code" - $(INSTALL_DATA) *.py $(DESTDIR)$(install_pythondir) - @for i in $(PACKAGES) ; \ - do \ - $(INSTALL_DATA) -r $$i $(DESTDIR)$(install_pythondir) ; \ - done +# Generate this two files individually without the --no-package option to ensure the +# IceMX package is updated. +$(eval $(call make-python-slice,$(slicedir),$(lang_srcdir)/python,Ice,Metrics)) +$(eval $(call make-python-slice,$(slicedir),$(lang_srcdir)/python,Glacier2,Metrics)) -clean:: - rm -rf $(PACKAGES) *_ice.py diff --git a/python/python/Makefile.mak b/python/python/Makefile.mak deleted file mode 100644 index 4b55e6d8b63..00000000000 --- a/python/python/Makefile.mak +++ /dev/null @@ -1,361 +0,0 @@ -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -top_srcdir = .. - -!include $(top_srcdir)\config\Make.rules.mak - -ICE_SDIR = Ice - -ICE_SLICES = Ice\BuiltinSequences.ice \ - Ice\Communicator.ice \ - Ice\CommunicatorF.ice \ - Ice\Connection.ice \ - Ice\ConnectionF.ice \ - Ice\Current.ice \ - Ice\Endpoint.ice \ - Ice\EndpointF.ice \ - Ice\EndpointTypes.ice \ - Ice\FacetMap.ice \ - Ice\Identity.ice \ - Ice\ImplicitContext.ice \ - Ice\ImplicitContextF.ice \ - Ice\Instrumentation.ice \ - Ice\InstrumentationF.ice \ - Ice\LocalException.ice \ - Ice\Locator.ice \ - Ice\LocatorF.ice \ - Ice\Logger.ice \ - Ice\LoggerF.ice \ - Ice\Metrics.ice \ - Ice\ObjectAdapter.ice \ - Ice\ObjectAdapterF.ice \ - Ice\ObjectFactory.ice \ - Ice\ObjectFactoryF.ice \ - Ice\Plugin.ice \ - Ice\PluginF.ice \ - Ice\Process.ice \ - Ice\ProcessF.ice \ - Ice\Properties.ice \ - Ice\PropertiesAdmin.ice \ - Ice\PropertiesF.ice \ - Ice\RemoteLogger.ice \ - Ice\Router.ice \ - Ice\RouterF.ice \ - Ice\ServantLocator.ice \ - Ice\ServantLocatorF.ice \ - Ice\SliceChecksumDict.ice \ - Ice\Version.ice \ - -ICE_SRCS = $(ICE_SLICES:.ice=_ice.py) -ICE_SRCS = $(ICE_SRCS:Ice\=Ice_) - -GLACIER2_SDIR = Glacier2 - -GLACIER2_SLICES = Glacier2\Metrics.ice \ - Glacier2\PermissionsVerifier.ice \ - Glacier2\PermissionsVerifierF.ice \ - Glacier2\Router.ice \ - Glacier2\RouterF.ice \ - Glacier2\Session.ice \ - Glacier2\SSLInfo.ice \ - -GLACIER2_SRCS = $(GLACIER2_SLICES:.ice=_ice.py) -GLACIER2_SRCS = $(GLACIER2_SRCS:Glacier2\=Glacier2_) - -ICEBOX_SDIR = IceBox - -ICEBOX_SLICES = IceBox\IceBox.ice -ICEBOX_SRCS = $(ICEBOX_SLICES:.ice=_ice.py) -ICEBOX_SRCS = $(ICEBOX_SRCS:IceBox\=IceBox_) - -ICEGRID_SDIR = IceGrid - -ICEGRID_SLICES = IceGrid\Admin.ice \ - IceGrid\Descriptor.ice \ - IceGrid\Exception.ice \ - IceGrid\FileParser.ice \ - IceGrid\Locator.ice \ - IceGrid\Observer.ice \ - IceGrid\Query.ice \ - IceGrid\Registry.ice \ - IceGrid\Session.ice \ - IceGrid\UserAccountMapper.ice \ - -ICEGRID_SRCS = $(ICEGRID_SLICES:.ice=_ice.py) -ICEGRID_SRCS = $(ICEGRID_SRCS:IceGrid\=IceGrid_) - -ICEPATCH2_SDIR = IcePatch2 - -ICEPATCH2_SLICES = IcePatch2\FileInfo.ice \ - IcePatch2\FileServer.ice - -ICEPATCH2_SRCS = $(ICEPATCH2_SLICES:.ice=_ice.py) -ICEPATCH2_SRCS = $(ICEPATCH2_SRCS:IcePatch2\=IcePatch2_) - -ICESTORM_SDIR = IceStorm - -ICESTORM_SLICES = IceStorm\Metrics.ice \ - IceStorm\IceStorm.ice - -ICESTORM_SRCS = $(ICESTORM_SLICES:.ice=_ice.py) -ICESTORM_SRCS = $(ICESTORM_SRCS:IceStorm\=IceStorm_) - -DEPENDS = $(ICE_SLICES:.ice=.d) \ - $(GLACIER2_SLICES:.ice=.d) \ - $(ICEBOX_SLICES:.ice=.d) \ - $(ICEGRID_SLICES:.ice=.d) \ - $(ICEPATCH2_SLICES:.ice=.d) \ - $(ICESTORM_SLICES:.ice=.d) - -ALL_SRCS = $(ICE_SRCS) \ - $(GLACIER2_SRCS) \ - $(ICEBOX_SRCS) \ - $(ICEGRID_SRCS) \ - $(ICEPATCH2_SRCS) \ - $(ICESTORM_SRCS) - -PACKAGES = IceBox IceGrid IcePatch2 IceStorm IceMX - -SLICE2PYFLAGS = $(SLICE2PYFLAGS) --ice - -all:: $(ALL_SRCS) - -depend:: - del /q .depend.mak - -{$(slicedir)\$(ICE_SDIR)\}.ice{$(ICE_SDIR)\}.d: - @echo Generating dependencies for $< - @"$(SLICE2PY)" --prefix Ice_ --no-package $(SLICE2PYFLAGS) --depend "$<" | \ - cscript /NoLogo $(top_srcdir)\..\config\makedepend-slice.vbs $(*F).ice - -{$(slicedir)\$(GLACIER2_SDIR)\}.ice{$(GLACIER2_SDIR)\}.d: - @echo Generating dependencies for $< - @"$(SLICE2PY)" --prefix Glacier2_ --no-package $(SLICE2PYFLAGS) --depend "$<" | \ - cscript /NoLogo $(top_srcdir)\..\config\makedepend-slice.vbs $(*F).ice - -{$(slicedir)\$(ICEBOX_SDIR)\}.ice{$(ICEBOX_SDIR)\}.d: - @echo Generating dependencies for $< - @"$(SLICE2PY)" --prefix IceBox_ --no-package $(SLICE2PYFLAGS) --depend "$<" | \ - cscript /NoLogo $(top_srcdir)\..\config\makedepend-slice.vbs $(*F).ice - -{$(slicedir)\$(ICEGRID_SDIR)\}.ice{$(ICEGRID_SDIR)\}.d: - @echo Generating dependencies for $< - @"$(SLICE2PY)" --prefix IceGrid_ --no-package $(SLICE2PYFLAGS) --depend "$<" | \ - cscript /NoLogo $(top_srcdir)\..\config\makedepend-slice.vbs $(*F).ice - -{$(slicedir)\$(ICEPATCH2_SDIR)\}.ice{$(ICEPATCH2_SDIR)\}.d: - @echo Generating dependencies for $< - @"$(SLICE2PY)" --prefix IcePatch2_ --no-package $(SLICE2PYFLAGS) --depend "$<" | \ - cscript /NoLogo $(top_srcdir)\..\config\makedepend-slice.vbs $(*F).ice - -{$(slicedir)\$(ICESTORM_SDIR)\}.ice{$(ICESTORM_SDIR)\}.d: - @echo Generating dependencies for $< - @"$(SLICE2PY)" --prefix IceStorm_ --no-package $(SLICE2PYFLAGS) --depend "$<" | \ - cscript /NoLogo $(top_srcdir)\..\config\makedepend-slice.vbs $(*F).ice - -depend:: $(DEPENDS) - -Ice_LocalException_ice.py: "$(slicedir)/Ice/LocalException.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package "$(slicedir)/Ice/LocalException.ice" - -Ice_Communicator_ice.py: "$(slicedir)/Ice/Communicator.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package "$(slicedir)/Ice/Communicator.ice" - -Ice_CommunicatorF_ice.py: "$(slicedir)/Ice/CommunicatorF.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package "$(slicedir)/Ice/CommunicatorF.ice" - -Ice_Logger_ice.py: "$(slicedir)/Ice/Logger.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package "$(slicedir)/Ice/Logger.ice" - -Ice_LoggerF_ice.py: "$(slicedir)/Ice/LoggerF.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package "$(slicedir)/Ice/LoggerF.ice" - -Ice_BuiltinSequences_ice.py: "$(slicedir)/Ice/BuiltinSequences.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package "$(slicedir)/Ice/BuiltinSequences.ice" - -Ice_ObjectAdapter_ice.py: "$(slicedir)/Ice/ObjectAdapter.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package "$(slicedir)/Ice/ObjectAdapter.ice" - -Ice_ObjectAdapterF_ice.py: "$(slicedir)/Ice/ObjectAdapterF.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package "$(slicedir)/Ice/ObjectAdapterF.ice" - -Ice_ServantLocator_ice.py: "$(slicedir)/Ice/ServantLocator.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package "$(slicedir)/Ice/ServantLocator.ice" - -Ice_ServantLocatorF_ice.py: "$(slicedir)/Ice/ServantLocatorF.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package "$(slicedir)/Ice/ServantLocatorF.ice" - -Ice_PropertiesAdmin_ice.py: "$(slicedir)/Ice/PropertiesAdmin.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package "$(slicedir)/Ice/PropertiesAdmin.ice" - -Ice_Properties_ice.py: "$(slicedir)/Ice/Properties.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package "$(slicedir)/Ice/Properties.ice" - -Ice_PropertiesF_ice.py: "$(slicedir)/Ice/PropertiesF.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package "$(slicedir)/Ice/PropertiesF.ice" - -Ice_ObjectFactory_ice.py: "$(slicedir)/Ice/ObjectFactory.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package "$(slicedir)/Ice/ObjectFactory.ice" - -Ice_ObjectFactoryF_ice.py: "$(slicedir)/Ice/ObjectFactoryF.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package "$(slicedir)/Ice/ObjectFactoryF.ice" - -Ice_Identity_ice.py: "$(slicedir)/Ice/Identity.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package "$(slicedir)/Ice/Identity.ice" - -Ice_Current_ice.py: "$(slicedir)/Ice/Current.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package "$(slicedir)/Ice/Current.ice" - -Ice_ImplicitContext_ice.py: "$(slicedir)/Ice/ImplicitContext.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package "$(slicedir)/Ice/ImplicitContext.ice" - -Ice_ImplicitContextF_ice.py: "$(slicedir)/Ice/ImplicitContextF.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package "$(slicedir)/Ice/ImplicitContextF.ice" - -Ice_RemoteLogger_ice.py: "$(slicedir)/Ice/RemoteLogger.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package "$(slicedir)/Ice/RemoteLogger.ice" - -Ice_Router_ice.py: "$(slicedir)/Ice/Router.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package "$(slicedir)/Ice/Router.ice" - -Ice_RouterF_ice.py: "$(slicedir)/Ice/RouterF.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package "$(slicedir)/Ice/RouterF.ice" - -Ice_Plugin_ice.py: "$(slicedir)/Ice/Plugin.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package "$(slicedir)/Ice/Plugin.ice" - -Ice_PluginF_ice.py: "$(slicedir)/Ice/PluginF.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package "$(slicedir)/Ice/PluginF.ice" - -Ice_Locator_ice.py: "$(slicedir)/Ice/Locator.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package "$(slicedir)/Ice/Locator.ice" - -Ice_LocatorF_ice.py: "$(slicedir)/Ice/LocatorF.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package "$(slicedir)/Ice/LocatorF.ice" - -Ice_Process_ice.py: "$(slicedir)/Ice/Process.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package "$(slicedir)/Ice/Process.ice" - -Ice_ProcessF_ice.py: "$(slicedir)/Ice/ProcessF.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package "$(slicedir)/Ice/ProcessF.ice" - -Ice_FacetMap_ice.py: "$(slicedir)/Ice/FacetMap.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package "$(slicedir)/Ice/FacetMap.ice" - -Ice_Connection_ice.py: "$(slicedir)/Ice/Connection.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package "$(slicedir)/Ice/Connection.ice" - -Ice_ConnectionF_ice.py: "$(slicedir)/Ice/ConnectionF.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package "$(slicedir)/Ice/ConnectionF.ice" - -Ice_SliceChecksumDict_ice.py: "$(slicedir)/Ice/SliceChecksumDict.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package "$(slicedir)/Ice/SliceChecksumDict.ice" - -Ice_Endpoint_ice.py: "$(slicedir)/Ice/Endpoint.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package "$(slicedir)/Ice/Endpoint.ice" - -Ice_EndpointF_ice.py: "$(slicedir)/Ice/EndpointF.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package "$(slicedir)/Ice/EndpointF.ice" - -Ice_EndpointTypes_ice.py: "$(slicedir)/Ice/EndpointTypes.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package "$(slicedir)/Ice/EndpointTypes.ice" - -Ice_Version_ice.py: "$(slicedir)/Ice/Version.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package "$(slicedir)/Ice/Version.ice" - -Ice_Instrumentation_ice.py: "$(slicedir)/Ice/Instrumentation.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package "$(slicedir)/Ice/Instrumentation.ice" - -Ice_InstrumentationF_ice.py: "$(slicedir)/Ice/InstrumentationF.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package "$(slicedir)/Ice/InstrumentationF.ice" - -Ice_Metrics_ice.py: "$(slicedir)/Ice/Metrics.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Ice_ --no-package --checksum "$(slicedir)/Ice/Metrics.ice" - -Glacier2_RouterF_ice.py: "$(slicedir)/Glacier2/RouterF.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Glacier2_ --no-package --checksum "$(slicedir)/Glacier2/RouterF.ice" - -Glacier2_Router_ice.py: "$(slicedir)/Glacier2/Router.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Glacier2_ --no-package --checksum "$(slicedir)/Glacier2/Router.ice" - -Glacier2_Session_ice.py: "$(slicedir)/Glacier2/Session.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Glacier2_ --no-package --checksum "$(slicedir)/Glacier2/Session.ice" - -Glacier2_PermissionsVerifierF_ice.py: "$(slicedir)/Glacier2/PermissionsVerifierF.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Glacier2_ --no-package --checksum "$(slicedir)/Glacier2/PermissionsVerifierF.ice" - -Glacier2_PermissionsVerifier_ice.py: "$(slicedir)/Glacier2/PermissionsVerifier.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Glacier2_ --no-package --checksum "$(slicedir)/Glacier2/PermissionsVerifier.ice" - -Glacier2_SSLInfo_ice.py: "$(slicedir)/Glacier2/SSLInfo.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Glacier2_ --no-package --checksum "$(slicedir)/Glacier2/SSLInfo.ice" - -Glacier2_Metrics_ice.py: "$(slicedir)/Glacier2/Metrics.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix Glacier2_ --no-package --checksum "$(slicedir)/Glacier2/Metrics.ice" - -IceBox_IceBox_ice.py: "$(slicedir)/IceBox/IceBox.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix IceBox_ --checksum "$(slicedir)/IceBox/IceBox.ice" - -IceGrid_Admin_ice.py: "$(slicedir)/IceGrid/Admin.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix IceGrid_ --checksum "$(slicedir)/IceGrid/Admin.ice" - -IceGrid_Descriptor_ice.py: "$(slicedir)/IceGrid/Descriptor.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix IceGrid_ --checksum "$(slicedir)/IceGrid/Descriptor.ice" - -IceGrid_Exception_ice.py: "$(slicedir)/IceGrid/Exception.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix IceGrid_ --checksum "$(slicedir)/IceGrid/Exception.ice" - -IceGrid_FileParser_ice.py: "$(slicedir)/IceGrid/FileParser.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix IceGrid_ --checksum "$(slicedir)/IceGrid/FileParser.ice" - -IceGrid_Locator_ice.py: "$(slicedir)/IceGrid/Locator.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix IceGrid_ --checksum "$(slicedir)/IceGrid/Locator.ice" - -IceGrid_Observer_ice.py: "$(slicedir)/IceGrid/Observer.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix IceGrid_ --checksum "$(slicedir)/IceGrid/Observer.ice" - -IceGrid_Query_ice.py: "$(slicedir)/IceGrid/Query.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix IceGrid_ --checksum "$(slicedir)/IceGrid/Query.ice" - -IceGrid_Registry_ice.py: "$(slicedir)/IceGrid/Registry.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix IceGrid_ --checksum "$(slicedir)/IceGrid/Registry.ice" - -IceGrid_Session_ice.py: "$(slicedir)/IceGrid/Session.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix IceGrid_ --checksum "$(slicedir)/IceGrid/Session.ice" - -IceGrid_UserAccountMapper_ice.py: "$(slicedir)/IceGrid/UserAccountMapper.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix IceGrid_ --checksum "$(slicedir)/IceGrid/UserAccountMapper.ice" - -IcePatch2_FileInfo_ice.py: "$(slicedir)/IcePatch2/FileInfo.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix IcePatch2_ --checksum "$(slicedir)/IcePatch2/FileInfo.ice" - -IcePatch2_FileServer_ice.py: "$(slicedir)/IcePatch2/FileServer.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix IcePatch2_ --checksum "$(slicedir)/IcePatch2/FileServer.ice" - -IceStorm_IceStorm_ice.py: "$(slicedir)/IceStorm/IceStorm.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix IceStorm_ --checksum "$(slicedir)/IceStorm/IceStorm.ice" - -IceStorm_Metrics_ice.py: "$(slicedir)/IceStorm/Metrics.ice" "$(SLICEPARSERLIB)" - "$(SLICE2PY)" $(SLICE2PYFLAGS) --prefix IceStorm_ --checksum "$(slicedir)/IceStorm/Metrics.ice" - -install:: $(ALL_SRCS) - @echo "Installing generated code" - copy *.py "$(install_pythondir)" - @for %i in ( $(PACKAGES) ) do \ - @if not exist "$(install_pythondir)\%i" \ - $(MKDIR) "$(install_pythondir)\%i" - @for %i in ( $(PACKAGES) ) do \ - copy %i\* "$(install_pythondir)\%i" - -clean:: - -rmdir /s /q $(PACKAGES) - del /q *_ice.py - -#include .depend.mak diff --git a/python/test/Ice/acm/AllTests.py b/python/test/Ice/acm/AllTests.py index 5dcb67f9c32..365a0daa26f 100644 --- a/python/test/Ice/acm/AllTests.py +++ b/python/test/Ice/acm/AllTests.py @@ -20,48 +20,33 @@ class LoggerI(Ice.Logger): self.m = threading.Lock() def start(self): - self.m.acquire() - try: + with self.m: self._started = True self.dump() - finally: - self.m.release() def _print(self, msg): - self.m.acquire() - try: + with self.m: self._messages.append(msg) if self._started: self.dump() - finally: - self.m.release() def trace(self, category, msg): - self.m.acquire() - try: + with self.m: self._messages.append("[" + category + "] " + msg) if self._started: self.dump() - finally: - self.m.release() def warning(self, msg): - self.m.acquire() - try: + with self.m: self._messages.append("warning: " + msg) if self._started: self.dump() - finally: - self.m.release() def error(self, msg): - self.m.acquire() - try: + with self.m: self._messages.append("error: " + msg) if self._started: self.dump() - finally: - self.m.release() def getPrefix(self): return "" @@ -74,7 +59,7 @@ class LoggerI(Ice.Logger): print(p) self._messages = [] -class TestCase(threading.Thread, Ice.ConnectionCallback): +class TestCase(threading.Thread): def __init__(self, name, com): threading.Thread.__init__(self) self._name = name @@ -128,24 +113,20 @@ class TestCase(threading.Thread, Ice.ConnectionCallback): proxy = Test.TestIntfPrx.uncheckedCast(self._communicator.stringToProxy( self._adapter.getTestIntf().ice_toString())) try: - proxy.ice_getConnection().setCallback(self) + proxy.ice_getConnection().setCloseCallback(lambda conn: self.closed(conn)) + proxy.ice_getConnection().setHeartbeatCallback(lambda conn: self.heartbeat(conn)) + self.runTestCase(self._adapter, proxy) except Exception as ex: self._msg = "unexpected exception:\n" + traceback.format_exc() def heartbeat(self, con): - self.m.acquire() - try: + with self.m: self._heartbeat = self._heartbeat + 1 - finally: - self.m.release() def closed(self, con): - self.m.acquire() - try: + with self.m: self._closed = True - finally: - self.m.release() def runTestCase(self, adapter, proxy): test(False) @@ -173,11 +154,8 @@ def allTests(communicator): def runTestCase(self, adapter, proxy): proxy.sleep(2) - self.m.acquire() - try: + with self.m: test(self._heartbeat >= 2) - finally: - self.m.release() class InvocationHeartbeatOnHoldTest(TestCase): def __init__(self, com): @@ -195,11 +173,8 @@ def allTests(communicator): adapter.activate() proxy.interruptSleep() - self.m.acquire() - try: + with self.m: test(self._closed) - finally: - self.m.release() class InvocationNoHeartbeatTest(TestCase): def __init__(self, com): @@ -216,12 +191,9 @@ def allTests(communicator): except Ice.ConnectionTimeoutException: proxy.interruptSleep() - self.m.acquire() - try: + with self.m: test(self._heartbeat == 0) test(self._closed) - finally: - self.m.release() class InvocationHeartbeatCloseOnIdleTest(TestCase): def __init__(self, com): @@ -233,12 +205,9 @@ def allTests(communicator): # No close on invocation, the call should succeed this time. proxy.sleep(2) - self.m.acquire() - try: + with self.m: test(self._heartbeat == 0) test(not self._closed) - finally: - self.m.release() class CloseOnIdleTest(TestCase): def __init__(self, com): @@ -248,12 +217,9 @@ def allTests(communicator): def runTestCase(self, adapter, proxy): time.sleep(1.6) # Idle for 1.6 seconds - self.m.acquire() - try: + with self.m: test(self._heartbeat == 0) test(self._closed) - finally: - self.m.release() class CloseOnInvocationTest(TestCase): def __init__(self, com): @@ -263,12 +229,9 @@ def allTests(communicator): def runTestCase(self, adapter, proxy): time.sleep(1.5) # Idle for 1.5 seconds - self.m.acquire() - try: + with self.m: test(self._heartbeat == 0) test(not self._closed) - finally: - self.m.release() class CloseOnIdleAndInvocationTest(TestCase): def __init__(self, com): @@ -284,21 +247,15 @@ def allTests(communicator): adapter.hold() time.sleep(1.6) # Idle for 1.6 seconds - self.m.acquire() - try: + with self.m: test(self._heartbeat == 0) test(not self._closed) # Not closed yet because of graceful close. - finally: - self.m.release() adapter.activate() time.sleep(0.5) - self.m.acquire() - try: + with self.m: test(self._closed) # Connection should be closed this time. - finally: - self.m.release() class ForcefulCloseOnIdleAndInvocationTest(TestCase): def __init__(self, com): @@ -309,12 +266,9 @@ def allTests(communicator): adapter.hold() time.sleep(1.6) # Idle for 1.6 seconds - self.m.acquire() - try: + with self.m: test(self._heartbeat == 0) test(self._closed) # Connection closed forcefully by ACM. - finally: - self.m.release() class HeartbeatOnIdleTest(TestCase): def __init__(self, com): @@ -324,11 +278,8 @@ def allTests(communicator): def runTestCase(self, adapter, proxy): time.sleep(2) - self.m.acquire() - try: + with self.m: test(self._heartbeat >= 3) - finally: - self.m.release() class HeartbeatAlwaysTest(TestCase): def __init__(self, com): @@ -340,11 +291,27 @@ def allTests(communicator): proxy.ice_ping() time.sleep(0.1) - self.m.acquire() - try: + with self.m: test(self._heartbeat >= 3) - finally: - self.m.release() + + class HeartbeatManualTest(TestCase): + def __init__(self, com): + TestCase.__init__(self, "manual heartbeats", com) + # + # Disable heartbeats. + # + self.setClientACM(10, -1, 0) + self.setServerACM(10, -1, 0) + + def runTestCase(self, adapter, proxy): + proxy.startHeartbeatCount() + con = proxy.ice_getConnection() + con.heartbeat() + con.heartbeat() + con.heartbeat() + con.heartbeat() + con.heartbeat() + proxy.waitForHeartbeatCount(5) class SetACMTest(TestCase): def __init__(self, com): @@ -370,7 +337,8 @@ def allTests(communicator): test(acm.close == Ice.ACMClose.CloseOnInvocationAndIdle) test(acm.heartbeat == Ice.ACMHeartbeat.HeartbeatAlways) - proxy.waitForHeartbeat(2) + proxy.startHeartbeatCount() + proxy.waitForHeartbeatCount(2) tests.append(InvocationHeartbeatTest(com)) tests.append(InvocationHeartbeatOnHoldTest(com)) @@ -384,6 +352,7 @@ def allTests(communicator): tests.append(HeartbeatOnIdleTest(com)) tests.append(HeartbeatAlwaysTest(com)) + tests.append(HeartbeatManualTest(com)) tests.append(SetACMTest(com)) for p in tests: diff --git a/python/test/Ice/acm/Client.py b/python/test/Ice/acm/Client.py index 0c81ffe7cc5..aa46258a512 100755 --- a/python/test/Ice/acm/Client.py +++ b/python/test/Ice/acm/Client.py @@ -32,17 +32,10 @@ try: initData = Ice.InitializationData() initData.properties = Ice.createProperties(sys.argv) initData.properties.setProperty('Ice.Warn.Connections', '0') - communicator = Ice.initialize(sys.argv, initData) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv, initData) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/acm/Server.py b/python/test/Ice/acm/Server.py index 5a9b3b82667..d00888764cb 100755 --- a/python/test/Ice/acm/Server.py +++ b/python/test/Ice/acm/Server.py @@ -22,7 +22,7 @@ def run(args, communicator): communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010") communicator.getProperties().setProperty("TestAdapter.ACM.Timeout", "0") adapter = communicator.createObjectAdapter("TestAdapter") - id = communicator.stringToIdentity("communicator") + id = Ice.stringToIdentity("communicator") adapter.add(TestI.RemoteCommunicatorI(), id) adapter.activate() @@ -37,17 +37,10 @@ try: initData.properties = Ice.createProperties(sys.argv) initData.properties.setProperty("Ice.Warn.Connections", "0"); initData.properties.setProperty("Ice.ACM.Timeout", "1"); - communicator = Ice.initialize(sys.argv, initData) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv, initData) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/acm/Test.ice b/python/test/Ice/acm/Test.ice index cd9867f820e..7018c9df821 100644 --- a/python/test/Ice/acm/Test.ice +++ b/python/test/Ice/acm/Test.ice @@ -17,7 +17,8 @@ interface TestIntf void sleep(int seconds); void sleepAndHold(int seconds); void interruptSleep(); - void waitForHeartbeat(int count); + void startHeartbeatCount(); + void waitForHeartbeatCount(int count); }; interface RemoteObjectAdapter diff --git a/python/test/Ice/acm/TestI.py b/python/test/Ice/acm/TestI.py index 21ab6444384..53158e42a28 100644 --- a/python/test/Ice/acm/TestI.py +++ b/python/test/Ice/acm/TestI.py @@ -9,7 +9,22 @@ import Ice, Test, threading -class RemoteCommunicatorI(Test.RemoteCommunicator): +class ConnectionCallbackI(): + def __init__(self): + self.m = threading.Condition() + self.count = 0 + + def heartbeat(self, con): + with self.m: + self.count += 1 + self.m.notifyAll() + + def waitForCount(self, count): + with self.m: + while self.count < count: + self.m.wait() + +class RemoteCommunicatorI(Test._RemoteCommunicatorDisp): def createObjectAdapter(self, timeout, close, heartbeat, current=None): com = current.adapter.getCommunicator() properties = com.getProperties() @@ -29,11 +44,11 @@ class RemoteCommunicatorI(Test.RemoteCommunicator): def shutdown(self, current=None): current.adapter.getCommunicator().shutdown() -class RemoteObjectAdapterI(Test.RemoteObjectAdapter): +class RemoteObjectAdapterI(Test._RemoteObjectAdapterDisp): def __init__(self, adapter): self._adapter = adapter self._testIntf = Test.TestIntfPrx.uncheckedCast(adapter.add(TestIntfI(), - adapter.getCommunicator().stringToIdentity("test"))) + Ice.stringToIdentity("test"))) adapter.activate() def getTestIntf(self, current=None): @@ -51,61 +66,26 @@ class RemoteObjectAdapterI(Test.RemoteObjectAdapter): except Ice.ObjectAdapterDeactivatedException: pass -class TestIntfI(Test.TestIntf): +class TestIntfI(Test._TestIntfDisp): def __init__(self): self.m = threading.Condition() def sleep(self, delay, current=None): - self.m.acquire() - try: + with self.m: self.m.wait(delay) - finally: - self.m.release() def sleepAndHold(self, delay, current=None): - self.m.acquire() - try: + with self.m: current.adapter.hold() self.m.wait(delay) - finally: - self.m.release() def interruptSleep(self, delay, current=None): - self.m.acquire() - try: + with self.m: self.m.notifyAll() - finally: - self.m.release() - - def waitForHeartbeat(self, count, current=None): - - class ConnectionCallbackI(Ice.ConnectionCallback): - - def __init__(self): - self.m = threading.Condition() - self.count = 0 - - def heartbeat(self, con): - self.m.acquire() - try: - self.count -= 1 - self.m.notifyAll() - finally: - self.m.release() - - def closed(self, con): - pass - - def waitForCount(self, count): - self.m.acquire() - self.count = count - try: - while self.count > 0: - self.m.wait() - finally: - self.m.release() - callback = ConnectionCallbackI() - current.con.setCallback(callback) - callback.waitForCount(2) + def startHeartbeatCount(self, current=None): + self.callback = ConnectionCallbackI() + current.con.setHeartbeatCallback(lambda con: self.callback.heartbeat(con)) + def waitForHeartbeatCount(self, count, current=None): + self.callback.waitForCount(2) diff --git a/python/test/Ice/acm/run.py b/python/test/Ice/acm/run.py deleted file mode 100755 index 1a8297794cd..00000000000 --- a/python/test/Ice/acm/run.py +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env python -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -import os, sys - -path = [ ".", "..", "../..", "../../..", "../../../.." ] -head = os.path.dirname(sys.argv[0]) -if len(head) > 0: - path = [os.path.join(head, p) for p in path] -path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ] -if len(path) == 0: - raise RuntimeError("can't find toplevel directory!") -sys.path.append(os.path.join(path[0], "scripts")) -import TestUtil - -TestUtil.clientServerTest() diff --git a/python/test/Ice/adapterDeactivation/AllTests.py b/python/test/Ice/adapterDeactivation/AllTests.py index e690c8ff5a3..3adb8987a4b 100644 --- a/python/test/Ice/adapterDeactivation/AllTests.py +++ b/python/test/Ice/adapterDeactivation/AllTests.py @@ -57,14 +57,14 @@ def allTests(communicator): initData = Ice.InitializationData(); initData.properties = communicator.getProperties().clone(); comm = Ice.initialize(initData); - comm.stringToProxy("test:default -p 12010").begin_ice_ping(); + comm.stringToProxy("test:default -p 12010").ice_pingAsync(); comm.destroy(); print("ok"); sys.stdout.write("testing whether server is gone... ") sys.stdout.flush() try: - obj.ice_ping() + obj.ice_timeout(100).ice_ping() # Use timeout to speed up testing on Windows test(False) except Ice.LocalException: print("ok") diff --git a/python/test/Ice/adapterDeactivation/TestI.py b/python/test/Ice/adapterDeactivation/TestI.py index 03e44ce4911..aeb4f60e98b 100644 --- a/python/test/Ice/adapterDeactivation/TestI.py +++ b/python/test/Ice/adapterDeactivation/TestI.py @@ -14,7 +14,7 @@ def test(b): if not b: raise RuntimeError('test assertion failed') -class TestI(Test.TestIntf): +class TestI(Test._TestIntfDisp): def transient(self, current=None): communicator = current.adapter.getCommunicator() adapter = communicator.createObjectAdapterWithEndpoints("TransientTestAdapter", "default -p 9999") diff --git a/python/test/Ice/adapterDeactivation/run.py b/python/test/Ice/adapterDeactivation/run.py deleted file mode 100755 index e3c2c280892..00000000000 --- a/python/test/Ice/adapterDeactivation/run.py +++ /dev/null @@ -1,24 +0,0 @@ -#!/usr/bin/env python -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -import os, sys - -path = [ ".", "..", "../..", "../../..", "../../../.." ] -head = os.path.dirname(sys.argv[0]) -if len(head) > 0: - path = [os.path.join(head, p) for p in path] -path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ] -if len(path) == 0: - raise RuntimeError("can't find toplevel directory!") -sys.path.append(os.path.join(path[0], "scripts")) -import TestUtil - -TestUtil.clientServerTest() -TestUtil.collocatedTest() diff --git a/python/test/Ice/admin/AllTests.py b/python/test/Ice/admin/AllTests.py index b42e293f8c6..749dd1bc7eb 100644 --- a/python/test/Ice/admin/AllTests.py +++ b/python/test/Ice/admin/AllTests.py @@ -116,7 +116,7 @@ def allTests(communicator): init.properties.setProperty("Ice.Admin.Enabled", "1") com = Ice.initialize(init) test(com.getAdmin() == None) - identity = com.stringToIdentity("test-admin") + identity = Ice.stringToIdentity("test-admin") try: com.createAdmin(None, identity) test(False) diff --git a/python/test/Ice/admin/Client.py b/python/test/Ice/admin/Client.py index 54186aa5583..65174adc68a 100644 --- a/python/test/Ice/admin/Client.py +++ b/python/test/Ice/admin/Client.py @@ -28,17 +28,10 @@ def run(args, communicator): return True try: - communicator = Ice.initialize(sys.argv) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/admin/Server.py b/python/test/Ice/admin/Server.py index 81ea14d8029..adc448c6396 100644 --- a/python/test/Ice/admin/Server.py +++ b/python/test/Ice/admin/Server.py @@ -22,7 +22,7 @@ import Test, TestI def run(args, communicator): communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010 -t 10000"); adapter = communicator.createObjectAdapter("TestAdapter"); - ident = communicator.stringToIdentity("factory"); + ident = Ice.stringToIdentity("factory"); adapter.add(TestI.RemoteCommunicatorFactoryI(), ident); adapter.activate(); @@ -30,17 +30,10 @@ def run(args, communicator): return True; try: - communicator = Ice.initialize(sys.argv) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/admin/TestI.py b/python/test/Ice/admin/TestI.py index 89fcb9360d1..9172a2da65d 100644 --- a/python/test/Ice/admin/TestI.py +++ b/python/test/Ice/admin/TestI.py @@ -13,11 +13,11 @@ def test(b): if not b: raise RuntimeError('test assertion failed') -class TestFacetI(Test.TestFacet): +class TestFacetI(Test._TestFacetDisp): def op(self, current = None): return -class RemoteCommunicatorI(Test.RemoteCommunicator, Ice.PropertiesAdminUpdateCallback): +class RemoteCommunicatorI(Test._RemoteCommunicatorDisp, Ice.PropertiesAdminUpdateCallback): def __init__(self, communicator): self.communicator = communicator self.called = False @@ -27,8 +27,7 @@ class RemoteCommunicatorI(Test.RemoteCommunicator, Ice.PropertiesAdminUpdateCall return self.communicator.getAdmin() def getChanges(self, current = None): - self.m.acquire() - try: + with self.m: # # The client calls PropertiesAdmin::setProperties() and then invokes # this operation. Since setProperties() is implemented using AMD, the @@ -42,8 +41,6 @@ class RemoteCommunicatorI(Test.RemoteCommunicator, Ice.PropertiesAdminUpdateCall self.called = False return self.changes - finally: - self.m.release() def shutdown(self, current = None): self.communicator.shutdown() @@ -59,15 +56,12 @@ class RemoteCommunicatorI(Test.RemoteCommunicator, Ice.PropertiesAdminUpdateCall self.communicator.destroy() def updated(self, changes): - self.m.acquire() - try: + with self.m: self.changes = changes self.called = True self.m.notify() - finally: - self.m.release() -class RemoteCommunicatorFactoryI(Test.RemoteCommunicatorFactory): +class RemoteCommunicatorFactoryI(Test._RemoteCommunicatorFactoryDisp): def createCommunicator(self, props, current = None): # diff --git a/python/test/Ice/admin/run.py b/python/test/Ice/admin/run.py deleted file mode 100755 index 1a8297794cd..00000000000 --- a/python/test/Ice/admin/run.py +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env python -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -import os, sys - -path = [ ".", "..", "../..", "../../..", "../../../.." ] -head = os.path.dirname(sys.argv[0]) -if len(head) > 0: - path = [os.path.join(head, p) for p in path] -path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ] -if len(path) == 0: - raise RuntimeError("can't find toplevel directory!") -sys.path.append(os.path.join(path[0], "scripts")) -import TestUtil - -TestUtil.clientServerTest() diff --git a/python/test/Ice/ami/AllTests.py b/python/test/Ice/ami/AllTests.py index 1b49e269a30..b7dd106aadb 100644 --- a/python/test/Ice/ami/AllTests.py +++ b/python/test/Ice/ami/AllTests.py @@ -19,19 +19,15 @@ class CallbackBase: self._cond = threading.Condition() def check(self): - self._cond.acquire() - try: + with self._cond: while not self._called: self._cond.wait() self._called = False - finally: - self._cond.release() def called(self): - self._cond.acquire() - self._called = True - self._cond.notify() - self._cond.release() + with self._cond: + self._called = True + self._cond.notify() def exception(self, ex): test(False) @@ -241,6 +237,86 @@ class FlushExCallback(CallbackBase): def sentWC(self, sentSynchronously, cookie): test(False) +class FutureDoneCallback(CallbackBase): + def isA(self, f): + test(f.result()) + self.called() + + def ping(self, f): + self.called() + + def id(self, f): + test(f.result() == "::Test::TestIntf") + self.called() + + def ids(self, f): + test(len(f.result()) == 2) + self.called() + + def connection(self, f): + test(f.result() != None) + self.called() + + def op(self, f): + self.called() + + def opWithResult(self, f): + test(f.result() == 15) + self.called() + + def opWithUE(self, f): + try: + f.result() + test(False) + except Test.TestIntfException: + self.called() + except: + test(False) + +class FutureExceptionCallback(CallbackBase): + def opWithUE(self, f): + test(isinstance(f.exception(), Test.TestIntfException)) + self.called() + + def ex(self, f): + test(isinstance(f.exception(), Ice.NoEndpointException)) + self.called() + + def noEx(self, f): + test(f.exception() is None) + +class FutureSentCallback(CallbackBase): + def __init__(self): + CallbackBase.__init__(self) + self._thread = threading.currentThread() + + def sent(self, f, sentSynchronously): + test((sentSynchronously and self._thread == threading.currentThread()) or \ + (not sentSynchronously and self._thread != threading.currentThread())) + self.called() + +class FutureFlushCallback(CallbackBase): + def __init__(self, cookie=None): + CallbackBase.__init__(self) + self._thread = threading.currentThread() + self._cookie = cookie + + def sent(self, f, sentSynchronously): + test((sentSynchronously and self._thread == threading.currentThread()) or \ + (not sentSynchronously and self._thread != threading.currentThread())) + self.called() + +class FutureFlushExCallback(CallbackBase): + def __init__(self, cookie=None): + CallbackBase.__init__(self) + self._cookie = cookie + + def exception(self, f): + self.called() + + def sent(self, f, sentSynchronously): + test(False) + LocalException = 0 UserException = 1 OtherException = 2 @@ -315,22 +391,22 @@ def allTests(communicator, collocated): result = p.begin_ice_isA("::Test::TestIntf") test(p.end_ice_isA(result)) - result = p.begin_ice_isA("::Test::TestIntf", _ctx=ctx) + result = p.begin_ice_isA("::Test::TestIntf", context=ctx) test(p.end_ice_isA(result)) result = p.begin_ice_ping() p.end_ice_ping(result) - result = p.begin_ice_ping(_ctx=ctx) + result = p.begin_ice_ping(context=ctx) p.end_ice_ping(result) result = p.begin_ice_id() test(p.end_ice_id(result) == "::Test::TestIntf") - result = p.begin_ice_id(_ctx=ctx) + result = p.begin_ice_id(context=ctx) test(p.end_ice_id(result) == "::Test::TestIntf") result = p.begin_ice_ids() test(len(p.end_ice_ids(result)) == 2) - result = p.begin_ice_ids(_ctx=ctx) + result = p.begin_ice_ids(context=ctx) test(len(p.end_ice_ids(result)) == 2) if not collocated: @@ -339,12 +415,12 @@ def allTests(communicator, collocated): result = p.begin_op() p.end_op(result) - result = p.begin_op(_ctx=ctx) + result = p.begin_op(context=ctx) p.end_op(result) result = p.begin_opWithResult() test(p.end_opWithResult(result) == 15) - result = p.begin_opWithResult(_ctx=ctx) + result = p.begin_opWithResult(context=ctx) test(p.end_opWithResult(result) == 15) result = p.begin_opWithUE() @@ -353,7 +429,7 @@ def allTests(communicator, collocated): test(False) except Test.TestIntfException: pass - result = p.begin_opWithUE(_ctx=ctx) + result = p.begin_opWithUE(context=ctx) try: p.end_opWithUE(result) test(False) @@ -370,41 +446,41 @@ def allTests(communicator, collocated): cookie = 5 cbWC = ResponseCallbackWC(cookie) - p.begin_ice_isA(Test.TestIntf.ice_staticId(), cb.isA, cb.ex) + p.begin_ice_isA(Test._TestIntfDisp.ice_staticId(), cb.isA, cb.ex) cb.check() - p.begin_ice_isA(Test.TestIntf.ice_staticId(), lambda r: cbWC.isA(r, cookie), lambda ex: cbWC.ex(ex, cookie)) + p.begin_ice_isA(Test._TestIntfDisp.ice_staticId(), lambda r: cbWC.isA(r, cookie), lambda ex: cbWC.ex(ex, cookie)) cbWC.check() - p.begin_ice_isA(Test.TestIntf.ice_staticId(), cb.isA, cb.ex, _ctx=ctx) + p.begin_ice_isA(Test._TestIntfDisp.ice_staticId(), cb.isA, cb.ex, context=ctx) cb.check() - p.begin_ice_isA(Test.TestIntf.ice_staticId(), lambda r: cbWC.isA(r, cookie), lambda ex: cbWC.ex(ex, cookie), - _ctx=ctx) + p.begin_ice_isA(Test._TestIntfDisp.ice_staticId(), lambda r: cbWC.isA(r, cookie), lambda ex: cbWC.ex(ex, cookie), + context=ctx) cbWC.check() p.begin_ice_ping(cb.ping, cb.ex) cb.check() p.begin_ice_ping(lambda: cbWC.ping(cookie), lambda ex: cbWC.ex(ex, cookie)) cbWC.check() - p.begin_ice_ping(cb.ping, cb.ex, _ctx=ctx) + p.begin_ice_ping(cb.ping, cb.ex, context=ctx) cb.check() - p.begin_ice_ping(lambda: cbWC.ping(cookie), lambda: cbWC.ex(ex, cookie), _ctx=ctx) + p.begin_ice_ping(lambda: cbWC.ping(cookie), lambda: cbWC.ex(ex, cookie), context=ctx) cbWC.check() p.begin_ice_id(cb.id, cb.ex) cb.check() p.begin_ice_id(lambda id: cbWC.id(id, cookie), lambda ex: cbWC.ex(ex, cookie)) cbWC.check() - p.begin_ice_id(cb.id, cb.ex, _ctx=ctx) + p.begin_ice_id(cb.id, cb.ex, context=ctx) cb.check() - p.begin_ice_id(lambda id: cbWC.id(id, cookie), lambda ex: cbWC.ex(ex, cookie), _ctx=ctx) + p.begin_ice_id(lambda id: cbWC.id(id, cookie), lambda ex: cbWC.ex(ex, cookie), context=ctx) cbWC.check() p.begin_ice_ids(cb.ids, cb.ex) cb.check() p.begin_ice_ids(lambda ids: cbWC.ids(ids, cookie), lambda ex: cbWC.ex(ex, cookie)) cbWC.check() - p.begin_ice_ids(cb.ids, cb.ex, _ctx=ctx) + p.begin_ice_ids(cb.ids, cb.ex, context=ctx) cb.check() - p.begin_ice_ids(lambda ids: cbWC.ids(ids, cookie), lambda ex: cbWC.ex(ex, cookie), _ctx=ctx) + p.begin_ice_ids(lambda ids: cbWC.ids(ids, cookie), lambda ex: cbWC.ex(ex, cookie), context=ctx) cbWC.check() if not collocated: @@ -417,27 +493,27 @@ def allTests(communicator, collocated): cb.check() p.begin_op(lambda: cbWC.op(cookie), lambda ex: cbWC.ex(ex, cookie)) cbWC.check() - p.begin_op(cb.op, cb.ex, _ctx=ctx) + p.begin_op(cb.op, cb.ex, context=ctx) cb.check() - p.begin_op(lambda: cbWC.op(cookie), lambda ex: cbWC.ex(ex, cookie), _ctx=ctx) + p.begin_op(lambda: cbWC.op(cookie), lambda ex: cbWC.ex(ex, cookie), context=ctx) cbWC.check() p.begin_opWithResult(cb.opWithResult, cb.ex) cb.check() p.begin_opWithResult(lambda r: cbWC.opWithResult(r, cookie), lambda ex: cbWC.ex(ex, cookie)) cbWC.check() - p.begin_opWithResult(cb.opWithResult, cb.ex, _ctx=ctx) + p.begin_opWithResult(cb.opWithResult, cb.ex, context=ctx) cb.check() - p.begin_opWithResult(lambda r: cbWC.opWithResult(r, cookie), lambda ex: cbWC.ex(ex, cookie), _ctx=ctx) + p.begin_opWithResult(lambda r: cbWC.opWithResult(r, cookie), lambda ex: cbWC.ex(ex, cookie), context=ctx) cbWC.check() p.begin_opWithUE(cb.op, cb.opWithUE) cb.check() p.begin_opWithUE(lambda: cbWC.op(cookie), lambda ex: cbWC.opWithUE(ex, cookie)) cbWC.check() - p.begin_opWithUE(cb.op, cb.opWithUE, _ctx=ctx) + p.begin_opWithUE(cb.op, cb.opWithUE, context=ctx) cb.check() - p.begin_opWithUE(lambda: cbWC.op(cookie), lambda ex: cbWC.opWithUE(ex, cookie), _ctx=ctx) + p.begin_opWithUE(lambda: cbWC.op(cookie), lambda ex: cbWC.opWithUE(ex, cookie), context=ctx) cbWC.check() print("ok") @@ -487,9 +563,9 @@ def allTests(communicator, collocated): cookie = 5 cbWC = ExceptionCallbackWC(cookie) - i.begin_ice_isA(Test.TestIntf.ice_staticId(), cb.response, cb.ex) + i.begin_ice_isA(Test._TestIntfDisp.ice_staticId(), cb.response, cb.ex) cb.check() - i.begin_ice_isA(Test.TestIntf.ice_staticId(), lambda b: cbWC.response(b, cookie), lambda ex: cbWC.ex(ex, cookie)) + i.begin_ice_isA(Test._TestIntfDisp.ice_staticId(), lambda b: cbWC.response(b, cookie), lambda ex: cbWC.ex(ex, cookie)) cbWC.check() i.begin_ice_ping(cb.response, cb.ex) @@ -528,8 +604,8 @@ def allTests(communicator, collocated): cbWC = ExceptionCallbackWC(cookie) # Ensures no exception is called when response is received. - p.begin_ice_isA(Test.TestIntf.ice_staticId(), cb.nullResponse, cb.noEx) - p.begin_ice_isA(Test.TestIntf.ice_staticId(), lambda b: cbWC.nullResponse(b, cookie), + p.begin_ice_isA(Test._TestIntfDisp.ice_staticId(), cb.nullResponse, cb.noEx) + p.begin_ice_isA(Test._TestIntfDisp.ice_staticId(), lambda b: cbWC.nullResponse(b, cookie), lambda ex: cbWC.noEx(ex, cookie)) p.begin_op(cb.nullResponse, cb.noEx) p.begin_op(lambda: cbWC.nullResponse(cookie), lambda ex: cbWC.noEx(ex, cookie)) @@ -693,7 +769,7 @@ def allTests(communicator, collocated): test(p.opBatchCount() == 0) b1 = p.ice_batchOneway() b1.opBatch() - b1.ice_getConnection().close(False) + b1.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait) cb = FlushCallback() r = b1.begin_ice_flushBatchRequests(cb.exception, cb.sent) cb.check() @@ -707,7 +783,7 @@ def allTests(communicator, collocated): test(p.opBatchCount() == 0) b1 = p.ice_batchOneway() b1.opBatch() - b1.ice_getConnection().close(False) + b1.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait) cb = FlushCallback(cookie) r = b1.begin_ice_flushBatchRequests(lambda ex: cb.exceptionWC(ex, cookie), lambda ss: cb.sentWC(ss, cookie)) cb.check() @@ -729,7 +805,7 @@ def allTests(communicator, collocated): b1.opBatch() b1.opBatch() cb = FlushCallback() - r = b1.ice_getConnection().begin_flushBatchRequests(cb.exception, cb.sent) + r = b1.ice_getConnection().begin_flushBatchRequests(Ice.CompressBatch.BasedOnProxy, cb.exception, cb.sent) cb.check() test(r.isSent()) test(r.isCompleted()) @@ -743,7 +819,8 @@ def allTests(communicator, collocated): b1.opBatch() b1.opBatch() cb = FlushCallback(cookie) - r = b1.ice_getConnection().begin_flushBatchRequests(lambda ex: cb.exceptionWC(ex, cookie), + r = b1.ice_getConnection().begin_flushBatchRequests(Ice.CompressBatch.BasedOnProxy, + lambda ex: cb.exceptionWC(ex, cookie), lambda ss: cb.sentWC(ss, cookie)) cb.check() test(p.waitForBatch(2)) @@ -754,9 +831,9 @@ def allTests(communicator, collocated): test(p.opBatchCount() == 0) b1 = Test.TestIntfPrx.uncheckedCast(p.ice_getConnection().createProxy(p.ice_getIdentity()).ice_batchOneway()) b1.opBatch() - b1.ice_getConnection().close(False) + b1.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait) cb = FlushExCallback() - r = b1.ice_getConnection().begin_flushBatchRequests(cb.exception, cb.sent) + r = b1.ice_getConnection().begin_flushBatchRequests(Ice.CompressBatch.BasedOnProxy, cb.exception, cb.sent) cb.check() test(not r.isSent()) test(r.isCompleted()) @@ -768,9 +845,10 @@ def allTests(communicator, collocated): test(p.opBatchCount() == 0) b1 = Test.TestIntfPrx.uncheckedCast(p.ice_getConnection().createProxy(p.ice_getIdentity()).ice_batchOneway()) b1.opBatch() - b1.ice_getConnection().close(False) + b1.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait) cb = FlushExCallback(cookie) - r = b1.ice_getConnection().begin_flushBatchRequests(lambda ex: cb.exceptionWC(ex, cookie), + r = b1.ice_getConnection().begin_flushBatchRequests(Ice.CompressBatch.BasedOnProxy, + lambda ex: cb.exceptionWC(ex, cookie), lambda ss: cb.sentWC(ss, cookie)) cb.check() test(p.opBatchCount() == 0) @@ -788,7 +866,7 @@ def allTests(communicator, collocated): b1.opBatch() b1.opBatch() cb = FlushCallback() - r = communicator.begin_flushBatchRequests(cb.exception, cb.sent) + r = communicator.begin_flushBatchRequests(Ice.CompressBatch.BasedOnProxy, cb.exception, cb.sent) cb.check() test(r.isSent()) test(r.isCompleted()) @@ -800,9 +878,9 @@ def allTests(communicator, collocated): test(p.opBatchCount() == 0) b1 = Test.TestIntfPrx.uncheckedCast(p.ice_getConnection().createProxy(p.ice_getIdentity()).ice_batchOneway()) b1.opBatch() - b1.ice_getConnection().close(False) + b1.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait) cb = FlushCallback() - r = communicator.begin_flushBatchRequests(cb.exception, cb.sent) + r = communicator.begin_flushBatchRequests(Ice.CompressBatch.BasedOnProxy, cb.exception, cb.sent) cb.check() test(r.isSent()) # Exceptions are ignored! test(r.isCompleted()) @@ -821,7 +899,7 @@ def allTests(communicator, collocated): b2.opBatch() b2.opBatch() cb = FlushCallback() - r = communicator.begin_flushBatchRequests(cb.exception, cb.sent) + r = communicator.begin_flushBatchRequests(Ice.CompressBatch.BasedOnProxy, cb.exception, cb.sent) cb.check() test(r.isSent()) test(r.isCompleted()) @@ -840,9 +918,9 @@ def allTests(communicator, collocated): b2.ice_getConnection() # Ensure connection is established. b1.opBatch() b2.opBatch() - b1.ice_getConnection().close(False) + b1.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait) cb = FlushCallback() - r = communicator.begin_flushBatchRequests(cb.exception, cb.sent) + r = communicator.begin_flushBatchRequests(Ice.CompressBatch.BasedOnProxy, cb.exception, cb.sent) cb.check() test(r.isSent()) # Exceptions are ignored! test(r.isCompleted()) @@ -860,10 +938,10 @@ def allTests(communicator, collocated): b2.ice_getConnection() # Ensure connection is established. b1.opBatch() b2.opBatch() - b1.ice_getConnection().close(False) - b2.ice_getConnection().close(False) + b1.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait) + b2.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait) cb = FlushCallback() - r = communicator.begin_flushBatchRequests(cb.exception, cb.sent) + r = communicator.begin_flushBatchRequests(Ice.CompressBatch.BasedOnProxy, cb.exception, cb.sent) cb.check() test(r.isSent()) # Exceptions are ignored! test(r.isCompleted()) @@ -965,7 +1043,7 @@ def allTests(communicator, collocated): con = p.ice_getConnection() p2 = p.ice_batchOneway() p2.ice_ping() - r = con.begin_flushBatchRequests() + r = con.begin_flushBatchRequests(Ice.CompressBatch.BasedOnProxy) test(r.getConnection() == con) test(r.getCommunicator() == communicator) test(r.getProxy() == None) # Expected @@ -976,7 +1054,7 @@ def allTests(communicator, collocated): # p2 = p.ice_batchOneway() p2.ice_ping() - r = communicator.begin_flushBatchRequests() + r = communicator.begin_flushBatchRequests(Ice.CompressBatch.BasedOnProxy) test(r.getConnection() == None) # Expected test(r.getCommunicator() == communicator) test(r.getProxy() == None) # Expected @@ -1043,10 +1121,26 @@ def allTests(communicator, collocated): print("ok") - if p.ice_getConnection(): - sys.stdout.write("testing close connection with sending queue... ") + if p.ice_getConnection() and p.supportsAMD(): + + sys.stdout.write("testing graceful close connection with wait... ") sys.stdout.flush() + # + # Local case: begin a request, close the connection gracefully, and make sure it waits + # for the request to complete. + # + cb = CallbackBase() + con = p.ice_getConnection() + con.setCloseCallback(lambda con: cb.called()) + f = p.sleepAsync(100) + con.close(Ice.ConnectionClose.GracefullyWithWait) # Blocks until the request completes. + f.result() # Should complete successfully. + cb.check() + + # + # Remote case. + # if sys.version_info[0] == 2: b = [chr(random.randint(0, 255)) for x in range(0, 10*1024)] seq = ''.join(b) @@ -1067,7 +1161,7 @@ def allTests(communicator, collocated): results = [] for i in range(0, maxQueue): results.append(p.begin_opWithPayload(seq)) - if not p.begin_close(False).isSent(): + if not p.begin_close(Test.CloseMode.GracefullyWithWait).isSent(): for i in range(0, maxQueue): r = p.begin_opWithPayload(seq) results.append(r) @@ -1087,4 +1181,634 @@ def allTests(communicator, collocated): print("ok") + sys.stdout.write("testing graceful close connection without wait... ") + sys.stdout.flush() + + # + # Local case: start an operation and then close the connection gracefully on the client side + # without waiting for the pending invocation to complete. There will be no retry and we expect the + # invocation to fail with ConnectionManuallyClosedException. + # + p = p.ice_connectionId("CloseGracefully") # Start with a new connection. + con = p.ice_getConnection() + f = p.startDispatchAsync() + f.sent() # Ensure the request was sent before we close the connection. + con.close(Ice.ConnectionClose.Gracefully) + try: + f.result() + test(False) + except Ice.ConnectionManuallyClosedException as ex: + test(ex.graceful) + p.finishDispatch() + + # + # Remote case: the server closes the connection gracefully, which means the connection + # will not be closed until all pending dispatched requests have completed. + # + con = p.ice_getConnection() + cb = CallbackBase() + con.setCloseCallback(lambda c: cb.called()) + f = p.sleepAsync(100) + p.close(Test.CloseMode.Gracefully) # Close is delayed until sleep completes. + cb.check() # Ensure connection was closed. + try: + f.result() + except: + test(false) + + print("ok") + + sys.stdout.write("testing forceful close connection... ") + sys.stdout.flush() + + # + # Local case: start an operation and then close the connection forcefully on the client side. + # There will be no retry and we expect the invocation to fail with ConnectionManuallyClosedException. + # + p.ice_ping() + con = p.ice_getConnection() + f = p.startDispatchAsync() + f.sent() # Ensure the request was sent before we close the connection. + con.close(Ice.ConnectionClose.Forcefully) + try: + f.result() + test(False) + except Ice.ConnectionManuallyClosedException as ex: + test(not ex.graceful) + p.finishDispatch() + + # + # Remote case: the server closes the connection forcefully. This causes the request to fail + # with a ConnectionLostException. Since the close() operation is not idempotent, the client + # will not retry. + # + try: + p.close(Test.CloseMode.Forcefully) + test(False) + except Ice.ConnectionLostException: + # Expected. + pass + + print("ok") + +def allTestsFuture(communicator, collocated): + sref = "test:default -p 12010" + obj = communicator.stringToProxy(sref) + test(obj) + + p = Test.TestIntfPrx.uncheckedCast(obj) + + sref = "testController:default -p 12011" + obj = communicator.stringToProxy(sref) + test(obj) + + testController = Test.TestIntfControllerPrx.uncheckedCast(obj) + + sys.stdout.write("testing future invocations... ") + sys.stdout.flush() + ctx = {} + + test(p.ice_isAAsync("::Test::TestIntf").result()) + test(p.ice_isAAsync("::Test::TestIntf", ctx).result()) + + p.ice_pingAsync().result() + p.ice_pingAsync(ctx).result() + + test(p.ice_idAsync().result() == "::Test::TestIntf") + test(p.ice_idAsync(ctx).result() == "::Test::TestIntf") + + test(len(p.ice_idsAsync().result()) == 2) + test(len(p.ice_idsAsync(ctx).result()) == 2) + + if not collocated: + test(p.ice_getConnectionAsync().result() != None) + + p.opAsync().result() + p.opAsync(ctx).result() + + test(p.opWithResultAsync().result() == 15) + test(p.opWithResultAsync(ctx).result() == 15) + + try: + p.opWithUEAsync().result() + test(False) + except Test.TestIntfException: + pass + try: + p.opWithUEAsync(ctx).result() + test(False) + except Test.TestIntfException: + pass + + print("ok") + + sys.stdout.write("testing done callback... ") + sys.stdout.flush() + + ctx = {} + cb = FutureDoneCallback() + + p.ice_isAAsync(Test._TestIntfDisp.ice_staticId()).add_done_callback(cb.isA) + cb.check() + p.ice_isAAsync(Test._TestIntfDisp.ice_staticId(), ctx).add_done_callback(cb.isA) + cb.check() + + p.ice_pingAsync().add_done_callback(cb.ping) + cb.check() + p.ice_pingAsync(ctx).add_done_callback(cb.ping) + cb.check() + + p.ice_idAsync().add_done_callback(cb.id) + cb.check() + p.ice_idAsync(ctx).add_done_callback(cb.id) + cb.check() + + p.ice_idsAsync().add_done_callback(cb.ids) + cb.check() + p.ice_idsAsync(ctx).add_done_callback(cb.ids) + cb.check() + + if not collocated: + p.ice_getConnectionAsync().add_done_callback(cb.connection) + cb.check() + + p.opAsync().add_done_callback(cb.op) + cb.check() + p.opAsync(ctx).add_done_callback(cb.op) + cb.check() + + p.opWithResultAsync().add_done_callback(cb.opWithResult) + cb.check() + p.opWithResultAsync(ctx).add_done_callback(cb.opWithResult) + cb.check() + + p.opWithUEAsync().add_done_callback(cb.opWithUE) + cb.check() + p.opWithUEAsync(ctx).add_done_callback(cb.opWithUE) + cb.check() + + print("ok") + + sys.stdout.write("testing local exceptions... ") + sys.stdout.flush() + + indirect = Test.TestIntfPrx.uncheckedCast(p.ice_adapterId("dummy")) + + try: + indirect.opAsync().result() + test(False) + except Ice.NoEndpointException: + pass + + try: + p.ice_oneway().opWithResultAsync().result() + test(False) + except RuntimeError: + pass + + # + # Check that CommunicatorDestroyedException is raised directly. + # + if p.ice_getConnection(): + initData = Ice.InitializationData() + initData.properties = communicator.getProperties().clone() + ic = Ice.initialize(initData) + obj = ic.stringToProxy(p.ice_toString()) + p2 = Test.TestIntfPrx.checkedCast(obj) + ic.destroy(); + + try: + p2.opAsync() + test(False) + except Ice.CommunicatorDestroyedException: + pass + + print("ok") + + sys.stdout.write("testing local exceptions with done callback... ") + sys.stdout.flush() + + i = Test.TestIntfPrx.uncheckedCast(p.ice_adapterId("dummy")) + cb = FutureExceptionCallback() + + i.ice_isAAsync(Test._TestIntfDisp.ice_staticId()).add_done_callback(cb.ex) + cb.check() + + i.ice_pingAsync().add_done_callback(cb.ex) + cb.check() + + i.ice_idAsync().add_done_callback(cb.ex) + cb.check() + + i.ice_idsAsync().add_done_callback(cb.ex) + cb.check() + + if not collocated: + i.ice_getConnectionAsync().add_done_callback(cb.ex) + cb.check() + + i.opAsync().add_done_callback(cb.ex) + cb.check() + + print("ok") + + sys.stdout.write("testing exceptions with done callback... ") + sys.stdout.flush() + + cb = FutureExceptionCallback() + + # Ensures no exception is set when response is received. + p.ice_isAAsync(Test._TestIntfDisp.ice_staticId()).add_done_callback(cb.noEx) + p.opAsync().add_done_callback(cb.noEx) + + # If response is a user exception, it should be received. + p.opWithUEAsync().add_done_callback(cb.opWithUE) + cb.check() + + print("ok") + + sys.stdout.write("testing sent callback... ") + sys.stdout.flush() + + cb = FutureSentCallback() + + p.ice_isAAsync("").add_sent_callback(cb.sent) + cb.check() + + p.ice_pingAsync().add_sent_callback(cb.sent) + cb.check() + + p.ice_idAsync().add_sent_callback(cb.sent) + cb.check() + + p.ice_idsAsync().add_sent_callback(cb.sent) + cb.check() + + p.opAsync().add_sent_callback(cb.sent) + cb.check() + + cbs = [] + if sys.version_info[0] == 2: + b = [chr(random.randint(0, 255)) for x in range(0, 1024)] + seq = ''.join(b) + else: + b = [random.randint(0, 255) for x in range(0, 1024)] + seq = bytes(b) + testController.holdAdapter() + try: + cb = FutureSentCallback() + while True: + f = p.opWithPayloadAsync(seq) + f.add_sent_callback(cb.sent) + cbs.append(cb) + if not f.is_sent_synchronously(): + break + cb = FutureSentCallback() + except Exception as ex: + testController.resumeAdapter() + raise ex + testController.resumeAdapter() + for r in cbs: + r.check() + + print("ok") + + sys.stdout.write("testing batch requests with proxy... ") + sys.stdout.flush() + + test(p.opBatchCount() == 0) + b1 = p.ice_batchOneway() + b1.opBatch() + b1.opBatch() + cb = FutureFlushCallback() + f = b1.ice_flushBatchRequestsAsync() + f.add_sent_callback(cb.sent) + cb.check() + test(f.is_sent()) + test(f.done()) + test(p.waitForBatch(2)) + + if p.ice_getConnection(): # No collocation optimization + test(p.opBatchCount() == 0) + b1 = p.ice_batchOneway() + b1.opBatch() + b1.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait) + cb = FutureFlushCallback() + f = b1.ice_flushBatchRequestsAsync() + f.add_sent_callback(cb.sent) + cb.check() + f.result() # Wait until finished. + test(f.is_sent()) + test(f.done()) + test(p.waitForBatch(1)) + + print("ok") + + if p.ice_getConnection(): # No collocation optimization + sys.stdout.write("testing batch requests with connection... ") + sys.stdout.flush() + + test(p.opBatchCount() == 0) + b1 = Test.TestIntfPrx.uncheckedCast(p.ice_getConnection().createProxy(p.ice_getIdentity()).ice_batchOneway()) + b1.opBatch() + b1.opBatch() + cb = FutureFlushCallback() + f = b1.ice_getConnection().flushBatchRequestsAsync(Ice.CompressBatch.BasedOnProxy) + f.add_sent_callback(cb.sent) + cb.check() + f.result() # Wait until finished. + test(f.is_sent()) + test(f.done()) + test(p.waitForBatch(2)) + + test(p.opBatchCount() == 0) + b1 = Test.TestIntfPrx.uncheckedCast(p.ice_getConnection().createProxy(p.ice_getIdentity()).ice_batchOneway()) + b1.opBatch() + b1.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait) + cb = FutureFlushExCallback() + f = b1.ice_getConnection().flushBatchRequestsAsync(Ice.CompressBatch.BasedOnProxy) + f.add_done_callback(cb.exception) + f.add_sent_callback(cb.sent) + cb.check() + test(not f.is_sent()) + test(f.done()) + test(p.opBatchCount() == 0) + + print("ok") + + sys.stdout.write("testing batch requests with communicator... ") + sys.stdout.flush() + + # + # 1 connection. + # + test(p.opBatchCount() == 0) + b1 = Test.TestIntfPrx.uncheckedCast(p.ice_getConnection().createProxy(p.ice_getIdentity()).ice_batchOneway()) + b1.opBatch() + b1.opBatch() + cb = FutureFlushCallback() + f = communicator.flushBatchRequestsAsync(Ice.CompressBatch.BasedOnProxy) + f.add_sent_callback(cb.sent) + cb.check() + f.result() # Wait until finished. + test(f.is_sent()) + test(f.done()) + test(p.waitForBatch(2)) + + # + # 1 connection. + # + test(p.opBatchCount() == 0) + b1 = Test.TestIntfPrx.uncheckedCast(p.ice_getConnection().createProxy(p.ice_getIdentity()).ice_batchOneway()) + b1.opBatch() + b1.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait) + cb = FutureFlushCallback() + f = communicator.flushBatchRequestsAsync(Ice.CompressBatch.BasedOnProxy) + f.add_sent_callback(cb.sent) + cb.check() + f.result() # Wait until finished. + test(f.is_sent()) # Exceptions are ignored! + test(f.done()) + test(p.opBatchCount() == 0) + + # + # 2 connections. + # + test(p.opBatchCount() == 0) + b1 = Test.TestIntfPrx.uncheckedCast(p.ice_getConnection().createProxy(p.ice_getIdentity()).ice_batchOneway()) + b2 = Test.TestIntfPrx.uncheckedCast(p.ice_connectionId("2").ice_getConnection().createProxy( + p.ice_getIdentity()).ice_batchOneway()) + b2.ice_getConnection() # Ensure connection is established. + b1.opBatch() + b1.opBatch() + b2.opBatch() + b2.opBatch() + cb = FutureFlushCallback() + f = communicator.flushBatchRequestsAsync(Ice.CompressBatch.BasedOnProxy) + f.add_sent_callback(cb.sent) + cb.check() + f.result() # Wait until finished. + test(f.is_sent()) + test(f.done()) + test(p.waitForBatch(4)) + + # + # 2 connections - 1 failure. + # + # All connections should be flushed even if there are failures on some connections. + # Exceptions should not be reported. + # + test(p.opBatchCount() == 0) + b1 = Test.TestIntfPrx.uncheckedCast(p.ice_getConnection().createProxy(p.ice_getIdentity()).ice_batchOneway()) + b2 = Test.TestIntfPrx.uncheckedCast(p.ice_connectionId("2").ice_getConnection().createProxy( + p.ice_getIdentity()).ice_batchOneway()) + b2.ice_getConnection() # Ensure connection is established. + b1.opBatch() + b2.opBatch() + b1.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait) + cb = FutureFlushCallback() + f = communicator.flushBatchRequestsAsync(Ice.CompressBatch.BasedOnProxy) + f.add_sent_callback(cb.sent) + cb.check() + f.result() # Wait until finished. + test(f.is_sent()) # Exceptions are ignored! + test(f.done()) + test(p.waitForBatch(1)) + + # + # 2 connections - 2 failures. + # + # The sent callback should be invoked even if all connections fail. + # + test(p.opBatchCount() == 0) + b1 = Test.TestIntfPrx.uncheckedCast(p.ice_getConnection().createProxy(p.ice_getIdentity()).ice_batchOneway()) + b2 = Test.TestIntfPrx.uncheckedCast(p.ice_connectionId("2").ice_getConnection().createProxy( + p.ice_getIdentity()).ice_batchOneway()) + b2.ice_getConnection() # Ensure connection is established. + b1.opBatch() + b2.opBatch() + b1.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait) + b2.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait) + cb = FutureFlushCallback() + f = communicator.flushBatchRequestsAsync(Ice.CompressBatch.BasedOnProxy) + f.add_sent_callback(cb.sent) + cb.check() + f.result() # Wait until finished. + test(f.is_sent()) # Exceptions are ignored! + test(f.done()) + test(p.opBatchCount() == 0) + + print("ok") + + sys.stdout.write("testing future operations... ") + sys.stdout.flush() + + indirect = Test.TestIntfPrx.uncheckedCast(p.ice_adapterId("dummy")) + f = indirect.opAsync() + try: + f.result() + test(False) + except Ice.NoEndpointException: + pass + + testController.holdAdapter() + f1 = None + f2 = None + try: + f1 = p.opAsync() + if sys.version_info[0] == 2: + b = [chr(random.randint(0, 255)) for x in range(0, 1024)] + seq = ''.join(b) + else: + b = [random.randint(0, 255) for x in range(0, 1024)] + seq = bytes(b) + while(True): + f2 = p.opWithPayloadAsync(seq) + if not f2.is_sent_synchronously(): + break + + test(f1 == f1) + test(f1 != f2) + + if p.ice_getConnection(): + test((f1.is_sent_synchronously() and f1.is_sent() and not f1.done()) or + (not f1.is_sent_synchronously() and not f1.done())) + + test(not f2.is_sent_synchronously() and not f2.done()) + except Exception as ex: + testController.resumeAdapter() + raise ex + testController.resumeAdapter() + + f1.sent() + test(f1.is_sent()) + + f2.sent() + test(f2.is_sent()) + + f1.result() + test(f1.done()) + + f2.result() + test(f2.done()) + + test(f1.operation() == "op") + test(f2.operation() == "opWithPayload") + + # + # Twoway + # + f = p.ice_pingAsync() + test(f.operation() == "ice_ping") + test(f.connection() == None) # Expected + test(f.communicator() == communicator) + test(f.proxy() == p) + f.result() + + # + # Oneway + # + p2 = p.ice_oneway() + f = p2.ice_pingAsync() + test(f.operation() == "ice_ping") + test(f.connection() == None) # Expected + test(f.communicator() == communicator) + test(f.proxy() == p2) + + # + # Batch request via proxy + # + p2 = p.ice_batchOneway() + p2.ice_ping() + f = p2.ice_flushBatchRequestsAsync() + test(f.connection() == None) # Expected + test(f.communicator() == communicator) + test(f.proxy() == p2) + f.result() + + if p.ice_getConnection(): + # + # Batch request via connection + # + con = p.ice_getConnection() + p2 = p.ice_batchOneway() + p2.ice_ping() + f = con.flushBatchRequestsAsync(Ice.CompressBatch.BasedOnProxy) + test(f.connection() == con) + test(f.communicator() == communicator) + test(f.proxy() == None) # Expected + f.result() + + # + # Batch request via communicator + # + p2 = p.ice_batchOneway() + p2.ice_ping() + f = communicator.flushBatchRequestsAsync(Ice.CompressBatch.BasedOnProxy) + test(f.connection() == None) # Expected + test(f.communicator() == communicator) + test(f.proxy() == None) # Expected + f.result() + + if(p.ice_getConnection()): + f1 = None + f2 = None + + if sys.version_info[0] == 2: + b = [chr(random.randint(0, 255)) for x in range(0, 10024)] + seq = ''.join(b) + else: + b = [random.randint(0, 255) for x in range(0, 10024)] + seq = bytes(b) + + testController.holdAdapter() + + for x in range(0, 200): # 2MB + f = p.opWithPayloadAsync(seq) + + test(not f.is_sent()) + + f1 = p.ice_pingAsync() + f2 = p.ice_idAsync() + f1.cancel() + f2.cancel() + try: + f1.result() + test(false) + except(Ice.InvocationCanceledException): + pass + + try: + f2.result() + test(false) + except(Ice.InvocationCanceledException): + pass + + testController.resumeAdapter() + p.ice_ping() + test(not f1.is_sent() and f1.done()) + test(not f2.is_sent() and f2.done()) + + testController.holdAdapter() + + f1 = p.opAsync() + f2 = p.ice_idAsync() + f1.sent() + f2.sent() + f1.cancel() + f2.cancel() + try: + f1.result() + test(false) + except: + pass + try: + f2.result() + test(false) + except: + pass + testController.resumeAdapter() + + print("ok") + p.shutdown() diff --git a/python/test/Ice/ami/Client.py b/python/test/Ice/ami/Client.py index 70efcce696f..ecd21b9bb85 100755 --- a/python/test/Ice/ami/Client.py +++ b/python/test/Ice/ami/Client.py @@ -26,12 +26,14 @@ def test(b): def run(args, communicator): AllTests.allTests(communicator, False) + AllTests.allTestsFuture(communicator, False) return True try: initData = Ice.InitializationData() initData.properties = Ice.createProperties(sys.argv) initData.properties.setProperty('Ice.Warn.AMICallback', '0') + initData.properties.setProperty('Ice.Warn.Connections', '0') # # Limit the send buffer size, this test relies on the socket @@ -39,17 +41,10 @@ try: # initData.properties.setProperty("Ice.TCP.SndSize", "50000"); - communicator = Ice.initialize(sys.argv, initData) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv, initData) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/ami/Collocated.py b/python/test/Ice/ami/Collocated.py index 767ebee3d5c..d349e62c1d5 100755 --- a/python/test/Ice/ami/Collocated.py +++ b/python/test/Ice/ami/Collocated.py @@ -29,10 +29,10 @@ def run(args, communicator): testController = TestI.TestIntfControllerI(adapter) - adapter.add(TestI.TestIntfI(), communicator.stringToIdentity("test")) + adapter.add(TestI.TestIntfI(), Ice.stringToIdentity("test")) #adapter.activate() # Collocated test doesn't need to active the OA - - adapter2.add(testController, communicator.stringToIdentity("testController")) + + adapter2.add(testController, Ice.stringToIdentity("testController")) #adapter2.activate() # Collocated test doesn't need to active the OA AllTests.allTests(communicator, True) @@ -50,17 +50,10 @@ try: # initData.properties.setProperty("Ice.Warn.Connections", "0"); - communicator = Ice.initialize(sys.argv, initData) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv, initData) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/ami/Server.py b/python/test/Ice/ami/Server.py index 51242e16a3e..c60a21bbb06 100755 --- a/python/test/Ice/ami/Server.py +++ b/python/test/Ice/ami/Server.py @@ -28,10 +28,10 @@ def run(args, communicator): testController = TestI.TestIntfControllerI(adapter) - adapter.add(TestI.TestIntfI(), communicator.stringToIdentity("test")) + adapter.add(TestI.TestIntfI(), Ice.stringToIdentity("test")) adapter.activate() - adapter2.add(testController, communicator.stringToIdentity("testController")) + adapter2.add(testController, Ice.stringToIdentity("testController")) adapter2.activate() communicator.waitForShutdown() @@ -44,25 +44,18 @@ try: # # This test kills connections, so we don't want warnings. # - initData.properties.setProperty("Ice.Warn.Connections", "0"); + initData.properties.setProperty("Ice.Warn.Connections", "0") # # Limit the recv buffer size, this test relies on the socket # send() blocking after sending a given amount of data. # - initData.properties.setProperty("Ice.TCP.RcvSize", "50000"); + initData.properties.setProperty("Ice.TCP.RcvSize", "50000") - communicator = Ice.initialize(sys.argv, initData) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv, initData) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/ami/Test.ice b/python/test/Ice/ami/Test.ice index fa0affce73a..88cd7c71841 100644 --- a/python/test/Ice/ami/Test.ice +++ b/python/test/Ice/ami/Test.ice @@ -10,7 +10,6 @@ #pragma once #include <Ice/BuiltinSequences.ice> -#include <Ice/Endpoint.ice> module Test { @@ -19,6 +18,13 @@ exception TestIntfException { }; +enum CloseMode +{ + Forcefully, + Gracefully, + GracefullyWithWait +}; + interface TestIntf { void op(); @@ -29,9 +35,13 @@ interface TestIntf void opBatch(); int opBatchCount(); bool waitForBatch(int count); - void close(bool force); + void close(CloseMode mode); + void sleep(int ms); + ["amd"] void startDispatch(); + void finishDispatch(); void shutdown(); + bool supportsAMD(); bool supportsFunctionalTests(); }; @@ -42,4 +52,3 @@ interface TestIntfController }; }; - diff --git a/python/test/Ice/ami/TestI.py b/python/test/Ice/ami/TestI.py index 2950c206f70..d969b10fd72 100644 --- a/python/test/Ice/ami/TestI.py +++ b/python/test/Ice/ami/TestI.py @@ -7,12 +7,13 @@ # # ********************************************************************** -import Ice, Test, threading +import Ice, Test, threading, time -class TestIntfI(Test.TestIntf): +class TestIntfI(Test._TestIntfDisp): def __init__(self): self._cond = threading.Condition() self._batchCount = 0 + self._pending = [] def op(self, current=None): pass @@ -27,41 +28,56 @@ class TestIntfI(Test.TestIntf): pass def opBatch(self, current=None): - self._cond.acquire() - try: + with self._cond: self._batchCount += 1 self._cond.notify() - finally: - self._cond.release() def opBatchCount(self, current=None): - self._cond.acquire() - try: + with self._cond: return self._batchCount - finally: - self._cond.release() def waitForBatch(self, count, current=None): - self._cond.acquire() - try: + with self._cond: while self._batchCount < count: self._cond.wait(5) result = count == self._batchCount self._batchCount = 0 return result - finally: - self._cond.release() - def close(self, force, current=None): - current.con.close(force) + def close(self, mode, current=None): + current.con.close(Ice.ConnectionClose.valueOf(mode.value)) + + def sleep(self, ms, current=None): + time.sleep(ms / 1000.0) + + def startDispatch(self, current=None): + f = Ice.Future() + with self._cond: + self._pending.append(f) + return f + + def finishDispatch(self, current=None): + with self._cond: + for f in self._pending: + f.set_result(None) + self._pending = [] def shutdown(self, current=None): + # + # Just in case a request arrived late. + # + with self._cond: + for f in self._pending: + f.set_result(None) current.adapter.getCommunicator().shutdown() + def supportsAMD(self, current=None): + return True + def supportsFunctionalTests(self, current=None): return False -class TestIntfControllerI(Test.TestIntfController): +class TestIntfControllerI(Test._TestIntfControllerDisp): def __init__(self, adapter): self._adapter = adapter diff --git a/python/test/Ice/ami/run.py b/python/test/Ice/ami/run.py deleted file mode 100755 index 13c9c5d76d2..00000000000 --- a/python/test/Ice/ami/run.py +++ /dev/null @@ -1,26 +0,0 @@ -#!/usr/bin/env python -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -import os, sys - -path = [ ".", "..", "../..", "../../..", "../../../.." ] -head = os.path.dirname(sys.argv[0]) -if len(head) > 0: - path = [os.path.join(head, p) for p in path] -path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ] -if len(path) == 0: - raise RuntimeError("can't find toplevel directory!") -sys.path.append(os.path.join(path[0], "scripts")) -import TestUtil - -print("tests with regular server.") -TestUtil.clientServerTest() -print("tests with collocated server.") -TestUtil.collocatedTest() diff --git a/python/test/Ice/application/test.py b/python/test/Ice/application/test.py new file mode 100644 index 00000000000..6dda05ec6ec --- /dev/null +++ b/python/test/Ice/application/test.py @@ -0,0 +1,10 @@ +# ********************************************************************** +# +# Copyright (c) 2003-2016 ZeroC, Inc. All rights reserved. +# +# This copy of Ice is licensed to you under the terms described in the +# ICE_LICENSE file included in this distribution. +# +# ********************************************************************** + +# Dummy file to not run this test which is only ran manually.
\ No newline at end of file diff --git a/python/test/Ice/binding/AllTests.py b/python/test/Ice/binding/AllTests.py index 83fce934f57..c028d92c6d3 100644 --- a/python/test/Ice/binding/AllTests.py +++ b/python/test/Ice/binding/AllTests.py @@ -18,32 +18,25 @@ class GetAdapterNameCB: self._name = "" self._cond = threading.Condition() - def response(self, name): - self._cond.acquire() - self._name = name - self._cond.notify() - self._cond.release() - - def exception(self, ex): - test(False) + def response(self, f): + with self._cond: + self._name = f.result() + self._cond.notify() def getResult(self): - self._cond.acquire() - try: + with self._cond: while self._name == "": self._cond.wait(5.0) if self._name != "": return self._name else: return "" - finally: - self._cond.release() def getAdapterNameWithAMI(proxy): cb = GetAdapterNameCB() - proxy.begin_getAdapterName(cb.response, cb.exception) + proxy.getAdapterNameAsync().add_done_callback(cb.response) return cb.getResult() - + def createTestIntfPrx(adapters): endpoints = [] test = None @@ -72,9 +65,9 @@ def allTests(communicator): test1.ice_ping() test2.ice_ping() - + com.deactivateObjectAdapter(adapter) - + test3 = Test.TestIntfPrx.uncheckedCast(test1) test(test3.ice_getConnection() == test1.ice_getConnection()) test(test3.ice_getConnection() == test2.ice_getConnection()) @@ -84,6 +77,8 @@ def allTests(communicator): test(False) except Ice.ConnectionRefusedException: pass + except Ice.ConnectTimeoutException: + pass print("ok") @@ -115,7 +110,7 @@ def allTests(communicator): name = test1.getAdapterName() if names.count(name) > 0: names.remove(name) - test1.ice_getConnection().close(False) + test1.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait) # # Ensure that the proxy correctly caches the connection (we @@ -131,10 +126,10 @@ def allTests(communicator): while i < nRetry and t.getAdapterName() == name: i = i + 1 test(i == nRetry) - + for a in adapters: - a.getTestIntf().ice_getConnection().close(False) - + a.getTestIntf().ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait) + # # Deactivate an adapter and ensure that we can still # establish the connection to the remaining adapters. @@ -157,13 +152,13 @@ def allTests(communicator): name = test1.getAdapterName() if names.count(name) > 0: names.remove(name) - test1.ice_getConnection().close(False) + test1.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait) # # Deactivate an adapter and ensure that we can still # establish the connection to the remaining adapters. # - com.deactivateObjectAdapter(adapters[2]) + com.deactivateObjectAdapter(adapters[2]) t = createTestIntfPrx(adapters) test(t.getAdapterName() == "Adapter12") @@ -199,7 +194,7 @@ def allTests(communicator): name = getAdapterNameWithAMI(test1) if names.count(name) > 0: names.remove(name) - test1.ice_getConnection().close(False) + test1.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait) # # Ensure that the proxy correctly caches the connection (we @@ -215,10 +210,10 @@ def allTests(communicator): while i < nRetry and getAdapterNameWithAMI(t) == name: i = i + 1 test(i == nRetry) - + for a in adapters: - a.getTestIntf().ice_getConnection().close(False) - + a.getTestIntf().ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait) + # # Deactivate an adapter and ensure that we can still # establish the connection to the remaining adapters. @@ -241,13 +236,13 @@ def allTests(communicator): name = getAdapterNameWithAMI(test1) if names.count(name) > 0: names.remove(name) - test1.ice_getConnection().close(False) + test1.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait) # # Deactivate an adapter and ensure that we can still # establish the connection to the remaining adapters. # - com.deactivateObjectAdapter(adapters[2]) + com.deactivateObjectAdapter(adapters[2]) t = createTestIntfPrx(adapters) test(getAdapterNameWithAMI(t) == "AdapterAMI12") @@ -271,7 +266,7 @@ def allTests(communicator): name = t.getAdapterName() if names.count(name) > 0: names.remove(name) - t.ice_getConnection().close(False) + t.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait) t = Test.TestIntfPrx.uncheckedCast(t.ice_endpointSelection(Ice.EndpointSelectionType.Random)) test(t.ice_getEndpointSelection() == Ice.EndpointSelectionType.Random) @@ -283,7 +278,7 @@ def allTests(communicator): name = t.getAdapterName() if names.count(name) > 0: names.remove(name) - t.ice_getConnection().close(False) + t.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait) deactivate(com, adapters) @@ -326,6 +321,8 @@ def allTests(communicator): t.getAdapterName() except Ice.ConnectionRefusedException: pass + except Ice.ConnectTimeoutException: + pass endpoints = t.ice_getEndpoints() @@ -334,19 +331,19 @@ def allTests(communicator): # # Now, re-activate the adapters with the same endpoints in the opposite # order. - # + # adapters.append(com.createObjectAdapter("Adapter36", endpoints[2].toString())) i = 0 while i < nRetry and t.getAdapterName() == "Adapter36": i = i + 1 test(i == nRetry) - t.ice_getConnection().close(False) + t.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait) adapters.append(com.createObjectAdapter("Adapter35", endpoints[1].toString())) i = 0 while i < nRetry and t.getAdapterName() == "Adapter35": i = i + 1 test(i == nRetry) - t.ice_getConnection().close(False) + t.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait) adapters.append(com.createObjectAdapter("Adapter34", endpoints[0].toString())) i = 0 while i < nRetry and t.getAdapterName() == "Adapter34": @@ -378,6 +375,8 @@ def allTests(communicator): test(False) except Ice.ConnectionRefusedException: pass + except Ice.ConnectTimeoutException: + pass print("ok") @@ -488,6 +487,8 @@ def allTests(communicator): t.getAdapterName() except Ice.ConnectionRefusedException: pass + except Ice.ConnectTimeoutException: + pass endpoints = t.ice_getEndpoints() @@ -496,7 +497,7 @@ def allTests(communicator): # # Now, re-activate the adapters with the same endpoints in the opposite # order. - # + # adapters.append(com.createObjectAdapter("Adapter66", endpoints[2].toString())) i = 0 while i < nRetry and t.getAdapterName() == "Adapter66": @@ -556,6 +557,8 @@ def allTests(communicator): t.getAdapterName() except Ice.ConnectionRefusedException: pass + except Ice.ConnectTimeoutException: + pass endpoints = t.ice_getEndpoints() @@ -564,7 +567,7 @@ def allTests(communicator): # # Now, re-activate the adapters with the same endpoints in the opposite # order. - # + # adapters.append(com.createObjectAdapter("AdapterAMI66", endpoints[2].toString())) i = 0 while i < nRetry and getAdapterNameWithAMI(t) == "AdapterAMI66": @@ -611,11 +614,11 @@ def allTests(communicator): adapters = [] adapters.append(com.createObjectAdapter("Adapter81", "ssl")) adapters.append(com.createObjectAdapter("Adapter82", "tcp")) - + t = createTestIntfPrx(adapters) for i in range(0, 5): test(t.getAdapterName() == "Adapter82") - t.ice_getConnection().close(False) + t.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait) testSecure = Test.TestIntfPrx.uncheckedCast(t.ice_secure(True)) test(testSecure.ice_isSecure()) @@ -629,13 +632,13 @@ def allTests(communicator): for i in range(0, 5): test(t.getAdapterName() == "Adapter81") - t.ice_getConnection().close(False) + t.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait) com.createObjectAdapter("Adapter83", (t.ice_getEndpoints()[1]).toString()) # Reactive tcp OA. for i in range(0, 5): test(t.getAdapterName() == "Adapter83") - t.ice_getConnection().close(False) + t.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait) com.deactivateObjectAdapter(adapters[0]) try: @@ -643,6 +646,8 @@ def allTests(communicator): test(False) except Ice.ConnectionRefusedException: pass + except Ice.ConnectTimeoutException: + pass deactivate(com, adapters) diff --git a/python/test/Ice/binding/Client.py b/python/test/Ice/binding/Client.py index bb3ba837f48..e68dfb5a518 100755 --- a/python/test/Ice/binding/Client.py +++ b/python/test/Ice/binding/Client.py @@ -20,17 +20,10 @@ def run(args, communicator): return True try: - communicator = Ice.initialize(sys.argv) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/binding/Server.py b/python/test/Ice/binding/Server.py index e4ba5333d5f..ace8c09fbd5 100755 --- a/python/test/Ice/binding/Server.py +++ b/python/test/Ice/binding/Server.py @@ -17,7 +17,7 @@ import Test, TestI def run(args, communicator): communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010:udp") adapter = communicator.createObjectAdapter("TestAdapter") - id = communicator.stringToIdentity("communicator") + id = Ice.stringToIdentity("communicator") adapter.add(TestI.RemoteCommunicatorI(), id) adapter.activate() @@ -25,17 +25,10 @@ def run(args, communicator): return True try: - communicator = Ice.initialize(sys.argv) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/binding/TestI.py b/python/test/Ice/binding/TestI.py index 94030aa5774..1cf751840bc 100644 --- a/python/test/Ice/binding/TestI.py +++ b/python/test/Ice/binding/TestI.py @@ -9,7 +9,7 @@ import Ice, Test -class RemoteCommunicatorI(Test.RemoteCommunicator): +class RemoteCommunicatorI(Test._RemoteCommunicatorDisp): def __init__(self): self._nextPort = 10001 @@ -32,10 +32,10 @@ class RemoteCommunicatorI(Test.RemoteCommunicator): def shutdown(self, current=None): current.adapter.getCommunicator().shutdown() -class RemoteObjectAdapterI(Test.RemoteObjectAdapter): +class RemoteObjectAdapterI(Test._RemoteObjectAdapterDisp): def __init__(self, adapter): self._adapter = adapter - self._testIntf = Test.TestIntfPrx.uncheckedCast(self._adapter.add(TestI(), adapter.getCommunicator().stringToIdentity("test"))) + self._testIntf = Test.TestIntfPrx.uncheckedCast(self._adapter.add(TestI(), Ice.stringToIdentity("test"))) self._adapter.activate() def getTestIntf(self, current=None): @@ -47,6 +47,6 @@ class RemoteObjectAdapterI(Test.RemoteObjectAdapter): except Ice.ObjectAdapterDeactivatedException: pass -class TestI(Test.TestIntf): +class TestI(Test._TestIntfDisp): def getAdapterName(self, current=None): return current.adapter.getName() diff --git a/python/test/Ice/binding/run.py b/python/test/Ice/binding/run.py deleted file mode 100755 index 1a8297794cd..00000000000 --- a/python/test/Ice/binding/run.py +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env python -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -import os, sys - -path = [ ".", "..", "../..", "../../..", "../../../.." ] -head = os.path.dirname(sys.argv[0]) -if len(head) > 0: - path = [os.path.join(head, p) for p in path] -path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ] -if len(path) == 0: - raise RuntimeError("can't find toplevel directory!") -sys.path.append(os.path.join(path[0], "scripts")) -import TestUtil - -TestUtil.clientServerTest() diff --git a/python/test/Ice/blobject/Client.py b/python/test/Ice/blobject/Client.py index d61d5430c6a..3b7cb0821cf 100755 --- a/python/test/Ice/blobject/Client.py +++ b/python/test/Ice/blobject/Client.py @@ -52,45 +52,31 @@ try: initData = Ice.InitializationData() initData.properties = Ice.createProperties(argv) initData.properties.setProperty('Ice.Warn.Dispatch', '0') - communicator = Ice.initialize(argv, initData) - router = RouterI.RouterI(communicator, False) - sys.stdout.write("testing async blobject... ") - sys.stdout.flush() - status = run(sys.argv, communicator, False) - print("ok") - router.destroy() + with Ice.initialize(argv, initData) as communicator: + router = RouterI.RouterI(communicator, False) + sys.stdout.write("testing async blobject... ") + sys.stdout.flush() + status = run(sys.argv, communicator, False) + print("ok") + router.destroy() except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - if status: try: initData = Ice.InitializationData() initData.properties = Ice.createProperties(sys.argv) initData.properties.setProperty('Ice.Warn.Dispatch', '0') - communicator = Ice.initialize(sys.argv, initData) - router = RouterI.RouterI(communicator, True) - sys.stdout.write("testing sync blobject... ") - sys.stdout.flush() - status = run(sys.argv, communicator, True) - print("ok") - router.destroy() + with Ice.initialize(sys.argv, initData) as communicator: + router = RouterI.RouterI(communicator, True) + sys.stdout.write("testing sync blobject... ") + sys.stdout.flush() + status = run(sys.argv, communicator, True) + print("ok") + router.destroy() except: traceback.print_exc() status = False - if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/blobject/RouterI.py b/python/test/Ice/blobject/RouterI.py index bccca264b04..34928c48f89 100644 --- a/python/test/Ice/blobject/RouterI.py +++ b/python/test/Ice/blobject/RouterI.py @@ -17,43 +17,29 @@ class CallQueue(threading.Thread): self._destroy = False def add(self, call): - self._condVar.acquire() - self._queue.append(call) - self._condVar.notify() - self._condVar.release() + with self._condVar: + self._queue.append(call) + self._condVar.notify() def destroy(self): - self._condVar.acquire() - self._destroy = True - self._condVar.notify() - self._condVar.release() + with self._condVar: + self._destroy = True + self._condVar.notify() def run(self): while True: - self._condVar.acquire() - while len(self._queue) == 0 and not self._destroy: - self._condVar.wait() - if self._destroy: - self._condVar.release() - break - call = self._queue.pop() - self._condVar.release() + with self._condVar: + while len(self._queue) == 0 and not self._destroy: + self._condVar.wait() + if self._destroy: + break + call = self._queue.pop() call.execute() -class AsyncCallback(object): - def __init__(self, cb): - self._cb = cb - - def response(self, ok, results): - self._cb.ice_response(ok, results) - - def exception(self, ex): - self._cb.ice_exception(ex) - class BlobjectCall(object): - def __init__(self, proxy, amdCallback, inParams, curr): + def __init__(self, proxy, future, inParams, curr): self._proxy = proxy - self._amdCallback = amdCallback + self._future = future self._inParams = inParams self._curr = curr @@ -66,13 +52,19 @@ class BlobjectCall(object): proxy = proxy.ice_oneway() try: ok, out = proxy.ice_invoke(self._curr.operation, self._curr.mode, self._inParams, self._curr.ctx) - self._amdCallback.ice_response(ok, out) + self._future.set_result((ok, out)) except Ice.Exception as e: - self._amdCallback.ice_exception(e) + self._future.set_exception(e) else: - cb = AsyncCallback(self._amdCallback) - proxy.begin_ice_invoke(self._curr.operation, self._curr.mode, self._inParams, cb.response, cb.exception, - None, self._curr.ctx) + f = proxy.ice_invokeAsync(self._curr.operation, self._curr.mode, self._inParams, self._curr.ctx) + f.add_done_callback(self.done) + + def done(self, future): + try: + (ok, bytes) = future.result() + self._future.set_result((ok, bytes)) + except Exception as ex: + self._future.set_exception(ex) class BlobjectAsyncI(Ice.BlobjectAsync): def __init__(self): @@ -81,23 +73,22 @@ class BlobjectAsyncI(Ice.BlobjectAsync): self._objects = {} self._lock = threading.Lock() - def ice_invoke_async(self, amdCallback, inParams, curr): - self._lock.acquire() - proxy = self._objects[curr.id] - assert proxy - self._lock.release() - self._queue.add(BlobjectCall(proxy, amdCallback, inParams, curr)) + def ice_invoke(self, inParams, curr): + f = Ice.Future() + with self._lock: + proxy = self._objects[curr.id] + assert proxy + self._queue.add(BlobjectCall(proxy, f, inParams, curr)) + return f def add(self, proxy): - self._lock.acquire() - self._objects[proxy.ice_getIdentity()] = proxy.ice_facet("").ice_twoway().ice_router(None) - self._lock.release() + with self._lock: + self._objects[proxy.ice_getIdentity()] = proxy.ice_facet("").ice_twoway().ice_router(None) def destroy(self): - self._lock.acquire() - self._queue.destroy() - self._queue.join() - self._lock.release() + with self._lock: + self._queue.destroy() + self._queue.join() class BlobjectI(Ice.Blobject): def __init__(self): @@ -105,9 +96,8 @@ class BlobjectI(Ice.Blobject): self._lock = threading.Lock() def ice_invoke(self, inParams, curr): - self._lock.acquire() - proxy = self._objects[curr.id] - self._lock.release() + with self._lock: + proxy = self._objects[curr.id] if len(curr.facet) > 0: proxy = proxy.ice_facet(curr.facet) @@ -122,9 +112,8 @@ class BlobjectI(Ice.Blobject): raise def add(self, proxy): - self._lock.acquire() - self._objects[proxy.ice_getIdentity()] = proxy.ice_facet("").ice_twoway().ice_router(None) - self._lock.release() + with self._lock: + self._objects[proxy.ice_getIdentity()] = proxy.ice_facet("").ice_twoway().ice_router(None) def destroy(self): pass @@ -142,7 +131,7 @@ class ServantLocatorI(Ice.ServantLocator): def deactivate(self, s): pass -class RouterI(Ice.Router): +class RouterI(Ice._RouterDisp): def __init__(self, communicator, sync): self._adapter = communicator.createObjectAdapterWithEndpoints("forward", "default -h 127.0.0.1") if sync: diff --git a/python/test/Ice/blobject/Server.py b/python/test/Ice/blobject/Server.py index 19db1d77c83..9cd56f0de08 100755 --- a/python/test/Ice/blobject/Server.py +++ b/python/test/Ice/blobject/Server.py @@ -15,7 +15,7 @@ import Ice Ice.loadSlice('Test.ice') import Test -class TestI(Test.Hello): +class TestI(Test._HelloDisp): def sayHello(self, delay, current=None): if delay != 0: time.sleep(delay / 1000.0) @@ -33,7 +33,7 @@ class TestI(Test.Hello): def run(args, communicator): communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010:udp") adapter = communicator.createObjectAdapter("TestAdapter") - adapter.add(TestI(), communicator.stringToIdentity("test")) + adapter.add(TestI(), Ice.stringToIdentity("test")) adapter.activate() communicator.waitForShutdown() return True @@ -47,17 +47,10 @@ try: # this warning. # initData.properties.setProperty("Ice.Warn.Dispatch", "0"); - communicator = Ice.initialize(sys.argv, initData) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv, initData) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/blobject/run.py b/python/test/Ice/blobject/run.py deleted file mode 100755 index 1a8297794cd..00000000000 --- a/python/test/Ice/blobject/run.py +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env python -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -import os, sys - -path = [ ".", "..", "../..", "../../..", "../../../.." ] -head = os.path.dirname(sys.argv[0]) -if len(head) > 0: - path = [os.path.join(head, p) for p in path] -path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ] -if len(path) == 0: - raise RuntimeError("can't find toplevel directory!") -sys.path.append(os.path.join(path[0], "scripts")) -import TestUtil - -TestUtil.clientServerTest() diff --git a/python/test/Ice/checksum/AllTests.py b/python/test/Ice/checksum/AllTests.py index 4a91a943fd8..77683b92770 100644 --- a/python/test/Ice/checksum/AllTests.py +++ b/python/test/Ice/checksum/AllTests.py @@ -46,7 +46,6 @@ def allTests(communicator): m = patt.search(i) if m: n = int(i[m.start():]) - test(i in Ice.sliceChecksums) if n <= 1: diff --git a/python/test/Ice/checksum/CTypes.ice b/python/test/Ice/checksum/CTypes.ice index f4d3198b613..c15d5c94633 100644 --- a/python/test/Ice/checksum/CTypes.ice +++ b/python/test/Ice/checksum/CTypes.ice @@ -378,7 +378,7 @@ exception OptionalEx4 // // TEST: Same // -class BaseClass1 +interface BaseInterface1 { void baseOp1(); void baseOp2(int i, out string s) throws Exception1; @@ -387,7 +387,7 @@ class BaseClass1 // // TEST: Change return type // -class BaseClass2 +interface BaseInterface2 { void baseOp(); void baseOp2(int i, out string s) throws Exception1; @@ -396,7 +396,7 @@ class BaseClass2 // // TEST: Add parameter // -class BaseClass3 +interface BaseInterface3 { void baseOp(); void baseOp2(int i, out string s) throws Exception1; @@ -405,7 +405,7 @@ class BaseClass3 // // TEST: Add exception // -class BaseClass4 +interface BaseInterface4 { void baseOp(); void baseOp2(int i, out string s) throws Exception1; @@ -414,7 +414,7 @@ class BaseClass4 // // TEST: Change out parameter to in parameter // -class BaseClass5 +interface BaseInterface5 { void baseOp(); void baseOp2(int i, out string s) throws Exception1; @@ -423,7 +423,7 @@ class BaseClass5 // // TEST: Remove parameter // -class BaseClass6 +interface BaseInterface6 { void baseOp(); void baseOp2(int i, out string s) throws Exception1; @@ -432,7 +432,7 @@ class BaseClass6 // // TEST: Remove exception // -class BaseClass7 +interface BaseInterface7 { void baseOp(); void baseOp2(int i, out string s) throws Exception1; @@ -441,34 +441,16 @@ class BaseClass7 // // TEST: Remove operation // -class BaseClass8 +interface BaseInterface8 { void baseOp(); void baseOp2(int i, out string s) throws Exception1; }; // -// TEST: Add base class -// -class BaseClass9 -{ - void baseOp(); - void baseOp2(int i, out string s) throws Exception1; -}; - -// -// TEST: Add interface -// -class BaseClass10 -{ - void baseOp(); - void baseOp2(int i, out string s) throws Exception1; -}; - -// -// TEST: Add base class and interface +// TEST: Add base interface // -class BaseClass11 +interface BaseInterface9 { void baseOp(); void baseOp2(int i, out string s) throws Exception1; @@ -479,8 +461,7 @@ class BaseClass11 // class Compact1(1) { - void baseOp(); - void baseOp2(int i, out string s) throws Exception1; + int id; }; // @@ -495,8 +476,7 @@ class Derived1 extends Compact1 // class Compact2(2) { - void baseOp(); - void baseOp2(int i, out string s) throws Exception1; + int id; }; // @@ -550,53 +530,53 @@ class Optional4 }; // -// TEST: Class with optional parameters. +// TEST: Interface with optional parameters. // -class OptionalParameters0 +interface OptionalParameters0 { void op1(string firstName, optional(1) string secondName, optional(2) string emailAddress); }; // -// TEST: Class with optional parameters, different order. +// TEST: Interface with optional parameters, different order. // -class OptionalParameters1 +interface OptionalParameters1 { void op1(string firstName, optional(1) string secondName, optional(2) string emailAddress); }; // -// TEST: Class with optional parameters, different tags. +// TEST: Interface with optional parameters, different tags. // -class OptionalParameters2 +interface OptionalParameters2 { void op1(string firstName, optional(1) string emailAddress, optional(2) string secondName); }; // -// TEST: Class with different optional parameters. +// TEST: Interface with different optional parameters. // -class OptionalParameters3 +interface OptionalParameters3 { void op1(string firstName, optional(1) string emailAddress, string secondName); }; // -// TEST: Class with optional return type. +// TEST: Interface with optional return type. // -class OptionalReturn0 +interface OptionalReturn0 { optional(1) int op(); }; // -// TEST: Class that changes optional return type. +// TEST: Interface that changes optional return type. // -class OptionalReturn2 +interface OptionalReturn2 { optional(1) int op(); }; diff --git a/python/test/Ice/checksum/Client.py b/python/test/Ice/checksum/Client.py index cf30cc1c55e..0cc81d37861 100755 --- a/python/test/Ice/checksum/Client.py +++ b/python/test/Ice/checksum/Client.py @@ -25,17 +25,10 @@ def run(args, communicator): return True try: - communicator = Ice.initialize(sys.argv) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/checksum/STypes.ice b/python/test/Ice/checksum/STypes.ice index 991c6316d42..98c5e37f143 100644 --- a/python/test/Ice/checksum/STypes.ice +++ b/python/test/Ice/checksum/STypes.ice @@ -375,7 +375,7 @@ exception OptionalEx4 // // TEST: Same // -class BaseClass1 +interface BaseInterface1 { void baseOp1(); void baseOp2(int i, out string s) throws Exception1; @@ -384,7 +384,7 @@ class BaseClass1 // // TEST: Change return type // -class BaseClass2 +interface BaseInterface2 { int baseOp(); void baseOp2(int i, out string s) throws Exception1; @@ -393,7 +393,7 @@ class BaseClass2 // // TEST: Add parameter // -class BaseClass3 +interface BaseInterface3 { void baseOp(Object o); void baseOp2(int i, out string s) throws Exception1; @@ -402,7 +402,7 @@ class BaseClass3 // // TEST: Add exception // -class BaseClass4 +interface BaseInterface4 { void baseOp(); void baseOp2(int i, out string s) throws Exception1, Exception2; @@ -411,7 +411,7 @@ class BaseClass4 // // TEST: Change out parameter to in parameter // -class BaseClass5 +interface BaseInterface5 { void baseOp(); void baseOp2(int i, string s) throws Exception1; @@ -420,7 +420,7 @@ class BaseClass5 // // TEST: Remove parameter // -class BaseClass6 +interface BaseInterface6 { void baseOp(); void baseOp2(out string s) throws Exception1; @@ -429,7 +429,7 @@ class BaseClass6 // // TEST: Remove exception // -class BaseClass7 +interface BaseInterface7 { void baseOp(); void baseOp2(int i, out string s); @@ -438,7 +438,7 @@ class BaseClass7 // // TEST: Remove operation // -class BaseClass8 +interface BaseInterface8 { void baseOp2(int i, out string s) throws Exception1; }; @@ -446,25 +446,7 @@ class BaseClass8 // // TEST: Add base class // -class BaseClass9 extends EmptyClass1 -{ - void baseOp(); - void baseOp2(int i, out string s) throws Exception1; -}; - -// -// TEST: Add interface -// -class BaseClass10 implements Interface1 -{ - void baseOp(); - void baseOp2(int i, out string s) throws Exception1; -}; - -// -// TEST: Add base class and interface -// -class BaseClass11 extends EmptyClass1 implements Interface1 +interface BaseInterface9 extends Interface1 { void baseOp(); void baseOp2(int i, out string s) throws Exception1; @@ -475,8 +457,7 @@ class BaseClass11 extends EmptyClass1 implements Interface1 // class Compact1(1) { - void baseOp(); - void baseOp2(int i, out string s) throws Exception1; + int id; }; // @@ -491,8 +472,7 @@ class Derived1 extends Compact1 // class Compact2(3) { - void baseOp(); - void baseOp2(int i, out string s) throws Exception1; + int id; }; // @@ -547,53 +527,53 @@ class Optional4 }; // -// TEST: Class with optional parameters. +// TEST: Interface with optional parameters. // -class OptionalParameters0 +interface OptionalParameters0 { void op1(string firstName, optional(1) string secondName, optional(2) string emailAddress); }; // -// TEST: Class with optional parameters, different order. +// TEST: Interface with optional parameters, different order. // -class OptionalParameters1 +interface OptionalParameters1 { void op1(string firstName, optional(2) string emailAddress, optional(1) string secondName); }; // -// TEST: Class with optional parameters, different tags. +// TEST: Interface with optional parameters, different tags. // -class OptionalParameters2 +interface OptionalParameters2 { void op1(string firstName, optional(2) string emailAddress, optional(1) string secondName); }; // -// TEST: Class with different optional parameters. +// TEST: Interface with different optional parameters. // -class OptionalParameters3 +interface OptionalParameters3 { void op1(string firstName, string emailAddress, optional(1) string secondName); }; // -// TEST: Class with optional return type. +// TEST: Interface with optional return type. // -class OptionalReturn0 +interface OptionalReturn0 { optional(1) int op(); }; // -// TEST: Class that changes optional return type. +// TEST: Interface that changes optional return type. // -class OptionalReturn2 +interface OptionalReturn2 { int op(); }; diff --git a/python/test/Ice/checksum/Server.py b/python/test/Ice/checksum/Server.py index 0005e80051d..54028534eb7 100755 --- a/python/test/Ice/checksum/Server.py +++ b/python/test/Ice/checksum/Server.py @@ -19,7 +19,7 @@ if not slice_dir: Ice.loadSlice("'-I" + slice_dir + "' --checksum Test.ice STypes.ice") import Test -class ChecksumI(Test.Checksum): +class ChecksumI(Test._ChecksumDisp): def getSliceChecksums(self, current=None): return Ice.sliceChecksums @@ -30,23 +30,16 @@ def run(args, communicator): communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010") adapter = communicator.createObjectAdapter("TestAdapter") object = ChecksumI() - adapter.add(object, communicator.stringToIdentity("test")) + adapter.add(object, Ice.stringToIdentity("test")) adapter.activate() communicator.waitForShutdown() return True try: - communicator = Ice.initialize(sys.argv) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/checksum/run.py b/python/test/Ice/checksum/run.py deleted file mode 100755 index 1a8297794cd..00000000000 --- a/python/test/Ice/checksum/run.py +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env python -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -import os, sys - -path = [ ".", "..", "../..", "../../..", "../../../.." ] -head = os.path.dirname(sys.argv[0]) -if len(head) > 0: - path = [os.path.join(head, p) for p in path] -path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ] -if len(path) == 0: - raise RuntimeError("can't find toplevel directory!") -sys.path.append(os.path.join(path[0], "scripts")) -import TestUtil - -TestUtil.clientServerTest() diff --git a/python/test/Ice/custom/Client.py b/python/test/Ice/custom/Client.py index 83e845dc8d8..ccffc2b1508 100755 --- a/python/test/Ice/custom/Client.py +++ b/python/test/Ice/custom/Client.py @@ -20,17 +20,10 @@ def run(args, communicator): return True try: - communicator = Ice.initialize(sys.argv) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/custom/Server.py b/python/test/Ice/custom/Server.py index cb5680ecdd3..ad132e98526 100755 --- a/python/test/Ice/custom/Server.py +++ b/python/test/Ice/custom/Server.py @@ -18,7 +18,7 @@ def test(b): if not b: raise RuntimeError('test assertion failed') -class CustomI(Test.Custom): +class CustomI(Test._CustomDisp): def opByteString1(self, b1, current=None): if sys.version_info[0] == 2: test(isinstance(b1, str)) @@ -93,23 +93,16 @@ def run(args, communicator): communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010") adapter = communicator.createObjectAdapter("TestAdapter") object = CustomI() - adapter.add(object, communicator.stringToIdentity("test")) + adapter.add(object, Ice.stringToIdentity("test")) adapter.activate() communicator.waitForShutdown() return True try: - communicator = Ice.initialize(sys.argv) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/custom/run.py b/python/test/Ice/custom/run.py deleted file mode 100755 index 1a8297794cd..00000000000 --- a/python/test/Ice/custom/run.py +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env python -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -import os, sys - -path = [ ".", "..", "../..", "../../..", "../../../.." ] -head = os.path.dirname(sys.argv[0]) -if len(head) > 0: - path = [os.path.join(head, p) for p in path] -path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ] -if len(path) == 0: - raise RuntimeError("can't find toplevel directory!") -sys.path.append(os.path.join(path[0], "scripts")) -import TestUtil - -TestUtil.clientServerTest() diff --git a/python/test/Ice/defaultServant/Client.py b/python/test/Ice/defaultServant/Client.py index bb3ba837f48..e68dfb5a518 100755 --- a/python/test/Ice/defaultServant/Client.py +++ b/python/test/Ice/defaultServant/Client.py @@ -20,17 +20,10 @@ def run(args, communicator): return True try: - communicator = Ice.initialize(sys.argv) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/defaultServant/MyObjectI.py b/python/test/Ice/defaultServant/MyObjectI.py index 5ff29e8bc28..13eaf576f83 100644 --- a/python/test/Ice/defaultServant/MyObjectI.py +++ b/python/test/Ice/defaultServant/MyObjectI.py @@ -9,7 +9,7 @@ import Ice, Test -class MyObjectI(Test.MyObject): +class MyObjectI(Test._MyObjectDisp): def ice_ping(self, current=None): name = current.id.name diff --git a/python/test/Ice/defaultServant/run.py b/python/test/Ice/defaultServant/run.py deleted file mode 100755 index 3082ed4e986..00000000000 --- a/python/test/Ice/defaultServant/run.py +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env python -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -import os, sys - -path = [ ".", "..", "../..", "../../..", "../../../.." ] -head = os.path.dirname(sys.argv[0]) -if len(head) > 0: - path = [os.path.join(head, p) for p in path] -path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ] -if len(path) == 0: - raise RuntimeError("can't find toplevel directory!") -sys.path.append(os.path.join(path[0], "scripts")) -import TestUtil - -sys.stdout.write("starting client... ") -sys.stdout.flush() -clientProc = TestUtil.startClient("Client.py", startReader = False) -print("ok") -clientProc.startReader() - -clientProc.waitTestSuccess() diff --git a/python/test/Ice/defaultValue/Test.ice b/python/test/Ice/defaultValue/Test.ice index e4bb79e50e0..c29b88c956c 100644 --- a/python/test/Ice/defaultValue/Test.ice +++ b/python/test/Ice/defaultValue/Test.ice @@ -9,6 +9,8 @@ #pragma once +[["suppress-warning:deprecated"]] // For enumerator references + module Test { @@ -33,12 +35,12 @@ struct Struct1 float f = 5.1; double d = 6.2; string str = "foo \\ \"bar\n \r\n\t\v\f\a\b\? \007 \x07"; - Color c1 = ::Test::red; + Color c1 = ::Test::Color::red; Color c2 = Test::green; Color c3 = blue; - Nested::Color nc1 = ::Test::Nested::red; + Nested::Color nc1 = Test::Nested::Color::red; Nested::Color nc2 = Nested::green; - Nested::Color nc3 = Nested::blue; + Nested::Color nc3 = blue; string noDefault; int zeroI = 0; long zeroL = 0; @@ -56,12 +58,12 @@ const long ConstLong = 4; const float ConstFloat = 5.1; const double ConstDouble = 6.2; const string ConstString = "foo \\ \"bar\n \r\n\t\v\f\a\b\? \007 \x07"; -const Color ConstColor1 = ::Test::red; +const Color ConstColor1 = ::Test::Color::red; const Color ConstColor2 = Test::green; const Color ConstColor3 = blue; -const Nested::Color ConstNestedColor1 = ::Test::Nested::red; +const Nested::Color ConstNestedColor1 = Test::Nested::Color::red; const Nested::Color ConstNestedColor2 = Test::Nested::green; -const Nested::Color ConstNestedColor3 = Nested::blue; +const Nested::Color ConstNestedColor3 = blue; const int ConstZeroI = 0; const long ConstZeroL = 0; const float ConstZeroF = 0; @@ -115,12 +117,12 @@ class Base class Derived extends Base { - Color c1 = ::Test::red; + Color c1 = ::Test::Color::red; Color c2 = Test::green; Color c3 = blue; - Nested::Color nc1 = ::Test::Nested::red; + Nested::Color nc1 = ::Test::Nested::Color::red; Nested::Color nc2 = Nested::green; - Nested::Color nc3 = Nested::blue; + Nested::Color nc3 = blue; }; exception BaseEx diff --git a/python/test/Ice/defaultValue/run.py b/python/test/Ice/defaultValue/run.py deleted file mode 100755 index 3082ed4e986..00000000000 --- a/python/test/Ice/defaultValue/run.py +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env python -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -import os, sys - -path = [ ".", "..", "../..", "../../..", "../../../.." ] -head = os.path.dirname(sys.argv[0]) -if len(head) > 0: - path = [os.path.join(head, p) for p in path] -path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ] -if len(path) == 0: - raise RuntimeError("can't find toplevel directory!") -sys.path.append(os.path.join(path[0], "scripts")) -import TestUtil - -sys.stdout.write("starting client... ") -sys.stdout.flush() -clientProc = TestUtil.startClient("Client.py", startReader = False) -print("ok") -clientProc.startReader() - -clientProc.waitTestSuccess() diff --git a/python/test/Ice/enums/Client.py b/python/test/Ice/enums/Client.py index 9e3b20d38ef..ae42eead6ac 100755 --- a/python/test/Ice/enums/Client.py +++ b/python/test/Ice/enums/Client.py @@ -20,17 +20,10 @@ def run(args, communicator): return True try: - communicator = Ice.initialize(sys.argv) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/enums/Server.py b/python/test/Ice/enums/Server.py index 8f9559a83bc..93f27f861c0 100755 --- a/python/test/Ice/enums/Server.py +++ b/python/test/Ice/enums/Server.py @@ -18,7 +18,7 @@ def test(b): if not b: raise RuntimeError('test assertion failed') -class TestIntfI(Test.TestIntf): +class TestIntfI(Test._TestIntfDisp): def opByte(self, b1, current=None): return (b1, b1) @@ -50,23 +50,16 @@ def run(args, communicator): communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010") adapter = communicator.createObjectAdapter("TestAdapter") object = TestIntfI() - adapter.add(object, communicator.stringToIdentity("test")) + adapter.add(object, Ice.stringToIdentity("test")) adapter.activate() communicator.waitForShutdown() return True try: - communicator = Ice.initialize(sys.argv) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/enums/run.py b/python/test/Ice/enums/run.py deleted file mode 100755 index eb0e326db74..00000000000 --- a/python/test/Ice/enums/run.py +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env python -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -import os, sys - -path = [ ".", "..", "../..", "../../..", "../../../.." ] -head = os.path.dirname(sys.argv[0]) -if len(head) > 0: - path = [os.path.join(head, p) for p in path] -path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ] -if len(path) == 0: - raise RuntimeError("can't find toplevel directory!") -sys.path.append(os.path.join(path[0], "scripts")) -import TestUtil - -print("Running test with 1.0 encoding.") -TestUtil.clientServerTest(additionalClientOptions="--Ice.Default.EncodingVersion=1.0", - additionalServerOptions="--Ice.Default.EncodingVersion=1.0") - -print("Running test with 1.1 encoding.") -TestUtil.clientServerTest() diff --git a/python/test/Ice/exceptions/AllTests.py b/python/test/Ice/exceptions/AllTests.py index 9dae9af06e2..88d948324b2 100644 --- a/python/test/Ice/exceptions/AllTests.py +++ b/python/test/Ice/exceptions/AllTests.py @@ -13,7 +13,7 @@ def test(b): if not b: raise RuntimeError('test assertion failed') -class EmptyI(Test.Empty): +class EmptyI(Test._EmptyDisp): pass class ServantLocatorI(Ice.ServantLocator): @@ -26,12 +26,8 @@ class ServantLocatorI(Ice.ServantLocator): def deactivate(self, category): pass -class ObjectFactoryI(Ice.ObjectFactory): - def create(id): - return None - - def destroy(): - pass +def ValueFactory(type): + return None class CallbackBase: def __init__(self): @@ -39,19 +35,15 @@ class CallbackBase: self._cond = threading.Condition() def check(self): - self._cond.acquire() - try: + with self._cond: while not self._called: self._cond.wait() self._called = False - finally: - self._cond.release() def called(self): - self._cond.acquire() - self._called = True - self._cond.notify() - self._cond.release() + with self._cond: + self._called = True + self._cond.notify() class Callback(CallbackBase): def __init__(self, communicator=None): @@ -176,7 +168,7 @@ class Callback(CallbackBase): try: raise ex except Ice.ObjectNotExistException as ex: - id = self._communicator.stringToIdentity("does not exist") + id = Ice.stringToIdentity("does not exist") test(ex.id == id) except: test(False) @@ -226,29 +218,29 @@ def allTests(communicator): communicator.getProperties().setProperty("TestAdapter1.Endpoints", "default") adapter = communicator.createObjectAdapter("TestAdapter1") obj = EmptyI() - adapter.add(obj, communicator.stringToIdentity("x")) + adapter.add(obj, Ice.stringToIdentity("x")) try: - adapter.add(obj, communicator.stringToIdentity("x")) + adapter.add(obj, Ice.stringToIdentity("x")) test(false) except Ice.AlreadyRegisteredException: pass try: - adapter.add(obj, communicator.stringToIdentity("")) + adapter.add(obj, Ice.stringToIdentity("")) test(false) except Ice.IllegalIdentityException as ex: test(ex.id.name == "") try: - adapter.add(None, communicator.stringToIdentity("x")) + adapter.add(None, Ice.stringToIdentity("x")) test(false) except Ice.IllegalServantException: pass - adapter.remove(communicator.stringToIdentity("x")) + adapter.remove(Ice.stringToIdentity("x")) try: - adapter.remove(communicator.stringToIdentity("x")) + adapter.remove(Ice.stringToIdentity("x")) test(false) except Ice.NotRegisteredException: pass @@ -273,10 +265,10 @@ def allTests(communicator): sys.stdout.write("testing object factory registration exception... ") sys.stdout.flush() - of = ObjectFactoryI() - communicator.addObjectFactory(of, "x") + + communicator.getValueFactoryManager().add(ValueFactory, "x") try: - communicator.addObjectFactory(of, "x") + communicator.getValueFactoryManager().add(ValueFactory, "x") test(false) except Ice.AlreadyRegisteredException: pass @@ -499,7 +491,7 @@ def allTests(communicator): sys.stdout.write("catching object not exist exception... ") sys.stdout.flush() - id = communicator.stringToIdentity("does not exist") + id = Ice.stringToIdentity("does not exist") try: thrower2 = Test.ThrowerPrx.uncheckedCast(thrower.ice_identity(id)) thrower2.throwAasA(1) @@ -593,6 +585,7 @@ def allTests(communicator): try: thrower.throwAfterException() + test(False) except Test.A: pass except: @@ -601,6 +594,230 @@ def allTests(communicator): print("ok") + sys.stdout.write("catching exact types with futures... ") + sys.stdout.flush() + + try: + thrower.throwAasAAsync(1).result() + test(False) + except Test.A as ex: + test(ex.aMem == 1) + except: + print(sys.exc_info()) + test(False) + + try: + thrower.throwAorDasAorDAsync(1).result() + test(False) + except Test.A as ex: + test(ex.aMem == 1) + except: + print(sys.exc_info()) + test(False) + + try: + thrower.throwAorDasAorDAsync(-1).result() + test(False) + except Test.D as ex: + test(ex.dMem == -1) + except: + print(sys.exc_info()) + test(False) + + try: + thrower.throwBasBAsync(1, 2).result() + test(False) + except Test.B as ex: + test(ex.aMem == 1) + test(ex.bMem == 2) + except: + print(sys.exc_info()) + test(False) + + try: + thrower.throwCasCAsync(1, 2, 3).result() + test(False) + except Test.C as ex: + test(ex.aMem == 1) + test(ex.bMem == 2) + test(ex.cMem == 3) + except: + print(sys.exc_info()) + test(False) + + try: + thrower.throwModAAsync(1, 2).result() + test(False) + except Test.Mod.A as ex: + test(ex.aMem == 1) + test(ex.a2Mem == 2) + except Ice.OperationNotExistException: + # + # This operation is not supported in Java. + # + pass + except: + print(sys.exc_info()) + test(False) + + print("ok") + + sys.stdout.write("catching derived types with futures... ") + sys.stdout.flush() + + try: + thrower.throwBasAAsync(1, 2).result() + test(False) + except Test.B as ex: + test(ex.aMem == 1) + test(ex.bMem == 2) + except: + print(sys.exc_info()) + test(False) + + try: + thrower.throwCasAAsync(1, 2, 3).result() + test(False) + except Test.C as ex: + test(ex.aMem == 1) + test(ex.bMem == 2) + test(ex.cMem == 3) + except: + print(sys.exc_info()) + test(False) + + try: + thrower.throwCasBAsync(1, 2, 3).result() + test(False) + except Test.C as ex: + test(ex.aMem == 1) + test(ex.bMem == 2) + test(ex.cMem == 3) + except: + print(sys.exc_info()) + test(False) + + print("ok") + + if thrower.supportsUndeclaredExceptions(): + sys.stdout.write("catching unknown user exception with futures... ") + sys.stdout.flush() + + try: + thrower.throwUndeclaredAAsync(1).result() + test(False) + except Ice.UnknownUserException: + pass + except: + print(sys.exc_info()) + test(False) + + try: + thrower.throwUndeclaredBAsync(1, 2).result() + test(False) + except Ice.UnknownUserException: + pass + except: + print(sys.exc_info()) + test(False) + + try: + thrower.throwUndeclaredCAsync(1, 2, 3).result() + test(False) + except Ice.UnknownUserException: + pass + except: + print(sys.exc_info()) + test(False) + + print("ok") + + sys.stdout.write("catching object not exist exception with futures... ") + sys.stdout.flush() + + id = Ice.stringToIdentity("does not exist") + try: + thrower2 = Test.ThrowerPrx.uncheckedCast(thrower.ice_identity(id)) + thrower2.throwAasAAsync(1).result() +# thrower2.ice_ping() + test(False) + except Ice.ObjectNotExistException as ex: + test(ex.id == id) + except: + print(sys.exc_info()) + test(False) + + print("ok") + + sys.stdout.write("catching facet not exist exception with futures... ") + sys.stdout.flush() + + try: + thrower2 = Test.ThrowerPrx.uncheckedCast(thrower, "no such facet") + try: + thrower2.ice_pingAsync().result() + test(False) + except Ice.FacetNotExistException as ex: + test(ex.facet == "no such facet") + except: + print(sys.exc_info()) + test(False) + + print("ok") + + sys.stdout.write("catching operation not exist exception with futures... ") + sys.stdout.flush() + + try: + thrower2 = Test.WrongOperationPrx.uncheckedCast(thrower) + thrower2.noSuchOperationAsync().result() + test(False) + except Ice.OperationNotExistException as ex: + test(ex.operation == "noSuchOperation") + except: + print(sys.exc_info()) + test(False) + + print("ok") + + sys.stdout.write("catching unknown local exception with futures... ") + sys.stdout.flush() + + try: + thrower.throwLocalExceptionAsync().result() + test(False) + except Ice.UnknownLocalException: + pass + except: + print(sys.exc_info()) + test(False) + try: + thrower.throwLocalExceptionIdempotentAsync().result() + test(False) + except Ice.UnknownLocalException: + pass + except Ice.OperationNotExistException: + pass + except: + print(sys.exc_info()) + test(False) + + print("ok") + + sys.stdout.write("catching unknown non-Ice exception with futures... ") + sys.stdout.flush() + + try: + thrower.throwNonIceExceptionAsync().result() + test(False) + except Ice.UnknownException: + pass + except: + print(sys.exc_info()) + test(False) + + print("ok") + sys.stdout.write("catching exact types with AMI mapping... ") sys.stdout.flush() @@ -668,7 +885,7 @@ def allTests(communicator): sys.stdout.write("catching object not exist exception with AMI mapping... ") sys.stdout.flush() - id = communicator.stringToIdentity("does not exist") + id = Ice.stringToIdentity("does not exist") thrower2 = Test.ThrowerPrx.uncheckedCast(thrower.ice_identity(id)) cb = Callback(communicator) thrower2.begin_throwAasA(1, cb.response, cb.exception_AasAObjectNotExist) diff --git a/python/test/Ice/exceptions/Client.py b/python/test/Ice/exceptions/Client.py index 61ab651cb11..7016fac1441 100755 --- a/python/test/Ice/exceptions/Client.py +++ b/python/test/Ice/exceptions/Client.py @@ -29,17 +29,10 @@ try: initData.properties = Ice.createProperties(sys.argv) initData.properties.setProperty("Ice.MessageSizeMax", "10") initData.properties.setProperty("Ice.Warn.Connections", "0"); - communicator = Ice.initialize(sys.argv, initData) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv, initData) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/exceptions/Collocated.py b/python/test/Ice/exceptions/Collocated.py index 510584ddb0f..1f5ee529e14 100755 --- a/python/test/Ice/exceptions/Collocated.py +++ b/python/test/Ice/exceptions/Collocated.py @@ -25,7 +25,7 @@ def run(args, communicator): properties.setProperty("TestAdapter.Endpoints", "default -p 12010") adapter = communicator.createObjectAdapter("TestAdapter") object = TestI.ThrowerI() - adapter.add(object, communicator.stringToIdentity("thrower")) + adapter.add(object, Ice.stringToIdentity("thrower")) #adapter.activate() // Don't activate OA to ensure collocation is used. thrower = AllTests.allTests(communicator) @@ -36,17 +36,10 @@ try: initData = Ice.InitializationData() initData.properties = Ice.createProperties(sys.argv) initData.properties.setProperty("Ice.MessageSizeMax", "10") - communicator = Ice.initialize(sys.argv, initData) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv, initData) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/exceptions/Server.py b/python/test/Ice/exceptions/Server.py index 51c2978d2b3..2afc4e427f5 100755 --- a/python/test/Ice/exceptions/Server.py +++ b/python/test/Ice/exceptions/Server.py @@ -24,9 +24,9 @@ def run(args, communicator): adapter2 = communicator.createObjectAdapter("TestAdapter2") adapter3 = communicator.createObjectAdapter("TestAdapter3") object = TestI.ThrowerI() - adapter.add(object, communicator.stringToIdentity("thrower")) - adapter2.add(object, communicator.stringToIdentity("thrower")) - adapter3.add(object, communicator.stringToIdentity("thrower")) + adapter.add(object, Ice.stringToIdentity("thrower")) + adapter2.add(object, Ice.stringToIdentity("thrower")) + adapter3.add(object, Ice.stringToIdentity("thrower")) adapter.activate() adapter2.activate() adapter3.activate() @@ -44,17 +44,10 @@ try: initData.properties.setProperty("TestAdapter2.MessageSizeMax", "0") initData.properties.setProperty("TestAdapter3.Endpoints", "default -p 12012") initData.properties.setProperty("TestAdapter3.MessageSizeMax", "1") - communicator = Ice.initialize(sys.argv, initData) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv, initData) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/exceptions/ServerAMD.py b/python/test/Ice/exceptions/ServerAMD.py index 07b323fa947..7e3d005ecc1 100755 --- a/python/test/Ice/exceptions/ServerAMD.py +++ b/python/test/Ice/exceptions/ServerAMD.py @@ -23,130 +23,141 @@ def test(b): if not b: raise RuntimeError('test assertion failed') -class ThrowerI(Test.Thrower): - def shutdown_async(self, cb, current=None): +class ThrowerI(Test._ThrowerDisp): + def shutdown(self, current=None): current.adapter.getCommunicator().shutdown() - cb.ice_response() - def supportsUndeclaredExceptions_async(self, cb, current=None): - cb.ice_response(True) + def supportsUndeclaredExceptions(self, current=None): + return True - def supportsAssertException_async(self, cb, current=None): - cb.ice_response(False) + def supportsAssertException(self, current=None): + return False - def throwAasA_async(self, cb, a, current=None): + def throwAasA(self, a, current=None): ex = Test.A() ex.aMem = a - cb.ice_exception(ex) + f = Ice.Future() + f.set_exception(ex) + return f - def throwAorDasAorD_async(self, cb, a, current=None): + def throwAorDasAorD(self, a, current=None): + f = Ice.Future() if a > 0: ex = Test.A() ex.aMem = a - cb.ice_exception(ex) + f.set_exception(ex) else: ex = Test.D() ex.dMem = a - cb.ice_exception(ex) + f.set_exception(ex) + return f - def throwBasA_async(self, cb, a, b, current=None): + def throwBasA(self, a, b, current=None): ex = Test.B() ex.aMem = a ex.bMem = b raise ex - #cb.ice_exception(ex) - def throwCasA_async(self, cb, a, b, c, current=None): + def throwCasA(self, a, b, c, current=None): ex = Test.C() ex.aMem = a ex.bMem = b ex.cMem = c - cb.ice_exception(ex) + f = Ice.Future() + f.set_exception(ex) + return f - def throwBasB_async(self, cb, a, b, current=None): + def throwBasB(self, a, b, current=None): ex = Test.B() ex.aMem = a ex.bMem = b raise ex - #cb.ice_exception(ex) - def throwCasB_async(self, cb, a, b, c, current=None): + def throwCasB(self, a, b, c, current=None): ex = Test.C() ex.aMem = a ex.bMem = b ex.cMem = c - cb.ice_exception(ex) + f = Ice.Future() + f.set_exception(ex) + return f - def throwCasC_async(self, cb, a, b, c, current=None): + def throwCasC(self, a, b, c, current=None): ex = Test.C() ex.aMem = a ex.bMem = b ex.cMem = c - cb.ice_exception(ex) + f = Ice.Future() + f.set_exception(ex) + return f - def throwModA_async(self, cb, a, a2, current=None): + def throwModA(self, a, a2, current=None): ex = Test.Mod.A() ex.aMem = a ex.a2Mem = a2 raise ex - def throwUndeclaredA_async(self, cb, a, current=None): + def throwUndeclaredA(self, a, current=None): ex = Test.A() ex.aMem = a - cb.ice_exception(ex) + f = Ice.Future() + f.set_exception(ex) + return f - def throwUndeclaredB_async(self, cb, a, b, current=None): + def throwUndeclaredB(self, a, b, current=None): ex = Test.B() ex.aMem = a ex.bMem = b raise ex - #cb.ice_exception(ex) - def throwUndeclaredC_async(self, cb, a, b, c, current=None): + def throwUndeclaredC(self, a, b, c, current=None): ex = Test.C() ex.aMem = a ex.bMem = b ex.cMem = c - cb.ice_exception(ex) + f = Ice.Future() + f.set_exception(ex) + return f - def throwLocalException_async(self, cb, current=None): - cb.ice_exception(Ice.TimeoutException()) + def throwLocalException(self, current=None): + f = Ice.Future() + f.set_exception(Ice.TimeoutException()) + return f - def throwNonIceException_async(self, cb, current=None): - # Python-specific: make sure the argument is validated. - try: - cb.ice_exception('foo') - test(False) - except TypeError: - pass + def throwNonIceException(self, current=None): + f = Ice.Future() + f.set_exception(RuntimeError("12345")) + return f - cb.ice_exception(RuntimeError("12345")) - - def throwAssertException_async(self, cb, current=None): + def throwAssertException(self, current=None): raise RuntimeError("operation `throwAssertException' not supported") - def throwMemoryLimitException_async(self, cb, seq, current=None): - cb.ice_response(bytearray(20 * 1024)) + def throwMemoryLimitException(self, seq, current=None): + return Ice.Future.completed(bytearray(20 * 1024)) - def throwLocalExceptionIdempotent_async(self, cb, current=None): - cb.ice_exception(Ice.TimeoutException()) + def throwLocalExceptionIdempotent(self, current=None): + f = Ice.Future() + f.set_exception(Ice.TimeoutException()) + return f - def throwAfterResponse_async(self, cb, current=None): - cb.ice_response() - raise RuntimeError("12345") + def throwAfterResponse(self, current=None): + # Cannot be implemented with Futures + return None - def throwAfterException_async(self, cb, current=None): - cb.ice_exception(Test.A()) - raise RuntimeError("12345") + def throwAfterException(self, current=None): + # Cannot be implemented with Futures + f = Ice.Future() + f.set_exception(Test.A()) + return f def run(args, communicator): adapter = communicator.createObjectAdapter("TestAdapter") adapter2 = communicator.createObjectAdapter("TestAdapter2") adapter3 = communicator.createObjectAdapter("TestAdapter3") object = ThrowerI() - adapter.add(object, communicator.stringToIdentity("thrower")) - adapter2.add(object, communicator.stringToIdentity("thrower")) - adapter3.add(object, communicator.stringToIdentity("thrower")) + adapter.add(object, Ice.stringToIdentity("thrower")) + adapter2.add(object, Ice.stringToIdentity("thrower")) + adapter3.add(object, Ice.stringToIdentity("thrower")) adapter.activate() adapter2.activate() adapter3.activate() @@ -164,17 +175,10 @@ try: initData.properties.setProperty("TestAdapter2.MessageSizeMax", "0") initData.properties.setProperty("TestAdapter3.Endpoints", "default -p 12012") initData.properties.setProperty("TestAdapter3.MessageSizeMax", "1") - communicator = Ice.initialize(sys.argv, initData) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv, initData) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/exceptions/TestI.py b/python/test/Ice/exceptions/TestI.py index 2f994f3422c..ac4e3ab99f2 100644 --- a/python/test/Ice/exceptions/TestI.py +++ b/python/test/Ice/exceptions/TestI.py @@ -9,7 +9,7 @@ import Ice, Test, array, sys -class ThrowerI(Test.Thrower): +class ThrowerI(Test._ThrowerDisp): def shutdown(self, current=None): current.adapter.getCommunicator().shutdown() diff --git a/python/test/Ice/exceptions/run.py b/python/test/Ice/exceptions/run.py deleted file mode 100755 index 96a9752d793..00000000000 --- a/python/test/Ice/exceptions/run.py +++ /dev/null @@ -1,48 +0,0 @@ -#!/usr/bin/env python -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -import os, sys - -path = [ ".", "..", "../..", "../../..", "../../../.." ] -head = os.path.dirname(sys.argv[0]) -if len(head) > 0: - path = [os.path.join(head, p) for p in path] -path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ] -if len(path) == 0: - raise RuntimeError("can't find toplevel directory!") -sys.path.append(os.path.join(path[0], "scripts")) -import TestUtil - -print("Running test with compact (default) format.") -TestUtil.clientServerTest() - -print("Running test with sliced format.") -TestUtil.clientServerTest(additionalClientOptions="--Ice.Default.SlicedFormat", - additionalServerOptions="--Ice.Default.SlicedFormat") - -print("Running test with 1.0 encoding.") -TestUtil.clientServerTest(additionalClientOptions="--Ice.Default.EncodingVersion=1.0", - additionalServerOptions="--Ice.Default.EncodingVersion=1.0") - -print("Running test with compact (default) format and AMD server.") -TestUtil.clientServerTest(server="ServerAMD.py") - -print("Running test with sliced format and AMD server.") -TestUtil.clientServerTest(server="ServerAMD.py", - additionalClientOptions="--Ice.Default.SlicedFormat", - additionalServerOptions="--Ice.Default.SlicedFormat") - -print("Running test with 1.0 encoding and AMD server.") -TestUtil.clientServerTest(server="ServerAMD.py", - additionalClientOptions="--Ice.Default.EncodingVersion=1.0", - additionalServerOptions="--Ice.Default.EncodingVersion=1.0") - -print("Running collocated test.") -TestUtil.collocatedTest() diff --git a/python/test/Ice/facets/AllTests.py b/python/test/Ice/facets/AllTests.py index 5a553700407..b9fcba386dd 100644 --- a/python/test/Ice/facets/AllTests.py +++ b/python/test/Ice/facets/AllTests.py @@ -13,7 +13,7 @@ def test(b): if not b: raise RuntimeError('test assertion failed') -class EmptyI(Test.Empty): +class EmptyI(Test._EmptyDisp): pass def allTests(communicator): @@ -45,16 +45,16 @@ def allTests(communicator): communicator.getProperties().setProperty("FacetExceptionTestAdapter.Endpoints", "default") adapter = communicator.createObjectAdapter("FacetExceptionTestAdapter") obj = EmptyI() - adapter.add(obj, communicator.stringToIdentity("d")) - adapter.addFacet(obj, communicator.stringToIdentity("d"), "facetABCD") + adapter.add(obj, Ice.stringToIdentity("d")) + adapter.addFacet(obj, Ice.stringToIdentity("d"), "facetABCD") try: - adapter.addFacet(obj, communicator.stringToIdentity("d"), "facetABCD") + adapter.addFacet(obj, Ice.stringToIdentity("d"), "facetABCD") test(false) except Ice.AlreadyRegisteredException: pass - adapter.removeFacet(communicator.stringToIdentity("d"), "facetABCD") + adapter.removeFacet(Ice.stringToIdentity("d"), "facetABCD") try: - adapter.removeFacet(communicator.stringToIdentity("d"), "facetABCD") + adapter.removeFacet(Ice.stringToIdentity("d"), "facetABCD") test(false) except Ice.NotRegisteredException: pass @@ -64,22 +64,22 @@ def allTests(communicator): sys.stdout.flush() obj1 = EmptyI() obj2 = EmptyI() - adapter.addFacet(obj1, communicator.stringToIdentity("id1"), "f1") - adapter.addFacet(obj2, communicator.stringToIdentity("id1"), "f2") + adapter.addFacet(obj1, Ice.stringToIdentity("id1"), "f1") + adapter.addFacet(obj2, Ice.stringToIdentity("id1"), "f2") obj3 = EmptyI() - adapter.addFacet(obj1, communicator.stringToIdentity("id2"), "f1") - adapter.addFacet(obj2, communicator.stringToIdentity("id2"), "f2") - adapter.addFacet(obj3, communicator.stringToIdentity("id2"), "") - fm = adapter.removeAllFacets(communicator.stringToIdentity("id1")) + adapter.addFacet(obj1, Ice.stringToIdentity("id2"), "f1") + adapter.addFacet(obj2, Ice.stringToIdentity("id2"), "f2") + adapter.addFacet(obj3, Ice.stringToIdentity("id2"), "") + fm = adapter.removeAllFacets(Ice.stringToIdentity("id1")) test(len(fm) == 2) test(fm["f1"] == obj1) test(fm["f2"] == obj2) try: - adapter.removeAllFacets(communicator.stringToIdentity("id1")) + adapter.removeAllFacets(Ice.stringToIdentity("id1")) test(false) except Ice.NotRegisteredException: pass - fm = adapter.removeAllFacets(communicator.stringToIdentity("id2")) + fm = adapter.removeAllFacets(Ice.stringToIdentity("id2")) test(len(fm) == 3) test(fm["f1"] == obj1) test(fm["f2"] == obj2) diff --git a/python/test/Ice/facets/Client.py b/python/test/Ice/facets/Client.py index 2339436a44c..86807cecb5d 100755 --- a/python/test/Ice/facets/Client.py +++ b/python/test/Ice/facets/Client.py @@ -21,17 +21,10 @@ def run(args, communicator): return True try: - communicator = Ice.initialize(sys.argv) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/facets/Collocated.py b/python/test/Ice/facets/Collocated.py index 5760df42994..f336384b0ea 100755 --- a/python/test/Ice/facets/Collocated.py +++ b/python/test/Ice/facets/Collocated.py @@ -18,12 +18,12 @@ def run(args, communicator): communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010") adapter = communicator.createObjectAdapter("TestAdapter") d = TestI.DI() - adapter.add(d, communicator.stringToIdentity("d")) - adapter.addFacet(d, communicator.stringToIdentity("d"), "facetABCD") + adapter.add(d, Ice.stringToIdentity("d")) + adapter.addFacet(d, Ice.stringToIdentity("d"), "facetABCD") f = TestI.FI() - adapter.addFacet(f, communicator.stringToIdentity("d"), "facetEF") + adapter.addFacet(f, Ice.stringToIdentity("d"), "facetEF") h = TestI.HI(communicator) - adapter.addFacet(h, communicator.stringToIdentity("d"), "facetGH") + adapter.addFacet(h, Ice.stringToIdentity("d"), "facetGH") #adapter.activate() // Don't activate OA to ensure collocation is used. @@ -32,17 +32,10 @@ def run(args, communicator): return True try: - communicator = Ice.initialize(sys.argv) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/facets/Server.py b/python/test/Ice/facets/Server.py index f89933d33a1..846e724f4a2 100755 --- a/python/test/Ice/facets/Server.py +++ b/python/test/Ice/facets/Server.py @@ -18,12 +18,12 @@ def run(args, communicator): communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010") adapter = communicator.createObjectAdapter("TestAdapter") d = TestI.DI() - adapter.add(d, communicator.stringToIdentity("d")) - adapter.addFacet(d, communicator.stringToIdentity("d"), "facetABCD") + adapter.add(d, Ice.stringToIdentity("d")) + adapter.addFacet(d, Ice.stringToIdentity("d"), "facetABCD") f = TestI.FI() - adapter.addFacet(f, communicator.stringToIdentity("d"), "facetEF") + adapter.addFacet(f, Ice.stringToIdentity("d"), "facetEF") h = TestI.HI(communicator) - adapter.addFacet(h, communicator.stringToIdentity("d"), "facetGH") + adapter.addFacet(h, Ice.stringToIdentity("d"), "facetGH") adapter.activate() communicator.waitForShutdown() @@ -31,17 +31,10 @@ def run(args, communicator): return True try: - communicator = Ice.initialize(sys.argv) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/facets/TestI.py b/python/test/Ice/facets/TestI.py index 4f977b74c32..c3bcfe20042 100644 --- a/python/test/Ice/facets/TestI.py +++ b/python/test/Ice/facets/TestI.py @@ -9,31 +9,31 @@ import Test -class AI(Test.A): +class AI(Test._ADisp): def callA(self, current=None): return "A" -class BI(Test.B, AI): +class BI(Test._BDisp, AI): def callB(self, current=None): return "B" -class CI(Test.C, AI): +class CI(Test._CDisp, AI): def callC(self, current=None): return "C" -class DI(Test.D, BI, CI): +class DI(Test._DDisp, BI, CI): def callD(self, current=None): return "D" -class EI(Test.E): +class EI(Test._EDisp): def callE(self, current=None): return "E" -class FI(Test.F, EI): +class FI(Test._FDisp, EI): def callF(self, current=None): return "F" -class GI(Test.G): +class GI(Test._GDisp): def __init__(self, communicator): self._communicator = communicator @@ -43,7 +43,7 @@ class GI(Test.G): def callG(self, current=None): return "G" -class HI(Test.H, GI): +class HI(Test._HDisp, GI): def __init__(self, communicator): GI.__init__(self, communicator) diff --git a/python/test/Ice/facets/run.py b/python/test/Ice/facets/run.py deleted file mode 100755 index e3c2c280892..00000000000 --- a/python/test/Ice/facets/run.py +++ /dev/null @@ -1,24 +0,0 @@ -#!/usr/bin/env python -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -import os, sys - -path = [ ".", "..", "../..", "../../..", "../../../.." ] -head = os.path.dirname(sys.argv[0]) -if len(head) > 0: - path = [os.path.join(head, p) for p in path] -path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ] -if len(path) == 0: - raise RuntimeError("can't find toplevel directory!") -sys.path.append(os.path.join(path[0], "scripts")) -import TestUtil - -TestUtil.clientServerTest() -TestUtil.collocatedTest() diff --git a/python/test/Ice/faultTolerance/AllTests.py b/python/test/Ice/faultTolerance/AllTests.py index 8445c159321..dda42cfd74a 100644 --- a/python/test/Ice/faultTolerance/AllTests.py +++ b/python/test/Ice/faultTolerance/AllTests.py @@ -22,37 +22,32 @@ class CallbackBase: self._cond = threading.Condition() def check(self): - self._cond.acquire() - try: + with self._cond: while not self._called: self._cond.wait() self._called = False - finally: - self._cond.release() def called(self): - self._cond.acquire() - self._called = True - self._cond.notify() - self._cond.release() + with self._cond: + self._called = True + self._cond.notify() class Callback(CallbackBase): - def response(self): - test(False) - - def exception(self, ex): - test(False) - - def opPidI(self, pid): - self._pid = pid - self.called() + def opPidI(self, f): + try: + self._pid = f.result() + self.called() + except: + test(False) - def opShutdownI(self): + def opShutdownI(self, f): + test(f.exception() is None) self.called() - def exceptAbortI(self, ex): + def exceptAbortI(self, f): + test(f.exception() is not None) try: - raise ex + f.result() except Ice.ConnectionLostException: pass except Ice.ConnectFailedException: @@ -102,7 +97,7 @@ def allTests(communicator, ports): sys.stdout.write("testing server #%d with AMI... " % i) sys.stdout.flush() cb = Callback() - obj.begin_pid(cb.opPidI, cb.exception) + obj.pidAsync().add_done_callback(cb.opPidI) cb.check() pid = cb.pid() test(pid != oldPid) @@ -119,7 +114,7 @@ def allTests(communicator, ports): sys.stdout.write("shutting down server #%d with AMI... " % i) sys.stdout.flush() cb = Callback() - obj.begin_shutdown(cb.opShutdownI, cb.exception) + obj.shutdownAsync().add_done_callback(cb.opShutdownI) cb.check() print("ok") elif j == 1 or i + 1 > len(ports): @@ -137,7 +132,7 @@ def allTests(communicator, ports): sys.stdout.write("aborting server #%d with AMI... " % i) sys.stdout.flush() cb = Callback() - obj.begin_abort(cb.response, cb.exceptAbortI) + obj.abortAsync().add_done_callback(cb.exceptAbortI) cb.check() print("ok") elif j == 2 or j == 3: @@ -155,7 +150,7 @@ def allTests(communicator, ports): sys.stdout.write("aborting server #%d and #%d with idempotent AMI call... " % (i, i + 1)) sys.stdout.flush() cb = Callback() - obj.begin_idempotentAbort(cb.response, cb.exceptAbortI) + obj.idempotentAbortAsync().add_done_callback(cb.exceptAbortI) cb.check() print("ok") diff --git a/python/test/Ice/faultTolerance/Client.py b/python/test/Ice/faultTolerance/Client.py index ef78b617521..eb87436670c 100755 --- a/python/test/Ice/faultTolerance/Client.py +++ b/python/test/Ice/faultTolerance/Client.py @@ -27,7 +27,7 @@ def run(args, communicator): usage(args[0]) return False - ports.append(int(arg)) + ports.append(12010 + int(arg)) if len(ports) == 0: sys.stderr.write(args[0] + ": no ports specified\n") @@ -45,23 +45,16 @@ def run(args, communicator): try: initData = Ice.InitializationData() initData.properties = Ice.createProperties(sys.argv) - + # # This test aborts servers, so we don't want warnings. # initData.properties.setProperty('Ice.Warn.Connections', '0') - communicator = Ice.initialize(sys.argv, initData) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv, initData) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/faultTolerance/Server.py b/python/test/Ice/faultTolerance/Server.py index 8f6fcddf314..c6c96c99744 100755 --- a/python/test/Ice/faultTolerance/Server.py +++ b/python/test/Ice/faultTolerance/Server.py @@ -17,7 +17,7 @@ import Test def usage(n): sys.stderr.write("Usage: " + n + " port\n") -class TestI(Test.TestIntf): +class TestI(Test._TestIntfDisp): def shutdown(self, current=None): current.adapter.getCommunicator().shutdown() @@ -43,7 +43,7 @@ def run(args, communicator): usage(args[0]) return False - port = int(arg) + port = 12010 + int(arg) if port <= 0: sys.stderr.write(args[0] + ": no port specified\n") @@ -54,7 +54,7 @@ def run(args, communicator): communicator.getProperties().setProperty("TestAdapter.Endpoints", endpts) adapter = communicator.createObjectAdapter("TestAdapter") object = TestI() - adapter.add(object, communicator.stringToIdentity("test")) + adapter.add(object, Ice.stringToIdentity("test")) adapter.activate() communicator.waitForShutdown() return True @@ -69,17 +69,10 @@ try: initData.properties = Ice.createProperties(sys.argv) initData.properties.setProperty("Ice.ServerIdleTime", "120") # Two minutes. - communicator = Ice.initialize(sys.argv, initData) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv, initData) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/faultTolerance/run.py b/python/test/Ice/faultTolerance/run.py deleted file mode 100755 index fae644649f7..00000000000 --- a/python/test/Ice/faultTolerance/run.py +++ /dev/null @@ -1,47 +0,0 @@ -#!/usr/bin/env python -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -import os, sys - -path = [ ".", "..", "../..", "../../..", "../../../.." ] -head = os.path.dirname(sys.argv[0]) -if len(head) > 0: - path = [os.path.join(head, p) for p in path] -path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ] -if len(path) == 0: - raise RuntimeError("can't find toplevel directory!") -sys.path.append(os.path.join(path[0], "scripts")) -import TestUtil - -server = os.path.join(os.getcwd(), "Server.py") -client = os.path.join(os.getcwd(), "Client.py") - -num = 12 -base = 12340 - -serverProc = [] -for i in range(0, num): - sys.stdout.write("starting server #%d... " % (i + 1)) - sys.stdout.flush() - serverProc.append(TestUtil.startServer(server, "%d" % (base + i))) - print("ok") - -ports = "" -for i in range(0, num): - ports = "%s %d" % (ports, base + i) -sys.stdout.write("starting client... ") -sys.stdout.flush() -clientProc = TestUtil.startClient(client, ports, startReader = False) -print("ok") -clientProc.startReader() - -clientProc.waitTestSuccess() -for p in serverProc: - p.waitTestSuccess() diff --git a/python/test/Ice/info/AllTests.py b/python/test/Ice/info/AllTests.py index d94b78edfce..43f9d24dc1d 100644 --- a/python/test/Ice/info/AllTests.py +++ b/python/test/Ice/info/AllTests.py @@ -13,6 +13,18 @@ def test(b): if not b: raise RuntimeError('test assertion failed') +def getTCPEndpointInfo(info): + while(info): + if isinstance(info, Ice.TCPEndpointInfo): + return info + info = info.underlying + +def getTCPConnectionInfo(info): + while(info): + if isinstance(info, Ice.TCPConnectionInfo): + return info + info = info.underlying + def allTests(communicator): sys.stdout.write("testing proxy endpoint information... ") sys.stdout.flush() @@ -23,22 +35,23 @@ def allTests(communicator): endps = p1.ice_getEndpoints() - ipEndpoint = endps[0].getInfo() - test(isinstance(ipEndpoint, Ice.IPEndpointInfo)) - test(ipEndpoint.host == "tcphost") - test(ipEndpoint.port == 10000) - test(ipEndpoint.sourceAddress == "10.10.10.10") - test(ipEndpoint.timeout == 1200) - test(ipEndpoint.compress) - test(not ipEndpoint.datagram()) - test((ipEndpoint.type() == Ice.TCPEndpointType and not ipEndpoint.secure()) or - (ipEndpoint.type() == Ice.SSLEndpointType and ipEndpoint.secure()) or # SSL - (ipEndpoint.type() == Ice.WSEndpointType and not ipEndpoint.secure()) or # WS - (ipEndpoint.type() == Ice.WSSEndpointType and ipEndpoint.secure())) # WS - test((ipEndpoint.type() == Ice.TCPEndpointType and isinstance(ipEndpoint, Ice.TCPEndpointInfo)) or - (ipEndpoint.type() == Ice.SSLEndpointType and isinstance(ipEndpoint, Ice.SSLEndpointInfo)) or - (ipEndpoint.type() == Ice.WSEndpointType and isinstance(ipEndpoint, Ice.WSEndpointInfo)) or - (ipEndpoint.type() == Ice.WSSEndpointType and isinstance(ipEndpoint, Ice.WSSEndpointInfo))) + endpoint = endps[0].getInfo() + tcpEndpoint = getTCPEndpointInfo(endpoint) + test(isinstance(tcpEndpoint, Ice.TCPEndpointInfo)) + test(tcpEndpoint.host == "tcphost") + test(tcpEndpoint.port == 10000) + test(tcpEndpoint.sourceAddress == "10.10.10.10") + test(tcpEndpoint.timeout == 1200) + test(tcpEndpoint.compress) + test(not tcpEndpoint.datagram()) + test((tcpEndpoint.type() == Ice.TCPEndpointType and not tcpEndpoint.secure()) or + (tcpEndpoint.type() == Ice.SSLEndpointType and tcpEndpoint.secure()) or # SSL + (tcpEndpoint.type() == Ice.WSEndpointType and not tcpEndpoint.secure()) or # WS + (tcpEndpoint.type() == Ice.WSSEndpointType and tcpEndpoint.secure())) # WS + test((tcpEndpoint.type() == Ice.TCPEndpointType and isinstance(endpoint, Ice.TCPEndpointInfo)) or + (tcpEndpoint.type() == Ice.SSLEndpointType and isinstance(endpoint, Ice.SSLEndpointInfo)) or + (tcpEndpoint.type() == Ice.WSEndpointType and isinstance(endpoint, Ice.WSEndpointInfo)) or + (tcpEndpoint.type() == Ice.WSSEndpointType and isinstance(endpoint, Ice.WSEndpointInfo))) udpEndpoint = endps[1].getInfo() test(isinstance(udpEndpoint, Ice.UDPEndpointInfo)) @@ -71,18 +84,24 @@ def allTests(communicator): publishedEndpoints = adapter.getPublishedEndpoints() test(endpoints == publishedEndpoints) - ipEndpoint = endpoints[0].getInfo() - test(ipEndpoint.type() == Ice.TCPEndpointType or ipEndpoint.type() == 2 or ipEndpoint.type() == 4 or - ipEndpoint.type() == 5) - test(ipEndpoint.host == defaultHost) - test(ipEndpoint.port > 0) - test(ipEndpoint.timeout == 15000) + tcpEndpoint = getTCPEndpointInfo(endpoints[0].getInfo()) + test(tcpEndpoint.type() == Ice.TCPEndpointType or tcpEndpoint.type() == 2 or tcpEndpoint.type() == 4 or + tcpEndpoint.type() == 5) + test(tcpEndpoint.host == defaultHost) + test(tcpEndpoint.port > 0) + test(tcpEndpoint.timeout == 15000) udpEndpoint = endpoints[1].getInfo() test(udpEndpoint.host == defaultHost) test(udpEndpoint.datagram()) test(udpEndpoint.port > 0) + endpoints = (endpoints[0], ) + test(len(endpoints) == 1) + adapter.setPublishedEndpoints(endpoints) + publishedEndpoints = adapter.getPublishedEndpoints() + test(endpoints == publishedEndpoints) + adapter.destroy() communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -h * -p 12020") @@ -92,15 +111,16 @@ def allTests(communicator): endpoints = adapter.getEndpoints() test(len(endpoints) >= 1) publishedEndpoints = adapter.getPublishedEndpoints() + test(len(publishedEndpoints) == 1) for i in range(0, len(endpoints)): - ipEndpoint = endpoints[i].getInfo() - test(ipEndpoint.port == 12020) + tcpEndpoint = getTCPEndpointInfo(endpoints[i].getInfo()) + test(tcpEndpoint.port == 12020) - ipEndpoint = publishedEndpoints[0].getInfo() - test(ipEndpoint.host == "127.0.0.1") - test(ipEndpoint.port == 12020) + tcpEndpoint = getTCPEndpointInfo(publishedEndpoints[0].getInfo()) + test(tcpEndpoint.host == "127.0.0.1") + test(tcpEndpoint.port == 12020) adapter.destroy() @@ -112,13 +132,13 @@ def allTests(communicator): sys.stdout.write("test connection endpoint information... ") sys.stdout.flush() - ipinfo = base.ice_getConnection().getEndpoint().getInfo() - test(ipinfo.port == 12010) - test(not ipinfo.compress) - test(ipinfo.host == defaultHost) + tcpinfo = getTCPEndpointInfo(base.ice_getConnection().getEndpoint().getInfo()) + test(tcpinfo.port == 12010) + test(not tcpinfo.compress) + test(tcpinfo.host == defaultHost) ctx = testIntf.getEndpointInfoAsContext() - test(ctx["host"] == ipinfo.host) + test(ctx["host"] == tcpinfo.host) test(ctx["compress"] == "false") port = int(ctx["port"]) test(port > 0) @@ -136,26 +156,26 @@ def allTests(communicator): connection.setBufferSize(1024, 2048) info = connection.getInfo() + tcpinfo = getTCPConnectionInfo(info) test(not info.incoming) test(len(info.adapterName) == 0) - test(info.remotePort == 12010) + test(tcpinfo.remotePort == 12010) if defaultHost == '127.0.0.1': - test(info.remoteAddress == defaultHost) - test(info.localAddress == defaultHost) - test(info.rcvSize >= 1024) - test(info.sndSize >= 2048) + test(tcpinfo.remoteAddress == defaultHost) + test(tcpinfo.localAddress == defaultHost) + test(tcpinfo.rcvSize >= 1024) + test(tcpinfo.sndSize >= 2048) ctx = testIntf.getConnectionInfoAsContext() test(ctx["incoming"] == "true") test(ctx["adapterName"] == "TestAdapter") - test(ctx["remoteAddress"] == info.localAddress) - test(ctx["localAddress"] == info.remoteAddress) - test(ctx["remotePort"] == str(info.localPort)) - test(ctx["localPort"] == str(info.remotePort)) + test(ctx["remoteAddress"] == tcpinfo.localAddress) + test(ctx["localAddress"] == tcpinfo.remoteAddress) + test(ctx["remotePort"] == str(tcpinfo.localPort)) + test(ctx["localPort"] == str(tcpinfo.remotePort)) if(base.ice_getConnection().type() == "ws" or base.ice_getConnection().type() == "wss"): - test((base.ice_getConnection().type() == "ws" and isinstance(info, Ice.WSConnectionInfo)) or - (base.ice_getConnection().type() == "wss" and isinstance(info, Ice.WSSConnectionInfo))) + test(isinstance(info, Ice.WSConnectionInfo)) test(info.headers["Upgrade"] == "websocket") test(info.headers["Connection"] == "Upgrade") diff --git a/python/test/Ice/info/Client.py b/python/test/Ice/info/Client.py index 299cde74e86..49db5dbee46 100755 --- a/python/test/Ice/info/Client.py +++ b/python/test/Ice/info/Client.py @@ -30,17 +30,10 @@ def run(args, communicator): try: initData = Ice.InitializationData() initData.properties = Ice.createProperties(sys.argv) - communicator = Ice.initialize(sys.argv, initData) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv, initData) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/info/Server.py b/python/test/Ice/info/Server.py index 0ae75f959f5..371e544e042 100755 --- a/python/test/Ice/info/Server.py +++ b/python/test/Ice/info/Server.py @@ -22,7 +22,7 @@ import Test, TestI def run(args, communicator): communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010:udp -p 12010") adapter = communicator.createObjectAdapter("TestAdapter") - adapter.add(TestI.MyDerivedClassI(), communicator.stringToIdentity("test")) + adapter.add(TestI.MyDerivedClassI(), Ice.stringToIdentity("test")) adapter.activate() communicator.waitForShutdown() return True @@ -30,17 +30,10 @@ def run(args, communicator): try: initData = Ice.InitializationData() initData.properties = Ice.createProperties(sys.argv) - communicator = Ice.initialize(sys.argv, initData) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv, initData) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/info/TestI.py b/python/test/Ice/info/TestI.py index 7fc0e5abd92..563e9e8180b 100644 --- a/python/test/Ice/info/TestI.py +++ b/python/test/Ice/info/TestI.py @@ -10,7 +10,19 @@ import Ice, Test import time -class MyDerivedClassI(Test.TestIntf): +def getIPEndpointInfo(info): + while(info): + if isinstance(info, Ice.IPEndpointInfo): + return info + info = info.underlying + +def getIPConnectionInfo(info): + while(info): + if isinstance(info, Ice.IPConnectionInfo): + return info + info = info.underlying + +class MyDerivedClassI(Test._TestIntfDisp): def __init__(self): self.ctx = None @@ -19,7 +31,7 @@ class MyDerivedClassI(Test.TestIntf): def getEndpointInfoAsContext(self, current): ctx = {} - info = current.con.getEndpoint().getInfo() + info = getIPEndpointInfo(current.con.getEndpoint().getInfo()) ctx["timeout"] = str(info.timeout) if info.compress: ctx["compress"] = "true" @@ -51,18 +63,19 @@ class MyDerivedClassI(Test.TestIntf): def getConnectionInfoAsContext(self, current): ctx = {} info = current.con.getInfo() + ipinfo = getIPConnectionInfo(info) ctx["adapterName"] = info.adapterName if info.incoming: ctx["incoming"] = "true" else: ctx["incoming"] ="false" - ctx["localAddress"] = info.localAddress - ctx["localPort"] = str(info.localPort) - ctx["remoteAddress"] = info.remoteAddress - ctx["remotePort"] = str(info.remotePort) + ctx["localAddress"] = ipinfo.localAddress + ctx["localPort"] = str(ipinfo.localPort) + ctx["remoteAddress"] = ipinfo.remoteAddress + ctx["remotePort"] = str(ipinfo.remotePort) - if isinstance(info, Ice.WSConnectionInfo) or isinstance(info, Ice.WSSConnectionInfo): + if isinstance(info, Ice.WSConnectionInfo): for key, value in info.headers.items(): ctx["ws." + key] = value diff --git a/python/test/Ice/info/run.py b/python/test/Ice/info/run.py deleted file mode 100755 index 1a8297794cd..00000000000 --- a/python/test/Ice/info/run.py +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env python -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -import os, sys - -path = [ ".", "..", "../..", "../../..", "../../../.." ] -head = os.path.dirname(sys.argv[0]) -if len(head) > 0: - path = [os.path.join(head, p) for p in path] -path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ] -if len(path) == 0: - raise RuntimeError("can't find toplevel directory!") -sys.path.append(os.path.join(path[0], "scripts")) -import TestUtil - -TestUtil.clientServerTest() diff --git a/python/test/Ice/inheritance/Client.py b/python/test/Ice/inheritance/Client.py index 842cef5c4be..256854795fe 100755 --- a/python/test/Ice/inheritance/Client.py +++ b/python/test/Ice/inheritance/Client.py @@ -20,17 +20,10 @@ def run(args, communicator): return True try: - communicator = Ice.initialize(sys.argv) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/inheritance/Collocated.py b/python/test/Ice/inheritance/Collocated.py index 479f94dd558..d8fc1925da5 100755 --- a/python/test/Ice/inheritance/Collocated.py +++ b/python/test/Ice/inheritance/Collocated.py @@ -18,7 +18,7 @@ def run(args, communicator): communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010") adapter = communicator.createObjectAdapter("TestAdapter") object = TestI.InitialI(adapter) - adapter.add(object, communicator.stringToIdentity("initial")) + adapter.add(object, Ice.stringToIdentity("initial")) #adapter.activate() // Don't activate OA to ensure collocation is used. AllTests.allTests(communicator) @@ -26,17 +26,10 @@ def run(args, communicator): return True try: - communicator = Ice.initialize(sys.argv) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/inheritance/Server.py b/python/test/Ice/inheritance/Server.py index a445f89f0db..c08e4f6b29d 100755 --- a/python/test/Ice/inheritance/Server.py +++ b/python/test/Ice/inheritance/Server.py @@ -18,23 +18,16 @@ def run(args, communicator): communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010") adapter = communicator.createObjectAdapter("TestAdapter") object = TestI.InitialI(adapter) - adapter.add(object, communicator.stringToIdentity("initial")) + adapter.add(object, Ice.stringToIdentity("initial")) adapter.activate() communicator.waitForShutdown() return True try: - communicator = Ice.initialize(sys.argv) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/inheritance/Test.ice b/python/test/Ice/inheritance/Test.ice index 84af3da3fd6..372dbcc414a 100644 --- a/python/test/Ice/inheritance/Test.ice +++ b/python/test/Ice/inheritance/Test.ice @@ -9,6 +9,8 @@ #pragma once +[["suppress-warning:deprecated"]] // For classes with operations + module Test { diff --git a/python/test/Ice/inheritance/TestI.py b/python/test/Ice/inheritance/TestI.py index 9b06a39c8cb..f4d98732334 100644 --- a/python/test/Ice/inheritance/TestI.py +++ b/python/test/Ice/inheritance/TestI.py @@ -9,39 +9,39 @@ import Ice, Test -class CAI(Test.MA.CA): +class CAI(Test.MA._CADisp): def caop(self, p, current=None): return p -class CBI(Test.MB.CB, CAI): +class CBI(Test.MB._CBDisp, CAI): def cbop(self, p, current=None): return p -class CCI(Test.MA.CC, CBI): +class CCI(Test.MA._CCDisp, CBI): def ccop(self, p, current=None): return p -class IAI(Test.MA.IA): +class IAI(Test.MA._IADisp): def iaop(self, p, current=None): return p -class IB1I(Test.MB.IB1, IAI): +class IB1I(Test.MB._IB1Disp, IAI): def ib1op(self, p, current=None): return p -class IB2I(Test.MB.IB2, IAI): +class IB2I(Test.MB._IB2Disp, IAI): def ib2op(self, p, current=None): return p -class ICI(Test.MA.IC, IB1I, IB2I): +class ICI(Test.MA._ICDisp, IB1I, IB2I): def icop(self, p, current=None): return p -class CDI(Test.MA.CD, CCI, IB1I, IB2I): +class CDI(Test.MA._CDDisp, CCI, IB1I, IB2I): def cdop(self, p, current=None): return p -class InitialI(Test.Initial): +class InitialI(Test._InitialDisp): def __init__(self, adapter): self._ca = Test.MA.CAPrx.uncheckedCast(adapter.addWithUUID(CAI())) self._cb = Test.MB.CBPrx.uncheckedCast(adapter.addWithUUID(CBI())) diff --git a/python/test/Ice/inheritance/run.py b/python/test/Ice/inheritance/run.py deleted file mode 100755 index e3c2c280892..00000000000 --- a/python/test/Ice/inheritance/run.py +++ /dev/null @@ -1,24 +0,0 @@ -#!/usr/bin/env python -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -import os, sys - -path = [ ".", "..", "../..", "../../..", "../../../.." ] -head = os.path.dirname(sys.argv[0]) -if len(head) > 0: - path = [os.path.join(head, p) for p in path] -path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ] -if len(path) == 0: - raise RuntimeError("can't find toplevel directory!") -sys.path.append(os.path.join(path[0], "scripts")) -import TestUtil - -TestUtil.clientServerTest() -TestUtil.collocatedTest() diff --git a/python/test/Ice/location/AllTests.py b/python/test/Ice/location/AllTests.py index fb4113238ba..4fddaac9ec6 100644 --- a/python/test/Ice/location/AllTests.py +++ b/python/test/Ice/location/AllTests.py @@ -9,7 +9,7 @@ import Ice, Test, sys -class HelloI(Test.Hello): +class HelloI(Test._HelloDisp): def sayHello(self, current=None): pass @@ -22,8 +22,8 @@ def allTests(communicator, ref): locator = communicator.getDefaultLocator() test(manager) - registry = Test.TestLocatorRegistryPrx.checkedCast(locator.getRegistry()); - test(registry); + registry = Test.TestLocatorRegistryPrx.checkedCast(locator.getRegistry()) + test(registry) sys.stdout.write("testing stringToProxy... ") sys.stdout.flush() @@ -36,34 +36,34 @@ def allTests(communicator, ref): sys.stdout.write("testing ice_locator and ice_getLocator... ") sys.stdout.flush() - test(Ice.proxyIdentityEqual(base.ice_getLocator(), communicator.getDefaultLocator())); - anotherLocator = Ice.LocatorPrx.uncheckedCast(communicator.stringToProxy("anotherLocator")); - base = base.ice_locator(anotherLocator); - test(Ice.proxyIdentityEqual(base.ice_getLocator(), anotherLocator)); - communicator.setDefaultLocator(None); - base = communicator.stringToProxy("test @ TestAdapter"); - test(not base.ice_getLocator()); - base = base.ice_locator(anotherLocator); - test(Ice.proxyIdentityEqual(base.ice_getLocator(), anotherLocator)); - communicator.setDefaultLocator(locator); - base = communicator.stringToProxy("test @ TestAdapter"); - test(Ice.proxyIdentityEqual(base.ice_getLocator(), communicator.getDefaultLocator())); - + test(Ice.proxyIdentityEqual(base.ice_getLocator(), communicator.getDefaultLocator())) + anotherLocator = Ice.LocatorPrx.uncheckedCast(communicator.stringToProxy("anotherLocator")) + base = base.ice_locator(anotherLocator) + test(Ice.proxyIdentityEqual(base.ice_getLocator(), anotherLocator)) + communicator.setDefaultLocator(None) + base = communicator.stringToProxy("test @ TestAdapter") + test(not base.ice_getLocator()) + base = base.ice_locator(anotherLocator) + test(Ice.proxyIdentityEqual(base.ice_getLocator(), anotherLocator)) + communicator.setDefaultLocator(locator) + base = communicator.stringToProxy("test @ TestAdapter") + test(Ice.proxyIdentityEqual(base.ice_getLocator(), communicator.getDefaultLocator())) + # # We also test ice_router/ice_getRouter (perhaps we should add a # test/Ice/router test?) # - test(not base.ice_getRouter()); - anotherRouter = Ice.RouterPrx.uncheckedCast(communicator.stringToProxy("anotherRouter")); - base = base.ice_router(anotherRouter); - test(Ice.proxyIdentityEqual(base.ice_getRouter(), anotherRouter)); - router = Ice.RouterPrx.uncheckedCast(communicator.stringToProxy("dummyrouter")); - communicator.setDefaultRouter(router); - base = communicator.stringToProxy("test @ TestAdapter"); - test(Ice.proxyIdentityEqual(base.ice_getRouter(), communicator.getDefaultRouter())); - communicator.setDefaultRouter(None); - base = communicator.stringToProxy("test @ TestAdapter"); - test(not base.ice_getRouter()); + test(not base.ice_getRouter()) + anotherRouter = Ice.RouterPrx.uncheckedCast(communicator.stringToProxy("anotherRouter")) + base = base.ice_router(anotherRouter) + test(Ice.proxyIdentityEqual(base.ice_getRouter(), anotherRouter)) + router = Ice.RouterPrx.uncheckedCast(communicator.stringToProxy("dummyrouter")) + communicator.setDefaultRouter(router) + base = communicator.stringToProxy("test @ TestAdapter") + test(Ice.proxyIdentityEqual(base.ice_getRouter(), communicator.getDefaultRouter())) + communicator.setDefaultRouter(None) + base = communicator.stringToProxy("test @ TestAdapter") + test(not base.ice_getRouter()) print("ok") sys.stdout.write("starting server... ") @@ -106,24 +106,28 @@ def allTests(communicator, ref): try: obj3 = Test.TestIntfPrx.checkedCast(base3) obj3.ice_ping() - except Ice.LocalException: + except Ice.LocalException as ex: + print(ex) test(False) try: obj2 = Test.TestIntfPrx.checkedCast(base2) obj2.ice_ping() - except Ice.LocalException: + except Ice.LocalException as ex: + print(ex) test(False) obj.shutdown() manager.startServer() try: obj2 = Test.TestIntfPrx.checkedCast(base2) obj2.ice_ping() - except Ice.LocalException: + except Ice.LocalException as ex: + print(ex) test(False) try: obj3 = Test.TestIntfPrx.checkedCast(base3) obj3.ice_ping() - except Ice.LocalException: + except Ice.LocalException as ex: + print(ex) test(False) obj.shutdown() manager.startServer() @@ -196,7 +200,7 @@ def allTests(communicator, ref): sys.stdout.flush() hello = Test.HelloPrx.checkedCast(communicator.stringToProxy("hello")) obj.migrateHello() - hello.ice_getConnection().close(False); + hello.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait) hello.sayHello() obj.migrateHello() hello.sayHello() @@ -233,21 +237,21 @@ def allTests(communicator, ref): # sys.stdout.write("testing indirect references to collocated objects... ") sys.stdout.flush() - properties = communicator.getProperties(); - properties.setProperty("Ice.PrintAdapterReady", "0"); - adapter = communicator.createObjectAdapterWithEndpoints("Hello", "default"); - adapter.setLocator(locator); + properties = communicator.getProperties() + properties.setProperty("Ice.PrintAdapterReady", "0") + adapter = communicator.createObjectAdapterWithEndpoints("Hello", "default") + adapter.setLocator(locator) assert(adapter.getLocator() == locator) - id = Ice.Identity(); - id.name = Ice.generateUUID(); - registry.addObject(adapter.add(HelloI(), id)); - adapter.activate(); - - helloPrx = Test.HelloPrx.checkedCast(communicator.stringToProxy(communicator.identityToString(id))); - test(not helloPrx.ice_getConnection()); + id = Ice.Identity() + id.name = Ice.generateUUID() + registry.addObject(adapter.add(HelloI(), id)) + adapter.activate() + + helloPrx = Test.HelloPrx.checkedCast(communicator.stringToProxy(Ice.identityToString(id))) + test(not helloPrx.ice_getConnection()) - adapter.deactivate(); + adapter.deactivate() print("ok") sys.stdout.write("shutdown server manager... ") diff --git a/python/test/Ice/location/Client.py b/python/test/Ice/location/Client.py index 00f224ad1f9..ddb9601b7d8 100755 --- a/python/test/Ice/location/Client.py +++ b/python/test/Ice/location/Client.py @@ -31,17 +31,10 @@ try: data = Ice.InitializationData() data.properties = Ice.createProperties(sys.argv) data.properties.setProperty("Ice.Default.Locator", "locator:default -p 12010") - communicator = Ice.initialize(sys.argv, data) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv, data) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/location/Server.py b/python/test/Ice/location/Server.py index e354926119c..ecb351b820d 100755 --- a/python/test/Ice/location/Server.py +++ b/python/test/Ice/location/Server.py @@ -19,29 +19,29 @@ if not slice_dir: Ice.loadSlice("'-I" + slice_dir + "' Test.ice") import Test -class ServerLocatorRegistry(Test.TestLocatorRegistry): +class ServerLocatorRegistry(Test._TestLocatorRegistryDisp): def __init__(self): self._adapters = {} self._objects = {} - def setAdapterDirectProxy_async(self, cb, adapter, obj, current=None): + def setAdapterDirectProxy(self, adapter, obj, current=None): if obj: self._adapters[adapter] = obj else: self._adapters.pop(adapter) - cb.ice_response() + return None - def setReplicatedAdapterDirectProxy_async(self, cb, adapter, replica, obj, current=None): + def setReplicatedAdapterDirectProxy(self, adapter, replica, obj, current=None): if obj: self._adapters[adapter] = obj self._adapters[replica] = obj else: self._adapters.pop(adapter) self._adapters.pop(replica) - cb.ice_response() + return None - def setServerProcessProxy_async(self, id, proxy, current=None): - cb.ice_response() + def setServerProcessProxy(self, id, proxy, current=None): + return None def addObject(self, obj, current=None): self._objects[obj.ice_getIdentity()] = obj @@ -56,20 +56,20 @@ class ServerLocatorRegistry(Test.TestLocatorRegistry): raise Ice.ObjectNotFoundException() return self._objects[id] -class ServerLocator(Test.TestLocator): +class ServerLocator(Test._TestLocatorDisp): def __init__(self, registry, registryPrx): self._registry = registry self._registryPrx = registryPrx self._requestCount = 0 - def findObjectById_async(self, response, id, current=None): + def findObjectById(self, id, current=None): self._requestCount += 1 - response.ice_response(self._registry.getObject(id)) + return Ice.Future.completed(self._registry.getObject(id)) - def findAdapterById_async(self, response, id, current=None): + def findAdapterById(self, id, current=None): self._requestCount += 1 - response.ice_response(self._registry.getAdapter(id)) + return Ice.Future.completed(self._registry.getAdapter(id)) def getRegistry(self, current=None): return self._registryPrx @@ -77,7 +77,7 @@ class ServerLocator(Test.TestLocator): def getRequestCount(self, current=None): return self._requestCount -class ServerManagerI(Test.ServerManager): +class ServerManagerI(Test._ServerManagerDisp): def __init__(self, registry, initData): self._registry = registry self._communicators = [] @@ -89,7 +89,7 @@ class ServerManagerI(Test.ServerManager): self._initData.properties.setProperty("TestAdapter2.AdapterId", "TestAdapter2") def startServer(self, current=None): - + # # Simulate a server: create a new communicator and object # adapter. The object adapter is started on a system allocated @@ -109,9 +109,9 @@ class ServerManagerI(Test.ServerManager): adapter2.setLocator(Ice.LocatorPrx.uncheckedCast(locator)) object = TestI(adapter, adapter2, self._registry) - self._registry.addObject(adapter.add(object, communicator.stringToIdentity("test"))) - self._registry.addObject(adapter.add(object, communicator.stringToIdentity("test2"))) - adapter.add(object, communicator.stringToIdentity("test3")) + self._registry.addObject(adapter.add(object, Ice.stringToIdentity("test"))) + self._registry.addObject(adapter.add(object, Ice.stringToIdentity("test2"))) + adapter.add(object, Ice.stringToIdentity("test3")) adapter.activate() adapter2.activate() @@ -121,28 +121,28 @@ class ServerManagerI(Test.ServerManager): i.destroy() current.adapter.getCommunicator().shutdown() -class HelloI(Test.Hello): +class HelloI(Test._HelloDisp): def sayHello(self, current=None): pass -class TestI(Test.TestIntf): +class TestI(Test._TestIntfDisp): def __init__(self, adapter, adapter2, registry): self._adapter1 = adapter self._adapter2 = adapter2 self._registry = registry - self._registry.addObject(self._adapter1.add(HelloI(), communicator.stringToIdentity("hello"))) + self._registry.addObject(self._adapter1.add(HelloI(), Ice.stringToIdentity("hello"))) def shutdown(self, current=None): self._adapter1.getCommunicator().shutdown() def getHello(self, current=None): - return Test.HelloPrx.uncheckedCast(self._adapter1.createIndirectProxy(communicator.stringToIdentity("hello"))) + return Test.HelloPrx.uncheckedCast(self._adapter1.createIndirectProxy(Ice.stringToIdentity("hello"))) def getReplicatedHello(self, current=None): - return Test.HelloPrx.uncheckedCast(self._adapter1.createProxy(communicator.stringToIdentity("hello"))) + return Test.HelloPrx.uncheckedCast(self._adapter1.createProxy(Ice.stringToIdentity("hello"))) def migrateHello(self, current=None): - id = communicator.stringToIdentity("hello") + id = Ice.stringToIdentity("hello") try: self._registry.addObject(self._adapter2.add(self._adapter1.remove(id), id)) except Ice.NotRegisteredException: @@ -166,14 +166,14 @@ def run(args, communicator, initData): # 'servers' created with the server manager interface. # registry = ServerLocatorRegistry() - registry.addObject(adapter.createProxy(communicator.stringToIdentity("ServerManager"))) + registry.addObject(adapter.createProxy(Ice.stringToIdentity("ServerManager"))) object = ServerManagerI(registry, initData) - adapter.add(object, communicator.stringToIdentity("ServerManager")) + adapter.add(object, Ice.stringToIdentity("ServerManager")) - registryPrx = Ice.LocatorRegistryPrx.uncheckedCast(adapter.add(registry, communicator.stringToIdentity("registry"))) + registryPrx = Ice.LocatorRegistryPrx.uncheckedCast(adapter.add(registry, Ice.stringToIdentity("registry"))) locator = ServerLocator(registry, registryPrx) - adapter.add(locator, communicator.stringToIdentity("locator")) + adapter.add(locator, Ice.stringToIdentity("locator")) adapter.activate() communicator.waitForShutdown() @@ -183,17 +183,10 @@ def run(args, communicator, initData): try: initData = Ice.InitializationData() initData.properties = Ice.createProperties(sys.argv) - communicator = Ice.initialize(sys.argv, initData) - status = run(sys.argv, communicator, initData) + with Ice.initialize(sys.argv, initData) as communicator: + status = run(sys.argv, communicator, initData) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/location/run.py b/python/test/Ice/location/run.py deleted file mode 100755 index 1a8297794cd..00000000000 --- a/python/test/Ice/location/run.py +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env python -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -import os, sys - -path = [ ".", "..", "../..", "../../..", "../../../.." ] -head = os.path.dirname(sys.argv[0]) -if len(head) > 0: - path = [os.path.join(head, p) for p in path] -path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ] -if len(path) == 0: - raise RuntimeError("can't find toplevel directory!") -sys.path.append(os.path.join(path[0], "scripts")) -import TestUtil - -TestUtil.clientServerTest() diff --git a/python/test/Ice/objects/AllTests.py b/python/test/Ice/objects/AllTests.py index bc7fceab2e9..7578f850ecf 100644 --- a/python/test/Ice/objects/AllTests.py +++ b/python/test/Ice/objects/AllTests.py @@ -9,28 +9,30 @@ import Ice, Test, TestI, sys +def MyValueFactory(type): + if type == '::Test::B': + return TestI.BI() + elif type == '::Test::C': + return TestI.CI() + elif type == '::Test::D': + return TestI.DI() + elif type == '::Test::E': + return TestI.EI() + elif type == '::Test::F': + return TestI.FI() + elif type == '::Test::I': + return TestI.II() + elif type == '::Test::J': + return TestI.JI() + elif type == '::Test::H': + return TestI.HI() + assert(False) # Should never be reached + class MyObjectFactory(Ice.ObjectFactory): def create(self, type): - if type == '::Test::B': - return TestI.BI() - elif type == '::Test::C': - return TestI.CI() - elif type == '::Test::D': - return TestI.DI() - elif type == '::Test::E': - return TestI.EI() - elif type == '::Test::F': - return TestI.FI() - elif type == '::Test::I': - return TestI.II() - elif type == '::Test::J': - return TestI.JI() - elif type == '::Test::H': - return TestI.HI() - assert(False) # Should never be reached - - def destroy(self): - # Nothing to do + return None + + def destroy(): pass def test(b): @@ -38,15 +40,16 @@ def test(b): raise RuntimeError('test assertion failed') def allTests(communicator): - factory = MyObjectFactory() - communicator.addObjectFactory(factory, '::Test::B') - communicator.addObjectFactory(factory, '::Test::C') - communicator.addObjectFactory(factory, '::Test::D') - communicator.addObjectFactory(factory, '::Test::E') - communicator.addObjectFactory(factory, '::Test::F') - communicator.addObjectFactory(factory, '::Test::I') - communicator.addObjectFactory(factory, '::Test::J') - communicator.addObjectFactory(factory, '::Test::H') + communicator.getValueFactoryManager().add(MyValueFactory, '::Test::B') + communicator.getValueFactoryManager().add(MyValueFactory, '::Test::C') + communicator.getValueFactoryManager().add(MyValueFactory, '::Test::D') + communicator.getValueFactoryManager().add(MyValueFactory, '::Test::E') + communicator.getValueFactoryManager().add(MyValueFactory, '::Test::F') + communicator.getValueFactoryManager().add(MyValueFactory, '::Test::I') + communicator.getValueFactoryManager().add(MyValueFactory, '::Test::J') + communicator.getValueFactoryManager().add(MyValueFactory, '::Test::H') + + communicator.addObjectFactory(MyObjectFactory(), "TestOF") sys.stdout.write("testing stringToProxy... ") sys.stdout.flush() @@ -67,19 +70,19 @@ def allTests(communicator): b1 = initial.getB1() test(b1) print("ok") - + sys.stdout.write("getting B2... ") sys.stdout.flush() b2 = initial.getB2() test(b2) print("ok") - + sys.stdout.write("getting C... ") sys.stdout.flush() c = initial.getC() test(c) print("ok") - + sys.stdout.write("getting D... ") sys.stdout.flush() d = initial.getD() @@ -97,26 +100,26 @@ def allTests(communicator): test(f.e2.checkValues()) test(f._e1.checkValues()) print("ok") - + sys.stdout.write("getting I, J, H... ") sys.stdout.flush() i = initial.getI() test(i) j = initial.getJ() - test(isinstance(j, Test.J)) + test(isinstance(j, TestI.JI)) h = initial.getH() test(isinstance(h, Test.H)) print("ok") - + sys.stdout.write("getting D1... ") sys.stdout.flush() - d1 = initial.getD1(Test.D1(Test.A1("a1"), Test.A1("a2"), Test.A1("a3"), Test.A1("a4"))); + d1 = initial.getD1(Test.D1(Test.A1("a1"), Test.A1("a2"), Test.A1("a3"), Test.A1("a4"))) test(d1.a1.name == "a1") test(d1.a2.name == "a2") test(d1.a3.name == "a3") test(d1.a4.name == "a4") print("ok") - + sys.stdout.write("throw EDerived... ") sys.stdout.flush() try: @@ -135,7 +138,7 @@ def allTests(communicator): initial.setI(TestI.JI()) initial.setI(TestI.HI()) print("ok") - + sys.stdout.write("checking consistency... ") sys.stdout.flush() test(b1 != b2) @@ -152,11 +155,11 @@ def allTests(communicator): test(b1.theA.theC) test(b1.theA.theC.theB == b1.theA) test(b1.preMarshalInvoked) - test(b1.postUnmarshalInvoked()) + test(b1.postUnmarshalInvoked) test(b1.theA.preMarshalInvoked) - test(b1.theA.postUnmarshalInvoked()) + test(b1.theA.postUnmarshalInvoked) test(b1.theA.theC.preMarshalInvoked) - test(b1.theA.theC.postUnmarshalInvoked()) + test(b1.theA.theC.postUnmarshalInvoked) # More tests possible for b2 and d, but I think this is already sufficient. test(b2.theA == b2) test(d.theC == None) @@ -170,7 +173,7 @@ def allTests(communicator): test(c) test(d) print("ok") - + sys.stdout.write("checking consistency... ") sys.stdout.flush() test(b1 != b2) @@ -190,13 +193,13 @@ def allTests(communicator): test(d.theB == b2) test(d.theC == None) test(d.preMarshalInvoked) - test(d.postUnmarshalInvoked()) + test(d.postUnmarshalInvoked) test(d.theA.preMarshalInvoked) - test(d.theA.postUnmarshalInvoked()) + test(d.theA.postUnmarshalInvoked) test(d.theB.preMarshalInvoked) - test(d.theB.postUnmarshalInvoked()) + test(d.theB.postUnmarshalInvoked) test(d.theB.theC.preMarshalInvoked) - test(d.theB.theC.postUnmarshalInvoked()) + test(d.theB.theC.postUnmarshalInvoked) print("ok") sys.stdout.write("testing sequences... ") @@ -219,8 +222,16 @@ def allTests(communicator): pass print("ok") + sys.stdout.write("testing marshaled results...") + sys.stdout.flush() + b1 = initial.getMB() + test(b1 != None and b1.theB == b1) + b1 = initial.getAMDMBAsync().result() + test(b1 != None and b1.theB == b1) + print("ok") + # Don't run this test with collocation, this should work with collocation - # but the test isn't written to support it (we'd need support for the + # but the test isn't written to support it (we'd need support for the # streaming interface) if initial.ice_getConnection(): sys.stdout.write("testing UnexpectedObjectException... ") @@ -244,4 +255,14 @@ def allTests(communicator): test(False) print("ok") + sys.stdout.write("testing getting ObjectFactory... ") + sys.stdout.flush() + test(communicator.findObjectFactory("TestOF") != None) + print("ok") + + sys.stdout.write("testing getting ObjectFactory as ValueFactory... ") + sys.stdout.flush() + test(communicator.getValueFactoryManager().find("TestOF") != None) + print("ok") + return initial diff --git a/python/test/Ice/objects/Client.py b/python/test/Ice/objects/Client.py index a27a4771580..eb34e04fc41 100755 --- a/python/test/Ice/objects/Client.py +++ b/python/test/Ice/objects/Client.py @@ -21,17 +21,10 @@ def run(args, communicator): return True try: - communicator = Ice.initialize(sys.argv) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/objects/Collocated.py b/python/test/Ice/objects/Collocated.py index a44a1c9a48f..845d56c4cea 100755 --- a/python/test/Ice/objects/Collocated.py +++ b/python/test/Ice/objects/Collocated.py @@ -19,9 +19,9 @@ def run(args, communicator): communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010") adapter = communicator.createObjectAdapter("TestAdapter") initial = TestI.InitialI(adapter) - adapter.add(initial, communicator.stringToIdentity("initial")) + adapter.add(initial, Ice.stringToIdentity("initial")) uoet = TestI.UnexpectedObjectExceptionTestI() - adapter.add(uoet, communicator.stringToIdentity("uoet")) + adapter.add(uoet, Ice.stringToIdentity("uoet")) #adapter.activate() // Don't activate OA to ensure collocation is used. AllTests.allTests(communicator) @@ -32,17 +32,10 @@ def run(args, communicator): return True try: - communicator = Ice.initialize(sys.argv) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/objects/Server.py b/python/test/Ice/objects/Server.py index b23f646405d..b4352d82b5d 100755 --- a/python/test/Ice/objects/Server.py +++ b/python/test/Ice/objects/Server.py @@ -15,48 +15,35 @@ Ice.loadSlice('Test.ice') Ice.loadSlice('ServerPrivate.ice') import Test, TestI -class MyObjectFactory(Ice.ObjectFactory): - def create(self, type): - if type == '::Test::I': - return TestI.II() - elif type == '::Test::J': - return TestI.JI() - elif type == '::Test::H': - return TestI.HI() - assert(False) # Should never be reached - - def destroy(self): - # Nothing to do - pass +def MyValueFactory(type): + if type == '::Test::I': + return TestI.II() + elif type == '::Test::J': + return TestI.JI() + elif type == '::Test::H': + return TestI.HI() + assert(False) # Should never be reached def run(args, communicator): - factory = MyObjectFactory() - communicator.addObjectFactory(factory, '::Test::I') - communicator.addObjectFactory(factory, '::Test::J') - communicator.addObjectFactory(factory, '::Test::H') + communicator.getValueFactoryManager().add(MyValueFactory, '::Test::I') + communicator.getValueFactoryManager().add(MyValueFactory, '::Test::J') + communicator.getValueFactoryManager().add(MyValueFactory, '::Test::H') communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010") adapter = communicator.createObjectAdapter("TestAdapter") initial = TestI.InitialI(adapter) - adapter.add(initial, communicator.stringToIdentity("initial")) + adapter.add(initial, Ice.stringToIdentity("initial")) uoet = TestI.UnexpectedObjectExceptionTestI() - adapter.add(uoet, communicator.stringToIdentity("uoet")) + adapter.add(uoet, Ice.stringToIdentity("uoet")) adapter.activate() communicator.waitForShutdown() return True try: - communicator = Ice.initialize(sys.argv) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/objects/Test.ice b/python/test/Ice/objects/Test.ice index 9517a5b050f..8ddd5e1d4cc 100644 --- a/python/test/Ice/objects/Test.ice +++ b/python/test/Ice/objects/Test.ice @@ -9,6 +9,8 @@ #pragma once +[["suppress-warning:deprecated"]] // For classes with operations + module Test { @@ -37,7 +39,7 @@ class A C theC; bool preMarshalInvoked; - bool postUnmarshalInvoked(); + bool postUnmarshalInvoked; }; class B extends A @@ -50,7 +52,7 @@ class C B theB; bool preMarshalInvoked; - bool postUnmarshalInvoked(); + bool postUnmarshalInvoked; }; class D @@ -60,23 +62,19 @@ class D C theC; bool preMarshalInvoked; - bool postUnmarshalInvoked(); + bool postUnmarshalInvoked; }; ["protected"] class E { int i; string s; - - bool checkValues(); }; class F { ["protected"] E e1; E e2; - - bool checkValues(); }; interface I @@ -174,6 +172,9 @@ class Initial E getE(); F getF(); + ["marshaled-result"] B getMB(); + ["amd", "marshaled-result"] B getAMDMB(); + void getAll(out B b1, out B b2, out C theC, out D theD); I getI(); diff --git a/python/test/Ice/objects/TestI.py b/python/test/Ice/objects/TestI.py index 03c4e4db06d..f711157a741 100644 --- a/python/test/Ice/objects/TestI.py +++ b/python/test/Ice/objects/TestI.py @@ -12,44 +12,35 @@ import Ice, Test class BI(Test.B): def __init__(self): self.preMarshalInvoked = False - self._postUnmarshalInvoked = False - - def postUnmarshalInvoked(self, current=None): - return self._postUnmarshalInvoked + self.postUnmarshalInvoked = False def ice_preMarshal(self): self.preMarshalInvoked = True def ice_postUnmarshal(self): - self._postUnmarshalInvoked = True + self.postUnmarshalInvoked = True class CI(Test.C): def __init__(self): self.preMarshalInvoked = False - self._postUnmarshalInvoked = False - - def postUnmarshalInvoked(self, current=None): - return self._postUnmarshalInvoked + self.postUnmarshalInvoked = False def ice_preMarshal(self): self.preMarshalInvoked = True def ice_postUnmarshal(self): - self._postUnmarshalInvoked = True + self.postUnmarshalInvoked = True class DI(Test.D): def __init__(self): self.preMarshalInvoked = False - self._postUnmarshalInvoked = False - - def postUnmarshalInvoked(self, current=None): - return self._postUnmarshalInvoked + self.postUnmarshalInvoked = False def ice_preMarshal(self): self.preMarshalInvoked = True def ice_postUnmarshal(self): - self._postUnmarshalInvoked = True + self.postUnmarshalInvoked = True class EI(Test.E): def __init__(self): @@ -65,16 +56,18 @@ class FI(Test.F): def checkValues(self, current=None): return self._e1 != None and self._e1 == self.e2 -class II(Test.I): - pass +class II(Ice.InterfaceByValue): + def __init__(self): + Ice.InterfaceByValue.__init__(self, "::Test::I") -class JI(Test.J): - pass +class JI(Ice.InterfaceByValue): + def __init__(self): + Ice.InterfaceByValue.__init__(self, "::Test::J") class HI(Test.H): pass -class InitialI(Test.Initial): +class InitialI(Test._InitialDisp): def __init__(self, adapter): self._adapter = adapter self._b1 = BI() @@ -132,6 +125,12 @@ class InitialI(Test.Initial): def getF(self, current=None): return self._f + def getMB(self, current): + return self._b1 + + def getAMDMB(self, current): + return Ice.Future.completed(self._b1) + def getAll(self, current=None): self._b1.preMarshalInvoked = False self._b2.preMarshalInvoked = False @@ -175,6 +174,6 @@ class InitialI(Test.Initial): def throwInnerSubEx(self, current=None): raise Test.Inner.Sub.Ex("Inner::Sub::Ex") -class UnexpectedObjectExceptionTestI(Test.UnexpectedObjectExceptionTest): +class UnexpectedObjectExceptionTestI(Test._UnexpectedObjectExceptionTestDisp): def op(self, current=None): return Test.AlsoEmpty() diff --git a/python/test/Ice/objects/run.py b/python/test/Ice/objects/run.py deleted file mode 100755 index 670da8fecb4..00000000000 --- a/python/test/Ice/objects/run.py +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env python -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -import os, sys - -path = [ ".", "..", "../..", "../../..", "../../../.." ] -head = os.path.dirname(sys.argv[0]) -if len(head) > 0: - path = [os.path.join(head, p) for p in path] -path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ] -if len(path) == 0: - raise RuntimeError("can't find toplevel directory!") -sys.path.append(os.path.join(path[0], "scripts")) -import TestUtil - -print("Running test with compact (default) format.") -TestUtil.clientServerTest() - -print("Running test with sliced format.") -TestUtil.clientServerTest(additionalClientOptions="--Ice.Default.SlicedFormat", - additionalServerOptions="--Ice.Default.SlicedFormat") - -print("Running test with 1.0 encoding.") -TestUtil.clientServerTest(additionalClientOptions="--Ice.Default.EncodingVersion=1.0", - additionalServerOptions="--Ice.Default.EncodingVersion=1.0") - -print("Running collocated test.") -TestUtil.collocatedTest() diff --git a/python/test/Ice/operations/AllTests.py b/python/test/Ice/operations/AllTests.py index 802e595037b..d306b75ec87 100644 --- a/python/test/Ice/operations/AllTests.py +++ b/python/test/Ice/operations/AllTests.py @@ -7,8 +7,8 @@ # # ********************************************************************** -import Ice, Test, Twoways, TwowaysAMI, Oneways, OnewaysAMI, BatchOneways, sys -import BatchOnewaysAMI +import Ice, Test, Twoways, TwowaysFuture, TwowaysAMI, Oneways, OnewaysFuture, OnewaysAMI, BatchOneways, sys +import BatchOnewaysAMI, BatchOnewaysFuture def test(b): if not b: @@ -32,23 +32,39 @@ def allTests(communicator): Oneways.oneways(communicator, cl) print("ok") + sys.stdout.write("testing twoway operations with futures... ") + sys.stdout.flush() + TwowaysFuture.twowaysFuture(communicator, cl) + print("ok") + sys.stdout.write("testing twoway operations with AMI... ") sys.stdout.flush() TwowaysAMI.twowaysAMI(communicator, cl) print("ok") - + + sys.stdout.write("testing oneway operations with futures... ") + sys.stdout.flush() + OnewaysFuture.onewaysFuture(communicator, cl) + print("ok") + sys.stdout.write("testing oneway operations with AMI... ") sys.stdout.flush() OnewaysAMI.onewaysAMI(communicator, cl) print("ok") - + sys.stdout.write("testing batch oneway operations... ") sys.stdout.flush() BatchOneways.batchOneways(cl) BatchOneways.batchOneways(derived) print("ok") - - sys.stdout.write("testing batch AMI oneway operations... ") + + sys.stdout.write("testing batch oneway operations with futures... ") + sys.stdout.flush() + BatchOnewaysFuture.batchOneways(cl) + BatchOnewaysFuture.batchOneways(derived) + print("ok") + + sys.stdout.write("testing batch oneway operations with AMI... ") sys.stdout.flush() BatchOnewaysAMI.batchOneways(cl) BatchOnewaysAMI.batchOneways(derived) diff --git a/python/test/Ice/operations/BatchOneways.py b/python/test/Ice/operations/BatchOneways.py index fdef04bf70c..4cbe23276a6 100644 --- a/python/test/Ice/operations/BatchOneways.py +++ b/python/test/Ice/operations/BatchOneways.py @@ -64,6 +64,9 @@ def batchOneways(p): batch = Test.MyClassPrx.uncheckedCast(p.ice_batchOneway()) batch.ice_flushBatchRequests() # Empty flush + if batch.ice_getConnection(): + batch.ice_getConnection().flushBatchRequests(Ice.CompressBatch.BasedOnProxy) + batch.ice_getCommunicator().flushBatchRequests(Ice.CompressBatch.BasedOnProxy) p.opByteSOnewayCallCount() # Reset the call count @@ -82,7 +85,7 @@ def batchOneways(p): batch1.ice_ping() batch2.ice_ping() batch1.ice_flushBatchRequests() - batch1.ice_getConnection().close(False) + batch1.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait) batch1.ice_ping() batch2.ice_ping() @@ -90,7 +93,7 @@ def batchOneways(p): batch2.ice_getConnection() batch1.ice_ping() - batch1.ice_getConnection().close(False) + batch1.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait) batch1.ice_ping() batch2.ice_ping() diff --git a/python/test/Ice/operations/BatchOnewaysAMI.py b/python/test/Ice/operations/BatchOnewaysAMI.py index 28e1b47149c..7629d7d1627 100644 --- a/python/test/Ice/operations/BatchOnewaysAMI.py +++ b/python/test/Ice/operations/BatchOnewaysAMI.py @@ -19,19 +19,15 @@ class Callback: self._cond = threading.Condition() def check(self): - self._cond.acquire() - try: + with self._cond: while not self._called: self._cond.wait() self._called = False - finally: - self._cond.release() def called(self): - self._cond.acquire() - self._called = True - self._cond.notify() - self._cond.release() + with self._cond: + self._called = True + self._cond.notify() def batchOneways(p): @@ -65,14 +61,14 @@ def batchOneways(p): batch1.end_ice_ping(batch1.begin_ice_ping()) batch2.end_ice_ping(batch2.begin_ice_ping()) batch1.end_ice_flushBatchRequests(batch1.begin_ice_flushBatchRequests()) - batch1.ice_getConnection().close(False) + batch1.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait) batch1.end_ice_ping(batch1.begin_ice_ping()) batch2.end_ice_ping(batch2.begin_ice_ping()) batch1.ice_getConnection() batch2.ice_getConnection() - batch1.ice_getConnection().close(False) + batch1.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait) batch1.end_ice_ping(batch1.begin_ice_ping()) batch2.end_ice_ping(batch2.begin_ice_ping()) diff --git a/python/test/Ice/operations/BatchOnewaysFuture.py b/python/test/Ice/operations/BatchOnewaysFuture.py new file mode 100644 index 00000000000..7f2b89cfc81 --- /dev/null +++ b/python/test/Ice/operations/BatchOnewaysFuture.py @@ -0,0 +1,88 @@ +# ********************************************************************** +# +# Copyright (c) 2003-2016 ZeroC, Inc. All rights reserved. +# +# This copy of Ice is licensed to you under the terms described in the +# ICE_LICENSE file included in this distribution. +# +# ********************************************************************** + +import Ice, Test, array, sys, threading, time + +def test(b): + if not b: + raise RuntimeError('test assertion failed') + +class Callback: + def __init__(self): + self._called = False + self._cond = threading.Condition() + + def check(self): + with self._cond: + while not self._called: + self._cond.wait() + self._called = False + + def called(self): + with self._cond: + self._called = True + self._cond.notify() + +def batchOneways(p): + + if sys.version_info[0] == 2: + bs1 = [] + bs1[0:10 * 1024] = range(0, 10 * 1024) # add 100,000 entries. + bs1 = ['\x00' for x in bs1] # set them all to \x00 + bs1 = ''.join(bs1) # make into a byte array + else: + bs1 = bytes([0 for x in range(0, 10 * 1024)]) + batch = Test.MyClassPrx.uncheckedCast(p.ice_batchOneway()) + + f = batch.ice_flushBatchRequestsAsync() # Empty flush + f.result() + + test(batch.ice_flushBatchRequestsAsync().is_sent()) # Empty flush + test(batch.ice_flushBatchRequestsAsync().done()) # Empty flush + test(batch.ice_flushBatchRequestsAsync().is_sent_synchronously()) # Empty flush + + for i in range(30): + batch.opByteSOnewayAsync(bs1) + + count = 0 + while count < 27: # 3 * 9 requests auto-flushed. + count += p.opByteSOnewayCallCount() + time.sleep(0.01) + + if p.ice_getConnection(): + + batch1 = Test.MyClassPrx.uncheckedCast(p.ice_batchOneway()) + batch2 = Test.MyClassPrx.uncheckedCast(p.ice_batchOneway()) + + batch1.ice_pingAsync() + batch2.ice_pingAsync() + batch1.ice_flushBatchRequestsAsync().result() + batch1.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait) + batch1.ice_pingAsync() + batch2.ice_pingAsync() + + batch1.ice_getConnection() + batch2.ice_getConnection() + + batch1.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait) + + test(not batch1.ice_pingAsync().done()) + test(not batch2.ice_pingAsync().done()) + + identity = Ice.Identity() + identity.name = "invalid"; + batch3 = batch.ice_identity(identity) + batch3.ice_ping() + batch3.ice_flushBatchRequestsAsync().result() + + # Make sure that a bogus batch request doesn't cause troubles to other ones. + batch3.ice_ping() + batch.ice_ping() + batch.ice_flushBatchRequestsAsync().result() + batch.ice_ping() diff --git a/python/test/Ice/operations/Client.py b/python/test/Ice/operations/Client.py index e5c66401c07..51da4c466b3 100755 --- a/python/test/Ice/operations/Client.py +++ b/python/test/Ice/operations/Client.py @@ -31,7 +31,7 @@ def run(args, communicator): sys.stdout.flush() myClass.shutdown() try: - myClass.opVoid() + myClass.ice_timeout(100).ice_ping(); # Use timeout to speed up testing on Windows test(False) except Ice.LocalException: print("ok") @@ -49,17 +49,13 @@ try: initData.properties.setProperty('Ice.ThreadPool.Client.SizeWarn', '0') initData.properties.setProperty("Ice.BatchAutoFlushSize", "100") - communicator = Ice.initialize(sys.argv, initData) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv, initData) as communicator: + status = run(sys.argv, communicator) + # Test multiple destroy calls + communicator.destroy() + communicator.destroy() except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/operations/Collocated.py b/python/test/Ice/operations/Collocated.py index 36b09e12f11..8148b7af298 100755 --- a/python/test/Ice/operations/Collocated.py +++ b/python/test/Ice/operations/Collocated.py @@ -22,7 +22,7 @@ import Test, TestI, AllTests def run(args, communicator): communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010") adapter = communicator.createObjectAdapter("TestAdapter") - prx = adapter.add(TestI.MyDerivedClassI(), communicator.stringToIdentity("test")) + prx = adapter.add(TestI.MyDerivedClassI(), Ice.stringToIdentity("test")) #adapter.activate() // Don't activate OA to ensure collocation is used. if prx.ice_getConnection(): @@ -38,17 +38,10 @@ try: initData.properties.setProperty("Ice.BatchAutoFlushSize", "100") - communicator = Ice.initialize(sys.argv, initData) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv, initData) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/operations/OnewaysAMI.py b/python/test/Ice/operations/OnewaysAMI.py index a2dc299933c..79b31c73eb3 100644 --- a/python/test/Ice/operations/OnewaysAMI.py +++ b/python/test/Ice/operations/OnewaysAMI.py @@ -19,19 +19,15 @@ class CallbackBase: self._cond = threading.Condition() def check(self): - self._cond.acquire() - try: + with self._cond: while not self._called: self._cond.wait() self._called = False - finally: - self._cond.release() def called(self): - self._cond.acquire() - self._called = True - self._cond.notify() - self._cond.release() + with self._cond: + self._called = True + self._cond.notify() class Callback(CallbackBase): def sent(self, sentSynchronously): @@ -49,7 +45,7 @@ def onewaysAMI(communicator, proxy): cb.check() try: - p.begin_ice_isA(Test.MyClass.ice_staticId()) + p.begin_ice_isA(Test._MyClassDisp.ice_staticId()) test(False) except RuntimeError: pass diff --git a/python/test/Ice/operations/OnewaysFuture.py b/python/test/Ice/operations/OnewaysFuture.py new file mode 100644 index 00000000000..741425a0ef4 --- /dev/null +++ b/python/test/Ice/operations/OnewaysFuture.py @@ -0,0 +1,54 @@ +# ********************************************************************** +# +# Copyright (c) 2003-2016 ZeroC, Inc. All rights reserved. +# +# This copy of Ice is licensed to you under the terms described in the +# ICE_LICENSE file included in this distribution. +# +# ********************************************************************** + +import Ice, Test + +def test(b): + if not b: + raise RuntimeError('test assertion failed') + +def onewaysFuture(communicator, proxy): + + p = Test.MyClassPrx.uncheckedCast(proxy.ice_oneway()) + + f = p.ice_pingAsync() + f.sent() + + try: + p.ice_isAAsync(Test._MyClassDisp.ice_staticId()) + test(False) + except RuntimeError: + pass + + try: + p.ice_idAsync() + test(False) + except RuntimeError: + pass + + try: + p.ice_idsAsync() + test(False) + except RuntimeError: + pass + + f = p.opVoidAsync() + f.sent() + + f = p.opIdempotentAsync() + f.sent() + + f = p.opNonmutatingAsync() + f.sent() + + try: + p.opByteAsync(0xff, 0x0f) + test(False) + except RuntimeError: + pass diff --git a/python/test/Ice/operations/Server.py b/python/test/Ice/operations/Server.py index 9b19906eafe..5ec8816dc25 100755 --- a/python/test/Ice/operations/Server.py +++ b/python/test/Ice/operations/Server.py @@ -21,7 +21,7 @@ import Test, TestI def run(args, communicator): communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010:udp") adapter = communicator.createObjectAdapter("TestAdapter") - adapter.add(TestI.MyDerivedClassI(), communicator.stringToIdentity("test")) + adapter.add(TestI.MyDerivedClassI(), Ice.stringToIdentity("test")) adapter.activate() communicator.waitForShutdown() return True @@ -35,17 +35,10 @@ try: # this warning. # initData.properties.setProperty("Ice.Warn.Dispatch", "0"); - communicator = Ice.initialize(sys.argv, initData) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv, initData) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/operations/ServerAMD.py b/python/test/Ice/operations/ServerAMD.py index f3dd86e001b..0b727f42970 100755 --- a/python/test/Ice/operations/ServerAMD.py +++ b/python/test/Ice/operations/ServerAMD.py @@ -8,7 +8,11 @@ # # ********************************************************************** -import os, sys, traceback, threading +import os, sys, traceback, threading, time + +haveConcurrentFuture = sys.version_info.major > 3 or (sys.version_info.major == 3 and sys.version_info.minor >= 5) +if haveConcurrentFuture: + import concurrent.futures import Ice slice_dir = Ice.getSliceDir() @@ -23,87 +27,96 @@ def test(b): if not b: raise RuntimeError('test assertion failed') -class Thread_opVoid(threading.Thread): - def __init__(self, cb): +class FutureThread(threading.Thread): + def __init__(self, f, r): threading.Thread.__init__(self) - self.cb = cb + self.future = f + self.result = r def run(self): - self.cb.ice_response() + time.sleep(0.01) + self.future.set_result(self.result) -class MyDerivedClassI(Test.MyDerivedClass): +class MyDerivedClassI(Test._MyDerivedClassDisp): def __init__(self): - self.opVoidThread = None - self.opVoidThreadLock = threading.Lock() + self.threads = [] + self.threadLock = threading.Lock() self.lock = threading.Lock() self.opByteSOnewayCount = 0 def ice_isA(self, id, current=None): test(current.mode == Ice.OperationMode.Nonmutating) - return Test.MyDerivedClass.ice_isA(self, id, current) + return Test._MyDerivedClassDisp.ice_isA(self, id, current) def ice_ping(self, current=None): test(current.mode == Ice.OperationMode.Nonmutating) - Test.MyDerivedClass.ice_ping(self, current) + Test._MyDerivedClassDisp.ice_ping(self, current) def ice_ids(self, current=None): test(current.mode == Ice.OperationMode.Nonmutating) - return Test.MyDerivedClass.ice_ids(self, current) + return Test._MyDerivedClassDisp.ice_ids(self, current) def ice_id(self, current=None): test(current.mode == Ice.OperationMode.Nonmutating) - return Test.MyDerivedClass.ice_id(self, current) + return Test._MyDerivedClassDisp.ice_id(self, current) - def shutdown_async(self, cb, current=None): - self.opVoidThreadLock.acquire() - if self.opVoidThread: - self.opVoidThread.join() - self.opVoidThread = None - self.opVoidThreadLock.release() + def shutdown(self, current=None): + with self.threadLock: + for thread in self.threads: + thread.join() + self.threads = [] current.adapter.getCommunicator().shutdown() - cb.ice_response() - def opVoid_async(self, cb, current=None): + def opVoid(self, current=None): test(current.mode == Ice.OperationMode.Normal) - self.opVoidThreadLock.acquire() - if self.opVoidThread: - self.opVoidThread.join() - self.opVoidThread = None + f = Ice.Future() + + with self.threadLock: + thread = FutureThread(f, None) + self.threads.append(thread) + thread.start() - self.opVoidThread = Thread_opVoid(cb) - self.opVoidThread.start() - self.opVoidThreadLock.release() + return f - def opByte_async(self, cb, p1, p2, current=None): - cb.ice_response(p1, p1 ^ p2) + def opByte(self, p1, p2, current=None): + # Test the ability to use another Future type + if haveConcurrentFuture: + f = concurrent.futures.Future() + with self.threadLock: + thread = FutureThread(f, (p1, p1 ^ p2)) + self.threads.append(thread) + thread.start() + else: + f = Ice.Future.completed((p1, p1 ^ p2)) + return f - def opBool_async(self, cb, p1, p2, current=None): - cb.ice_response(p2, p1) + def opBool(self, p1, p2, current=None): + return Ice.Future.completed((p2, p1)) - def opShortIntLong_async(self, cb, p1, p2, p3, current=None): - cb.ice_response(p3, p1, p2, p3) + def opShortIntLong(self, p1, p2, p3, current=None): + return Ice.Future.completed((p3, p1, p2, p3)) - def opFloatDouble_async(self, cb, p1, p2, current=None): - cb.ice_response(p2, p1, p2) + def opFloatDouble(self, p1, p2, current=None): + return Ice.Future.completed((p2, p1, p2)) - def opString_async(self, cb, p1, p2, current=None): - cb.ice_response(p1 + " " + p2, p2 + " " + p1) + def opString(self, p1, p2, current=None): + return Ice.Future.completed((p1 + " " + p2, p2 + " " + p1)) - def opMyEnum_async(self, cb, p1, current=None): - cb.ice_response(Test.MyEnum.enum3, p1) + def opMyEnum(self, p1, current=None): + return Ice.Future.completed((Test.MyEnum.enum3, p1)) - def opMyClass_async(self, cb, p1, current=None): + def opMyClass(self, p1, current=None): p2 = p1 - p3 = Test.MyClassPrx.uncheckedCast(current.adapter.createProxy(communicator.stringToIdentity("noSuchIdentity"))) - cb.ice_response(Test.MyClassPrx.uncheckedCast(current.adapter.createProxy(current.id)), p2, p3) + p3 = Test.MyClassPrx.uncheckedCast(current.adapter.createProxy(Ice.stringToIdentity("noSuchIdentity"))) + return Ice.Future.completed((Test.MyClassPrx.uncheckedCast(current.adapter.createProxy(current.id)), p2, p3)) - def opStruct_async(self, cb, p1, p2, current=None): + def opStruct(self, p1, p2, current=None): p1.s.s = "a new string" - cb.ice_response(p2, p1) + return Ice.Future.completed((p2, p1)) - def opByteS_async(self, cb, p1, p2, current=None): + def opByteS(self, p1, p2, current=None): if sys.version_info[0] == 2: # By default sequence<byte> maps to a string. p3 = map(ord, p1) @@ -113,310 +126,327 @@ class MyDerivedClassI(Test.MyDerivedClass): else: p3 = bytes(reversed(p1)) r = p1 + p2 - cb.ice_response(r, p3) + return Ice.Future.completed((r, p3)) - def opBoolS_async(self, cb, p1, p2, current=None): + def opBoolS(self, p1, p2, current=None): p3 = p1[0:] p3.extend(p2) r = p1[0:] r.reverse(); - cb.ice_response(r, p3) + return Ice.Future.completed((r, p3)) - def opShortIntLongS_async(self, cb, p1, p2, p3, current=None): + def opShortIntLongS(self, p1, p2, p3, current=None): p4 = p1[0:] p5 = p2[0:] p5.reverse() p6 = p3[0:] p6.extend(p3) - cb.ice_response(p3, p4, p5, p6) + return Ice.Future.completed((p3, p4, p5, p6)) - def opFloatDoubleS_async(self, cb, p1, p2, current=None): + def opFloatDoubleS(self, p1, p2, current=None): p3 = p1[0:] p4 = p2[0:] p4.reverse() r = p2[0:] r.extend(p1) - cb.ice_response(r, p3, p4) + return Ice.Future.completed((r, p3, p4)) - def opStringS_async(self, cb, p1, p2, current=None): + def opStringS(self, p1, p2, current=None): p3 = p1[0:] p3.extend(p2) r = p1[0:] r.reverse() - cb.ice_response(r, p3) + return Ice.Future.completed((r, p3)) - def opByteSS_async(self, cb, p1, p2, current=None): + def opByteSS(self, p1, p2, current=None): p3 = p1[0:] p3.reverse() r = p1[0:] r.extend(p2) - cb.ice_response(r, p3) + return Ice.Future.completed((r, p3)) - def opBoolSS_async(self, cb, p1, p2, current=None): + def opBoolSS(self, p1, p2, current=None): p3 = p1[0:] p3.extend(p2) r = p1[0:] r.reverse() - cb.ice_response(r, p3) + return Ice.Future.completed((r, p3)) - def opShortIntLongSS_async(self, cb, p1, p2, p3, current=None): + def opShortIntLongSS(self, p1, p2, p3, current=None): p4 = p1[0:] p5 = p2[0:] p5.reverse() p6 = p3[0:] p6.extend(p3) - cb.ice_response(p3, p4, p5, p6) + return Ice.Future.completed((p3, p4, p5, p6)) - def opFloatDoubleSS_async(self, cb, p1, p2, current=None): + def opFloatDoubleSS(self, p1, p2, current=None): p3 = p1[0:] p4 = p2[0:] p4.reverse() r = p2[0:] r.extend(p2) - cb.ice_response(r, p3, p4) + return Ice.Future.completed((r, p3, p4)) - def opStringSS_async(self, cb, p1, p2, current=None): + def opStringSS(self, p1, p2, current=None): p3 = p1[0:] p3.extend(p2) r = p2[0:] r.reverse() - cb.ice_response(r, p3) + return Ice.Future.completed((r, p3)) - def opStringSSS_async(self, cb, p1, p2, current=None): + def opStringSSS(self, p1, p2, current=None): p3 = p1[0:] p3.extend(p2) r = p2[0:] r.reverse() - cb.ice_response(r, p3) + return Ice.Future.completed((r, p3)) - def opByteBoolD_async(self, cb, p1, p2, current=None): + def opByteBoolD(self, p1, p2, current=None): p3 = p1.copy() r = p1.copy() r.update(p2) - cb.ice_response(r, p3) + return Ice.Future.completed((r, p3)) - def opShortIntD_async(self, cb, p1, p2, current=None): + def opShortIntD(self, p1, p2, current=None): p3 = p1.copy() r = p1.copy() r.update(p2) - cb.ice_response(r, p3) + return Ice.Future.completed((r, p3)) - def opLongFloatD_async(self, cb, p1, p2, current=None): + def opLongFloatD(self, p1, p2, current=None): p3 = p1.copy() r = p1.copy() r.update(p2) - cb.ice_response(r, p3) + return Ice.Future.completed((r, p3)) - def opStringStringD_async(self, cb, p1, p2, current=None): + def opStringStringD(self, p1, p2, current=None): p3 = p1.copy() r = p1.copy() r.update(p2) - cb.ice_response(r, p3) + return Ice.Future.completed((r, p3)) - def opStringMyEnumD_async(self, cb, p1, p2, current=None): + def opStringMyEnumD(self, p1, p2, current=None): p3 = p1.copy() r = p1.copy() r.update(p2) - cb.ice_response(r, p3) + return Ice.Future.completed((r, p3)) - def opMyEnumStringD_async(self, cb, p1, p2, current=None): + def opMyEnumStringD(self, p1, p2, current=None): p3 = p1.copy() r = p1.copy() r.update(p2) - cb.ice_response(r, p3) + return Ice.Future.completed((r, p3)) - def opMyStructMyEnumD_async(self, cb, p1, p2, current=None): + def opMyStructMyEnumD(self, p1, p2, current=None): p3 = p1.copy() r = p1.copy() r.update(p2) - cb.ice_response(r, p3) + return Ice.Future.completed((r, p3)) - def opByteBoolDS_async(self, cb, p1, p2, current=None): + def opByteBoolDS(self, p1, p2, current=None): p3 = p2[0:] p3.extend(p1) r = p1[::-1] - cb.ice_response(r, p3) + return Ice.Future.completed((r, p3)) - def opShortIntDS_async(self, cb, p1, p2, current=None): + def opShortIntDS(self, p1, p2, current=None): p3 = p2[0:] p3.extend(p1) r = p1[::-1] - cb.ice_response(r, p3) + return Ice.Future.completed((r, p3)) - def opLongFloatDS_async(self, cb, p1, p2, current=None): + def opLongFloatDS(self, p1, p2, current=None): p3 = p2[0:] p3.extend(p1) r = p1[::-1] - cb.ice_response(r, p3) + return Ice.Future.completed((r, p3)) - def opStringStringDS_async(self, cb, p1, p2, current=None): + def opStringStringDS(self, p1, p2, current=None): p3 = p2[0:] p3.extend(p1) r = p1[::-1] - cb.ice_response(r, p3) + return Ice.Future.completed((r, p3)) - def opStringMyEnumDS_async(self, cb, p1, p2, current=None): + def opStringMyEnumDS(self, p1, p2, current=None): p3 = p2[0:] p3.extend(p1) r = p1[::-1] - cb.ice_response(r, p3) + return Ice.Future.completed((r, p3)) - def opMyEnumStringDS_async(self, cb, p1, p2, current=None): + def opMyEnumStringDS(self, p1, p2, current=None): p3 = p2[0:] p3.extend(p1) r = p1[::-1] - cb.ice_response(r, p3) + return Ice.Future.completed((r, p3)) - def opMyStructMyEnumDS_async(self, cb, p1, p2, current=None): + def opMyStructMyEnumDS(self, p1, p2, current=None): p3 = p2[0:] p3.extend(p1) r = p1[::-1] - cb.ice_response(r, p3) + return Ice.Future.completed((r, p3)) - def opByteByteSD_async(self, cb, p1, p2, current=None): + def opByteByteSD(self, p1, p2, current=None): p3 = p2.copy() r = p1.copy() r.update(p2) - cb.ice_response(r, p3) + return Ice.Future.completed((r, p3)) - def opBoolBoolSD_async(self, cb, p1, p2, current=None): + def opBoolBoolSD(self, p1, p2, current=None): p3 = p2.copy() r = p1.copy() r.update(p2) - cb.ice_response(r, p3) + return Ice.Future.completed((r, p3)) - def opShortShortSD_async(self, cb, p1, p2, current=None): + def opShortShortSD(self, p1, p2, current=None): p3 = p2.copy() r = p1.copy() r.update(p2) - cb.ice_response(r, p3) + return Ice.Future.completed((r, p3)) - def opIntIntSD_async(self, cb, p1, p2, current=None): + def opIntIntSD(self, p1, p2, current=None): p3 = p2.copy() r = p1.copy() r.update(p2) - cb.ice_response(r, p3) + return Ice.Future.completed((r, p3)) - def opLongLongSD_async(self, cb, p1, p2, current=None): + def opLongLongSD(self, p1, p2, current=None): p3 = p2.copy() r = p1.copy() r.update(p2) - cb.ice_response(r, p3) + return Ice.Future.completed((r, p3)) - def opStringFloatSD_async(self, cb, p1, p2, current=None): + def opStringFloatSD(self, p1, p2, current=None): p3 = p2.copy() r = p1.copy() r.update(p2) - cb.ice_response(r, p3) + return Ice.Future.completed((r, p3)) - def opStringDoubleSD_async(self, cb, p1, p2, current=None): + def opStringDoubleSD(self, p1, p2, current=None): p3 = p2.copy() r = p1.copy() r.update(p2) - cb.ice_response(r, p3) + return Ice.Future.completed((r, p3)) - def opStringStringSD_async(self, cb, p1, p2, current=None): + def opStringStringSD(self, p1, p2, current=None): p3 = p2.copy() r = p1.copy() r.update(p2) - cb.ice_response(r, p3) + return Ice.Future.completed((r, p3)) - def opMyEnumMyEnumSD_async(self, cb, p1, p2, current=None): + def opMyEnumMyEnumSD(self, p1, p2, current=None): p3 = p2.copy() r = p1.copy() r.update(p2) - cb.ice_response(r, p3) + return Ice.Future.completed((r, p3)) - def opIntS_async(self, cb, s, current=None): - cb.ice_response([-x for x in s]) + def opIntS(self, s, current=None): + return Ice.Future.completed([-x for x in s]) - def opByteSOneway_async(self, cb, s, current=None): - self.lock.acquire() - self.opByteSOnewayCount += 1 - self.lock.release() - cb.ice_response() + def opByteSOneway(self, s, current=None): + with self.lock: + self.opByteSOnewayCount += 1 + return Ice.Future.completed(None) - def opByteSOnewayCallCount_async(self, cb, current=None): - self.lock.acquire() - count = self.opByteSOnewayCount - self.opByteSOnewayCount = 0 - self.lock.release() - cb.ice_response(count) + def opByteSOnewayCallCount(self, current=None): + with self.lock: + count = self.opByteSOnewayCount + self.opByteSOnewayCount = 0 + return Ice.Future.completed(count) - def opDoubleMarshaling_async(self, cb, p1, p2, current=None): + def opDoubleMarshaling(self, p1, p2, current=None): d = 1278312346.0 / 13.0; test(p1 == d) for i in p2: test(i == d) - cb.ice_response() + return Ice.Future.completed(None) - def opContext_async(self, cb, current=None): - cb.ice_response(current.ctx) + def opContext(self, current=None): + return Ice.Future.completed(current.ctx) - def opIdempotent_async(self, cb, current=None): + def opIdempotent(self, current=None): test(current.mode == Ice.OperationMode.Idempotent) - cb.ice_response() + return Ice.Future.completed(None) - def opNonmutating_async(self, cb, current=None): + def opNonmutating(self, current=None): test(current.mode == Ice.OperationMode.Nonmutating) - cb.ice_response() - - def opDerived_async(self, cb, current=None): - cb.ice_response() - - def opByte1_async(self, cb, value, current=None): - cb.ice_response(value) - - def opShort1_async(self, cb, value, current=None): - cb.ice_response(value) - - def opInt1_async(self, cb, value, current=None): - cb.ice_response(value) - - def opLong1_async(self, cb, value, current=None): - cb.ice_response(value) - - def opFloat1_async(self, cb, value, current=None): - cb.ice_response(value) - - def opDouble1_async(self, cb, value, current=None): - cb.ice_response(value) - - def opString1_async(self, cb, value, current=None): - cb.ice_response(value) - - def opStringS1_async(self, cb, value, current=None): - cb.ice_response(value) - - def opByteBoolD1_async(self, cb, value, current=None): - cb.ice_response(value) - - def opStringS2_async(self, cb, value, current=None): - cb.ice_response(value) - - def opByteBoolD2_async(self, cb, value, current=None): - cb.ice_response(value) - - def opMyClass1_async(self, cb, value, current=None): - return cb.ice_response(value) - - def opMyStruct1_async(self, cb, value, current=None): - return cb.ice_response(value) - - def opStringLiterals_async(self, cb, current=None): - return cb.ice_response([ + return Ice.Future.completed(None) + + def opDerived(self, current=None): + return Ice.Future.completed(None) + + def opByte1(self, value, current=None): + return Ice.Future.completed(value) + + def opShort1(self, value, current=None): + return Ice.Future.completed(value) + + def opInt1(self, value, current=None): + return Ice.Future.completed(value) + + def opLong1(self, value, current=None): + return Ice.Future.completed(value) + + def opFloat1(self, value, current=None): + return Ice.Future.completed(value) + + def opDouble1(self, value, current=None): + return Ice.Future.completed(value) + + def opString1(self, value, current=None): + return Ice.Future.completed(value) + + def opStringS1(self, value, current=None): + return Ice.Future.completed(value) + + def opByteBoolD1(self, value, current=None): + return Ice.Future.completed(value) + + def opStringS2(self, value, current=None): + return Ice.Future.completed(value) + + def opByteBoolD2(self, value, current=None): + return Ice.Future.completed(value) + + def opMyClass1(self, value, current=None): + return Ice.Future.completed(value) + + def opMyStruct1(self, value, current=None): + return Ice.Future.completed(value) + + def opStringLiterals(self, current=None): + return Ice.Future.completed([ Test.s0, Test.s1, Test.s2, Test.s3, Test.s4, Test.s5, Test.s6, Test.s7, Test.s8, Test.s9, Test.s10, - Test.sw0, Test.sw1, Test.sw2, Test.sw3, Test.sw4, Test.sw5, Test.sw6, Test.sw7, Test.sw8, Test.sw9, Test.sw10, + Test.sw0, Test.sw1, Test.sw2, Test.sw3, Test.sw4, Test.sw5, Test.sw6, Test.sw7, Test.sw8, Test.sw9, + Test.sw10, Test.ss0, Test.ss1, Test.ss2, Test.ss3, Test.ss4, Test.ss5, Test.su0, Test.su1, Test.su2]) - - def opWStringLiterals_async(self, cb, current=None): - return self.opStringLiterals_async(cb, current) + + def opWStringLiterals(self, current=None): + return self.opStringLiterals(current) + + def opMStruct1(self, current): + return Ice.Future.completed(Test.Structure()) + + def opMStruct2(self, p1, current): + return Ice.Future.completed((p1, p1)) + + def opMSeq1(self, current): + return Ice.Future.completed([]) + + def opMSeq2(self, p1, current): + return Ice.Future.completed((p1, p1)) + + def opMDict1(self, current): + return Ice.Future.completed({}) + + def opMDict2(self, p1, current): + return Ice.Future.completed((p1, p1)) def run(args, communicator): communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010:udp") adapter = communicator.createObjectAdapter("TestAdapter") - adapter.add(MyDerivedClassI(), communicator.stringToIdentity("test")) + adapter.add(MyDerivedClassI(), Ice.stringToIdentity("test")) adapter.activate() communicator.waitForShutdown() return True @@ -425,17 +455,10 @@ try: initData = Ice.InitializationData() initData.properties = Ice.createProperties(sys.argv) initData.properties.setProperty("Ice.Warn.Dispatch", "0"); - communicator = Ice.initialize(sys.argv, initData) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv, initData) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/operations/Test.ice b/python/test/Ice/operations/Test.ice index 82e7cba1dfc..dfb978df5d3 100644 --- a/python/test/Ice/operations/Test.ice +++ b/python/test/Ice/operations/Test.ice @@ -21,7 +21,7 @@ enum MyEnum enum3 }; -class MyClass; +interface MyClass; struct AnotherStruct { @@ -91,7 +91,7 @@ dictionary<string, DoubleS> StringDoubleSD; dictionary<string, StringS> StringStringSD; dictionary<MyEnum, MyEnumS> MyEnumMyEnumSD; -class MyClass +interface MyClass { void shutdown(); @@ -249,6 +249,15 @@ class MyClass StringS opStringLiterals(); StringS opWStringLiterals(); + + ["marshaled-result"] Structure opMStruct1(); + ["marshaled-result"] Structure opMStruct2(Structure p1, out Structure p2); + + ["marshaled-result"] StringS opMSeq1(); + ["marshaled-result"] StringS opMSeq2(StringS p1, out StringS p2); + + ["marshaled-result"] StringStringD opMDict1(); + ["marshaled-result"] StringStringD opMDict2(StringStringD p1, out StringStringD p2); }; struct MyStruct1 @@ -265,7 +274,7 @@ class MyClass1 string myClass1; // Same name as the enclosing class }; -class MyDerivedClass extends MyClass +interface MyDerivedClass extends MyClass { void opDerived(); MyClass1 opMyClass1(MyClass1 opMyClass1); @@ -314,9 +323,9 @@ const string sw10 = "\U00000DA7"; // Sinhala Letter Alpapraa \v vertical tab byte 0x0b in ASCII encoding **/ -const string ss0 = "\'\"\?\\\a\b\f\n\r\t\v"; -const string ss1 = "\u0027\u0022\u003f\u005c\u0007\u0008\u000c\u000a\u000d\u0009\u000b"; -const string ss2 = "\U00000027\U00000022\U0000003f\U0000005c\U00000007\U00000008\U0000000c\U0000000a\U0000000d\U00000009\U0000000b"; +const string ss0 = "\'\"\?\\\a\b\f\n\r\t\v\6"; +const string ss1 = "\u0027\u0022\u003f\u005c\u0007\u0008\u000c\u000a\u000d\u0009\u000b\u0006"; +const string ss2 = "\U00000027\U00000022\U0000003f\U0000005c\U00000007\U00000008\U0000000c\U0000000a\U0000000d\U00000009\U0000000b\U00000006"; const string ss3 = "\\\\U\\u\\"; /* \\U\u\ */ const string ss4 = "\\\u0041\\"; /* \A\ */ diff --git a/python/test/Ice/operations/TestAMD.ice b/python/test/Ice/operations/TestAMD.ice index 6be5c0d6f5d..078fd362409 100644 --- a/python/test/Ice/operations/TestAMD.ice +++ b/python/test/Ice/operations/TestAMD.ice @@ -19,7 +19,7 @@ enum MyEnum enum3 }; -class MyClass; +interface MyClass; struct AnotherStruct { @@ -89,7 +89,7 @@ dictionary<string, DoubleS> StringDoubleSD; dictionary<string, StringS> StringStringSD; dictionary<MyEnum, MyEnumS> MyEnumMyEnumSD; -["amd"] class MyClass +["amd"] interface MyClass { void shutdown(); @@ -247,6 +247,15 @@ dictionary<MyEnum, MyEnumS> MyEnumMyEnumSD; StringS opStringLiterals(); StringS opWStringLiterals(); + + ["marshaled-result"] Structure opMStruct1(); + ["marshaled-result"] Structure opMStruct2(Structure p1, out Structure p2); + + ["marshaled-result"] StringS opMSeq1(); + ["marshaled-result"] StringS opMSeq2(StringS p1, out StringS p2); + + ["marshaled-result"] StringStringD opMDict1(); + ["marshaled-result"] StringStringD opMDict2(StringStringD p1, out StringStringD p2); }; struct MyStruct1 @@ -263,7 +272,7 @@ class MyClass1 string myClass1; // Same name as the enclosing class }; -["amd"] class MyDerivedClass extends MyClass +["amd"] interface MyDerivedClass extends MyClass { void opDerived(); MyClass1 opMyClass1(MyClass1 opMyClass1); @@ -312,9 +321,9 @@ const string sw10 = "\U00000DA7"; // Sinhala Letter Alpapraa \v vertical tab byte 0x0b in ASCII encoding **/ -const string ss0 = "\'\"\?\\\a\b\f\n\r\t\v"; -const string ss1 = "\u0027\u0022\u003f\u005c\u0007\u0008\u000c\u000a\u000d\u0009\u000b"; -const string ss2 = "\U00000027\U00000022\U0000003f\U0000005c\U00000007\U00000008\U0000000c\U0000000a\U0000000d\U00000009\U0000000b"; +const string ss0 = "\'\"\?\\\a\b\f\n\r\t\v\6"; +const string ss1 = "\u0027\u0022\u003f\u005c\u0007\u0008\u000c\u000a\u000d\u0009\u000b\u0006"; +const string ss2 = "\U00000027\U00000022\U0000003f\U0000005c\U00000007\U00000008\U0000000c\U0000000a\U0000000d\U00000009\U0000000b\U00000006"; const string ss3 = "\\\\U\\u\\"; /* \\U\u\ */ const string ss4 = "\\\u0041\\"; /* \A\ */ diff --git a/python/test/Ice/operations/TestI.py b/python/test/Ice/operations/TestI.py index 789add7eb15..0a3b39966ff 100644 --- a/python/test/Ice/operations/TestI.py +++ b/python/test/Ice/operations/TestI.py @@ -13,26 +13,26 @@ def test(b): if not b: raise RuntimeError('test assertion failed') -class MyDerivedClassI(Test.MyDerivedClass): +class MyDerivedClassI(Test._MyDerivedClassDisp): def __init__(self): self.lock = threading.Lock() self.opByteSOnewayCount = 0 def ice_isA(self, id, current=None): test(current.mode == Ice.OperationMode.Nonmutating) - return Test.MyDerivedClass.ice_isA(self, id, current) + return Test._MyDerivedClassDisp.ice_isA(self, id, current) def ice_ping(self, current=None): test(current.mode == Ice.OperationMode.Nonmutating) - Test.MyDerivedClass.ice_ping(self, current) + Test._MyDerivedClassDisp.ice_ping(self, current) def ice_ids(self, current=None): test(current.mode == Ice.OperationMode.Nonmutating) - return Test.MyDerivedClass.ice_ids(self, current) + return Test._MyDerivedClassDisp.ice_ids(self, current) def ice_id(self, current=None): test(current.mode == Ice.OperationMode.Nonmutating) - return Test.MyDerivedClass.ice_id(self, current) + return Test._MyDerivedClassDisp.ice_id(self, current) def shutdown(self, current=None): current.adapter.getCommunicator().shutdown() @@ -60,7 +60,7 @@ class MyDerivedClassI(Test.MyDerivedClass): def opMyClass(self, p1, current=None): return (Test.MyClassPrx.uncheckedCast(current.adapter.createProxy(current.id)), p1, - Test.MyClassPrx.uncheckedCast(current.adapter.createProxy(current.adapter.getCommunicator().stringToIdentity("noSuchIdentity")))) + Test.MyClassPrx.uncheckedCast(current.adapter.createProxy(Ice.stringToIdentity("noSuchIdentity")))) def opStruct(self, p1, p2, current=None): p1.s.s = "a new string" @@ -294,15 +294,13 @@ class MyDerivedClassI(Test.MyDerivedClass): return [-x for x in s] def opByteSOneway(self, s, current=None): - self.lock.acquire() - self.opByteSOnewayCount += 1 - self.lock.release() + with self.lock: + self.opByteSOnewayCount += 1 def opByteSOnewayCallCount(self, current=None): - self.lock.acquire() - count = self.opByteSOnewayCount - self.opByteSOnewayCount = 0 - self.lock.release() + with self.lock: + count = self.opByteSOnewayCount + self.opByteSOnewayCount = 0 return count def opContext(self, current=None): @@ -328,47 +326,63 @@ class MyDerivedClassI(Test.MyDerivedClass): def opShort1(self, value, current=None): return value - + def opInt1(self, value, current=None): return value - + def opLong1(self, value, current=None): return value - + def opFloat1(self, value, current=None): return value - + def opDouble1(self, value, current=None): return value - + def opString1(self, value, current=None): return value - + def opStringS1(self, value, current=None): return value - + def opByteBoolD1(self, value, current=None): return value - + def opStringS2(self, value, current=None): return value - + def opByteBoolD2(self, value, current=None): return value - + def opMyClass1(self, value, current=None): return value def opMyStruct1(self, value, current=None): return value - + def opStringLiterals(self, current=None): return [Test.s0, Test.s1, Test.s2, Test.s3, Test.s4, Test.s5, Test.s6, Test.s7, Test.s8, Test.s9, Test.s10, Test.sw0, Test.sw1, Test.sw2, Test.sw3, Test.sw4, Test.sw5, Test.sw6, Test.sw7, Test.sw8, Test.sw9, Test.sw10, Test.ss0, Test.ss1, Test.ss2, Test.ss3, Test.ss4, Test.ss5, Test.su0, Test.su1, Test.su2] - + def opWStringLiterals(self, current=None): return self.opStringLiterals(current) -
\ No newline at end of file + def opMStruct1(self, current): + return Test.Structure(); + + def opMStruct2(self, p1, current): + return (p1, p1); + + def opMSeq1(self, current): + return () + + def opMSeq2(self, p1, current): + return (p1, p1); + + def opMDict1(self, current): + return {}; + + def opMDict2(self, p1, current): + return (p1, p1); diff --git a/python/test/Ice/operations/Twoways.py b/python/test/Ice/operations/Twoways.py index ebaa50ae011..1e473884823 100644 --- a/python/test/Ice/operations/Twoways.py +++ b/python/test/Ice/operations/Twoways.py @@ -15,9 +15,9 @@ def test(b): raise RuntimeError('test assertion failed') def twoways(communicator, p): - + literals = p.opStringLiterals(); - + test(Test.s0 == "\\") test(Test.s0 == Test.sw0) test(Test.s0 == literals[0]) @@ -32,7 +32,7 @@ def twoways(communicator, p): test(Test.s2 == Test.sw2) test(Test.s2 == literals[2]) test(Test.s2 == literals[13]) - + test(Test.s3 == "A21") test(Test.s3 == Test.sw3) test(Test.s3 == literals[3]) @@ -62,7 +62,7 @@ def twoways(communicator, p): test(Test.s8 == Test.sw8) test(Test.s8 == literals[8]) test(Test.s8 == literals[19]) - + test(Test.s9 == "\xf0\x9f\x8d\x8c" if version_info[0] < 3 else b"\xf0\x9f\x8d\x8c".decode("utf-8")) test(Test.s9 == Test.sw9) test(Test.s9 == literals[9]) @@ -73,13 +73,13 @@ def twoways(communicator, p): test(Test.s10 == literals[10]) test(Test.s10 == literals[21]) - test(Test.ss0 == "\'\"\x3f\\\a\b\f\n\r\t\v") + test(Test.ss0 == "\'\"\x3f\\\a\b\f\n\r\t\v\x06") test(Test.ss0 == Test.ss1) test(Test.ss0 == Test.ss2) test(Test.ss0 == literals[22]) test(Test.ss0 == literals[23]) test(Test.ss0 == literals[24]) - + test(Test.ss3 == "\\\\U\\u\\") test(Test.ss3 == literals[25]) @@ -103,7 +103,7 @@ def twoways(communicator, p): # # ice_isA # - test(p.ice_isA(Test.MyClass.ice_staticId())) + test(p.ice_isA(Test._MyClassDisp.ice_staticId())) # # ice_ids @@ -117,13 +117,13 @@ def twoways(communicator, p): # # ice_id # - test(p.ice_id() == Test.MyDerivedClass.ice_staticId()) + test(p.ice_id() == Test._MyDerivedClassDisp.ice_staticId()) # # Prx ice_staticId # - test(Test.MyClassPrx.ice_staticId() == Test.MyClass.ice_staticId()) - test(Test.MyDerivedClassPrx.ice_staticId() == Test.MyDerivedClass.ice_staticId()) + test(Test.MyClassPrx.ice_staticId() == Test._MyClassDisp.ice_staticId()) + test(Test.MyDerivedClassPrx.ice_staticId() == Test._MyDerivedClassDisp.ice_staticId()) test(Ice.ObjectPrx.ice_staticId() == Ice.Object.ice_staticId()) # @@ -266,9 +266,9 @@ def twoways(communicator, p): test(Ice.proxyIdentityAndFacetEqual(c1, p)) test(not Ice.proxyIdentityAndFacetEqual(c2, p)) test(Ice.proxyIdentityAndFacetEqual(r, p)) - test(c1.ice_getIdentity() == communicator.stringToIdentity("test")) - test(c2.ice_getIdentity() == communicator.stringToIdentity("noSuchIdentity")) - test(r.ice_getIdentity() == communicator.stringToIdentity("test")) + test(c1.ice_getIdentity() == Ice.stringToIdentity("test")) + test(c2.ice_getIdentity() == Ice.stringToIdentity("noSuchIdentity")) + test(r.ice_getIdentity() == Ice.stringToIdentity("test")) r.opVoid() c1.opVoid() try: @@ -1420,3 +1420,19 @@ def twoways(communicator, p): test(c.tesT == "Test.MyClass1.testT") test(c.myClass == None) test(c.myClass1 == "Test.MyClass1.myClass1") + + p1 = p.opMStruct1() + p1.e = Test.MyEnum.enum3 + (p3, p2) = p.opMStruct2(p1) + test(p2 == p1 and p3 == p1) + + p.opMSeq1(); + p1 = ["test"] + (p3, p2) = p.opMSeq2(p1) + test(p2[0] == "test" and p3[0] == "test"); + + p.opMDict1(); + + p1 = { "test": "test" } + (p3, p2) = p.opMDict2(p1) + test(p3["test"] == "test" and p2["test"] == "test") diff --git a/python/test/Ice/operations/TwowaysAMI.py b/python/test/Ice/operations/TwowaysAMI.py index c8aee9df604..5f7cc1445c0 100644 --- a/python/test/Ice/operations/TwowaysAMI.py +++ b/python/test/Ice/operations/TwowaysAMI.py @@ -19,19 +19,15 @@ class CallbackBase: self._cond = threading.Condition() def check(self): - self._cond.acquire() - try: + with self._cond: while not self._called: self._cond.wait() self._called = False - finally: - self._cond.release() def called(self): - self._cond.acquire() - self._called = True - self._cond.notify() - self._cond.release() + with self._cond: + self._called = True + self._cond.notify() class Callback(CallbackBase): def __init__(self, communicator=None): @@ -90,9 +86,9 @@ class Callback(CallbackBase): self.called() def opMyClass(self, r, c1, c2): - test(c1.ice_getIdentity() == self._communicator.stringToIdentity("test")) - test(c2.ice_getIdentity() == self._communicator.stringToIdentity("noSuchIdentity")) - test(r.ice_getIdentity() == self._communicator.stringToIdentity("test")) + test(c1.ice_getIdentity() == Ice.stringToIdentity("test")) + test(c2.ice_getIdentity() == Ice.stringToIdentity("noSuchIdentity")) + test(r.ice_getIdentity() == Ice.stringToIdentity("test")) # We can't do the callbacks below in serialize mode if self._communicator.getProperties().getPropertyAsInt("Ice.Client.ThreadPool.Serialize") == 0: r.opVoid() @@ -761,7 +757,7 @@ def twowaysAMI(communicator, p): cb.check() cb = Callback() - p.begin_ice_isA(Test.MyClass.ice_staticId(), cb.isA, cb.exCB) + p.begin_ice_isA(Test._MyClassDisp.ice_staticId(), cb.isA, cb.exCB) cb.check() cb = Callback() @@ -1105,7 +1101,7 @@ def twowaysAMI(communicator, p): test(c != ctx) test(len(p.ice_getContext()) == 0) - r = p.begin_opContext(_ctx=ctx) + r = p.begin_opContext(context=ctx) c = p.end_opContext(r) test(c == ctx) @@ -1115,7 +1111,7 @@ def twowaysAMI(communicator, p): c = p2.end_opContext(r) test(c == ctx) - r = p2.begin_opContext(_ctx=ctx) + r = p2.begin_opContext(context=ctx) c = p2.end_opContext(r) test(c == ctx) diff --git a/python/test/Ice/operations/TwowaysFuture.py b/python/test/Ice/operations/TwowaysFuture.py new file mode 100644 index 00000000000..19b0bdaab6c --- /dev/null +++ b/python/test/Ice/operations/TwowaysFuture.py @@ -0,0 +1,1354 @@ +# ********************************************************************** +# +# Copyright (c) 2003-2016 ZeroC, Inc. All rights reserved. +# +# This copy of Ice is licensed to you under the terms described in the +# ICE_LICENSE file included in this distribution. +# +# ********************************************************************** + +import Ice, Test, math, sys, threading + +def test(b): + if not b: + raise RuntimeError('test assertion failed') + +class CallbackBase: + def __init__(self): + self._called = False + self._cond = threading.Condition() + + def check(self): + with self._cond: + while not self._called: + self._cond.wait() + self._called = False + + def called(self): + with self._cond: + self._called = True + self._cond.notify() + +class Callback(CallbackBase): + def __init__(self, communicator=None): + CallbackBase.__init__(self) + self._communicator = communicator + + def opByte(self, f): + try: + (r, b) = f.result() + test(b == 0xf0) + test(r == 0xff) + self.called() + except: + test(False) + + def opBool(self, f): + try: + (r, b) = f.result() + test(b) + test(not r) + self.called() + except: + test(False) + + def opShortIntLong(self, f): + try: + (r, s, i, l) = f.result() + test(s == 10) + test(i == 11) + test(l == 12) + test(r == 12) + self.called() + except: + test(False) + + def opFloatDouble(self, fut): + try: + (r, f, d) = fut.result() + test(f - 3.14 < 0.001) + test(d == 1.1E10) + test(r == 1.1E10) + self.called() + except: + test(False) + + def opString(self, f): + try: + (r, s) = f.result() + test(s == "world hello") + test(r == "hello world") + self.called() + except: + test(False) + + def opMyEnum(self, f): + try: + (r, e) = f.result() + test(e == Test.MyEnum.enum2) + test(r == Test.MyEnum.enum3) + self.called() + except: + test(False) + + def opMyClass(self, f): + try: + (r, c1, c2) = f.result() + test(c1.ice_getIdentity() == Ice.stringToIdentity("test")) + test(c2.ice_getIdentity() == Ice.stringToIdentity("noSuchIdentity")) + test(r.ice_getIdentity() == Ice.stringToIdentity("test")) + # We can't do the callbacks below in serialize mode + if self._communicator.getProperties().getPropertyAsInt("Ice.Client.ThreadPool.Serialize") == 0: + r.opVoid() + c1.opVoid() + try: + c2.opVoid() + test(False) + except Ice.ObjectNotExistException: + pass + self.called() + except: + test(False) + + def opStruct(self, f): + try: + (rso, so) = f.result() + test(rso.p == None) + test(rso.e == Test.MyEnum.enum2) + test(rso.s.s == "def") + test(so.e == Test.MyEnum.enum3) + test(so.s.s == "a new string") + # We can't do the callbacks below in serialize mode. + if self._communicator.getProperties().getPropertyAsInt("Ice.ThreadPool.Client.Serialize") == 0: + so.p.opVoid() + self.called() + except: + test(False) + + def opByteS(self, f): + try: + (rso, bso) = f.result() + test(len(bso) == 4) + test(len(rso) == 8) + if sys.version_info[0] == 2: + test(bso[0] == '\x22') + test(bso[1] == '\x12') + test(bso[2] == '\x11') + test(bso[3] == '\x01') + test(rso[0] == '\x01') + test(rso[1] == '\x11') + test(rso[2] == '\x12') + test(rso[3] == '\x22') + test(rso[4] == '\xf1') + test(rso[5] == '\xf2') + test(rso[6] == '\xf3') + test(rso[7] == '\xf4') + else: + test(bso[0] == 0x22) + test(bso[1] == 0x12) + test(bso[2] == 0x11) + test(bso[3] == 0x01) + test(rso[0] == 0x01) + test(rso[1] == 0x11) + test(rso[2] == 0x12) + test(rso[3] == 0x22) + test(rso[4] == 0xf1) + test(rso[5] == 0xf2) + test(rso[6] == 0xf3) + test(rso[7] == 0xf4) + self.called() + except: + test(False) + + def opBoolS(self, f): + try: + (rso, bso) = f.result() + test(len(bso) == 4) + test(bso[0]) + test(bso[1]) + test(not bso[2]) + test(not bso[3]) + test(len(rso) == 3) + test(not rso[0]) + test(rso[1]) + test(rso[2]) + self.called() + except: + test(False) + + def opShortIntLongS(self, f): + try: + (rso, sso, iso, lso) = f.result() + test(len(sso) == 3) + test(sso[0] == 1) + test(sso[1] == 2) + test(sso[2] == 3) + test(len(iso) == 4) + test(iso[0] == 8) + test(iso[1] == 7) + test(iso[2] == 6) + test(iso[3] == 5) + test(len(lso) == 6) + test(lso[0] == 10) + test(lso[1] == 30) + test(lso[2] == 20) + test(lso[3] == 10) + test(lso[4] == 30) + test(lso[5] == 20) + test(len(rso) == 3) + test(rso[0] == 10) + test(rso[1] == 30) + test(rso[2] == 20) + self.called() + except: + test(False) + + def opFloatDoubleS(self, f): + try: + (rso, fso, dso) = f.result() + test(len(fso) == 2) + test(fso[0] - 3.14 < 0.001) + test(fso[1] - 1.11 < 0.001) + test(len(dso) == 3) + test(dso[0] == 1.3E10) + test(dso[1] == 1.2E10) + test(dso[2] == 1.1E10) + test(len(rso) == 5) + test(rso[0] == 1.1E10) + test(rso[1] == 1.2E10) + test(rso[2] == 1.3E10) + test(rso[3] - 3.14 < 0.001) + test(rso[4] - 1.11 < 0.001) + self.called() + except: + test(False) + + def opStringS(self, f): + try: + (rso, sso) = f.result() + test(len(sso) == 4) + test(sso[0] == "abc") + test(sso[1] == "de") + test(sso[2] == "fghi") + test(sso[3] == "xyz") + test(len(rso) == 3) + test(rso[0] == "fghi") + test(rso[1] == "de") + test(rso[2] == "abc") + self.called() + except: + test(False) + + def opByteSS(self, f): + try: + (rso, bso) = f.result() + test(len(bso) == 2) + test(len(bso[0]) == 1) + test(len(bso[1]) == 3) + test(len(rso) == 4) + test(len(rso[0]) == 3) + test(len(rso[1]) == 1) + test(len(rso[2]) == 1) + test(len(rso[3]) == 2) + if sys.version_info[0] == 2: + test(bso[0][0] == '\xff') + test(bso[1][0] == '\x01') + test(bso[1][1] == '\x11') + test(bso[1][2] == '\x12') + test(rso[0][0] == '\x01') + test(rso[0][1] == '\x11') + test(rso[0][2] == '\x12') + test(rso[1][0] == '\xff') + test(rso[2][0] == '\x0e') + test(rso[3][0] == '\xf2') + test(rso[3][1] == '\xf1') + else: + test(bso[0][0] == 0xff) + test(bso[1][0] == 0x01) + test(bso[1][1] == 0x11) + test(bso[1][2] == 0x12) + test(rso[0][0] == 0x01) + test(rso[0][1] == 0x11) + test(rso[0][2] == 0x12) + test(rso[1][0] == 0xff) + test(rso[2][0] == 0x0e) + test(rso[3][0] == 0xf2) + test(rso[3][1] == 0xf1) + self.called() + except: + test(False) + + def opBoolSS(self, f): + try: + (rso, bso) = f.result() + test(len(bso) == 4); + test(len(bso[0]) == 1); + test(bso[0][0]); + test(len(bso[1]) == 1); + test(not bso[1][0]); + test(len(bso[2]) == 2); + test(bso[2][0]); + test(bso[2][1]); + test(len(bso[3]) == 3); + test(not bso[3][0]); + test(not bso[3][1]); + test(bso[3][2]); + test(len(rso) == 3); + test(len(rso[0]) == 2); + test(rso[0][0]); + test(rso[0][1]); + test(len(rso[1]) == 1); + test(not rso[1][0]); + test(len(rso[2]) == 1); + test(rso[2][0]); + self.called(); + except: + test(False) + + def opShortIntLongSS(self, f): + try: + (rso, sso, iso, lso) = f.result() + test(len(rso) == 1); + test(len(rso[0]) == 2); + test(rso[0][0] == 496); + test(rso[0][1] == 1729); + test(len(sso) == 3); + test(len(sso[0]) == 3); + test(sso[0][0] == 1); + test(sso[0][1] == 2); + test(sso[0][2] == 5); + test(len(sso[1]) == 1); + test(sso[1][0] == 13); + test(len(sso[2]) == 0); + test(len(iso) == 2); + test(len(iso[0]) == 1); + test(iso[0][0] == 42); + test(len(iso[1]) == 2); + test(iso[1][0] == 24); + test(iso[1][1] == 98); + test(len(lso) == 2); + test(len(lso[0]) == 2); + test(lso[0][0] == 496); + test(lso[0][1] == 1729); + test(len(lso[1]) == 2); + test(lso[1][0] == 496); + test(lso[1][1] == 1729); + self.called(); + except: + test(False) + + def opFloatDoubleSS(self, f): + try: + (rso, fso, dso) = f.result() + test(len(fso) == 3) + test(len(fso[0]) == 1) + test(fso[0][0] - 3.14 < 0.001) + test(len(fso[1]) == 1) + test(fso[1][0] - 1.11 < 0.001) + test(len(fso[2]) == 0) + test(len(dso) == 1) + test(len(dso[0]) == 3) + test(dso[0][0] == 1.1E10) + test(dso[0][1] == 1.2E10) + test(dso[0][2] == 1.3E10) + test(len(rso) == 2) + test(len(rso[0]) == 3) + test(rso[0][0] == 1.1E10) + test(rso[0][1] == 1.2E10) + test(rso[0][2] == 1.3E10) + test(len(rso[1]) == 3) + test(rso[1][0] == 1.1E10) + test(rso[1][1] == 1.2E10) + test(rso[1][2] == 1.3E10) + self.called() + except: + test(False) + + def opStringSS(self, f): + try: + (rso, sso) = f.result() + test(len(sso) == 5) + test(len(sso[0]) == 1) + test(sso[0][0] == "abc") + test(len(sso[1]) == 2) + test(sso[1][0] == "de") + test(sso[1][1] == "fghi") + test(len(sso[2]) == 0) + test(len(sso[3]) == 0) + test(len(sso[4]) == 1) + test(sso[4][0] == "xyz") + test(len(rso) == 3) + test(len(rso[0]) == 1) + test(rso[0][0] == "xyz") + test(len(rso[1]) == 0) + test(len(rso[2]) == 0) + self.called() + except: + test(False) + + def opByteBoolD(self, f): + try: + (ro, do) = f.result() + di1 = {10: True, 100: False} + test(do == di1) + test(len(ro) == 4) + test(ro[10]) + test(not ro[11]) + test(not ro[100]) + test(ro[101]) + self.called() + except: + test(False) + + def opShortIntD(self, f): + try: + (ro, do) = f.result() + di1 = {110: -1, 1100: 123123} + test(do == di1) + test(len(ro) == 4) + test(ro[110] == -1) + test(ro[111] == -100) + test(ro[1100] == 123123) + test(ro[1101] == 0) + self.called() + except: + test(False) + + def opLongFloatD(self, f): + try: + (ro, do) = f.result() + di1 = {999999110: -1.1, 999999111: 123123.2} + for k in do: + test(math.fabs(do[k] - di1[k]) < 0.01) + test(len(ro) == 4) + test(ro[999999110] - -1.1 < 0.01) + test(ro[999999120] - -100.4 < 0.01) + test(ro[999999111] - 123123.2 < 0.01) + test(ro[999999130] - 0.5 < 0.01) + self.called() + except: + test(False) + + def opStringStringD(self, f): + try: + (ro, do) = f.result() + di1 = {'foo': 'abc -1.1', 'bar': 'abc 123123.2'} + test(do == di1) + test(len(ro) == 4) + test(ro["foo"] == "abc -1.1") + test(ro["FOO"] == "abc -100.4") + test(ro["bar"] == "abc 123123.2") + test(ro["BAR"] == "abc 0.5") + self.called() + except: + test(False) + + def opStringMyEnumD(self, f): + try: + (ro, do) = f.result() + di1 = {'abc': Test.MyEnum.enum1, '': Test.MyEnum.enum2} + test(do == di1) + test(len(ro) == 4) + test(ro["abc"] == Test.MyEnum.enum1) + test(ro["qwerty"] == Test.MyEnum.enum3) + test(ro[""] == Test.MyEnum.enum2) + test(ro["Hello!!"] == Test.MyEnum.enum2) + self.called() + except: + test(False) + + def opMyEnumStringD(self, f): + try: + (ro, do) = f.result() + di1 = {Test.MyEnum.enum1: 'abc'} + test(do == di1) + test(len(ro) == 3) + test(ro[Test.MyEnum.enum1] == "abc") + test(ro[Test.MyEnum.enum2] == "Hello!!") + test(ro[Test.MyEnum.enum3] == "qwerty") + self.called() + except: + test(False) + + def opMyStructMyEnumD(self, f): + try: + (ro, do) = f.result() + s11 = Test.MyStruct() + s11.i = 1 + s11.j = 1 + s12 = Test.MyStruct() + s12.i = 1 + s12.j = 2 + s22 = Test.MyStruct() + s22.i = 2 + s22.j = 2 + s23 = Test.MyStruct() + s23.i = 2 + s23.j = 3 + di1 = {s11: Test.MyEnum.enum1, s12: Test.MyEnum.enum2} + test(do == di1) + test(len(ro) == 4) + test(ro[s11] == Test.MyEnum.enum1) + test(ro[s12] == Test.MyEnum.enum2) + test(ro[s22] == Test.MyEnum.enum3) + test(ro[s23] == Test.MyEnum.enum2) + self.called() + except: + test(False) + + def opByteBoolDS(self, f): + try: + (ro, do) = f.result() + test(len(ro) == 2) + test(len(ro[0]) == 3) + test(ro[0][10]) + test(not ro[0][11]) + test(ro[0][101]) + test(len(ro[1]) == 2) + test(ro[1][10]) + test(not ro[1][100]) + test(len(do) == 3) + test(len(do[0]) == 2) + test(not do[0][100]) + test(not do[0][101]) + test(len(do[1]) == 2) + test(do[1][10]) + test(not do[1][100]) + test(len(do[2]) == 3) + test(do[2][10]) + test(not do[2][11]) + test(do[2][101]) + self.called() + except: + test(False) + + def opShortIntDS(self, f): + try: + (ro, do) = f.result() + test(len(ro) == 2) + test(len(ro[0]) == 3) + test(ro[0][110] == -1) + test(ro[0][111] == -100) + test(ro[0][1101] == 0) + test(len(ro[1]) == 2) + test(ro[1][110] == -1) + test(ro[1][1100] == 123123) + test(len(do) == 3) + test(len(do[0]) == 1) + test(do[0][100] == -1001) + test(len(do[1]) == 2) + test(do[1][110] == -1) + test(do[1][1100] == 123123) + test(len(do[2]) == 3) + test(do[2][110] == -1) + test(do[2][111] == -100) + test(do[2][1101] == 0) + self.called() + except: + test(False) + + def opLongFloatDS(self, f): + try: + (ro, do) = f.result() + test(len(ro) == 2) + test(len(ro[0]) == 3) + test(ro[0][999999110] - -1.1 < 0.01) + test(ro[0][999999120] - -100.4 < 0.01) + test(ro[0][999999130] - 0.5 < 0.01) + test(len(ro[1]) == 2) + test(ro[1][999999110] - -1.1 < 0.01) + test(ro[1][999999111] - 123123.2 < 0.01) + test(len(do) == 3) + test(len(do[0]) == 1) + test(do[0][999999140] - 3.14 < 0.01) + test(len(do[1]) == 2) + test(do[1][999999110] - -1.1 < 0.01) + test(do[1][999999111] - 123123.2 < 0.01) + test(len(do[2]) == 3) + test(do[2][999999110] - -1.1 < 0.01) + test(do[2][999999120] - -100.4 < 0.01) + test(do[2][999999130] - 0.5 < 0.01) + self.called() + except: + test(False) + + def opStringStringDS(self, f): + try: + (ro, do) = f.result() + test(len(ro) == 2) + test(len(ro[0]) == 3) + test(ro[0]["foo"] == "abc -1.1") + test(ro[0]["FOO"] == "abc -100.4") + test(ro[0]["BAR"] == "abc 0.5") + test(len(ro[1]) == 2) + test(ro[1]["foo"] == "abc -1.1") + test(ro[1]["bar"] == "abc 123123.2") + test(len(do) == 3) + test(len(do[0]) == 1) + test(do[0]["f00"] == "ABC -3.14") + test(len(do[1]) == 2) + test(do[1]["foo"] == "abc -1.1") + test(do[1]["bar"] == "abc 123123.2") + test(len(do[2]) == 3) + test(do[2]["foo"] == "abc -1.1") + test(do[2]["FOO"] == "abc -100.4") + test(do[2]["BAR"] == "abc 0.5") + self.called() + except: + test(False) + + def opStringMyEnumDS(self, f): + try: + (ro, do) = f.result() + test(len(ro) == 2) + test(len(ro[0]) == 3) + test(ro[0]["abc"] == Test.MyEnum.enum1) + test(ro[0]["qwerty"] == Test.MyEnum.enum3) + test(ro[0]["Hello!!"] == Test.MyEnum.enum2) + test(len(ro[1]) == 2) + test(ro[1]["abc"] == Test.MyEnum.enum1) + test(ro[1][""] == Test.MyEnum.enum2) + test(len(do) == 3) + test(len(do[0]) == 1) + test(do[0]["Goodbye"] == Test.MyEnum.enum1) + test(len(do[1]) == 2) + test(do[1]["abc"] == Test.MyEnum.enum1) + test(do[1][""] == Test.MyEnum.enum2) + test(len(do[2]) == 3) + test(do[2]["abc"] == Test.MyEnum.enum1) + test(do[2]["qwerty"] == Test.MyEnum.enum3) + test(do[2]["Hello!!"] == Test.MyEnum.enum2) + self.called() + except: + test(False) + + def opMyEnumStringDS(self, f): + try: + (ro, do) = f.result() + test(len(ro) == 2) + test(len(ro[0]) == 2) + test(ro[0][Test.MyEnum.enum2] == "Hello!!") + test(ro[0][Test.MyEnum.enum3] == "qwerty") + test(len(ro[1]) == 1) + test(ro[1][Test.MyEnum.enum1] == "abc") + test(len(do) == 3) + test(len(do[0]) == 1) + test(do[0][Test.MyEnum.enum1] == "Goodbye") + test(len(do[1]) == 1) + test(do[1][Test.MyEnum.enum1] == "abc") + test(len(do[2]) == 2) + test(do[2][Test.MyEnum.enum2] == "Hello!!") + test(do[2][Test.MyEnum.enum3] == "qwerty") + self.called() + except: + test(False) + + def opMyStructMyEnumDS(self, f): + try: + (ro, do) = f.result() + s11 = Test.MyStruct(1, 1) + s12 = Test.MyStruct(1, 2) + s22 = Test.MyStruct(2, 2) + s23 = Test.MyStruct(2, 3) + test(len(ro) == 2) + test(len(ro[0]) == 3) + test(ro[0][s11] == Test.MyEnum.enum1) + test(ro[0][s22] == Test.MyEnum.enum3) + test(ro[0][s23] == Test.MyEnum.enum2) + test(len(ro[1]) == 2) + test(ro[1][s11] == Test.MyEnum.enum1) + test(ro[1][s12] == Test.MyEnum.enum2) + test(len(do) == 3) + test(len(do[0]) == 1) + test(do[0][s23] == Test.MyEnum.enum3) + test(len(do[1]) == 2) + test(do[1][s11] == Test.MyEnum.enum1) + test(do[1][s12] == Test.MyEnum.enum2) + test(len(do[2]) == 3) + test(do[2][s11] == Test.MyEnum.enum1) + test(do[2][s22] == Test.MyEnum.enum3) + test(do[2][s23] == Test.MyEnum.enum2) + self.called() + except: + test(False) + + def opByteByteSD(self, f): + try: + (ro, do) = f.result() + if sys.version_info[0] == 2: + test(len(do) == 1) + test(len(do[0xf1]) == 2) + test(do[0xf1][0] == '\xf2') + test(do[0xf1][1] == '\xf3') + test(len(ro) == 3) + test(len(ro[0x01]) == 2) + test(ro[0x01][0] == '\x01') + test(ro[0x01][1] == '\x11') + test(len(ro[0x22]) == 1) + test(ro[0x22][0] == '\x12') + test(len(ro[0xf1]) == 2) + test(ro[0xf1][0] == '\xf2') + test(ro[0xf1][1] == '\xf3') + else: + test(len(do) == 1) + test(len(do[0xf1]) == 2) + test(do[0xf1][0] == 0xf2) + test(do[0xf1][1] == 0xf3) + test(len(ro) == 3) + test(len(ro[0x01]) == 2) + test(ro[0x01][0] == 0x01) + test(ro[0x01][1] == 0x11) + test(len(ro[0x22]) == 1) + test(ro[0x22][0] == 0x12) + test(len(ro[0xf1]) == 2) + test(ro[0xf1][0] == 0xf2) + test(ro[0xf1][1] == 0xf3) + self.called() + except: + test(False) + + def opBoolBoolSD(self, f): + try: + (ro, do) = f.result() + test(len(do) == 1) + test(len(do[False]) == 2) + test(do[False][0]) + test(not do[False][1]) + test(len(ro) == 2) + test(len(ro[False]) == 2) + test(ro[False][0]) + test(not ro[False][1]) + test(len(ro[True]) == 3) + test(not ro[True][0]) + test(ro[True][1]) + test(ro[True][2]) + self.called() + except: + test(False) + + def opShortShortSD(self, f): + try: + (ro, do) = f.result() + test(len(do) == 1) + test(len(do[4]) == 2) + test(do[4][0] == 6) + test(do[4][1] == 7) + test(len(ro) == 3) + test(len(ro[1]) == 3) + test(ro[1][0] == 1) + test(ro[1][1] == 2) + test(ro[1][2] == 3) + test(len(ro[2]) == 2) + test(ro[2][0] == 4) + test(ro[2][1] == 5) + test(len(ro[4]) == 2) + test(ro[4][0] == 6) + test(ro[4][1] == 7) + self.called() + except: + test(False) + + def opIntIntSD(self, f): + try: + (ro, do) = f.result() + test(len(do) == 1) + test(len(do[400]) == 2) + test(do[400][0] == 600) + test(do[400][1] == 700) + test(len(ro) == 3) + test(len(ro[100]) == 3) + test(ro[100][0] == 100) + test(ro[100][1] == 200) + test(ro[100][2] == 300) + test(len(ro[200]) == 2) + test(ro[200][0] == 400) + test(ro[200][1] == 500) + test(len(ro[400]) == 2) + test(ro[400][0] == 600) + test(ro[400][1] == 700) + self.called() + except: + test(False) + + def opLongLongSD(self, f): + try: + (ro, do) = f.result() + test(len(do) == 1) + test(len(do[999999992]) == 2) + test(do[999999992][0] == 999999110) + test(do[999999992][1] == 999999120) + test(len(ro) == 3) + test(len(ro[999999990]) == 3) + test(ro[999999990][0] == 999999110) + test(ro[999999990][1] == 999999111) + test(ro[999999990][2] == 999999110) + test(len(ro[999999991]) == 2) + test(ro[999999991][0] == 999999120) + test(ro[999999991][1] == 999999130) + test(len(ro[999999992]) == 2) + test(ro[999999992][0] == 999999110) + test(ro[999999992][1] == 999999120) + self.called() + except: + test(False) + + def opStringFloatSD(self, f): + try: + (ro, do) = f.result() + test(len(do) == 1) + test(len(do["aBc"]) == 2) + test(do["aBc"][0] - -3.14 < 0.10) + test(do["aBc"][1] - 3.14 < 0.10) + test(len(ro) == 3) + test(len(ro["abc"]) == 3) + test(ro["abc"][0] - -1.1 < 0.10) + test(ro["abc"][1] - 123123.2 < 0.10) + test(ro["abc"][2] - 100.0 < 0.10) + test(len(ro["ABC"]) == 2) + test(ro["ABC"][0] - 42.24 < 0.10) + test(ro["ABC"][1] - -1.61 < 0.10) + test(len(ro["aBc"]) == 2) + test(ro["aBc"][0] - -3.14 < 0.10) + test(ro["aBc"][1] - 3.14 < 0.10) + self.called() + except: + test(False) + + def opStringDoubleSD(self, f): + try: + (ro, do) = f.result() + test(len(do) == 1) + test(len(do[""]) == 2) + test(do[""][0] == 1.6E10) + test(do[""][1] == 1.7E10) + test(len(ro) == 3) + test(len(ro["Hello!!"]) == 3) + test(ro["Hello!!"][0] == 1.1E10) + test(ro["Hello!!"][1] == 1.2E10) + test(ro["Hello!!"][2] == 1.3E10) + test(len(ro["Goodbye"]) == 2) + test(ro["Goodbye"][0] == 1.4E10) + test(ro["Goodbye"][1] == 1.5E10) + test(len(ro[""]) == 2) + test(ro[""][0] == 1.6E10) + test(ro[""][1] == 1.7E10) + self.called() + except: + test(False) + + def opStringStringSD(self, f): + try: + (ro, do) = f.result() + test(len(do) == 1) + test(len(do["ghi"]) == 2) + test(do["ghi"][0] == "and") + test(do["ghi"][1] == "xor") + test(len(ro) == 3) + test(len(ro["abc"]) == 3) + test(ro["abc"][0] == "abc") + test(ro["abc"][1] == "de") + test(ro["abc"][2] == "fghi") + test(len(ro["def"]) == 2) + test(ro["def"][0] == "xyz") + test(ro["def"][1] == "or") + test(len(ro["ghi"]) == 2) + test(ro["ghi"][0] == "and") + test(ro["ghi"][1] == "xor") + self.called() + except: + test(False) + + def opMyEnumMyEnumSD(self, f): + try: + (ro, do) = f.result() + test(len(do) == 1) + test(len(do[Test.MyEnum.enum1]) == 2) + test(do[Test.MyEnum.enum1][0] == Test.MyEnum.enum3) + test(do[Test.MyEnum.enum1][1] == Test.MyEnum.enum3) + test(len(ro) == 3) + test(len(ro[Test.MyEnum.enum3]) == 3) + test(ro[Test.MyEnum.enum3][0] == Test.MyEnum.enum1) + test(ro[Test.MyEnum.enum3][1] == Test.MyEnum.enum1) + test(ro[Test.MyEnum.enum3][2] == Test.MyEnum.enum2) + test(len(ro[Test.MyEnum.enum2]) == 2) + test(ro[Test.MyEnum.enum2][0] == Test.MyEnum.enum1) + test(ro[Test.MyEnum.enum2][1] == Test.MyEnum.enum2) + test(len(ro[Test.MyEnum.enum1]) == 2) + test(ro[Test.MyEnum.enum1][0] == Test.MyEnum.enum3) + test(ro[Test.MyEnum.enum1][1] == Test.MyEnum.enum3) + self.called() + except: + test(False) + + def opIntS(self, f): + try: + r = f.result() + for j in range(0, len(r)): + test(r[j] == -j) + self.called() + except: + test(False) + + def opIdempotent(self, f): + self.called() + + def opNonmutating(self, f): + self.called() + + def opDerived(self, f): + self.called() + +def twowaysFuture(communicator, p): + f = p.ice_pingAsync() + test(f.result() is None) + + f = p.ice_isAAsync(Test._MyClassDisp.ice_staticId()) + test(f.result()) + + f = p.ice_idAsync() + test(f.result() == "::Test::MyDerivedClass") + + f = p.ice_idsAsync() + test(len(f.result()) == 3) + + f = p.opVoidAsync() + test(f.result() is None) + + cb = Callback() + p.opVoidAsync().add_done_callback(lambda f: cb.called()) + cb.check() + + f = p.opByteAsync(0xff, 0x0f) + (ret, p3) = f.result() + test(p3 == 0xf0) + test(ret == 0xff) + + cb = Callback() + p.opByteAsync(0xff, 0x0f).add_done_callback(cb.opByte) + cb.check() + + cb = Callback() + p.opBoolAsync(True, False).add_done_callback(cb.opBool) + cb.check() + + cb = Callback() + p.opShortIntLongAsync(10, 11, 12).add_done_callback(cb.opShortIntLong) + cb.check() + + cb = Callback() + p.opFloatDoubleAsync(3.14, 1.1E10).add_done_callback(cb.opFloatDouble) + cb.check() + + cb = Callback() + p.opStringAsync("hello", "world").add_done_callback(cb.opString) + cb.check() + + cb = Callback() + p.opMyEnumAsync(Test.MyEnum.enum2).add_done_callback(cb.opMyEnum) + cb.check() + + cb = Callback(communicator) + p.opMyClassAsync(p).add_done_callback(cb.opMyClass) + cb.check() + + si1 = Test.Structure() + si1.p = p + si1.e = Test.MyEnum.enum3 + si1.s = Test.AnotherStruct() + si1.s.s = "abc" + si2 = Test.Structure() + si2.p = None + si2.e = Test.MyEnum.enum2 + si2.s = Test.AnotherStruct() + si2.s.s = "def" + + cb = Callback(communicator) + p.opStructAsync(si1, si2).add_done_callback(cb.opStruct) + cb.check() + + bsi1 = (0x01, 0x11, 0x12, 0x22) + bsi2 = (0xf1, 0xf2, 0xf3, 0xf4) + + cb = Callback() + p.opByteSAsync(bsi1, bsi2).add_done_callback(cb.opByteS) + cb.check() + + bsi1 = (True, True, False) + bsi2 = (False,) + + cb = Callback() + p.opBoolSAsync(bsi1, bsi2).add_done_callback(cb.opBoolS) + cb.check() + + ssi = (1, 2, 3) + isi = (5, 6, 7, 8) + lsi = (10, 30, 20) + + cb = Callback() + p.opShortIntLongSAsync(ssi, isi, lsi).add_done_callback(cb.opShortIntLongS) + cb.check() + + fsi = (3.14, 1.11) + dsi = (1.1E10, 1.2E10, 1.3E10) + + cb = Callback() + p.opFloatDoubleSAsync(fsi, dsi).add_done_callback(cb.opFloatDoubleS) + cb.check() + + ssi1 = ('abc', 'de', 'fghi') + ssi2 = ('xyz',) + + cb = Callback() + p.opStringSAsync(ssi1, ssi2).add_done_callback(cb.opStringS) + cb.check() + + bsi1 = ((0x01, 0x11, 0x12), (0xff,)) + bsi2 = ((0x0e,), (0xf2, 0xf1)) + + cb = Callback() + p.opByteSSAsync(bsi1, bsi2).add_done_callback(cb.opByteSS) + cb.check() + + bsi1 = ((True,), (False,), (True, True),) + bsi2 = ((False, False, True),) + + cb = Callback() + p.opBoolSSAsync(bsi1, bsi2).add_done_callback(cb.opBoolSS) + cb.check(); + + ssi = ((1,2,5), (13,), ()) + isi = ((24, 98), (42,)) + lsi = ((496, 1729),) + + cb = Callback() + p.opShortIntLongSSAsync(ssi, isi, lsi).add_done_callback(cb.opShortIntLongSS) + cb.check() + + fsi = ((3.14,), (1.11,), ()) + dsi = ((1.1E10, 1.2E10, 1.3E10),) + + cb = Callback() + p.opFloatDoubleSSAsync(fsi, dsi).add_done_callback(cb.opFloatDoubleSS) + cb.check() + + ssi1 = (('abc',), ('de', 'fghi')) + ssi2 = ((), (), ('xyz',)) + + cb = Callback() + p.opStringSSAsync(ssi1, ssi2).add_done_callback(cb.opStringSS) + cb.check() + + di1 = {10: True, 100: False} + di2 = {10: True, 11: False, 101: True} + + cb = Callback() + p.opByteBoolDAsync(di1, di2).add_done_callback(cb.opByteBoolD) + cb.check() + + di1 = {110: -1, 1100: 123123} + di2 = {110: -1, 111: -100, 1101: 0} + + cb = Callback() + p.opShortIntDAsync(di1, di2).add_done_callback(cb.opShortIntD) + cb.check() + + di1 = {999999110: -1.1, 999999111: 123123.2} + di2 = {999999110: -1.1, 999999120: -100.4, 999999130: 0.5} + + cb = Callback() + p.opLongFloatDAsync(di1, di2).add_done_callback(cb.opLongFloatD) + cb.check() + + di1 = {'foo': 'abc -1.1', 'bar': 'abc 123123.2'} + di2 = {'foo': 'abc -1.1', 'FOO': 'abc -100.4', 'BAR': 'abc 0.5'} + + cb = Callback() + p.opStringStringDAsync(di1, di2).add_done_callback(cb.opStringStringD) + cb.check() + + di1 = {'abc': Test.MyEnum.enum1, '': Test.MyEnum.enum2} + di2 = {'abc': Test.MyEnum.enum1, 'qwerty': Test.MyEnum.enum3, 'Hello!!': Test.MyEnum.enum2} + + cb = Callback() + p.opStringMyEnumDAsync(di1, di2).add_done_callback(cb.opStringMyEnumD) + cb.check() + + di1 = {Test.MyEnum.enum1: 'abc'} + di2 = {Test.MyEnum.enum2: 'Hello!!', Test.MyEnum.enum3: 'qwerty'} + + cb = Callback() + p.opMyEnumStringDAsync(di1, di2).add_done_callback(cb.opMyEnumStringD) + cb.check() + + s11 = Test.MyStruct() + s11.i = 1 + s11.j = 1 + s12 = Test.MyStruct() + s12.i = 1 + s12.j = 2 + s22 = Test.MyStruct() + s22.i = 2 + s22.j = 2 + s23 = Test.MyStruct() + s23.i = 2 + s23.j = 3 + di1 = {s11: Test.MyEnum.enum1, s12: Test.MyEnum.enum2} + di2 = {s11: Test.MyEnum.enum1, s22: Test.MyEnum.enum3, s23: Test.MyEnum.enum2} + + cb = Callback() + p.opMyStructMyEnumDAsync(di1, di2).add_done_callback(cb.opMyStructMyEnumD) + cb.check() + + dsi1 = ({ 10: True, 100: False }, { 10: True, 11: False, 101: True }) + dsi2 = ({ 100: False, 101: False },) + + cb = Callback() + p.opByteBoolDSAsync(dsi1, dsi2).add_done_callback(cb.opByteBoolDS) + cb.check() + + dsi1 = ({ 110: -1, 1100: 123123 }, { 110: -1, 111: -100, 1101: 0 }) + dsi2 = ({ 100: -1001 },) + + cb = Callback() + p.opShortIntDSAsync(dsi1, dsi2).add_done_callback(cb.opShortIntDS) + cb.called() + + dsi1 = ({ 999999110: -1.1, 999999111: 123123.2 }, { 999999110: -1.1, 999999120: -100.4, 999999130: 0.5 }) + dsi2 = ({ 999999140: 3.14 },) + + cb = Callback() + p.opLongFloatDSAsync(dsi1, dsi2).add_done_callback(cb.opLongFloatDS) + cb.called() + + dsi1 = ({ "foo": "abc -1.1", "bar": "abc 123123.2" }, { "foo": "abc -1.1", "FOO": "abc -100.4", "BAR": "abc 0.5" }) + dsi2 = ({ "f00": "ABC -3.14" },) + + cb = Callback() + p.opStringStringDSAsync(dsi1, dsi2).add_done_callback(cb.opStringStringDS) + cb.called() + + dsi1 = ( + { "abc": Test.MyEnum.enum1, "": Test.MyEnum.enum2 }, + { "abc": Test.MyEnum.enum1, "qwerty": Test.MyEnum.enum3, "Hello!!": Test.MyEnum.enum2 } + ) + + dsi2 = ({ "Goodbye": Test.MyEnum.enum1 },) + + cb = Callback() + p.opStringMyEnumDSAsync(dsi1, dsi2).add_done_callback(cb.opStringMyEnumDS) + cb.called() + + dsi1 = ({ Test.MyEnum.enum1: 'abc' }, { Test.MyEnum.enum2: 'Hello!!', Test.MyEnum.enum3: 'qwerty'}) + dsi2 = ({ Test.MyEnum.enum1: 'Goodbye' },) + + cb = Callback() + p.opMyEnumStringDSAsync(dsi1, dsi2).add_done_callback(cb.opMyEnumStringDS) + cb.called() + + s11 = Test.MyStruct(1, 1) + s12 = Test.MyStruct(1, 2) + + s22 = Test.MyStruct(2, 2) + s23 = Test.MyStruct(2, 3) + + dsi1 = ( + { s11: Test.MyEnum.enum1, s12: Test.MyEnum.enum2 }, + { s11: Test.MyEnum.enum1, s22: Test.MyEnum.enum3, s23: Test.MyEnum.enum2 } + ) + dsi2 = ({ s23: Test.MyEnum.enum3 },) + + cb = Callback() + p.opMyStructMyEnumDSAsync(dsi1, dsi2).add_done_callback(cb.opMyStructMyEnumDS) + cb.called() + + sdi1 = { 0x01: (0x01, 0x11), 0x22: (0x12,) } + sdi2 = { 0xf1: (0xf2, 0xf3) } + + cb = Callback() + p.opByteByteSDAsync(sdi1, sdi2).add_done_callback(cb.opByteByteSD) + cb.called() + + sdi1 = { False: (True, False), True: (False, True, True) } + sdi2 = { False: (True, False) } + + cb = Callback() + p.opBoolBoolSDAsync(sdi1, sdi2).add_done_callback(cb.opBoolBoolSD) + cb.called() + + sdi1 = { 1: (1, 2, 3), 2: (4, 5) } + sdi2 = { 4: (6, 7) } + + cb = Callback() + p.opShortShortSDAsync(sdi1, sdi2).add_done_callback(cb.opShortShortSD) + cb.called() + + sdi1 = { 100: (100, 200, 300), 200: (400, 500) } + sdi2 = { 400: (600, 700) } + + cb = Callback() + p.opIntIntSDAsync(sdi1, sdi2).add_done_callback(cb.opIntIntSD) + cb.called() + + sdi1 = { 999999990: (999999110, 999999111, 999999110), 999999991: (999999120, 999999130) } + sdi2 = { 999999992: (999999110, 999999120) } + + cb = Callback() + p.opLongLongSDAsync(sdi1, sdi2).add_done_callback(cb.opLongLongSD) + cb.called() + + sdi1 = { "abc": (-1.1, 123123.2, 100.0), "ABC": (42.24, -1.61) } + sdi2 = { "aBc": (-3.14, 3.14) } + + cb = Callback() + p.opStringFloatSDAsync(sdi1, sdi2).add_done_callback(cb.opStringFloatSD) + cb.called() + + sdi1 = { "Hello!!": (1.1E10, 1.2E10, 1.3E10), "Goodbye": (1.4E10, 1.5E10) } + sdi2 = { "": (1.6E10, 1.7E10) } + + cb = Callback() + p.opStringDoubleSDAsync(sdi1, sdi2).add_done_callback(cb.opStringDoubleSD) + cb.called() + + sdi1 = { "abc": ("abc", "de", "fghi") , "def": ("xyz", "or") } + sdi2 = { "ghi": ("and", "xor") } + + cb = Callback() + p.opStringStringSDAsync(sdi1, sdi2).add_done_callback(cb.opStringStringSD) + cb.called() + + sdi1 = { + Test.MyEnum.enum3: (Test.MyEnum.enum1, Test.MyEnum.enum1, Test.MyEnum.enum2), + Test.MyEnum.enum2: (Test.MyEnum.enum1, Test.MyEnum.enum2) + } + sdi2 = { Test.MyEnum.enum1: (Test.MyEnum.enum3, Test.MyEnum.enum3) } + + cb = Callback() + p.opMyEnumMyEnumSDAsync(sdi1, sdi2).add_done_callback(cb.opMyEnumMyEnumSD) + cb.called() + + lengths = ( 0, 1, 2, 126, 127, 128, 129, 253, 254, 255, 256, 257, 1000 ) + for l in lengths: + s = [] + for i in range(l): + s.append(i) + cb = Callback(l) + p.opIntSAsync(s).add_done_callback(cb.opIntS) + cb.check() + + ctx = {'one': 'ONE', 'two': 'TWO', 'three': 'THREE'} + + test(len(p.ice_getContext()) == 0) + f = p.opContextAsync() + c = f.result() + test(c != ctx) + + test(len(p.ice_getContext()) == 0) + f = p.opContextAsync(context=ctx) + c = f.result() + test(c == ctx) + + p2 = Test.MyClassPrx.checkedCast(p.ice_context(ctx)) + test(p2.ice_getContext() == ctx) + f = p2.opContextAsync() + c = f.result() + test(c == ctx) + + f = p2.opContextAsync(context=ctx) + c = f.result() + test(c == ctx) + + # + # Test implicit context propagation + # + if p.ice_getConnection(): + impls = ( 'Shared', 'PerThread' ) + for i in impls: + initData = Ice.InitializationData() + initData.properties = communicator.getProperties().clone() + initData.properties.setProperty('Ice.ImplicitContext', i) + ic = Ice.initialize(data=initData) + + ctx = {'one': 'ONE', 'two': 'TWO', 'three': 'THREE'} + + p3 = Test.MyClassPrx.uncheckedCast(ic.stringToProxy("test:default -p 12010")) + + ic.getImplicitContext().setContext(ctx) + test(ic.getImplicitContext().getContext() == ctx) + f = p3.opContextAsync() + c = f.result() + test(c == ctx) + + ic.getImplicitContext().put('zero', 'ZERO') + + ctx = ic.getImplicitContext().getContext() + f = p3.opContextAsync() + c = f.result() + test(c == ctx) + + prxContext = {'one': 'UN', 'four': 'QUATRE'} + + combined = {} + combined.update(ctx) + combined.update(prxContext) + test(combined['one'] == 'UN') + + p3 = Test.MyClassPrx.uncheckedCast(p3.ice_context(prxContext)) + ic.getImplicitContext().setContext({}) + f = p3.opContextAsync() + c = f.result() + test(c == prxContext) + + ic.getImplicitContext().setContext(ctx) + f = p3.opContextAsync() + c = f.result() + test(c == combined) + + ic.destroy() + + cb = Callback() + p.opIdempotentAsync().add_done_callback(cb.opIdempotent) + cb.check() + + cb = Callback() + p.opNonmutatingAsync().add_done_callback(cb.opNonmutating) + cb.check() + + derived = Test.MyDerivedClassPrx.checkedCast(p) + test(derived) + cb = Callback() + derived.opDerivedAsync().add_done_callback(cb.opDerived) + cb.check() + + f = p.opByte1Async(0xFF) + test(f.result() == 0xFF) + + f = p.opShort1Async(0x7FFF) + test(f.result() == 0x7FFF) + + f = p.opInt1Async(0x7FFFFFFF) + test(f.result() == 0x7FFFFFFF) + + f = p.opLong1Async(0x7FFFFFFFFFFFFFFF) + test(f.result() == 0x7FFFFFFFFFFFFFFF) + + f = p.opFloat1Async(1.0) + test(f.result() == 1.0) + + f = p.opDouble1Async(1.0) + test(f.result() == 1.0) + + f = p.opString1Async("opString1") + test(f.result() == "opString1") + + f = p.opStringS1Async(None) + test(len(f.result()) == 0) + + f = p.opByteBoolD1Async(None) + test(len(f.result()) == 0) + + f = p.opStringS2Async(None) + test(len(f.result()) == 0) + + f = p.opByteBoolD2Async(None) + test(len(f.result()) == 0) diff --git a/python/test/Ice/operations/run.py b/python/test/Ice/operations/run.py deleted file mode 100755 index 63b57c4f797..00000000000 --- a/python/test/Ice/operations/run.py +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env python -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -import os, sys - -path = [ ".", "..", "../..", "../../..", "../../../.." ] -head = os.path.dirname(sys.argv[0]) -if len(head) > 0: - path = [os.path.join(head, p) for p in path] -path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ] -if len(path) == 0: - raise RuntimeError("can't find toplevel directory!") -sys.path.append(os.path.join(path[0], "scripts")) -import TestUtil - -print("tests with regular server.") -TestUtil.clientServerTest() -print("tests with AMD server.") -TestUtil.clientServerTest(server="ServerAMD.py") -print("tests with collocated server.") -TestUtil.collocatedTest(" --Ice.ThreadPool.Client.SizeMax=2 --Ice.ThreadPool.Client.SizeWarn=0") diff --git a/python/test/Ice/optional/AllTests.py b/python/test/Ice/optional/AllTests.py index f798be8f20e..ee5565db1b4 100644 --- a/python/test/Ice/optional/AllTests.py +++ b/python/test/Ice/optional/AllTests.py @@ -76,13 +76,13 @@ def allTests(communicator): fs = Test.FixedStruct(78) vs = Test.VarStruct("hello") mo1 = Test.MultiOptional(15, True, 19, 78, 99, 5.5, 1.0, "test", Test.MyEnum.MyEnumMember, \ - Test.MultiOptionalPrx.uncheckedCast(communicator.stringToProxy("test")), \ + communicator.stringToProxy("test"), \ None, [5], ["test", "test2"], {4:3}, {"test":10}, fs, vs, [1], \ [Test.MyEnum.MyEnumMember, Test.MyEnum.MyEnumMember], \ [ fs ], [ vs ], [ oo1 ], \ - [ Test.OneOptionalPrx.uncheckedCast(communicator.stringToProxy("test")) ], \ + [ communicator.stringToProxy("test") ], \ {4:Test.MyEnum.MyEnumMember}, {4:fs}, {5:vs}, {5:Test.OneOptional(15)}, \ - {5:Test.OneOptionalPrx.uncheckedCast(communicator.stringToProxy("test"))}, \ + {5:communicator.stringToProxy("test")}, \ [False, True, False]) test(mo1.a == 15) @@ -94,7 +94,7 @@ def allTests(communicator): test(mo1.g == 1.0) test(mo1.h == "test") test(mo1.i == Test.MyEnum.MyEnumMember) - test(mo1.j == Test.MultiOptionalPrx.uncheckedCast(communicator.stringToProxy("test"))) + test(mo1.j == communicator.stringToProxy("test")) test(mo1.k == None) test(mo1.bs == [5]) test(mo1.ss == ["test", "test2"]) @@ -108,13 +108,13 @@ def allTests(communicator): test(mo1.fss[0] == Test.FixedStruct(78)) test(mo1.vss[0] == Test.VarStruct("hello")) test(mo1.oos[0] == oo1) - test(mo1.oops[0] == Test.OneOptionalPrx.uncheckedCast(communicator.stringToProxy("test"))) + test(mo1.oops[0] == communicator.stringToProxy("test")) test(mo1.ied[4] == Test.MyEnum.MyEnumMember) test(mo1.ifsd[4] == Test.FixedStruct(78)) test(mo1.ivsd[5] == Test.VarStruct("hello")) test(mo1.iood[5].a == 15) - test(mo1.ioopd[5] == Test.OneOptionalPrx.uncheckedCast(communicator.stringToProxy("test"))) + test(mo1.ioopd[5] == communicator.stringToProxy("test")) test(mo1.bos == [False, True, False]) @@ -197,13 +197,13 @@ def allTests(communicator): test(mo5.fss[0] == Test.FixedStruct(78)) test(mo5.vss[0] == Test.VarStruct("hello")) test(mo5.oos[0].a == 15) - test(mo5.oops[0] == Test.OneOptionalPrx.uncheckedCast(communicator.stringToProxy("test"))) + test(mo5.oops[0] == communicator.stringToProxy("test")) test(mo5.ied[4] == Test.MyEnum.MyEnumMember) test(mo5.ifsd[4] == Test.FixedStruct(78)) test(mo5.ivsd[5] == Test.VarStruct("hello")) test(mo5.iood[5].a == 15) - test(mo5.ioopd[5] == Test.OneOptionalPrx.uncheckedCast(communicator.stringToProxy("test"))) + test(mo5.ioopd[5] == communicator.stringToProxy("test")) test(mo5.bos == mo1.bos) @@ -305,13 +305,13 @@ def allTests(communicator): test(mo9.fss is Ice.Unset) test(mo9.vss[0] == Test.VarStruct("hello")) test(mo9.oos is Ice.Unset) - test(mo9.oops[0] == Test.OneOptionalPrx.uncheckedCast(communicator.stringToProxy("test"))) + test(mo9.oops[0] == communicator.stringToProxy("test")) test(mo9.ied[4] == Test.MyEnum.MyEnumMember) test(mo9.ifsd is Ice.Unset) test(mo9.ivsd[5] == Test.VarStruct("hello")) test(mo9.iood is Ice.Unset) - test(mo9.ioopd[5] == Test.OneOptionalPrx.uncheckedCast(communicator.stringToProxy("test"))) + test(mo9.ioopd[5] == communicator.stringToProxy("test")) test(mo9.bos is Ice.Unset) @@ -465,72 +465,72 @@ def allTests(communicator): test(p2 is Ice.Unset and p3 is Ice.Unset) (p2, p3) = initial.opByte(56) test(p2 == 56 and p3 == 56) - r = initial.begin_opByte(56) - (p2, p3) = initial.end_opByte(r) + f = initial.opByteAsync(56) + (p2, p3) = f.result() test(p2 == 56 and p3 == 56) (p2, p3) = initial.opBool(Ice.Unset) test(p2 is Ice.Unset and p3 is Ice.Unset) (p2, p3) = initial.opBool(True) test(p2 == True and p3 == True) - r = initial.begin_opBool(True) - (p2, p3) = initial.end_opBool(r) + f = initial.opBoolAsync(True) + (p2, p3) = f.result() test(p2 == True and p3 == True) (p2, p3) = initial.opShort(Ice.Unset) test(p2 is Ice.Unset and p3 is Ice.Unset) (p2, p3) = initial.opShort(56) test(p2 == 56 and p3 == 56) - r = initial.begin_opShort(56) - (p2, p3) = initial.end_opShort(r) + f = initial.opShortAsync(56) + (p2, p3) = f.result() test(p2 == 56 and p3 == 56) (p2, p3) = initial.opInt(Ice.Unset) test(p2 is Ice.Unset and p3 is Ice.Unset) (p2, p3) = initial.opInt(56) test(p2 == 56 and p3 == 56) - r = initial.begin_opInt(56) - (p2, p3) = initial.end_opInt(r) + f = initial.opIntAsync(56) + (p2, p3) = f.result() test(p2 == 56 and p3 == 56) (p2, p3) = initial.opLong(Ice.Unset) test(p2 is Ice.Unset and p3 is Ice.Unset) (p2, p3) = initial.opLong(56) test(p2 == 56 and p3 == 56) - r = initial.begin_opLong(56) - (p2, p3) = initial.end_opLong(r) + f = initial.opLongAsync(56) + (p2, p3) = f.result() test(p2 == 56 and p3 == 56) (p2, p3) = initial.opFloat(Ice.Unset) test(p2 is Ice.Unset and p3 is Ice.Unset) (p2, p3) = initial.opFloat(1.0) test(p2 == 1.0 and p3 == 1.0) - r = initial.begin_opFloat(1.0) - (p2, p3) = initial.end_opFloat(r) + f = initial.opFloatAsync(1.0) + (p2, p3) = f.result() test(p2 == 1.0 and p3 == 1.0) (p2, p3) = initial.opDouble(Ice.Unset) test(p2 is Ice.Unset and p3 is Ice.Unset) (p2, p3) = initial.opDouble(1.0) test(p2 == 1.0 and p3 == 1.0) - r = initial.begin_opDouble(1.0) - (p2, p3) = initial.end_opDouble(r) + f = initial.opDoubleAsync(1.0) + (p2, p3) = f.result() test(p2 == 1.0 and p3 == 1.0) (p2, p3) = initial.opString(Ice.Unset) test(p2 is Ice.Unset and p3 is Ice.Unset) (p2, p3) = initial.opString("test") test(p2 == "test" and p3 == "test") - r = initial.begin_opString("test") - (p2, p3) = initial.end_opString(r) + f = initial.opStringAsync("test") + (p2, p3) = f.result() test(p2 == "test" and p3 == "test") (p2, p3) = initial.opMyEnum(Ice.Unset) test(p2 is Ice.Unset and p3 is Ice.Unset) (p2, p3) = initial.opMyEnum(Test.MyEnum.MyEnumMember) test(p2 == Test.MyEnum.MyEnumMember and p3 == Test.MyEnum.MyEnumMember) - r = initial.begin_opMyEnum(Test.MyEnum.MyEnumMember) - (p2, p3) = initial.end_opMyEnum(r) + f = initial.opMyEnumAsync(Test.MyEnum.MyEnumMember) + (p2, p3) = f.result() test(p2 == Test.MyEnum.MyEnumMember and p3 == Test.MyEnum.MyEnumMember) (p2, p3) = initial.opSmallStruct(Ice.Unset) @@ -540,8 +540,8 @@ def allTests(communicator): test(p2 == p1 and p3 == p1) (p2, p3) = initial.opSmallStruct(None) # Test null struct test(p2.m == 0 and p3.m == 0) - r = initial.begin_opSmallStruct(p1) - (p2, p3) = initial.end_opSmallStruct(r) + f = initial.opSmallStructAsync(p1) + (p2, p3) = f.result() test(p2 == p1 and p3 == p1) (p2, p3) = initial.opFixedStruct(Ice.Unset) @@ -549,8 +549,8 @@ def allTests(communicator): p1 = Test.FixedStruct(56) (p2, p3) = initial.opFixedStruct(p1) test(p2 == p1 and p3 == p1) - r = initial.begin_opFixedStruct(p1) - (p2, p3) = initial.end_opFixedStruct(r) + f = initial.opFixedStructAsync(p1) + (p2, p3) = f.result() test(p2 == p1 and p3 == p1) (p2, p3) = initial.opVarStruct(Ice.Unset) @@ -558,8 +558,8 @@ def allTests(communicator): p1 = Test.VarStruct("test") (p2, p3) = initial.opVarStruct(p1) test(p2 == p1 and p3 == p1) - r = initial.begin_opVarStruct(p1) - (p2, p3) = initial.end_opVarStruct(r) + f = initial.opVarStructAsync(p1) + (p2, p3) = f.result() test(p2 == p1 and p3 == p1) (p2, p3) = initial.opOneOptional(Ice.Unset) @@ -567,17 +567,17 @@ def allTests(communicator): p1 = Test.OneOptional(58) (p2, p3) = initial.opOneOptional(p1) test(p2.a == p1.a and p3.a == p1.a) - r = initial.begin_opOneOptional(p1) - (p2, p3) = initial.end_opOneOptional(r) + f = initial.opOneOptionalAsync(p1) + (p2, p3) = f.result() test(p2.a == p1.a and p3.a == p1.a) (p2, p3) = initial.opOneOptionalProxy(Ice.Unset) test(p2 is Ice.Unset and p3 is Ice.Unset) - p1 = Test.OneOptionalPrx.uncheckedCast(communicator.stringToProxy("test")) + p1 = communicator.stringToProxy("test") (p2, p3) = initial.opOneOptionalProxy(p1) test(p2 == p1 and p3 == p1) - r = initial.begin_opOneOptionalProxy(p1) - (p2, p3) = initial.end_opOneOptionalProxy(r) + f = initial.opOneOptionalProxyAsync(p1) + (p2, p3) = f.result() test(p2 == p1 and p3 == p1) (p2, p3) = initial.opByteSeq(Ice.Unset) @@ -591,8 +591,8 @@ def allTests(communicator): else: test(p2[0] == 0x38) test(p3[0] == 0x38) - r = initial.begin_opByteSeq(p1) - (p2, p3) = initial.end_opByteSeq(r) + f = initial.opByteSeqAsync(p1) + (p2, p3) = f.result() test(len(p2) == len(p1) and len(p3) == len(p1)) if sys.version_info[0] == 2: test(p2[0] == '\x38') @@ -606,8 +606,8 @@ def allTests(communicator): p1 = [True for x in range(100)] (p2, p3) = initial.opBoolSeq(p1) test(p2 == p1 and p3 == p1) - r = initial.begin_opBoolSeq(p1) - (p2, p3) = initial.end_opBoolSeq(r) + f = initial.opBoolSeqAsync(p1) + (p2, p3) = f.result() test(p2 == p1 and p3 == p1) (p2, p3) = initial.opShortSeq(Ice.Unset) @@ -615,8 +615,8 @@ def allTests(communicator): p1 = [56 for x in range(100)] (p2, p3) = initial.opShortSeq(p1) test(p2 == p1 and p3 == p1) - r = initial.begin_opShortSeq(p1) - (p2, p3) = initial.end_opShortSeq(r) + f = initial.opShortSeqAsync(p1) + (p2, p3) = f.result() test(p2 == p1 and p3 == p1) (p2, p3) = initial.opIntSeq(Ice.Unset) @@ -624,8 +624,8 @@ def allTests(communicator): p1 = [56 for x in range(100)] (p2, p3) = initial.opIntSeq(p1) test(p2 == p1 and p3 == p1) - r = initial.begin_opIntSeq(p1) - (p2, p3) = initial.end_opIntSeq(r) + f = initial.opIntSeqAsync(p1) + (p2, p3) = f.result() test(p2 == p1 and p3 == p1) (p2, p3) = initial.opLongSeq(Ice.Unset) @@ -633,8 +633,8 @@ def allTests(communicator): p1 = [56 for x in range(100)] (p2, p3) = initial.opLongSeq(p1) test(p2 == p1 and p3 == p1) - r = initial.begin_opLongSeq(p1) - (p2, p3) = initial.end_opLongSeq(r) + f = initial.opLongSeqAsync(p1) + (p2, p3) = f.result() test(p2 == p1 and p3 == p1) (p2, p3) = initial.opFloatSeq(Ice.Unset) @@ -642,8 +642,8 @@ def allTests(communicator): p1 = [1.0 for x in range(100)] (p2, p3) = initial.opFloatSeq(p1) test(p2 == p1 and p3 == p1) - r = initial.begin_opFloatSeq(p1) - (p2, p3) = initial.end_opFloatSeq(r) + f = initial.opFloatSeqAsync(p1) + (p2, p3) = f.result() test(p2 == p1 and p3 == p1) (p2, p3) = initial.opDoubleSeq(Ice.Unset) @@ -651,8 +651,8 @@ def allTests(communicator): p1 = [1.0 for x in range(100)] (p2, p3) = initial.opDoubleSeq(p1) test(p2 == p1 and p3 == p1) - r = initial.begin_opDoubleSeq(p1) - (p2, p3) = initial.end_opDoubleSeq(r) + f = initial.opDoubleSeqAsync(p1) + (p2, p3) = f.result() test(p2 == p1 and p3 == p1) (p2, p3) = initial.opStringSeq(Ice.Unset) @@ -660,8 +660,8 @@ def allTests(communicator): p1 = ["test1" for x in range(100)] (p2, p3) = initial.opStringSeq(p1) test(p2 == p1 and p3 == p1) - r = initial.begin_opStringSeq(p1) - (p2, p3) = initial.end_opStringSeq(r) + f = initial.opStringSeqAsync(p1) + (p2, p3) = f.result() test(p2 == p1 and p3 == p1) (p2, p3) = initial.opSmallStructSeq(Ice.Unset) @@ -669,8 +669,8 @@ def allTests(communicator): p1 = [Test.SmallStruct(1) for x in range(10)] (p2, p3) = initial.opSmallStructSeq(p1) test(p2 == p1 and p3 == p1) - r = initial.begin_opSmallStructSeq(p1) - (p2, p3) = initial.end_opSmallStructSeq(r) + f = initial.opSmallStructSeqAsync(p1) + (p2, p3) = f.result() test(p2 == p1 and p3 == p1) (p2, p3) = initial.opSmallStructList(Ice.Unset) @@ -678,8 +678,8 @@ def allTests(communicator): p1 = tuple([Test.SmallStruct(1) for x in range(10)]) (p2, p3) = initial.opSmallStructList(p1) test(p2 == p1 and p3 == p1) - r = initial.begin_opSmallStructList(p1) - (p2, p3) = initial.end_opSmallStructList(r) + f = initial.opSmallStructListAsync(p1) + (p2, p3) = f.result() test(p2 == p1 and p3 == p1) (p2, p3) = initial.opFixedStructSeq(Ice.Unset) @@ -687,8 +687,8 @@ def allTests(communicator): p1 = [Test.FixedStruct(1) for x in range(10)] (p2, p3) = initial.opFixedStructSeq(p1) test(p2 == p1 and p3 == p1) - r = initial.begin_opFixedStructSeq(p1) - (p2, p3) = initial.end_opFixedStructSeq(r) + f = initial.opFixedStructSeqAsync(p1) + (p2, p3) = f.result() test(p2 == p1 and p3 == p1) (p2, p3) = initial.opFixedStructList(Ice.Unset) @@ -696,8 +696,8 @@ def allTests(communicator): p1 = tuple([Test.FixedStruct(1) for x in range(10)]) (p2, p3) = initial.opFixedStructList(p1) test(p2 == p1 and p3 == p1) - r = initial.begin_opFixedStructList(p1) - (p2, p3) = initial.end_opFixedStructList(r) + f = initial.opFixedStructListAsync(p1) + (p2, p3) = f.result() test(p2 == p1 and p3 == p1) (p2, p3) = initial.opVarStructSeq(Ice.Unset) @@ -705,8 +705,8 @@ def allTests(communicator): p1 = [Test.VarStruct("test") for x in range(10)] (p2, p3) = initial.opVarStructSeq(p1) test(p2 == p1 and p3 == p1) - r = initial.begin_opVarStructSeq(p1) - (p2, p3) = initial.end_opVarStructSeq(r) + f = initial.opVarStructSeqAsync(p1) + (p2, p3) = f.result() test(p2 == p1 and p3 == p1) (p2, p3) = initial.opIntIntDict(Ice.Unset) @@ -714,8 +714,8 @@ def allTests(communicator): p1 = {1:2, 2:3} (p2, p3) = initial.opIntIntDict(p1) test(p2 == p1 and p3 == p1) - r = initial.begin_opIntIntDict(p1) - (p2, p3) = initial.end_opIntIntDict(r) + f = initial.opIntIntDictAsync(p1) + (p2, p3) = f.result() test(p2 == p1 and p3 == p1) (p2, p3) = initial.opStringIntDict(Ice.Unset) @@ -723,10 +723,19 @@ def allTests(communicator): p1 = {"1":2, "2":3} (p2, p3) = initial.opStringIntDict(p1) test(p2 == p1 and p3 == p1) - r = initial.begin_opStringIntDict(p1) - (p2, p3) = initial.end_opStringIntDict(r) + f = initial.opStringIntDictAsync(p1) + (p2, p3) = f.result() test(p2 == p1 and p3 == p1) + (p2, p3) = initial.opIntOneOptionalDict(Ice.Unset) + test(p2 is Ice.Unset and p3 is Ice.Unset) + p1 = {1:Test.OneOptional(58), 2:Test.OneOptional(59)} + (p2, p3) = initial.opIntOneOptionalDict(p1) + test(p2[1].a == 58 and p3[1].a == 58); + f = initial.opIntOneOptionalDictAsync(p1) + (p2, p3) = f.result() + test(p2[1].a == 58 and p3[1].a == 58); + print("ok") sys.stdout.write("testing exception optionals... ") @@ -794,4 +803,42 @@ def allTests(communicator): print("ok") + sys.stdout.write("testing optionals with marshaled results... ") + sys.stdout.flush() + + test(initial.opMStruct1() != Ice.Unset); + test(initial.opMDict1() != Ice.Unset); + test(initial.opMSeq1() != Ice.Unset); + test(initial.opMG1() != Ice.Unset); + + (p3, p2) = initial.opMStruct2(Ice.Unset); + test(p2 == Ice.Unset and p3 == Ice.Unset); + + p1 = Test.SmallStruct(); + (p3, p2) = initial.opMStruct2(p1) + test(p2 == p1 and p3 == p1) + + (p3, p2) = initial.opMSeq2(Ice.Unset) + test(p2 == Ice.Unset and p3 == Ice.Unset) + + p1 = ["hello"] + (p3, p2) = initial.opMSeq2(p1); + test(p2[0] == "hello" and p3[0] == "hello") + + (p3, p2) = initial.opMDict2(Ice.Unset) + test(p2 == Ice.Unset and p3 == Ice.Unset) + + p1 = {"test" : 54} + (p3, p2) = initial.opMDict2(p1) + test(p2["test"] == 54 and p3["test"] == 54) + + (p3, p2) = initial.opMG2(Ice.Unset) + test(p2 == Ice.Unset and p3 == Ice.Unset) + + p1 = Test.G(); + (p3, p2) = initial.opMG2(p1); + test(p2 != Ice.Unset and p3 != Ice.Unset and p3 == p2); + + print("ok") + return initial diff --git a/python/test/Ice/optional/Client.py b/python/test/Ice/optional/Client.py index c0dd750ba76..4af2bbcbe37 100755 --- a/python/test/Ice/optional/Client.py +++ b/python/test/Ice/optional/Client.py @@ -20,17 +20,10 @@ def run(args, communicator): return True try: - communicator = Ice.initialize(sys.argv) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/optional/ClientPrivate.ice b/python/test/Ice/optional/ClientPrivate.ice index 866fabc1905..ddb03cd4aa5 100644 --- a/python/test/Ice/optional/ClientPrivate.ice +++ b/python/test/Ice/optional/ClientPrivate.ice @@ -29,7 +29,7 @@ class D extends B // on the server and pass an optional argument. This isn't necessary in other language // mappings where the public stream API is available. // -class Initial2 +interface Initial2 { void opClassAndUnknownOptional(A p, optional(1) Object o); diff --git a/python/test/Ice/optional/Server.py b/python/test/Ice/optional/Server.py index 6fdb9ad6ab4..46cd0fbebf2 100755 --- a/python/test/Ice/optional/Server.py +++ b/python/test/Ice/optional/Server.py @@ -14,7 +14,7 @@ import Ice Ice.loadSlice('Test.ice') import Test -class InitialI(Test.Initial): +class InitialI(Test._InitialDisp): def shutdown(self, current=None): current.adapter.getCommunicator().shutdown() @@ -129,6 +129,9 @@ class InitialI(Test.Initial): def opStringIntDict(self, p1, current=None): return (p1, p1) + def opIntOneOptionalDict(self, p1, current=None): + return (p1, p1) + def opClassAndUnknownOptional(self, p, current=None): pass @@ -144,6 +147,30 @@ class InitialI(Test.Initial): def opVoid(self, current=None): pass + def opMStruct1(self, current): + return Test.SmallStruct() + + def opMStruct2(self, p1, current): + return (p1, p1) + + def opMSeq1(self, current): + return [] + + def opMSeq2(self, p1, current): + return (p1, p1) + + def opMDict1(self, current): + return {} + + def opMDict2(self, p1, current): + return (p1, p1) + + def opMG1(self, current): + return Test.G() + + def opMG2(self, p1, current): + return (p1, p1) + def supportsRequiredParams(self, current=None): return False @@ -156,28 +183,24 @@ class InitialI(Test.Initial): def supportsCppStringView(self, current=None): return False + def supportsNullOptional(self, current=None): + return True + def run(args, communicator): communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010:udp") adapter = communicator.createObjectAdapter("TestAdapter") initial = InitialI() - adapter.add(initial, communicator.stringToIdentity("initial")) + adapter.add(initial, Ice.stringToIdentity("initial")) adapter.activate() communicator.waitForShutdown() return True try: - communicator = Ice.initialize(sys.argv) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/optional/ServerAMD.py b/python/test/Ice/optional/ServerAMD.py index c69ad90f864..c2cbe60ceec 100755 --- a/python/test/Ice/optional/ServerAMD.py +++ b/python/test/Ice/optional/ServerAMD.py @@ -14,22 +14,25 @@ import Ice Ice.loadSlice('TestAMD.ice') import Test -class InitialI(Test.Initial): +class InitialI(Test._InitialDisp): - def shutdown_async(self, cb, current=None): + def shutdown(self, current=None): current.adapter.getCommunicator().shutdown() - cb.ice_response() - def pingPong_async(self, cb, o, current=None): - cb.ice_response(o) + def pingPong(self, o, current=None): + return Ice.Future.completed(o) - def opOptionalException_async(self, cb, a, b, o, current=None): - cb.ice_exception(Test.OptionalException(False, a, b, o)) + def opOptionalException(self, a, b, o, current=None): + f = Ice.Future() + f.set_exception(Test.OptionalException(False, a, b, o)) + return f - def opDerivedException_async(self, cb, a, b, o, current=None): - cb.ice_exception(Test.DerivedException(False, a, b, o, b, o)) + def opDerivedException(self, a, b, o, current=None): + f = Ice.Future() + f.set_exception(Test.DerivedException(False, a, b, o, b, o)) + return f - def opRequiredException_async(self, cb, a, b, o, current=None): + def opRequiredException(self, a, b, o, current=None): e = Test.RequiredException() e.a = a e.b = b @@ -38,147 +41,172 @@ class InitialI(Test.Initial): e.ss = b if o is not Ice.Unset: e.o2 = o - cb.ice_exception(e) + f = Ice.Future() + f.set_exception(e) + return f - def opByte_async(self, cb, p1, current=None): - cb.ice_response(p1, p1) + def opByte(self, p1, current=None): + return Ice.Future.completed((p1, p1)) - def opBool_async(self, cb, p1, current=None): - cb.ice_response(p1, p1) + def opBool(self, p1, current=None): + return Ice.Future.completed((p1, p1)) - def opShort_async(self, cb, p1, current=None): - cb.ice_response(p1, p1) + def opShort(self, p1, current=None): + return Ice.Future.completed((p1, p1)) - def opInt_async(self, cb, p1, current=None): - cb.ice_response(p1, p1) + def opInt(self, p1, current=None): + return Ice.Future.completed((p1, p1)) - def opLong_async(self, cb, p1, current=None): - cb.ice_response(p1, p1) + def opLong(self, p1, current=None): + return Ice.Future.completed((p1, p1)) - def opFloat_async(self, cb, p1, current=None): - cb.ice_response(p1, p1) + def opFloat(self, p1, current=None): + return Ice.Future.completed((p1, p1)) - def opDouble_async(self, cb, p1, current=None): - cb.ice_response(p1, p1) + def opDouble(self, p1, current=None): + return Ice.Future.completed((p1, p1)) - def opString_async(self, cb, p1, current=None): - cb.ice_response(p1, p1) + def opString(self, p1, current=None): + return Ice.Future.completed((p1, p1)) - def opMyEnum_async(self, cb, p1, current=None): - cb.ice_response(p1, p1) + def opMyEnum(self, p1, current=None): + return Ice.Future.completed((p1, p1)) - def opSmallStruct_async(self, cb, p1, current=None): - cb.ice_response(p1, p1) + def opSmallStruct(self, p1, current=None): + return Ice.Future.completed((p1, p1)) - def opFixedStruct_async(self, cb, p1, current=None): - cb.ice_response(p1, p1) + def opFixedStruct(self, p1, current=None): + return Ice.Future.completed((p1, p1)) - def opVarStruct_async(self, cb, p1, current=None): - cb.ice_response(p1, p1) + def opVarStruct(self, p1, current=None): + return Ice.Future.completed((p1, p1)) - def opOneOptional_async(self, cb, p1, current=None): - cb.ice_response(p1, p1) + def opOneOptional(self, p1, current=None): + return Ice.Future.completed((p1, p1)) - def opOneOptionalProxy_async(self, cb, p1, current=None): - cb.ice_response(p1, p1) + def opOneOptionalProxy(self, p1, current=None): + return Ice.Future.completed((p1, p1)) - def opByteSeq_async(self, cb, p1, current=None): - cb.ice_response(p1, p1) + def opByteSeq(self, p1, current=None): + return Ice.Future.completed((p1, p1)) - def opBoolSeq_async(self, cb, p1, current=None): - cb.ice_response(p1, p1) + def opBoolSeq(self, p1, current=None): + return Ice.Future.completed((p1, p1)) - def opShortSeq_async(self, cb, p1, current=None): - cb.ice_response(p1, p1) + def opShortSeq(self, p1, current=None): + return Ice.Future.completed((p1, p1)) - def opIntSeq_async(self, cb, p1, current=None): - cb.ice_response(p1, p1) + def opIntSeq(self, p1, current=None): + return Ice.Future.completed((p1, p1)) - def opLongSeq_async(self, cb, p1, current=None): - cb.ice_response(p1, p1) + def opLongSeq(self, p1, current=None): + return Ice.Future.completed((p1, p1)) - def opFloatSeq_async(self, cb, p1, current=None): - cb.ice_response(p1, p1) + def opFloatSeq(self, p1, current=None): + return Ice.Future.completed((p1, p1)) - def opDoubleSeq_async(self, cb, p1, current=None): - cb.ice_response(p1, p1) + def opDoubleSeq(self, p1, current=None): + return Ice.Future.completed((p1, p1)) - def opStringSeq_async(self, cb, p1, current=None): - cb.ice_response(p1, p1) + def opStringSeq(self, p1, current=None): + return Ice.Future.completed((p1, p1)) - def opSmallStructSeq_async(self, cb, p1, current=None): - cb.ice_response(p1, p1) + def opSmallStructSeq(self, p1, current=None): + return Ice.Future.completed((p1, p1)) - def opSmallStructList_async(self, cb, p1, current=None): - cb.ice_response(p1, p1) + def opSmallStructList(self, p1, current=None): + return Ice.Future.completed((p1, p1)) - def opFixedStructSeq_async(self, cb, p1, current=None): - cb.ice_response(p1, p1) + def opFixedStructSeq(self, p1, current=None): + return Ice.Future.completed((p1, p1)) - def opFixedStructList_async(self, cb, p1, current=None): - cb.ice_response(p1, p1) + def opFixedStructList(self, p1, current=None): + return Ice.Future.completed((p1, p1)) - def opVarStructSeq_async(self, cb, p1, current=None): - cb.ice_response(p1, p1) + def opVarStructSeq(self, p1, current=None): + return Ice.Future.completed((p1, p1)) - def opSerializable_async(self, cb, p1, current=None): - cb.ice_response(p1, p1) + def opSerializable(self, p1, current=None): + return Ice.Future.completed((p1, p1)) - def opIntIntDict_async(self, cb, p1, current=None): - cb.ice_response(p1, p1) + def opIntIntDict(self, p1, current=None): + return Ice.Future.completed((p1, p1)) - def opStringIntDict_async(self, cb, p1, current=None): - cb.ice_response(p1, p1) + def opStringIntDict(self, p1, current=None): + return Ice.Future.completed((p1, p1)) - def opClassAndUnknownOptional_async(self, cb, p, current=None): - cb.ice_response() + def opIntOneOptionalDict(self, p1, current=None): + return Ice.Future.completed((p1, p1)) - def sendOptionalClass_async(self, cb, req, o, current=None): - cb.ice_response() + def opClassAndUnknownOptional(self, p, current=None): + return Ice.Future.completed(None) - def returnOptionalClass_async(self, cb, req, current=None): - cb.ice_response(Test.OneOptional(53)) + def sendOptionalClass(self, req, o, current=None): + return Ice.Future.completed(None) - def opG_async(self, cb, g, current=None): - cb.ice_response(g) + def returnOptionalClass(self, req, current=None): + return Ice.Future.completed(Test.OneOptional(53)) - def opVoid_async(self, cb, current=None): - cb.ice_response() + def opG(self, g, current=None): + return Ice.Future.completed(g) - def supportsRequiredParams_async(self, cb, current=None): - cb.ice_response(False) + def opVoid(self, current=None): + return Ice.Future.completed(None) - def supportsJavaSerializable_async(self, cb, current=None): - cb.ice_response(True) + def opMStruct1(self, current): + return Ice.Future.completed(Test.SmallStruct()) - def supportsCsharpSerializable_async(self, cb, current=None): - cb.ice_response(False) + def opMStruct2(self, p1, current): + return Ice.Future.completed((p1, p1)) - def supportsCppStringView_async(self, cb, current=None): - cb.ice_response(False) + def opMSeq1(self, current): + return Ice.Future.completed([]) + + def opMSeq2(self, p1, current): + return Ice.Future.completed((p1, p1)) + + def opMDict1(self, current): + return Ice.Future.completed({}) + + def opMDict2(self, p1, current): + return Ice.Future.completed((p1, p1)) + + def opMG1(self, current): + return Ice.Future.completed(Test.G()) + + def opMG2(self, p1, current): + return Ice.Future.completed((p1, p1)) + + def supportsRequiredParams(self, current=None): + return Ice.Future.completed(False) + + def supportsJavaSerializable(self, current=None): + return Ice.Future.completed(True) + + def supportsCsharpSerializable(self, current=None): + return Ice.Future.completed(False) + + def supportsCppStringView(self, current=None): + return Ice.Future.completed(False) + + def supportsNullOptional(self, current=None): + return Ice.Future.completed(True) def run(args, communicator): communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010:udp") adapter = communicator.createObjectAdapter("TestAdapter") initial = InitialI() - adapter.add(initial, communicator.stringToIdentity("initial")) + adapter.add(initial, Ice.stringToIdentity("initial")) adapter.activate() communicator.waitForShutdown() return True try: - communicator = Ice.initialize(sys.argv) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/optional/Test.ice b/python/test/Ice/optional/Test.ice index b28ba7add93..b95de842d06 100644 --- a/python/test/Ice/optional/Test.ice +++ b/python/test/Ice/optional/Test.ice @@ -196,7 +196,7 @@ class Recursive { optional(0) RecursiveSeq value; }; -class Initial +interface Initial { void shutdown(); @@ -271,6 +271,9 @@ class Initial optional(1) StringIntDict opStringIntDict(optional(2) StringIntDict p1, out optional(3) StringIntDict p3); + optional(1) IntOneOptionalDict opIntOneOptionalDict(optional(2) IntOneOptionalDict p1, + out optional(3) IntOneOptionalDict p3); + void opClassAndUnknownOptional(A p); void sendOptionalClass(bool req, optional(1) OneOptional o); @@ -281,6 +284,21 @@ class Initial void opVoid(); + ["marshaled-result"] optional(1) SmallStruct opMStruct1(); + ["marshaled-result"] optional(1) SmallStruct opMStruct2(optional(2) SmallStruct p1, + out optional(3)SmallStruct p2); + + ["marshaled-result"] optional(1) StringSeq opMSeq1(); + ["marshaled-result"] optional(1) StringSeq opMSeq2(optional(2) StringSeq p1, + out optional(3) StringSeq p2); + + ["marshaled-result"] optional(1) StringIntDict opMDict1(); + ["marshaled-result"] optional(1) StringIntDict opMDict2(optional(2) StringIntDict p1, + out optional(3) StringIntDict p2); + + ["marshaled-result"] optional(1) G opMG1(); + ["marshaled-result"] optional(1) G opMG2(optional(2) G p1, out optional(3) G p2); + bool supportsRequiredParams(); bool supportsJavaSerializable(); @@ -288,6 +306,8 @@ class Initial bool supportsCsharpSerializable(); bool supportsCppStringView(); + + bool supportsNullOptional(); }; }; diff --git a/python/test/Ice/optional/TestAMD.ice b/python/test/Ice/optional/TestAMD.ice index d44c0ca159d..1562414e1c2 100644 --- a/python/test/Ice/optional/TestAMD.ice +++ b/python/test/Ice/optional/TestAMD.ice @@ -192,12 +192,13 @@ class G class Recursive; sequence<Recursive> RecursiveSeq; -class Recursive { +class Recursive +{ optional(0) RecursiveSeq value; }; ["amd"] -class Initial +interface Initial { void shutdown(); @@ -272,6 +273,9 @@ class Initial optional(1) StringIntDict opStringIntDict(optional(2) StringIntDict p1, out optional(3) StringIntDict p3); + optional(1) IntOneOptionalDict opIntOneOptionalDict(optional(2) IntOneOptionalDict p1, + out optional(3) IntOneOptionalDict p3); + void opClassAndUnknownOptional(A p); void sendOptionalClass(bool req, optional(1) OneOptional o); @@ -282,6 +286,21 @@ class Initial void opVoid(); + ["marshaled-result"] optional(1) SmallStruct opMStruct1(); + ["marshaled-result"] optional(1) SmallStruct opMStruct2(optional(2) SmallStruct p1, + out optional(3)SmallStruct p2); + + ["marshaled-result"] optional(1) StringSeq opMSeq1(); + ["marshaled-result"] optional(1) StringSeq opMSeq2(optional(2) StringSeq p1, + out optional(3) StringSeq p2); + + ["marshaled-result"] optional(1) StringIntDict opMDict1(); + ["marshaled-result"] optional(1) StringIntDict opMDict2(optional(2) StringIntDict p1, + out optional(3) StringIntDict p2); + + ["marshaled-result"] optional(1) G opMG1(); + ["marshaled-result"] optional(1) G opMG2(optional(2) G p1, out optional(3) G p2); + bool supportsRequiredParams(); bool supportsJavaSerializable(); @@ -289,6 +308,8 @@ class Initial bool supportsCsharpSerializable(); bool supportsCppStringView(); + + bool supportsNullOptional(); }; }; diff --git a/python/test/Ice/optional/run.py b/python/test/Ice/optional/run.py deleted file mode 100755 index 1f5ee28b14f..00000000000 --- a/python/test/Ice/optional/run.py +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env python -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -import os, sys - -path = [ ".", "..", "../..", "../../..", "../../../.." ] -head = os.path.dirname(sys.argv[0]) -if len(head) > 0: - path = [os.path.join(head, p) for p in path] -path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ] -if len(path) == 0: - raise RuntimeError("can't find toplevel directory!") -sys.path.append(os.path.join(path[0], "scripts")) -import TestUtil - -print("Running test with compact (default) format.") -TestUtil.clientServerTest() -print("Running test with sliced format.") -TestUtil.clientServerTest(additionalClientOptions="--Ice.Default.SlicedFormat", additionalServerOptions="--Ice.Default.SlicedFormat") -print("Running test with AMD server.") -TestUtil.clientServerTest(server="ServerAMD.py") diff --git a/python/test/Ice/properties/run.py b/python/test/Ice/properties/run.py deleted file mode 100755 index 7e3f28eddab..00000000000 --- a/python/test/Ice/properties/run.py +++ /dev/null @@ -1,45 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -import os, sys - -path = [ ".", "..", "../..", "../../..", "../../../.." ] -head = os.path.dirname(sys.argv[0]) -if len(head) > 0: - path = [os.path.join(head, p) for p in path] -path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ] -if len(path) == 0: - raise RuntimeError("can't find toplevel directory!") -sys.path.append(os.path.join(path[0], "scripts")) -import TestUtil - -# -# Write config -# -if sys.version_info[0] == 2: - configPath = "./config/\xe4\xb8\xad\xe5\x9b\xbd_client.config" - decodedPath = configPath.decode("utf-8") -else: - configPath = "./config/\u4e2d\u56fd_client.config" - decodedPath = configPath # No need to decode with Python3, strings are already Unicode - -TestUtil.createFile(decodedPath, - ["# Automatically generated by Ice test driver.", - "Ice.Trace.Protocol=1", - "Ice.Trace.Network=1", - "Ice.ProgramName=PropertiesClient", - "Config.Path=" + configPath], - "utf-8") - -TestUtil.simpleTest() - -if os.path.exists(decodedPath): - os.remove(decodedPath) diff --git a/python/test/Ice/proxy/AllTests.py b/python/test/Ice/proxy/AllTests.py index 5ab14dd3d73..8c34f28cc29 100644 --- a/python/test/Ice/proxy/AllTests.py +++ b/python/test/Ice/proxy/AllTests.py @@ -358,10 +358,36 @@ def allTests(communicator, collocated): sys.stdout.write("testing proxy methods... ") sys.stdout.flush() + + test(communicator.identityToString(base.ice_identity(communicator.stringToIdentity("other")).ice_getIdentity()) \ == "other") - test(Ice.identityToString(base.ice_identity(Ice.stringToIdentity("other")).ice_getIdentity()) == "other") - + + # + # Verify that ToStringMode is passed correctly + # + euroStr = "\xE2\x82\xAC" if sys.version_info[0] < 3 else "\u20ac" + ident = Ice.Identity("test", "\x7F{}".format(euroStr)) + + idStr = Ice.identityToString(ident, Ice.ToStringMode.Unicode) + test(idStr == "\\u007f{}/test".format(euroStr)) + ident2 = Ice.stringToIdentity(idStr) + test(ident == ident2) + test(Ice.identityToString(ident) == idStr) + + idStr = Ice.identityToString(ident, Ice.ToStringMode.ASCII) + test(idStr == "\\u007f\\u20ac/test") + ident2 = Ice.stringToIdentity(idStr) + test(ident == ident2) + + idStr = Ice.identityToString(ident, Ice.ToStringMode.Compat) + test(idStr == "\\177\\342\\202\\254/test") + ident2 = Ice.stringToIdentity(idStr) + test(ident == ident2) + + ident2 = Ice.stringToIdentity(communicator.identityToString(ident)) + test(ident == ident2) + test(base.ice_facet("facet").ice_getFacet() == "facet") test(base.ice_adapterId("id").ice_getAdapterId() == "id") test(base.ice_twoway().ice_isTwoway()) diff --git a/python/test/Ice/proxy/Client.py b/python/test/Ice/proxy/Client.py index 5139f0e248a..5d83b846460 100755 --- a/python/test/Ice/proxy/Client.py +++ b/python/test/Ice/proxy/Client.py @@ -32,17 +32,10 @@ def run(args, communicator): try: initData = Ice.InitializationData() initData.properties = Ice.createProperties(sys.argv) - communicator = Ice.initialize(sys.argv, initData) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv, initData) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/proxy/Collocated.py b/python/test/Ice/proxy/Collocated.py index 4f4adcc66ed..2d12b55c431 100755 --- a/python/test/Ice/proxy/Collocated.py +++ b/python/test/Ice/proxy/Collocated.py @@ -22,7 +22,7 @@ import Test, TestI, AllTests def run(args, communicator): communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010") adapter = communicator.createObjectAdapter("TestAdapter") - adapter.add(TestI.MyDerivedClassI(), communicator.stringToIdentity("test")) + adapter.add(TestI.MyDerivedClassI(), Ice.stringToIdentity("test")) #adapter.activate() // Don't activate OA to ensure collocation is used. AllTests.allTests(communicator, True) @@ -32,17 +32,10 @@ def run(args, communicator): try: initData = Ice.InitializationData() initData.properties = Ice.createProperties(sys.argv) - communicator = Ice.initialize(sys.argv, initData) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv, initData) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/proxy/Server.py b/python/test/Ice/proxy/Server.py index 66e359e170f..2c6d3ee8c2f 100755 --- a/python/test/Ice/proxy/Server.py +++ b/python/test/Ice/proxy/Server.py @@ -23,7 +23,7 @@ def run(args, communicator): communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010:udp") adapter = communicator.createObjectAdapter("TestAdapter") - adapter.add(TestI.MyDerivedClassI(), communicator.stringToIdentity("test")) + adapter.add(TestI.MyDerivedClassI(), Ice.stringToIdentity("test")) adapter.activate() communicator.waitForShutdown() return True @@ -32,17 +32,10 @@ try: initData = Ice.InitializationData() initData.properties = Ice.createProperties(sys.argv) initData.properties.setProperty("Ice.Warn.Dispatch", "0") - communicator = Ice.initialize(sys.argv, initData) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv, initData) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/proxy/ServerAMD.py b/python/test/Ice/proxy/ServerAMD.py index c767ac44efb..6a310161383 100755 --- a/python/test/Ice/proxy/ServerAMD.py +++ b/python/test/Ice/proxy/ServerAMD.py @@ -19,28 +19,27 @@ if not slice_dir: Ice.loadSlice("'-I" + slice_dir + "' TestAMD.ice") import Test -class MyDerivedClassI(Test.MyDerivedClass): +class MyDerivedClassI(Test._MyDerivedClassDisp): def __init__(self): self.ctx = None - def shutdown_async(self, cb, current=None): + def shutdown(self, current=None): current.adapter.getCommunicator().shutdown() - cb.ice_response() - def getContext_async(self, cb, current): - return cb.ice_response(self.ctx) + def getContext(self, current): + return Ice.Future.completed(self.ctx) - def echo_async(self, cb, obj, current): - return cb.ice_response(obj) + def echo(self, obj, current): + return Ice.Future.completed(obj) def ice_isA(self, s, current): self.ctx = current.ctx - return Test.MyDerivedClass.ice_isA(self, s, current) + return Test._MyDerivedClassDisp.ice_isA(self, s, current) def run(args, communicator): communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010:udp") adapter = communicator.createObjectAdapter("TestAdapter") - adapter.add(MyDerivedClassI(), communicator.stringToIdentity("test")) + adapter.add(MyDerivedClassI(), Ice.stringToIdentity("test")) adapter.activate() communicator.waitForShutdown() return True @@ -50,17 +49,10 @@ try: initData.properties = Ice.createProperties(sys.argv) initData.properties.setProperty("Ice.Warn.Connections", "0") initData.properties.setProperty("Ice.Warn.Dispatch", "0") - communicator = Ice.initialize(sys.argv, initData) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv, initData) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/proxy/Test.ice b/python/test/Ice/proxy/Test.ice index b96eced15dc..f98d7dbcb3d 100644 --- a/python/test/Ice/proxy/Test.ice +++ b/python/test/Ice/proxy/Test.ice @@ -14,14 +14,14 @@ module Test { -class MyClass +interface MyClass { void shutdown(); Ice::Context getContext(); }; -class MyDerivedClass extends MyClass +interface MyDerivedClass extends MyClass { Object* echo(Object* obj); }; diff --git a/python/test/Ice/proxy/TestAMD.ice b/python/test/Ice/proxy/TestAMD.ice index beeb7692447..d0312f701b1 100644 --- a/python/test/Ice/proxy/TestAMD.ice +++ b/python/test/Ice/proxy/TestAMD.ice @@ -14,14 +14,14 @@ module Test { -["amd"] class MyClass +["amd"] interface MyClass { void shutdown(); Ice::Context getContext(); }; -["amd"] class MyDerivedClass extends MyClass +["amd"] interface MyDerivedClass extends MyClass { Object* echo(Object* obj); }; diff --git a/python/test/Ice/proxy/TestI.py b/python/test/Ice/proxy/TestI.py index 5ee763ab1ee..3c6be1cba94 100644 --- a/python/test/Ice/proxy/TestI.py +++ b/python/test/Ice/proxy/TestI.py @@ -10,7 +10,7 @@ import Ice, Test import time -class MyDerivedClassI(Test.MyDerivedClass): +class MyDerivedClassI(Test._MyDerivedClassDisp): def __init__(self): self.ctx = None @@ -25,4 +25,4 @@ class MyDerivedClassI(Test.MyDerivedClass): def ice_isA(self, s, current): self.ctx = current.ctx - return Test.MyDerivedClass.ice_isA(self, s, current) + return Test._MyDerivedClassDisp.ice_isA(self, s, current) diff --git a/python/test/Ice/proxy/run.py b/python/test/Ice/proxy/run.py deleted file mode 100755 index 63b57c4f797..00000000000 --- a/python/test/Ice/proxy/run.py +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env python -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -import os, sys - -path = [ ".", "..", "../..", "../../..", "../../../.." ] -head = os.path.dirname(sys.argv[0]) -if len(head) > 0: - path = [os.path.join(head, p) for p in path] -path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ] -if len(path) == 0: - raise RuntimeError("can't find toplevel directory!") -sys.path.append(os.path.join(path[0], "scripts")) -import TestUtil - -print("tests with regular server.") -TestUtil.clientServerTest() -print("tests with AMD server.") -TestUtil.clientServerTest(server="ServerAMD.py") -print("tests with collocated server.") -TestUtil.collocatedTest(" --Ice.ThreadPool.Client.SizeMax=2 --Ice.ThreadPool.Client.SizeWarn=0") diff --git a/python/test/Ice/servantLocator/AllTests.py b/python/test/Ice/servantLocator/AllTests.py index 2c8bcc159a3..55d77d5f43f 100644 --- a/python/test/Ice/servantLocator/AllTests.py +++ b/python/test/Ice/servantLocator/AllTests.py @@ -52,7 +52,7 @@ def testExceptions(obj, collocated): obj.userException() test(False) except Ice.UnknownUserException as ex: - test(ex.unknown.find("Test::TestIntfUserException") >= 0) + test(ex.unknown.find("::Test::TestIntfUserException") >= 0) except Ice.OperationNotExistException: pass except AttributeError: @@ -148,7 +148,7 @@ def allTests(communicator, collocated): obj.ice_ids() test(False) except Ice.UnknownUserException as ex: - test(ex.unknown == "Test::TestIntfUserException") + test(ex.unknown == "::Test::TestIntfUserException") except: test(False) @@ -157,7 +157,7 @@ def allTests(communicator, collocated): obj.ice_ids() test(False) except Ice.UnknownUserException as ex: - test(ex.unknown == "Test::TestIntfUserException") + test(ex.unknown == "::Test::TestIntfUserException") except: test(False) print("ok") diff --git a/python/test/Ice/servantLocator/Collocated.py b/python/test/Ice/servantLocator/Collocated.py index 0f90ca48ef4..41d0c8e9148 100755 --- a/python/test/Ice/servantLocator/Collocated.py +++ b/python/test/Ice/servantLocator/Collocated.py @@ -23,8 +23,8 @@ class TestServer(Ice.Application): #adapter.activate() // Don't activate OA to ensure collocation is used. adapter.addServantLocator(TestI.ServantLocatorI("category"), "category") adapter.addServantLocator(TestI.ServantLocatorI(""), "") - adapter.add(TestI.TestI(), self.communicator().stringToIdentity("asm")) - adapter.add(TestActivationI.TestActivationI(), self.communicator().stringToIdentity("test/activation")) + adapter.add(TestI.TestI(), Ice.stringToIdentity("asm")) + adapter.add(TestActivationI.TestActivationI(), Ice.stringToIdentity("test/activation")) AllTests.allTests(self.communicator(), False) diff --git a/python/test/Ice/servantLocator/Server.py b/python/test/Ice/servantLocator/Server.py index bada31bcabe..12f7d67d846 100755 --- a/python/test/Ice/servantLocator/Server.py +++ b/python/test/Ice/servantLocator/Server.py @@ -22,8 +22,8 @@ class TestServer(Ice.Application): adapter = self.communicator().createObjectAdapter("TestAdapter") adapter.addServantLocator(TestI.ServantLocatorI("category"), "category") adapter.addServantLocator(TestI.ServantLocatorI(""), "") - adapter.add(TestI.TestI(), self.communicator().stringToIdentity("asm")) - adapter.add(TestActivationI.TestActivationI(), self.communicator().stringToIdentity("test/activation")) + adapter.add(TestI.TestI(), Ice.stringToIdentity("asm")) + adapter.add(TestActivationI.TestActivationI(), Ice.stringToIdentity("test/activation")) adapter.activate() adapter.waitForDeactivate() diff --git a/python/test/Ice/servantLocator/ServerAMD.py b/python/test/Ice/servantLocator/ServerAMD.py index f36103f1f64..b29f6f5aa7d 100755 --- a/python/test/Ice/servantLocator/ServerAMD.py +++ b/python/test/Ice/servantLocator/ServerAMD.py @@ -22,8 +22,8 @@ class TestServer(Ice.Application): adapter = self.communicator().createObjectAdapter("TestAdapter") adapter.addServantLocator(TestAMDI.ServantLocatorI("category"), "category") adapter.addServantLocator(TestAMDI.ServantLocatorI(""), "") - adapter.add(TestAMDI.TestI(), self.communicator().stringToIdentity("asm")) - adapter.add(TestActivationAMDI.TestActivationAMDI(), self.communicator().stringToIdentity("test/activation")) + adapter.add(TestAMDI.TestI(), Ice.stringToIdentity("asm")) + adapter.add(TestActivationAMDI.TestActivationAMDI(), Ice.stringToIdentity("test/activation")) adapter.activate() adapter.waitForDeactivate() diff --git a/python/test/Ice/servantLocator/TestAMDI.py b/python/test/Ice/servantLocator/TestAMDI.py index 83394875075..2b53c01863f 100644 --- a/python/test/Ice/servantLocator/TestAMDI.py +++ b/python/test/Ice/servantLocator/TestAMDI.py @@ -14,63 +14,76 @@ def test(b): if not b: raise RuntimeError('test assertion failed') -class TestI(Test.TestIntf): +class TestI(Test._TestIntfDisp): - def requestFailedException_async(self, cb, current=None): - cb.ice_response() + def requestFailedException(self, current=None): + return None - def unknownUserException_async(self, cb, current=None): - cb.ice_response() + def unknownUserException(self, current=None): + return None - def unknownLocalException_async(self, cb, current=None): - cb.ice_response() + def unknownLocalException(self, current=None): + return None - def unknownException_async(self, cb, current=None): - cb.ice_response() + def unknownException(self, current=None): + return None - def localException_async(self, cb, current=None): - cb.ice_response() + def localException(self, current=None): + return None - def userException_async(self, cb, current=None): - cb.ice_response() + def userException(self, current=None): + return None - def pythonException_async(self, cb, current=None): - cb.ice_response() + def pythonException(self, current=None): + return None - def unknownExceptionWithServantException_async(self, cb, current=None): - cb.ice_exception(Ice.ObjectNotExistException()) + def unknownExceptionWithServantException(self, current=None): + f = Ice.Future() + f.set_exception(Ice.ObjectNotExistException()) + return f - def impossibleException_async(self, cb, throw, current=None): + def impossibleException(self, throw, current=None): + f = Ice.Future() if throw: - cb.ice_exception(Test.TestImpossibleException()) + f.set_exception(Test.TestImpossibleException()) else: # # Return a value so we can be sure that the stream position # is reset correctly if finished() throws. # - cb.ice_response("Hello") + f.set_result("Hello") + return f - def intfUserException_async(self, cb, throw, current=None): + def intfUserException(self, throw, current=None): + f = Ice.Future() if throw: - cb.ice_exception(Test.TestIntfUserException()) + f.set_exception(Test.TestIntfUserException()) else: # # Return a value so we can be sure that the stream position # is reset correctly if finished() throws. # - cb.ice_response("Hello") + f.set_result("Hello") + return f - def asyncResponse_async(self, cb, current=None): - cb.ice_response() + def asyncResponse(self, current=None): + # + # We can't do this with futures. + # + #return Ice.Future.completed(None) raise Ice.ObjectNotExistException() - def asyncException_async(self, cb, current=None): - cb.ice_exception(Test.TestIntfUserException()) + def asyncException(self, current=None): + # + # We can't do this with futures. + # + #f = Ice.Future() + #f.set_exception(Test.TestIntfUserException()) + #return f raise Ice.ObjectNotExistException() - def shutdown_async(self, cb, current=None): + def shutdown(self, current=None): current.adapter.deactivate() - cb.ice_response() class CookieI(Test.Cookie): def message(self): diff --git a/python/test/Ice/servantLocator/TestActivationAMDI.py b/python/test/Ice/servantLocator/TestActivationAMDI.py index f5ac04384a6..af47ff448b5 100644 --- a/python/test/Ice/servantLocator/TestActivationAMDI.py +++ b/python/test/Ice/servantLocator/TestActivationAMDI.py @@ -11,7 +11,7 @@ import os, sys, traceback, time import Ice, Test, TestAMDI -class TestActivationAMDI(Test.TestActivation): +class TestActivationAMDI(Test._TestActivationDisp): def activateServantLocator(self, activate, current=None): if(activate): diff --git a/python/test/Ice/servantLocator/TestActivationI.py b/python/test/Ice/servantLocator/TestActivationI.py index 4e795914b79..fc01f072f34 100644 --- a/python/test/Ice/servantLocator/TestActivationI.py +++ b/python/test/Ice/servantLocator/TestActivationI.py @@ -11,7 +11,7 @@ import os, sys, traceback, time import Ice, Test, TestI -class TestActivationI(Test.TestActivation): +class TestActivationI(Test._TestActivationDisp): def activateServantLocator(self, activate, current=None): if activate: diff --git a/python/test/Ice/servantLocator/TestI.py b/python/test/Ice/servantLocator/TestI.py index 6063eb7e288..4b9eb26c0cf 100644 --- a/python/test/Ice/servantLocator/TestI.py +++ b/python/test/Ice/servantLocator/TestI.py @@ -14,7 +14,7 @@ def test(b): if not b: raise RuntimeError('test assertion failed') -class TestI(Test.TestIntf): +class TestI(Test._TestIntfDisp): def requestFailedException(self, current=None): pass diff --git a/python/test/Ice/servantLocator/run.py b/python/test/Ice/servantLocator/run.py deleted file mode 100755 index 63b57c4f797..00000000000 --- a/python/test/Ice/servantLocator/run.py +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env python -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -import os, sys - -path = [ ".", "..", "../..", "../../..", "../../../.." ] -head = os.path.dirname(sys.argv[0]) -if len(head) > 0: - path = [os.path.join(head, p) for p in path] -path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ] -if len(path) == 0: - raise RuntimeError("can't find toplevel directory!") -sys.path.append(os.path.join(path[0], "scripts")) -import TestUtil - -print("tests with regular server.") -TestUtil.clientServerTest() -print("tests with AMD server.") -TestUtil.clientServerTest(server="ServerAMD.py") -print("tests with collocated server.") -TestUtil.collocatedTest(" --Ice.ThreadPool.Client.SizeMax=2 --Ice.ThreadPool.Client.SizeWarn=0") diff --git a/python/test/Ice/slicing/exceptions/AllTests.py b/python/test/Ice/slicing/exceptions/AllTests.py index fbf0828b008..6a8dc126729 100644 --- a/python/test/Ice/slicing/exceptions/AllTests.py +++ b/python/test/Ice/slicing/exceptions/AllTests.py @@ -23,167 +23,173 @@ class CallbackBase: self._cond = threading.Condition() def check(self): - self._cond.acquire() - try: + with self._cond: while not self._called: self._cond.wait() self._called = False - finally: - self._cond.release() def called(self): - self._cond.acquire() - self._called = True - self._cond.notify() - self._cond.release() + with self._cond: + self._called = True + self._cond.notify() class Callback(CallbackBase): - def response(self): - test(False) - - def exception_baseAsBase(self, exc): + def exception_baseAsBase(self, f): try: - raise exc + f.result() + test(False) except Test.Base as b: test(b.b == "Base.b") - test(b.ice_name() =="Test::Base") + test(b.ice_id() == "::Test::Base") except: test(False) self.called() - def exception_unknownDerivedAsBase(self, exc): + def exception_unknownDerivedAsBase(self, f): try: - raise exc + f.result() + test(False) except Test.Base as b: test(b.b == "UnknownDerived.b") - test(b.ice_name() =="Test::Base") + test(b.ice_id() == "::Test::Base") except: test(False) self.called() - def exception_knownDerivedAsBase(self, exc): + def exception_knownDerivedAsBase(self, f): try: - raise exc + f.result() + test(False) except Test.KnownDerived as k: test(k.b == "KnownDerived.b") test(k.kd == "KnownDerived.kd") - test(k.ice_name() =="Test::KnownDerived") + test(k.ice_id() == "::Test::KnownDerived") except: test(False) self.called() - def exception_knownDerivedAsKnownDerived(self, exc): + def exception_knownDerivedAsKnownDerived(self, f): try: - raise exc + f.result() + test(False) except Test.KnownDerived as k: test(k.b == "KnownDerived.b") test(k.kd == "KnownDerived.kd") - test(k.ice_name() =="Test::KnownDerived") + test(k.ice_id() == "::Test::KnownDerived") except: test(False) self.called() - def exception_unknownIntermediateAsBase(self, exc): + def exception_unknownIntermediateAsBase(self, f): try: - raise exc + f.result() + test(False) except Test.Base as b: test(b.b == "UnknownIntermediate.b") - test(b.ice_name() =="Test::Base") + test(b.ice_id() == "::Test::Base") except: test(False) self.called() - def exception_knownIntermediateAsBase(self, exc): + def exception_knownIntermediateAsBase(self, f): try: - raise exc + f.result() + test(False) except Test.KnownIntermediate as ki: test(ki.b == "KnownIntermediate.b") test(ki.ki == "KnownIntermediate.ki") - test(ki.ice_name() =="Test::KnownIntermediate") + test(ki.ice_id() == "::Test::KnownIntermediate") except: test(False) self.called() - def exception_knownMostDerivedAsBase(self, exc): + def exception_knownMostDerivedAsBase(self, f): try: - raise exc + f.result() + test(False) except Test.KnownMostDerived as kmd: test(kmd.b == "KnownMostDerived.b") test(kmd.ki == "KnownMostDerived.ki") test(kmd.kmd == "KnownMostDerived.kmd") - test(kmd.ice_name() =="Test::KnownMostDerived") + test(kmd.ice_id() == "::Test::KnownMostDerived") except: test(False) self.called() - def exception_knownIntermediateAsKnownIntermediate(self, exc): + def exception_knownIntermediateAsKnownIntermediate(self, f): try: - raise exc + f.result() + test(False) except Test.KnownIntermediate as ki: test(ki.b == "KnownIntermediate.b") test(ki.ki == "KnownIntermediate.ki") - test(ki.ice_name() =="Test::KnownIntermediate") + test(ki.ice_id() == "::Test::KnownIntermediate") except: test(False) self.called() - def exception_knownMostDerivedAsKnownMostDerived(self, exc): + def exception_knownMostDerivedAsKnownMostDerived(self, f): try: - raise exc + f.result() + test(False) except Test.KnownMostDerived as kmd: test(kmd.b == "KnownMostDerived.b") test(kmd.ki == "KnownMostDerived.ki") test(kmd.kmd == "KnownMostDerived.kmd") - test(kmd.ice_name() =="Test::KnownMostDerived") + test(kmd.ice_id() == "::Test::KnownMostDerived") except: test(False) self.called() - def exception_knownMostDerivedAsKnownIntermediate(self, exc): + def exception_knownMostDerivedAsKnownIntermediate(self, f): try: - raise exc + f.result() + test(False) except Test.KnownMostDerived as kmd: test(kmd.b == "KnownMostDerived.b") test(kmd.ki == "KnownMostDerived.ki") test(kmd.kmd == "KnownMostDerived.kmd") - test(kmd.ice_name() =="Test::KnownMostDerived") + test(kmd.ice_id() == "::Test::KnownMostDerived") except: test(False) self.called() - def exception_unknownMostDerived1AsBase(self, exc): + def exception_unknownMostDerived1AsBase(self, f): try: - raise exc + f.result() + test(False) except Test.KnownIntermediate as ki: test(ki.b == "UnknownMostDerived1.b") test(ki.ki == "UnknownMostDerived1.ki") - test(ki.ice_name() =="Test::KnownIntermediate") + test(ki.ice_id() == "::Test::KnownIntermediate") except: test(False) self.called() - def exception_unknownMostDerived1AsKnownIntermediate(self, exc): + def exception_unknownMostDerived1AsKnownIntermediate(self, f): try: - raise exc + f.result() + test(False) except Test.KnownIntermediate as ki: test(ki.b == "UnknownMostDerived1.b") test(ki.ki == "UnknownMostDerived1.ki") - test(ki.ice_name() =="Test::KnownIntermediate") + test(ki.ice_id() == "::Test::KnownIntermediate") except: test(False) self.called() - def exception_unknownMostDerived2AsBase(self, exc): + def exception_unknownMostDerived2AsBase(self, f): try: - raise exc + f.result() + test(False) except Test.Base as b: test(b.b == "UnknownMostDerived2.b") - test(b.ice_name() =="Test::Base") + test(b.ice_id() == "::Test::Base") except: test(False) self.called() -class RelayI(Test.Relay): +class RelayI(Test._RelayDisp): def knownPreservedAsBase(self, current=None): ex = Test.KnownPreservedDerived() ex.b = "base" @@ -227,7 +233,7 @@ def allTests(communicator): test(false) except Test.Base as b: test(b.b == "Base.b") - test(b.ice_name() == "Test::Base") + test(b.ice_id() == "::Test::Base") except: test(False) print("ok") @@ -235,7 +241,7 @@ def allTests(communicator): sys.stdout.write("base (AMI)... ") sys.stdout.flush() cb = Callback() - t.begin_baseAsBase(cb.response, cb.exception_baseAsBase) + t.baseAsBaseAsync().add_done_callback(cb.exception_baseAsBase) cb.check() print("ok") @@ -246,7 +252,7 @@ def allTests(communicator): test(false) except Test.Base as b: test(b.b == "UnknownDerived.b") - test(b.ice_name() == "Test::Base") + test(b.ice_id() == "::Test::Base") except: test(False) print("ok") @@ -254,7 +260,7 @@ def allTests(communicator): sys.stdout.write("slicing of unknown derived (AMI)... ") sys.stdout.flush() cb = Callback() - t.begin_unknownDerivedAsBase(cb.response, cb.exception_unknownDerivedAsBase) + t.unknownDerivedAsBaseAsync().add_done_callback(cb.exception_unknownDerivedAsBase) cb.check() print("ok") @@ -266,7 +272,7 @@ def allTests(communicator): except Test.KnownDerived as k: test(k.b == "KnownDerived.b") test(k.kd == "KnownDerived.kd") - test(k.ice_name() == "Test::KnownDerived") + test(k.ice_id() == "::Test::KnownDerived") except: test(False) print("ok") @@ -274,7 +280,7 @@ def allTests(communicator): sys.stdout.write("non-slicing of known derived as base (AMI)... ") sys.stdout.flush() cb = Callback() - t.begin_knownDerivedAsBase(cb.response, cb.exception_knownDerivedAsBase) + t.knownDerivedAsBaseAsync().add_done_callback(cb.exception_knownDerivedAsBase) cb.check() print("ok") @@ -286,7 +292,7 @@ def allTests(communicator): except Test.KnownDerived as k: test(k.b == "KnownDerived.b") test(k.kd == "KnownDerived.kd") - test(k.ice_name() == "Test::KnownDerived") + test(k.ice_id() == "::Test::KnownDerived") except: test(False) print("ok") @@ -294,7 +300,7 @@ def allTests(communicator): sys.stdout.write("non-slicing of known derived as derived (AMI)... ") sys.stdout.flush() cb = Callback() - t.begin_knownDerivedAsKnownDerived(cb.response, cb.exception_knownDerivedAsKnownDerived) + t.knownDerivedAsKnownDerivedAsync().add_done_callback(cb.exception_knownDerivedAsKnownDerived) cb.check() print("ok") @@ -305,7 +311,7 @@ def allTests(communicator): test(false) except Test.Base as b: test(b.b == "UnknownIntermediate.b") - test(b.ice_name() == "Test::Base") + test(b.ice_id() == "::Test::Base") except: test(False) print("ok") @@ -313,7 +319,7 @@ def allTests(communicator): sys.stdout.write("slicing of unknown intermediate as base (AMI)... ") sys.stdout.flush() cb = Callback() - t.begin_unknownIntermediateAsBase(cb.response, cb.exception_unknownIntermediateAsBase) + t.unknownIntermediateAsBaseAsync().add_done_callback(cb.exception_unknownIntermediateAsBase) cb.check() print("ok") @@ -325,7 +331,7 @@ def allTests(communicator): except Test.KnownIntermediate as ki: test(ki.b == "KnownIntermediate.b") test(ki.ki == "KnownIntermediate.ki") - test(ki.ice_name() == "Test::KnownIntermediate") + test(ki.ice_id() == "::Test::KnownIntermediate") except: test(False) print("ok") @@ -333,7 +339,7 @@ def allTests(communicator): sys.stdout.write("slicing of known intermediate as base (AMI)... ") sys.stdout.flush() cb = Callback() - t.begin_knownIntermediateAsBase(cb.response, cb.exception_knownIntermediateAsBase) + t.knownIntermediateAsBaseAsync().add_done_callback(cb.exception_knownIntermediateAsBase) cb.check() print("ok") @@ -346,7 +352,7 @@ def allTests(communicator): test(kmd.b == "KnownMostDerived.b") test(kmd.ki == "KnownMostDerived.ki") test(kmd.kmd == "KnownMostDerived.kmd") - test(kmd.ice_name() == "Test::KnownMostDerived") + test(kmd.ice_id() == "::Test::KnownMostDerived") except: test(False) print("ok") @@ -354,7 +360,7 @@ def allTests(communicator): sys.stdout.write("slicing of known most derived as base (AMI)... ") sys.stdout.flush() cb = Callback() - t.begin_knownMostDerivedAsBase(cb.response, cb.exception_knownMostDerivedAsBase) + t.knownMostDerivedAsBaseAsync().add_done_callback(cb.exception_knownMostDerivedAsBase) cb.check() print("ok") @@ -366,7 +372,7 @@ def allTests(communicator): except Test.KnownIntermediate as ki: test(ki.b == "KnownIntermediate.b") test(ki.ki == "KnownIntermediate.ki") - test(ki.ice_name() == "Test::KnownIntermediate") + test(ki.ice_id() == "::Test::KnownIntermediate") except: test(False) print("ok") @@ -374,7 +380,7 @@ def allTests(communicator): sys.stdout.write("non-slicing of known intermediate as intermediate (AMI)... ") sys.stdout.flush() cb = Callback() - t.begin_knownIntermediateAsKnownIntermediate(cb.response, cb.exception_knownIntermediateAsKnownIntermediate) + t.knownIntermediateAsKnownIntermediateAsync().add_done_callback(cb.exception_knownIntermediateAsKnownIntermediate) cb.check() print("ok") @@ -387,7 +393,7 @@ def allTests(communicator): test(kmd.b == "KnownMostDerived.b") test(kmd.ki == "KnownMostDerived.ki") test(kmd.kmd == "KnownMostDerived.kmd") - test(kmd.ice_name() == "Test::KnownMostDerived") + test(kmd.ice_id() == "::Test::KnownMostDerived") except: test(False) print("ok") @@ -395,7 +401,7 @@ def allTests(communicator): sys.stdout.write("non-slicing of known most derived as intermediate (AMI)... ") sys.stdout.flush() cb = Callback() - t.begin_knownMostDerivedAsKnownIntermediate(cb.response, cb.exception_knownMostDerivedAsKnownIntermediate) + t.knownMostDerivedAsKnownIntermediateAsync().add_done_callback(cb.exception_knownMostDerivedAsKnownIntermediate) cb.check() print("ok") @@ -408,7 +414,7 @@ def allTests(communicator): test(kmd.b == "KnownMostDerived.b") test(kmd.ki == "KnownMostDerived.ki") test(kmd.kmd == "KnownMostDerived.kmd") - test(kmd.ice_name() == "Test::KnownMostDerived") + test(kmd.ice_id() == "::Test::KnownMostDerived") except: test(False) print("ok") @@ -416,7 +422,7 @@ def allTests(communicator): sys.stdout.write("non-slicing of known most derived as most derived (AMI)... ") sys.stdout.flush() cb = Callback() - t.begin_knownMostDerivedAsKnownMostDerived(cb.response, cb.exception_knownMostDerivedAsKnownMostDerived) + t.knownMostDerivedAsKnownMostDerivedAsync().add_done_callback(cb.exception_knownMostDerivedAsKnownMostDerived) cb.check() print("ok") @@ -428,7 +434,7 @@ def allTests(communicator): except Test.KnownIntermediate as ki: test(ki.b == "UnknownMostDerived1.b") test(ki.ki == "UnknownMostDerived1.ki") - test(ki.ice_name() == "Test::KnownIntermediate") + test(ki.ice_id() == "::Test::KnownIntermediate") except: test(False) print("ok") @@ -436,7 +442,7 @@ def allTests(communicator): sys.stdout.write("slicing of unknown most derived, known intermediate as base (AMI)... ") sys.stdout.flush() cb = Callback() - t.begin_unknownMostDerived1AsBase(cb.response, cb.exception_unknownMostDerived1AsBase) + t.unknownMostDerived1AsBaseAsync().add_done_callback(cb.exception_unknownMostDerived1AsBase) cb.check() print("ok") @@ -448,7 +454,7 @@ def allTests(communicator): except Test.KnownIntermediate as ki: test(ki.b == "UnknownMostDerived1.b") test(ki.ki == "UnknownMostDerived1.ki") - test(ki.ice_name() == "Test::KnownIntermediate") + test(ki.ice_id() == "::Test::KnownIntermediate") except: test(False) print("ok") @@ -456,7 +462,8 @@ def allTests(communicator): sys.stdout.write("slicing of unknown most derived, known intermediate as intermediate (AMI)... ") sys.stdout.flush() cb = Callback() - t.begin_unknownMostDerived1AsKnownIntermediate(cb.response, cb.exception_unknownMostDerived1AsKnownIntermediate) + t.unknownMostDerived1AsKnownIntermediateAsync().add_done_callback( + cb.exception_unknownMostDerived1AsKnownIntermediate) cb.check() print("ok") @@ -467,7 +474,7 @@ def allTests(communicator): test(false) except Test.Base as b: test(b.b == "UnknownMostDerived2.b") - test(b.ice_name() == "Test::Base") + test(b.ice_id() == "::Test::Base") except: test(False) print("ok") @@ -475,7 +482,7 @@ def allTests(communicator): sys.stdout.write("slicing of unknown most derived, unknown intermediate as base (AMI)... ") sys.stdout.flush() cb = Callback() - t.begin_unknownMostDerived2AsBase(cb.response, cb.exception_unknownMostDerived2AsBase) + t.unknownMostDerived2AsBaseAsync().add_done_callback(cb.exception_unknownMostDerived2AsBase) cb.check() print("ok") diff --git a/python/test/Ice/slicing/exceptions/Client.py b/python/test/Ice/slicing/exceptions/Client.py index 370ed6305b8..830d6f18148 100755 --- a/python/test/Ice/slicing/exceptions/Client.py +++ b/python/test/Ice/slicing/exceptions/Client.py @@ -18,17 +18,10 @@ def run(args, communicator): return True try: - communicator = Ice.initialize(sys.argv) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/slicing/exceptions/Server.py b/python/test/Ice/slicing/exceptions/Server.py index 383a8c6dea8..223cdb31ebd 100755 --- a/python/test/Ice/slicing/exceptions/Server.py +++ b/python/test/Ice/slicing/exceptions/Server.py @@ -13,7 +13,7 @@ import Ice Ice.loadSlice('-I. --all ServerPrivate.ice') import Test -class TestI(Test.TestIntf): +class TestI(Test._TestIntfDisp): def shutdown(self, current=None): current.adapter.getCommunicator().shutdown() @@ -157,23 +157,16 @@ def run(args, communicator): properties.setProperty("TestAdapter.Endpoints", "default -p 12010 -t 10000") adapter = communicator.createObjectAdapter("TestAdapter") object = TestI() - adapter.add(object, communicator.stringToIdentity("Test")) + adapter.add(object, Ice.stringToIdentity("Test")) adapter.activate() communicator.waitForShutdown() return True try: - communicator = Ice.initialize(sys.argv) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/slicing/exceptions/ServerAMD.py b/python/test/Ice/slicing/exceptions/ServerAMD.py index 9df80030c3f..d398e502e77 100755 --- a/python/test/Ice/slicing/exceptions/ServerAMD.py +++ b/python/test/Ice/slicing/exceptions/ServerAMD.py @@ -14,160 +14,203 @@ import Ice Ice.loadSlice('-I. --all ServerPrivateAMD.ice') import Test -class TestI(Test.TestIntf): - def shutdown_async(self, cb, current=None): +class TestI(Test._TestIntfDisp): + def shutdown(self, current=None): current.adapter.getCommunicator().shutdown() - cb.ice_response() - def baseAsBase_async(self, cb, current=None): + def baseAsBase(self, current=None): b = Test.Base() b.b = "Base.b" - cb.ice_exception(b) + f = Ice.Future() + f.set_exception(b) + return f - def unknownDerivedAsBase_async(self, cb, current=None): + def unknownDerivedAsBase(self, current=None): d = Test.UnknownDerived() d.b = "UnknownDerived.b" d.ud = "UnknownDerived.ud" - cb.ice_exception(d) + f = Ice.Future() + f.set_exception(d) + return f - def knownDerivedAsBase_async(self, cb, current=None): + def knownDerivedAsBase(self, current=None): d = Test.KnownDerived() d.b = "KnownDerived.b" d.kd = "KnownDerived.kd" - cb.ice_exception(d) + f = Ice.Future() + f.set_exception(d) + return f - def knownDerivedAsKnownDerived_async(self, cb, current=None): + def knownDerivedAsKnownDerived(self, current=None): d = Test.KnownDerived() d.b = "KnownDerived.b" d.kd = "KnownDerived.kd" - cb.ice_exception(d) + f = Ice.Future() + f.set_exception(d) + return f - def unknownIntermediateAsBase_async(self, cb, current=None): + def unknownIntermediateAsBase(self, current=None): ui = Test.UnknownIntermediate() ui.b = "UnknownIntermediate.b" ui.ui = "UnknownIntermediate.ui" - cb.ice_exception(ui) + f = Ice.Future() + f.set_exception(ui) + return f - def knownIntermediateAsBase_async(self, cb, current=None): + def knownIntermediateAsBase(self, current=None): ki = Test.KnownIntermediate() ki.b = "KnownIntermediate.b" ki.ki = "KnownIntermediate.ki" - cb.ice_exception(ki) + f = Ice.Future() + f.set_exception(ki) + return f - def knownMostDerivedAsBase_async(self, cb, current=None): + def knownMostDerivedAsBase(self, current=None): kmd = Test.KnownMostDerived() kmd.b = "KnownMostDerived.b" kmd.ki = "KnownMostDerived.ki" kmd.kmd = "KnownMostDerived.kmd" - cb.ice_exception(kmd) + f = Ice.Future() + f.set_exception(kmd) + return f - def knownIntermediateAsKnownIntermediate_async(self, cb, current=None): + def knownIntermediateAsKnownIntermediate(self, current=None): ki = Test.KnownIntermediate() ki.b = "KnownIntermediate.b" ki.ki = "KnownIntermediate.ki" - cb.ice_exception(ki) + f = Ice.Future() + f.set_exception(ki) + return f - def knownMostDerivedAsKnownIntermediate_async(self, cb, current=None): + def knownMostDerivedAsKnownIntermediate(self, current=None): kmd = Test.KnownMostDerived() kmd.b = "KnownMostDerived.b" kmd.ki = "KnownMostDerived.ki" kmd.kmd = "KnownMostDerived.kmd" - cb.ice_exception(kmd) + f = Ice.Future() + f.set_exception(kmd) + return f - def knownMostDerivedAsKnownMostDerived_async(self, cb, current=None): + def knownMostDerivedAsKnownMostDerived(self, current=None): kmd = Test.KnownMostDerived() kmd.b = "KnownMostDerived.b" kmd.ki = "KnownMostDerived.ki" kmd.kmd = "KnownMostDerived.kmd" - cb.ice_exception(kmd) + f = Ice.Future() + f.set_exception(kmd) + return f - def unknownMostDerived1AsBase_async(self, cb, current=None): + def unknownMostDerived1AsBase(self, current=None): umd1 = Test.UnknownMostDerived1() umd1.b = "UnknownMostDerived1.b" umd1.ki = "UnknownMostDerived1.ki" umd1.umd1 = "UnknownMostDerived1.umd1" - cb.ice_exception(umd1) + f = Ice.Future() + f.set_exception(umd1) + return f - def unknownMostDerived1AsKnownIntermediate_async(self, cb, current=None): + def unknownMostDerived1AsKnownIntermediate(self, current=None): umd1 = Test.UnknownMostDerived1() umd1.b = "UnknownMostDerived1.b" umd1.ki = "UnknownMostDerived1.ki" umd1.umd1 = "UnknownMostDerived1.umd1" - cb.ice_exception(umd1) + f = Ice.Future() + f.set_exception(umd1) + return f - def unknownMostDerived2AsBase_async(self, cb, current=None): + def unknownMostDerived2AsBase(self, current=None): umd2 = Test.UnknownMostDerived2() umd2.b = "UnknownMostDerived2.b" umd2.ui = "UnknownMostDerived2.ui" umd2.umd2 = "UnknownMostDerived2.umd2" - cb.ice_exception(umd2) + f = Ice.Future() + f.set_exception(umd2) + return f - def unknownMostDerived2AsBaseCompact_async(self, cb, current=None): + def unknownMostDerived2AsBaseCompact(self, current=None): umd2 = Test.UnknownMostDerived2() umd2.b = "UnknownMostDerived2.b" umd2.ui = "UnknownMostDerived2.ui" umd2.umd2 = "UnknownMostDerived2.umd2" - cb.ice_exception(umd2) + f = Ice.Future() + f.set_exception(umd2) + return f - def knownPreservedAsBase_async(self, cb, r, current=None): + def knownPreservedAsBase(self, r, current=None): ex = Test.KnownPreservedDerived() ex.b = "base" ex.kp = "preserved" ex.kpd = "derived" - cb.ice_exception(ex) + f = Ice.Future() + f.set_exception(ex) + return f - def knownPreservedAsKnownPreserved_async(self, cb, r, current=None): + def knownPreservedAsKnownPreserved(self, r, current=None): ex = Test.KnownPreservedDerived() ex.b = "base" ex.kp = "preserved" ex.kpd = "derived" - cb.ice_exception(ex) + f = Ice.Future() + f.set_exception(ex) + return f - def relayKnownPreservedAsBase_async(self, cb, r, current=None): + def relayKnownPreservedAsBase(self, r, current=None): + f = Ice.Future() try: r.knownPreservedAsBase() test(False) except Ice.Exception as ex: - cb.ice_exception(ex) + f.set_exception(ex) + return f - def relayKnownPreservedAsKnownPreserved_async(self, cb, r, current=None): + def relayKnownPreservedAsKnownPreserved(self, r, current=None): + f = Ice.Future() try: r.knownPreservedAsKnownPreserved() test(False) except Ice.Exception as ex: - cb.ice_exception(ex) + f.set_exception(ex) + return f - def unknownPreservedAsBase_async(self, cb, r, current=None): + def unknownPreservedAsBase(self, r, current=None): ex = Test.SPreserved2() ex.b = "base" ex.kp = "preserved" ex.kpd = "derived" ex.p1 = Test.SPreservedClass("bc", "spc") ex.p2 = ex.p1 - cb.ice_exception(ex) + f = Ice.Future() + f.set_exception(ex) + return f - def unknownPreservedAsKnownPreserved_async(self, cb, r, current=None): + def unknownPreservedAsKnownPreserved(self, r, current=None): ex = Test.SPreserved2() ex.b = "base" ex.kp = "preserved" ex.kpd = "derived" ex.p1 = Test.SPreservedClass("bc", "spc") ex.p2 = ex.p1 - cb.ice_exception(ex) + f = Ice.Future() + f.set_exception(ex) + return f - def relayUnknownPreservedAsBase_async(self, cb, r, current=None): + def relayUnknownPreservedAsBase(self, r, current=None): + f = Ice.Future() try: r.unknownPreservedAsBase() test(False) except Ice.Exception as ex: - cb.ice_exception(ex) + f.set_exception(ex) + return f - def relayUnknownPreservedAsKnownPreserved_async(self, cb, r, current=None): + def relayUnknownPreservedAsKnownPreserved(self, r, current=None): + f = Ice.Future() try: r.unknownPreservedAsKnownPreserved() test(False) except Ice.Exception as ex: - cb.ice_exception(ex) + f.set_exception(ex) + return f def run(args, communicator): properties = communicator.getProperties() @@ -175,23 +218,16 @@ def run(args, communicator): properties.setProperty("TestAdapter.Endpoints", "default -p 12010 -t 10000") adapter = communicator.createObjectAdapter("TestAdapter") object = TestI() - adapter.add(object, communicator.stringToIdentity("Test")) + adapter.add(object, Ice.stringToIdentity("Test")) adapter.activate() communicator.waitForShutdown() return True try: - communicator = Ice.initialize(sys.argv) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/slicing/exceptions/run.py b/python/test/Ice/slicing/exceptions/run.py deleted file mode 100755 index 358f20eb50d..00000000000 --- a/python/test/Ice/slicing/exceptions/run.py +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env python -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -import os, sys - -path = [ ".", "..", "../..", "../../..", "../../../..", "../../../../.." ] -head = os.path.dirname(sys.argv[0]) -if len(head) > 0: - path = [os.path.join(head, p) for p in path] -path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ] -if len(path) == 0: - raise RuntimeError("can't find toplevel directory!") -sys.path.append(os.path.join(path[0], "scripts")) -import TestUtil - -print("Running test with sliced format.") -TestUtil.clientServerTest() - -print("Running test with 1.0 encoding.") -TestUtil.clientServerTest(additionalClientOptions="--Ice.Default.EncodingVersion=1.0", - additionalServerOptions="--Ice.Default.EncodingVersion=1.0") - -print("Running test with sliced format and AMD server.") -TestUtil.clientServerTest(server="ServerAMD.py") - -print("Running test with 1.0 encoding and AMD server.") -TestUtil.clientServerTest(server="ServerAMD.py", - additionalClientOptions="--Ice.Default.EncodingVersion=1.0", - additionalServerOptions="--Ice.Default.EncodingVersion=1.0") diff --git a/python/test/Ice/slicing/objects/AllTests.py b/python/test/Ice/slicing/objects/AllTests.py index 4d4e7d424d4..10c0fd251b9 100644 --- a/python/test/Ice/slicing/objects/AllTests.py +++ b/python/test/Ice/slicing/objects/AllTests.py @@ -10,7 +10,7 @@ import Ice, gc, sys, threading -Ice.loadSlice('-I. --all Forward.ice ClientPrivate.ice') +Ice.loadSlice('-I. --all ClientPrivate.ice') import Test def test(b): @@ -23,22 +23,19 @@ class CallbackBase: self._cond = threading.Condition() def check(self): - self._cond.acquire() - try: + with self._cond: while not self._called: self._cond.wait() self._called = False - finally: - self._cond.release() def called(self): - self._cond.acquire() - self._called = True - self._cond.notify() - self._cond.release() + with self._cond: + self._called = True + self._cond.notify() class Callback(CallbackBase): - def response_SBaseAsObject(self, o): + def response_SBaseAsObject(self, f): + o = f.result() test(o) test(o.ice_id() == "::Test::SBase") sb = o @@ -46,54 +43,53 @@ class Callback(CallbackBase): test(sb.sb == "SBase.sb") self.called() - def response_SBaseAsSBase(self, sb): + def response_SBaseAsSBase(self, f): + sb = f.result() test(sb.sb == "SBase.sb") self.called() - def response_SBSKnownDerivedAsSBase(self, sb): - sbskd = sb + def response_SBSKnownDerivedAsSBase(self, f): + sbskd = f.result() test(isinstance(sbskd, Test.SBSKnownDerived)) test(sbskd.sbskd == "SBSKnownDerived.sbskd") self.called() - def response_SBSKnownDerivedAsSBSKnownDerived(self, sbskd): + def response_SBSKnownDerivedAsSBSKnownDerived(self, f): + sbskd = f.result() test(sbskd.sbskd == "SBSKnownDerived.sbskd") self.called() - def response_SBSUnknownDerivedAsSBase(self, sb): + def response_SBSUnknownDerivedAsSBase(self, f): + sb = f.result() test(sb.sb == "SBSUnknownDerived.sb") self.called() - def response_SBSUnknownDerivedAsSBaseCompact(self, sb): - test(False) - - def exception_SBSUnknownDerivedAsSBaseCompact(self, ex): - test(isinstance(ex, Ice.NoObjectFactoryException)) + def exception_SBSUnknownDerivedAsSBaseCompact(self, f): + test(f.exception() is not None) + test(isinstance(f.exception(), Ice.NoValueFactoryException)) self.called() - def response_SUnknownAsObject10(self, o): - test(False) - - def exception_SUnknownAsObject10(self, exc): - test(exc.ice_name() == "Ice::NoObjectFactoryException") + def exception_SUnknownAsObject10(self, f): + test(f.exception() is not None) + test(f.exception().ice_id() == "::Ice::NoValueFactoryException") self.called() - def response_SUnknownAsObject11(self, o): - test(isinstance(o, Ice.UnknownSlicedObject)) + def response_SUnknownAsObject11(self, f): + o = f.result() + test(isinstance(o, Ice.UnknownSlicedValue)) test(o.unknownTypeId == "::Test::SUnknown") self.called() - def exception_SUnknownAsObject11(self, exc): - test(False) - - def response_oneElementCycle(self, b): + def response_oneElementCycle(self, f): + b = f.result() test(b) test(b.ice_id() == "::Test::B") test(b.sb == "B1.sb") test(b.pb == b) self.called() - def response_twoElementCycle(self, b1): + def response_twoElementCycle(self, f): + b1 = f.result() test(b1) test(b1.ice_id() == "::Test::B") test(b1.sb == "B1.sb") @@ -105,7 +101,8 @@ class Callback(CallbackBase): test(b2.pb == b1) self.called() - def response_D1AsB(self, b1): + def response_D1AsB(self, f): + b1 = f.result() test(b1) test(b1.ice_id() == "::Test::D1") test(b1.sb == "D1.sb") @@ -125,7 +122,8 @@ class Callback(CallbackBase): test(b2.ice_id() == "::Test::B") self.called() - def response_D1AsD1(self, d1): + def response_D1AsD1(self, f): + d1 = f.result() test(d1) test(d1.ice_id() == "::Test::D1") test(d1.sb == "D1.sb") @@ -139,7 +137,8 @@ class Callback(CallbackBase): test(b2.pb == d1) self.called() - def response_D2AsB(self, b2): + def response_D2AsB(self, f): + b2 = f.result() test(b2) test(b2.ice_id() == "::Test::B") test(b2.sb == "D2.sb") @@ -157,7 +156,8 @@ class Callback(CallbackBase): test(d1.pd1 == b2) self.called() - def response_paramTest1(self, b1, b2): + def response_paramTest1(self, f): + (b1, b2) = f.result() test(b1) test(b1.ice_id() == "::Test::D1") test(b1.sb == "D1.sb") @@ -173,19 +173,23 @@ class Callback(CallbackBase): test(b2.pb == b1) self.called() - def response_returnTest1(self, r, p1, p2): + def response_returnTest1(self, f): + (r, p1, p2) = f.result() test(r == p1) self.called() - def response_returnTest2(self, r, p1, p2): + def response_returnTest2(self, f): + (r, p1, p2) = f.result() test(r == p1) self.called() - def response_returnTest3(self, b): + def response_returnTest3(self, f): + b = f.result() self.r = b self.called() - def response_paramTest3(self, ret, p1, p2): + def response_paramTest3(self, f): + (ret, p1, p2) = f.result() test(p1) test(p1.sb == "D2.sb (p1 1)") test(p1.pb == None) @@ -202,7 +206,8 @@ class Callback(CallbackBase): test(ret.ice_id() == "::Test::D1") self.called() - def response_paramTest4(self, ret, b): + def response_paramTest4(self, f): + (ret, b) = f.result() test(b) test(b.sb == "D4.sb (1)") test(b.pb == None) @@ -214,17 +219,21 @@ class Callback(CallbackBase): test(ret.ice_id() == "::Test::B") self.called() - def response_sequenceTest(self, ss): + def response_sequenceTest(self, f): + ss = f.result() self.r = ss self.called() - def response_dictionaryTest(self, r, bout): + def response_dictionaryTest(self, f): + (r, bout) = f.result() self.r = r self.bout = bout self.called() - def exception_throwBaseAsBase(self, ex): - test(ex.ice_name() == "Test::BaseException") + def exception_throwBaseAsBase(self, f): + ex = f.exception() + test(ex is not None) + test(ex.ice_id() == "::Test::BaseException") e = ex test(isinstance(e, Test.BaseException)) test(e.sbe == "sbe") @@ -233,8 +242,10 @@ class Callback(CallbackBase): test(e.pb.pb == e.pb) self.called() - def exception_throwDerivedAsBase(self, ex): - test(ex.ice_name() == "Test::DerivedException") + def exception_throwDerivedAsBase(self, f): + ex = f.exception() + test(ex is not None) + test(ex.ice_id() == "::Test::DerivedException") e = ex test(isinstance(e, Test.DerivedException)) test(e.sbe == "sbe") @@ -249,8 +260,10 @@ class Callback(CallbackBase): test(e.pd1.pd1 == e.pd1) self.called() - def exception_throwDerivedAsDerived(self, ex): - test(ex.ice_name() == "Test::DerivedException") + def exception_throwDerivedAsDerived(self, f): + ex = f.exception() + test(ex is not None) + test(ex.ice_id() == "::Test::DerivedException") e = ex test(isinstance(e, Test.DerivedException)) test(e.sbe == "sbe") @@ -265,8 +278,10 @@ class Callback(CallbackBase): test(e.pd1.pd1 == e.pd1) self.called() - def exception_throwUnknownDerivedAsBase(self, ex): - test(ex.ice_name() == "Test::BaseException") + def exception_throwUnknownDerivedAsBase(self, f): + ex = f.exception() + test(ex is not None) + test(ex.ice_id() == "::Test::BaseException") e = ex test(isinstance(e, Test.BaseException)) test(e.sbe == "sbe") @@ -276,10 +291,12 @@ class Callback(CallbackBase): self.called() def response_useForward(self, f): - test(f) + fwd = f.result() + test(fwd) self.called() - def response_preserved1(self, r): + def response_preserved1(self, f): + r = f.result() test(r) test(isinstance(r, Test.PDerived)) test(r.pi == 3) @@ -287,30 +304,34 @@ class Callback(CallbackBase): test(r.pb == r) self.called() - def response_preserved2(self, r): + def response_preserved2(self, f): + r = f.result() test(r) test(not isinstance(r, Test.PCUnknown)) test(r.pi == 3) self.called() - def response_preserved3(self, r): + def response_preserved3(self, f): # # Encoding 1.0 # + r = f.result() test(not isinstance(r, Test.PCDerived)) test(r.pi == 3) self.called() - def response_preserved4(self, r): + def response_preserved4(self, f): # # Encoding > 1.0 # + r = f.result() test(isinstance(r, Test.PCDerived)) test(r.pi == 3) test(r.pbs[0] == r) self.called() - def response_preserved5(self, r): + def response_preserved5(self, f): + r = f.result() test(isinstance(r, Test.PCDerived3)) test(r.pi == 3) for i in range(0, 300): @@ -324,32 +345,25 @@ class Callback(CallbackBase): test(r.pcd3 == r.pbs[10]) self.called() - def response_compactPreserved1(self, r): + def response_compactPreserved1(self, f): # # Encoding 1.0 # + r = f.result() test(not isinstance(r, Test.CompactPCDerived)) test(r.pi == 3) self.called() - def response_compactPreserved2(self, r): + def response_compactPreserved2(self, f): # # Encoding > 1.0 # + r = f.result() test(isinstance(r, Test.CompactPCDerived)) test(r.pi == 3) test(r.pbs[0] == r) self.called() - def response(self): - test(False) - - def exception(self, exc): - if(isinstance(exc, Ice.OperationNotExistException)): - self.called() - return - test(False) - class PNodeI(Test.PNode): counter = 0 @@ -359,14 +373,10 @@ class PNodeI(Test.PNode): def __del__(self): PNodeI.counter = PNodeI.counter - 1 -class NodeFactoryI(Ice.ObjectFactory): - def create(self, id): - if id == Test.PNode.ice_staticId(): - return PNodeI() - return None - - def destroy(self): - pass +def NodeFactoryI(id): + if id == Test.PNode.ice_staticId(): + return PNodeI() + return None class PreservedI(Test.Preserved): counter = 0 @@ -377,14 +387,10 @@ class PreservedI(Test.Preserved): def __del__(self): PreservedI.counter = PreservedI.counter - 1 -class PreservedFactoryI(Ice.ObjectFactory): - def create(self, id): - if id == Test.Preserved.ice_staticId(): - return PreservedI() - return None - - def destroy(self): - pass +def PreservedFactoryI(id): + if id == Test.Preserved.ice_staticId(): + return PreservedI() + return None def allTests(communicator): obj = communicator.stringToProxy("Test:default -p 12010") @@ -408,7 +414,7 @@ def allTests(communicator): sys.stdout.write("base as Object (AMI)... ") sys.stdout.flush() cb = Callback() - t.begin_SBaseAsObject(cb.response_SBaseAsObject, cb.exception) + t.SBaseAsObjectAsync().add_done_callback(cb.response_SBaseAsObject) cb.check() print("ok") @@ -424,7 +430,7 @@ def allTests(communicator): sys.stdout.write("base as base (AMI)... ") sys.stdout.flush() cb = Callback() - t.begin_SBaseAsSBase(cb.response_SBaseAsSBase, cb.exception) + t.SBaseAsSBaseAsync().add_done_callback(cb.response_SBaseAsSBase) cb.check() print("ok") @@ -444,7 +450,7 @@ def allTests(communicator): sys.stdout.write("base with known derived as base (AMI)... ") sys.stdout.flush() cb = Callback() - t.begin_SBSKnownDerivedAsSBase(cb.response_SBSKnownDerivedAsSBase, cb.exception) + t.SBSKnownDerivedAsSBaseAsync().add_done_callback(cb.response_SBSKnownDerivedAsSBase) cb.check() print("ok") @@ -460,7 +466,7 @@ def allTests(communicator): sys.stdout.write("base with known derived as known derived (AMI)... ") sys.stdout.flush() cb = Callback() - t.begin_SBSKnownDerivedAsSBSKnownDerived(cb.response_SBSKnownDerivedAsSBSKnownDerived, cb.exception) + t.SBSKnownDerivedAsSBSKnownDerivedAsync().add_done_callback(cb.response_SBSKnownDerivedAsSBSKnownDerived) cb.check() print("ok") @@ -492,7 +498,7 @@ def allTests(communicator): test(False) except Ice.OperationNotExistException: pass - except Ice.NoObjectFactoryException: + except Ice.NoValueFactoryException: # Expected. pass except: @@ -502,14 +508,14 @@ def allTests(communicator): sys.stdout.write("base with unknown derived as base (AMI)... ") sys.stdout.flush() cb = Callback() - t.begin_SBSUnknownDerivedAsSBase(cb.response_SBSUnknownDerivedAsSBase, cb.exception) + t.SBSUnknownDerivedAsSBaseAsync().add_done_callback(cb.response_SBSUnknownDerivedAsSBase) cb.check() if t.ice_getEncodingVersion() == Ice.Encoding_1_0: # # This test succeeds for the 1.0 encoding. # cb = Callback() - t.begin_SBSUnknownDerivedAsSBaseCompact(cb.response_SBSUnknownDerivedAsSBase, cb.exception) + t.SBSUnknownDerivedAsSBaseCompactAsync().add_done_callback(cb.response_SBSUnknownDerivedAsSBase) cb.check() else: # @@ -517,8 +523,7 @@ def allTests(communicator): # be sliced to a known type. # cb = Callback() - t.begin_SBSUnknownDerivedAsSBaseCompact(cb.response_SBSUnknownDerivedAsSBaseCompact, - cb.exception_SBSUnknownDerivedAsSBaseCompact) + t.SBSUnknownDerivedAsSBaseCompactAsync().add_done_callback(cb.exception_SBSUnknownDerivedAsSBaseCompact) cb.check() print("ok") @@ -527,10 +532,10 @@ def allTests(communicator): try: o = t.SUnknownAsObject() test(t.ice_getEncodingVersion() != Ice.Encoding_1_0) - test(isinstance(o, Ice.UnknownSlicedObject)) + test(isinstance(o, Ice.UnknownSlicedValue)) test(o.unknownTypeId == "::Test::SUnknown") t.checkSUnknown(o) - except Ice.NoObjectFactoryException: + except Ice.NoValueFactoryException: test(t.ice_getEncodingVersion() == Ice.Encoding_1_0) except Ice.Exception: test(False) @@ -541,9 +546,9 @@ def allTests(communicator): try: cb = Callback() if t.ice_getEncodingVersion() == Ice.Encoding_1_0: - t.begin_SUnknownAsObject(cb.response_SUnknownAsObject10, cb.exception_SUnknownAsObject10) + t.SUnknownAsObjectAsync().add_done_callback(cb.exception_SUnknownAsObject10) else: - t.begin_SUnknownAsObject(cb.response_SUnknownAsObject11, cb.exception_SUnknownAsObject11) + t.SUnknownAsObjectAsync().add_done_callback(cb.response_SUnknownAsObject11) cb.check() except Ice.Exception: test(False) @@ -564,7 +569,7 @@ def allTests(communicator): sys.stdout.write("one-element cycle (AMI)... ") sys.stdout.flush() cb = Callback() - t.begin_oneElementCycle(cb.response_oneElementCycle, cb.exception) + t.oneElementCycleAsync().add_done_callback(cb.response_oneElementCycle) cb.check() print("ok") @@ -588,7 +593,7 @@ def allTests(communicator): sys.stdout.write("two-element cycle (AMI)... ") sys.stdout.flush() cb = Callback() - t.begin_twoElementCycle(cb.response_twoElementCycle, cb.exception) + t.twoElementCycleAsync().add_done_callback(cb.response_twoElementCycle) cb.check() print("ok") @@ -620,7 +625,7 @@ def allTests(communicator): sys.stdout.write("known derived pointer slicing as base (AMI)... ") sys.stdout.flush() cb = Callback() - t.begin_D1AsB(cb.response_D1AsB, cb.exception) + t.D1AsBAsync().add_done_callback(cb.response_D1AsB) cb.check() print("ok") @@ -646,7 +651,7 @@ def allTests(communicator): sys.stdout.write("known derived pointer slicing as derived (AMI)... ") sys.stdout.flush() cb = Callback() - t.begin_D1AsD1(cb.response_D1AsD1, cb.exception) + t.D1AsD1Async().add_done_callback(cb.response_D1AsD1) cb.check() print("ok") @@ -676,7 +681,7 @@ def allTests(communicator): sys.stdout.write("unknown derived pointer slicing as base (AMI)... ") sys.stdout.flush() cb = Callback() - t.begin_D2AsB(cb.response_D2AsB, cb.exception) + t.D2AsBAsync().add_done_callback(cb.response_D2AsB) cb.check() print("ok") @@ -705,7 +710,7 @@ def allTests(communicator): sys.stdout.write("param ptr slicing with known first (AMI)... ") sys.stdout.flush() cb = Callback() - t.begin_paramTest1(cb.response_paramTest1, cb.exception) + t.paramTest1Async().add_done_callback(cb.response_paramTest1) cb.check() print("ok") @@ -743,7 +748,7 @@ def allTests(communicator): sys.stdout.write("return value identity with known first (AMI)... ") sys.stdout.flush() cb = Callback() - t.begin_returnTest1(cb.response_returnTest1, cb.exception) + t.returnTest1Async().add_done_callback(cb.response_returnTest1) cb.check() print("ok") @@ -759,7 +764,7 @@ def allTests(communicator): sys.stdout.write("return value identity with unknown first (AMI)... ") sys.stdout.flush() cb = Callback() - t.begin_returnTest2(cb.response_returnTest2, cb.exception) + t.returnTest2Async().add_done_callback(cb.response_returnTest2) cb.check() print("ok") @@ -818,7 +823,7 @@ def allTests(communicator): d1.pd1 = d3 cb = Callback() - t.begin_returnTest3(d1, d3, cb.response_returnTest3, cb.exception) + t.returnTest3Async(d1, d3).add_done_callback(cb.response_returnTest3) cb.check() b1 = cb.r @@ -901,7 +906,7 @@ def allTests(communicator): d1.pd1 = d3 cb = Callback() - t.begin_returnTest3(d3, d1, cb.response_returnTest3, cb.exception) + t.returnTest3Async(d3, d1).add_done_callback(cb.response_returnTest3) cb.check() b1 = cb.r @@ -955,7 +960,7 @@ def allTests(communicator): sys.stdout.write("remainder unmarshaling (3 instances) (AMI)... ") sys.stdout.flush() cb = Callback() - t.begin_paramTest3(cb.response_paramTest3, cb.exception) + t.paramTest3Async().add_done_callback(cb.response_paramTest3) cb.check() print("ok") @@ -980,7 +985,7 @@ def allTests(communicator): sys.stdout.write("remainder unmarshaling (4 instances) (AMI)... ") sys.stdout.flush() cb = Callback() - t.begin_paramTest4(cb.response_paramTest4, cb.exception) + t.paramTest4Async().add_done_callback(cb.response_paramTest4) cb.check() print("ok") @@ -1029,7 +1034,7 @@ def allTests(communicator): b2.pb = b1 cb = Callback() - t.begin_returnTest3(d3, b2, cb.response_returnTest3, cb.exception) + t.returnTest3Async(d3, b2).add_done_callback(cb.response_returnTest3) cb.check() r = cb.r @@ -1093,7 +1098,7 @@ def allTests(communicator): d12.pd1 = d11 cb = Callback() - t.begin_returnTest3(d3, d12, cb.response_returnTest3, cb.exception) + t.returnTest3Async(d3, d12).add_done_callback(cb.response_returnTest3) cb.check() r = cb.r @@ -1226,7 +1231,7 @@ def allTests(communicator): ss2.s = (ss2b, ss2d1, ss2d3) cb = Callback() - t.begin_sequenceTest(ss1, ss2, cb.response_sequenceTest, cb.exception) + t.sequenceTestAsync(ss1, ss2).add_done_callback(cb.response_sequenceTest) cb.check() ss = cb.r @@ -1318,7 +1323,7 @@ def allTests(communicator): bin[i] = d1 cb = Callback() - t.begin_dictionaryTest(bin, cb.response_dictionaryTest, cb.exception) + t.dictionaryTestAsync(bin).add_done_callback(cb.response_dictionaryTest) cb.check() bout = cb.bout r = cb.r @@ -1358,7 +1363,7 @@ def allTests(communicator): t.throwBaseAsBase() test(False) except Test.BaseException as e: - test(e.ice_name() == "Test::BaseException") + test(e.ice_id() == "::Test::BaseException") test(e.sbe == "sbe") test(e.pb) test(e.pb.sb == "sb") @@ -1370,7 +1375,7 @@ def allTests(communicator): sys.stdout.write("base exception thrown as base exception (AMI)... ") sys.stdout.flush() cb = Callback() - t.begin_throwBaseAsBase(cb.response, cb.exception_throwBaseAsBase) + t.throwBaseAsBaseAsync().add_done_callback(cb.exception_throwBaseAsBase) cb.check() print("ok") @@ -1380,7 +1385,7 @@ def allTests(communicator): t.throwDerivedAsBase() test(False) except Test.DerivedException as e: - test(e.ice_name() == "Test::DerivedException") + test(e.ice_id() == "::Test::DerivedException") test(e.sbe == "sbe") test(e.pb) test(e.pb.sb == "sb1") @@ -1398,7 +1403,7 @@ def allTests(communicator): sys.stdout.write("derived exception thrown as base exception (AMI)... ") sys.stdout.flush() cb = Callback() - t.begin_throwDerivedAsBase(cb.response, cb.exception_throwDerivedAsBase) + t.throwDerivedAsBaseAsync().add_done_callback(cb.exception_throwDerivedAsBase) cb.check() print("ok") @@ -1408,7 +1413,7 @@ def allTests(communicator): t.throwDerivedAsDerived() test(False) except Test.DerivedException as e: - test(e.ice_name() == "Test::DerivedException") + test(e.ice_id() == "::Test::DerivedException") test(e.sbe == "sbe") test(e.pb) test(e.pb.sb == "sb1") @@ -1426,7 +1431,7 @@ def allTests(communicator): sys.stdout.write("derived exception thrown as derived exception (AMI)... ") sys.stdout.flush() cb = Callback() - t.begin_throwDerivedAsDerived(cb.response, cb.exception_throwDerivedAsDerived) + t.throwDerivedAsDerivedAsync().add_done_callback(cb.exception_throwDerivedAsDerived) cb.check() print("ok") @@ -1436,7 +1441,7 @@ def allTests(communicator): t.throwUnknownDerivedAsBase() test(False) except Test.BaseException as e: - test(e.ice_name() == "Test::BaseException") + test(e.ice_id() == "::Test::BaseException") test(e.sbe == "sbe") test(e.pb) test(e.pb.sb == "sb d2") @@ -1448,7 +1453,7 @@ def allTests(communicator): sys.stdout.write("unknown derived exception thrown as base exception (AMI)... ") sys.stdout.flush() cb = Callback() - t.begin_throwUnknownDerivedAsBase(cb.response, cb.exception_throwUnknownDerivedAsBase) + t.throwUnknownDerivedAsBaseAsync().add_done_callback(cb.exception_throwUnknownDerivedAsBase) cb.check() print("ok") @@ -1464,7 +1469,7 @@ def allTests(communicator): sys.stdout.write("forward-declared class (AMI)... ") sys.stdout.flush() cb = Callback() - t.begin_useForward(cb.response_useForward, cb.exception) + t.useForwardAsync().add_done_callback(cb.response_useForward) cb.check() print("ok") @@ -1579,7 +1584,7 @@ def allTests(communicator): t.ice_encodingVersion(Ice.Encoding_1_0).checkPBSUnknown(p) except Ice.OperationNotExistException: pass - + print("ok") sys.stdout.write("preserved classes (AMI)... ") @@ -1594,7 +1599,7 @@ def allTests(communicator): pd.pb = pd cb = Callback() - t.begin_exchangePBase(pd, cb.response_preserved1, cb.exception) + t.exchangePBaseAsync(pd).add_done_callback(cb.response_preserved1) cb.check() # @@ -1605,7 +1610,7 @@ def allTests(communicator): pu.pu = "preserved" cb = Callback() - t.begin_exchangePBase(pu, cb.response_preserved2, cb.exception) + t.exchangePBaseAsync(pu).add_done_callback(cb.response_preserved2) cb.check() # @@ -1618,9 +1623,9 @@ def allTests(communicator): cb = Callback() if t.ice_getEncodingVersion() == Ice.Encoding_1_0: - t.begin_exchangePBase(pcd, cb.response_preserved3, cb.exception) + t.exchangePBaseAsync(pcd).add_done_callback(cb.response_preserved3) else: - t.begin_exchangePBase(pcd, cb.response_preserved4, cb.exception) + t.exchangePBaseAsync(pcd).add_done_callback(cb.response_preserved4) cb.check() # @@ -1633,9 +1638,9 @@ def allTests(communicator): cb = Callback() if t.ice_getEncodingVersion() == Ice.Encoding_1_0: - t.begin_exchangePBase(pcd, cb.response_compactPreserved1, cb.exception) + t.exchangePBaseAsync(pcd).add_done_callback(cb.response_compactPreserved1) else: - t.begin_exchangePBase(pcd, cb.response_compactPreserved2, cb.exception) + t.exchangePBaseAsync(pcd).add_done_callback(cb.response_compactPreserved2) cb.check() # @@ -1659,9 +1664,9 @@ def allTests(communicator): cb = Callback() if t.ice_getEncodingVersion() == Ice.Encoding_1_0: - t.begin_exchangePBase(pcd, cb.response_preserved3, cb.exception) + t.exchangePBaseAsync(pcd).add_done_callback(cb.response_preserved3) else: - t.begin_exchangePBase(pcd, cb.response_preserved5, cb.exception) + t.exchangePBaseAsync(pcd).add_done_callback(cb.response_preserved5) cb.check() print("ok") @@ -1674,7 +1679,7 @@ def allTests(communicator): # UCNode. This provides an easy way to determine how many # unmarshaled instances currently exist. # - communicator.addObjectFactory(NodeFactoryI(), Test.PNode.ice_staticId()) + communicator.getValueFactoryManager().add(NodeFactoryI, Test.PNode.ice_staticId()) # # Relay a graph through the server. This test uses a preserved class @@ -1761,7 +1766,7 @@ def allTests(communicator): # Preserved. This provides an easy way to determine how many # unmarshaled instances currently exist. # - communicator.addObjectFactory(PreservedFactoryI(), Test.Preserved.ice_staticId()) + communicator.getValueFactoryManager().add(PreservedFactoryI, Test.Preserved.ice_staticId()) # # Obtain a preserved object from the server where the most-derived diff --git a/python/test/Ice/slicing/objects/Client.py b/python/test/Ice/slicing/objects/Client.py index 370ed6305b8..830d6f18148 100755 --- a/python/test/Ice/slicing/objects/Client.py +++ b/python/test/Ice/slicing/objects/Client.py @@ -18,17 +18,10 @@ def run(args, communicator): return True try: - communicator = Ice.initialize(sys.argv) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/slicing/objects/Forward.ice b/python/test/Ice/slicing/objects/Forward.ice deleted file mode 100644 index 1654e5f10ae..00000000000 --- a/python/test/Ice/slicing/objects/Forward.ice +++ /dev/null @@ -1,27 +0,0 @@ -// ********************************************************************** -// -// Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -// -// This copy of Ice is licensed to you under the terms described in the -// ICE_LICENSE file included in this distribution. -// -// ********************************************************************** - -#pragma once - -module Test -{ - -class Forward; - -class Hidden -{ - Forward f; -}; - -class Forward -{ - Hidden h; -}; - -}; diff --git a/python/test/Ice/slicing/objects/Server.py b/python/test/Ice/slicing/objects/Server.py index 8dec2d3461e..b1780ef5881 100755 --- a/python/test/Ice/slicing/objects/Server.py +++ b/python/test/Ice/slicing/objects/Server.py @@ -11,14 +11,14 @@ import os, sys, traceback import Ice -Ice.loadSlice('-I. --all ServerPrivate.ice Forward.ice') +Ice.loadSlice('-I. --all ServerPrivate.ice') import Test def test(b): if not b: raise RuntimeError('test assertion failed') -class TestI(Test.TestIntf): +class TestI(Test._TestIntfDisp): def SBaseAsObject(self, current=None): sb = Test.SBase() sb.sb = "SBase.sb" @@ -244,7 +244,7 @@ class TestI(Test.TestIntf): test(p.psu == "unknown") test(not p.graph) - def PBSUnknownAsPreservedWithGraph_async(self, cb, current=None): + def PBSUnknownAsPreservedWithGraph(self, current=None): r = Test.PSUnknown() r.pi = 5 r.ps = "preserved" @@ -253,8 +253,8 @@ class TestI(Test.TestIntf): r.graph.next = Test.PNode() r.graph.next.next = Test.PNode() r.graph.next.next.next = r.graph - cb.ice_response(r) - r.graph.next.next.next = None # Break the cycle. + return Ice.Future.completed(r) + #r.graph.next.next.next = None # Break the cycle. def checkPBSUnknownWithGraph(self, p, current=None): if current.encoding == Ice.Encoding_1_0: @@ -271,13 +271,13 @@ class TestI(Test.TestIntf): test(p.graph.next.next.next == p.graph) p.graph.next.next.next = None # Break the cycle. - def PBSUnknown2AsPreservedWithGraph_async(self, cb, current=None): + def PBSUnknown2AsPreservedWithGraph(self, current=None): r = Test.PSUnknown2() r.pi = 5 r.ps = "preserved" r.pb = r - cb.ice_response(r) - r.pb = None # Break the cycle. + return Ice.Future.completed(r) + #r.pb = None # Break the cycle. def checkPBSUnknown2WithGraph(self, p, current=None): if current.encoding == Ice.Encoding_1_0: @@ -344,14 +344,16 @@ class TestI(Test.TestIntf): ude.pd2 = d2 raise ude - def throwPreservedException_async(self, cb, current=None): + def throwPreservedException(self, current=None): ue = Test.PSUnknownException() ue.p = Test.PSUnknown2() ue.p.pi = 5 ue.p.ps = "preserved" ue.p.pb = ue.p - cb.ice_exception(ue) - ue.p.pb = None # Break the cycle. + f = Ice.Future() + f.set_exception(ue) + return f + #ue.p.pb = None # Break the cycle. def useForward(self, current=None): f = Test.Forward() @@ -368,23 +370,16 @@ def run(args, communicator): properties.setProperty("TestAdapter.Endpoints", "default -p 12010 -t 10000") adapter = communicator.createObjectAdapter("TestAdapter") object = TestI() - adapter.add(object, communicator.stringToIdentity("Test")) + adapter.add(object, Ice.stringToIdentity("Test")) adapter.activate() communicator.waitForShutdown() return True try: - communicator = Ice.initialize(sys.argv) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/slicing/objects/ServerAMD.py b/python/test/Ice/slicing/objects/ServerAMD.py index 11410253a14..f64a6f13af9 100755 --- a/python/test/Ice/slicing/objects/ServerAMD.py +++ b/python/test/Ice/slicing/objects/ServerAMD.py @@ -11,77 +11,77 @@ import os, sys, traceback import Ice -Ice.loadSlice('-I. --all ServerPrivateAMD.ice Forward.ice') +Ice.loadSlice('-I. --all ServerPrivateAMD.ice') import Test def test(b): if not b: raise RuntimeError('test assertion failed') -class TestI(Test.TestIntf): - def SBaseAsObject_async(self, cb, current=None): +class TestI(Test._TestIntfDisp): + def SBaseAsObject(self, current=None): sb = Test.SBase() sb.sb = "SBase.sb" - cb.ice_response(sb) + return Ice.Future.completed(sb) - def SBaseAsSBase_async(self, cb, current=None): + def SBaseAsSBase(self, current=None): sb = Test.SBase() sb.sb = "SBase.sb" - cb.ice_response(sb) + return Ice.Future.completed(sb) - def SBSKnownDerivedAsSBase_async(self, cb, current=None): + def SBSKnownDerivedAsSBase(self, current=None): sbskd = Test.SBSKnownDerived() sbskd.sb = "SBSKnownDerived.sb" sbskd.sbskd = "SBSKnownDerived.sbskd" - cb.ice_response(sbskd) + return Ice.Future.completed(sbskd) - def SBSKnownDerivedAsSBSKnownDerived_async(self, cb, current=None): + def SBSKnownDerivedAsSBSKnownDerived(self, current=None): sbskd = Test.SBSKnownDerived() sbskd.sb = "SBSKnownDerived.sb" sbskd.sbskd = "SBSKnownDerived.sbskd" - cb.ice_response(sbskd) + return Ice.Future.completed(sbskd) - def SBSUnknownDerivedAsSBase_async(self, cb, current=None): + def SBSUnknownDerivedAsSBase(self, current=None): sbsud = Test.SBSUnknownDerived() sbsud.sb = "SBSUnknownDerived.sb" sbsud.sbsud = "SBSUnknownDerived.sbsud" - cb.ice_response(sbsud) + return Ice.Future.completed(sbsud) - def SBSUnknownDerivedAsSBaseCompact_async(self, cb, current=None): + def SBSUnknownDerivedAsSBaseCompact(self, current=None): sbsud = Test.SBSUnknownDerived() sbsud.sb = "SBSUnknownDerived.sb" sbsud.sbsud = "SBSUnknownDerived.sbsud" - cb.ice_response(sbsud) + return Ice.Future.completed(sbsud) - def SUnknownAsObject_async(self, cb, current=None): + def SUnknownAsObject(self, current=None): su = Test.SUnknown() su.su = "SUnknown.su" - cb.ice_response(su) + return Ice.Future.completed(su) - def checkSUnknown_async(self, cb, obj, current=None): + def checkSUnknown(self, obj, current=None): if current.encoding == Ice.Encoding_1_0: test(not isinstance(obj, Test.SUnknown)) else: test(isinstance(obj, Test.SUnknown)) test(obj.su == "SUnknown.su") - cb.ice_response() + return Ice.Future.completed(None) - def oneElementCycle_async(self, cb, current=None): + def oneElementCycle(self, current=None): b = Test.B() b.sb = "B1.sb" b.pb = b - cb.ice_response(b) + return Ice.Future.completed(b) - def twoElementCycle_async(self, cb, current=None): + def twoElementCycle(self, current=None): b1 = Test.B() b1.sb = "B1.sb" b2 = Test.B() b2.sb = "B2.sb" b2.pb = b1 b1.pb = b2 - cb.ice_response(b1) + return Ice.Future.completed(b1) - def D1AsB_async(self, cb, current=None): + def D1AsB(self, current=None): d1 = Test.D1() d1.sb = "D1.sb" d1.sd1 = "D1.sd1" @@ -92,9 +92,9 @@ class TestI(Test.TestIntf): d2.pd2 = d1 d1.pb = d2 d1.pd1 = d2 - cb.ice_response(d1) + return Ice.Future.completed(d1) - def D1AsD1_async(self, cb, current=None): + def D1AsD1(self, current=None): d1 = Test.D1() d1.sb = "D1.sb" d1.sd1 = "D1.sd1" @@ -105,9 +105,9 @@ class TestI(Test.TestIntf): d2.pd2 = d1 d1.pb = d2 d1.pd1 = d2 - cb.ice_response(d1) + return Ice.Future.completed(d1) - def D2AsB_async(self, cb, current=None): + def D2AsB(self, current=None): d2 = Test.D2() d2.sb = "D2.sb" d2.sd2 = "D2.sd2" @@ -118,9 +118,9 @@ class TestI(Test.TestIntf): d1.pd1 = d2 d2.pb = d1 d2.pd2 = d1 - cb.ice_response(d2) + return Ice.Future.completed(d2) - def paramTest1_async(self, cb, current=None): + def paramTest1(self, current=None): d1 = Test.D1() d1.sb = "D1.sb" d1.sd1 = "D1.sd1" @@ -131,9 +131,9 @@ class TestI(Test.TestIntf): d2.pd2 = d1 d1.pb = d2 d1.pd1 = d2 - cb.ice_response(d1, d2) + return Ice.Future.completed((d1, d2)) - def paramTest2_async(self, cb, current=None): + def paramTest2(self, current=None): d1 = Test.D1() d1.sb = "D1.sb" d1.sd1 = "D1.sd1" @@ -144,9 +144,9 @@ class TestI(Test.TestIntf): d2.pd2 = d1 d1.pb = d2 d1.pd1 = d2 - cb.ice_response(d2, d1) + return Ice.Future.completed((d2, d1)) - def paramTest3_async(self, cb, current=None): + def paramTest3(self, current=None): d2 = Test.D2() d2.sb = "D2.sb (p1 1)" d2.pb = None @@ -171,9 +171,9 @@ class TestI(Test.TestIntf): d3.pd1 = None d4.pd2 = d3 - cb.ice_response(d3, d2, d4) + return Ice.Future.completed((d3, d2, d4)) - def paramTest4_async(self, cb, current=None): + def paramTest4(self, current=None): d4 = Test.D4() d4.sb = "D4.sb (1)" d4.pb = None @@ -183,9 +183,9 @@ class TestI(Test.TestIntf): d4.p2 = Test.B() d4.p2.sb = "B.sb (2)" d4.p2.pb = None - cb.ice_response(d4.p2, d4) + return Ice.Future.completed((d4.p2, d4)) - def returnTest1_async(self, cb, current=None): + def returnTest1(self, current=None): d1 = Test.D1() d1.sb = "D1.sb" d1.sd1 = "D1.sd1" @@ -196,9 +196,9 @@ class TestI(Test.TestIntf): d2.pd2 = d1 d1.pb = d2 d1.pd1 = d2 - cb.ice_response(d2, d2, d1) + return Ice.Future.completed((d2, d2, d1)) - def returnTest2_async(self, cb, current=None): + def returnTest2(self, current=None): d1 = Test.D1() d1.sb = "D1.sb" d1.sd1 = "D1.sd1" @@ -209,18 +209,18 @@ class TestI(Test.TestIntf): d2.pd2 = d1 d1.pb = d2 d1.pd1 = d2 - cb.ice_response(d1, d1, d2) + return Ice.Future.completed((d1, d1, d2)) - def returnTest3_async(self, cb, p1, p2, current=None): - cb.ice_response(p1) + def returnTest3(self, p1, p2, current=None): + return Ice.Future.completed(p1) - def sequenceTest_async(self, cb, p1, p2, current=None): + def sequenceTest(self, p1, p2, current=None): ss = Test.SS3() ss.c1 = p1 ss.c2 = p2 - cb.ice_response(ss) + return Ice.Future.completed(ss) - def dictionaryTest_async(self, cb, bin, current=None): + def dictionaryTest(self, bin, current=None): bout = {} for i in range(0, 10): b = bin[i] @@ -244,20 +244,20 @@ class TestI(Test.TestIntf): d1.pd1 = d1 r[i * 20] = d1 - cb.ice_response(r, bout) + return Ice.Future.completed((r, bout)) - def exchangePBase_async(self, cb, pb, current=None): - cb.ice_response(pb) + def exchangePBase(self, pb, current=None): + return Ice.Future.completed(pb) - def PBSUnknownAsPreserved_async(self, cb, current=None): + def PBSUnknownAsPreserved(self, current=None): r = Test.PSUnknown() r.pi = 5 r.ps = "preserved" r.psu = "unknown" r.graph = None - cb.ice_response(r) + return Ice.Future.completed(r) - def checkPBSUnknown_async(self, cb, p, current=None): + def checkPBSUnknown(self, p, current=None): if current.encoding == Ice.Encoding_1_0: test(not isinstance(p, Test.PSUnknown)) test(p.pi == 5) @@ -268,9 +268,9 @@ class TestI(Test.TestIntf): test(p.ps == "preserved") test(p.psu == "unknown") test(not p.graph) - cb.ice_response() + return Ice.Future.completed(None) - def PBSUnknownAsPreservedWithGraph_async(self, cb, current=None): + def PBSUnknownAsPreservedWithGraph(self, current=None): r = Test.PSUnknown() r.pi = 5 r.ps = "preserved" @@ -279,10 +279,10 @@ class TestI(Test.TestIntf): r.graph.next = Test.PNode() r.graph.next.next = Test.PNode() r.graph.next.next.next = r.graph - cb.ice_response(r) - r.graph.next.next.next = None # Break the cycle. + return Ice.Future.completed(r) + #r.graph.next.next.next = None # Break the cycle. - def checkPBSUnknownWithGraph_async(self, cb, p, current=None): + def checkPBSUnknownWithGraph(self, p, current=None): if current.encoding == Ice.Encoding_1_0: test(not isinstance(p, Test.PSUnknown)) test(p.pi == 5) @@ -296,17 +296,17 @@ class TestI(Test.TestIntf): test(p.graph.next != p.graph.next.next) test(p.graph.next.next.next == p.graph) p.graph.next.next.next = None # Break the cycle. - cb.ice_response() + return Ice.Future.completed(None) - def PBSUnknown2AsPreservedWithGraph_async(self, cb, current=None): + def PBSUnknown2AsPreservedWithGraph(self, current=None): r = Test.PSUnknown2() r.pi = 5 r.ps = "preserved" r.pb = r - cb.ice_response(r) - r.pb = None # Break the cycle. + return Ice.Future.completed(r) + #r.pb = None # Break the cycle. - def checkPBSUnknown2WithGraph_async(self, cb, p, current=None): + def checkPBSUnknown2WithGraph(self, p, current=None): if current.encoding == Ice.Encoding_1_0: test(not isinstance(p, Test.PSUnknown2)) test(p.pi == 5) @@ -317,20 +317,22 @@ class TestI(Test.TestIntf): test(p.ps == "preserved") test(p.pb == p) p.pb = None # Break the cycle. - cb.ice_response() + return Ice.Future.completed(None) - def exchangePNode_async(self, cb, pn, current=None): - cb.ice_response(pn) + def exchangePNode(self, pn, current=None): + return Ice.Future.completed(pn) - def throwBaseAsBase_async(self, cb, current=None): + def throwBaseAsBase(self, current=None): be = Test.BaseException() be.sbe = "sbe" be.pb = Test.B() be.pb.sb = "sb" be.pb.pb = be.pb - cb.ice_exception(be) + f = Ice.Future() + f.set_exception(be) + return f - def throwDerivedAsBase_async(self, cb, current=None): + def throwDerivedAsBase(self, current=None): de = Test.DerivedException() de.sbe = "sbe" de.pb = Test.B() @@ -342,9 +344,11 @@ class TestI(Test.TestIntf): de.pd1.pb = de.pd1 de.pd1.sd1 = "sd2" de.pd1.pd1 = de.pd1 - cb.ice_exception(de) + f = Ice.Future() + f.set_exception(de) + return f - def throwDerivedAsDerived_async(self, cb, current=None): + def throwDerivedAsDerived(self, current=None): de = Test.DerivedException() de.sbe = "sbe" de.pb = Test.B() @@ -356,9 +360,11 @@ class TestI(Test.TestIntf): de.pd1.pb = de.pd1 de.pd1.sd1 = "sd2" de.pd1.pd1 = de.pd1 - cb.ice_exception(de) + f = Ice.Future() + f.set_exception(de) + return f - def throwUnknownDerivedAsBase_async(self, cb, current=None): + def throwUnknownDerivedAsBase(self, current=None): d2 = Test.D2() d2.sb = "sb d2" d2.pb = d2 @@ -370,26 +376,29 @@ class TestI(Test.TestIntf): ude.pb = d2 ude.sude = "sude" ude.pd2 = d2 - cb.ice_exception(ude) + f = Ice.Future() + f.set_exception(ude) + return f - def throwPreservedException_async(self, cb, current=None): + def throwPreservedException(self, current=None): ue = Test.PSUnknownException() ue.p = Test.PSUnknown2() ue.p.pi = 5 ue.p.ps = "preserved" ue.p.pb = ue.p - cb.ice_exception(ue) - ue.p.pb = None # Break the cycle. - - def useForward_async(self, cb, current=None): - f = Test.Forward() - f.h = Test.Hidden() - f.h.f = f - cb.ice_response(f) - - def shutdown_async(self, cb, current=None): + f = Ice.Future() + f.set_exception(ue) + return f + #ue.p.pb = None # Break the cycle. + + def useForward(self, current=None): + fwd = Test.Forward() + fwd.h = Test.Hidden() + fwd.h.f = fwd + return Ice.Future.completed(fwd) + + def shutdown(self, current=None): current.adapter.getCommunicator().shutdown() - cb.ice_response() def run(args, communicator): properties = communicator.getProperties() @@ -397,23 +406,16 @@ def run(args, communicator): properties.setProperty("TestAdapter.Endpoints", "default -p 12010 -t 10000") adapter = communicator.createObjectAdapter("TestAdapter") object = TestI() - adapter.add(object, communicator.stringToIdentity("Test")) + adapter.add(object, Ice.stringToIdentity("Test")) adapter.activate() communicator.waitForShutdown() return True try: - communicator = Ice.initialize(sys.argv) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/slicing/objects/Test.ice b/python/test/Ice/slicing/objects/Test.ice index b9936669b30..89f2780c352 100644 --- a/python/test/Ice/slicing/objects/Test.ice +++ b/python/test/Ice/slicing/objects/Test.ice @@ -66,7 +66,7 @@ exception DerivedException extends BaseException D1 pd1; }; -class Forward; /* Forward-declared class defined in another compilation unit */ +class Forward; class PBase { @@ -160,5 +160,15 @@ interface TestIntf void shutdown(); }; +class Hidden +{ + Forward f; +}; + +class Forward +{ + Hidden h; +}; + }; diff --git a/python/test/Ice/slicing/objects/TestAMD.ice b/python/test/Ice/slicing/objects/TestAMD.ice index 181e8279d94..dc034da87ab 100644 --- a/python/test/Ice/slicing/objects/TestAMD.ice +++ b/python/test/Ice/slicing/objects/TestAMD.ice @@ -66,7 +66,7 @@ exception DerivedException extends BaseException D1 pd1; }; -class Forward; // Forward-declared class defined in another compilation unit +class Forward; class PBase { @@ -155,4 +155,14 @@ interface TestIntf void shutdown(); }; +class Hidden +{ + Forward f; +}; + +class Forward +{ + Hidden h; +}; + }; diff --git a/python/test/Ice/slicing/objects/run.py b/python/test/Ice/slicing/objects/run.py deleted file mode 100755 index af4c5d38c06..00000000000 --- a/python/test/Ice/slicing/objects/run.py +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env python -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -import os, sys - -path = [ ".", "..", "../..", "../../..", "../../../..", "../../../../.." ] -head = os.path.dirname(sys.argv[0]) -if len(head) > 0: - path = [os.path.join(head, p) for p in path] -path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ] -if len(path) == 0: - raise RuntimeError("can't find toplevel directory!") -sys.path.append(os.path.join(path[0], "scripts")) -import TestUtil - -print("Running test with sliced format.") -TestUtil.clientServerTest() - -print("Running test with 1.0 encoding.") -TestUtil.clientServerTest(additionalClientOptions="--Ice.Default.EncodingVersion=1.0", - additionalServerOptions="--Ice.Default.EncodingVersion=1.0") - -print("Running test with sliced format and AMD server.") -TestUtil.clientServerTest(server="ServerAMD.py") - -print("Running test with 1.0 encoding and AMD server.") -TestUtil.clientServerTest(server="ServerAMD.py", - additionalClientOptions="--Ice.Default.EncodingVersion=1.0", - additionalServerOptions="--Ice.Default.EncodingVersion=1.0") diff --git a/python/test/Ice/timeout/AllTests.py b/python/test/Ice/timeout/AllTests.py index 0d4bd320336..65d923559d4 100644 --- a/python/test/Ice/timeout/AllTests.py +++ b/python/test/Ice/timeout/AllTests.py @@ -19,17 +19,16 @@ class CallbackBase: self._cond = threading.Condition() def called(self): - self._cond.acquire() - self._called = True - self._cond.notify() - self._cond.release() + with self._cond: + self._called = True + self._cond.notify() def check(self): - self._cond.acquire() - while not self._called: - self._cond.wait() - self._called = False - return True + with self._cond: + while not self._called: + self._cond.wait() + self._called = False + return True class Callback(CallbackBase): def response(self): @@ -117,58 +116,58 @@ def allTests(communicator): sys.stdout.write("testing invocation timeout... ") sys.stdout.flush() - connection = obj.ice_getConnection(); - to = Test.TimeoutPrx.uncheckedCast(obj.ice_invocationTimeout(100)); - test(connection == to.ice_getConnection()); + connection = obj.ice_getConnection() + to = Test.TimeoutPrx.uncheckedCast(obj.ice_invocationTimeout(100)) + test(connection == to.ice_getConnection()) try: - to.sleep(750); - test(False); + to.sleep(750) + test(False) except Ice.InvocationTimeoutException: pass - obj.ice_ping(); - to = Test.TimeoutPrx.uncheckedCast(obj.ice_invocationTimeout(500)); - test(connection == to.ice_getConnection()); + obj.ice_ping() + to = Test.TimeoutPrx.uncheckedCast(obj.ice_invocationTimeout(500)) + test(connection == to.ice_getConnection()) try: - to.sleep(250); + to.sleep(250) except Ice.InvocationTimeoutException: - test(False); - test(connection == to.ice_getConnection()); + test(False) + test(connection == to.ice_getConnection()) # # # # Expect InvocationTimeoutException. # # - # to = Test.TimeoutPrx.uncheckedCast(obj.ice_invocationTimeout(250)); - # cb = new Callback(); - # to.begin_sleep(750, newCallback_Timeout_sleep(cb, &Callback.responseEx, &Callback.exceptionEx)); - # cb.check(); + # to = Test.TimeoutPrx.uncheckedCast(obj.ice_invocationTimeout(250)) + # cb = new Callback() + # to.begin_sleep(750, newCallback_Timeout_sleep(cb, &Callback.responseEx, &Callback.exceptionEx)) + # cb.check() # # # # Expect success. # # - # to = Test.TimeoutPrx.uncheckedCast(obj.ice_invocationTimeout(500)); - # cb = new Callback(); - # to.begin_sleep(250, newCallback_Timeout_sleep(cb, &Callback.response, &Callback.exception)); - # cb.check(); + # to = Test.TimeoutPrx.uncheckedCast(obj.ice_invocationTimeout(500)) + # cb = new Callback() + # to.begin_sleep(250, newCallback_Timeout_sleep(cb, &Callback.response, &Callback.exception)) + # cb.check() print("ok") sys.stdout.write("testing close timeout... ") sys.stdout.flush() - to = Test.TimeoutPrx.checkedCast(obj.ice_timeout(100)); - connection = to.ice_getConnection(); - timeout.holdAdapter(500); - connection.close(False); + to = Test.TimeoutPrx.checkedCast(obj.ice_timeout(100)) + connection = to.ice_getConnection() + timeout.holdAdapter(500) + connection.close(Ice.ConnectionClose.GracefullyWithWait) try: connection.getInfo(); # getInfo() doesn't throw in the closing state. except Ice.LocalException: - test(False); - time.sleep(0.5); + test(False) + time.sleep(0.5) try: - connection.getInfo(); - test(False); - except Ice.CloseConnectionException: + connection.getInfo() + test(False) + except Ice.ConnectionManuallyClosedException as ex: # Expected. - pass - timeout.op(); # Ensure adapter is active. + test(ex.graceful) + timeout.op() # Ensure adapter is active. print("ok") sys.stdout.write("testing timeout overrides... ") @@ -180,10 +179,10 @@ def allTests(communicator): # initData = Ice.InitializationData() initData.properties = communicator.getProperties().clone() - initData.properties.setProperty("Ice.Override.Timeout", "100") + initData.properties.setProperty("Ice.Override.Timeout", "250") comm = Ice.initialize(initData) to = Test.TimeoutPrx.checkedCast(comm.stringToProxy(sref)) - timeout.holdAdapter(500) + timeout.holdAdapter(700) try: to.sendData(seq) test(False) @@ -194,7 +193,7 @@ def allTests(communicator): # timeout.op() # Ensure adapter is active. to = Test.TimeoutPrx.checkedCast(to.ice_timeout(1000)) - timeout.holdAdapter(500); + timeout.holdAdapter(500) try: to.sendData(seq) test(False) @@ -230,9 +229,9 @@ def allTests(communicator): # Verify that timeout set via ice_timeout() is still used for requests. # timeout.op() # Ensure adapter is active. - to = Test.TimeoutPrx.uncheckedCast(to.ice_timeout(250)); + to = Test.TimeoutPrx.uncheckedCast(to.ice_timeout(250)) to.ice_getConnection(); # Establish connection - timeout.holdAdapter(750); + timeout.holdAdapter(750) try: to.sendData(seq) test(False) @@ -247,11 +246,11 @@ def allTests(communicator): initData.properties = communicator.getProperties().clone() initData.properties.setProperty("Ice.Override.CloseTimeout", "100") comm = Ice.initialize(initData) - connection = comm.stringToProxy(sref).ice_getConnection(); - timeout.holdAdapter(800); - now = time.clock(); - comm.destroy(); - test((time.clock() - now) < 0.7); + connection = comm.stringToProxy(sref).ice_getConnection() + timeout.holdAdapter(800) + now = time.clock() + comm.destroy() + test((time.clock() - now) < 0.7) print("ok") diff --git a/python/test/Ice/timeout/Client.py b/python/test/Ice/timeout/Client.py index cf8c193ee70..2e1a5dbf3bd 100755 --- a/python/test/Ice/timeout/Client.py +++ b/python/test/Ice/timeout/Client.py @@ -58,17 +58,10 @@ try: # initData.properties.setProperty("Ice.TCP.SndSize", "50000"); - communicator = Ice.initialize(sys.argv, initData) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv, initData) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/timeout/Server.py b/python/test/Ice/timeout/Server.py index bfffcd560ba..8834fe8d1ce 100755 --- a/python/test/Ice/timeout/Server.py +++ b/python/test/Ice/timeout/Server.py @@ -29,7 +29,7 @@ class ActivateAdapterThread(threading.Thread): time.sleep(self._timeout / 1000.0) self._adapter.activate() -class TimeoutI(Test.Timeout): +class TimeoutI(Test._TimeoutDisp): def op(self, current=None): pass @@ -51,7 +51,7 @@ class TimeoutI(Test.Timeout): def run(args, communicator): communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010:udp") adapter = communicator.createObjectAdapter("TestAdapter") - adapter.add(TimeoutI(), communicator.stringToIdentity("timeout")) + adapter.add(TimeoutI(), Ice.stringToIdentity("timeout")) adapter.activate() communicator.waitForShutdown() return True @@ -65,17 +65,10 @@ try: # send() blocking after sending a given amount of data. # initData.properties.setProperty("Ice.TCP.RcvSize", "50000"); - communicator = Ice.initialize(sys.argv, initData) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv, initData) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Ice/timeout/run.py b/python/test/Ice/timeout/run.py deleted file mode 100755 index 1a8297794cd..00000000000 --- a/python/test/Ice/timeout/run.py +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env python -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -import os, sys - -path = [ ".", "..", "../..", "../../..", "../../../.." ] -head = os.path.dirname(sys.argv[0]) -if len(head) > 0: - path = [os.path.join(head, p) for p in path] -path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ] -if len(path) == 0: - raise RuntimeError("can't find toplevel directory!") -sys.path.append(os.path.join(path[0], "scripts")) -import TestUtil - -TestUtil.clientServerTest() diff --git a/python/test/Slice/escape/Clash.ice b/python/test/Slice/escape/Clash.ice new file mode 100644 index 00000000000..63df89f2e7b --- /dev/null +++ b/python/test/Slice/escape/Clash.ice @@ -0,0 +1,69 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2016 ZeroC, Inc. All rights reserved. +// +// This copy of Ice is licensed to you under the terms described in the +// ICE_LICENSE file included in this distribution. +// +// ********************************************************************** + +[["underscore"]] + +module Clash +{ + +interface Intf +{ + void context(); + void current(); + void response(); + void upCast(); + void typeId(); + void del(); + void cookie(); + void sync(); + void inS(); + void istr(); + + void op(string context, string current, string response, string ex, string sent, string cookie, + string sync, string result, string istr, string ostr, optional(1) string proxy); + void opOut(out string context, out string current, out string response, out string ex, + out string sent, out string cookie, out string sync, out string result, out string istr, + out string ostr, out optional(1) string proxy); +}; + +class Cls +{ + Intf* s; + string context; + int current; + short response; + string upCast; + int typeId; + short del; + optional(1) short cookie; + string ex; + int result; + string istr; + string ostr; + string inS; + string in; + string proxy; +}; + +struct St +{ + string v; + short istr; + int ostr; + int rhs; + string other; +}; + +exception Ex +{ + short istr; + int ostr; +}; + +}; diff --git a/python/test/Slice/keyword/Client.py b/python/test/Slice/escape/Client.py index 710eb343f6b..1d91d29d434 100755 --- a/python/test/Slice/keyword/Client.py +++ b/python/test/Slice/escape/Client.py @@ -1,7 +1,7 @@ #!/usr/bin/env python # ********************************************************************** # -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. +# Copyright (c) 2003-2016 ZeroC, Inc. All rights reserved. # # This copy of Ice is licensed to you under the terms described in the # ICE_LICENSE file included in this distribution. @@ -20,22 +20,20 @@ else: import Ice Ice.loadSlice('Key.ice') +Ice.loadSlice('Clash.ice') + import _and -class delI(_and._del): - def _elif_async(self, _cb, _else, current=None): +class delI(_and._delDisp): + def _elifAsync(self, _else, current=None): pass -class execI(_and._exec): +class execI(_and._execDisp): def _finally(self, current=None): assert current.operation == "finally" -class forI(_and._for): - def foo(self, _from, current=None): - pass - -class ifI(_and._if): - def _elif_async(self, _cb, _else, current=None): +class ifI(_and._ifDisp): + def _elifAsync(self, _else, current=None): pass def _finally(self, current=None): pass @@ -59,7 +57,7 @@ def testtypes(): assert "_finally" in dir(_and.execPrx) d1 = execI() - e1 = forI() + e1 = _and._for() f = _and.ifPrx.uncheckedCast(None) assert "_finally" in dir(_and.ifPrx) @@ -79,13 +77,13 @@ def testtypes(): def run(args, communicator): communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010:udp") adapter = communicator.createObjectAdapter("TestAdapter") - adapter.add(execI(), communicator.stringToIdentity("test")) + adapter.add(execI(), Ice.stringToIdentity("test")) adapter.activate() sys.stdout.write("Testing operation name... ") sys.stdout.flush() p = _and.execPrx.uncheckedCast( - adapter.createProxy(communicator.stringToIdentity("test"))); + adapter.createProxy(Ice.stringToIdentity("test"))); p._finally(); print("ok") @@ -102,17 +100,10 @@ try: # this warning. # initData.properties.setProperty("Ice.Warn.Dispatch", "0"); - communicator = Ice.initialize(sys.argv, initData) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv, initData) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Slice/keyword/Key.ice b/python/test/Slice/escape/Key.ice index 39b462dd9e2..6c27b307d09 100644 --- a/python/test/Slice/keyword/Key.ice +++ b/python/test/Slice/escape/Key.ice @@ -1,6 +1,6 @@ // ********************************************************************** // -// Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. +// Copyright (c) 2003-2016 ZeroC, Inc. All rights reserved. // // This copy of Ice is licensed to you under the terms described in the // ICE_LICENSE file included in this distribution. @@ -32,10 +32,11 @@ module and class for { int lambda; - void foo(exec* from, out int global); + exec* from; + int global; }; - class if extends for implements exec, del + interface if extends exec, del { }; @@ -46,6 +47,7 @@ module and { int lambda; }; + exception not extends is { int or; @@ -54,14 +56,15 @@ module and local interface print { - assert raise(continue else, for return, if try, del* while, exec* yield, - for* lambda, if* or, int global) - throws is; + assert raise(continue else, for return, if try, del* while, exec* yield, + for* lambda, if* or, int global) + throws is; }; const int lambda = 0; - enum EnumNone { + enum EnumNone + { None }; }; diff --git a/python/test/Slice/import/.depend.mak b/python/test/Slice/import/.depend.mak deleted file mode 100644 index e69de29bb2d..00000000000 --- a/python/test/Slice/import/.depend.mak +++ /dev/null diff --git a/python/test/Slice/import/run.py b/python/test/Slice/import/run.py deleted file mode 100755 index cc9f8b41d2f..00000000000 --- a/python/test/Slice/import/run.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/env python -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -import os, sys, shutil, subprocess - -path = [ ".", "..", "../..", "../../..", "../../../.." ] -head = os.path.dirname(sys.argv[0]) -if len(head) > 0: - path = [os.path.join(head, p) for p in path] -path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ] -if len(path) == 0: - raise RuntimeError("can't find toplevel directory!") -sys.path.append(os.path.join(path[0], "scripts")) -import TestUtil - -testdir = os.path.dirname(os.path.abspath(__file__)) - -if os.path.exists(os.path.join(testdir, "Test1_ice.py")): - os.remove(os.path.join(testdir, "Test1_ice.py")) -if os.path.exists(os.path.join(testdir, "Test2_ice.py")): - os.remove(os.path.join(testdir, "Test2_ice.py")) -if os.path.exists(os.path.join(testdir, "Test")): - shutil.rmtree(os.path.join(testdir, "Test")) - -if os.environ.get("USE_BIN_DIST", "no") == "yes": - if TestUtil.isDarwin(): - slice2py = sys.executable + " /usr/local/bin/slice2py" - elif TestUtil.isWin32(): - pythonHome = os.path.dirname(sys.executable) - slice2py = os.path.join(pythonHome, "Scripts", "slice2py.exe") - elif os.path.isfile(os.path.join(TestUtil.getCppBinDir(), "slice2py")): - slice2py = os.path.join(TestUtil.getCppBinDir(), "slice2py") - else: - import slice2py - slice2py = sys.executable + " " + os.path.normpath(os.path.join(slice2py.__file__, "..", "..", "..", "..", "bin", "slice2py")) -else: - if TestUtil.isYocto(): - slice2py = os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "..", "..", "..", "cpp", "bin", "slice2py") - else: - slice2py = sys.executable + " " + os.path.join(path[0], "python", "config", "s2py.py") - -s2p = TestUtil.spawn(slice2py + " Test1.ice") -s2p.waitTestSuccess() -s2p = TestUtil.spawn(slice2py + " Test2.ice") -s2p.waitTestSuccess() - -sys.stdout.write("starting client... ") -sys.stdout.flush() -clientProc = TestUtil.startClient("Client.py", "--Ice.Default.Host=127.0.0.1", startReader = False) -print("ok") -clientProc.startReader() -clientProc.waitTestSuccess() diff --git a/python/test/Slice/import/test.py b/python/test/Slice/import/test.py new file mode 100644 index 00000000000..6a0343d1e4e --- /dev/null +++ b/python/test/Slice/import/test.py @@ -0,0 +1,26 @@ +# ********************************************************************** +# +# Copyright (c) 2003-2016 ZeroC, Inc. All rights reserved. +# +# This copy of Ice is licensed to you under the terms described in the +# ICE_LICENSE file included in this distribution. +# +# ********************************************************************** + +class SliceImportTestCase(ClientTestCase): + + def setupClientSide(self, current): + + testdir = current.testcase.getPath() + if os.path.exists(os.path.join(testdir, "Test1_ice.py")): + os.remove(os.path.join(testdir, "Test1_ice.py")) + if os.path.exists(os.path.join(testdir, "Test2_ice.py")): + os.remove(os.path.join(testdir, "Test2_ice.py")) + if os.path.exists(os.path.join(testdir, "Test")): + shutil.rmtree(os.path.join(testdir, "Test")) + + slice2py = SliceTranslator("slice2py") + slice2py.run(current, args=["Test1.ice"]) + slice2py.run(current, args=["Test2.ice"]) + +TestSuite(__name__, [ SliceImportTestCase() ])
\ No newline at end of file diff --git a/python/test/Slice/keyword/run.py b/python/test/Slice/keyword/run.py deleted file mode 100755 index b7fe1b9ed2c..00000000000 --- a/python/test/Slice/keyword/run.py +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env python -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -import os, sys - -path = [ ".", "..", "../..", "../../..", "../../../.." ] -head = os.path.dirname(sys.argv[0]) -if len(head) > 0: - path = [os.path.join(head, p) for p in path] -path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ] -if len(path) == 0: - raise RuntimeError("can't find toplevel directory!") -sys.path.append(os.path.join(path[0], "scripts")) -import TestUtil - -sys.stdout.write("starting client... ") -sys.stdout.flush() -clientProc = TestUtil.startClient("Client.py", "--Ice.Default.Host=127.0.0.1", startReader = False) -print("ok") -clientProc.startReader() -clientProc.waitTestSuccess() diff --git a/python/test/Slice/macros/run.py b/python/test/Slice/macros/run.py deleted file mode 100755 index b7fe1b9ed2c..00000000000 --- a/python/test/Slice/macros/run.py +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env python -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -import os, sys - -path = [ ".", "..", "../..", "../../..", "../../../.." ] -head = os.path.dirname(sys.argv[0]) -if len(head) > 0: - path = [os.path.join(head, p) for p in path] -path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ] -if len(path) == 0: - raise RuntimeError("can't find toplevel directory!") -sys.path.append(os.path.join(path[0], "scripts")) -import TestUtil - -sys.stdout.write("starting client... ") -sys.stdout.flush() -clientProc = TestUtil.startClient("Client.py", "--Ice.Default.Host=127.0.0.1", startReader = False) -print("ok") -clientProc.startReader() -clientProc.waitTestSuccess() diff --git a/python/test/Slice/structure/Client.py b/python/test/Slice/structure/Client.py index b820506ec8b..2a9e23246db 100755 --- a/python/test/Slice/structure/Client.py +++ b/python/test/Slice/structure/Client.py @@ -195,17 +195,10 @@ def run(args, communicator): try: initData = Ice.InitializationData() initData.properties = Ice.createProperties(sys.argv) - communicator = Ice.initialize(sys.argv, initData) - status = run(sys.argv, communicator) + with Ice.initialize(sys.argv, initData) as communicator: + status = run(sys.argv, communicator) except: traceback.print_exc() status = False -if communicator: - try: - communicator.destroy() - except: - traceback.print_exc() - status = False - sys.exit(not status) diff --git a/python/test/Slice/structure/run.py b/python/test/Slice/structure/run.py deleted file mode 100755 index b7fe1b9ed2c..00000000000 --- a/python/test/Slice/structure/run.py +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env python -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -import os, sys - -path = [ ".", "..", "../..", "../../..", "../../../.." ] -head = os.path.dirname(sys.argv[0]) -if len(head) > 0: - path = [os.path.join(head, p) for p in path] -path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ] -if len(path) == 0: - raise RuntimeError("can't find toplevel directory!") -sys.path.append(os.path.join(path[0], "scripts")) -import TestUtil - -sys.stdout.write("starting client... ") -sys.stdout.flush() -clientProc = TestUtil.startClient("Client.py", "--Ice.Default.Host=127.0.0.1", startReader = False) -print("ok") -clientProc.startReader() -clientProc.waitTestSuccess() diff --git a/python/test/Slice/unicodePaths/run.py b/python/test/Slice/unicodePaths/run.py deleted file mode 100644 index d192cc607ce..00000000000 --- a/python/test/Slice/unicodePaths/run.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# ********************************************************************** -# -# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. -# -# This copy of Ice is licensed to you under the terms described in the -# ICE_LICENSE file included in this distribution. -# -# ********************************************************************** - -import os, sys, locale, shutil - -path = [ ".", "..", "../..", "../../..", "../../../..", "../../../../.." ] -head = os.path.dirname(sys.argv[0]) -if len(head) > 0: - path = [os.path.join(head, p) for p in path] -path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ] -if len(path) == 0: - raise RuntimeError("can't find toplevel directory!") -sys.path.append(os.path.join(path[0], "scripts")) -import TestUtil - -def test(b): - if not b: - print("failed!") - sys.exit(1) - -if TestUtil.isAIX() or TestUtil.isLinux(): - encoding = locale.getdefaultlocale()[1] - if encoding != "UTF-8": - print("Please set LC_ALL to xx_xx.UTF-8, for example FR_FR.UTF-8") - print("Skipping test") - sys.exit(0) - -if sys.version_info[0] == 2 and TestUtil.isWin32(): - print("To run this test on Windows you need to be using Python 3.x") - print("Python 2.x subprocess module doesn't support unicode on Windows") - print("Skipping test") - sys.exit(0) - -if os.environ.get("USE_BIN_DIST", "no") == "yes": - if TestUtil.isDarwin(): - slice2py = sys.executable + " /usr/local/bin/slice2py" - elif TestUtil.isWin32(): - pythonHome = os.path.dirname(sys.executable) - slice2py = os.path.join(pythonHome, "Scripts", "slice2py.exe") - elif os.path.isfile(os.path.join(TestUtil.getCppBinDir(), "slice2py")): - slice2py = os.path.join(TestUtil.getCppBinDir(), "slice2py") - else: - import slice2py - slice2py = sys.executable + " " + os.path.normpath(os.path.join(slice2py.__file__, "..", "..", "..", "..", "bin", "slice2py")) -else: - if TestUtil.isYocto(): - slice2py = os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "..", "..", "..", "cpp", "bin", "slice2py") - else: - slice2py = sys.executable + " " + os.path.join(path[0], "python", "config", "s2py.py") - -sys.stdout.write("testing Slice compiler and unicode file paths... ") -sys.stdout.flush() - -# -# Write config -# -if sys.version_info[0] == 2: - srcPath = "./\xe4\xb8\xad\xe5\x9b\xbd".decode("utf-8") -else: - srcPath = "./\u4e2d\u56fd" -if os.path.exists(srcPath): - shutil.rmtree(srcPath) -os.mkdir(srcPath) -TestUtil.createFile("%s/Test.ice" % srcPath, ["module Test { ", - "class Point{int x; int y; };", - "interface Canvas{ void draw(Point p); };", - "};"], "utf-8") -p = TestUtil.runCommand('%s %s/Test.ice --output-dir %s' % (slice2py, srcPath, srcPath)) -test(p.wait() == 0) -test(os.path.isfile("%s/Test_ice.py" % srcPath)) - -if os.path.exists(srcPath): - shutil.rmtree(srcPath) -print("ok") |