code
stringlengths 501
5.19M
| package
stringlengths 2
81
| path
stringlengths 9
304
| filename
stringlengths 4
145
|
---|---|---|---|
# zsfile
zstandard compress and decompress tool.
## Install
```
pip3 install zsfile
```
## Command Usage
```
test@test Downloads % zsf --help
Usage: zsf [OPTIONS] INPUT
Zstandard compress and decompress tool.
Options:
-d, --decompress force decompression. default to false.
-o, --output TEXT Output filename.
--help Show this message and exit.
```
## Examples
```
test@test test01 % ls
mingw-w64-x86_64-file-5.39-2-any.pkg.tar.zst
test@test test01 % zsf -d mingw-w64-x86_64-file-5.39-2-any.pkg.tar.zst
decompressing file mingw-w64-x86_64-file-5.39-2-any.pkg.tar.zst to mingw-w64-x86_64-file-5.39-2-any.pkg.tar...
test@test test01 % ls
mingw-w64-x86_64-file-5.39-2-any.pkg.tar mingw-w64-x86_64-file-5.39-2-any.pkg.tar.zst
test@test test01 % file mingw-w64-x86_64-file-5.39-2-any.pkg.tar.zst
mingw-w64-x86_64-file-5.39-2-any.pkg.tar.zst: Zstandard compressed data (v0.8+), Dictionary ID: None
test@test test01 % file mingw-w64-x86_64-file-5.39-2-any.pkg.tar
mingw-w64-x86_64-file-5.39-2-any.pkg.tar: POSIX tar archive
test@test test01 %
```
## Releases
### v0.1.0
- First release.
| zsfile | /zsfile-0.1.0.tar.gz/zsfile-0.1.0/README.md | README.md |
===============
zsft.recipe.cmd
===============
.. contents::
This recipe allows you to run arbitrary shell and python scripts from buildout.
It's inspired by similar recipes but has few added features.
Repository: https://github.com/zartsoft/zsft.recipe.cmd
To clone:
`git clone https://github.com/zartsoft/zsft.recipe.cmd`
Issue tracker: https://github.com/zartsoft/zsft.recipe.cmd/issues
Supported Python versions: 2.7, 3.3+
Supported zc.buildout versions: 1.x, 2.x.
Usage
=====
``install``
Commands to execute on install phase.
``update``
Commands to execute on update phase.
``shell``
Shell to run script with. If not set uses default system shell.
Special value `internal` means executing as python code from buildout.
``install-shell``
Can override shell for install phase.
``update-shell``
Can override shell for update phase.
``shell-options``
Additional switch to shell, like `-File` for PowerShell, `-f` for Awk, etc.
``install-shell-options``
Can override shell options for install phase.
``update-shell-options``
Can override shell options for update phase.
``env``
List of KEY=VALUE pairs to set environment variables.
Examples
========
.. code:: ini
[cmmi]
recipe = zsft.recipe.cmd
install =
./configure --prefix=${buildout:parts-directory}/opt
make
make install
env =
CFLAGS = -g -Wall -O2
LDFLAGS = -lm
LD_RUN_PATH = $ORIGIN/../lib
[pythonscript]
recipe = zsft.recipe.cmd
shell = internal
install =
os.chdir('${buildout:parts-directory}')
if not os.path.exists('opt'):
os.makedirs('opt')
os.chdir('opt')
check_call(['./config ; make'], shell=True)
[msbuild:windows]
recipe = zsft.recipe.cmd
configuration = Release
platform = Win32
install =
msbuild.exe /t:Build /p:Configuration=${:configuration} /p:Platform=${:platform}
[service-restart:windows]
recipe = zsft.recipe.cmd
shell = powershell.exe
shell-options = -File
service = foo
update =
$service = "${:service}"
Write-Host -ForegroundColor Yellow "Restarting service '$service'"
Restart-Service -Verbose $service
Difference from other recipes
=============================
Unlike other similar recipes this one allows you to specify custom shell on
Windows and environment variables.
``iw.recipe.cmd``
Does not allow you to have different scripts for install and update.
Specifying shell is POSIX only.
``collective.recipe.cmd``
Same limitations as in `iw.recipe.cmd`. Has `uninstall_cmds` and python mode.
``plone.recipe.command``
Has `stop-on-error` option and allows different scripts for install/update.
Does not seem to allow multiline commands or custom shells.
| zsft.recipe.cmd | /zsft.recipe.cmd-0.4.tar.gz/zsft.recipe.cmd-0.4/README.rst | README.rst |
import sys
import os
import logging
import shutil
import tempfile
import zc.buildout
from subprocess import check_call
def _env(env):
"""Parse multiline KEY=VALUE string into dict."""
return dict((key.strip(), val)
for line in env.strip().splitlines()
for key, _, val in [line.partition('=')])
class ShellRecipe(object):
"""zc.buildout recipe to execute commands with shell"""
def __init__(self, buildout, name, options):
"""Recipe constructor"""
self.log = logging.getLogger(name)
self.buildout = buildout
self.name = name
self.options = options
options['location'] = os.path.join(
buildout['buildout']['parts-directory'], name)
def _execute(self, content, env={}, shell='', shell_opts=''):
"""Execute code with given shell by creating temporary script"""
log = self.log
name = self.name
options = self.options
buildout = self.buildout
path = tempfile.mkdtemp()
try:
env = dict(os.environ, **env)
suffix = ''
if os.name == 'nt': # TODO: jython?
suffix = '.ps1' if 'powershell' in shell.lower() else '.bat'
script = os.path.join(path, 'run'+suffix)
if not shell:
if os.name == 'nt':
shell = os.environ.get('COMSPEC', 'COMMAND.COM')
shell_opts = '/c'
else:
shell = os.environ.get('SHELL', '/bin/sh')
shell_opts = ''
with open(script, 'w') as f:
f.write(content)
del f
if shell == 'internal':
self.log.debug('Executing python code: %r', content)
exec(content)
else:
command = list(filter(None, [shell, shell_opts, script]))
self.log.debug('Executing: %r', command)
check_call(command, env=env)
finally:
shutil.rmtree(path)
def _process(self, prefix):
"""Common logic for both install and update"""
options = self.options
script = options.get(prefix, '').strip()
if script:
env = _env(options.get(prefix+'-env') or options.get('env') or '')
shell = (options.get(prefix+'-shell')
or options.get('shell') or '')
shell_opts = (options.get(prefix+'-shell-options') or
options.get('shell-options') or '')
self.log.info('Executing %s script', prefix)
self._execute(script, env=env, shell=shell, shell_opts=shell_opts)
return ()
def install(self):
"""Execute script on install phase"""
return self._process('install')
def update(self):
"""Execute script on update phase"""
return self._process('update') | zsft.recipe.cmd | /zsft.recipe.cmd-0.4.tar.gz/zsft.recipe.cmd-0.4/src/zsft/recipe/cmd/shell.py | shell.py |
import os
import sys
from contextlib import contextmanager
import subprocess
from itertools import starmap
import click
from . import __description__
ZSH_HISTORY_FILE = '~/.zsh_history'
FISH_HISTORY_FILE = '~/.local/share/fish/fish_history'
DIM, Z, BLUE, YELLOW = '\033[2m', '\033[0m', '\033[94m', '\033[93m'
# use zsh itself to read history file, since it is not utf-8 encoded.
# suggested in https://github.com/rsalmei/zsh-history-to-fish/issues/2
ZSH_HISTORY_READER = "zsh -i -c 'fc -R {}; fc -l -t \"%s\" 0'"
def read_history(input_file):
command = ZSH_HISTORY_READER.format(input_file)
p = subprocess.run(command, capture_output=True, shell=True, encoding='utf8')
lines = p.stdout.splitlines()
yield from map(lambda x: x.replace('\\n', '\n'), lines)
def parse_history(input_file):
stream = map(lambda x: x.split(maxsplit=2)[1:], read_history(input_file))
yield from filter(lambda x: len(x) > 1, stream)
def naive_zsh_to_fish(cmd):
result = cmd \
.replace(' && ', '&&') \
.replace('&&', '; and ') \
.replace(' || ', '||') \
.replace('||', '; or ')
return result
def display_changed(zsh, fish):
if zsh != fish:
return f'{DIM}zsh {Z}: {zsh}\n' \
f'{DIM}fish{Z}: {YELLOW}{fish}{Z}'
@contextmanager
def writer_factory(output_file, dry_run):
if dry_run:
yield lambda x: None
print(f'No file has been written.')
return
with open(output_file, 'a') as out:
yield lambda x: out.write(x)
print(f'\nFile "{output_file}" has been written successfully.')
@click.command(help=__description__)
@click.version_option()
@click.argument('input_file', type=click.Path(exists=True), required=False,
default=os.path.expanduser(ZSH_HISTORY_FILE))
@click.option('--output_file', '-o', type=click.Path(),
default=os.path.expanduser(FISH_HISTORY_FILE),
help='Optional output, will append to fish history by default')
@click.option('--dry-run', '-d', is_flag=True, help='Do not write anything to filesystem')
@click.option('--no-convert', '-n', is_flag=True, help='Do not naively convert commands')
def exporter(input_file, output_file, dry_run, no_convert):
print('ZSH history to Fish')
print('===================')
print(f'{DIM}input {Z}: {BLUE}{input_file}{Z} ({YELLOW}naive-convert={not no_convert}{Z})')
print(f'{DIM}output{Z}: {BLUE}{"dry run mode" if dry_run else output_file}{Z}')
converter = (lambda x: x) if no_convert else naive_zsh_to_fish
changed = []
with writer_factory(output_file, dry_run) as writer:
for i, (timestamp, command_zsh) in enumerate(parse_history(input_file)):
command_fish = converter(command_zsh)
fish_history = f'- cmd: {command_fish}\n when: {timestamp}\n'
writer(fish_history)
if command_zsh != command_fish:
changed.append((command_zsh, command_fish))
if i % 1000 == 0:
print('.', end='')
sys.stdout.flush()
print(f'\nProcessed {BLUE}{i + 1}{Z} commands.')
if changed:
print('Converted commands:\n', '\n'.join(starmap(display_changed, changed)), sep='') | zsh-history-to-fish | /zsh_history_to_fish-0.3.0-py3-none-any.whl/zsh_history_to_fish/command.py | command.py |
import io
import json
import logging
import os
import re
from collections import OrderedDict as odict
import pexpect
from ipykernel.kernelbase import Kernel
from .config import config
# noinspection PyAbstractClass
from .fun import get_word_at_pos
class ZshKernel (Kernel):
implementation = config['kernel']['info']['implementation']
implementation_version = config['kernel']['info']['implementation_version']
protocol_version = config['kernel']['info']['protocol_version']
banner = config['kernel']['info']['banner']
language_info = config['kernel']['info']['language_info']
p : pexpect.spawn # [spawn]
ps = odict([
('PS1', 'PEXPECT_PS1 > '),
('PS2', 'PEXPECT_PS2 + '),
('PS3', 'PEXPECT_PS3 : '),
])
ps_re = odict([
('PS1', '^PEXPECT_PS1 > ' ),
('PS2', '^PEXPECT_PS2 \+ '),
('PS3', '^PEXPECT_PS3 : ' ),
])
# [zsh-prompts]
pexpect_logfile : io.IOBase = None
log_enabled : bool
@staticmethod
def _json_(d : dict):
return json.dumps(d, indent = 4)
def _init_log_(self, **kwargs):
self.log_enabled = config['logging_enabled']
if self.log_enabled:
handler = logging.handlers.WatchedFileHandler(config['logfile'])
formatter = logging.Formatter(config['logging_formatter'])
handler.setFormatter(formatter)
self.log.setLevel(config['log_level'])
self.log.addHandler(handler)
def _init_spawn_(self, **kwargs):
# noinspection PyTypeChecker
args = [
'-o', 'INTERACTIVE', # just to make sure
'-o', 'NO_ZLE', # no need for zsh line editor
'-o', 'NO_BEEP',
'-o', 'TRANSIENT_RPROMPT',
'-o', 'NO_PROMPT_CR',
'-o', 'INTERACTIVE_COMMENTS',
] # [zsh-options]
if not kwargs.get("rcs", False):
args.extend(['-o', 'NO_RCS'])
if self.log_enabled:
# noinspection PyTypeChecker
self.pexpect_logfile = open(config['pexpect']['logfile'], 'a')
self.p = pexpect.spawn(
"zsh",
args,
echo = False,
encoding = config['pexpect']['encoding'],
codec_errors = config['pexpect']['codec_errors'],
timeout = config['pexpect']['timeout'],
logfile = self.pexpect_logfile,
)
def _init_zsh_(self, **kwargs):
init_cmds = [
*config['zsh']['init_cmds'],
*map(lambda kv: "{}='{}'".format(*kv), self.ps.items()),
]
self.p.sendline("; ".join(init_cmds))
self.p.expect_exact(self.ps['PS1'])
config_cmds = [
*config['zsh']['config_cmds'],
]
self.p.sendline("; ".join(config_cmds))
self.p.expect_exact(self.ps['PS1'])
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._init_log_()
if self.log_enabled: self.log.debug("initializing %s", self._json_(config))
self._init_spawn_()
self._init_zsh_(**kwargs)
# self.p.sendline("tty")
# self.p.expect_exact(self.ps['PS1'])
if self.log_enabled: self.log.debug("initialized")
if self.log_enabled: self.log.debug("kwargs:" + str(kwargs))
def __del__(self):
try:
self.pexpect_logfile.close()
except AttributeError:
pass
def kernel_info_request(self, stream, ident, parent):
content = {'status': 'ok'}
content.update(self.kernel_info)
content.update({'protocol_version': self.protocol_version})
msg = self.session.send(stream, 'kernel_info_reply', content, parent, ident)
if self.log_enabled: self.log.debug("info request sent: %s", msg)
def do_execute(self, code : str, silent : bool, store_history = True, user_expressions : dict = None, allow_stdin = False, cell_id = None):
try:
code_lines : list = code.splitlines()
actual = None
for line in code_lines:
if self.log_enabled: self.log.debug("code: %s", line)
self.p.sendline(line)
actual = self.p.expect(list(self.ps_re.values()) + [os.linesep])
if actual == 0:
if self.log_enabled: self.log.debug(f"got PS1. output: {self.p.before}")
if not silent:
if len(self.p.before) != 0:
self.send_response(self.iopub_socket, 'stream', {
'name': 'stdout',
'text': self.p.before,
})
else:
while actual == 3:
if self.log_enabled: self.log.debug(f"got linesep. output: {self.p.before}")
if not silent:
self.send_response(self.iopub_socket, 'stream', {
'name': 'stdout',
'text': self.p.before + os.linesep,
})
actual = self.p.expect(list(self.ps_re.values()) + [os.linesep])
if self.log_enabled: self.log.debug(f"executed all lines. actual: {actual}")
if actual in [1, 2]:
self.p.sendline()
# "flushing"
actual = self.p.expect(list(self.ps_re.values()))
while actual != 0:
actual = self.p.expect(self.p.expect(list(self.ps_re.values())) + [re.compile(".*")])
if not silent:
self.send_response(self.iopub_socket, 'stream', {
'name': 'stdout',
'text': self.p.before,
})
raise ValueError("Continuation or selection prompts are not handled yet")
except KeyboardInterrupt as e:
if self.log_enabled: self.log.debug("interrupted by user")
self.p.sendintr()
self.p.expect_exact(self.ps['PS1'])
if not silent:
self.send_response(self.iopub_socket, 'stream', {
'name': 'stdout',
'text': self.p.before,
})
return {
'status': 'error',
'execution_count': self.execution_count,
'ename': e.__class__.__name__,
'evalue': e.__class__.__name__,
'traceback': [],
}
except ValueError as e:
if self.log_enabled: self.log.exception("value error")
error_response = {
'execution_count': self.execution_count,
'ename': e.__class__.__name__,
'evalue': e.__class__.__name__,
'traceback': [],
# 'traceback': traceback.extract_stack(e), # [traceback]
}
self.send_response(self.iopub_socket, 'error', error_response)
return {
'status': 'error',
**error_response,
}
except pexpect.TIMEOUT as e:
if self.log_enabled: self.log.exception("timeout")
error_response = {
'execution_count': self.execution_count,
'ename': e.__class__.__name__,
'evalue': e.__class__.__name__,
'traceback': [],
# 'traceback': traceback.extract_stack(e), # [traceback]
}
self.send_response(self.iopub_socket, 'error', error_response)
return {
'status': 'error',
**error_response,
}
except pexpect.EOF as e:
if self.log_enabled: self.log.exception("end of file")
error_response = {
'execution_count': self.execution_count,
'ename': e.__class__.__name__,
'evalue': e.__class__.__name__,
'traceback': [],
# 'traceback': traceback.extract_stack(e), # [traceback]
}
self.send_response(self.iopub_socket, 'error', error_response)
return {
'status': 'error',
**error_response,
}
if self.log_enabled: self.log.debug(f"success {self.execution_count}")
return {
'status': 'ok',
'execution_count': self.execution_count,
'payload': [],
'user_expressions': {},
}
def do_is_complete(self, code : str):
(_, exitstatus) = pexpect.run(
config['kernel']['code_completness']['cmd'].format(code),
withexitstatus = True,
)
if exitstatus == 0:
return {'status': 'complete' }
elif exitstatus == 1:
return {'status': 'incomplete' }
def do_inspect(self, code : str, cursor_pos : int, detail_level : int = 0, omit_sections = ()):
word = get_word_at_pos(code, cursor_pos)
if self.log_enabled: self.log.debug("inspecting: %s", word)
cman = f"man --pager ul {word}"
res = pexpect.run(cman).decode()
return {
'status': 'ok',
'found': True,
'data': {'text/plain': res },
'metadata': {},
}
def do_complete(self, code : str, cursor_pos : int):
if self.log_enabled: self.log.debug("received code to complete:\n%s", code)
if self.log_enabled: self.log.debug("cursor_pos=%s", cursor_pos)
(context, completee, cursor_start, cursor_end) = self.parse_completee(code, cursor_pos)
if self.log_enabled: self.log.debug("parsed completee: %s", (context, completee, cursor_start, cursor_end))
completion_cmd = config['kernel']['code_completion']['cmd'].format(context)
self.p.sendline(completion_cmd)
self.p.expect_exact(self.ps['PS1'])
raw_completions = self.p.before.strip()
if self.log_enabled: self.log.debug("got completions:\n%s", raw_completions)
completions = list(filter(None, raw_completions.splitlines()))
if self.log_enabled: self.log.debug("array of completions: %s", completions)
matches_data = list(map(lambda x: x.split(' -- '), completions)) # [match, description]
if self.log_enabled: self.log.debug("processed matches: %s", matches_data)
return {
'status': 'ok',
'matches': [x[0] for x in matches_data],
'cursor_start' : cursor_start,
'cursor_end' : cursor_end,
'metadata' : {},
}
@staticmethod
def parse_completee(code : str, cursor_pos : int) -> tuple:
# (context, completee, cursor_start, cursor_end)
context = code[:cursor_pos]
match = re.search(r'\S+$', context)
if not match:
match = re.search(r'\w+$', context)
if not match:
completee = ''
else:
completee = match.group(0)
cursor_start = cursor_pos - len(completee)
cursor_end = cursor_pos
return context, completee, cursor_start, cursor_end
# Reference
# [spawn]: https://pexpect.readthedocs.io/en/stable/api/pexpect.html#spawn-class
# [zsh-prompts]: https://jlk.fjfi.cvut.cz/arch/manpages/man/zshparam.1#PARAMETERS_USED_BY_THE_SHELL
# [1]: # https://pexpect.readthedocs.io/en/stable/api/pexpect.html#pexpect.spawn.expect
# [traceback]: https://docs.python.org/3/library/traceback.html#traceback.extract_tb | zsh-jupyter-kernel | /zsh_jupyter_kernel-3.5.0-py3-none-any.whl/zsh_jupyter_kernel/kernel.py | kernel.py |
__all__ = ['config']
import json
import re
import sys
from os import makedirs
from os.path import join, dirname, realpath
from typing import Dict, Any
config : Dict[str, Any] = {}
config.update({
'logging_enabled': False,
})
config.update({
'module_dir': dirname(realpath(__file__)),
})
version : str
with open(join(config['module_dir'], 'version')) as f:
version = f.read()
config.update({
'name': 'zsh-jupyter-kernel',
'module': 'zsh_jupyter_kernel',
'version': version,
'description': 'Z shell kernel for Jupyter',
'author': 'dan oak',
'author_email': '[email protected]',
'license': '',
'github_url': 'https://github.com/dany-oak/zsh-jupyter-kernel',
'keywords': [
'jupyter',
'ipython',
'zsh',
'shell',
'kernel',
],
'requirements': [
'ipykernel',
# kernelapp.IPKernelApp - Kernel launcher
# kernelbase.Kernel - Convenient parent class with low level instrumentation
'jupyter_client',
# KernelSpecManager().install_kernel_spec
'IPython',
# only for tempdir
'pexpect',
# Spawning and interacting with Zsh pseudo terminal
],
})
config.update({
'python_version': '>=3.10',
# 'git_revision_hash': subprocess
# .check_output(['git', 'rev-parse', 'HEAD'])
# .decode()
# .strip(), # git-config fails in a distributed package
'tests_suffix': "_test.py",
'log_dir': realpath(join(dirname(realpath(__file__)), 'log')),
})
config.update({
'readme': realpath(join(config['module_dir'], 'README.md')),
})
config['long_description'] = {}
with open(join(config['module_dir'], config['readme'])) as f:
readme_md = f.read()
config['long_description']['md'] = {
'content': readme_md,
'type': 'text/markdown',
}
config['long_description']['md_with_github_image_links'] = {
'content': re.sub(
r'(!\[.*screenshot.*])\((.*)\)',
r'\1(https://raw.githubusercontent.com/dan-oak/zsh-jupyter-kernel/master/\2)',
readme_md),
'type': 'text/markdown',
}
config.update({
# 'log_level': "DEBUG",
'log_level': "INFO",
})
if config['logging_enabled']:
config.update({
'logfile': join(config['log_dir'], 'kernel.log'),
'logging_formatter': # [logging]
'%(asctime)s | %(name)-10s | %(levelname)-6s | %(message)s',
})
makedirs(dirname(config['logfile']), exist_ok = True)
config.update({
'non_python_files': [
'banner.txt',
'capture.zsh',
'README.md',
'version',
],
'pexpect': { # [pexpect-spawn]
'encoding': 'utf-8',
'codec_errors': 'replace', # [codecs]
'timeout': None, # [pexpect-spawn-timeout]
'logfile': join(config['log_dir'], 'pexpect.log'),
},
'zsh': {
'init_cmds': [
# "TERM=dumb",
"autoload -Uz add-zsh-hook",
"add-zsh-hook -D precmd \*",
"add-zsh-hook -D preexec \*",
# [zsh-hooks]
"precmd() {}",
"preexec() {}",
# [zsh-functions]
],
'config_cmds': [
"unset zle_bracketed_paste", # [zsh-bracketed-paste]
"zle_highlight=(none)", # https://linux.die.net/man/1/zshzle
],
},
'kernel': {
'code_completness': {'cmd': "zsh -nc '{}'"},
'code_inspection': {'cmd': r"""zsh -c 'man -P "col -b" \'{}\\''"""},
'code_completion': {'cmd': config['module_dir'] + "/capture.zsh '{}'"},
# https://github.com/danylo-dubinin/zsh-capture-completion
# Thanks to https://github.com/Valodim/zsh-capture-completion
},
})
if config['logging_enabled']:
makedirs(dirname(config['pexpect']['logfile']), exist_ok = True)
config['kernel']['info'] = {
'protocol_version': '5.3',
'implementation': "ZshKernel",
'implementation_version': config['version'],
'language_info': {
'name': 'zsh',
'version': '5.7.1',
'mimetype': 'text/x-zsh',
'file_extension': '.zsh',
'pygments_lexer': 'shell',
'codemirror_mode': 'shell',
# 'help_links': [
# {
# 'text': 'Intro',
# 'url': f'{config["github_url"]}/blob/{config["git_revision_hash"]}/README.md',
# },
# ], # git-config fails in a distributed package
},
}
with open(join(config['module_dir'], 'banner.txt'), 'r') as f:
config['kernel']['info']['banner'] = f.read()
if __name__ == '__main__':
print(json.dumps(config, indent = 4)) | zsh-jupyter-kernel | /zsh_jupyter_kernel-3.5.0-py3-none-any.whl/zsh_jupyter_kernel/config.py | config.py |
import argparse
import json
import os
import sys
from IPython.utils.tempdir import TemporaryDirectory
from jupyter_client.kernelspec import install_kernel_spec, get_kernel_spec, KernelSpec
def main(argv = None):
try:
args = parse_args(argv)
if args.sys_prefix:
args.prefix = sys.prefix
if not args.prefix and not is_root():
args.user = True
with TemporaryDirectory() as tempd:
os.chmod(tempd, 0o755) # Starts off as 700, not user readable
with open(os.path.join(tempd, 'kernel.json'), 'w') as f:
json.dump(
{ # [kernel-specs]
"argv" : [sys.executable, "-m", 'zsh_jupyter_kernel', "-f", "{connection_file}"],
"display_name" : args.display_name,
"language" : "zsh",
"interrupt_mode": "signal",
},
fp = f,
indent = 4,
)
try:
install_kernel_spec(
source_dir = tempd,
kernel_name = args.name,
user = args.user,
prefix = args.prefix,
)
except OSError as e:
print(e)
print('you do not have appropriate permissions to install kernel in the specified location.\n'
'try installing in a location of your user using --user option'
' or specify a custom value with --prefix.')
else:
spec: KernelSpec = get_kernel_spec(kernel_name = args.name)
print(
f"installed z shell jupyter kernel spec in {spec.resource_dir}:\n"
f"""{json.dumps(dict(
argv = spec.argv,
env = spec.env,
display_name = spec.display_name,
language = spec.language,
interrupt_mode = spec.interrupt_mode,
metadata = spec.metadata,
), indent = 4)}"""
)
except Exception as e:
print(e)
print('sorry, an unhandled error occured.'
f' please report this bug to https://github.com/dan-oak/zsh-jupyter-kernel/issues')
def is_root() -> bool:
try:
return os.geteuid() == 0
except AttributeError:
return False # assume not an admin on non-Unix platforms
def parse_args(argv) -> argparse.Namespace:
ap = argparse.ArgumentParser()
ap.add_argument(
'--name',
default = 'zsh',
help = "directory name in the kernelspec repository. use this to specify a unique location for the kernel"
" if you use more than one version, otherwise just skip it and use the default 'zsh' value."
" kernelspec will be installed in {prefix}/{name}/share/jupyter/kernels/."
" since kernelspecs show up in urls and other places, a kernelspec is required to have a simple name,"
" only containing ascii letters, ascii numbers, and the simple separators:"
" - hyphen, . period, _ underscore.",
)
ap.add_argument(
'--display-name',
default = 'Z shell',
help = "the kernel’s name as it should be displayed in the ui. unlike the --name used in the api,"
" this can contain arbitrary unicode characters.",
)
ap.add_argument(
'--user',
action = 'store_true',
help = "install to the per-user kernels registry. default if not root. ignored if --prefix is specified",
)
ap.add_argument(
'--sys-prefix',
action = 'store_true',
help = "install to sys.prefix (e.g. a virtualenv, pipenv or conda env)",
)
ap.add_argument(
'--prefix',
help = "install to the given prefix. kernelspec will be installed in {prefix}/{name}/share/jupyter/kernels/",
)
return ap.parse_args(argv)
if __name__ == '__main__':
main(sys.argv[1:]) | zsh-jupyter-kernel | /zsh_jupyter_kernel-3.5.0-py3-none-any.whl/zsh_jupyter_kernel/install.py | install.py |
# zsh kernel for jupyter

a simple z shell jupyter kernel powered by python 3, pexpect and enthusiasm.
i love experimentation and tinkering, but usual shell terminals does not allow developing multiple different code snippets at once conveniently.
with shell kernels you can turn your scripts into notebooks!
if you find this product useful, please consider supporting me with a one-time tip.
## installation
1. install the python package from [pypi](https://pypi.org/project/zsh-jupyter-kernel/).
2. install the jupyter kernel spec using python script `install` in the `zsh_jupyter_kernel` module.
check `python -m zsh_jupyter_kernel.install -h` for possible installation options.
default installation will install the kernel in the user location.
use `--sys-prefix` option if you want to install the kernel in your current virtual environment.
see some common installation examples below.
### pipenv
```sh
pipenv --python 3.10 install notebook zsh_jupyter_kernel
pipenv run python -m zsh_jupyter_kernel.install --sys-prefix
```
### pip
```sh
python -m pip install notebook zsh_jupyter_kernel
python -m zsh_jupyter_kernel.install --sys-prefix
```
## technical overview
the kernel launches zsh as if it was a regular process launched from your terminal with a few minor settings to make sure it works with jupyter. there is slight chance it wont work with super complicated zshrc setups, but it works with majority of configs including oh-my-zsh.
### how does code execution work
the kernel configures zsh prompt string to its own custom value.
when a user requests a cell execution, the code is sent to the kernel.
then the kernel puts the frontend on hold, sends the code to zsh process, and waits for the prompt string to release the frontend and let the user request more code execution.
### code completion
code completion is powered by quite a non-trivial script that involves multiple steps, including spawning another temporary zsh process and capturing completion options into a data structure that jupyter frontend understands.
### code inspection
code inspection is done by `man --pager ul` which sends the whole man page to the frontend.
### code completeness
code completeness is checked with the temporary zsh process and help of `EXEC` zsh option, which allows switching off code execution and simply check if the code is complete using the exit code of the zsh process itself.
### stderr
stderr content is just sent to the front-end as regular stdout.
### stdin
stdin is not supported because of the execution system when a process spawned by a user waits for stdin, there is no way to detect it.
### missing features
- history
- rich html output for things like images and tables
- stdin. might be possible with or without the current system
- pagers. might be possible or not
- stored and referenceable outputs
| zsh-jupyter-kernel | /zsh_jupyter_kernel-3.5.0-py3-none-any.whl/zsh_jupyter_kernel/README.md | README.md |
from ipykernel.kernelbase import Kernel
import os
import io
import pexpect
import signal
import logging as log
from collections import OrderedDict
from .conf import conf
from . import __version__
class ZshKernel (Kernel):
implementation = "ZshKernel"
implementation_version = __version__
with open(os.path.join(conf['module_root'], 'banner.txt'), 'r') as f:
banner = f.read()
language_info = {
'name': 'zsh',
'version': '5.3',
'mimetype': 'text/x-zsh',
'file_extension': '.zsh',
'pygments_lexer': 'shell',
'codemirror_mode': 'shell',
}
child : pexpect.spawn # [spawn]
prompts = OrderedDict([
('PS1', 'PEXPECT_PS1 > '),
('PS2', 'PEXPECT_PS2 + '),
('PS3', 'PEXPECT_PS3 : '),
]) # [zsh-prompts]
pexpect_logfile : io.IOBase = None
def _init_log_(self):
handler = log.handlers.WatchedFileHandler(conf['logfile'])
formatter = log.Formatter(conf['logging_formatter'])
handler.setFormatter(formatter)
root = log.getLogger()
root.setLevel(conf['log_level'])
root.addHandler(handler)
def _init_spawn_(self):
self.pexpect_logfile = open(conf['pexpect']['logfile'], 'a')
self.child = pexpect.spawn(
conf['pexpect']['cmd'], conf['pexpect']['args'],
echo = False,
encoding = conf['pexpect']['encoding'],
codec_errors = conf['pexpect']['codec_errors'],
timeout = conf['pexpect']['timeout'],
logfile = self.pexpect_logfile,
)
def _init_zsh_(self):
log.debug("Reinitializing required parameters and functions")
init_cmds = [
"precmd() {}", # [zsh-functions]
*map(lambda kv: "{}='{}'".format(*kv), self.prompts.items()),
"unset zle_bracketed_paste", # [zsh-bracketed-paste]
]
self.child.sendline("; ".join(init_cmds))
self.child.expect_exact(self.prompts['PS1'])
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._init_log_()
log.debug(f"Initializing using {conf}")
self._init_spawn_()
self._init_zsh_()
log.debug("Initialized")
def __del__(self):
try:
self.pexpect_logfile.close()
except AttributeError:
pass
def do_execute(
self,
code : str,
silent : bool,
store_history = True,
user_expressions : dict = None,
allow_stdin = False,
):
try:
if not code:
raise ValueError("No code given")
code_lines : list = code.splitlines()
for line in code_lines:
log.debug("code: %s", line)
self.child.sendline(line)
actual = self.child.expect_exact(
list(self.prompts.values()) + [os.linesep]
)
if actual == 0:
log.debug("got primary prompt")
log.debug(f"output: {self.child.before}")
if not silent:
self.send_response(self.iopub_socket, 'stream', {
'name': 'stdout',
'text': self.child.before,
})
elif actual == 1:
log.debug("got secondary prompt")
else:
log.debug("got return")
while actual == 3:
log.debug(f"output: {self.child.before}")
if not silent:
self.send_response(self.iopub_socket, 'stream', {
'name': 'stdout',
'text': self.child.before + os.linesep,
})
actual = self.child.expect_exact(
list(self.prompts.values()) + [os.linesep]
)
if actual in [1, 2]:
self.child.sendintr()
self.child.expect_exact(self.prompts.values())
raise ValueError(
"Continuation prompt found - command was incomplete"
)
except KeyboardInterrupt as e:
log.info("Interrupted by user")
self.child.kill(signal.SIGQUIT) # [pexpect-kill][os-kill][signal]
# self.child.expect_exact(self.prompts['PS1'])
if not silent:
self.send_response(self.iopub_socket, 'stream', {
'name': 'stdout',
'text': self.child.before,
})
return {
'status': 'error',
'execution_count': self.execution_count,
'ename': e.__class__.__name__,
'evalue': e.__class__.__name__,
'traceback': [],
}
except ValueError as e:
log.exception("Value Error")
error_response = {
'execution_count': self.execution_count,
'ename': e.__class__.__name__,
'evalue': e.__class__.__name__,
'traceback': [],
# 'traceback': traceback.extract_stack(e), # [traceback]
}
self.send_response(self.iopub_socket, 'error', error_response)
return {
'status': 'error',
**error_response,
}
except pexpect.TIMEOUT as e:
log.exception("Timeout")
error_response = {
'execution_count': self.execution_count,
'ename': e.__class__.__name__,
'evalue': e.__class__.__name__,
'traceback': [],
# 'traceback': traceback.extract_stack(e), # [traceback]
}
self.send_response(self.iopub_socket, 'error', error_response)
return {
'status': 'error',
**error_response,
}
except pexpect.EOF as e:
log.exception("End of file")
error_response = {
'execution_count': self.execution_count,
'ename': e.__class__.__name__,
'evalue': e.__class__.__name__,
'traceback': [],
# 'traceback': traceback.extract_stack(e), # [traceback]
}
self.send_response(self.iopub_socket, 'error', error_response)
return {
'status': 'error',
**error_response,
}
log.info(f"Success {self.execution_count}")
return {
'status': 'ok',
'execution_count': self.execution_count,
'payload': [],
'user_expressions': {},
}
def do_is_complete(self, code : str):
# TODO: make it actually work for incomplete ones. exitstatus always 0
try:
(_, exitstatus) = pexpect.run(
conf['kernel']['code_completness']['cmd'].format(code),
withexitstatus = True,
)
except pexpect.ExceptionPexpect:
return {
'status': 'unknown',
}
if exitstatus == 0:
return {
'status': 'complete',
}
elif exitstatus == 1:
return {
'status': 'invalid',
}
# Reference
# [spawn]: https://pexpect.readthedocs.io/en/stable/api/pexpect.html#spawn-class
# [zsh-prompts]: https://jlk.fjfi.cvut.cz/arch/manpages/man/zshparam.1#PARAMETERS_USED_BY_THE_SHELL
# [1]: # https://pexpect.readthedocs.io/en/stable/api/pexpect.html#pexpect.spawn.expect
# [traceback]: https://docs.python.org/3/library/traceback.html#traceback.extract_tb
# [zsh-functions]: http://zsh.sourceforge.net/Doc/Release/Functions.html
# [zsh-bracketed-paste]: https://archive.zhimingwang.org/blog/2015-09-21-zsh-51-and-bracketed-paste.html
# [pexpect-kill]: https://pexpect.readthedocs.io/en/stable/api/pexpect.html#pexpect.spawn.kill
# [os-kill]: https://docs.python.org/3/library/os.html#os.kill
# [signal]: `man signal` | zsh-kernel | /zsh_kernel-2.0-py3-none-any.whl/zsh_kernel/kernel.py | kernel.py |
# Standard Library Imports
from os import system, getenv
from time import sleep
from shlex import quote
# 3rd Party Library Imports
import libtmux
from halo import Halo
from pyfiglet import Figlet
from colorama import Fore, Style
from PyInquirer import prompt, style_from_dict, Token, \
Validator, ValidationError
############
# Prettify #
############
def print_blue(text):
print(Fore.BLUE + Style.BRIGHT + text + Style.RESET_ALL)
def print_red(text):
print(Fore.RED + Style.BRIGHT + text + Style.RESET_ALL)
def print_yellow(text):
print(Fore.YELLOW + Style.BRIGHT + text + Style.RESET_ALL)
def print_green(text):
print(Fore.GREEN + Style.BRIGHT + text + Style.RESET_ALL)
def splash():
"""Print splash screen text. Uses env vars for font and header if they
exist."""
font = getenv("ZSH_STARTIFY_HEADER_FONT", "univers")
text = getenv("ZSH_STARTIFY_HEADER_TEXT", "zsh")
fig = Figlet(font=font)
formatted = "\t" + fig.renderText(text).replace("\n", "\n\t")
# TODO: Python lolcat would be more efficient, but don't care for now.
rainbow = True
if rainbow:
system("echo " + quote(formatted) + " | lolcat")
else:
print_green(formatted)
def sleep_with_spinner(secs):
"""Sleep with a nice spinner and then print a success messsage."""
spinner = Halo(text='Loading', spinner='dots')
spinner.start()
sleep(secs)
spinner.succeed("Success.")
def pretty_print_session_names(sessions, splash_flag):
if not splash_flag:
print("\n")
print_blue(" === Active tmux sessions ===")
for session in sessions:
print_red(f" [*] {session}")
print()
########
# tmux #
########
def get_tmux_session_names(server) -> list:
"""Returns all current tmux session names"""
return [session.name for session in server.list_sessions()]
def get_tmux_session(server, name) -> libtmux.Session:
"""Looks up a tmux session by name and returns it if it exists. Returns
None if the session doesn't exist.
"""
session = server.find_where({"session_name": name})
if session is None:
raise ValueError(f"Error: No session of name \'{name}\' exists.")
return session
def attach_to_session(server, name):
session = get_tmux_session(server, name)
session.attach_session()
def create_new_named_session(server, name):
session = server.new_session(name)
session.attach_session()
def get_tmux_server() -> libtmux.Server:
"""
Returns tmux server if it's running, and starts one if it's not.
"""
server = libtmux.Server()
try:
server.list_sessions()
except libtmux.exc.LibTmuxException:
print_blue("Starting tmux server...")
# Apparently, there is no way to start a server without any sessions
# (https://github.com/tmux/tmux/issues/182). So, we're going to spawn a
# new server, create a dummy session and then kill it later. I'm sorry.
hack_session = "zsh-startify-tmux-server-hack"
start_server_hack = f"tmux has-session -t {hack_session} || \
tmux new-session -d -s {hack_session}"
system(start_server_hack)
# Sleep to give tmux some time to restore sessions if tmux-resurrect or
# tmux-continuum is used
# TODO: Make this sleep value configurable in .zshrc
sleep_with_spinner(5)
server = libtmux.Server()
# Kill the hacky tmux session we just started.
get_tmux_session(server, hack_session).kill_session()
return server
def is_inside_tmux_session() -> bool:
"""Returns True if already attached to a tmux session, False otherwise"""
return getenv("TMUX", "") != ""
#############
# Prompting #
#############
# These get prepended to the actions in the list for selection.
MARK = {
"tmux-session": " ",
"non-tmux-session": "- ",
}
ACTIONS = {
"zsh": "Launch zsh",
"new-tmux-session": "Create new tmux session",
"attach-tmux-session": "Attach to existing tmux session",
}
# TODO: Finalize default colors
# TODO: Make colors configurable. Maybe add color themes?
SELECTOR_STYLE = style_from_dict({
Token.QuestionMARK: '#dcbf85 bold',
Token.Question: '#1776A5 bold',
Token.Instruction: '#1776A5 bold',
Token.Pointer: '#FF9D00 bold',
Token.Selected: '#cc5454',
Token.Answer: '#f44336 bold',
})
def prompt_for_action(tmux_sessions) -> str:
"""
Show a prompt with all available tmux sessions, letting the user choose a
session to attach to, the option to create a new session, or create a
non-tmux-session session.
"""
launch_zsh = MARK["non-tmux-session"] + ACTIONS["zsh"]
choices = [
launch_zsh,
MARK["non-tmux-session"] + ACTIONS["new-tmux-session"],
{
'name': ACTIONS["attach-tmux-session"],
'disabled': 'Select from below'
}
]
choices += [MARK["tmux-session"] + session for session in tmux_sessions]
questions = [
{
'type': 'list',
'name': 'action',
'message': 'What do you want to do?',
'choices': choices
},
]
try:
answers = prompt(questions, style=SELECTOR_STYLE)
# Handle CTRL+D
except EOFError:
return launch_zsh
if answers == {}:
return launch_zsh
else:
return answers["action"]
class TmuxSessionValidator(Validator):
"""
Tmux session names must not contain periods and must not be the empty
string.
"""
def validate(self, document):
name = document.text
if len(name) == 0:
raise ValidationError(
message="tmux session name must not be an empty string",
cursor_position=0)
elif "." in name:
raise ValidationError(
message="tmux session names may not contain '.'",
cursor_position=len(name)) # Move cursor to end
def prompt_for_session_name() -> str:
questions = [
{
'type': 'input',
'name': 'session_name',
'message': 'Enter a session name',
'default': "",
'validate': TmuxSessionValidator
},
]
answers = prompt(questions, style=SELECTOR_STYLE)
return answers["session_name"]
##################
# And here we go #
##################
def action_handler(server, action):
# Attach to session
if action.startswith(MARK["tmux-session"]):
attach_to_session(server, action.strip())
# Create new session
elif ACTIONS["new-tmux-session"] in action:
session_name = prompt_for_session_name()
create_new_named_session(server, session_name)
# Launch zsh
else:
return
def main():
# If we're running in a tmux session, abort.
if is_inside_tmux_session():
return
# Print splash screen if desired
splash_flag = not getenv("ZSH_STARTIFY_NO_SPLASH", "")
if splash_flag:
splash()
server = get_tmux_server()
tmux_sessions = get_tmux_session_names(server)
# Print all session names so that if the user wants to keymash enter
# to get a shell, they can still see what sessions are there.
pretty_print_session_names(tmux_sessions, splash_flag)
# Set up interactive session picker if desired
if not getenv("ZSH_STARTIFY_NON_INTERACTIVE", ""):
action = prompt_for_action(tmux_sessions)
action_handler(server, action)
if __name__ == "__main__":
main() | zsh-startify | /zsh_startify-0.3.0-py3-none-any.whl/zsh_startify/__main__.py | __main__.py |
# zshgpt
[](https://pypi.org/project/zshgpt)
[](https://pypi.org/project/zshgpt)
-----
**Table of Contents**
- [About](#about)
- [Installation](#installation)
- [Prerequisite](#prerequisite)
- [Future plans](#future-plans)
- [License](#license)
## About

Heavily inspired by the abandoned project [https://github.com/microsoft/Codex-CLI](https://github.com/microsoft/Codex-CLI)
Made into a oh-my-zsh plugin.
In your zsh console, type a question, starting with comment sign `#`, hit `ctrl+g` and get an answer.
```bash
# Who edited README.MD last according to git history?
```
ChatGPT will then answer with e.g.:
```bash
git log -1 --format="%an" README.md
```
Hit `enter` to execute or `ctrl+c` to deny.
If asked a question that will not resolve in a command, GPT is instructed to use `#`.
```bash
# Who was Norways first prime minister?
# Norway's first prime minister was Frederik Stang, serving from 1873 to 1880.
```
## Prerequisite
* Python >= 3.7
* ZSH + Oh-my-zsh
* Valid Openai API-key
* make sure to save under `OPENAI_API_KEY` env.
* `export OPENAI_API_KEY='sk-...'`
## Installation
With zshgpt alone, you can ask questions with `zshgpt # Show me all my drives` and it will return an answer from GPT. But the true performance boost comes when you also add the zsh plugin.
```bash
pip install zshgpt # Or preferably install with pipx
mkdir $ZSH_CUSTOM/plugins/zshgpt
curl https://raw.githubusercontent.com/AndersSteenNilsen/zshgpt/main/zsh_plugin/zsh_plugin.zsh -o $ZSH_CUSTOM/plugins/zshgpt/zshgpt.plugin.zsh
```
Then add zshgpt in your list of plugins in `~/.zshrc`
```
plugins(
...
zshgpt
...
)
```
## Future plans
### Functionaliy
* Remember last couple messages so you could do something like:
```bash
# Open README.md <-- USER
# You can open the README.md file using a text editor of your choice. Here's an example using vim:
vim README.md
# But I don't have vim, can you open it in VSCode? <-- USER
code README.md
```
* Cycle through choices
* Give possibility to switch model
* Give info about how many token has been used
### CI/CD
* Pre-commit.
* Add to flatpack or similar to ease installation.
* Publish as part of git flow.
## License
`zshgpt` is distributed under the terms of the [MIT](https://spdx.org/licenses/MIT.html) license.
| zshgpt | /zshgpt-0.3.0.tar.gz/zshgpt-0.3.0/README.md | README.md |
<div align="center">
<img height="170x" src="https://ibm.github.io/zshot/img/graph.png" />
<h1>Zshot</h1>
<p>
<strong>Zero and Few shot named entity & relationships recognition</strong>
</p>
<p>
<a href="https://ibm.github.io/zshot/"><img alt="Tutorials" src="https://img.shields.io/badge/docs-tutorials-green" /></a>
<a href="https://pypi.org/project/zshot/"><img src="https://img.shields.io/pypi/v/zshot" /></a>
<a href="https://pypi.org/project/zshot/"><img src="https://img.shields.io/pypi/dm/zshot" /></a>
<a href="https://github.com/IBM/zshot/actions/workflows/python-tests.yml"> <img alt="Build" src="https://github.com/IBM/zshot/actions/workflows/python-tests.yml/badge.svg" /></a>
<a href="https://app.codecov.io/github/ibm/zshot"> <img alt="Build" src="https://codecov.io/github/ibm/zshot/branch/main/graph/badge.svg" /></a>
</p>
</div>
**Documentation**: <a href="https://ibm.github.io/zshot/" target="_blank">https://ibm.github.io/zshot</a>
**Source Code**: <a href="https://github.com/IBM/zshot" target="_blank">https://github.com/IBM/zshot</a>
Zshot is a highly customisable framework for performing Zero and Few shot named entity recognition.
Can be used to perform:
- **Mentions extraction**: Identify globally relevant mentions or mentions relevant for a given domain
- **Wikification**: The task of linking textual mentions to entities in Wikipedia
- **Zero and Few Shot named entity recognition**: using language description perform NER to generalize to unseen domains
- **Zero and Few Shot named relationship recognition** (work in progress)
## Requirements
* `Python 3.6+`
* <a href="https://spacy.io/" target="_blank"><code>spacy</code></a> - Zshot rely on <a href="https://spacy.io/" class="external-link" target="_blank">Spacy</a> for pipelining and visualization
* <a href="https://pytorch.org/get-started" target="_blank"><code>torch</code></a> - PyTorch is required to run pytorch models.
* <a href="https://huggingface.co/docs/transformers/index" target="_blank"><code>transformers</code></a> - Required for pre-trained language models.
* <a href="https://huggingface.co/docs/evaluate/index" target="_blank"><code>evaluate</code></a> - Required for evaluation.
* <a href="https://huggingface.co/docs/datasets/index" target="_blank"><code>datasets</code></a> - Required to evaluate over datasets (e.g.: OntoNotes).
## Optional Dependencies
* <a href="https://github.com/flairNLP/flair" target="_blank"><code>flair</code></a> - Required if you want to use Flair mentions extractor and for TARS linker.
* <a href="https://github.com/facebookresearch/BLINK" target="_blank"><code>blink</code></a> - Required if you want to use Blink for linking to Wikipedia pages.
## Installation
<div class="termy">
```console
$ pip install zshot
---> 100%
```
</div>
## Zshot Approach
ZShot contains two different components, the **mentions extractor** and the **linker**.
## Mentions Extractor
The **mentions extractor** will detect the possible entities (a.k.a. mentions), that will be then linked to a data source (e.g.: Wikidata) by the **linker**.
Currently, there are 4 different **mentions extractors** supported, 2 of them are based on *SpaCy*, and 2 of them are based on *Flair*. The two different versions for each library are similar, one is based on Named Entity Recognition and Classification (NERC) and the other one is based on the linguistics (i.e.: using Part Of the Speech tagging (PoS) and Dependency Parsing(DP)).
The NERC approach will use NERC models to detect all the entities that have to be linked. This approach depends on the model that is being used, and the entities the model has been trained on, so depending on the use case and the target entities it may be not the best approach, as the entities may be not recognized by the NERC model and thus won't be linked.
The linguistic approach relies on the idea that mentions will usually be a syntagma or a noun. Therefore, this approach detects nouns that are included in a syntagma and that act like objects, subjects, etc. This approach do not depend on the model (although the performance does), but a noun in a text should be always a noun, it doesn't depend on the dataset the model has been trained on.
## Linker
The **linker** will link the detected entities to a existing set of labels. Some of the **linkers**, however, are *end-to-end*, i.e. they don't need the **mentions extractor**, as they detect and link the entities at the same time.
Again, there are 4 **linkers** available currently, 2 of them are *end-to-end* and 2 are not. Let's start with those thar are not *end-to-end*:
| Linker Name | end-to-end | Source Code | Paper |
|:-----------:|:----------:|----------------------------------------------------------|--------------------------------------------------------------------|
| Blink | X | [Source Code](https://github.com/facebookresearch/BLINK) | [Paper](https://arxiv.org/pdf/1911.03814.pdf) |
| GENRE | X | [Source Code](https://github.com/facebookresearch/GENRE) | [Paper](https://arxiv.org/pdf/2010.00904.pdf) |
| SMXM | ✓ | [Source Code](https://github.com/Raldir/Zero-shot-NERC) | [Paper](https://aclanthology.org/2021.acl-long.120/) |
| TARS | ✓ | [Source Code](https://github.com/flairNLP/flair) | [Paper](https://kishaloyhalder.github.io/pdfs/tars_coling2020.pdf) |
## Example: Zero-Shot Entity Recognition
### How to use it
* Install requirements: `pip install -r requirements.txt`
* Install a spacy pipeline to use it for mentions extraction: `python -m spacy download en_core_web_sm`
* Create a file `main.py` with the pipeline configuration and entities definition (*Wikipedia abstract are usually a good starting point for descriptions*):
```Python
import spacy
from zshot import PipelineConfig, displacy
from zshot.linker import LinkerRegen
from zshot.mentions_extractor import MentionsExtractorSpacy
from zshot.utils.data_models import Entity
nlp = spacy.load("en_core_web_sm")
nlp_config = PipelineConfig(
mentions_extractor=MentionsExtractorSpacy(),
linker=LinkerRegen(),
entities=[
Entity(name="Paris",
description="Paris is located in northern central France, in a north-bending arc of the river Seine"),
Entity(name="IBM",
description="International Business Machines Corporation (IBM) is an American multinational technology corporation headquartered in Armonk, New York"),
Entity(name="New York", description="New York is a city in U.S. state"),
Entity(name="Florida", description="southeasternmost U.S. state"),
Entity(name="American",
description="American, something of, from, or related to the United States of America, commonly known as the United States or America"),
Entity(name="Chemical formula",
description="In chemistry, a chemical formula is a way of presenting information about the chemical proportions of atoms that constitute a particular chemical compound or molecule"),
Entity(name="Acetamide",
description="Acetamide (systematic name: ethanamide) is an organic compound with the formula CH3CONH2. It is the simplest amide derived from acetic acid. It finds some use as a plasticizer and as an industrial solvent."),
Entity(name="Armonk",
description="Armonk is a hamlet and census-designated place (CDP) in the town of North Castle, located in Westchester County, New York, United States."),
Entity(name="Acetic Acid",
description="Acetic acid, systematically named ethanoic acid, is an acidic, colourless liquid and organic compound with the chemical formula CH3COOH"),
Entity(name="Industrial solvent",
description="Acetamide (systematic name: ethanamide) is an organic compound with the formula CH3CONH2. It is the simplest amide derived from acetic acid. It finds some use as a plasticizer and as an industrial solvent."),
]
)
nlp.add_pipe("zshot", config=nlp_config, last=True)
text = "International Business Machines Corporation (IBM) is an American multinational technology corporation" \
" headquartered in Armonk, New York, with operations in over 171 countries."
doc = nlp(text)
displacy.serve(doc, style="ent")
```
### Run it
Run with
```console
$ python main.py
Using the 'ent' visualizer
Serving on http://0.0.0.0:5000 ...
```
The script will annotate the text using Zshot and use Displacy for visualising the annotations
### Check it
Open your browser at <a href="http://127.0.0.1:5000" class="external-link" target="_blank">http://127.0.0.1:5000</a> .
You will see the annotated sentence:
<img src="https://ibm.github.io/zshot/img/annotations.png" />
### How to create a custom component
If you want to implement your own mentions_extractor or linker and use it with ZShot you can do it. To make it easier for the user to implement a new component, some base classes are provided that you have to extend with your code.
It is as simple as create a new class extending the base class (`MentionsExtractor` or `Linker`). You will have to implement the predict method, which will receive the SpaCy Documents and will return a list of `zshot.utils.data_models.Span` for each document.
This is a simple mentions_extractor that will extract as mentions all words that contain the letter s:
```python
from typing import Iterable
import spacy
from spacy.tokens import Doc
from zshot import PipelineConfig
from zshot.utils.data_models import Span
from zshot.mentions_extractor import MentionsExtractor
class SimpleMentionExtractor(MentionsExtractor):
def predict(self, docs: Iterable[Doc], batch_size=None):
spans = [[Span(tok.idx, tok.idx + len(tok)) for tok in doc if "s" in tok.text] for doc in docs]
return spans
new_nlp = spacy.load("en_core_web_sm")
config = PipelineConfig(
mentions_extractor=SimpleMentionExtractor()
)
new_nlp.add_pipe("zshot", config=config, last=True)
text_acetamide = "CH2O2 is a chemical compound similar to Acetamide used in International Business " \
"Machines Corporation (IBM)."
doc = new_nlp(text_acetamide)
print(doc._.mentions)
>>> [is, similar, used, Business, Machines, materials]
```
### How to evaluate ZShot
Evaluation is an important process to keep improving the performance of the models, that's why ZShot allows to evaluate the component with two predefined datasets: OntoNotes and MedMentions, in a Zero-Shot version in which the entities of the test and validation splits don't appear in the train set.
The package `evaluation` contains all the functionalities to evaluate the ZShot components. The main function is `zshot.evaluation.zshot_evaluate.evaluate`, that will take as input the SpaCy `nlp` model and the dataset(s) and split(s) to evaluate. It will return a `str` containing a table with the results of the evaluation. For instance the evaluation of the ZShot custom component implemented above would be:
```python
from zshot.evaluation.zshot_evaluate import evaluate
from datasets import Split
evaluation = evaluate(new_nlp, datasets="ontonotes",
splits=[Split.VALIDATION])
print(evaluation)
```
| zshot | /zshot-0.0.4.tar.gz/zshot-0.0.4/README.md | README.md |
.. image:: https://raw.githubusercontent.com/snakypy/assets/master/zshpower/images/zshpower-transparent.png
:align: center
:alt: ZSHPower
_________________
.. image:: https://github.com/snakypy/zshpower/workflows/Tests/badge.svg
:target: https://github.com/snakypy/zshpower
.. image:: https://img.shields.io/pypi/v/zshpower.svg
:target: https://pypi.python.org/pypi/zshpower
:alt: PyPI - ZSHPower
.. image:: https://img.shields.io/pypi/wheel/zshpower
:target: https://pypi.org/project/wheel/
:alt: PyPI - Wheel
.. image:: https://img.shields.io/pypi/pyversions/zshpower
:target: https://pyup.io/repos/github/snakypy/zshpower/
:alt: Python versions
.. image:: https://img.shields.io/badge/code%20style-black-000000.svg
:target: https://github.com/psf/black
:alt: Black
.. image:: https://img.shields.io/badge/%20imports-isort-%231674b1?style=flat&labelColor=ef8336
:target: https://pycqa.github.io/isort/
:alt: Isort
.. image:: http://www.mypy-lang.org/static/mypy_badge.svg
:target: http://mypy-lang.org/
:alt: Mypy
.. image:: https://pyup.io/repos/github/snakypy/zshpower/shield.svg
:target: https://pyup.io/repos/github/snakypy/zshpower/
:alt: Updates
.. image:: https://img.shields.io/github/issues-raw/snakypy/zshpower
:target: https://github.com/snakypy/zshpower/issues
:alt: GitHub issues
.. image:: https://img.shields.io/github/license/snakypy/zshpower
:target: https://github.com/snakypy/zshpower/blob/main/LICENSE
:alt: GitHub license
_________________
`ZSHPower` is a theme for ZSH; especially for the `Python`_ developer. Pleasant to look at, the **ZSHPower** comforts you with its colors and icons vibrant.
Installing **ZSHPower** is the easiest thing you will see in any existing theme for **ZSH**, because there is a manager.
The changes in the theme become more dynamic through a configuration file, where the user can make various combinations for the style of **ZSHPower**.
The **ZSHPower** supports installation along with `Oh My ZSH`_, where changes to: **enable** and **disable** an `Oh My ZSH`_ theme are easier, all in a simplified command line, without opening any files or creating symbolic links.
In addition, the **ZSHPower** manager downloads **Oh My Zsh** and the
`zsh-autosuggestions`_ and `zsh-syntax-highlighting`_ plugins automatically, everything to make your ZSH very power.
Requirements
------------
To work correctly, you will first need:
* `git`_ (v2.25 or recent) must be installed.
* `zsh`_ (v5.2 or recent) must be installed.
* `python`_ (v3.9 or recent) must be installed.
* `sqlite3`_ (v3.35 or recent) must be installed.
* `pip`_ (v21.0.1 or recent) must be installed.
* `nerd fonts`_ must be installed.
Features
--------
* `Oh My Zsh`_ installation automatically;*
* Automatically install `zsh-autosuggestions`_ and `zsh-syntax-highlighting`_;
* Automated installation and uninstallation;
* Enable and disable `ZSHPower` anytime;
* Upgrade `ZSHPower` effortlessly;
* Reset the settings with one command only;
* Personalized directory with truncate option;
* Current Git branch and rich repo status:
* — untracked changes;
* — new files added;
* — deleted files;
* — new modified files;
* — commits made;
* — and more.
* Application versions shown with `nerd fonts`_, they are:
* CMake, Crystal, Dart, Deno, Docker, Docker, Dotnet, Elixir, Erlang, Go, Gulp, Helm, Java, Julia, Kotlin, Nim, NodeJS, Ocaml, Perl, Php, Python, Ruby, Rust, Scala, Vagrant, Zig
* Package versions such as Crystal, Helm, NodeJS, Python, Rust shown;
* Shows the time in the upper right corner;
* and, many other dynamic settings in `$HOME/.zshpower/config/zshpower.toml`.
\* features if used with **Oh My ZSH**.
Installing
----------
.. code-block:: shell
$ python3 -m pip install zshpower --user
NOTE: It is recommended that you install for user rather than global.
Using
-----
Run the command below to set `ZSHPower`_ on your ZSH:
.. code-block:: shell
$ zshpower init
If you want to use ZSHPower with `Oh My Zsh`_, use the **--omz** flag:
.. code-block:: shell
$ zshpower init --omz
For more command information, run:
.. code-block:: shell
$ zshpower --help
More information: https://github.com/snakypy/zshpower
Donation
--------
Click on the image below to be redirected the donation forms:
.. image:: https://raw.githubusercontent.com/snakypy/donations/main/svg/donate/donate-hand.svg
:width: 160 px
:height: 100px
:target: https://github.com/snakypy/donations/blob/main/README.md
License
-------
The gem is available as open source under the terms of the `MIT License`_ ©
Credits
-------
See, `AUTHORS`_.
Links
-----
* Code: https://github.com/snakypy/zshpower
* Documentation: https://github.com/snakypy/zshpower/blob/main/README.md
* Releases: https://pypi.org/project/zshpower/#history
* Issue tracker: https://github.com/snakypy/zshpower/issues
.. _AUTHORS: https://github.com/snakypy/zshpower/blob/main/AUTHORS.rst
.. _Oh My Zsh: https://ohmyz.sh
.. _zsh-autosuggestions: https://github.com/zsh-users/zsh-autosuggestions
.. _zsh-syntax-highlighting: https://github.com/zsh-users/zsh-syntax-highlighting
.. _ZSHPower: https://github.com/snakypy/zshpower
.. _git: https://git-scm.com/downloads
.. _zsh: http://www.zsh.org/
.. _python: https://python.org
.. _sqlite3: https://www.sqlite.org
.. _pip: https://pip.pypa.io/en/stable/quickstart/
.. _nerd fonts: https://www.nerdfonts.com/font-downloads
.. _MIT License: https://github.com/snakypy/zshpower/blob/main/LICENSE
.. _William Canin: http://williamcanin.github.io
.. _Cookiecutter: https://github.com/audreyr/cookiecutter
.. _`williamcanin/pypkg-cookiecutter`: https://github.com/williamcanin/pypkg-cookiecutter
| zshpower | /zshpower-0.11.8.tar.gz/zshpower-0.11.8/README.rst | README.rst |
import getopt, socket, sys
from cpackets import testlist
try:
(opts, args) = getopt.getopt(sys.argv[1:],
'h:lp:qst:w',
( 'host=', 'list', 'port=',
'quit', 'statusonly', 'test=', 'wsdl', 'help'))
except getopt.GetoptError, e:
print >>sys.stderr, sys.argv[0] + ': ' + str(e)
sys.exit(1)
if args:
print sys.argv[0] + ': Usage error; try --help.'
sys.exit(1)
hostname, portnum, tests, quitting, getwsdl, verbose = \
'localhost', 1122, [0,1], 0, 0, 1
for opt, val in opts:
if opt in [ '--help' ]:
print '''Options include:
--host HOST (-h HOST) Name of server host
--port PORT (-p PORT) Port server is listening on
--quit (-q) Send server a QUIT command
--testnum 1,2,3 (-t ...) Run comma-separated tests; use * or all for all
--list (-l) List tests (brief description)
--statusonly (-s) Do not output reply packets; just status code
--wsdl (-w) Get the WSDL file
Default is -h%s -p%d -t%s''' % \
(hostname, portnum, ','.join([str(x) for x in tests]))
sys.exit(0)
if opt in [ '-h', '--host' ]:
hostname = val
elif opt in [ '-p', '--port' ]:
portnum = int(val)
elif opt in [ '-s', '--statusonly' ]:
verbose = 0
elif opt in [ '-q', '--quit' ]:
quitting = 1
elif opt in [ '-t', '--testnum' ]:
if val in [ '*', 'all' ]:
tests = range(len(testlist))
else:
tests = [ int(t) for t in val.split(',') ]
elif opt in [ '-l', '--list' ]:
for i in range(len(testlist)):
print i, testlist[i][0]
sys.exit(0)
elif opt in [ '-w', '--wsdl' ]:
getwsdl = 1
if quitting:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((hostname, portnum))
except socket.error, e:
if e.args[1] == 'Connection refused': sys.exit(0)
raise
f = s.makefile('r+')
f.write('QUIT / HTTP/1.0\r\n')
f.flush()
sys.exit(0)
if getwsdl:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((hostname, portnum))
f = s.makefile('r+')
f.write('GET /wsdl HTTP/1.0\r\n\r\n')
f.flush()
status = f.readline()
print status,
while 1:
l = f.readline()
if l == '': break
print l,
sys.exit(0)
for T in tests:
descr, IN, header = testlist[T]
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((hostname, portnum))
f = s.makefile('r+')
print '-' * 60, '\n\n\n', T, descr
f.write('POST / HTTP/1.0\r\n')
f.write('SOAPAction: "http://soapinterop.org/"\r\n')
if header == None:
f.write('Content-type: text/xml; charset="utf-8"\r\n')
f.write('Content-Length: %d\r\n\r\n' % len(IN))
else:
f.write(header)
f.write(IN)
f.flush()
status = f.readline()
print status,
while 1:
l = f.readline()
if l == '': break
if verbose: print l,
f.close() | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/interop/client.py | client.py |
WSDL_DEFINITION = '''<?xml version="1.0"?>
<definitions name="InteropTest"
targetNamespace="http://soapinterop.org/"
xmlns="http://schemas.xmlsoap.org/wsdl/"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://soapinterop.org/">
<import
location="http://www.whitemesa.com/interop/InteropTest.wsdl"
namespace="http://soapinterop.org/xsd"/>
<import
location="http://www.whitemesa.com/interop/InteropTest.wsdl"
namespace="http://soapinterop.org/"/>
<import
location="http://www.whitemesa.com/interop/InteropTestB.wsdl"
namespace="http://soapinterop.org/"/>
<import
location="http://www.whitemesa.com/interop/echoHeaderBindings.wsdl"
namespace="http://soapinterop.org/"/>
<import
location="http://www.whitemesa.com/interop/InteropTestMap.wsdl"
namespace="http://soapinterop.org/"/>
<!-- DOCSTYLE; soon.
<import
location="http://www.whitemesa.com/interop/interopdoc.wsdl"
namespace="http://soapinterop.org/"/>
-->
<service name="interop">
<port name="TestSoap" binding="tns:InteropTestSoapBinding">
<soap:address location=">>>URL<<<"/>
</port>
<port name="TestSoapB" binding="tns:InteropTestSoapBindingB">
<soap:address location=">>>URL<<<"/>
</port>
<port name="EchoHeaderString" binding="tns:InteropEchoHeaderStringBinding">
<soap:address location=">>>URL<<<"/>
</port>
<port name="EchoHeaderStruct" binding="tns:InteropEchoHeaderStructBinding">
<soap:address location=">>>URL<<<"/>
</port>
<port name="TestSoapMap" binding="tns:InteropTestSoapBindingMap">
<soap:address location=">>>URL<<<"/>
</port>
<!-- DOCSTYLE; soon.
<port name="TestDoc" binding="tns:doc_test_binding">
<soap:address location=">>>URL<<<"/>
</port>
-->
</service>
</definitions>
'''
from ZSI import *
from ZSI import _copyright, _seqtypes
import types
class SOAPStruct:
def __init__(self, name):
pass
def __str__(self):
return str(self.__dict__)
class TC_SOAPStruct(TC.Struct):
def __init__(self, pname=None, **kw):
TC.Struct.__init__(self, SOAPStruct, [
TC.String('varString', strip=0, inline=1),
TC.Iint('varInt'),
TC.FPfloat('varFloat', format='%.18g'),
], pname, **kw)
class TC_SOAPStructStruct(TC.Struct):
def __init__(self, pname=None, **kw):
TC.Struct.__init__(self, SOAPStruct, [
TC.String('varString', strip=0),
TC.Iint('varInt'),
TC.FPfloat('varFloat', format='%.18g'),
TC_SOAPStruct('varStruct'),
], pname, **kw)
class TC_SOAPArrayStruct(TC.Struct):
def __init__(self, pname=None, **kw):
TC.Struct.__init__(self, SOAPStruct, [
TC.String('varString', strip=0),
TC.Iint('varInt'),
TC.FPfloat('varFloat', format='%.18g'),
TC.Array('xsd:string', TC.String(string=0), 'varArray'),
], pname, **kw)
class TC_ArrayOfstring(TC.Array):
def __init__(self, pname=None, **kw):
TC.Array.__init__(self, 'xsd:string', TC.String(string=0), pname, **kw)
class TC_ArrayOfint(TC.Array):
def __init__(self, pname=None, **kw):
TC.Array.__init__(self, 'xsd:int', TC.Iint(), pname, **kw)
class TC_ArrayOffloat(TC.Array):
def __init__(self, pname=None, **kw):
TC.Array.__init__(self, 'xsd:float', TC.FPfloat(format='%.18g'),
pname, **kw)
class TC_ArrayOfSOAPStruct(TC.Array):
def __init__(self, pname=None, **kw):
TC.Array.__init__(self, 'Za:SOAPStruct', TC_SOAPStruct(), pname, **kw)
#class TC_ArrayOfstring2D(TC.Array):
# def __init__(self, pname=None, **kw):
# TC.Array.__init__(self, 'xsd:string', TC.String(string=0), pname, **kw)
class RPCParameters:
def __init__(self, name):
pass
def __str__(self):
t = str(self.__dict__)
if hasattr(self, 'inputStruct'):
t += '\ninputStruct\n'
t += str(self.inputStruct)
if hasattr(self, 'inputStructArray'):
t += '\ninputStructArray\n'
t += str(self.inputStructArray)
return t
def frominput(self, arg):
self.v = s = SOAPStruct(None)
self.v.varString = arg.inputString
self.v.varInt = arg.inputInteger
self.v.varFloat = arg.inputFloat
return self
class Operation:
dispatch = {}
SOAPAction = '''"http://soapinterop.org/"'''
ns = "http://soapinterop.org/"
hdr_ns = "http://soapinterop.org/echoheader/"
def __init__(self, name, tcin, tcout, **kw):
self.name = name
if type(tcin) not in _seqtypes: tcin = tcin,
self.TCin = TC.Struct(RPCParameters, tuple(tcin), name)
if type(tcout) not in _seqtypes: tcout = tcout,
self.TCout = TC.Struct(RPCParameters, tuple(tcout), name + 'Response')
self.convert = kw.get('convert', None)
self.headers = kw.get('headers', [])
self.nsdict = kw.get('nsdict', {})
Operation.dispatch[name] = self
Operation("echoString",
TC.String('inputString', strip=0),
TC.String('inputString', oname='return', strip=0)
)
Operation("echoStringArray",
TC_ArrayOfstring('inputStringArray'),
TC_ArrayOfstring('inputStringArray', oname='return')
)
Operation("echoInteger",
TC.Iint('inputInteger'),
TC.Iint('inputInteger', oname='return'),
)
Operation("echoIntegerArray",
TC_ArrayOfint('inputIntegerArray'),
TC_ArrayOfint('inputIntegerArray', oname='return'),
)
Operation("echoFloat",
TC.FPfloat('inputFloat', format='%.18g'),
TC.FPfloat('inputFloat', format='%.18g', oname='return'),
)
Operation("echoFloatArray",
TC_ArrayOffloat('inputFloatArray'),
TC_ArrayOffloat('inputFloatArray', oname='return'),
)
Operation("echoStruct",
TC_SOAPStruct('inputStruct'),
TC_SOAPStruct('inputStruct', oname='return'),
)
Operation("echoStructArray",
TC_ArrayOfSOAPStruct('inputStructArray'),
TC_ArrayOfSOAPStruct('inputStructArray', oname='return'),
nsdict={'Za': 'http://soapinterop.org/xsd'}
)
Operation("echoVoid",
[],
[],
headers=( ( Operation.hdr_ns, 'echoMeStringRequest' ),
( Operation.hdr_ns, 'echoMeStructRequest' ) )
)
Operation("echoBase64",
TC.Base64String('inputBase64'),
TC.Base64String('inputBase64', oname='return'),
)
Operation("echoDate",
TC.gDateTime('inputDate'),
TC.gDateTime('inputDate', oname='return'),
)
Operation("echoHexBinary",
TC.HexBinaryString('inputHexBinary'),
TC.HexBinaryString('inputHexBinary', oname='return'),
)
Operation("echoDecimal",
TC.Decimal('inputDecimal'),
TC.Decimal('inputDecimal', oname='return'),
)
Operation("echoBoolean",
TC.Boolean('inputBoolean'),
TC.Boolean('inputBoolean', oname='return'),
)
Operation("echoStructAsSimpleTypes",
TC_SOAPStruct('inputStruct'),
( TC.String('outputString', strip=0), TC.Iint('outputInteger'),
TC.FPfloat('outputFloat', format='%.18g') ),
convert=lambda s: (s.v.varString, s.v.varInt, s.v.varFloat),
)
Operation("echoSimpleTypesAsStruct",
( TC.String('inputString', strip=0), TC.Iint('inputInteger'),
TC.FPfloat('inputFloat') ),
TC_SOAPStruct('v', opname='return'),
convert=lambda arg: RPCParameters(None).frominput(arg),
)
#Operation("echo2DStringArray",
# TC_ArrayOfstring2D('input2DStringArray'),
# TC_ArrayOfstring2D('return')
#),
Operation("echoNestedStruct",
TC_SOAPStructStruct('inputStruct'),
TC_SOAPStructStruct('inputStruct', oname='return'),
)
Operation("echoNestedArray",
TC_SOAPArrayStruct('inputStruct'),
TC_SOAPArrayStruct('inputStruct', oname='return'),
) | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/interop/sclasses.py | sclasses.py |
pocketsoap_struct_test = '''<SOAP-ENV:Envelope
xmlns="http://www.example.com/schemas/TEST"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:ZSI="http://www.zolera.com/schemas/ZSI/"
xmlns:ps42='http://soapinterop.org/xsd'
xmlns:xsd='http://www.w3.org/1999/XMLSchema'
xmlns:xsi='http://www.w3.org/1999/XMLSchema-instance'>
<SOAP-ENV:Header>
<ww:echoMeStringRequest xmlns:ww="http://soapinterop.org/echoheader/">
Please release <me</ww:echoMeStringRequest>
</SOAP-ENV:Header>
<SOAP-ENV:Body>
<m:echoStruct xmlns:m='http://soapinterop.org/'>
<inputStruct xsi:type='ps42:SOAPStruct'>
<varInt xsi:type='xsd:int'>1073741824</varInt>
<varFloat xsi:type='xsd:float'>-42.24</varFloat>
<varString xsi:type='xsd:string'>pocketSOAP
rocks!<g></varString>
</inputStruct>
</m:echoStruct>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>'''
phalanx_b64_test = '''<SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:m='http://soapinterop.org/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:SOAP-ENC='http://schemas.xmlsoap.org/soap/encoding/' xmlns:xsd='http://www.w3.org/2001/XMLSchema' SOAP-ENV:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'>
<SOAP-ENV:Body>
<m:echoBase64>
<inputBase64 xsi:type='xsd:base64Binary'>Ty4rY6==</inputBase64>
</m:echoBase64>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>'''
hexbin_test = '''<SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:m='http://soapinterop.org/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:SOAP-ENC='http://schemas.xmlsoap.org/soap/encoding/' xmlns:xsd='http://www.w3.org/2001/XMLSchema' SOAP-ENV:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'>
<SOAP-ENV:Body>
<m:echoHexBinary>
<inputHexBinary xsi:type='xsd:hexBinary'>656174206d792073686f72747321</inputHexBinary>
</m:echoHexBinary>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>'''
phalanx_badhref_test = '''<SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:ns1='http://soapinterop.org/xsd' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:ns='http://soapinterop.org/' xmlns:SOAP-ENC='http://schemas.xmlsoap.org/soap/encoding/' SOAP-ENV:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'>
<SOAP-ENV:Body>
<ns:echoStructArray>
<inputStructArray xsi:type='SOAP-ENC:Array' SOAP-ENC:arrayType='ns1:SOAPStruct[3]'>
<item xsi:type='ns1:SOAPStruct' href='#2'>invalid value</item>
<item xsi:type='ns1:SOAPStruct'>
<varFloat xsi:type='xsd:float'>21.02</varFloat>
<varString xsi:type='xsd:string'>c</varString>
<varInt xsi:type='xsd:int'>3</varInt>
</item>
<item xsi:type='ns1:SOAPStruct' href='#1'/>
</inputStructArray>
</ns:echoStructArray>
<mrA xsi:type='ns1:SOAPStruct' id='1'>
<varInt xsi:type='xsd:int'>-33</varInt>
<varFloat xsi:type='xsd:float'>33.33</varFloat>
<varString xsi:type='xsd:string'>test 1</varString>
</mrA>
<mrB xsi:type='ns1:SOAPStruct' id='2'>
<varFloat xsi:type='xsd:float'>11.11</varFloat>
<varString xsi:type='xsd:string'>test 2</varString>
<varInt xsi:type='xsd:int'>-11</varInt>
</mrB>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>'''
someones_b64_test = '''<S:Envelope
S:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'
xmlns:S='http://schemas.xmlsoap.org/soap/envelope/'
xmlns:E='http://schemas.xmlsoap.org/soap/encoding/'
xmlns:a='http://soapinterop.org/'
xmlns:b='http://www.w3.org/2001/XMLSchema-instance'>
<S:Body>
<a:echoBase64><inputBase64
b:type='E:base64'>AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T1</inputBase64>
</a:echoBase64>
</S:Body></S:Envelope>'''
phalanx_void_test = '''<SOAP-ENV:Envelope
xmlns="http://www.example.com/schemas/TEST"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:ZSI="http://www.zolera.com/schemas/ZSI/"
xmlns:ps42='http://soapinterop.org/xsd'
xmlns:xsd='http://www.w3.org/1999/XMLSchema'
xmlns:xsi='http://www.w3.org/1999/XMLSchema-instance'>
<SOAP-ENV:Header>
<ww:echoMeStringRequest SOAP-ENV:mustUnderstand="1" xmlns:ww="http://soapinterop.org/echoheader/">
Please release me</ww:echoMeStringRequest>
<ww:echoMeStructRequest xmlns:ww="http://soapinterop.org/echoheader/">
<varInt>111</varInt>
<varFloat>-42.24</varFloat>
<varString>Header text string.</varString>
</ww:echoMeStructRequest>
</SOAP-ENV:Header>
<SOAP-ENV:Body>
<m:echoVoid xmlns:m='http://soapinterop.org/'/>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>'''
multipart_test = '''
Ignore this
--sep
Content-Type: text/xml
<SOAP-ENV:Envelope
xmlns="http://www.example.com/schemas/TEST"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:ZSI="http://www.zolera.com/schemas/ZSI/"
xmlns:ps42='http://soapinterop.org/xsd'
xmlns:xsd='http://www.w3.org/1999/XMLSchema'
xmlns:xsi='http://www.w3.org/1999/XMLSchema-instance'>
<SOAP-ENV:Body>
<m:echoStruct xmlns:m='http://soapinterop.org/'>
<inputStruct xsi:type='ps42:SOAPStruct'>
<varInt xsi:type='xsd:int'>1073741824</varInt>
<varFloat xsi:type='xsd:float'>-42.24</varFloat>
<varString xsi:type='xsd:string' href="cid:123@456"/>
</inputStruct>
</m:echoStruct>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
--sep
Content-ID: otherwise
yehll
--sep
Content-ID: 123@456
this is a very long string
it is separated over several lines.
hwlleasdfasdf
asdfad
--sep--
'''
phalanx_badstructtype_test = '''<SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:ns1='http://soapinterop.org/xsd' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:m='http://soapinterop.org/' xmlns:SOAP-ENC='http://schemas.xmlsoap.org/soap/encoding/' SOAP-ENV:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'>
<SOAP-ENV:Body>
<m:echoStruct>
<inputStruct xsi:type='ns1:roastbeef'>
<varString xsi:type='xsd:string'>easy test</varString>
<varInt xsi:type='xsd:int'>11</varInt>
<varFloat xsi:type='xsd:float'>22.33</varFloat>
</inputStruct>
</m:echoStruct>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>'''
phalanx_int_href_test = '''<SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:m='http://soapinterop.org/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:SOAP-ENC='http://schemas.xmlsoap.org/soap/encoding/' xmlns:xsd='http://www.w3.org/2001/XMLSchema' SOAP-ENV:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'>
<SOAP-ENV:Body>
<m:echoInteger>
<inputInteger href='#a1'/>
</m:echoInteger>
<multiref xsi:type='xsd:int' id='a1'>13</multiref>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
'''
wm_simple_as_struct_test = '''<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SOAP-ENV:Body>
<m:echoSimpleTypesAsStruct xmlns:m="http://soapinterop.org/">
<inputString>White Mesa Test</inputString>
<inputInteger>42</inputInteger>
<inputFloat>0.0999</inputFloat>
</m:echoSimpleTypesAsStruct>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
'''
apache_float_test = '''<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SOAP-ENV:Body>
<ns1:echoFloat xmlns:ns1="http://soapinterop.org/">
<inputFloat xsi:type="xsd:float">3.7</inputFloat>
</ns1:echoFloat>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>'''
testlist = (
( 'struct test', pocketsoap_struct_test, None),
( 'base64 test', phalanx_b64_test, None),
( 'hexBinary', hexbin_test, None),
( 'big base64 test', someones_b64_test, None),
( 'echovoid', phalanx_void_test, None),
( 'simple2struct', wm_simple_as_struct_test, None),
( 'multipart', multipart_test,
'Content-type: multipart/related; boundary="sep"\r\n' ),
( 'int href test', phalanx_int_href_test, None),
( 'apache float', apache_float_test, None),
( 'bad href test', phalanx_badhref_test, None),
( 'bad type attr on struct', phalanx_badstructtype_test, None),
) | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/interop/cpackets.py | cpackets.py |
from ZSI import *
from ZSI import _copyright, resolvers, _child_elements, _textprotect
import sys, time, cStringIO as StringIO
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from sclasses import Operation, WSDL_DEFINITION, TC_SOAPStruct
class InteropRequestHandler(BaseHTTPRequestHandler):
server_version = 'ZSI/1.2 OS390/VM5.4 ' + BaseHTTPRequestHandler.server_version
def send_xml(self, text, code=200):
'''Send some XML.'''
self.send_response(code)
self.send_header('Content-type', 'text/xml; charset="utf-8"')
self.send_header('Content-Length', str(len(text)))
self.end_headers()
self.wfile.write(text)
self.trace(text, 'SENT')
self.wfile.flush()
def send_fault(self, f):
'''Send a fault.'''
self.send_xml(f.AsSOAP(), 500)
def trace(self, text, what):
'''Log a debug/trace message.'''
F = self.server.tracefile
if not F: return
print >>F, '=' * 60, '\n%s %s %s %s:' % \
(what, self.client_address, self.path, time.ctime(time.time()))
print >>F, text
print >>F, '=' * 60, '\n'
F.flush()
def do_QUIT(self):
'''Quit.'''
self.server.quitting = 1
self.log_message('Got QUIT command')
sys.stderr.flush()
raise SystemExit
def do_GET(self):
'''The GET command. Always returns the WSDL.'''
self.send_xml(WSDL_DEFINITION.replace('>>>URL<<<', self.server.url))
def do_POST(self):
'''The POST command.'''
try:
# SOAPAction header.
action = self.headers.get('soapaction', None)
if not action:
self.send_fault(Fault(Fault.Client,
'SOAPAction HTTP header missing.'))
return
if action != Operation.SOAPAction:
self.send_fault(Fault(Fault.Client,
'SOAPAction is "%s" not "%s"' % \
(action, Operation.SOAPAction)))
return
# Parse the message.
ct = self.headers['content-type']
if ct.startswith('multipart/'):
cid = resolvers.MIMEResolver(ct, self.rfile)
xml = cid.GetSOAPPart()
ps = ParsedSoap(xml, resolver=cid.Resolve)
else:
cl = int(self.headers['content-length'])
IN = self.rfile.read(cl)
self.trace(IN, 'RECEIVED')
ps = ParsedSoap(IN)
except ParseException, e:
self.send_fault(FaultFromZSIException(e))
return
except Exception, e:
# Faulted while processing; assume it's in the header.
self.send_fault(FaultFromException(e, 1, sys.exc_info()[2]))
return
try:
# Actors?
a = ps.WhatActorsArePresent()
if len(a):
self.send_fault(FaultFromActor(a[0]))
return
# Is the operation defined?
root = ps.body_root
if root.namespaceURI != Operation.ns:
self.send_fault(Fault(Fault.Client,
'Incorrect namespace "%s"' % root.namespaceURI))
return
n = root.localName
op = Operation.dispatch.get(n, None)
if not op:
self.send_fault(Fault(Fault.Client,
'Undefined operation "%s"' % n))
return
# Scan headers. First, see if we understand all headers with
# mustUnderstand set. Then, get the ones intended for us (ignoring
# others since step 1 insured they're not mustUnderstand).
for mu in ps.WhatMustIUnderstand():
if mu not in op.headers:
uri, localname = mu
self.send_fault(FaultFromNotUnderstood(uri, localname))
return
headers = [ e for e in ps.GetMyHeaderElements()
if (e.namespaceURI, e.localName) in op.headers ]
nsdict={ 'Z': Operation.ns }
if headers:
nsdict['E'] = Operation.hdr_ns
self.process_headers(headers, ps)
else:
self.headertext = None
try:
results = op.TCin.parse(ps.body_root, ps)
except ParseException, e:
self.send_fault(FaultFromZSIException(e))
self.trace(str(results), 'PARSED')
if op.convert:
results = op.convert(results)
if op.nsdict: nsdict.update(op.nsdict)
reply = StringIO.StringIO()
sw = SoapWriter(reply, nsdict=nsdict, header=self.headertext)
sw.serialize(results, op.TCout,
name = 'Z:' + n + 'Response', inline=1)
sw.close()
self.send_xml(reply.getvalue())
except Exception, e:
# Fault while processing; now it's in the body.
self.send_fault(FaultFromException(e, 0, sys.exc_info()[2]))
return
def process_headers(self, headers, ps):
'''Process headers, set self.headertext to be what to output.
'''
self.headertext = ''
for h in headers:
if h.localName == 'echoMeStringRequest':
s = TC.String().parse(h, ps)
self.headertext += \
'<E:echoMeStringResponse>%s</E:echoMeStringResponse>\n' % _textprotect(s)
elif h.localName == 'echoMeStructRequest':
tc = TC_SOAPStruct('echoMeStructRequest', inline=1)
data = tc.parse(h, ps)
s = StringIO.StringIO()
sw = SoapWriter(s, envelope=0)
tc.serialize(sw, data, name='E:echoMeStructResponse')
sw.close()
self.headertext += s.getvalue()
else:
raise TypeError('Unhandled header ' + h.nodeName)
pass
class InteropHTTPServer(HTTPServer):
def __init__(self, me, url, **kw):
HTTPServer.__init__(self, me, InteropRequestHandler)
self.quitting = 0
self.tracefile = kw.get('tracefile', None)
self.url = url
def handle_error(self, req, client_address):
if self.quitting: sys.exit(0)
HTTPServer.handle_error(self, req, client_address)
import getopt
try:
(opts, args) = getopt.getopt(sys.argv[1:], 'l:p:t:u:',
('log=', 'port=', 'tracefile=', 'url=') )
except getopt.GetoptError, e:
print >>sys.stderr, sys.argv[0] + ': ' + str(e)
sys.exit(1)
if args:
print >>sys.stderr, sys.argv[0] + ': Usage error.'
sys.exit(1)
portnum = 1122
tracefile = None
url = None
for opt, val in opts:
if opt in [ '-l', '--logfile' ]:
sys.stderr = open(val, 'a')
elif opt in [ '-p', '--port' ]:
portnum = int(val)
elif opt in [ '-t', '--tracefile' ]:
if val == '-':
tracefile = sys.stdout
else:
tracefile = open(val, 'a')
elif opt in [ '-u', '--url' ]:
url = val
ME = ( '', portnum )
if not url:
import socket
url = 'http://' + socket.getfqdn()
if portnum != 80: url += ':%d' % portnum
url += '/interop.wsdl'
try:
InteropHTTPServer(ME, url, tracefile=tracefile).serve_forever()
except SystemExit:
pass
sys.exit(0) | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/interop/server.py | server.py |
import getopt, socket, sys
try:
(opts, args) = getopt.getopt(sys.argv[1:],
'h:p:s',
( 'host=', 'port=',
'statusonly', 'help'))
except getopt.GetoptError, e:
print >>sys.stderr, sys.argv[0] + ': ' + str(e)
sys.exit(1)
if args:
print sys.argv[0] + ': Usage error; try --help.'
sys.exit(1)
hostname, portnum, verbose = 'localhost', 80, 1
for opt, val in opts:
if opt in [ '--help' ]:
print '''Options include:
--host HOST (-h HOST) Name of server host
--port PORT (-p PORT) Port server is listening on
--statusonly (-s) Do not output reply packets; just status code
Default is -h%s -p%d -t%s''' % \
(hostname, portnum, ','.join([str(x) for x in tests]))
sys.exit(0)
if opt in [ '-h', '--host' ]:
hostname = val
elif opt in [ '-p', '--port' ]:
portnum = int(val)
elif opt in [ '-s', '--statusonly' ]:
verbose = 0
IN = '''<SOAP-ENV:Envelope
xmlns="http://www.example.com/schemas/TEST"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<hello/>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
'''
IN = '''<SOAP-ENV:Envelope
xmlns="http://www.example.com/schemas/TEST"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<echo>
<SOAP-ENC:int>1</SOAP-ENC:int>
<SOAP-ENC:int>2</SOAP-ENC:int>
</echo>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
'''
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((hostname, portnum))
f = s.makefile('r+')
f.write('POST /cgi-bin/x HTTP/1.0\r\n')
f.write('Content-type: text/xml; charset="utf-8"\r\n')
f.write('Content-Length: %d\r\n\r\n' % len(IN))
f.write(IN)
f.flush()
status = f.readline()
print status,
while 1:
l = f.readline()
if l == '': break
if verbose: print l,
f.close() | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/test/cgicli.py | cgicli.py |
from compiler.ast import Module
import StringIO, copy, getopt
import os, sys, unittest, urlparse, signal, time, warnings, subprocess
from ConfigParser import ConfigParser, NoSectionError, NoOptionError
from ZSI.wstools.TimeoutSocket import TimeoutError
"""Global Variables:
CONFIG_FILE -- configuration file
CONFIG_PARSER -- ConfigParser instance
DOCUMENT -- test section variable, specifying document style.
LITERAL -- test section variable, specifying literal encodings.
BROKE -- test section variable, specifying broken test.
TESTS -- test section variable, whitespace separated list of modules.
SECTION_CONFIGURATION -- configuration section, turn on/off debuggging.
TRACEFILE -- file class instance.
TOPDIR -- current working directory
MODULEDIR -- stubs directory
PORT -- port of local container
HOST -- address of local container
SECTION_SERVERS -- services to be tested, values are paths to executables.
"""
CONFIG_FILE = 'config.txt'
CONFIG_PARSER = ConfigParser()
DOCUMENT = 'document'
LITERAL = 'literal'
BROKE = 'broke'
TESTS = 'tests'
SECTION_CONFIGURATION = 'configuration'
SECTION_DISPATCH = 'dispatch'
TRACEFILE = sys.stdout
TOPDIR = os.getcwd()
MODULEDIR = TOPDIR + '/stubs'
SECTION_SERVERS = 'servers'
CONFIG_PARSER.read(CONFIG_FILE)
DEBUG = CONFIG_PARSER.getboolean(SECTION_CONFIGURATION, 'debug')
SKIP = CONFIG_PARSER.getboolean(SECTION_CONFIGURATION, 'skip')
TWISTED = CONFIG_PARSER.getboolean(SECTION_CONFIGURATION, 'twisted')
LAZY = CONFIG_PARSER.getboolean(SECTION_CONFIGURATION, 'lazy')
OUTPUT = CONFIG_PARSER.get(SECTION_CONFIGURATION, 'output') or sys.stdout
if DEBUG:
from ZSI.wstools.logging import setBasicLoggerDEBUG
setBasicLoggerDEBUG()
sys.path.append('%s/%s' %(os.getcwd(), 'stubs'))
ENVIRON = copy.copy(os.environ)
ENVIRON['PYTHONPATH'] = ENVIRON.get('PYTHONPATH', '') + ':' + MODULEDIR
def _SimpleMain():
"""Gets tests to run from configuration file.
"""
unittest.TestProgram(defaultTest="all")
main = _SimpleMain
def _TwistedMain():
"""Gets tests to run from configuration file.
"""
from twisted.internet import reactor
reactor.callWhenRunning(_TwistedTestProgram, defaultTest="all")
reactor.run(installSignalHandlers=0)
if TWISTED: main = _TwistedMain
def _LaunchContainer(cmd):
'''
Parameters:
cmd -- executable, sets up a ServiceContainer or ?
'''
host = CONFIG_PARSER.get(SECTION_DISPATCH, 'host')
port = CONFIG_PARSER.get(SECTION_DISPATCH, 'port')
process = subprocess.Popen([cmd, port], env=ENVIRON)
time.sleep(1)
return process
class _TwistedTestProgram(unittest.TestProgram):
def runTests(self):
from twisted.internet import reactor
if self.testRunner is None:
self.testRunner = unittest.TextTestRunner(verbosity=self.verbosity)
result = self.testRunner.run(self.test)
reactor.stop()
return result.wasSuccessful()
class ConfigException(Exception):
"""Exception thrown when configuration settings arent correct.
"""
pass
class TestException(Exception):
"""Exception thrown when test case isn't correctly set up.
"""
pass
class ServiceTestCase(unittest.TestCase):
"""Conventions for method names:
test_net*
-- network tests
test_local*
-- local tests
test_dispatch*
-- tests that use the a spawned local container
class attributes: Edit/Override these in the inheriting class as needed
out -- file descriptor to write output to
name -- configuration item, must be set in class.
url_section -- configuration section, maps a test module
name to an URL.
client_file_name --
types_file_name --
server_file_name --
"""
out = OUTPUT
name = None
url_section = 'WSDL'
client_file_name = None
types_file_name = None
server_file_name = None
def __init__(self, methodName):
"""
parameters:
methodName --
instance variables:
client_module
types_module
server_module
processID
done
"""
self.methodName = methodName
self.url = None
self.wsdl2py_args = []
self.wsdl2dispatch_args = []
self.portkwargs = {}
self.client_module = self.types_module = self.server_module = None
self.done = False
if TWISTED:
self.wsdl2py_args.append('--twisted')
if LAZY:
self.wsdl2py_args.append('--lazy')
unittest.TestCase.__init__(self, methodName)
write = lambda self, arg: self.out.write(arg)
if sys.version_info[:2] >= (2,5):
_exc_info = unittest.TestCase._exc_info
else:
_exc_info = unittest.TestCase._TestCase__exc_info
def __call__(self, *args, **kwds):
self.run(*args, **kwds)
def run(self, result=None):
if result is None: result = self.defaultTestResult()
result.startTest(self)
testMethod = getattr(self, self.methodName)
try:
try:
self.setUp()
except KeyboardInterrupt:
raise
except:
result.addError(self, self._exc_info())
return
ok = False
try:
t1 = time.time()
pyobj = testMethod()
t2 = time.time()
ok = True
except self.failureException:
result.addFailure(self, self._exc_info())
except KeyboardInterrupt:
raise
except:
result.addError(self, self._exc_info())
try:
self.tearDown()
except KeyboardInterrupt:
raise
except:
result.addError(self, self._exc_info())
ok = False
if ok:
result.addSuccess(self)
print>>self
print>>self, "|"+"-"*60
print>>self, "| TestCase: %s" %self.methodName
print>>self, "|"+"-"*20
print>>self, "| run time: %s ms" %((t2-t1)*1000)
print>>self, "| return : %s" %pyobj
print>>self, "|"+"-"*60
finally:
result.stopTest(self)
def getPortKWArgs(self):
kw = {}
if CONFIG_PARSER.getboolean(SECTION_CONFIGURATION, 'tracefile'):
kw['tracefile'] = TRACEFILE
kw.update(self.portkwargs)
return kw
def _setUpDispatch(self):
"""Set this test up as a dispatch test.
url --
"""
host = CONFIG_PARSER.get(SECTION_DISPATCH, 'host')
port = CONFIG_PARSER.get(SECTION_DISPATCH, 'port')
path = CONFIG_PARSER.get(SECTION_DISPATCH, 'path')
scheme = 'http'
netloc = '%s:%s' %(host, port)
params = query = fragment = None
self.portkwargs['url'] = \
urlparse.urlunparse((scheme,netloc,path,params,query,fragment))
_wsdl = {}
def _generate(self):
"""call the wsdl2py and wsdl2dispatch scripts and
automatically add the "-f" or "-u" argument. Other args
can be appended via the "wsdl2py_args" and "wsdl2dispatch_args"
instance attributes.
"""
url = self.url
if SKIP:
ServiceTestCase._wsdl[url] = True
return
args = []
ServiceTestCase._wsdl[url] = False
if os.path.isfile(url):
args += ['-f', os.path.abspath(url)]
else:
args += ['-u', url]
try:
os.mkdir(MODULEDIR)
except OSError, ex:
pass
os.chdir(MODULEDIR)
if MODULEDIR not in sys.path:
sys.path.append(MODULEDIR)
try:
# Client Stubs
wsdl2py = ['wsdl2py'] + args + self.wsdl2py_args
try:
exit = subprocess.call(wsdl2py)
except OSError, ex:
warnings.warn("TODO: Not sure what is going on here?")
exit = -1
#TODO: returncode WINDOWS?
self.failUnless(os.WIFEXITED(exit),
'"%s" exited with signal#: %d' %(wsdl2py, exit))
self.failUnless(exit == 0,
'"%s" exited with exit status: %d' %(wsdl2py, exit))
# Service Stubs
if '-x' not in self.wsdl2py_args:
wsdl2dispatch = (['wsdl2dispatch'] + args +
self.wsdl2dispatch_args)
try:
exit = subprocess.call(wsdl2dispatch)
except OSError, ex:
warnings.warn("TODO: Not sure what is going on here?")
#TODO: returncode WINDOWS?
self.failUnless(os.WIFEXITED(exit),
'"%s" exited with signal#: %d' %(wsdl2dispatch, exit))
self.failUnless(exit == 0,
'"%s" exited with exit status: %d' %(wsdl2dispatch, exit))
ServiceTestCase._wsdl[url] = True
finally:
os.chdir(TOPDIR)
_process = None
_lastToDispatch = None
def setUp(self):
"""Generate types and services modules once, then make them
available thru the *_module attributes if the *_file_name
attributes were specified.
"""
section = self.url_section
name = self.name
if not section or not name:
raise TestException, 'section(%s) or name(%s) not defined' %(
section, name)
if not CONFIG_PARSER.has_section(section):
raise TestException,\
'No such section(%s) in configuration file(%s)' %(
self.url_section, CONFIG_FILE)
self.url = CONFIG_PARSER.get(section, name)
status = ServiceTestCase._wsdl.get(self.url)
if status is False:
self.fail('generation failed for "%s"' %self.url)
if status is None:
self._generate()
# Check for files
tfn = self.types_file_name
cfn = self.client_file_name
sfn = self.server_file_name
files = filter(lambda f: f is not None, [cfn, tfn,sfn])
if None is cfn is tfn is sfn:
return
for n,m in map(lambda i: (i,__import__(i.split('.py')[0])), files):
if tfn is not None and tfn == n:
self.types_module = m
elif cfn is not None and cfn == n:
self.client_module = m
elif sfn is not None and sfn == n:
self.server_module = m
else:
self.fail('Unexpected module %s' %n)
# DISPATCH PORTION OF SETUP
if not self.methodName.startswith('test_dispatch'):
return
self._setUpDispatch()
if ServiceTestCase._process is not None:
return
try:
expath = CONFIG_PARSER.get(SECTION_DISPATCH, name)
except (NoSectionError, NoOptionError), ex:
self.fail('section dispatch has no item "%s"' %name)
if ServiceTestCase._lastToDispatch == expath:
return
if ServiceTestCase._lastToDispatch is not None:
ServiceTestCase.CleanUp()
ServiceTestCase._lastToDispatch = expath
ServiceTestCase._process = _LaunchContainer(TOPDIR + '/' + expath)
def CleanUp(cls):
"""call this when dispatch server is no longer needed,
maybe another needs to be started. Assumption that
a single "Suite" uses the same server, once all the
tests are run in that suite do a cleanup.
"""
if cls._process is None:
return
os.kill(cls._process.pid, signal.SIGKILL)
cls._process = None
CleanUp = classmethod(CleanUp)
class ServiceTestSuite(unittest.TestSuite):
"""A test suite is a composite test consisting of a number of TestCases.
For use, create an instance of TestSuite, then add test case instances.
When all tests have been added, the suite can be passed to a test
runner, such as TextTestRunner. It will run the individual test cases
in the order in which they were added, aggregating the results. When
subclassing, do not forget to call the base class constructor.
"""
def __init__(self, tests=()):
unittest.TestSuite.__init__(self, tests)
def __call__(self, result):
# for python2.4
return self.run(result)
def addTest(self, test):
unittest.TestSuite.addTest(self, test)
def run(self, result):
for test in self._tests:
if result.shouldStop:
break
test(result)
ServiceTestCase.CleanUp()
return result | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/test/wsdl2py/ServiceTest.py | ServiceTest.py |
import unittest, warnings
from ServiceTest import main, CONFIG_PARSER, DOCUMENT, LITERAL, BROKE, TESTS
# General targets
def dispatch():
"""Run all dispatch tests"""
return _dispatchTestSuite(broke=False)
def local():
"""Run all local tests"""
return _localTestSuite(broke=False)
def net():
"""Run all network tests"""
return _netTestSuite(broke=False)
def all():
"""Run all tests"""
return _allTestSuite(broke=False)
# Specialized binding targets
def docLitTestSuite():
"""Run all doc/lit network tests"""
return _netTestSuite(broke=False, document=True, literal=True)
def rpcLitTestSuite():
"""Run all rpc/lit network tests"""
return _netTestSuite(broke=False, document=False, literal=True)
def rpcEncTestSuite():
"""Run all rpc/enc network tests"""
return _netTestSuite(broke=False, document=False, literal=False)
# Low level functions
def _allTestSuite(document=None, literal=None, broke=None):
return _makeTestSuite('all', document, literal, broke)
def _netTestSuite(document=None, literal=None, broke=None):
return _makeTestSuite('net', document, literal, broke)
def _localTestSuite(document=None, literal=None, broke=None):
return _makeTestSuite('local', document, literal, broke)
def _dispatchTestSuite(document=None, literal=None, broke=None):
return _makeTestSuite('dispatch', document, literal, broke)
def _makeTestSuite(test, document=None, literal=None, broke=None):
"""Return a test suite containing all test cases that satisfy
the parameters. None means don't check.
Parameters:
test -- "net" run network tests, "local" run local tests,
"dispatch" run dispatch tests, "all" run all tests.
document -- None, True, False
literal -- None, True, False
broke -- None, True, False
"""
assert test in ['net', 'local', 'dispatch', 'all'],(
'test must be net, local, dispatch, or all')
cp = CONFIG_PARSER
testSections = []
sections = [\
'rpc_encoded' , 'rpc_encoded_broke',
'rpc_literal', 'rpc_literal_broke', 'rpc_literal_broke_interop',
'doc_literal', 'doc_literal_broke', 'doc_literal_broke_interop',
]
boo = cp.getboolean
for s,d,l,b in map(\
lambda sec: \
(sec, (None,boo(sec,DOCUMENT)), (None,boo(sec,LITERAL)), (None,boo(sec,BROKE))), sections):
if document in d and literal in l and broke in b:
testSections.append(s)
suite = unittest.TestSuite()
for section in testSections:
moduleList = cp.get(section, TESTS).split()
for module in map(__import__, moduleList):
def _warn_empty():
warnings.warn('"%s" has no test "%s"' %(module, test))
return unittest.TestSuite()
s = getattr(module, test, _warn_empty)()
suite.addTest(s)
return suite
if __name__ == "__main__":
main() | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/test/wsdl2py/runTests.py | runTests.py |
from ZSI import _copyright, _children, _child_elements, \
_get_idstr, _stringtypes, _seqtypes, _Node, SoapWriter, ZSIException
from ZSI.TCcompound import Struct
from ZSI.TC import QName, URI, String, XMLString, AnyElement, UNBOUNDED
from ZSI.wstools.Namespaces import SOAP, ZSI_SCHEMA_URI
from ZSI.wstools.c14n import Canonicalize
from ZSI.TC import ElementDeclaration
import traceback, cStringIO as StringIO
class Detail:
def __init__(self, any=None):
self.any = any
Detail.typecode = Struct(Detail, [AnyElement(aname='any',minOccurs=0, maxOccurs="unbounded")], pname='detail', minOccurs=0)
class FaultType:
def __init__(self, faultcode=None, faultstring=None, faultactor=None, detail=None):
self.faultcode = faultcode
self.faultstring= faultstring
self.faultactor = faultactor
self.detail = detail
FaultType.typecode = \
Struct(FaultType,
[QName(pname='faultcode'),
String(pname='faultstring'),
URI(pname=(SOAP.ENV,'faultactor'), minOccurs=0),
Detail.typecode,
AnyElement(aname='any',minOccurs=0, maxOccurs=UNBOUNDED),
],
pname=(SOAP.ENV,'Fault'),
inline=True,
hasextras=0,
)
class ZSIHeaderDetail:
def __init__(self, detail):
self.any = detail
ZSIHeaderDetail.typecode =\
Struct(ZSIHeaderDetail,
[AnyElement(aname='any', minOccurs=0, maxOccurs=UNBOUNDED)],
pname=(ZSI_SCHEMA_URI, 'detail'))
class ZSIFaultDetailTypeCode(ElementDeclaration, Struct):
'''<ZSI:FaultDetail>
<ZSI:string>%s</ZSI:string>
<ZSI:trace>%s</ZSI:trace>
</ZSI:FaultDetail>
'''
schema = ZSI_SCHEMA_URI
literal = 'FaultDetail'
def __init__(self, **kw):
Struct.__init__(self, ZSIFaultDetail, [String(pname=(ZSI_SCHEMA_URI, 'string')),
String(pname=(ZSI_SCHEMA_URI, 'trace'),minOccurs=0),],
pname=(ZSI_SCHEMA_URI, 'FaultDetail'), **kw
)
class ZSIFaultDetail:
def __init__(self, string=None, trace=None):
self.string = string
self.trace = trace
def __str__(self):
if self.trace:
return self.string + '\n[trace: ' + self.trace + ']'
return self.string
def __repr__(self):
return "<%s.ZSIFaultDetail %s>" % (__name__, _get_idstr(self))
ZSIFaultDetail.typecode = ZSIFaultDetailTypeCode()
class URIFaultDetailTypeCode(ElementDeclaration, Struct):
'''
<ZSI:URIFaultDetail>
<ZSI:URI>uri</ZSI:URI>
<ZSI:localname>localname</ZSI:localname>
</ZSI:URIFaultDetail>
'''
schema = ZSI_SCHEMA_URI
literal = 'URIFaultDetail'
def __init__(self, **kw):
Struct.__init__(self, URIFaultDetail,
[String(pname=(ZSI_SCHEMA_URI, 'URI')), String(pname=(ZSI_SCHEMA_URI, 'localname')),],
pname=(ZSI_SCHEMA_URI, 'URIFaultDetail'), **kw
)
class URIFaultDetail:
def __init__(self, uri=None, localname=None):
self.URI = uri
self.localname = localname
URIFaultDetail.typecode = URIFaultDetailTypeCode()
class ActorFaultDetailTypeCode(ElementDeclaration, Struct):
'''
<ZSI:ActorFaultDetail>
<ZSI:URI>%s</ZSI:URI>
</ZSI:ActorFaultDetail>
'''
schema = ZSI_SCHEMA_URI
literal = 'ActorFaultDetail'
def __init__(self, **kw):
Struct.__init__(self, ActorFaultDetail, [String(pname=(ZSI_SCHEMA_URI, 'URI')),],
pname=(ZSI_SCHEMA_URI, 'ActorFaultDetail'), **kw
)
class ActorFaultDetail:
def __init__(self, uri=None):
self.URI = uri
ActorFaultDetail.typecode = ActorFaultDetailTypeCode()
class Fault(ZSIException):
'''SOAP Faults.
'''
Client = "SOAP-ENV:Client"
Server = "SOAP-ENV:Server"
MU = "SOAP-ENV:MustUnderstand"
def __init__(self, code, string,
actor=None, detail=None, headerdetail=None):
if detail is not None and type(detail) not in _seqtypes:
detail = (detail,)
if headerdetail is not None and type(headerdetail) not in _seqtypes:
headerdetail = (headerdetail,)
self.code, self.string, self.actor, self.detail, self.headerdetail = \
code, string, actor, detail, headerdetail
ZSIException.__init__(self, code, string, actor, detail, headerdetail)
def DataForSOAPHeader(self):
if not self.headerdetail: return None
# SOAP spec doesn't say how to encode header fault data.
return ZSIHeaderDetail(self.headerdetail)
def serialize(self, sw):
'''Serialize the object.'''
detail = None
if self.detail is not None:
detail = Detail()
detail.any = self.detail
pyobj = FaultType(self.code, self.string, self.actor, detail)
sw.serialize(pyobj, typed=False)
def AsSOAP(self, **kw):
header = self.DataForSOAPHeader()
sw = SoapWriter(**kw)
self.serialize(sw)
if header is not None:
sw.serialize_header(header, header.typecode, typed=False)
return str(sw)
def __str__(self):
strng = str(self.string) + "\n"
if hasattr(self, 'detail'):
if hasattr(self.detail, '__len__'):
for d in self.detail:
strng += str(d)
else:
strng += str(self.detail)
return strng
def __repr__(self):
return "<%s.Fault at %s>" % (__name__, _get_idstr(self))
AsSoap = AsSOAP
def FaultFromNotUnderstood(uri, localname, actor=None):
detail, headerdetail = None, URIFaultDetail(uri, localname)
return Fault(Fault.MU, 'SOAP mustUnderstand not understood',
actor, detail, headerdetail)
def FaultFromActor(uri, actor=None):
detail, headerdetail = None, ActorFaultDetail(uri)
return Fault(Fault.Client, 'Cannot process specified actor',
actor, detail, headerdetail)
def FaultFromZSIException(ex, actor=None):
'''Return a Fault object created from a ZSI exception object.
'''
mystr = getattr(ex, 'str', None) or str(ex)
mytrace = getattr(ex, 'trace', '')
elt = '''<ZSI:ParseFaultDetail>
<ZSI:string>%s</ZSI:string>
<ZSI:trace>%s</ZSI:trace>
</ZSI:ParseFaultDetail>
''' % (mystr, mytrace)
if getattr(ex, 'inheader', 0):
detail, headerdetail = None, elt
else:
detail, headerdetail = elt, None
return Fault(Fault.Client, 'Unparseable message',
actor, detail, headerdetail)
def FaultFromException(ex, inheader, tb=None, actor=None):
'''Return a Fault object created from a Python exception.
<SOAP-ENV:Fault>
<faultcode>SOAP-ENV:Server</faultcode>
<faultstring>Processing Failure</faultstring>
<detail>
<ZSI:FaultDetail>
<ZSI:string></ZSI:string>
<ZSI:trace></ZSI:trace>
</ZSI:FaultDetail>
</detail>
</SOAP-ENV:Fault>
'''
tracetext = None
if tb:
try:
lines = '\n'.join(['%s:%d:%s' % (name, line, func)
for name, line, func, text in traceback.extract_tb(tb)])
except:
pass
else:
tracetext = lines
exceptionName = ""
try:
exceptionName = ":".join([ex.__module__, ex.__class__.__name__])
except: pass
elt = ZSIFaultDetail(string=exceptionName + "\n" + str(ex), trace=tracetext)
if inheader:
detail, headerdetail = None, elt
else:
detail, headerdetail = elt, None
return Fault(Fault.Server, 'Processing Failure',
actor, detail, headerdetail)
def FaultFromFaultMessage(ps):
'''Parse the message as a fault.
'''
pyobj = ps.Parse(FaultType.typecode)
if pyobj.detail == None: detailany = None
else: detailany = pyobj.detail.any
return Fault(pyobj.faultcode, pyobj.faultstring,
pyobj.faultactor, detailany)
if __name__ == '__main__': print _copyright | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/fault.py | fault.py |
from ZSI import _copyright, _children, _attrs, _child_elements, _stringtypes, \
_backtrace, EvaluateException, ParseException, _valid_encoding, \
_Node, _find_attr, _resolve_prefix
from ZSI.TC import AnyElement
import types
from ZSI.wstools.Namespaces import SOAP, XMLNS
from ZSI.wstools.Utility import SplitQName
_find_actor = lambda E: E.getAttributeNS(SOAP.ENV, "actor") or None
_find_mu = lambda E: E.getAttributeNS(SOAP.ENV, "mustUnderstand")
_find_root = lambda E: E.getAttributeNS(SOAP.ENC, "root")
_find_id = lambda E: _find_attr(E, 'id')
class ParsedSoap:
'''A Parsed SOAP object.
Convert the text to a DOM tree and parse SOAP elements.
Instance data:
reader -- the DOM reader
dom -- the DOM object
ns_cache -- dictionary (by id(node)) of namespace dictionaries
id_cache -- dictionary (by XML ID attr) of elements
envelope -- the node holding the SOAP Envelope
header -- the node holding the SOAP Header (or None)
body -- the node holding the SOAP Body
body_root -- the serialization root in the SOAP Body
data_elements -- list of non-root elements in the SOAP Body
trailer_elements -- list of elements following the SOAP body
'''
defaultReaderClass = None
def __init__(self, input, readerclass=None, keepdom=False,
trailers=False, resolver=None, envelope=True, **kw):
'''Initialize.
Keyword arguments:
trailers -- allow trailer elments (default is zero)
resolver -- function (bound method) to resolve URI's
readerclass -- factory class to create a reader
keepdom -- do not release the DOM
envelope -- look for a SOAP envelope.
'''
self.readerclass = readerclass
self.keepdom = keepdom
if not self.readerclass:
if self.defaultReaderClass != None:
self.readerclass = self.defaultReaderClass
else:
from xml.dom.ext.reader import PyExpat
self.readerclass = PyExpat.Reader
try:
self.reader = self.readerclass()
if type(input) in _stringtypes:
self.dom = self.reader.fromString(input)
else:
self.dom = self.reader.fromStream(input)
except Exception, e:
# Is this in the header? Your guess is as good as mine.
#raise ParseException("Can't parse document (" + \
# str(e.__class__) + "): " + str(e), 0)
raise
self.ns_cache = {
id(self.dom): {
'xml': XMLNS.XML,
'xmlns': XMLNS.BASE,
'': ''
}
}
self.trailers, self.resolver, self.id_cache = trailers, resolver, {}
# Exactly one child element
c = [ E for E in _children(self.dom)
if E.nodeType == _Node.ELEMENT_NODE]
if len(c) == 0:
raise ParseException("Document has no Envelope", 0)
if len(c) != 1:
raise ParseException("Document has extra child elements", 0)
if envelope is False:
self.body_root = c[0]
return
# And that one child must be the Envelope
elt = c[0]
if elt.localName != "Envelope" \
or elt.namespaceURI != SOAP.ENV:
raise ParseException('Document has "' + elt.localName + \
'" element, not Envelope', 0)
self._check_for_legal_children("Envelope", elt)
for a in _attrs(elt):
name = a.nodeName
if name.find(":") == -1 and name not in [ "xmlns", "id" ]:
raise ParseException('Unqualified attribute "' + \
name + '" in Envelope', 0)
self.envelope = elt
if not _valid_encoding(self.envelope):
raise ParseException("Envelope has invalid encoding", 0)
# Get Envelope's child elements.
c = [ E for E in _children(self.envelope)
if E.nodeType == _Node.ELEMENT_NODE ]
if len(c) == 0:
raise ParseException("Envelope is empty (no Body)", 0)
# Envelope's first child might be the header; if so, nip it off.
elt = c[0]
if elt.localName == "Header" \
and elt.namespaceURI == SOAP.ENV:
self._check_for_legal_children("Header", elt)
self._check_for_pi_nodes(_children(elt), 1)
self.header = c.pop(0)
self.header_elements = _child_elements(self.header)
else:
self.header, self.header_elements = None, []
# Now the first child must be the body
if len(c) == 0:
raise ParseException("Envelope has header but no Body", 0)
elt = c.pop(0)
if elt.localName != "Body" \
or elt.namespaceURI != SOAP.ENV:
if self.header:
raise ParseException('Header followed by "' + \
elt.localName + \
'" element, not Body', 0, elt, self.dom)
else:
raise ParseException('Document has "' + \
elt.localName + \
'" element, not Body', 0, elt, self.dom)
self._check_for_legal_children("Body", elt, 0)
self._check_for_pi_nodes(_children(elt), 0)
self.body = elt
if not _valid_encoding(self.body):
raise ParseException("Body has invalid encoding", 0)
# Trailer elements.
if not self.trailers:
if len(c):
raise ParseException("Element found after Body",
0, elt, self.dom)
# Don't set self.trailer_elements = []; if user didn't ask
# for trailers we *want* to throw an exception.
else:
self.trailer_elements = c
for elt in self.trailer_elements:
if not elt.namespaceURI:
raise ParseException('Unqualified trailer element',
0, elt, self.dom)
# Find the serialization root. Divide the Body children into
# root (root=1), no (root=0), maybe (no root attribute).
self.body_root, no, maybe = None, [], []
for elt in _child_elements(self.body):
root = _find_root(elt)
if root == "1":
if self.body_root:
raise ParseException("Multiple seralization roots found",
0, elt, self.dom)
self.body_root = elt
elif root == "0":
no.append(elt)
elif not root:
maybe.append(elt)
else:
raise ParseException('Illegal value for root attribute',
0, elt, self.dom)
# If we didn't find a root, get the first one that didn't
# say "not me", unless they all said "not me."
if self.body_root is None:
if len(maybe):
self.body_root = maybe[0]
else:
raise ParseException('No serialization root found',
0, self.body, self.dom)
if not _valid_encoding(self.body_root):
raise ParseException("Invalid encoding", 0,
elt, self.dom)
# Now get all the non-roots (in order!).
rootid = id(self.body_root)
self.data_elements = [ E for E in _child_elements(self.body)
if id(E) != rootid ]
self._check_for_pi_nodes(self.data_elements, 0)
def __del__(self):
try:
if not self.keepdom:
self.reader.releaseNode(self.dom)
except:
pass
def _check_for_legal_children(self, name, elt, mustqualify=1):
'''Check if all children of this node are elements or whitespace-only
text nodes.
'''
inheader = name == "Header"
for n in _children(elt):
t = n.nodeType
if t == _Node.COMMENT_NODE: continue
if t != _Node.ELEMENT_NODE:
if t == _Node.TEXT_NODE and n.nodeValue.strip() == "":
continue
raise ParseException("Non-element child in " + name,
inheader, elt, self.dom)
if mustqualify and not n.namespaceURI:
raise ParseException('Unqualified element "' + \
n.nodeName + '" in ' + name, inheader, elt, self.dom)
def _check_for_pi_nodes(self, list, inheader):
'''Raise an exception if any of the list descendants are PI nodes.
'''
list = list[:]
while list:
elt = list.pop()
t = elt.nodeType
if t == _Node.PROCESSING_INSTRUCTION_NODE:
raise ParseException('Found processing instruction "<?' + \
elt.nodeName + '...>"',
inheader, elt.parentNode, self.dom)
elif t == _Node.DOCUMENT_TYPE_NODE:
raise ParseException('Found DTD', inheader,
elt.parentNode, self.dom)
list += _children(elt)
def Backtrace(self, elt):
'''Return a human-readable "backtrace" from the document root to
the specified element.
'''
return _backtrace(elt, self.dom)
def FindLocalHREF(self, href, elt, headers=1):
'''Find a local HREF in the data elements.
'''
if href[0] != '#':
raise EvaluateException(
'Absolute HREF ("%s") not implemented' % href,
self.Backtrace(elt))
frag = href[1:]
# Already found?
e = self.id_cache.get(frag)
if e: return e
# Do a breadth-first search, in the data first. Most likely
# to find multi-ref targets shallow in the data area.
list = self.data_elements[:] + [self.body_root]
if headers: list.extend(self.header_elements)
while list:
e = list.pop()
if e.nodeType == _Node.ELEMENT_NODE:
nodeid = _find_id(e)
if nodeid:
self.id_cache[nodeid] = e
if nodeid == frag: return e
list += _children(e)
raise EvaluateException('''Can't find node for HREF "%s"''' % href,
self.Backtrace(elt))
def ResolveHREF(self, uri, tc, **keywords):
r = getattr(tc, 'resolver', self.resolver)
if not r:
raise EvaluateException('No resolver for "' + uri + '"')
try:
if type(uri) == types.UnicodeType: uri = str(uri)
retval = r(uri, tc, self, **keywords)
except Exception, e:
raise EvaluateException('''Can't resolve "''' + uri + '" (' + \
str(e.__class__) + "): " + str(e))
return retval
def GetMyHeaderElements(self, actorlist=None):
'''Return a list of all elements intended for these actor(s).
'''
if actorlist is None:
actorlist = [None, SOAP.ACTOR_NEXT]
else:
actorlist = list(actorlist) + [None, SOAP.ACTOR_NEXT]
return [ E for E in self.header_elements
if _find_actor(E) in actorlist ]
def GetElementNSdict(self, elt):
'''Get a dictionary of all the namespace attributes for the indicated
element. The dictionaries are cached, and we recurse up the tree
as necessary.
'''
d = self.ns_cache.get(id(elt))
if not d:
if elt != self.dom: d = self.GetElementNSdict(elt.parentNode)
for a in _attrs(elt):
if a.namespaceURI == XMLNS.BASE:
if a.localName == "xmlns":
d[''] = a.nodeValue
else:
d[a.localName] = a.nodeValue
self.ns_cache[id(elt)] = d
return d.copy()
def GetDomAndReader(self):
'''Returns a tuple containing the dom and reader objects. (dom, reader)
Unless keepdom is true, the dom and reader objects will go out of scope
when the ParsedSoap instance is deleted. If keepdom is true, the reader
object is needed to properly clean up the dom tree with
reader.releaseNode(dom).
'''
return (self.dom, self.reader)
def IsAFault(self):
'''Is this a fault message?
'''
e = self.body_root
if not e: return 0
return e.namespaceURI == SOAP.ENV and e.localName == 'Fault'
def Parse(self, how):
'''Parse the message.
'''
if type(how) == types.ClassType: how = how.typecode
return how.parse(self.body_root, self)
def WhatMustIUnderstand(self):
'''Return a list of (uri,localname) tuples for all elements in the
header that have mustUnderstand set.
'''
return [ ( E.namespaceURI, E.localName )
for E in self.header_elements if _find_mu(E) == "1" ]
def WhatActorsArePresent(self):
'''Return a list of URI's of all the actor attributes found in
the header. The special actor "next" is ignored.
'''
results = []
for E in self.header_elements:
a = _find_actor(E)
if a not in [ None, SOAP.ACTOR_NEXT ]: results.append(a)
return results
def ParseHeaderElements(self, ofwhat):
'''Returns a dictionary of pyobjs.
ofhow -- list of typecodes w/matching nspname/pname to the header_elements.
'''
d = {}
lenofwhat = len(ofwhat)
c, crange = self.header_elements[:], range(len(self.header_elements))
for i,what in [ (i, ofwhat[i]) for i in range(lenofwhat) ]:
if isinstance(what, AnyElement):
raise EvaluateException, 'not supporting <any> as child of SOAP-ENC:Header'
v = []
occurs = 0
namespaceURI,tagName = what.nspname,what.pname
for j,c_elt in [ (j, c[j]) for j in crange if c[j] ]:
prefix,name = SplitQName(c_elt.tagName)
nsuri = _resolve_prefix(c_elt, prefix)
if tagName == name and namespaceURI == nsuri:
pyobj = what.parse(c_elt, self)
else:
continue
v.append(pyobj)
c[j] = None
if what.minOccurs > len(v) > what.maxOccurs:
raise EvaluateException, 'number of occurances(%d) doesnt fit constraints (%d,%s)'\
%(len(v),what.minOccurs,what.maxOccurs)
if what.maxOccurs == 1:
if len(v) == 0: v = None
else: v = v[0]
d[(what.nspname,what.pname)] = v
return d
if __name__ == '__main__': print _copyright | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/parse.py | parse.py |
from ZSI import _copyright, _children, _child_elements, \
_floattypes, _stringtypes, _seqtypes, _find_attr, _find_attrNS, _find_attrNodeNS, \
_find_arraytype, _find_default_namespace, _find_href, _find_encstyle, \
_resolve_prefix, _find_xsi_attr, _find_type, \
_find_xmlns_prefix, _get_element_nsuri_name, _get_idstr, \
_Node, EvaluateException, \
_valid_encoding, ParseException
from ZSI.wstools.Namespaces import SCHEMA, SOAP
from ZSI.wstools.Utility import SplitQName
from ZSI.wstools.c14n import Canonicalize
from ZSI.wstools.logging import getLogger as _GetLogger
import re, types, time, copy
from base64 import decodestring as b64decode, encodestring as b64encode
from urllib import unquote as urldecode, quote as urlencode
from binascii import unhexlify as hexdecode, hexlify as hexencode
_is_xsd_or_soap_ns = lambda ns: ns in [
SCHEMA.XSD3, SOAP.ENC, SCHEMA.XSD1, SCHEMA.XSD2, ]
_find_nil = lambda E: _find_xsi_attr(E, "null") or _find_xsi_attr(E, "nil")
def _get_xsitype(pyclass):
'''returns the xsi:type as a tuple, coupled with ZSI.schema
'''
if hasattr(pyclass,'type') and type(pyclass.type) in _seqtypes:
return pyclass.type
elif hasattr(pyclass,'type') and hasattr(pyclass, 'schema'):
return (pyclass.schema, pyclass.type)
return (None,None)
# value returned when xsi:nil="true"
Nilled = None
UNBOUNDED = 'unbounded'
class TypeCode:
'''The parent class for all parseable SOAP types.
Class data:
typechecks -- do init-time type checking if non-zero
Class data subclasses may define:
tag -- global element declaration
type -- global type definition
parselist -- list of valid SOAP types for this class, as
(uri,name) tuples, where a uri of None means "all the XML
Schema namespaces"
errorlist -- parselist in a human-readable form; will be
generated if/when needed
seriallist -- list of Python types or user-defined classes
that this typecode can serialize.
logger -- logger instance for this class.
'''
tag = None
type = (None,None)
typechecks = True
attribute_typecode_dict = None
logger = _GetLogger('ZSI.TC.TypeCode')
def __init__(self, pname=None, aname=None, minOccurs=1,
maxOccurs=1, nillable=False, typed=True, unique=True,
pyclass=None, attrs_aname='_attrs', **kw):
'''Baseclass initialization.
Instance data (and usually keyword arg)
pname -- the parameter name (localname).
nspname -- the namespace for the parameter;
None to ignore the namespace
typed -- output xsi:type attribute
unique -- data item is not aliased (no href/id needed)
minOccurs -- min occurances
maxOccurs -- max occurances
nillable -- is item nillable?
attrs_aname -- This is variable name to dictionary of attributes
encoded -- encoded namespaceURI (specify if use is encoded)
'''
if type(pname) in _seqtypes:
self.nspname, self.pname = pname
else:
self.nspname, self.pname = None, pname
if self.pname:
self.pname = str(self.pname).split(':')[-1]
self.aname = aname or self.pname
self.minOccurs = minOccurs
self.maxOccurs = maxOccurs
self.nillable = nillable
self.typed = typed
self.unique = unique
self.attrs_aname = attrs_aname
self.pyclass = pyclass
# Need this stuff for rpc/encoded.
encoded = kw.get('encoded')
if encoded is not None:
self.nspname = kw['encoded']
def parse(self, elt, ps):
'''
Parameters:
elt -- the DOM element being parsed
ps -- the ParsedSoap object.
'''
raise EvaluateException("Unimplemented evaluation", ps.Backtrace(elt))
def serialize(self, elt, sw, pyobj, name=None, orig=None, **kw):
'''
Parameters:
elt -- the current DOMWrapper element
sw -- soapWriter object
pyobj -- python object to serialize
'''
raise EvaluateException("Unimplemented evaluation", sw.Backtrace(elt))
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data.
Parameters:
text -- text content
elt -- the DOM element being parsed
ps -- the ParsedSoap object.
'''
raise EvaluateException("Unimplemented evaluation", ps.Backtrace(elt))
def serialize_as_nil(self, elt):
'''
Parameters:
elt -- the current DOMWrapper element
'''
elt.setAttributeNS(SCHEMA.XSI3, 'nil', '1')
def SimpleHREF(self, elt, ps, tag):
'''Simple HREF for non-string and non-struct and non-array.
Parameters:
elt -- the DOM element being parsed
ps -- the ParsedSoap object.
tag --
'''
if len(_children(elt)): return elt
href = _find_href(elt)
if not href:
if self.minOccurs is 0: return None
raise EvaluateException('Required' + tag + ' missing',
ps.Backtrace(elt))
return ps.FindLocalHREF(href, elt, 0)
def get_parse_and_errorlist(self):
"""Get the parselist and human-readable version, errorlist is returned,
because it is used in error messages.
"""
d = self.__class__.__dict__
parselist = d.get('parselist')
errorlist = d.get('errorlist')
if parselist and not errorlist:
errorlist = []
for t in parselist:
if t[1] not in errorlist: errorlist.append(t[1])
errorlist = ' or '.join(errorlist)
d['errorlist'] = errorlist
return (parselist, errorlist)
def checkname(self, elt, ps):
'''See if the name and type of the "elt" element is what we're
looking for. Return the element's type.
Parameters:
elt -- the DOM element being parsed
ps -- the ParsedSoap object.
'''
parselist,errorlist = self.get_parse_and_errorlist()
ns, name = _get_element_nsuri_name(elt)
if ns == SOAP.ENC:
# Element is in SOAP namespace, so the name is a type.
if parselist and \
(None, name) not in parselist and (ns, name) not in parselist:
raise EvaluateException(
'Element mismatch (got %s wanted %s) (SOAP encoding namespace)' % \
(name, errorlist), ps.Backtrace(elt))
return (ns, name)
# Not a type, check name matches.
if self.nspname and ns != self.nspname:
raise EvaluateException('Element NS mismatch (got %s wanted %s)' % \
(ns, self.nspname), ps.Backtrace(elt))
if self.pname and name != self.pname:
raise EvaluateException('Element Name mismatch (got %s wanted %s)' % \
(name, self.pname), ps.Backtrace(elt))
return self.checktype(elt, ps)
def checktype(self, elt, ps):
'''See if the type of the "elt" element is what we're looking for.
Return the element's type.
Parameters:
elt -- the DOM element being parsed
ps -- the ParsedSoap object.
'''
typeName = _find_type(elt)
if typeName is None or typeName == "":
return (None,None)
# Parse the QNAME.
prefix,typeName = SplitQName(typeName)
uri = ps.GetElementNSdict(elt).get(prefix)
if uri is None:
raise EvaluateException('Malformed type attribute (bad NS)',
ps.Backtrace(elt))
#typeName = list[1]
parselist,errorlist = self.get_parse_and_errorlist()
if not parselist or \
(uri,typeName) in parselist or \
(_is_xsd_or_soap_ns(uri) and (None,typeName) in parselist):
return (uri,typeName)
raise EvaluateException(
'Type mismatch (%s namespace) (got %s wanted %s)' % \
(uri, typeName, errorlist), ps.Backtrace(elt))
def name_match(self, elt):
'''Simple boolean test to see if we match the element name.
Parameters:
elt -- the DOM element being parsed
'''
return self.pname == elt.localName and \
self.nspname in [None, elt.namespaceURI]
def nilled(self, elt, ps):
'''Is the element NIL, and is that okay?
Parameters:
elt -- the DOM element being parsed
ps -- the ParsedSoap object.
'''
if _find_nil(elt) not in [ "true", "1"]: return False
if self.nillable is False:
raise EvaluateException('Non-nillable element is NIL',
ps.Backtrace(elt))
return True
def simple_value(self, elt, ps, mixed=False):
'''Get the value of the simple content of this element.
Parameters:
elt -- the DOM element being parsed
ps -- the ParsedSoap object.
mixed -- ignore element content, optional text node
'''
if not _valid_encoding(elt):
raise EvaluateException('Invalid encoding', ps.Backtrace(elt))
c = _children(elt)
if mixed is False:
if len(c) == 0:
raise EvaluateException('Value missing', ps.Backtrace(elt))
for c_elt in c:
if c_elt.nodeType == _Node.ELEMENT_NODE:
raise EvaluateException('Sub-elements in value',
ps.Backtrace(c_elt))
# It *seems* to be consensus that ignoring comments and
# concatenating the text nodes is the right thing to do.
return ''.join([E.nodeValue for E in c
if E.nodeType
in [ _Node.TEXT_NODE, _Node.CDATA_SECTION_NODE ]])
def parse_attributes(self, elt, ps):
'''find all attributes specified in the attribute_typecode_dict in
current element tag, if an attribute is found set it in the
self.attributes dictionary. Default to putting in String.
Parameters:
elt -- the DOM element being parsed
ps -- the ParsedSoap object.
'''
if self.attribute_typecode_dict is None:
return
attributes = {}
for attr,what in self.attribute_typecode_dict.items():
namespaceURI,localName = None,attr
if type(attr) in _seqtypes:
namespaceURI,localName = attr
value = _find_attrNodeNS(elt, namespaceURI, localName)
self.logger.debug("Parsed Attribute (%s,%s) -- %s",
namespaceURI, localName, value)
# For Now just set it w/o any type interpretation.
if value is None: continue
attributes[attr] = what.text_to_data(value, elt, ps)
return attributes
def set_attributes(self, el, pyobj):
'''Instance data attributes contains a dictionary
of keys (namespaceURI,localName) and attribute values.
These values can be self-describing (typecode), or use
attribute_typecode_dict to determine serialization.
Paramters:
el -- MessageInterface representing the element
pyobj --
'''
if not hasattr(pyobj, self.attrs_aname):
return
if not isinstance(getattr(pyobj, self.attrs_aname), dict):
raise TypeError,\
'pyobj.%s must be a dictionary of names and values'\
% self.attrs_aname
for attr, value in getattr(pyobj, self.attrs_aname).items():
namespaceURI,localName = None, attr
if type(attr) in _seqtypes:
namespaceURI, localName = attr
what = None
if getattr(self, 'attribute_typecode_dict', None) is not None:
what = self.attribute_typecode_dict.get(attr)
if what is None and namespaceURI is None:
what = self.attribute_typecode_dict.get(localName)
# allow derived type
if hasattr(value, 'typecode') and not isinstance(what, AnyType):
if what is not None and not isinstance(value.typecode, what):
raise EvaluateException, \
'self-describing attribute must subclass %s'\
%what.__class__
what = value.typecode
self.logger.debug("attribute create -- %s", value)
if isinstance(what, QName):
what.set_prefix(el, value)
#format the data
if what is None:
value = str(value)
else:
value = what.get_formatted_content(value)
el.setAttributeNS(namespaceURI, localName, value)
def set_attribute_xsi_type(self, el, **kw):
'''if typed, set the xsi:type attribute
Paramters:
el -- MessageInterface representing the element
'''
if kw.get('typed', self.typed):
namespaceURI,typeName = kw.get('type', _get_xsitype(self))
if namespaceURI and typeName:
self.logger.debug("attribute: (%s, %s)", namespaceURI, typeName)
el.setAttributeType(namespaceURI, typeName)
def set_attribute_href(self, el, objid):
'''set href attribute
Paramters:
el -- MessageInterface representing the element
objid -- ID type, unique id
'''
el.setAttributeNS(None, 'href', "#%s" %objid)
def set_attribute_id(self, el, objid):
'''set id attribute
Paramters:
el -- MessageInterface representing the element
objid -- ID type, unique id
'''
if self.unique is False:
el.setAttributeNS(None, 'id', "%s" %objid)
def get_name(self, name, objid):
'''
Paramters:
name -- element tag
objid -- ID type, unique id
'''
if type(name) is tuple:
return name
ns = self.nspname
n = name or self.pname or ('E' + objid)
return ns,n
def has_attributes(self):
'''Return True if Attributes are declared outside
the scope of SOAP ('root', 'id', 'href'), and some
attributes automatically handled (xmlns, xsi:type).
'''
if self.attribute_typecode_dict is None: return False
return len(self.attribute_typecode_dict) > 0
class SimpleType(TypeCode):
'''SimpleType -- consist exclusively of a tag, attributes, and a value
class attributes:
empty_content -- value representing an empty element.
'''
empty_content = None
logger = _GetLogger('ZSI.TC.SimpleType')
def parse(self, elt, ps):
self.checkname(elt, ps)
if len(_children(elt)) == 0:
href = _find_href(elt)
if not href:
if self.nilled(elt, ps) is False:
# No content, no HREF, not NIL: empty string
return self.text_to_data(self.empty_content, elt, ps)
# No content, no HREF, and is NIL...
if self.nillable is True:
return Nilled
raise EvaluateException('Requiredstring missing',
ps.Backtrace(elt))
if href[0] != '#':
return ps.ResolveHREF(href, self)
elt = ps.FindLocalHREF(href, elt)
self.checktype(elt, ps)
if self.nilled(elt, ps): return Nilled
if len(_children(elt)) == 0:
v = self.empty_content
else:
v = self.simple_value(elt, ps)
else:
v = self.simple_value(elt, ps)
pyobj = self.text_to_data(v, elt, ps)
# parse all attributes contained in attribute_typecode_dict
# (user-defined attributes), the values (if not None) will
# be keyed in self.attributes dictionary.
if self.attribute_typecode_dict is not None:
attributes = self.parse_attributes(elt, ps)
if attributes:
setattr(pyobj, self.attrs_aname, attributes)
return pyobj
def get_formatted_content(self, pyobj):
raise NotImplementedError, 'method get_formatted_content is not implemented'
def serialize_text_node(self, elt, sw, pyobj):
'''Serialize without an element node.
'''
textNode = None
if pyobj is not None:
text = self.get_formatted_content(pyobj)
if type(text) not in _stringtypes:
raise TypeError, 'pyobj must be a formatted string'
textNode = elt.createAppendTextNode(text)
return textNode
def serialize(self, elt, sw, pyobj, name=None, orig=None, **kw):
'''Handles the start and end tags, and attributes. callout
to get_formatted_content to get the textNode value.
Parameters:
elt -- ElementProxy/DOM element
sw -- SoapWriter instance
pyobj -- processed content
KeyWord Parameters:
name -- substitute name, (nspname,name) or name
orig --
'''
objid = _get_idstr(pyobj)
ns,n = self.get_name(name, objid)
# nillable
el = elt.createAppendElement(ns, n)
if self.nillable is True and pyobj is Nilled:
self.serialize_as_nil(el)
return None
# other attributes
self.set_attributes(el, pyobj)
# soap href attribute
unique = self.unique or kw.get('unique', False)
if unique is False and sw.Known(orig or pyobj):
self.set_attribute_href(el, objid)
return None
# xsi:type attribute
if kw.get('typed', self.typed) is True:
self.set_attribute_xsi_type(el, **kw)
# soap id attribute
if self.unique is False:
self.set_attribute_id(el, objid)
#Content, <empty tag/>c
self.serialize_text_node(el, sw, pyobj)
return el
class Any(TypeCode):
'''When the type isn't defined in the schema, but must be specified
in the incoming operation.
parsemap -- a type to class mapping (updated by descendants), for
parsing
serialmap -- same, for (outgoing) serialization
'''
logger = _GetLogger('ZSI.TC.Any')
parsemap, serialmap = {}, {}
def __init__(self, pname=None, aslist=False, minOccurs=0, **kw):
TypeCode.__init__(self, pname, minOccurs=minOccurs, **kw)
self.aslist = aslist
self.kwargs = {'aslist':aslist}
self.kwargs.update(kw)
self.unique = False
# input arg v should be a list of tuples (name, value).
def listify(self, v):
if self.aslist: return [ k for j,k in v ]
return dict(v)
def parse_into_dict_or_list(self, elt, ps):
c = _child_elements(elt)
count = len(c)
v = []
if count == 0:
href = _find_href(elt)
if not href: return v
elt = ps.FindLocalHREF(href, elt)
self.checktype(elt, ps)
c = _child_elements(elt)
count = len(c)
if count == 0: return self.listify(v)
if self.nilled(elt, ps): return Nilled
for c_elt in c:
v.append((str(c_elt.localName), self.__class__(**self.kwargs).parse(c_elt, ps)))
return self.listify(v)
def parse(self, elt, ps):
(ns,type) = self.checkname(elt, ps)
if not type and self.nilled(elt, ps): return Nilled
if len(_children(elt)) == 0:
href = _find_href(elt)
if not href:
if self.minOccurs < 1:
if _is_xsd_or_soap_ns(ns):
parser = Any.parsemap.get((None,type))
if parser: return parser.parse(elt, ps)
if ((ns,type) == (SOAP.ENC,'Array') or
(_find_arraytype(elt) or '').endswith('[0]')):
return []
return None
raise EvaluateException('Required Any missing',
ps.Backtrace(elt))
elt = ps.FindLocalHREF(href, elt)
(ns,type) = self.checktype(elt, ps)
if not type and elt.namespaceURI == SOAP.ENC:
ns,type = SOAP.ENC, elt.localName
if not type or (ns,type) == (SOAP.ENC,'Array'):
if self.aslist or _find_arraytype(elt):
return [ self.__class__(**self.kwargs).parse(e, ps)
for e in _child_elements(elt) ]
if len(_child_elements(elt)) == 0:
raise EvaluateException("Any cannot parse untyped element",
ps.Backtrace(elt))
return self.parse_into_dict_or_list(elt, ps)
parser = Any.parsemap.get((ns,type))
if not parser and _is_xsd_or_soap_ns(ns):
parser = Any.parsemap.get((None,type))
if not parser:
raise EvaluateException('''Any can't parse element''',
ps.Backtrace(elt))
return parser.parse(elt, ps)
def get_formatted_content(self, pyobj):
tc = type(pyobj)
if tc == types.InstanceType:
tc = pyobj.__class__
if hasattr(pyobj, 'typecode'):
#serializer = pyobj.typecode.serialmap.get(tc)
serializer = pyobj.typecode
else:
serializer = Any.serialmap.get(tc)
if not serializer:
tc = (types.ClassType, pyobj.__class__.__name__)
serializer = Any.serialmap.get(tc)
else:
serializer = Any.serialmap.get(tc)
if not serializer and isinstance(pyobj, time.struct_time):
from ZSI.TCtimes import gDateTime
serializer = gDateTime()
if serializer:
return serializer.get_formatted_content(pyobj)
raise EvaluateException, 'Failed to find serializer for pyobj %s' %pyobj
def serialize(self, elt, sw, pyobj, name=None, **kw):
if hasattr(pyobj, 'typecode') and pyobj.typecode is not self:
pyobj.typecode.serialize(elt, sw, pyobj, **kw)
return
objid = _get_idstr(pyobj)
ns,n = self.get_name(name, objid)
kw.setdefault('typed', self.typed)
tc = type(pyobj)
self.logger.debug('Any serialize -- %s', tc)
if tc in _seqtypes:
if self.aslist:
array = elt.createAppendElement(ns, n)
array.setAttributeType(SOAP.ENC, "Array")
array.setAttributeNS(self.nspname, 'SOAP-ENC:arrayType',
"xsd:anyType[" + str(len(pyobj)) + "]" )
for o in pyobj:
#TODO maybe this should take **self.kwargs...
serializer = getattr(o, 'typecode', self.__class__()) # also used by _AnyLax()
serializer.serialize(array, sw, o, name='element', **kw)
else:
struct = elt.createAppendElement(ns, n)
for o in pyobj:
#TODO maybe this should take **self.kwargs...
serializer = getattr(o, 'typecode', self.__class__()) # also used by _AnyLax()
serializer.serialize(struct, sw, o, **kw)
return
kw['name'] = (ns,n)
if tc == types.DictType:
el = elt.createAppendElement(ns, n)
parentNspname = self.nspname # temporarily clear nspname for dict elements
self.nspname = None
for o,m in pyobj.items():
if type(o) != types.StringType and type(o) != types.UnicodeType:
raise Exception, 'Dictionary implementation requires keys to be of type string (or unicode).' %pyobj
kw['name'] = o
kw.setdefault('typed', True)
self.serialize(el, sw, m, **kw)
# restore nspname
self.nspname = parentNspname
return
if tc == types.InstanceType:
tc = pyobj.__class__
if hasattr(pyobj, 'typecode'):
#serializer = pyobj.typecode.serialmap.get(tc)
serializer = pyobj.typecode
else:
serializer = Any.serialmap.get(tc)
if not serializer:
tc = (types.ClassType, pyobj.__class__.__name__)
serializer = Any.serialmap.get(tc)
else:
serializer = Any.serialmap.get(tc)
if not serializer and isinstance(pyobj, time.struct_time):
from ZSI.TCtimes import gDateTime
serializer = gDateTime()
if not serializer:
# Last-chance; serialize instances as dictionary
if pyobj is None:
self.serialize_as_nil(elt.createAppendElement(ns, n))
elif type(pyobj) != types.InstanceType:
raise EvaluateException('''Any can't serialize ''' + \
repr(pyobj))
else:
self.serialize(elt, sw, pyobj.__dict__, **kw)
else:
# Try to make the element name self-describing
tag = getattr(serializer, 'tag', None)
if self.pname is not None:
#serializer.nspname = self.nspname
#serializer.pname = self.pname
if "typed" not in kw:
kw['typed'] = False
elif tag:
if tag.find(':') == -1: tag = 'SOAP-ENC:' + tag
kw['name'] = tag
kw['typed'] = False
serializer.unique = self.unique
serializer.serialize(elt, sw, pyobj, **kw)
# Reset TypeCode
#serializer.nspname = None
#serializer.pname = None
class String(SimpleType):
'''A string type.
'''
empty_content = ''
parselist = [ (None,'string') ]
seriallist = [ types.StringType, types.UnicodeType ]
type = (SCHEMA.XSD3, 'string')
logger = _GetLogger('ZSI.TC.String')
def __init__(self, pname=None, strip=True, **kw):
TypeCode.__init__(self, pname, **kw)
if kw.has_key('resolver'): self.resolver = kw['resolver']
self.strip = strip
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data.
'''
if self.strip: text = text.strip()
if self.pyclass is not None:
return self.pyclass(text)
return text
def get_formatted_content(self, pyobj):
if type(pyobj) not in _stringtypes:
pyobj = str(pyobj)
if type(pyobj) == types.UnicodeType: pyobj = pyobj.encode('utf-8')
return pyobj
class URI(String):
'''A URI.
'''
parselist = [ (None,'anyURI'),(SCHEMA.XSD3, 'anyURI')]
type = (SCHEMA.XSD3, 'anyURI')
logger = _GetLogger('ZSI.TC.URI')
def text_to_data(self, text, elt, ps):
'''text --> typecode specific data.
'''
val = String.text_to_data(self, text, elt, ps)
return urldecode(val)
def get_formatted_content(self, pyobj):
'''typecode data --> text
'''
pyobj = String.get_formatted_content(self, pyobj)
return urlencode(pyobj)
class QName(String):
'''A QName type
'''
parselist = [ (None,'QName') ]
type = (SCHEMA.XSD3, 'QName')
logger = _GetLogger('ZSI.TC.QName')
def __init__(self, pname=None, strip=1, **kw):
String.__init__(self, pname, strip, **kw)
self.prefix = None
def get_formatted_content(self, pyobj):
value = pyobj
if isinstance(pyobj, tuple):
namespaceURI,localName = pyobj
if self.prefix is not None:
value = "%s:%s" %(self.prefix,localName)
return String.get_formatted_content(self, value)
def set_prefix(self, elt, pyobj):
'''use this method to set the prefix of the QName,
method looks in DOM to find prefix or set new prefix.
This method must be called before get_formatted_content.
'''
if isinstance(pyobj, tuple):
namespaceURI,localName = pyobj
self.prefix = elt.getPrefix(namespaceURI)
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data.
'''
prefix,localName = SplitQName(text)
nsdict = ps.GetElementNSdict(elt)
try:
namespaceURI = nsdict[prefix]
except KeyError, ex:
raise EvaluateException('cannot resolve prefix(%s)'%prefix,
ps.Backtrace(elt))
v = (namespaceURI,localName)
if self.pyclass is not None:
return self.pyclass(v)
return v
def serialize_text_node(self, elt, sw, pyobj):
'''Serialize without an element node.
'''
self.set_prefix(elt, pyobj)
return String.serialize_text_node(self, elt, sw, pyobj)
class Token(String):
'''an xsd:token type
'''
parselist = [ (None, 'token') ]
type = (SCHEMA.XSD3, 'token')
logger = _GetLogger('ZSI.TC.Token')
class Base64String(String):
'''A Base64 encoded string.
'''
parselist = [ (None,'base64Binary'), (SOAP.ENC, 'base64') ]
type = (SOAP.ENC, 'base64')
logger = _GetLogger('ZSI.TC.Base64String')
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data.
'''
val = b64decode(text.replace(' ', '').replace('\n','').replace('\r',''))
if self.pyclass is not None:
return self.pyclass(val)
return val
def get_formatted_content(self, pyobj):
pyobj = '\n' + b64encode(pyobj)
return String.get_formatted_content(self, pyobj)
class Base64Binary(String):
parselist = [ (None,'base64Binary'), ]
type = (SCHEMA.XSD3, 'base64Binary')
logger = _GetLogger('ZSI.TC.Base64Binary')
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data.
'''
val = b64decode(text)
if self.pyclass is not None:
return self.pyclass(val)
return val
def get_formatted_content(self, pyobj):
pyobj = b64encode(pyobj).strip()
return pyobj
class HexBinaryString(String):
'''Hex-encoded binary (yuk).
'''
parselist = [ (None,'hexBinary') ]
type = (SCHEMA.XSD3, 'hexBinary')
logger = _GetLogger('ZSI.TC.HexBinaryString')
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data.
'''
val = hexdecode(text)
if self.pyclass is not None:
return self.pyclass(val)
return val
def get_formatted_content(self, pyobj):
pyobj = hexencode(pyobj).upper()
return String.get_formatted_content(self, pyobj)
class XMLString(String):
'''A string that represents an XML document
'''
logger = _GetLogger('ZSI.TC.XMLString')
def __init__(self, pname=None, readerclass=None, **kw):
String.__init__(self, pname, **kw)
self.readerclass = readerclass
def parse(self, elt, ps):
if not self.readerclass:
from xml.dom.ext.reader import PyExpat
self.readerclass = PyExpat.Reader
v = String.parse(self, elt, ps)
return self.readerclass().fromString(v)
def get_formatted_content(self, pyobj):
pyobj = Canonicalize(pyobj)
return String.get_formatted_content(self, pyobj)
class Enumeration(String):
'''A string type, limited to a set of choices.
'''
logger = _GetLogger('ZSI.TC.Enumeration')
def __init__(self, choices, pname=None, **kw):
String.__init__(self, pname, **kw)
t = type(choices)
if t in _seqtypes:
self.choices = tuple(choices)
elif TypeCode.typechecks:
raise TypeError(
'Enumeration choices must be list or sequence, not ' + str(t))
if TypeCode.typechecks:
for c in self.choices:
if type(c) not in _stringtypes:
raise TypeError(
'Enumeration choice ' + str(c) + ' is not a string')
def parse(self, elt, ps):
val = String.parse(self, elt, ps)
if val not in self.choices:
raise EvaluateException('Value not in enumeration list',
ps.Backtrace(elt))
return val
def serialize(self, elt, sw, pyobj, name=None, orig=None, **kw):
if pyobj not in self.choices:
raise EvaluateException('Value not in enumeration list',
ps.Backtrace(elt))
String.serialize(self, elt, sw, pyobj, name=name, orig=orig, **kw)
# This is outside the Integer class purely for code esthetics.
_ignored = []
class Integer(SimpleType):
'''Common handling for all integers.
'''
ranges = {
'unsignedByte': (0, 255),
'unsignedShort': (0, 65535),
'unsignedInt': (0, 4294967295L),
'unsignedLong': (0, 18446744073709551615L),
'byte': (-128, 127),
'short': (-32768, 32767),
'int': (-2147483648L, 2147483647),
'long': (-9223372036854775808L, 9223372036854775807L),
'negativeInteger': (_ignored, -1),
'nonPositiveInteger': (_ignored, 0),
'nonNegativeInteger': (0, _ignored),
'positiveInteger': (1, _ignored),
'integer': (_ignored, _ignored)
}
parselist = [ (None,k) for k in ranges.keys() ]
seriallist = [ types.IntType, types.LongType ]
logger = _GetLogger('ZSI.TC.Integer')
def __init__(self, pname=None, format='%d', **kw):
TypeCode.__init__(self, pname, **kw)
self.format = format
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data.
'''
if self.pyclass is not None:
v = self.pyclass(text)
else:
try:
v = int(text)
except:
try:
v = long(text)
except:
raise EvaluateException('Unparseable integer',
ps.Backtrace(elt))
return v
def parse(self, elt, ps):
(ns,type) = self.checkname(elt, ps)
if self.nilled(elt, ps): return Nilled
elt = self.SimpleHREF(elt, ps, 'integer')
if not elt: return None
if type is None:
type = self.type[1]
elif self.type[1] is not None and type != self.type[1]:
raise EvaluateException('Integer type mismatch; ' \
'got %s wanted %s' % (type,self.type[1]), ps.Backtrace(elt))
v = self.simple_value(elt, ps)
v = self.text_to_data(v, elt, ps)
(rmin, rmax) = Integer.ranges.get(type, (_ignored, _ignored))
if rmin != _ignored and v < rmin:
raise EvaluateException('Underflow, less than ' + repr(rmin),
ps.Backtrace(elt))
if rmax != _ignored and v > rmax:
raise EvaluateException('Overflow, greater than ' + repr(rmax),
ps.Backtrace(elt))
return v
def get_formatted_content(self, pyobj):
return self.format %pyobj
# See credits, below.
def _make_inf():
x = 2.0
x2 = x * x
i = 0
while i < 100 and x != x2:
x = x2
x2 = x * x
i = i + 1
if x != x2:
raise ValueError("This machine's floats go on forever!")
return x
# This is outside the Decimal class purely for code esthetics.
_magicnums = { }
try:
_magicnums['INF'] = float('INF')
_magicnums['-INF'] = float('-INF')
except:
_magicnums['INF'] = _make_inf()
_magicnums['-INF'] = -_magicnums['INF']
# The following comment and code was written by Tim Peters in
# article <001401be92d2$09dcb800$5fa02299@tim> in comp.lang.python,
# also available at the following URL:
# http://groups.google.com/groups?selm=001401be92d2%2409dcb800%245fa02299%40tim
# Thanks, Tim!
# NaN-testing.
#
# The usual method (x != x) doesn't work.
# Python forces all comparisons thru a 3-outcome cmp protocol; unordered
# isn't a possible outcome. The float cmp outcome is essentially defined
# by this C expression (combining some cross-module implementation
# details, and where px and py are pointers to C double):
# px == py ? 0 : *px < *py ? -1 : *px > *py ? 1 : 0
# Comparing x to itself thus always yields 0 by the first clause, and so
# x != x is never true.
# If px and py point to distinct NaN objects, a strange thing happens:
# 1. On scrupulous 754 implementations, *px < *py returns false, and so
# does *px > *py. Python therefore returns 0, i.e. "equal"!
# 2. On Pentium HW, an unordered outcome sets an otherwise-impossible
# combination of condition codes, including both the "less than" and
# "equal to" flags. Microsoft C generates naive code that accepts
# the "less than" flag at face value, and so the *px < *py clause
# returns true, and Python returns -1, i.e. "not equal".
# So with a proper C 754 implementation Python returns the wrong result,
# and under MS's improper 754 implementation Python yields the right
# result -- both by accident. It's unclear who should be shot <wink>.
#
# Anyway, the point of all that was to convince you it's tricky getting
# the right answer in a portable way!
def isnan(x):
"""x -> true iff x is a NaN."""
# multiply by 1.0 to create a distinct object (x < x *always*
# false in Python, due to object identity forcing equality)
if x * 1.0 < x:
# it's a NaN and this is MS C on a Pentium
return 1
# Else it's non-NaN, or NaN on a non-MS+Pentium combo.
# If it's non-NaN, then x == 1.0 and x == 2.0 can't both be true,
# so we return false. If it is NaN, then assuming a good 754 C
# implementation Python maps both unordered outcomes to true.
return 1.0 == x and x == 2.0
class Decimal(SimpleType):
'''Parent class for floating-point numbers.
'''
parselist = [ (None,'decimal'), (None,'float'), (None,'double') ]
seriallist = _floattypes
type = None
ranges = {
'float': ( 7.0064923216240861E-46,
-3.4028234663852886E+38, 3.4028234663852886E+38 ),
'double': ( 2.4703282292062327E-324,
-1.7976931348623158E+308, 1.7976931348623157E+308),
}
zeropat = re.compile('[1-9]')
logger = _GetLogger('ZSI.TC.Decimal')
def __init__(self, pname=None, format='%f', **kw):
TypeCode.__init__(self, pname, **kw)
self.format = format
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data.
'''
v = text
if self.pyclass is not None:
return self.pyclass(v)
m = _magicnums.get(v)
if m: return m
try:
return float(v)
except:
raise EvaluateException('Unparseable floating point number',
ps.Backtrace(elt))
def parse(self, elt, ps):
(ns,type) = self.checkname(elt, ps)
elt = self.SimpleHREF(elt, ps, 'floating-point')
if not elt: return None
tag = getattr(self.__class__, 'type')
if tag:
if type is None:
type = tag
elif tag != (ns,type):
raise EvaluateException('Floating point type mismatch; ' \
'got (%s,%s) wanted %s' % (ns,type,tag), ps.Backtrace(elt))
# Special value?
if self.nilled(elt, ps): return Nilled
v = self.simple_value(elt, ps)
try:
fp = self.text_to_data(v, elt, ps)
except EvaluateException, ex:
ex.args.append(ps.Backtrace(elt))
raise ex
m = _magicnums.get(v)
if m:
return m
if str(fp).lower() in [ 'inf', '-inf', 'nan', '-nan' ]:
raise EvaluateException('Floating point number parsed as "' + \
str(fp) + '"', ps.Backtrace(elt))
if fp == 0 and Decimal.zeropat.search(v):
raise EvaluateException('Floating point number parsed as zero',
ps.Backtrace(elt))
(rtiny, rneg, rpos) = Decimal.ranges.get(type, (None, None, None))
if rneg and fp < 0 and fp < rneg:
raise EvaluateException('Negative underflow', ps.Backtrace(elt))
if rtiny and fp > 0 and fp < rtiny:
raise EvaluateException('Positive underflow', ps.Backtrace(elt))
if rpos and fp > 0 and fp > rpos:
raise EvaluateException('Overflow', ps.Backtrace(elt))
return fp
def get_formatted_content(self, pyobj):
if pyobj == _magicnums['INF']:
return 'INF'
elif pyobj == _magicnums['-INF']:
return '-INF'
elif isnan(pyobj):
return 'NaN'
else:
return self.format %pyobj
class Boolean(SimpleType):
'''A boolean.
'''
parselist = [ (None,'boolean') ]
seriallist = [ bool ]
type = (SCHEMA.XSD3, 'boolean')
logger = _GetLogger('ZSI.TC.Boolean')
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data.
'''
v = text
if v == 'false':
if self.pyclass is None:
return False
return self.pyclass(False)
if v == 'true':
if self.pyclass is None:
return True
return self.pyclass(True)
try:
v = int(v)
except:
try:
v = long(v)
except:
raise EvaluateException('Unparseable boolean',
ps.Backtrace(elt))
if v:
if self.pyclass is None:
return True
return self.pyclass(True)
if self.pyclass is None:
return False
return self.pyclass(False)
def parse(self, elt, ps):
self.checkname(elt, ps)
elt = self.SimpleHREF(elt, ps, 'boolean')
if not elt: return None
if self.nilled(elt, ps): return Nilled
v = self.simple_value(elt, ps).lower()
return self.text_to_data(v, elt, ps)
def get_formatted_content(self, pyobj):
if pyobj: return 'true'
return 'false'
#XXX NOT FIXED YET
class XML(TypeCode):
'''Opaque XML which shouldn't be parsed.
comments -- preserve comments
inline -- don't href/id when serializing
resolver -- object to resolve href's
wrapped -- put a wrapper element around it
'''
# Clone returned data?
copyit = 0
logger = _GetLogger('ZSI.TC.XML')
def __init__(self, pname=None, comments=0, inline=0, wrapped=True, **kw):
TypeCode.__init__(self, pname, **kw)
self.comments = comments
self.inline = inline
if kw.has_key('resolver'): self.resolver = kw['resolver']
self.wrapped = wrapped
self.copyit = kw.get('copyit', XML.copyit)
def parse(self, elt, ps):
if self.wrapped is False:
return elt
c = _child_elements(elt)
if not c:
href = _find_href(elt)
if not href:
if self.minOccurs == 0: return None
raise EvaluateException('Embedded XML document missing',
ps.Backtrace(elt))
if href[0] != '#':
return ps.ResolveHREF(href, self)
elt = ps.FindLocalHREF(href, elt)
c = _child_elements(elt)
if _find_encstyle(elt) != "":
#raise EvaluateException('Embedded XML has unknown encodingStyle',
# ps.Backtrace(elt)
pass
if len(c) != 1:
raise EvaluateException('Embedded XML has more than one child',
ps.Backtrace(elt))
if self.copyit: return c[0].cloneNode(1)
return c[0]
def serialize(self, elt, sw, pyobj, name=None, unsuppressedPrefixes=[], **kw):
if self.wrapped is False:
Canonicalize(pyobj, sw, unsuppressedPrefixes=unsuppressedPrefixes,
comments=self.comments)
return
objid = _get_idstr(pyobj)
ns,n = self.get_name(name, objid)
xmlelt = elt.createAppendElement(ns, n)
if type(pyobj) in _stringtypes:
self.set_attributes(xmlelt, pyobj)
self.set_attribute_href(xmlelt, objid)
elif kw.get('inline', self.inline):
self.cb(xmlelt, sw, pyobj, unsuppressedPrefixes)
else:
self.set_attributes(xmlelt, pyobj)
self.set_attribute_href(xmlelt, objid)
sw.AddCallback(self.cb, pyobj, unsuppressedPrefixes)
def cb(self, elt, sw, pyobj, unsuppressedPrefixes=[]):
if sw.Known(pyobj):
return
objid = _get_idstr(pyobj)
ns,n = self.get_name(name, objid)
xmlelt = elt.createAppendElement(ns, n)
self.set_attribute_id(xmlelt, objid)
xmlelt.setAttributeNS(SOAP.ENC, 'encodingStyle', '""')
Canonicalize(pyobj, sw, unsuppressedPrefixes=unsuppressedPrefixes,
comments=self.comments)
class AnyType(TypeCode):
"""XML Schema xsi:anyType type definition wildCard.
class variables:
all -- specifies use of all namespaces.
other -- specifies use of other namespaces
type --
"""
all = '#all'
other = '#other'
type = (SCHEMA.XSD3, 'anyType')
logger = _GetLogger('ZSI.TC.AnyType')
def __init__(self, pname=None, namespaces=['#all'],
minOccurs=1, maxOccurs=1, strip=1, **kw):
TypeCode.__init__(self, pname=pname, minOccurs=minOccurs,
maxOccurs=maxOccurs, **kw)
self.namespaces = namespaces
def get_formatted_content(self, pyobj):
# TODO: not sure this makes sense,
# parse side will be clueless, but oh well..
what = getattr(pyobj, 'typecode', Any())
return what.get_formatted_content(pyobj)
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data. Used only with
attributes so will not know anything about this content so
why guess?
Parameters:
text -- text content
elt -- the DOM element being parsed
ps -- the ParsedSoap object.
'''
return text
def serialize(self, elt, sw, pyobj, **kw):
nsuri,typeName = _get_xsitype(pyobj)
if self.all not in self.namespaces and nsuri not in self.namespaces:
raise EvaluateException(
'<anyType> unsupported use of namespaces "%s"' %self.namespaces)
what = getattr(pyobj, 'typecode', None)
if what is None:
# TODO: resolve this, "strict" processing but no
# concrete schema makes little sense.
#what = _AnyStrict(pname=(self.nspname,self.pname))
what = Any(pname=(self.nspname,self.pname), unique=True,
aslist=False)
kw['typed'] = True
what.serialize(elt, sw, pyobj, **kw)
return
# Namespace if element AnyType was namespaced.
what.serialize(elt, sw, pyobj,
name=(self.nspname or what.nspname, self.pname or what.pname), **kw)
def parse(self, elt, ps):
#element name must be declared ..
nspname,pname = _get_element_nsuri_name(elt)
if nspname != self.nspname or pname != self.pname:
raise EvaluateException('<anyType> instance is (%s,%s) found (%s,%s)' %(
self.nspname,self.pname,nspname,pname), ps.Backtrace(elt))
#locate xsi:type
prefix, typeName = SplitQName(_find_type(elt))
namespaceURI = _resolve_prefix(elt, prefix)
pyclass = GTD(namespaceURI, typeName)
if not pyclass:
if _is_xsd_or_soap_ns(namespaceURI):
pyclass = _AnyStrict
elif (str(namespaceURI).lower()==str(Apache.Map.type[0]).lower())\
and (str(typeName).lower() ==str(Apache.Map.type[1]).lower()):
pyclass = Apache.Map
else:
# Unknown type, so parse into a dictionary
pyobj = Any().parse_into_dict_or_list(elt, ps)
return pyobj
what = pyclass(pname=(self.nspname,self.pname))
pyobj = what.parse(elt, ps)
return pyobj
class AnyElement(AnyType):
"""XML Schema xsi:any element declaration wildCard.
class variables:
tag -- global element declaration
"""
tag = (SCHEMA.XSD3, 'any')
logger = _GetLogger('ZSI.TC.AnyElement')
def __init__(self, namespaces=['#all'],pname=None,
minOccurs=1, maxOccurs=1, strip=1, processContents='strict',
**kw):
if processContents not in ('lax', 'skip', 'strict'):
raise ValueError('processContents(%s) must be lax, skip, or strict')
self.processContents = processContents
AnyType.__init__(self, namespaces=namespaces,pname=pname,
minOccurs=minOccurs, maxOccurs=maxOccurs, strip=strip, **kw)
def serialize(self, elt, sw, pyobj, **kw):
'''Must provice typecode to AnyElement for serialization, else
try to use TC.Any to serialize instance which will serialize
based on the data type of pyobj w/o reference to XML schema
instance.
'''
if isinstance(pyobj, TypeCode):
raise TypeError, 'pyobj is a typecode instance.'
what = getattr(pyobj, 'typecode', None)
if what is not None and type(pyobj) is types.InstanceType:
tc = pyobj.__class__
what = Any.serialmap.get(tc)
if not what:
tc = (types.ClassType, pyobj.__class__.__name__)
what = Any.serialmap.get(tc)
# failed to find a registered type for class
if what is None:
#TODO: seems incomplete. what about facets.
if self.processContents == 'strict':
what = _AnyStrict(pname=(self.nspname,self.pname))
else:
what = _AnyLax(pname=(self.nspname,self.pname))
self.logger.debug('serialize with %s', what.__class__.__name__)
what.serialize(elt, sw, pyobj, **kw)
def parse(self, elt, ps):
'''
processContents -- 'lax' | 'skip' | 'strict', 'strict'
1) if 'skip' check namespaces, and return the DOM node.
2) if 'lax' look for declaration, or definition. If
not found return DOM node.
3) if 'strict' get declaration, or raise.
'''
skip = self.processContents == 'skip'
nspname,pname = _get_element_nsuri_name(elt)
what = GED(nspname, pname)
if not skip and what is not None:
pyobj = what.parse(elt, ps)
try:
pyobj.typecode = what
except AttributeError, ex:
# Assume this means builtin type.
pyobj = WrapImmutable(pyobj, what)
return pyobj
# Allow use of "<any>" element declarations w/ local
# element declarations
prefix, typeName = SplitQName(_find_type(elt))
if not skip and typeName:
namespaceURI = _resolve_prefix(elt, prefix or 'xmlns')
# First look thru user defined namespaces, if don't find
# look for 'primitives'.
pyclass = GTD(namespaceURI, typeName) or Any
what = pyclass(pname=(nspname,pname))
pyobj = what.parse(elt, ps)
try:
pyobj.typecode = what
except AttributeError, ex:
# Assume this means builtin type.
pyobj = WrapImmutable(pyobj, what)
what.typed = True
return pyobj
if skip:
what = XML(pname=(nspname,pname), wrapped=False)
elif self.processContents == 'lax':
what = _AnyLax(pname=(nspname,pname))
else:
what = _AnyStrict(pname=(nspname,pname))
try:
pyobj = what.parse(elt, ps)
except EvaluateException, ex:
self.logger.error("Give up, parse (%s,%s) as a String",
what.nspname, what.pname)
what = String(pname=(nspname,pname), typed=False)
pyobj = WrapImmutable(what.parse(elt, ps), what)
return pyobj
class Union(SimpleType):
'''simpleType Union
class variables:
memberTypes -- list [(namespace,name),] tuples, each representing a type defintion.
'''
memberTypes = None
logger = _GetLogger('ZSI.TC.Union')
def __init__(self, pname=None, minOccurs=1, maxOccurs=1, **kw):
SimpleType.__init__(self, pname=pname, minOccurs=minOccurs, maxOccurs=maxOccurs, **kw)
self.memberTypeCodes = []
def setMemberTypeCodes(self):
if len(self.memberTypeCodes) > 0:
return
if self.__class__.memberTypes is None:
raise EvaluateException, 'uninitialized class variable memberTypes [(namespace,name),]'
for nsuri,name in self.__class__.memberTypes:
tcclass = GTD(nsuri,name)
if tcclass is None:
tc = Any.parsemap.get((nsuri,name))
typecode = tc.__class__(pname=(self.nspname,self.pname))
else:
typecode = tcclass(pname=(self.nspname,self.pname))
if typecode is None:
raise EvaluateException, \
'Typecode class for Union memberType (%s,%s) is missing' %(nsuri,name)
if isinstance(typecode, Struct):
raise EvaluateException, \
'Illegal: Union memberType (%s,%s) is complexType' %(nsuri,name)
self.memberTypeCodes.append(typecode)
def parse(self, elt, ps, **kw):
'''attempt to parse sequentially. No way to know ahead of time
what this instance represents. Must be simple type so it can
not have attributes nor children, so this isn't too bad.
'''
self.setMemberTypeCodes()
(nsuri,typeName) = self.checkname(elt, ps)
#if (nsuri,typeName) not in self.memberTypes:
# raise EvaluateException(
# 'Union Type mismatch got (%s,%s) not in %s' % \
# (nsuri, typeName, self.memberTypes), ps.Backtrace(elt))
for indx in range(len(self.memberTypeCodes)):
typecode = self.memberTypeCodes[indx]
try:
pyobj = typecode.parse(elt, ps)
except ParseException, ex:
continue
except Exception, ex:
continue
if indx > 0:
self.memberTypeCodes.remove(typecode)
self.memberTypeCodes.insert(0, typecode)
break
else:
raise
return pyobj
def get_formatted_content(self, pyobj, **kw):
self.setMemberTypeCodes()
for indx in range(len(self.memberTypeCodes)):
typecode = self.memberTypeCodes[indx]
try:
content = typecode.get_formatted_content(copy.copy(pyobj))
break
except ParseException, ex:
pass
if indx > 0:
self.memberTypeCodes.remove(typecode)
self.memberTypeCodes.insert(0, typecode)
else:
raise
return content
class List(SimpleType):
'''simpleType List
Class data:
itemType -- sequence (namespaceURI,name) or a TypeCode instance
representing the type definition
'''
itemType = None
logger = _GetLogger('ZSI.TC.List')
def __init__(self, pname=None, itemType=None, **kw):
'''Currently need to require maxOccurs=1, so list
is interpreted as a single unit of data.
'''
assert kw.get('maxOccurs',1) == 1, \
'Currently only supporting SimpleType Lists with maxOccurs=1'
SimpleType.__init__(self, pname=pname, **kw)
self.itemType = itemType or self.itemType
self.itemTypeCode = self.itemType
itemTypeCode = None
if type(self.itemTypeCode) in _seqtypes:
namespaceURI,name = self.itemTypeCode
try:
itemTypeCode = GTD(*self.itemType)(None)
except:
if _is_xsd_or_soap_ns(namespaceURI) is False:
raise
for pyclass in TYPES:
if pyclass.type == self.itemTypeCode:
itemTypeCode = pyclass(None)
break
elif pyclass.type[1] == name:
itemTypeCode = pyclass(None)
if itemTypeCode is None:
raise EvaluateException('Filed to locate %s' %self.itemTypeCode)
if hasattr(itemTypeCode, 'text_to_data') is False:
raise EvaluateException('TypeCode class %s missing text_to_data method' %itemTypeCode)
self.itemTypeCode = itemTypeCode
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data. items in
list are space separated.
'''
v = []
for item in text.split(' '):
v.append(self.itemTypeCode.text_to_data(item, elt, ps))
if self.pyclass is not None:
return self.pyclass(v)
return v
def parse(self, elt, ps):
'''elt -- the DOM element being parsed
ps -- the ParsedSoap object.
'''
self.checkname(elt, ps)
if len(_children(elt)) == 0:
href = _find_href(elt)
if not href:
if self.nilled(elt, ps) is False:
# No content, no HREF, not NIL: empty string
return ""
# No content, no HREF, and is NIL...
if self.nillable is True:
return Nilled
raise EvaluateException('Required string missing',
ps.Backtrace(elt))
if href[0] != '#':
return ps.ResolveHREF(href, self)
elt = ps.FindLocalHREF(href, elt)
self.checktype(elt, ps)
if self.nilled(elt, ps): return Nilled
if len(_children(elt)) == 0: return ''
v = self.simple_value(elt, ps)
return self.text_to_data(v, elt, ps)
def serialize(self, elt, sw, pyobj, name=None, orig=None, **kw):
'''elt -- the current DOMWrapper element
sw -- soapWriter object
pyobj -- python object to serialize
'''
if type(pyobj) not in _seqtypes:
raise EvaluateException, 'expecting a list'
objid = _get_idstr(pyobj)
ns,n = self.get_name(name, objid)
el = elt.createAppendElement(ns, n)
if self.nillable is True and pyobj is None:
self.serialize_as_nil(el)
return None
tc = self.itemTypeCode
s = StringIO()
for item in pyobj:
s.write(tc.get_formatted_content(item))
s.write(' ')
el.createAppendTextNode(textNode)
class _AnyStrict(Any):
''' Handles an unspecified types when using a concrete schemas and
processContents = "strict".
'''
#WARNING: unstable
logger = _GetLogger('ZSI.TC._AnyStrict')
def __init__(self, pname=None, aslist=False, **kw):
TypeCode.__init__(self, pname=pname, **kw)
self.aslist = aslist
self.unique = True
def serialize(self, elt, sw, pyobj, name=None, **kw):
if not (type(pyobj) is dict and not self.aslist):
Any.serialize(self, elt=elt,sw=sw,pyobj=pyobj,name=name, **kw)
raise EvaluateException(
'Serializing dictionaries not implemented when processContents=\"strict\".' +
'Try as a list or use processContents=\"lax\".'
)
class _AnyLax(Any):
''' Handles unspecified types when using a concrete schemas and
processContents = "lax".
'''
logger = _GetLogger('ZSI.TC._AnyLax')
def __init__(self, pname=None, aslist=False, **kw):
TypeCode.__init__(self, pname=pname, **kw)
self.aslist = aslist
self.unique = True
def parse_into_dict_or_list(self, elt, ps):
c = _child_elements(elt)
count = len(c)
v = []
if count == 0:
href = _find_href(elt)
if not href: return {}
elt = ps.FindLocalHREF(href, elt)
self.checktype(elt, ps)
c = _child_elements(elt)
count = len(c)
if count == 0: return self.listify([])
if self.nilled(elt, ps): return Nilled
# group consecutive elements with the same name together
# We treat consecutive elements with the same name as lists.
groupedElements = [] # tuples of (name, elementList)
previousName = ""
currentElementList = None
for ce in _child_elements(elt):
name = ce.localName
if (name != previousName): # new name, so new group
if currentElementList != None: # store previous group if there is one
groupedElements.append( (previousName, currentElementList) )
currentElementList = list()
currentElementList.append(ce) # append to list
previousName = name
# add the last group if necessary
if currentElementList != None: # store previous group if there is one
groupedElements.append( (previousName, currentElementList) )
# parse the groups of names
if len(groupedElements) < 1: # should return earlier
return None
# return a list if there is one name and multiple data
elif (len(groupedElements) == 1) and (len(groupedElements[0][0]) > 1):
self.aslist = False
# else return a dictionary
for name,eltList in groupedElements:
lst = []
for elt in eltList:
#aslist = self.aslist
lst.append( self.parse(elt, ps) )
#self.aslist = aslist # restore the aslist setting
if len(lst) > 1: # consecutive elements with the same name means a list
v.append( (name, lst) )
elif len(lst) == 1:
v.append( (name, lst[0]) )
return self.listify(v)
def checkname(self, elt, ps):
'''See if the name and type of the "elt" element is what we're
looking for. Return the element's type.
Since this is _AnyLax, it's ok if names don't resolve.
'''
parselist,errorlist = self.get_parse_and_errorlist()
ns, name = _get_element_nsuri_name(elt)
if ns == SOAP.ENC:
if parselist and \
(None, name) not in parselist and (ns, name) not in parselist:
raise EvaluateException(
'Element mismatch (got %s wanted %s) (SOAP encoding namespace)' % \
(name, errorlist), ps.Backtrace(elt))
return (ns, name)
# Not a type, check name matches.
if self.nspname and ns != self.nspname:
raise EvaluateException('Element NS mismatch (got %s wanted %s)' % \
(ns, self.nspname), ps.Backtrace(elt))
return self.checktype(elt, ps)
def RegisterType(C, clobber=0, *args, **keywords):
instance = apply(C, args, keywords)
for t in C.__dict__.get('parselist', []):
prev = Any.parsemap.get(t)
if prev:
if prev.__class__ == C: continue
if not clobber:
raise TypeError(
str(C) + ' duplicating parse registration for ' + str(t))
Any.parsemap[t] = instance
for t in C.__dict__.get('seriallist', []):
ti = type(t)
if ti in [ types.TypeType, types.ClassType]:
key = t
elif ti in _stringtypes:
key = (types.ClassType, t)
else:
raise TypeError(str(t) + ' is not a class name')
prev = Any.serialmap.get(key)
if prev:
if prev.__class__ == C: continue
if not clobber:
raise TypeError(
str(C) + ' duplicating serial registration for ' + str(t))
Any.serialmap[key] = instance
from TCnumbers import *
from TCtimes import *
from schema import GTD, GED, WrapImmutable
from TCcompound import *
from TCapache import *
# aliases backwards compatiblity
_get_type_definition, _get_global_element_declaration, Wrap = GTD, GED, WrapImmutable
f = lambda x: type(x) == types.ClassType and issubclass(x, TypeCode) and getattr(x, 'type', None) is not None
TYPES = filter(f, map(lambda y:eval(y),dir()))
if __name__ == '__main__': print _copyright | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/TC.py | TC.py |
import time, urlparse, socket
from ZSI import _seqtypes, EvaluateException, WSActionException
from TC import AnyElement, AnyType, TypeCode
from schema import GED, GTD, _has_type_definition
from ZSI.TCcompound import ComplexType
from ZSI.wstools.Namespaces import WSA_LIST
class Address(object):
'''WS-Address
Implemented is dependent on the default "wsdl2py" convention of generating aname,
so the attributes representing element declaration names should be prefixed with
an underscore.
'''
def __init__(self, addressTo=None, wsAddressURI=None, action=None):
self.wsAddressURI = wsAddressURI
self.anonymousURI = None
self._addressTo = addressTo
self._messageID = None
self._action = action
self._endPointReference = None
self._replyTo = None
self._relatesTo = None
self.setUp()
def setUp(self):
'''Look for WS-Address
'''
toplist = filter(lambda wsa: wsa.ADDRESS==self.wsAddressURI, WSA_LIST)
epr = 'EndpointReferenceType'
for WSA in toplist+WSA_LIST:
if (self.wsAddressURI is not None and self.wsAddressURI != WSA.ADDRESS) or \
_has_type_definition(WSA.ADDRESS, epr) is True:
break
else:
raise EvaluateException,\
'enabling wsAddressing requires the inclusion of that namespace'
self.wsAddressURI = WSA.ADDRESS
self.anonymousURI = WSA.ANONYMOUS
self._replyTo = WSA.ANONYMOUS
def _checkAction(self, action, value):
'''WS-Address Action
action -- Action value expecting.
value -- Action value server returned.
'''
if action is None:
raise WSActionException, 'User did not specify WSAddress Action value to expect'
if not value:
raise WSActionException, 'missing WSAddress Action, expecting %s' %action
if value != action:
raise WSActionException, 'wrong WSAddress Action(%s), expecting %s'%(value,action)
def _checkFrom(self, pyobj):
'''WS-Address From,
XXX currently not checking the hostname, not forwarding messages.
pyobj -- From server returned.
'''
if pyobj is None: return
value = pyobj._Address
if value != self._addressTo:
scheme,netloc,path,query,fragment = urlparse.urlsplit(value)
hostport = netloc.split(':')
schemeF,netlocF,pathF,queryF,fragmentF = urlparse.urlsplit(self._addressTo)
if scheme==schemeF and path==pathF and query==queryF and fragment==fragmentF:
netloc = netloc.split(':') + ['80']
netlocF = netlocF.split(':') + ['80']
if netloc[1]==netlocF[1] and \
socket.gethostbyname(netloc[0])==socket.gethostbyname(netlocF[0]):
return
raise WSActionException, 'wrong WS-Address From(%s), expecting %s'%(value,self._addressTo)
def _checkRelatesTo(self, value):
'''WS-Address From
value -- From server returned.
'''
if value != self._messageID:
raise WSActionException, 'wrong WS-Address RelatesTo(%s), expecting %s'%(value,self._messageID)
def _checkReplyTo(self, value):
'''WS-Address From
value -- From server returned in wsa:To
'''
if value != self._replyTo:
raise WSActionException, 'wrong WS-Address ReplyTo(%s), expecting %s'%(value,self._replyTo)
def setAction(self, action):
self._action = action
def getAction(self):
return self._action
def getRelatesTo(self):
return self._relatesTo
def getMessageID(self):
return self._messageID
def _getWSAddressTypeCodes(self, **kw):
'''kw -- namespaceURI keys with sequence of element names.
'''
typecodes = []
try:
for nsuri,elements in kw.items():
for el in elements:
typecode = GED(nsuri, el)
if typecode is None:
raise WSActionException, 'Missing namespace, import "%s"' %nsuri
typecodes.append(typecode)
else:
pass
except EvaluateException, ex:
raise EvaluateException, \
'To use ws-addressing register typecodes for namespace(%s)' %self.wsAddressURI
return typecodes
def checkResponse(self, ps, action):
'''
ps -- ParsedSoap
action -- ws-action for response
'''
namespaceURI = self.wsAddressURI
d = {namespaceURI:("MessageID","Action","To","From","RelatesTo")}
typecodes = self._getWSAddressTypeCodes(**d)
pyobjs = ps.ParseHeaderElements(typecodes)
got_action = pyobjs.get((namespaceURI,"Action"))
self._checkAction(got_action, action)
From = pyobjs.get((namespaceURI,"From"))
self._checkFrom(From)
RelatesTo = pyobjs.get((namespaceURI,"RelatesTo"))
self._checkRelatesTo(RelatesTo)
To = pyobjs.get((namespaceURI,"To"))
if To: self._checkReplyTo(To)
def setRequest(self, endPointReference, action):
'''Call For Request
'''
self._action = action
self.header_pyobjs = None
pyobjs = []
namespaceURI = self.wsAddressURI
addressTo = self._addressTo
messageID = self._messageID = "uuid:%s" %time.time()
# Set Message Information Headers
# MessageID
typecode = GED(namespaceURI, "MessageID")
pyobjs.append(typecode.pyclass(messageID))
# Action
typecode = GED(namespaceURI, "Action")
pyobjs.append(typecode.pyclass(action))
# To
typecode = GED(namespaceURI, "To")
pyobjs.append(typecode.pyclass(addressTo))
# From
typecode = GED(namespaceURI, "From")
mihFrom = typecode.pyclass()
mihFrom._Address = self.anonymousURI
pyobjs.append(mihFrom)
if endPointReference:
if hasattr(endPointReference, 'typecode') is False:
raise EvaluateException, 'endPointReference must have a typecode attribute'
if isinstance(endPointReference.typecode, \
GTD(namespaceURI ,'EndpointReferenceType')) is False:
raise EvaluateException, 'endPointReference must be of type %s' \
%GTD(namespaceURI ,'EndpointReferenceType')
ReferenceProperties = endPointReference._ReferenceProperties
any = ReferenceProperties._any or []
#if not (what.maxOccurs=='unbounded' and type(any) in _seqtypes):
# raise EvaluateException, 'ReferenceProperties <any> assumed maxOccurs unbounded'
for v in any:
if not hasattr(v,'typecode'):
raise EvaluateException, '<any> element, instance missing typecode attribute'
pyobjs.append(v)
#pyobjs.append(v)
self.header_pyobjs = tuple(pyobjs)
def setResponseFromWSAddress(self, address, localURL):
'''Server-side has to set these fields in response.
address -- Address instance, representing a WS-Address
'''
self.From = localURL
self.header_pyobjs = None
pyobjs = []
namespaceURI = self.wsAddressURI
for nsuri,name,value in (\
(namespaceURI, "Action", self._action),
(namespaceURI, "MessageID","uuid:%s" %time.time()),
(namespaceURI, "RelatesTo", address.getMessageID()),
(namespaceURI, "To", self.anonymousURI),):
typecode = GED(nsuri, name)
pyobjs.append(typecode.pyclass(value))
typecode = GED(nsuri, "From")
pyobj = typecode.pyclass()
pyobj._Address = self.From
pyobjs.append(pyobj)
self.header_pyobjs = tuple(pyobjs)
def serialize(self, sw, **kw):
'''
sw -- SoapWriter instance, add WS-Address header.
'''
for pyobj in self.header_pyobjs:
if hasattr(pyobj, 'typecode') is False:
raise RuntimeError, 'all header pyobjs must have a typecode attribute'
sw.serialize_header(pyobj, **kw)
def parse(self, ps, **kw):
'''
ps -- ParsedSoap instance
'''
namespaceURI = self.wsAddressURI
elements = ("MessageID","Action","To","From","RelatesTo")
d = {namespaceURI:elements}
typecodes = self._getWSAddressTypeCodes(**d)
pyobjs = ps.ParseHeaderElements(typecodes)
self._messageID = pyobjs[(namespaceURI,elements[0])]
self._action = pyobjs[(namespaceURI,elements[1])]
self._addressTo = pyobjs[(namespaceURI,elements[2])]
self._from = pyobjs[(namespaceURI,elements[3])]
self._relatesTo = pyobjs[(namespaceURI,elements[4])]
# TODO: Remove MessageContainer. Hopefully the new <any> functionality
# makes this irrelevant. But could create an Interop problem.
"""
class MessageContainer:
'''Automatically wraps all primitive types so attributes
can be specified.
'''
class IntHolder(int): pass
class StrHolder(str): pass
class UnicodeHolder(unicode): pass
class LongHolder(long): pass
class FloatHolder(float): pass
class BoolHolder(int): pass
#class TupleHolder(tuple): pass
#class ListHolder(list): pass
typecode = None
pyclass_list = [IntHolder,StrHolder,UnicodeHolder,LongHolder,
FloatHolder,BoolHolder,]
def __setattr__(self, key, value):
'''wrap all primitives with Holders if present.
'''
if type(value) in _seqtypes:
value = list(value)
for indx in range(len(value)):
try:
item = self._wrap(value[indx])
except TypeError, ex:
pass
else:
value[indx] = item
elif type(value) is bool:
value = BoolHolder(value)
else:
try:
value = self._wrap(value)
except TypeError, ex:
pass
self.__dict__[key] = value
def _wrap(self, value):
'''wrap primitive, return None
'''
if value is None:
return value
for pyclass in self.pyclass_list:
if issubclass(value.__class__, pyclass): break
else:
raise TypeError, 'MessageContainer does not know about type %s' %(type(value))
return pyclass(value)
def setUp(self, typecode=None, pyclass=None):
'''set up all attribute names (aname) in this python instance.
If what is a ComplexType or a simpleType w/attributes instantiate
a new MessageContainer, else set attribute aname to None.
'''
if typecode is None:
typecode = self.typecode
else:
self.typecode = typecode
if not isinstance(typecode, TypeCode):
raise TypeError, 'typecode must be a TypeCode class instance'
if isinstance(typecode, ComplexType):
if typecode.has_attributes() is True:
setattr(self, typecode.attrs_aname, {})
if typecode.mixed is True:
setattr(self, typecode.mixed_aname, None)
for what in typecode.ofwhat:
setattr(self, what.aname, None)
if isinstance(what, ComplexType):
setattr(self, what.aname, MessageContainer())
getattr(self, what.aname).setUp(typecode=what)
else:
raise TypeError, 'Primitive type'
"""
if __name__ == '__main__': print _copyright | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/address.py | address.py |
'''Typecodes for numbers.
'''
import types
from ZSI import _copyright, _inttypes, _floattypes, _seqtypes, \
EvaluateException
from ZSI.TC import TypeCode, Integer, Decimal
from ZSI.wstools.Namespaces import SCHEMA
class IunsignedByte(Integer):
'''Unsigned 8bit value.
'''
type = (SCHEMA.XSD3, "unsignedByte")
parselist = [ (None, "unsignedByte") ]
seriallist = [ ]
class IunsignedShort(Integer):
'''Unsigned 16bit value.
'''
type = (SCHEMA.XSD3, "unsignedShort")
parselist = [ (None, "unsignedShort") ]
seriallist = [ ]
class IunsignedInt(Integer):
'''Unsigned 32bit value.
'''
type = (SCHEMA.XSD3, "unsignedInt")
parselist = [ (None, "unsignedInt") ]
seriallist = [ ]
class IunsignedLong(Integer):
'''Unsigned 64bit value.
'''
type = (SCHEMA.XSD3, "unsignedLong")
parselist = [ (None, "unsignedLong") ]
seriallist = [ ]
class Ibyte(Integer):
'''Signed 8bit value.
'''
type = (SCHEMA.XSD3, "byte")
parselist = [ (None, "byte") ]
seriallist = [ ]
class Ishort(Integer):
'''Signed 16bit value.
'''
type = (SCHEMA.XSD3, "short")
parselist = [ (None, "short") ]
seriallist = [ ]
class Iint(Integer):
'''Signed 32bit value.
'''
type = (SCHEMA.XSD3, "int")
parselist = [ (None, "int") ]
seriallist = [ types.IntType ]
class Ilong(Integer):
'''Signed 64bit value.
'''
type = (SCHEMA.XSD3, "long")
parselist = [(None, "long")]
seriallist = [ types.LongType ]
class InegativeInteger(Integer):
'''Value less than zero.
'''
type = (SCHEMA.XSD3, "negativeInteger")
parselist = [ (None, "negativeInteger") ]
seriallist = [ ]
class InonPositiveInteger(Integer):
'''Value less than or equal to zero.
'''
type = (SCHEMA.XSD3, "nonPositiveInteger")
parselist = [ (None, "nonPositiveInteger") ]
seriallist = [ ]
class InonNegativeInteger(Integer):
'''Value greater than or equal to zero.
'''
type = (SCHEMA.XSD3, "nonNegativeInteger")
parselist = [ (None, "nonNegativeInteger") ]
seriallist = [ ]
class IpositiveInteger(Integer):
'''Value greater than zero.
'''
type = (SCHEMA.XSD3, "positiveInteger")
parselist = [ (None, "positiveInteger") ]
seriallist = [ ]
class Iinteger(Integer):
'''Integer value.
'''
type = (SCHEMA.XSD3, "integer")
parselist = [ (None, "integer") ]
seriallist = [ ]
class IEnumeration(Integer):
'''Integer value, limited to a specified set of values.
'''
def __init__(self, choices, pname=None, **kw):
Integer.__init__(self, pname, **kw)
self.choices = choices
t = type(choices)
if t in _seqtypes:
self.choices = tuple(choices)
elif TypeCode.typechecks:
raise TypeError(
'Enumeration choices must be list or sequence, not ' + str(t))
if TypeCode.typechecks:
for c in self.choices:
if type(c) not in _inttypes:
raise TypeError('Enumeration choice "' +
str(c) + '" is not an integer')
def parse(self, elt, ps):
val = Integer.parse(self, elt, ps)
if val not in self.choices:
raise EvaluateException('Value "' + str(val) + \
'" not in enumeration list',
ps.Backtrace(elt))
return val
def serialize(self, elt, sw, pyobj, name=None, orig=None, **kw):
if pyobj not in self.choices:
raise EvaluateException('Value not in int enumeration list',
ps.Backtrace(elt))
Integer.serialize(self, elt, sw, pyobj, name=name, orig=orig, **kw)
class FPfloat(Decimal):
'''IEEE 32bit floating point value.
'''
type = (SCHEMA.XSD3, "float")
parselist = [ (None, "float") ]
seriallist = [ types.FloatType ]
class FPdouble(Decimal):
'''IEEE 64bit floating point value.
'''
type = (SCHEMA.XSD3, "double")
parselist = [ (None, "double") ]
seriallist = [ ]
class FPEnumeration(FPfloat):
'''Floating point value, limited to a specified set of values.
'''
def __init__(self, choices, pname=None, **kw):
FPfloat.__init__(self, pname, **kw)
self.choices = choices
t = type(choices)
if t in _seqtypes:
self.choices = tuple(choices)
elif TypeCode.typechecks:
raise TypeError(
'Enumeration choices must be list or sequence, not ' + str(t))
if TypeCode.typechecks:
for c in self.choices:
if type(c) not in _floattypes:
raise TypeError('Enumeration choice "' +
str(c) + '" is not floating point number')
def parse(self, elt, ps):
val = Decimal.parse(self, elt, ps)
if val not in self.choices:
raise EvaluateException('Value "' + str(val) + \
'" not in enumeration list',
ps.Backtrace(elt))
return val
def serialize(self, elt, sw, pyobj, name=None, orig=None, **kw):
if pyobj not in self.choices:
raise EvaluateException('Value not in int enumeration list',
ps.Backtrace(elt))
Decimal.serialize(self, elt, sw, pyobj, name=name, orig=orig, **kw)
if __name__ == '__main__': print _copyright | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/TCnumbers.py | TCnumbers.py |
from md5 import md5
import random
import time
import httplib
random.seed(int(time.time()*10))
def H(val):
return md5(val).hexdigest()
def KD(secret,data):
return H('%s:%s' % (secret,data))
def A1(username,realm,passwd,nonce=None,cnonce=None):
if nonce and cnonce:
return '%s:%s:%s:%s:%s' % (username,realm,passwd,nonce,cnonce)
else:
return '%s:%s:%s' % (username,realm,passwd)
def A2(method,uri):
return '%s:%s' % (method,uri)
def dict_fetch(d,k,defval=None):
if d.has_key(k):
return d[k]
return defval
def generate_response(chaldict,uri,username,passwd,method='GET',cnonce=None):
"""
Generate an authorization response dictionary. chaldict should contain the digest
challenge in dict form. Use fetch_challenge to create a chaldict from a HTTPResponse
object like this: fetch_challenge(res.getheaders()).
returns dict (the authdict)
Note. Use build_authorization_arg() to turn an authdict into the final Authorization
header value.
"""
authdict = {}
qop = dict_fetch(chaldict,'qop')
domain = dict_fetch(chaldict,'domain')
nonce = dict_fetch(chaldict,'nonce')
stale = dict_fetch(chaldict,'stale')
algorithm = dict_fetch(chaldict,'algorithm','MD5')
realm = dict_fetch(chaldict,'realm','MD5')
opaque = dict_fetch(chaldict,'opaque')
nc = "00000001"
if not cnonce:
cnonce = H(str(random.randint(0,10000000)))[:16]
if algorithm.lower()=='md5-sess':
a1 = A1(username,realm,passwd,nonce,cnonce)
else:
a1 = A1(username,realm,passwd)
a2 = A2(method,uri)
secret = H(a1)
data = '%s:%s:%s:%s:%s' % (nonce,nc,cnonce,qop,H(a2))
authdict['username'] = '"%s"' % username
authdict['realm'] = '"%s"' % realm
authdict['nonce'] = '"%s"' % nonce
authdict['uri'] = '"%s"' % uri
authdict['response'] = '"%s"' % KD(secret,data)
authdict['qop'] = '"%s"' % qop
authdict['nc'] = nc
authdict['cnonce'] = '"%s"' % cnonce
return authdict
def fetch_challenge(http_header):
"""
Create a challenge dictionary from a HTTPResponse objects getheaders() method.
"""
chaldict = {}
vals = http_header.split(' ')
chaldict['challenge'] = vals[0]
for val in vals[1:]:
try:
a,b = val.split('=')
b=b.replace('"','')
b=b.replace("'",'')
b=b.replace(",",'')
chaldict[a.lower()] = b
except:
pass
return chaldict
def build_authorization_arg(authdict):
"""
Create an "Authorization" header value from an authdict (created by generate_response()).
"""
vallist = []
for k in authdict.keys():
vallist += ['%s=%s' % (k,authdict[k])]
return 'Digest '+', '.join(vallist)
if __name__ == '__main__': print _copyright | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/digest_auth.py | digest_auth.py |
from ZSI import _copyright, _seqtypes, _find_type, EvaluateException
from ZSI.wstools.Namespaces import SCHEMA, SOAP
from ZSI.wstools.Utility import SplitQName
def _get_type_definition(namespaceURI, name, **kw):
return SchemaInstanceType.getTypeDefinition(namespaceURI, name, **kw)
def _get_global_element_declaration(namespaceURI, name, **kw):
return SchemaInstanceType.getElementDeclaration(namespaceURI, name, **kw)
def _get_substitute_element(elt, what):
raise NotImplementedError, 'Not implemented'
def _has_type_definition(namespaceURI, name):
return SchemaInstanceType.getTypeDefinition(namespaceURI, name) is not None
#
# functions for retrieving schema items from
# the global schema instance.
#
GED = _get_global_element_declaration
GTD = _get_type_definition
def WrapImmutable(pyobj, what):
'''Wrap immutable instance so a typecode can be
set, making it self-describing ie. serializable.
'''
return _GetPyobjWrapper.WrapImmutable(pyobj, what)
def RegisterBuiltin(arg):
'''Add a builtin to be registered, and register it
with the Any typecode.
'''
_GetPyobjWrapper.RegisterBuiltin(arg)
_GetPyobjWrapper.RegisterAnyElement()
def RegisterAnyElement():
'''register all Wrapper classes with the Any typecode.
This allows instances returned by Any to be self-describing.
ie. serializable. AnyElement falls back on Any to parse
anything it doesn't understand.
'''
return _GetPyobjWrapper.RegisterAnyElement()
class SchemaInstanceType(type):
'''Register all types/elements, when hit already defined
class dont create a new one just give back reference. Thus
import order determines which class is loaded.
class variables:
types -- dict of typecode classes definitions
representing global type definitions.
elements -- dict of typecode classes representing
global element declarations.
element_typecode_cache -- dict of typecode instances
representing global element declarations.
'''
types = {}
elements = {}
element_typecode_cache = {}
def __new__(cls,classname,bases,classdict):
'''If classdict has literal and schema register it as a
element declaration, else if has type and schema register
it as a type definition.
'''
if classname in ['ElementDeclaration', 'TypeDefinition', 'LocalElementDeclaration',]:
return type.__new__(cls,classname,bases,classdict)
if ElementDeclaration in bases:
if classdict.has_key('schema') is False or classdict.has_key('literal') is False:
raise AttributeError, 'ElementDeclaration must define schema and literal attributes'
key = (classdict['schema'],classdict['literal'])
if SchemaInstanceType.elements.has_key(key) is False:
SchemaInstanceType.elements[key] = type.__new__(cls,classname,bases,classdict)
return SchemaInstanceType.elements[key]
if TypeDefinition in bases:
if classdict.has_key('type') is None:
raise AttributeError, 'TypeDefinition must define type attribute'
key = classdict['type']
if SchemaInstanceType.types.has_key(key) is False:
SchemaInstanceType.types[key] = type.__new__(cls,classname,bases,classdict)
return SchemaInstanceType.types[key]
if LocalElementDeclaration in bases:
return type.__new__(cls,classname,bases,classdict)
raise TypeError, 'SchemaInstanceType must be an ElementDeclaration or TypeDefinition '
def getTypeDefinition(cls, namespaceURI, name, lazy=False):
'''Grab a type definition, returns a typecode class definition
because the facets (name, minOccurs, maxOccurs) must be provided.
Parameters:
namespaceURI --
name --
'''
klass = cls.types.get((namespaceURI, name), None)
if lazy and klass is not None:
return _Mirage(klass)
return klass
getTypeDefinition = classmethod(getTypeDefinition)
def getElementDeclaration(cls, namespaceURI, name, isref=False, lazy=False):
'''Grab an element declaration, returns a typecode instance
representation or a typecode class definition. An element
reference has its own facets, and is local so it will not be
cached.
Parameters:
namespaceURI --
name --
isref -- if element reference, return class definition.
'''
key = (namespaceURI, name)
if isref:
klass = cls.elements.get(key,None)
if klass is not None and lazy is True:
return _Mirage(klass)
return klass
typecode = cls.element_typecode_cache.get(key, None)
if typecode is None:
tcls = cls.elements.get(key,None)
if tcls is not None:
typecode = cls.element_typecode_cache[key] = tcls()
typecode.typed = False
return typecode
getElementDeclaration = classmethod(getElementDeclaration)
class ElementDeclaration:
'''Typecodes subclass to represent a Global Element Declaration by
setting class variables schema and literal.
schema = namespaceURI
literal = NCName
'''
__metaclass__ = SchemaInstanceType
class LocalElementDeclaration:
'''Typecodes subclass to represent a Local Element Declaration.
'''
__metaclass__ = SchemaInstanceType
class TypeDefinition:
'''Typecodes subclass to represent a Global Type Definition by
setting class variable type.
type = (namespaceURI, NCName)
'''
__metaclass__ = SchemaInstanceType
def getSubstituteType(self, elt, ps):
'''if xsi:type does not match the instance type attr,
check to see if it is a derived type substitution.
DONT Return the element's type.
Parameters:
elt -- the DOM element being parsed
ps -- the ParsedSoap object.
'''
pyclass = SchemaInstanceType.getTypeDefinition(*self.type)
if pyclass is None:
raise EvaluateException(
'No Type registed for xsi:type=(%s, %s)' %
(self.type[0], self.type[1]), ps.Backtrace(elt))
typeName = _find_type(elt)
prefix,typeName = SplitQName(typeName)
uri = ps.GetElementNSdict(elt).get(prefix)
subclass = SchemaInstanceType.getTypeDefinition(uri, typeName)
if subclass is None:
raise EvaluateException(
'No registered xsi:type=(%s, %s), substitute for xsi:type=(%s, %s)' %
(uri, typeName, self.type[0], self.type[1]), ps.Backtrace(elt))
if not issubclass(subclass, pyclass) and subclass(None) and not issubclass(subclass, pyclass):
raise TypeError(
'Substitute Type (%s, %s) is not derived from %s' %
(self.type[0], self.type[1], pyclass), ps.Backtrace(elt))
return subclass((self.nspname, self.pname))
class _Mirage:
'''Used with SchemaInstanceType for lazy evaluation, eval during serialize or
parse as needed. Mirage is callable, TypeCodes are not. When called it returns the
typecode. Tightly coupled with generated code.
NOTE: **Must Use ClassType** for intended MRO of __call__ since setting it in
an instance attribute rather than a class attribute (will not work for object).
'''
def __init__(self, klass):
self.klass = klass
self.__reveal = False
self.__cache = None
if issubclass(klass, ElementDeclaration):
self.__call__ = self._hide_element
def __str__(self):
msg = "<Mirage id=%s, Local Element %s>"
if issubclass(self.klass, ElementDeclaration):
msg = "<Mirage id=%s, GED %s>"
return msg %(id(self), self.klass)
def _hide_type(self, pname, aname, minOccurs=0, maxOccurs=1, nillable=False,
**kw):
self.__call__ = self._reveal_type
self.__reveal = True
# store all attributes, make some visable for pyclass_type
self.__kw = kw
self.minOccurs,self.maxOccurs,self.nillable = minOccurs,maxOccurs,nillable
self.nspname,self.pname,self.aname = None,pname,aname
if type(self.pname) in (tuple,list):
self.nspname,self.pname = pname
return self
def _hide_element(self, minOccurs=0, maxOccurs=1, nillable=False, **kw):
self.__call__ = self._reveal_element
self.__reveal = True
# store all attributes, make some visable for pyclass_type
self.__kw = kw
self.nspname = self.klass.schema
self.pname = self.klass.literal
#TODO: Fix hack
#self.aname = '_%s' %self.pname
self.minOccurs,self.maxOccurs,self.nillable = minOccurs,maxOccurs,nillable
return self
def _reveal_type(self):
if self.__cache is None:
self.__cache = self.klass(pname=self.pname,
aname=self.aname, minOccurs=self.minOccurs,
maxOccurs=self.maxOccurs, nillable=self.nillable,
**self.__kw)
return self.__cache
def _reveal_element(self):
if self.__cache is None:
self.__cache = self.klass(minOccurs=self.minOccurs,
maxOccurs=self.maxOccurs, nillable=self.nillable,
**self.__kw)
return self.__cache
__call__ = _hide_type
class _GetPyobjWrapper:
'''Get a python object that wraps data and typecode. Used by
<any> parse routine, so that typecode information discovered
during parsing is retained in the pyobj representation
and thus can be serialized.
'''
types_dict = {}
def RegisterBuiltin(cls, arg):
'''register a builtin, create a new wrapper.
'''
if arg in cls.types_dict:
raise RuntimeError, '%s already registered' %arg
class _Wrapper(arg):
'Wrapper for builtin %s\n%s' %(arg, cls.__doc__)
_Wrapper.__name__ = '_%sWrapper' %arg.__name__
cls.types_dict[arg] = _Wrapper
RegisterBuiltin = classmethod(RegisterBuiltin)
def RegisterAnyElement(cls):
'''If find registered TypeCode instance, add Wrapper class
to TypeCode class serialmap and Re-RegisterType. Provides
Any serialzation of any instances of the Wrapper.
'''
for k,v in cls.types_dict.items():
what = Any.serialmap.get(k)
if what is None: continue
if v in what.__class__.seriallist: continue
what.__class__.seriallist.append(v)
RegisterType(what.__class__, clobber=1, **what.__dict__)
RegisterAnyElement = classmethod(RegisterAnyElement)
def WrapImmutable(cls, pyobj, what):
'''return a wrapper for pyobj, with typecode attribute set.
Parameters:
pyobj -- instance of builtin type (immutable)
what -- typecode describing the data
'''
d = cls.types_dict
if type(pyobj) is bool:
pyclass = d[int]
elif d.has_key(type(pyobj)) is True:
pyclass = d[type(pyobj)]
else:
raise TypeError,\
'Expecting a built-in type in %s (got %s).' %(
d.keys(),type(pyobj))
newobj = pyclass(pyobj)
newobj.typecode = what
return newobj
WrapImmutable = classmethod(WrapImmutable)
from TC import Any, RegisterType
if __name__ == '__main__': print _copyright | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/schema.py | schema.py |
from ZSI.wstools.Utility import SplitQName
from ZSI.wstools.Namespaces import WSDL
from ZSI import *
from ZSI.client import *
from ZSI.TC import Any
from ZSI.typeinterpreter import BaseTypeInterpreter
import wstools
from wstools.Utility import DOM
from urlparse import urlparse
import weakref
class ServiceProxy:
"""A ServiceProxy provides a convenient way to call a remote web
service that is described with WSDL. The proxy exposes methods
that reflect the methods of the remote web service."""
def __init__(self, wsdl, service=None, port=None, tracefile=None,
nsdict=None, transdict=None):
"""
Parameters:
wsdl -- WSDLTools.WSDL instance or URL of WSDL.
service -- service name or index
port -- port name or index
tracefile --
nsdict -- key prefix to namespace mappings for serialization
in SOAP Envelope.
transdict -- arguments to pass into HTTPConnection constructor.
"""
self._tracefile = tracefile
self._nsdict = nsdict or {}
self._transdict = transdict
self._wsdl = wsdl
if isinstance(wsdl, basestring) is True:
self._wsdl = wstools.WSDLTools.WSDLReader().loadFromURL(wsdl)
assert isinstance(self._wsdl, wstools.WSDLTools.WSDL), 'expecting a WSDL instance'
self._service = self._wsdl.services[service or 0]
self.__doc__ = self._service.documentation
self._port = self._service.ports[port or 0]
self._name = self._service.name
self._methods = {}
binding = self._port.getBinding()
portType = binding.getPortType()
for port in self._service.ports:
for item in port.getPortType().operations:
callinfo = wstools.WSDLTools.callInfoFromWSDL(port, item.name)
method = MethodProxy(self, callinfo)
setattr(self, item.name, method)
self._methods.setdefault(item.name, []).append(method)
def _call(self, name, *args, **kwargs):
"""Call the named remote web service method."""
if len(args) and len(kwargs):
raise TypeError(
'Use positional or keyword argument only.'
)
callinfo = getattr(self, name).callinfo
# go through the list of defined methods, and look for the one with
# the same number of arguments as what was passed. this is a weak
# check that should probably be improved in the future to check the
# types of the arguments to allow for polymorphism
for method in self._methods[name]:
if len(method.callinfo.inparams) == len(kwargs):
callinfo = method.callinfo
soapAction = callinfo.soapAction
url = callinfo.location
(protocol, host, uri, query, fragment, identifier) = urlparse(url)
port = None
if host.find(':') >= 0:
host, port = host.split(':')
if protocol == 'http':
transport = httplib.HTTPConnection
elif protocol == 'https':
transport = httplib.HTTPSConnection
else:
raise RuntimeError, 'Unknown protocol %s' %protocol
binding = Binding(host=host, tracefile=self._tracefile,
transport=transport,transdict=self._transdict,
port=port, url=url, nsdict=self._nsdict,
soapaction=soapAction,)
request, response = self._getTypeCodes(callinfo)
if len(kwargs): args = kwargs
if request is None:
request = Any(oname=name)
binding.Send(url=url, opname=None, obj=args,
nsdict=self._nsdict, soapaction=soapAction, requesttypecode=request)
return binding.Receive(replytype=response)
def _getTypeCodes(self, callinfo):
"""Returns typecodes representing input and output messages, if request and/or
response fails to be generated return None for either or both.
callinfo -- WSDLTools.SOAPCallInfo instance describing an operation.
"""
prefix = None
self._resetPrefixDict()
if callinfo.use == 'encoded':
prefix = self._getPrefix(callinfo.namespace)
try:
requestTC = self._getTypeCode(parameters=callinfo.getInParameters(), literal=(callinfo.use=='literal'))
except EvaluateException, ex:
print "DEBUG: Request Failed to generate --", ex
requestTC = None
self._resetPrefixDict()
try:
replyTC = self._getTypeCode(parameters=callinfo.getOutParameters(), literal=(callinfo.use=='literal'))
except EvaluateException, ex:
print "DEBUG: Response Failed to generate --", ex
replyTC = None
request = response = None
if callinfo.style == 'rpc':
if requestTC: request = TC.Struct(pyclass=None, ofwhat=requestTC, pname=callinfo.methodName)
if replyTC: response = TC.Struct(pyclass=None, ofwhat=replyTC, pname='%sResponse' %callinfo.methodName)
else:
if requestTC: request = requestTC[0]
if replyTC: response = replyTC[0]
#THIS IS FOR RPC/ENCODED, DOC/ENCODED Wrapper
if request and prefix and callinfo.use == 'encoded':
request.oname = '%(prefix)s:%(name)s xmlns:%(prefix)s="%(namespaceURI)s"' \
%{'prefix':prefix, 'name':request.aname, 'namespaceURI':callinfo.namespace}
return request, response
def _getTypeCode(self, parameters, literal=False):
"""Returns typecodes representing a parameter set
parameters -- list of WSDLTools.ParameterInfo instances representing
the parts of a WSDL Message.
"""
ofwhat = []
for part in parameters:
namespaceURI,localName = part.type
if part.element_type:
#global element
element = self._wsdl.types[namespaceURI].elements[localName]
tc = self._getElement(element, literal=literal, local=False, namespaceURI=namespaceURI)
else:
#local element
name = part.name
typeClass = self._getTypeClass(namespaceURI, localName)
if not typeClass:
tp = self._wsdl.types[namespaceURI].types[localName]
tc = self._getType(tp, name, literal, local=True, namespaceURI=namespaceURI)
else:
tc = typeClass(name)
ofwhat.append(tc)
return ofwhat
def _globalElement(self, typeCode, namespaceURI, literal):
"""namespaces typecodes representing global elements with
literal encoding.
typeCode -- typecode representing an element.
namespaceURI -- namespace
literal -- True/False
"""
if literal:
typeCode.oname = '%(prefix)s:%(name)s xmlns:%(prefix)s="%(namespaceURI)s"' \
%{'prefix':self._getPrefix(namespaceURI), 'name':typeCode.oname, 'namespaceURI':namespaceURI}
def _getPrefix(self, namespaceURI):
"""Retrieves a prefix/namespace mapping.
namespaceURI -- namespace
"""
prefixDict = self._getPrefixDict()
if prefixDict.has_key(namespaceURI):
prefix = prefixDict[namespaceURI]
else:
prefix = 'ns1'
while prefix in prefixDict.values():
prefix = 'ns%d' %int(prefix[-1]) + 1
prefixDict[namespaceURI] = prefix
return prefix
def _getPrefixDict(self):
"""Used to hide the actual prefix dictionary.
"""
if not hasattr(self, '_prefixDict'):
self.__prefixDict = {}
return self.__prefixDict
def _resetPrefixDict(self):
"""Clears the prefix dictionary, this needs to be done
before creating a new typecode for a message
(ie. before, and after creating a new message typecode)
"""
self._getPrefixDict().clear()
def _getElement(self, element, literal=False, local=False, namespaceURI=None):
"""Returns a typecode instance representing the passed in element.
element -- XMLSchema.ElementDeclaration instance
literal -- literal encoding?
local -- is locally defined?
namespaceURI -- namespace
"""
if not element.isElement():
raise TypeError, 'Expecting an ElementDeclaration'
tc = None
elementName = element.getAttribute('name')
tp = element.getTypeDefinition('type')
typeObj = None
if not (tp or element.content):
nsuriType,localName = element.getAttribute('type')
typeClass = self._getTypeClass(nsuriType,localName)
typeObj = typeClass(elementName)
elif not tp:
tp = element.content
if not typeObj:
typeObj = self._getType(tp, elementName, literal, local, namespaceURI)
minOccurs = int(element.getAttribute('minOccurs'))
typeObj.optional = not minOccurs
typeObj.minOccurs = minOccurs
maxOccurs = element.getAttribute('maxOccurs')
typeObj.repeatable = (maxOccurs == 'unbounded') or (int(maxOccurs) > 1)
return typeObj
def _getType(self, tp, name, literal, local, namespaceURI):
"""Returns a typecode instance representing the passed in type and name.
tp -- XMLSchema.TypeDefinition instance
name -- element name
literal -- literal encoding?
local -- is locally defined?
namespaceURI -- namespace
"""
ofwhat = []
if not (tp.isDefinition() and tp.isComplex()):
raise EvaluateException, 'only supporting complexType definition'
elif tp.content.isComplex():
if hasattr(tp.content, 'derivation') and tp.content.derivation.isRestriction():
derived = tp.content.derivation
typeClass = self._getTypeClass(*derived.getAttribute('base'))
if typeClass == TC.Array:
attrs = derived.attr_content[0].attributes[WSDL.BASE]
prefix, localName = SplitQName(attrs['arrayType'])
nsuri = derived.attr_content[0].getXMLNS(prefix=prefix)
localName = localName.split('[')[0]
simpleTypeClass = self._getTypeClass(namespaceURI=nsuri, localName=localName)
if simpleTypeClass:
ofwhat = simpleTypeClass()
else:
tp = self._wsdl.types[nsuri].types[localName]
ofwhat = self._getType(tp=tp, name=None, literal=literal, local=True, namespaceURI=nsuri)
else:
raise EvaluateException, 'only support soapenc:Array restrictions'
return typeClass(atype=name, ofwhat=ofwhat, pname=name, childNames='item')
else:
raise EvaluateException, 'complexContent only supported for soapenc:Array derivations'
elif tp.content.isModelGroup():
modelGroup = tp.content
for item in modelGroup.content:
ofwhat.append(self._getElement(item, literal=literal, local=True))
tc = TC.Struct(pyclass=None, ofwhat=ofwhat, pname=name)
if not local:
self._globalElement(tc, namespaceURI=namespaceURI, literal=literal)
return tc
raise EvaluateException, 'only supporting complexType w/ model group, or soapenc:Array restriction'
def _getTypeClass(self, namespaceURI, localName):
"""Returns a typecode class representing the type we are looking for.
localName -- name of the type we are looking for.
namespaceURI -- defining XMLSchema targetNamespace.
"""
bti = BaseTypeInterpreter()
simpleTypeClass = bti.get_typeclass(localName, namespaceURI)
return simpleTypeClass
class MethodProxy:
""" """
def __init__(self, parent, callinfo):
self.__name__ = callinfo.methodName
self.__doc__ = callinfo.documentation
self.callinfo = callinfo
self.parent = weakref.ref(parent)
def __call__(self, *args, **kwargs):
return self.parent()._call(self.__name__, *args, **kwargs) | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/ServiceProxy.py | ServiceProxy.py |
from ZSI import _copyright, _child_elements, EvaluateException, TC
import multifile, mimetools, urllib
from base64 import decodestring as b64decode
import cStringIO as StringIO
def Opaque(uri, tc, ps, **keywords):
'''Resolve a URI and return its content as a string.
'''
source = urllib.urlopen(uri, **keywords)
enc = source.info().getencoding()
if enc in ['7bit', '8bit', 'binary']: return source.read()
data = StringIO.StringIO()
mimetools.decode(source, data, enc)
return data.getvalue()
def XML(uri, tc, ps, **keywords):
'''Resolve a URI and return its content as an XML DOM.
'''
source = urllib.urlopen(uri, **keywords)
enc = source.info().getencoding()
if enc in ['7bit', '8bit', 'binary']:
data = source
else:
data = StringIO.StringIO()
mimetools.decode(source, data, enc)
data.seek(0)
dom = ps.readerclass().fromStream(data)
return _child_elements(dom)[0]
class NetworkResolver:
'''A resolver that support string and XML.
'''
def __init__(self, prefix=None):
self.allowed = prefix or []
def _check_allowed(self, uri):
for a in self.allowed:
if uri.startswith(a): return
raise EvaluateException("Disallowed URI prefix")
def Opaque(self, uri, tc, ps, **keywords):
self._check_allowed(uri)
return Opaque(uri, tc, ps, **keywords)
def XML(self, uri, tc, ps, **keywords):
self._check_allowed(uri)
return XML(uri, tc, ps, **keywords)
def Resolve(self, uri, tc, ps, **keywords):
if isinstance(tc, TC.XML):
return XML(uri, tc, ps, **keywords)
return Opaque(uri, tc, ps, **keywords)
class MIMEResolver:
'''Multi-part MIME resolver -- SOAP With Attachments, mostly.
'''
def __init__(self, ct, f, next=None, uribase='thismessage:/',
seekable=0, **kw):
# Get the boundary. It's too bad I have to write this myself,
# but no way am I going to import cgi for 10 lines of code!
for param in ct.split(';'):
a = param.strip()
if a.startswith('boundary='):
if a[9] in [ '"', "'" ]:
boundary = a[10:-1]
else:
boundary = a[9:]
break
else:
raise ValueError('boundary parameter not found')
self.id_dict, self.loc_dict, self.parts = {}, {}, []
self.next = next
self.base = uribase
mf = multifile.MultiFile(f, seekable)
mf.push(boundary)
while mf.next():
head = mimetools.Message(mf)
body = StringIO.StringIO()
mimetools.decode(mf, body, head.getencoding())
body.seek(0)
part = (head, body)
self.parts.append(part)
key = head.get('content-id')
if key:
if key[0] == '<' and key[-1] == '>': key = key[1:-1]
self.id_dict[key] = part
key = head.get('content-location')
if key: self.loc_dict[key] = part
mf.pop()
def GetSOAPPart(self):
'''Get the SOAP body part.
'''
head, part = self.parts[0]
return StringIO.StringIO(part.getvalue())
def get(self, uri):
'''Get the content for the bodypart identified by the uri.
'''
if uri.startswith('cid:'):
# Content-ID, so raise exception if not found.
head, part = self.id_dict[uri[4:]]
return StringIO.StringIO(part.getvalue())
if self.loc_dict.has_key(uri):
head, part = self.loc_dict[uri]
return StringIO.StringIO(part.getvalue())
return None
def Opaque(self, uri, tc, ps, **keywords):
content = self.get(uri)
if content: return content.getvalue()
if not self.next: raise EvaluateException("Unresolvable URI " + uri)
return self.next.Opaque(uri, tc, ps, **keywords)
def XML(self, uri, tc, ps, **keywords):
content = self.get(uri)
if content:
dom = ps.readerclass().fromStream(content)
return _child_elements(dom)[0]
if not self.next: raise EvaluateException("Unresolvable URI " + uri)
return self.next.XML(uri, tc, ps, **keywords)
def Resolve(self, uri, tc, ps, **keywords):
if isinstance(tc, TC.XML):
return self.XML(uri, tc, ps, **keywords)
return self.Opaque(uri, tc, ps, **keywords)
def __getitem__(self, cid):
head, body = self.id_dict[cid]
newio = StringIO.StringIO(body.getvalue())
return newio
if __name__ == '__main__': print _copyright | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/resolvers.py | resolvers.py |
from ZSI import _copyright, _seqtypes, ParsedSoap, SoapWriter, TC, ZSI_SCHEMA_URI,\
EvaluateException, FaultFromFaultMessage, _child_elements, _attrs, _find_arraytype,\
_find_type, _get_idstr, _get_postvalue_from_absoluteURI, FaultException, WSActionException
from ZSI.auth import AUTH
from ZSI.TC import AnyElement, AnyType, String, TypeCode, _get_global_element_declaration,\
_get_type_definition
from ZSI.TCcompound import Struct
import base64, httplib, Cookie, types, time, urlparse
from ZSI.address import Address
from ZSI.wstools.logging import getLogger as _GetLogger
_b64_encode = base64.encodestring
class _AuthHeader:
"""<BasicAuth xmlns="ZSI_SCHEMA_URI">
<Name>%s</Name><Password>%s</Password>
</BasicAuth>
"""
def __init__(self, name=None, password=None):
self.Name = name
self.Password = password
_AuthHeader.typecode = Struct(_AuthHeader, ofwhat=(String((ZSI_SCHEMA_URI,'Name'), typed=False),
String((ZSI_SCHEMA_URI,'Password'), typed=False)), pname=(ZSI_SCHEMA_URI,'BasicAuth'),
typed=False)
class _Caller:
'''Internal class used to give the user a callable object
that calls back to the Binding object to make an RPC call.
'''
def __init__(self, binding, name):
self.binding, self.name = binding, name
def __call__(self, *args):
return self.binding.RPC(None, self.name, args,
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/",
replytype=TC.Any(self.name+"Response"))
class _NamedParamCaller:
'''Similar to _Caller, expect that there are named parameters
not positional.
'''
def __init__(self, binding, name):
self.binding, self.name = binding, name
def __call__(self, **params):
# Pull out arguments that Send() uses
kw = { }
for key in [ 'auth_header', 'nsdict', 'requesttypecode' 'soapaction' ]:
if params.has_key(key):
kw[key] = params[key]
del params[key]
return self.binding.RPC(None, self.name, None,
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/",
_args=params,
replytype=TC.Any(self.name+"Response", aslist=False),
**kw)
class _Binding:
'''Object that represents a binding (connection) to a SOAP server.
Once the binding is created, various ways of sending and
receiving SOAP messages are available.
'''
defaultHttpTransport = httplib.HTTPConnection
defaultHttpsTransport = httplib.HTTPSConnection
logger = _GetLogger('ZSI.client.Binding')
def __init__(self, nsdict=None, transport=None, url=None, tracefile=None,
readerclass=None, writerclass=None, soapaction='',
wsAddressURI=None, sig_handler=None, transdict=None, **kw):
'''Initialize.
Keyword arguments include:
transport -- default use HTTPConnection.
transdict -- dict of values to pass to transport.
url -- URL of resource, POST is path
soapaction -- value of SOAPAction header
auth -- (type, name, password) triplet; default is unauth
nsdict -- namespace entries to add
tracefile -- file to dump packet traces
cert_file, key_file -- SSL data (q.v.)
readerclass -- DOM reader class
writerclass -- DOM writer class, implements MessageInterface
wsAddressURI -- namespaceURI of WS-Address to use. By default
it's not used.
sig_handler -- XML Signature handler, must sign and verify.
endPointReference -- optional Endpoint Reference.
'''
self.data = None
self.ps = None
self.user_headers = []
self.nsdict = nsdict or {}
self.transport = transport
self.transdict = transdict or {}
self.url = url
self.trace = tracefile
self.readerclass = readerclass
self.writerclass = writerclass
self.soapaction = soapaction
self.wsAddressURI = wsAddressURI
self.sig_handler = sig_handler
self.address = None
self.endPointReference = kw.get('endPointReference', None)
self.cookies = Cookie.SimpleCookie()
self.http_callbacks = {}
if kw.has_key('auth'):
self.SetAuth(*kw['auth'])
else:
self.SetAuth(AUTH.none)
def SetAuth(self, style, user=None, password=None):
'''Change auth style, return object to user.
'''
self.auth_style, self.auth_user, self.auth_pass = \
style, user, password
return self
def SetURL(self, url):
'''Set the URL we post to.
'''
self.url = url
return self
def ResetHeaders(self):
'''Empty the list of additional headers.
'''
self.user_headers = []
return self
def ResetCookies(self):
'''Empty the list of cookies.
'''
self.cookies = Cookie.SimpleCookie()
def AddHeader(self, header, value):
'''Add a header to send.
'''
self.user_headers.append((header, value))
return self
def __addcookies(self):
'''Add cookies from self.cookies to request in self.h
'''
for cname, morsel in self.cookies.items():
attrs = []
value = morsel.get('version', '')
if value != '' and value != '0':
attrs.append('$Version=%s' % value)
attrs.append('%s=%s' % (cname, morsel.coded_value))
value = morsel.get('path')
if value:
attrs.append('$Path=%s' % value)
value = morsel.get('domain')
if value:
attrs.append('$Domain=%s' % value)
self.h.putheader('Cookie', "; ".join(attrs))
def RPC(self, url, opname, obj, replytype=None, **kw):
'''Send a request, return the reply. See Send() and Recieve()
docstrings for details.
'''
self.Send(url, opname, obj, **kw)
return self.Receive(replytype, **kw)
def Send(self, url, opname, obj, nsdict={}, soapaction=None, wsaction=None,
endPointReference=None, **kw):
'''Send a message. If url is None, use the value from the
constructor (else error). obj is the object (data) to send.
Data may be described with a requesttypecode keyword, the default
is the class's typecode (if there is one), else Any.
Try to serialize as a Struct, if this is not possible serialize an Array. If
data is a sequence of built-in python data types, it will be serialized as an
Array, unless requesttypecode is specified.
arguments:
url --
opname -- struct wrapper
obj -- python instance
key word arguments:
nsdict --
soapaction --
wsaction -- WS-Address Action, goes in SOAP Header.
endPointReference -- set by calling party, must be an
EndPointReference type instance.
requesttypecode --
'''
url = url or self.url
endPointReference = endPointReference or self.endPointReference
# Serialize the object.
d = {}
d.update(self.nsdict)
d.update(nsdict)
sw = SoapWriter(nsdict=d, header=True, outputclass=self.writerclass,
encodingStyle=kw.get('encodingStyle'),)
requesttypecode = kw.get('requesttypecode')
if kw.has_key('_args'): #NamedParamBinding
tc = requesttypecode or TC.Any(pname=opname, aslist=False)
sw.serialize(kw['_args'], tc)
elif not requesttypecode:
tc = getattr(obj, 'typecode', None) or TC.Any(pname=opname, aslist=False)
try:
if type(obj) in _seqtypes:
obj = dict(map(lambda i: (i.typecode.pname,i), obj))
except AttributeError:
# can't do anything but serialize this in a SOAP:Array
tc = TC.Any(pname=opname, aslist=True)
else:
tc = TC.Any(pname=opname, aslist=False)
sw.serialize(obj, tc)
else:
sw.serialize(obj, requesttypecode)
#
# Determine the SOAP auth element. SOAP:Header element
if self.auth_style & AUTH.zsibasic:
sw.serialize_header(_AuthHeader(self.auth_user, self.auth_pass),
_AuthHeader.typecode)
#
# Serialize WS-Address
if self.wsAddressURI is not None:
if self.soapaction and wsaction.strip('\'"') != self.soapaction:
raise WSActionException, 'soapAction(%s) and WS-Action(%s) must match'\
%(self.soapaction,wsaction)
self.address = Address(url, self.wsAddressURI)
self.address.setRequest(endPointReference, wsaction)
self.address.serialize(sw)
#
# WS-Security Signature Handler
if self.sig_handler is not None:
self.sig_handler.sign(sw)
scheme,netloc,path,nil,nil,nil = urlparse.urlparse(url)
transport = self.transport
if transport is None and url is not None:
if scheme == 'https':
transport = self.defaultHttpsTransport
elif scheme == 'http':
transport = self.defaultHttpTransport
else:
raise RuntimeError, 'must specify transport or url startswith https/http'
# Send the request.
if issubclass(transport, httplib.HTTPConnection) is False:
raise TypeError, 'transport must be a HTTPConnection'
soapdata = str(sw)
self.h = transport(netloc, None, **self.transdict)
self.h.connect()
self.SendSOAPData(soapdata, url, soapaction, **kw)
def SendSOAPData(self, soapdata, url, soapaction, headers={}, **kw):
# Tracing?
if self.trace:
print >>self.trace, "_" * 33, time.ctime(time.time()), "REQUEST:"
print >>self.trace, soapdata
#scheme,netloc,path,nil,nil,nil = urlparse.urlparse(url)
path = _get_postvalue_from_absoluteURI(url)
self.h.putrequest("POST", path)
self.h.putheader("Content-length", "%d" % len(soapdata))
self.h.putheader("Content-type", 'text/xml; charset=utf-8')
self.__addcookies()
for header,value in headers.items():
self.h.putheader(header, value)
SOAPActionValue = '"%s"' % (soapaction or self.soapaction)
self.h.putheader("SOAPAction", SOAPActionValue)
if self.auth_style & AUTH.httpbasic:
val = _b64_encode(self.auth_user + ':' + self.auth_pass) \
.replace("\012", "")
self.h.putheader('Authorization', 'Basic ' + val)
elif self.auth_style == AUTH.httpdigest and not headers.has_key('Authorization') \
and not headers.has_key('Expect'):
def digest_auth_cb(response):
self.SendSOAPDataHTTPDigestAuth(response, soapdata, url, soapaction, **kw)
self.http_callbacks[401] = None
self.http_callbacks[401] = digest_auth_cb
for header,value in self.user_headers:
self.h.putheader(header, value)
self.h.endheaders()
self.h.send(soapdata)
# Clear prior receive state.
self.data, self.ps = None, None
def SendSOAPDataHTTPDigestAuth(self, response, soapdata, url, soapaction, **kw):
'''Resend the initial request w/http digest authorization headers.
The SOAP server has requested authorization. Fetch the challenge,
generate the authdict for building a response.
'''
if self.trace:
print >>self.trace, "------ Digest Auth Header"
url = url or self.url
if response.status != 401:
raise RuntimeError, 'Expecting HTTP 401 response.'
if self.auth_style != AUTH.httpdigest:
raise RuntimeError,\
'Auth style(%d) does not support requested digest authorization.' %self.auth_style
from ZSI.digest_auth import fetch_challenge,\
generate_response,\
build_authorization_arg,\
dict_fetch
chaldict = fetch_challenge( response.getheader('www-authenticate') )
if dict_fetch(chaldict,'challenge','').lower() == 'digest' and \
dict_fetch(chaldict,'nonce',None) and \
dict_fetch(chaldict,'realm',None) and \
dict_fetch(chaldict,'qop',None):
authdict = generate_response(chaldict,
url, self.auth_user, self.auth_pass, method='POST')
headers = {\
'Authorization':build_authorization_arg(authdict),
'Expect':'100-continue',
}
self.SendSOAPData(soapdata, url, soapaction, headers, **kw)
return
raise RuntimeError,\
'Client expecting digest authorization challenge.'
def ReceiveRaw(self, **kw):
'''Read a server reply, unconverted to any format and return it.
'''
if self.data: return self.data
trace = self.trace
while 1:
response = self.h.getresponse()
self.reply_code, self.reply_msg, self.reply_headers, self.data = \
response.status, response.reason, response.msg, response.read()
if trace:
print >>trace, "_" * 33, time.ctime(time.time()), "RESPONSE:"
for i in (self.reply_code, self.reply_msg,):
print >>trace, str(i)
print >>trace, "-------"
print >>trace, str(self.reply_headers)
print >>trace, self.data
saved = None
for d in response.msg.getallmatchingheaders('set-cookie'):
if d[0] in [ ' ', '\t' ]:
saved += d.strip()
else:
if saved: self.cookies.load(saved)
saved = d.strip()
if saved: self.cookies.load(saved)
if response.status == 401:
if not callable(self.http_callbacks.get(response.status,None)):
raise RuntimeError, 'HTTP Digest Authorization Failed'
self.http_callbacks[response.status](response)
continue
if response.status != 100: break
# The httplib doesn't understand the HTTP continuation header.
# Horrible internals hack to patch things up.
self.h._HTTPConnection__state = httplib._CS_REQ_SENT
self.h._HTTPConnection__response = None
return self.data
def IsSOAP(self):
if self.ps: return 1
self.ReceiveRaw()
mimetype = self.reply_headers.type
return mimetype == 'text/xml'
def ReceiveSOAP(self, readerclass=None, **kw):
'''Get back a SOAP message.
'''
if self.ps: return self.ps
if not self.IsSOAP():
raise TypeError(
'Response is "%s", not "text/xml"' % self.reply_headers.type)
if len(self.data) == 0:
raise TypeError('Received empty response')
self.ps = ParsedSoap(self.data,
readerclass=readerclass or self.readerclass,
encodingStyle=kw.get('encodingStyle'))
if self.sig_handler is not None:
self.sig_handler.verify(self.ps)
return self.ps
def IsAFault(self):
'''Get a SOAP message, see if it has a fault.
'''
self.ReceiveSOAP()
return self.ps.IsAFault()
def ReceiveFault(self, **kw):
'''Parse incoming message as a fault. Raise TypeError if no
fault found.
'''
self.ReceiveSOAP(**kw)
if not self.ps.IsAFault():
raise TypeError("Expected SOAP Fault not found")
return FaultFromFaultMessage(self.ps)
def Receive(self, replytype, **kw):
'''Parse message, create Python object.
KeyWord data:
faults -- list of WSDL operation.fault typecodes
wsaction -- If using WS-Address, must specify Action value we expect to
receive.
'''
self.ReceiveSOAP(**kw)
if self.ps.IsAFault():
msg = FaultFromFaultMessage(self.ps)
raise FaultException(msg)
tc = replytype
if hasattr(replytype, 'typecode'):
tc = replytype.typecode
reply = self.ps.Parse(tc)
if self.address is not None:
self.address.checkResponse(self.ps, kw.get('wsaction'))
return reply
def __repr__(self):
return "<%s instance %s>" % (self.__class__.__name__, _get_idstr(self))
class Binding(_Binding):
'''Object that represents a binding (connection) to a SOAP server.
Can be used in the "name overloading" style.
class attr:
gettypecode -- funcion that returns typecode from typesmodule,
can be set so can use whatever mapping you desire.
'''
gettypecode = staticmethod(lambda mod,e: getattr(mod, str(e.localName)).typecode)
logger = _GetLogger('ZSI.client.Binding')
def __init__(self, typesmodule=None, **kw):
self.typesmodule = typesmodule
_Binding.__init__(self, **kw)
def __getattr__(self, name):
'''Return a callable object that will invoke the RPC method
named by the attribute.
'''
if name[:2] == '__' and len(name) > 5 and name[-2:] == '__':
if hasattr(self, name): return getattr(self, name)
return getattr(self.__class__, name)
return _Caller(self, name)
def __parse_child(self, node):
'''for rpc-style map each message part to a class in typesmodule
'''
try:
tc = self.gettypecode(self.typesmodule, node)
except:
self.logger.debug('didnt find typecode for "%s" in typesmodule: %s',
node.localName, self.typesmodule)
tc = TC.Any(aslist=1)
return tc.parse(node, self.ps)
self.logger.debug('parse child with typecode : %s', tc)
try:
return tc.parse(node, self.ps)
except Exception:
self.logger.debug('parse failed try Any : %s', tc)
tc = TC.Any(aslist=1)
return tc.parse(node, self.ps)
def Receive(self, replytype, **kw):
'''Parse message, create Python object.
KeyWord data:
faults -- list of WSDL operation.fault typecodes
wsaction -- If using WS-Address, must specify Action value we expect to
receive.
'''
self.ReceiveSOAP(**kw)
ps = self.ps
tp = _find_type(ps.body_root)
isarray = ((type(tp) in (tuple,list) and tp[1] == 'Array') or _find_arraytype(ps.body_root))
if self.typesmodule is None or isarray:
return _Binding.Receive(self, replytype, **kw)
if ps.IsAFault():
msg = FaultFromFaultMessage(ps)
raise FaultException(msg)
tc = replytype
if hasattr(replytype, 'typecode'):
tc = replytype.typecode
#Ignore response wrapper
reply = {}
for elt in _child_elements(ps.body_root):
name = str(elt.localName)
reply[name] = self.__parse_child(elt)
if self.address is not None:
self.address.checkResponse(ps, kw.get('wsaction'))
return reply
class NamedParamBinding(Binding):
'''Like Binding, except the argument list for invocation is
named parameters.
'''
logger = _GetLogger('ZSI.client.Binding')
def __getattr__(self, name):
'''Return a callable object that will invoke the RPC method
named by the attribute.
'''
if name[:2] == '__' and len(name) > 5 and name[-2:] == '__':
if hasattr(self, name): return getattr(self, name)
return getattr(self.__class__, name)
return _NamedParamCaller(self, name)
if __name__ == '__main__': print _copyright | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/client.py | client.py |
import urlparse, types, os, sys, cStringIO as StringIO, thread,re
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from ZSI import ParseException, FaultFromException, FaultFromZSIException, Fault
from ZSI import _copyright, _seqtypes, _get_element_nsuri_name, resolvers
from ZSI import _get_idstr
from ZSI.address import Address
from ZSI.parse import ParsedSoap
from ZSI.writer import SoapWriter
from ZSI.dispatch import _ModPythonSendXML, _ModPythonSendFault, _CGISendXML, _CGISendFault
from ZSI.dispatch import SOAPRequestHandler as BaseSOAPRequestHandler
"""
Functions:
_Dispatch
AsServer
GetSOAPContext
Classes:
SOAPContext
NoSuchService
PostNotSpecified
SOAPActionNotSpecified
ServiceSOAPBinding
SimpleWSResource
SOAPRequestHandler
ServiceContainer
"""
class NoSuchService(Exception): pass
class UnknownRequestException(Exception): pass
class PostNotSpecified(Exception): pass
class SOAPActionNotSpecified(Exception): pass
class WSActionException(Exception): pass
class WSActionNotSpecified(WSActionException): pass
class NotAuthorized(Exception): pass
class ServiceAlreadyPresent(Exception): pass
class SOAPContext:
def __init__(self, container, xmldata, ps, connection, httpheaders,
soapaction):
self.container = container
self.xmldata = xmldata
self.parsedsoap = ps
self.connection = connection
self.httpheaders= httpheaders
self.soapaction = soapaction
_contexts = dict()
def GetSOAPContext():
global _contexts
return _contexts[thread.get_ident()]
def _Dispatch(ps, server, SendResponse, SendFault, post, action, nsdict={}, **kw):
'''Send ParsedSoap instance to ServiceContainer, which dispatches to
appropriate service via post, and method via action. Response is a
self-describing pyobj, which is passed to a SoapWriter.
Call SendResponse or SendFault to send the reply back, appropriately.
server -- ServiceContainer instance
'''
localURL = 'http://%s:%d%s' %(server.server_name,server.server_port,post)
address = action
service = server.getNode(post)
isWSResource = False
if isinstance(service, SimpleWSResource):
isWSResource = True
service.setServiceURL(localURL)
address = Address()
try:
address.parse(ps)
except Exception, e:
return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)
if action and action != address.getAction():
e = WSActionException('SOAP Action("%s") must match WS-Action("%s") if specified.' \
%(action,address.getAction()))
return SendFault(FaultFromException(e, 0, None), **kw)
action = address.getAction()
if isinstance(service, ServiceInterface) is False:
e = NoSuchService('no service at POST(%s) in container: %s' %(post,server))
return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)
if not service.authorize(None, post, action):
return SendFault(Fault(Fault.Server, "Not authorized"), code=401)
#try:
# raise NotAuthorized()
#except Exception, e:
#return SendFault(FaultFromException(e, 0, None), code=401, **kw)
##return SendFault(FaultFromException(NotAuthorized(), 0, None), code=401, **kw)
try:
method = service.getOperation(ps, address)
except Exception, e:
return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)
try:
if isWSResource is True:
result = method(ps, address)
else:
result = method(ps)
except Exception, e:
return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)
# Verify if Signed
service.verify(ps)
# If No response just return.
if result is None:
return
sw = SoapWriter(nsdict=nsdict)
try:
sw.serialize(result)
except Exception, e:
return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)
if isWSResource is True:
action = service.getResponseAction(action)
addressRsp = Address(action=action)
try:
addressRsp.setResponseFromWSAddress(address, localURL)
addressRsp.serialize(sw)
except Exception, e:
return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)
# Create Signatures
service.sign(sw)
try:
soapdata = str(sw)
return SendResponse(soapdata, **kw)
except Exception, e:
return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)
def AsServer(port=80, services=()):
'''port --
services -- list of service instances
'''
address = ('', port)
sc = ServiceContainer(address, services)
#for service in services:
# path = service.getPost()
# sc.setNode(service, path)
sc.serve_forever()
class ServiceInterface:
'''Defines the interface for use with ServiceContainer Handlers.
class variables:
soapAction -- dictionary of soapAction keys, and operation name values.
These are specified in the WSDL soap bindings. There must be a
class method matching the operation name value. If WS-Action is
used the keys are WS-Action request values, according to the spec
if soapAction and WS-Action is specified they must be equal.
wsAction -- dictionary of operation name keys and WS-Action
response values. These values are specified by the portType.
root -- dictionary of root element keys, and operation name values.
'''
soapAction = {}
wsAction = {}
root = {}
def __init__(self, post):
self.post = post
def authorize(self, auth_info, post, action):
return 1
def __str__(self):
return '%s(%s) POST(%s)' %(self.__class__.__name__, _get_idstr(self), self.post)
def sign(self, sw):
return
def verify(self, ps):
return
def getPost(self):
return self.post
def getOperation(self, ps, action):
'''Returns a method of class.
action -- soapAction value
'''
opName = self.getOperationName(ps, action)
return getattr(self, opName)
def getOperationName(self, ps, action):
'''Returns operation name.
action -- soapAction value
'''
method = self.root.get(_get_element_nsuri_name(ps.body_root)) or \
self.soapAction.get(action)
if method is None:
raise UnknownRequestException, \
'failed to map request to a method: action(%s), root%s' %(action,_get_element_nsuri_name(ps.body_root))
return method
class ServiceSOAPBinding(ServiceInterface):
'''Binding defines the set of wsdl:binding operations, it takes as input a
ParsedSoap instance and parses it into a pyobj. It returns a response pyobj.
'''
def __init__(self, post):
ServiceInterface.__init__(self, post)
def __call___(self, action, ps):
return self.getOperation(ps, action)(ps)
class SimpleWSResource(ServiceSOAPBinding):
'''Simple WSRF service, performs method resolutions based
on WS-Action values rather than SOAP Action.
class variables:
encoding
wsAction -- Must override to set output Action values.
soapAction -- Must override to set input Action values.
'''
encoding = "UTF-8"
def __init__(self, post=None):
'''
post -- POST value
'''
assert isinstance(self.soapAction, dict), "soapAction must be a dict"
assert isinstance(self.wsAction, dict), "wsAction must be a dict"
ServiceSOAPBinding.__init__(self, post)
def __call___(self, action, ps, address):
return self.getOperation(ps, action)(ps, address)
def getServiceURL(self):
return self._url
def setServiceURL(self, url):
self._url = url
def getOperation(self, ps, address):
'''Returns a method of class.
address -- ws-address
'''
action = address.getAction()
opName = self.getOperationName(ps, action)
return getattr(self, opName)
def getResponseAction(self, ps, action):
'''Returns response WS-Action if available
action -- request WS-Action value.
'''
opName = self.getOperationName(ps, action)
if self.wsAction.has_key(opName) is False:
raise WSActionNotSpecified, 'wsAction dictionary missing key(%s)' %opName
return self.wsAction[opName]
def do_POST(self):
'''The POST command. This is called by HTTPServer, not twisted.
action -- SOAPAction(HTTP header) or wsa:Action(SOAP:Header)
'''
global _contexts
soapAction = self.headers.getheader('SOAPAction')
post = self.path
if not post:
raise PostNotSpecified, 'HTTP POST not specified in request'
if soapAction:
soapAction = soapAction.strip('\'"')
post = post.strip('\'"')
try:
ct = self.headers['content-type']
if ct.startswith('multipart/'):
cid = resolvers.MIMEResolver(ct, self.rfile)
xml = cid.GetSOAPPart()
ps = ParsedSoap(xml, resolver=cid.Resolve, readerclass=DomletteReader)
else:
length = int(self.headers['content-length'])
ps = ParsedSoap(self.rfile.read(length), readerclass=DomletteReader)
except ParseException, e:
self.send_fault(FaultFromZSIException(e))
except Exception, e:
# Faulted while processing; assume it's in the header.
self.send_fault(FaultFromException(e, 1, sys.exc_info()[2]))
else:
# Keep track of calls
thread_id = thread.get_ident()
_contexts[thread_id] = SOAPContext(self.server, xml, ps,
self.connection,
self.headers, soapAction)
try:
_Dispatch(ps, self.server, self.send_xml, self.send_fault,
post=post, action=soapAction)
except Exception, e:
self.send_fault(FaultFromException(e, 0, sys.exc_info()[2]))
# Clean up after the call
if _contexts.has_key(thread_id):
del _contexts[thread_id]
class SOAPRequestHandler(BaseSOAPRequestHandler):
'''SOAP handler.
'''
def do_POST(self):
'''The POST command.
action -- SOAPAction(HTTP header) or wsa:Action(SOAP:Header)
'''
soapAction = self.headers.getheader('SOAPAction')
post = self.path
if not post:
raise PostNotSpecified, 'HTTP POST not specified in request'
if soapAction:
soapAction = soapAction.strip('\'"')
post = post.strip('\'"')
try:
ct = self.headers['content-type']
if ct.startswith('multipart/'):
cid = resolvers.MIMEResolver(ct, self.rfile)
xml = cid.GetSOAPPart()
ps = ParsedSoap(xml, resolver=cid.Resolve)
else:
length = int(self.headers['content-length'])
xml = self.rfile.read(length)
ps = ParsedSoap(xml)
except ParseException, e:
self.send_fault(FaultFromZSIException(e))
except Exception, e:
# Faulted while processing; assume it's in the header.
self.send_fault(FaultFromException(e, 1, sys.exc_info()[2]))
else:
# Keep track of calls
thread_id = thread.get_ident()
_contexts[thread_id] = SOAPContext(self.server, xml, ps,
self.connection,
self.headers, soapAction)
try:
_Dispatch(ps, self.server, self.send_xml, self.send_fault,
post=post, action=soapAction)
except Exception, e:
self.send_fault(FaultFromException(e, 0, sys.exc_info()[2]))
# Clean up after the call
if _contexts.has_key(thread_id):
del _contexts[thread_id]
def do_GET(self):
'''The GET command.
'''
if self.path.lower().endswith("?wsdl"):
service_path = self.path[:-5]
service = self.server.getNode(service_path)
if hasattr(service, "_wsdl"):
wsdl = service._wsdl
# update the soap:location tag in the wsdl to the actual server
# location
# - default to 'http' as protocol, or use server-specified protocol
proto = 'http'
if hasattr(self.server,'proto'):
proto = self.server.proto
serviceUrl = '%s://%s:%d%s' % (proto,
self.server.server_name,
self.server.server_port,
service_path)
soapAddress = '<soap:address location="%s"/>' % serviceUrl
wsdlre = re.compile('\<soap:address[^\>]*>',re.IGNORECASE)
wsdl = re.sub(wsdlre,soapAddress,wsdl)
self.send_xml(wsdl)
else:
self.send_error(404, "WSDL not available for that service [%s]." % self.path)
else:
self.send_error(404, "Service not found [%s]." % self.path)
class ServiceContainer(HTTPServer):
'''HTTPServer that stores service instances according
to POST values. An action value is instance specific,
and specifies an operation (function) of an instance.
'''
class NodeTree:
'''Simple dictionary implementation of a node tree
'''
def __init__(self):
self.__dict = {}
def __str__(self):
return str(self.__dict)
def listNodes(self):
print self.__dict.keys()
def getNode(self, url):
path = urlparse.urlsplit(url)[2]
if path.startswith("/"):
path = path[1:]
if self.__dict.has_key(path):
return self.__dict[path]
else:
raise NoSuchService, 'No service(%s) in ServiceContainer' %path
def setNode(self, service, url):
path = urlparse.urlsplit(url)[2]
if path.startswith("/"):
path = path[1:]
if not isinstance(service, ServiceSOAPBinding):
raise TypeError, 'A Service must implement class ServiceSOAPBinding'
if self.__dict.has_key(path):
raise ServiceAlreadyPresent, 'Service(%s) already in ServiceContainer' % path
else:
self.__dict[path] = service
def removeNode(self, url):
path = urlparse.urlsplit(url)[2]
if path.startswith("/"):
path = path[1:]
if self.__dict.has_key(path):
node = self.__dict[path]
del self.__dict[path]
return node
else:
raise NoSuchService, 'No service(%s) in ServiceContainer' %path
def __init__(self, server_address, services=[], RequestHandlerClass=SOAPRequestHandler):
'''server_address --
RequestHandlerClass --
'''
HTTPServer.__init__(self, server_address, RequestHandlerClass)
self._nodes = self.NodeTree()
map(lambda s: self.setNode(s), services)
def __str__(self):
return '%s(%s) nodes( %s )' %(self.__class__, _get_idstr(self), str(self._nodes))
def __call__(self, ps, post, action, address=None):
'''ps -- ParsedSoap representing the request
post -- HTTP POST --> instance
action -- Soap Action header --> method
address -- Address instance representing WS-Address
'''
method = self.getCallBack(ps, post, action)
if isinstance(method.im_self, SimpleWSResource):
return method(ps, address)
return method(ps)
def setNode(self, service, url=None):
if url is None:
url = service.getPost()
self._nodes.setNode(service, url)
def getNode(self, url):
return self._nodes.getNode(url)
def removeNode(self, url):
self._nodes.removeNode(url)
class SimpleWSResource(ServiceSOAPBinding):
def getNode(self, post):
'''post -- POST HTTP value
'''
return self._nodes.getNode(post)
def setNode(self, service, post):
'''service -- service instance
post -- POST HTTP value
'''
self._nodes.setNode(service, post)
def getCallBack(self, ps, post, action):
'''post -- POST HTTP value
action -- SOAP Action value
'''
node = self.getNode(post)
if node is None:
raise NoSuchFunction
if node.authorize(None, post, action):
return node.getOperation(ps, action)
else:
raise NotAuthorized, "Authorization failed for method %s" % action
if __name__ == '__main__': print _copyright | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/ServiceContainer.py | ServiceContainer.py |
from ZSI import _copyright, _get_idstr, ZSI_SCHEMA_URI
from ZSI import _backtrace, _stringtypes, _seqtypes
from ZSI.wstools.Utility import MessageInterface, ElementProxy
from ZSI.wstools.Namespaces import XMLNS, SOAP, SCHEMA
from ZSI.wstools.c14n import Canonicalize
import types
_standard_ns = [ ('xml', XMLNS.XML), ('xmlns', XMLNS.BASE) ]
_reserved_ns = {
'SOAP-ENV': SOAP.ENV,
'SOAP-ENC': SOAP.ENC,
'ZSI': ZSI_SCHEMA_URI,
'xsd': SCHEMA.BASE,
'xsi': SCHEMA.BASE + '-instance',
}
class SoapWriter:
'''SOAP output formatter.
Instance Data:
memo -- memory for id/href
envelope -- add Envelope?
encodingStyle --
header -- add SOAP Header?
outputclass -- ElementProxy class.
'''
def __init__(self, envelope=True, encodingStyle=None, header=True,
nsdict={}, outputclass=None, **kw):
'''Initialize.
'''
outputclass = outputclass or ElementProxy
if not issubclass(outputclass, MessageInterface):
raise TypeError, 'outputclass must subclass MessageInterface'
self.dom, self.memo, self.nsdict= \
outputclass(self), [], nsdict
self.envelope = envelope
self.encodingStyle = encodingStyle
self.header = header
self.body = None
self.callbacks = []
self.closed = False
def __str__(self):
self.close()
return str(self.dom)
def getSOAPHeader(self):
if self.header in (True, False):
return None
return self.header
def serialize_header(self, pyobj, typecode=None, **kw):
'''Serialize a Python object in SOAP-ENV:Header, make
sure everything in Header unique (no #href). Must call
serialize first to create a document.
Parameters:
pyobjs -- instances to serialize in SOAP Header
typecode -- default typecode
'''
kw['unique'] = True
soap_env = _reserved_ns['SOAP-ENV']
#header = self.dom.getElement(soap_env, 'Header')
header = self._header
if header is None:
header = self._header = self.dom.createAppendElement(soap_env,
'Header')
typecode = getattr(pyobj, 'typecode', typecode)
if typecode is None:
raise RuntimeError(
'typecode is required to serialize pyobj in header')
helt = typecode.serialize(header, self, pyobj, **kw)
def serialize(self, pyobj, typecode=None, root=None, header_pyobjs=(), **kw):
'''Serialize a Python object to the output stream.
pyobj -- python instance to serialize in body.
typecode -- typecode describing body
root -- SOAP-ENC:root
header_pyobjs -- list of pyobj for soap header inclusion, each
instance must specify the typecode attribute.
'''
self.body = None
if self.envelope:
soap_env = _reserved_ns['SOAP-ENV']
self.dom.createDocument(soap_env, 'Envelope')
for prefix, nsuri in _reserved_ns.items():
self.dom.setNamespaceAttribute(prefix, nsuri)
self.writeNSdict(self.nsdict)
if self.encodingStyle:
self.dom.setAttributeNS(soap_env, 'encodingStyle',
self.encodingStyle)
if self.header:
self._header = self.dom.createAppendElement(soap_env, 'Header')
for h in header_pyobjs:
self.serialize_header(h, **kw)
self.body = self.dom.createAppendElement(soap_env, 'Body')
else:
self.dom.createDocument(None,None)
if typecode is None: typecode = pyobj.__class__.typecode
kw = kw.copy()
if self.body is None:
elt = typecode.serialize(self.dom, self, pyobj, **kw)
else:
elt = typecode.serialize(self.body, self, pyobj, **kw)
if root is not None:
if root not in [ 0, 1 ]:
raise ValueError, "SOAP-ENC root attribute not in [0,1]"
elt.setAttributeNS(SOAP.ENC, 'root', root)
return self
def writeNSdict(self, nsdict):
'''Write a namespace dictionary, taking care to not clobber the
standard (or reserved by us) prefixes.
'''
for k,v in nsdict.items():
if (k,v) in _standard_ns: continue
rv = _reserved_ns.get(k)
if rv:
if rv != v:
raise KeyError("Reserved namespace " + str((k,v)) + " used")
continue
if k:
self.dom.setNamespaceAttribute(k, v)
else:
self.dom.setNamespaceAttribute('xmlns', v)
def ReservedNS(self, prefix, uri):
'''Is this namespace (prefix,uri) reserved by us?
'''
return _reserved_ns.get(prefix, uri) != uri
def AddCallback(self, func, *arglist):
'''Add a callback function and argument list to be invoked before
closing off the SOAP Body.
'''
self.callbacks.append((func, arglist))
def Known(self, obj):
'''Seen this object (known by its id()? Return 1 if so,
otherwise add it to our memory and return 0.
'''
obj = _get_idstr(obj)
if obj in self.memo: return 1
self.memo.append(obj)
return 0
def Forget(self, obj):
'''Forget we've seen this object.
'''
obj = _get_idstr(obj)
try:
self.memo.remove(obj)
except ValueError:
pass
def Backtrace(self, elt):
'''Return a human-readable "backtrace" from the document root to
the specified element.
'''
return _backtrace(elt._getNode(), self.dom._getNode())
def close(self):
'''Invoke all the callbacks, and close off the SOAP message.
'''
if self.closed: return
for func,arglist in self.callbacks:
apply(func, arglist)
self.closed = True
def __del__(self):
if not self.closed: self.close()
if __name__ == '__main__': print _copyright | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/writer.py | writer.py |
import ZSI
from ZSI import TC, TCtimes, TCcompound
from ZSI.TC import TypeCode
from ZSI import _copyright, EvaluateException
from ZSI.wstools.Utility import SplitQName
from ZSI.wstools.Namespaces import SOAP, SCHEMA
###########################################################################
# Module Classes: BaseTypeInterpreter
###########################################################################
class NamespaceException(Exception): pass
class BaseTypeInterpreter:
"""Example mapping of xsd/soapenc types to zsi python types.
Checks against all available classes in ZSI.TC. Used in
wsdl2python, wsdlInterpreter, and ServiceProxy.
"""
def __init__(self):
self._type_list = [TC.Iinteger, TC.IunsignedShort, TC.gYearMonth, \
TC.InonNegativeInteger, TC.Iint, TC.String, \
TC.gDateTime, TC.IunsignedInt, TC.Duration,\
TC.IpositiveInteger, TC.FPfloat, TC.gDay, TC.gMonth, \
TC.InegativeInteger, TC.gDate, TC.URI, \
TC.HexBinaryString, TC.IunsignedByte, \
TC.gMonthDay, TC.InonPositiveInteger, \
TC.Ibyte, TC.FPdouble, TC.gTime, TC.gYear, \
TC.Ilong, TC.IunsignedLong, TC.Ishort, \
TC.Token, TC.QName]
self._tc_to_int = [
ZSI.TCnumbers.IEnumeration,
ZSI.TCnumbers.Iint,
ZSI.TCnumbers.Iinteger,
ZSI.TCnumbers.Ilong,
ZSI.TCnumbers.InegativeInteger,
ZSI.TCnumbers.InonNegativeInteger,
ZSI.TCnumbers.InonPositiveInteger,
ZSI.TC.Integer,
ZSI.TCnumbers.IpositiveInteger,
ZSI.TCnumbers.Ishort]
self._tc_to_float = [
ZSI.TC.Decimal,
ZSI.TCnumbers.FPEnumeration,
ZSI.TCnumbers.FPdouble,
ZSI.TCnumbers.FPfloat]
self._tc_to_string = [
ZSI.TC.Base64String,
ZSI.TC.Enumeration,
ZSI.TC.HexBinaryString,
ZSI.TCnumbers.Ibyte,
ZSI.TCnumbers.IunsignedByte,
ZSI.TCnumbers.IunsignedInt,
ZSI.TCnumbers.IunsignedLong,
ZSI.TCnumbers.IunsignedShort,
ZSI.TC.String,
ZSI.TC.URI,
ZSI.TC.XMLString,
ZSI.TC.Token]
self._tc_to_tuple = [
ZSI.TC.Duration,
ZSI.TC.QName,
ZSI.TCtimes.gDate,
ZSI.TCtimes.gDateTime,
ZSI.TCtimes.gDay,
ZSI.TCtimes.gMonthDay,
ZSI.TCtimes.gTime,
ZSI.TCtimes.gYear,
ZSI.TCtimes.gMonth,
ZSI.TCtimes.gYearMonth]
return
def _get_xsd_typecode(self, msg_type):
untaged_xsd_types = {'boolean':TC.Boolean,
'decimal':TC.Decimal,
'base64Binary':TC.Base64String}
if untaged_xsd_types.has_key(msg_type):
return untaged_xsd_types[msg_type]
for tc in self._type_list:
if tc.type == (SCHEMA.XSD3,msg_type):
break
else:
tc = TC.AnyType
return tc
def _get_soapenc_typecode(self, msg_type):
if msg_type == 'Array':
return TCcompound.Array
if msg_type == 'Struct':
return TCcompound.Struct
return self._get_xsd_typecode(msg_type)
def get_typeclass(self, msg_type, targetNamespace):
prefix, name = SplitQName(msg_type)
if targetNamespace in SCHEMA.XSD_LIST:
return self._get_xsd_typecode(name)
elif targetNamespace in [SOAP.ENC]:
return self._get_soapenc_typecode(name)
return None
def get_pythontype(self, msg_type, targetNamespace, typeclass=None):
if not typeclass:
tc = self.get_typeclass(msg_type, targetNamespace)
else:
tc = typeclass
if tc in self._tc_to_int:
return 'int'
elif tc in self._tc_to_float:
return 'float'
elif tc in self._tc_to_string:
return 'str'
elif tc in self._tc_to_tuple:
return 'tuple'
elif tc in [TCcompound.Array]:
return 'list'
elif tc in [TC.Boolean]:
return 'bool'
elif isinstance(tc, TypeCode):
raise EvaluateException,\
'failed to map zsi typecode to a python type'
return None | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/typeinterpreter.py | typeinterpreter.py |
from ZSI import _copyright, _child_elements, _get_idstr
from ZSI.TC import TypeCode, Struct as _Struct, Any as _Any
class Apache:
NS = "http://xml.apache.org/xml-soap"
class _Map(TypeCode):
'''Apache's "Map" type.
'''
parselist = [ (Apache.NS, 'Map') ]
def __init__(self, pname=None, aslist=0, **kw):
TypeCode.__init__(self, pname, **kw)
self.aslist = aslist
self.tc = _Struct(None, [ _Any('key'), _Any('value') ], inline=1)
def parse(self, elt, ps):
self.checkname(elt, ps)
if self.nilled(elt, ps): return None
p = self.tc.parse
if self.aslist:
v = []
for c in _child_elements(elt):
d = p(c, ps)
v.append((d['key'], d['value']))
else:
v = {}
for c in _child_elements(elt):
d = p(c, ps)
v[d['key']] = d['value']
return v
def serialize(self, elt, sw, pyobj, name=None, **kw):
objid = _get_idstr(pyobj)
n = name or self.pname or ('E' + objid)
# nillable
el = elt.createAppendElement(self.nspname, n)
if self.nillable is True and pyobj is None:
self.serialize_as_nil(el)
return None
# other attributes
self.set_attributes(el, pyobj)
# soap href attribute
unique = self.unique or kw.get('unique', False)
if unique is False and sw.Known(orig or pyobj):
self.set_attribute_href(el, objid)
return None
# xsi:type attribute
if kw.get('typed', self.typed) is True:
self.set_attribute_xsi_type(el, **kw)
# soap id attribute
if self.unique is False:
self.set_attribute_id(el, objid)
if self.aslist:
for k,v in pyobj:
self.tc.serialize(el, sw, {'key': k, 'value': v}, name='item')
else:
for k,v in pyobj.items():
self.tc.serialize(el, sw, {'key': k, 'value': v}, name='item')
Apache.Map = _Map
if __name__ == '__main__': print _copyright | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/TCapache.py | TCapache.py |
from ZSI import _copyright, _floattypes, _inttypes, _get_idstr, EvaluateException
from ZSI.TC import TypeCode, SimpleType
from ZSI.wstools.Namespaces import SCHEMA
import operator, re, time as _time
from time import mktime as _mktime, localtime as _localtime, gmtime as _gmtime
from datetime import tzinfo as _tzinfo, timedelta as _timedelta,\
datetime as _datetime
from math import modf as _modf
_niltime = [
0, 0, 0, # year month day
0, 0, 0, # hour minute second
0, 0, 0 # weekday, julian day, dst flag
]
#### Code added to check current timezone offset
_zero = _timedelta(0)
_dstoffset = _stdoffset = _timedelta(seconds=-_time.timezone)
if _time.daylight: _dstoffset = _timedelta(seconds=-_time.altzone)
_dstdiff = _dstoffset - _stdoffset
class _localtimezone(_tzinfo):
""" """
def dst(self, dt):
"""datetime -> DST offset in minutes east of UTC."""
tt = _localtime(_mktime((dt.year, dt.month, dt.day,
dt.hour, dt.minute, dt.second, dt.weekday(), 0, -1)))
if tt.tm_isdst > 0: return _dstdiff
return _zero
#def fromutc(...)
#datetime in UTC -> datetime in local time.
def tzname(self, dt):
"""datetime -> string name of time zone."""
tt = _localtime(_mktime((dt.year, dt.month, dt.day,
dt.hour, dt.minute, dt.second, dt.weekday(), 0, -1)))
return _time.tzname[tt.tm_isdst > 0]
def utcoffset(self, dt):
"""datetime -> minutes east of UTC (negative for west of UTC)."""
tt = _localtime(_mktime((dt.year, dt.month, dt.day,
dt.hour, dt.minute, dt.second, dt.weekday(), 0, -1)))
if tt.tm_isdst > 0: return _dstoffset
return _stdoffset
class _fixedoffset(_tzinfo):
"""Fixed offset in minutes east from UTC.
A class building tzinfo objects for fixed-offset time zones.
Note that _fixedoffset(0, "UTC") is a different way to build a
UTC tzinfo object.
"""
#def __init__(self, offset, name):
def __init__(self, offset):
self.__offset = _timedelta(minutes=offset)
#self.__name = name
def dst(self, dt):
"""datetime -> DST offset in minutes east of UTC."""
return _zero
def tzname(self, dt):
"""datetime -> string name of time zone."""
#return self.__name
return "server"
def utcoffset(self, dt):
"""datetime -> minutes east of UTC (negative for west of UTC)."""
return self.__offset
def _dict_to_tuple(d):
'''Convert a dictionary to a time tuple. Depends on key values in the
regexp pattern!
'''
retval = _niltime[:]
for k,i in ( ('Y', 0), ('M', 1), ('D', 2), ('h', 3), ('m', 4), ):
v = d.get(k)
if v: retval[i] = int(v)
v = d.get('s')
if v:
msec,sec = _modf(float(v))
retval[6],retval[5] = int(round(msec*1000)), int(sec)
v = d.get('tz')
if v and v != 'Z':
h,m = map(int, v.split(':'))
# check for time zone offset, if within the same timezone,
# ignore offset specific calculations
offset=_localtimezone().utcoffset(_datetime.now())
local_offset_hour = offset.seconds/3600
local_offset_min = (offset.seconds%3600)%60
if local_offset_hour > 12:
local_offset_hour -= 24
if local_offset_hour != h or local_offset_min != m:
if h<0:
#TODO: why is this set to server
#foff = _fixedoffset(-((abs(h)*60+m)),"server")
foff = _fixedoffset(-((abs(h)*60+m)))
else:
#TODO: why is this set to server
#foff = _fixedoffset((abs(h)*60+m),"server")
foff = _fixedoffset((abs(h)*60+m))
dt = _datetime(retval[0],retval[1],retval[2],retval[3],retval[4],
retval[5],0,foff)
# update dict with calculated timezone
localdt=dt.astimezone(_localtimezone())
retval[0] = localdt.year
retval[1] = localdt.month
retval[2] = localdt.day
retval[3] = localdt.hour
retval[4] = localdt.minute
retval[5] = localdt.second
if d.get('neg', 0):
retval[0:5] = map(operator.__neg__, retval[0:5])
return tuple(retval)
class Duration(SimpleType):
'''Time duration.
'''
parselist = [ (None,'duration') ]
lex_pattern = re.compile('^' r'(?P<neg>-?)P' \
r'((?P<Y>\d+)Y)?' r'((?P<M>\d+)M)?' r'((?P<D>\d+)D)?' \
r'(?P<T>T?)' r'((?P<h>\d+)H)?' r'((?P<m>\d+)M)?' \
r'((?P<s>\d*(\.\d+)?)S)?' '$')
type = (SCHEMA.XSD3, 'duration')
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data.
'''
if text is None:
return None
m = Duration.lex_pattern.match(text)
if m is None:
raise EvaluateException('Illegal duration', ps.Backtrace(elt))
d = m.groupdict()
if d['T'] and (d['h'] is None and d['m'] is None and d['s'] is None):
raise EvaluateException('Duration has T without time')
try:
retval = _dict_to_tuple(d)
except ValueError, e:
raise EvaluateException(str(e))
if self.pyclass is not None:
return self.pyclass(retval)
return retval
def get_formatted_content(self, pyobj):
if type(pyobj) in _floattypes or type(pyobj) in _inttypes:
pyobj = _gmtime(pyobj)
d = {}
pyobj = tuple(pyobj)
if 1 in map(lambda x: x < 0, pyobj[0:6]):
pyobj = map(abs, pyobj)
neg = '-'
else:
neg = ''
val = '%sP%dY%dM%dDT%dH%dM%dS' % \
( neg, pyobj[0], pyobj[1], pyobj[2], pyobj[3], pyobj[4], pyobj[5])
return val
class Gregorian(SimpleType):
'''Gregorian times.
'''
lex_pattern = tag = format = None
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data.
'''
if text is None:
return None
m = self.lex_pattern.match(text)
if not m:
raise EvaluateException('Bad Gregorian: %s' %text, ps.Backtrace(elt))
try:
retval = _dict_to_tuple(m.groupdict())
except ValueError, e:
#raise EvaluateException(str(e))
raise
if self.pyclass is not None:
return self.pyclass(retval)
return retval
def get_formatted_content(self, pyobj):
if type(pyobj) in _floattypes or type(pyobj) in _inttypes:
pyobj = _gmtime(pyobj)
d = {}
pyobj = tuple(pyobj)
if 1 in map(lambda x: x < 0, pyobj[0:6]):
pyobj = map(abs, pyobj)
d['neg'] = '-'
else:
d['neg'] = ''
ms = pyobj[6]
if not ms:
d = { 'Y': pyobj[0], 'M': pyobj[1], 'D': pyobj[2],
'h': pyobj[3], 'm': pyobj[4], 's': pyobj[5], }
return self.format % d
if ms > 999:
raise ValueError, 'milliseconds must be a integer between 0 and 999'
d = { 'Y': pyobj[0], 'M': pyobj[1], 'D': pyobj[2],
'h': pyobj[3], 'm': pyobj[4], 's': pyobj[5], 'ms':ms, }
return self.format_ms % d
class gDateTime(Gregorian):
'''A date and time.
'''
parselist = [ (None,'dateTime') ]
lex_pattern = re.compile('^' r'(?P<neg>-?)' \
'(?P<Y>\d{4,})-' r'(?P<M>\d\d)-' r'(?P<D>\d\d)' 'T' \
r'(?P<h>\d\d):' r'(?P<m>\d\d):' r'(?P<s>\d*(\.\d+)?)' \
r'(?P<tz>(Z|([-+]\d\d:\d\d))?)' '$')
tag, format = 'dateTime', '%(Y)04d-%(M)02d-%(D)02dT%(h)02d:%(m)02d:%(s)02dZ'
format_ms = format[:-1] + '.%(ms)03dZ'
type = (SCHEMA.XSD3, 'dateTime')
class gDate(Gregorian):
'''A date.
'''
parselist = [ (None,'date') ]
lex_pattern = re.compile('^' r'(?P<neg>-?)' \
'(?P<Y>\d{4,})-' r'(?P<M>\d\d)-' r'(?P<D>\d\d)' \
r'(?P<tz>Z|([-+]\d\d:\d\d))?' '$')
tag, format = 'date', '%(Y)04d-%(M)02d-%(D)02dZ'
type = (SCHEMA.XSD3, 'date')
class gYearMonth(Gregorian):
'''A date.
'''
parselist = [ (None,'gYearMonth') ]
lex_pattern = re.compile('^' r'(?P<neg>-?)' \
'(?P<Y>\d{4,})-' r'(?P<M>\d\d)' \
r'(?P<tz>Z|([-+]\d\d:\d\d))?' '$')
tag, format = 'gYearMonth', '%(Y)04d-%(M)02dZ'
type = (SCHEMA.XSD3, 'gYearMonth')
class gYear(Gregorian):
'''A date.
'''
parselist = [ (None,'gYear') ]
lex_pattern = re.compile('^' r'(?P<neg>-?)' \
'(?P<Y>\d{4,})' \
r'(?P<tz>Z|([-+]\d\d:\d\d))?' '$')
tag, format = 'gYear', '%(Y)04dZ'
type = (SCHEMA.XSD3, 'gYear')
class gMonthDay(Gregorian):
'''A gMonthDay.
'''
parselist = [ (None,'gMonthDay') ]
lex_pattern = re.compile('^' r'(?P<neg>-?)' \
r'--(?P<M>\d\d)-' r'(?P<D>\d\d)' \
r'(?P<tz>Z|([-+]\d\d:\d\d))?' '$')
tag, format = 'gMonthDay', '---%(M)02d-%(D)02dZ'
type = (SCHEMA.XSD3, 'gMonthDay')
class gDay(Gregorian):
'''A gDay.
'''
parselist = [ (None,'gDay') ]
lex_pattern = re.compile('^' r'(?P<neg>-?)' \
r'---(?P<D>\d\d)' \
r'(?P<tz>Z|([-+]\d\d:\d\d))?' '$')
tag, format = 'gDay', '---%(D)02dZ'
type = (SCHEMA.XSD3, 'gDay')
class gMonth(Gregorian):
'''A gMonth.
'''
parselist = [ (None,'gMonth') ]
lex_pattern = re.compile('^' r'(?P<neg>-?)' \
r'---(?P<M>\d\d)' \
r'(?P<tz>Z|([-+]\d\d:\d\d))?' '$')
tag, format = 'gMonth', '---%(M)02dZ'
type = (SCHEMA.XSD3, 'gMonth')
class gTime(Gregorian):
'''A time.
'''
parselist = [ (None,'time') ]
lex_pattern = re.compile('^' r'(?P<neg>-?)' \
r'(?P<h>\d\d):' r'(?P<m>\d\d):' r'(?P<s>\d*(\.\d+)?)' \
r'(?P<tz>Z|([-+]\d\d:\d\d))?' '$')
tag, format = 'time', '%(h)02d:%(m)02d:%(s)02dZ'
format_ms = format[:-1] + '.%(ms)03dZ'
type = (SCHEMA.XSD3, 'time')
if __name__ == '__main__': print _copyright | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/TCtimes.py | TCtimes.py |
_copyright = """ZSI: Zolera Soap Infrastructure.
Copyright 2001, Zolera Systems, Inc. All Rights Reserved.
Copyright 2002-2003, Rich Salz. All Rights Reserved.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, and/or
sell copies of the Software, and to permit persons to whom the Software
is furnished to do so, provided that the above copyright notice(s) and
this permission notice appear in all copies of the Software and that
both the above copyright notice(s) and this permission notice appear in
supporting documentation.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS
INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT
OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
OR PERFORMANCE OF THIS SOFTWARE.
Except as contained in this notice, the name of a copyright holder
shall not be used in advertising or otherwise to promote the sale, use
or other dealings in this Software without prior written authorization
of the copyright holder.
Portions are also:
Copyright (c) 2003, The Regents of the University of California,
through Lawrence Berkeley National Laboratory (subject to receipt of
any required approvals from the U.S. Dept. of Energy). All rights
reserved. Redistribution and use in source and binary forms, with or
without modification, are permitted provided that the following
conditions are met:
(1) Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
(2) Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
(3) Neither the name of the University of California, Lawrence Berkeley
National Laboratory, U.S. Dept. of Energy nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
You are under no obligation whatsoever to provide any bug fixes,
patches, or upgrades to the features, functionality or performance of
the source code ("Enhancements") to anyone; however, if you choose to
make your Enhancements available either publicly, or directly to
Lawrence Berkeley National Laboratory, without imposing a separate
written license agreement for such Enhancements, then you hereby grant
the following license: a non-exclusive, royalty-free perpetual license
to install, use, modify, prepare derivative works, incorporate into
other computer software, distribute, and sublicense such Enhancements
or derivative works thereof, in binary and source code form.
For wstools also:
Zope Public License (ZPL) Version 2.0
-----------------------------------------------
This software is Copyright (c) Zope Corporation (tm) and
Contributors. All rights reserved.
This license has been certified as open source. It has also
been designated as GPL compatible by the Free Software
Foundation (FSF).
Redistribution and use in source and binary forms, with or
without modification, are permitted provided that the
following conditions are met:
1. Redistributions in source code must retain the above
copyright notice, this list of conditions, and the following
disclaimer.
2. Redistributions in binary form must reproduce the above
copyright notice, this list of conditions, and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
3. The name Zope Corporation (tm) must not be used to
endorse or promote products derived from this software
without prior written permission from Zope Corporation.
4. The right to distribute this software or to use it for
any purpose does not give you the right to use Servicemarks
(sm) or Trademarks (tm) of Zope Corporation. Use of them is
covered in a separate agreement (see
http://www.zope.com/Marks).
5. If any files are modified, you must cause the modified
files to carry prominent notices stating that you changed
the files and the date of any change.
Disclaimer
THIS SOFTWARE IS PROVIDED BY ZOPE CORPORATION ``AS IS''
AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
NO EVENT SHALL ZOPE CORPORATION OR ITS CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
This software consists of contributions made by Zope
Corporation and many individuals on behalf of Zope
Corporation. Specific attributions are listed in the
accompanying credits file.
"""
##
## Stuff imported from elsewhere.
from xml.dom import Node as _Node
import types as _types
##
## Public constants.
from ZSI.wstools.Namespaces import ZSI_SCHEMA_URI
##
## Not public constants.
_inttypes = [ _types.IntType, _types.LongType ]
_floattypes = [ _types.FloatType ]
_seqtypes = [ _types.TupleType, _types.ListType ]
_stringtypes = [ _types.StringType, _types.UnicodeType ]
##
## Low-level DOM oriented utilities; useful for typecode implementors.
_attrs = lambda E: (E.attributes and E.attributes.values()) or []
_children = lambda E: E.childNodes or []
_child_elements = lambda E: [ n for n in (E.childNodes or [])
if n.nodeType == _Node.ELEMENT_NODE ]
##
## Stuff imported from elsewhere.
from ZSI.wstools.Namespaces import SOAP as _SOAP, SCHEMA as _SCHEMA, XMLNS as _XMLNS
##
## Low-level DOM oriented utilities; useful for typecode implementors.
_find_arraytype = lambda E: E.getAttributeNS(_SOAP.ENC, "arrayType")
_find_encstyle = lambda E: E.getAttributeNS(_SOAP.ENV, "encodingStyle")
try:
from xml.dom import EMPTY_NAMESPACE
_empty_nsuri_list = [ EMPTY_NAMESPACE ]
#if '' not in _empty_nsuri_list: __empty_nsuri_list.append('')
#if None not in _empty_nsuri_list: __empty_nsuri_list.append(None)
except:
_empty_nsuri_list = [ None, '' ]
def _find_attr(E, attr):
for nsuri in _empty_nsuri_list:
try:
v = E.getAttributeNS(nsuri, attr)
if v: return v
except: pass
return None
def _find_attrNS(E, namespaceURI, localName):
'''namespaceURI
localName
'''
try:
v = E.getAttributeNS(namespaceURI, localName)
if v: return v
except: pass
return None
def _find_attrNodeNS(E, namespaceURI, localName):
'''Must grab the attribute Node to distinquish between
an unspecified attribute(None) and one set to empty string("").
namespaceURI
localName
'''
attr = E.getAttributeNodeNS(namespaceURI, localName)
if attr is None: return None
try:
return attr.value
except: pass
return E.getAttributeNS(namespaceURI, localName)
_find_href = lambda E: _find_attr(E, "href")
_find_xsi_attr = lambda E, attr: \
E.getAttributeNS(_SCHEMA.XSI3, attr) \
or E.getAttributeNS(_SCHEMA.XSI1, attr) \
or E.getAttributeNS(_SCHEMA.XSI2, attr)
_find_type = lambda E: _find_xsi_attr(E, "type")
_find_xmlns_prefix = lambda E, attr: E.getAttributeNS(_XMLNS.BASE, attr)
_find_default_namespace = lambda E: E.getAttributeNS(_XMLNS.BASE, None)
#_textprotect = lambda s: s.replace('&', '&').replace('<', '<')
_get_element_nsuri_name = lambda E: (E.namespaceURI, E.localName)
_is_element = lambda E: E.nodeType == _Node.ELEMENT_NODE
def _resolve_prefix(celt, prefix):
'''resolve prefix to a namespaceURI. If None or
empty str, return default namespace or None.
Parameters:
celt -- element node
prefix -- xmlns:prefix, or empty str or None
'''
namespace = None
while _is_element(celt):
if prefix:
namespaceURI = _find_xmlns_prefix(celt, prefix)
else:
namespaceURI = _find_default_namespace(celt)
if namespaceURI: break
celt = celt.parentNode
else:
if prefix:
raise EvaluateException, 'cant resolve xmlns:%s' %prefix
return namespaceURI
def _valid_encoding(elt):
'''Does this node have a valid encoding?
'''
enc = _find_encstyle(elt)
if not enc or enc == _SOAP.ENC: return 1
for e in enc.split():
if e.startswith(_SOAP.ENC):
# XXX Is this correct? Once we find a Sec5 compatible
# XXX encoding, should we check that all the rest are from
# XXX that same base? Perhaps. But since the if test above
# XXX will surely get 99% of the cases, leave it for now.
return 1
return 0
def _backtrace(elt, dom):
'''Return a "backtrace" from the given element to the DOM root,
in XPath syntax.
'''
s = ''
while elt != dom:
name, parent = elt.nodeName, elt.parentNode
if parent is None: break
matches = [ c for c in _child_elements(parent)
if c.nodeName == name ]
if len(matches) == 1:
s = '/' + name + s
else:
i = matches.index(elt) + 1
s = ('/%s[%d]' % (name, i)) + s
elt = parent
return s
def _get_idstr(pyobj):
'''Python 2.3.x generates a FutureWarning for negative IDs, so
we use a different prefix character to ensure uniqueness, and
call abs() to avoid the warning.'''
x = id(pyobj)
if x < 0:
return 'x%x' % abs(x)
return 'o%x' % x
def _get_postvalue_from_absoluteURI(url):
"""Bug [ 1513000 ] POST Request-URI not limited to "abs_path"
Request-URI = "*" | absoluteURI | abs_path | authority
Not a complete solution, but it seems to work with all known
implementations. ValueError thrown if bad uri.
"""
cache = _get_postvalue_from_absoluteURI.cache
path = cache.get(url, '')
if not path:
scheme,authpath = url.split('://')
s = authpath.split('/', 1)
if len(s) == 2: path = '/%s' %s[1]
if len(cache) > _get_postvalue_from_absoluteURI.MAXLEN:cache.clear()
cache[url] = path
return path
_get_postvalue_from_absoluteURI.cache = {}
_get_postvalue_from_absoluteURI.MAXLEN = 20
##
## Exception classes.
class ZSIException(Exception):
'''Base class for all ZSI exceptions.
'''
pass
class ParseException(ZSIException):
'''Exception raised during parsing.
'''
def __init__(self, str, inheader, elt=None, dom=None):
Exception.__init__(self)
self.str, self.inheader, self.trace = str, inheader, None
if elt and dom:
self.trace = _backtrace(elt, dom)
def __str__(self):
if self.trace:
return self.str + '\n[Element trace: ' + self.trace + ']'
return self.str
def __repr__(self):
return "<%s.ParseException %s>" % (__name__, _get_idstr(self))
class EvaluateException(ZSIException):
'''Exception raised during data evaluation (serialization).
'''
def __init__(self, str, trace=None):
Exception.__init__(self)
self.str, self.trace = str, trace
def __str__(self):
if self.trace:
return self.str + '\n[Element trace: ' + self.trace + ']'
return self.str
def __repr__(self):
return "<%s.EvaluateException %s>" % (__name__, _get_idstr(self))
class FaultException(ZSIException):
'''Exception raised when a fault is received.
'''
def __init__(self, fault):
self.fault = fault
def __str__(self):
return str(self.fault)
def __repr__(self):
return "<%s.FaultException %s>" % (__name__, _get_idstr(self))
class WSActionException(ZSIException):
'''Exception raised when WS-Address Action Header is incorrectly
specified when received by client or server.
'''
pass
##
## Importing the rest of ZSI.
import version
def Version():
return version.Version
from writer import SoapWriter
from parse import ParsedSoap
from fault import Fault, \
FaultFromActor, FaultFromException, FaultFromFaultMessage, \
FaultFromNotUnderstood, FaultFromZSIException
import TC
TC.RegisterType(TC.String, minOccurs=0, nillable=False)
TC.RegisterType(TC.URI, minOccurs=0, nillable=False)
TC.RegisterType(TC.Base64String, minOccurs=0, nillable=False)
TC.RegisterType(TC.HexBinaryString, minOccurs=0, nillable=False)
#TC.RegisterType(TC.Integer)
#TC.RegisterType(TC.Decimal)
for pyclass in (TC.IunsignedByte, TC.IunsignedShort, TC.IunsignedInt, TC.IunsignedLong,
TC.Ibyte, TC.Ishort, TC.Iint, TC.Ilong, TC.InegativeInteger,
TC.InonPositiveInteger, TC.InonNegativeInteger, TC.IpositiveInteger,
TC.Iinteger, TC.FPfloat, TC.FPdouble, ):
TC.RegisterType(pyclass, minOccurs=0, nillable=False)
TC.RegisterType(TC.Boolean, minOccurs=0, nillable=False)
TC.RegisterType(TC.Duration, minOccurs=0, nillable=False)
TC.RegisterType(TC.gDateTime, minOccurs=0, nillable=False)
TC.RegisterType(TC.gDate, minOccurs=0, nillable=False)
TC.RegisterType(TC.gYearMonth, minOccurs=0, nillable=False)
TC.RegisterType(TC.gYear, minOccurs=0, nillable=False)
TC.RegisterType(TC.gMonthDay, minOccurs=0, nillable=False)
TC.RegisterType(TC.gDay, minOccurs=0, nillable=False)
TC.RegisterType(TC.gTime, minOccurs=0, nillable=False)
TC.RegisterType(TC.Apache.Map, minOccurs=0, nillable=False)
##
## Register Wrappers for builtin types.
## TC.AnyElement wraps builtins so element name information can be saved
##
import schema
for i in [int,float,str,tuple,list,unicode]:
schema._GetPyobjWrapper.RegisterBuiltin(i)
## Load up Wrappers for builtin types
schema.RegisterAnyElement()
#try:
# from ServiceProxy import *
#except:
# pass
if __name__ == '__main__': print _copyright | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/__init__.py | __init__.py |
import types, os, sys
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from ZSI import *
from ZSI import _child_elements, _copyright, _seqtypes, _find_arraytype, _find_type, resolvers
from ZSI.auth import _auth_tc, AUTH, ClientBinding
# Client binding information is stored in a global. We provide an accessor
# in case later on it's not.
_client_binding = None
def GetClientBinding():
'''Return the client binding object.
'''
return _client_binding
gettypecode = lambda mod,e: getattr(mod, str(e.localName)).typecode
def _Dispatch(ps, modules, SendResponse, SendFault, nsdict={}, typesmodule=None,
gettypecode=gettypecode, rpc=False, docstyle=False, **kw):
'''Find a handler for the SOAP request in ps; search modules.
Call SendResponse or SendFault to send the reply back, appropriately.
Behaviors:
default -- Call "handler" method with pyobj representation of body root, and return
a self-describing request (w/typecode). Parsing done via a typecode from
typesmodule, or Any.
docstyle -- Call "handler" method with ParsedSoap instance and parse result with an
XML typecode (DOM). Behavior, wrap result in a body_root "Response" appended message.
rpc -- Specify RPC wrapper of result. Behavior, ignore body root (RPC Wrapper)
of request, parse all "parts" of message via individual typecodes. Expect
the handler to return the parts of the message, whether it is a dict, single instance,
or a list try to serialize it as a Struct but if this is not possible put it in an Array.
Parsing done via a typecode from typesmodule, or Any.
'''
global _client_binding
try:
what = str(ps.body_root.localName)
# See what modules have the element name.
if modules is None:
modules = ( sys.modules['__main__'], )
handlers = [ getattr(m, what) for m in modules if hasattr(m, what) ]
if len(handlers) == 0:
raise TypeError("Unknown method " + what)
# Of those modules, see who's callable.
handlers = [ h for h in handlers if callable(h) ]
if len(handlers) == 0:
raise TypeError("Unimplemented method " + what)
if len(handlers) > 1:
raise TypeError("Multiple implementations found: " + `handlers`)
handler = handlers[0]
_client_binding = ClientBinding(ps)
if docstyle:
result = handler(ps.body_root)
tc = TC.XML(aslist=1, pname=what+'Response')
elif not rpc:
try:
tc = gettypecode(typesmodule, ps.body_root)
except Exception:
tc = TC.Any()
try:
arg = tc.parse(ps.body_root, ps)
except EvaluateException, ex:
SendFault(FaultFromZSIException(ex), **kw)
return
try:
result = handler(*arg)
except Exception,ex:
SendFault(FaultFromZSIException(ex), **kw)
try:
tc = result.typecode
except AttributeError,ex:
SendFault(FaultFromZSIException(ex), **kw)
elif typesmodule is not None:
kwargs = {}
for e in _child_elements(ps.body_root):
try:
tc = gettypecode(typesmodule, e)
except Exception:
tc = TC.Any()
try:
kwargs[str(e.localName)] = tc.parse(e, ps)
except EvaluateException, ex:
SendFault(FaultFromZSIException(ex), **kw)
return
result = handler(**kwargs)
aslist = False
# make sure data is wrapped, try to make this a Struct
if type(result) in _seqtypes:
for o in result:
aslist = hasattr(result, 'typecode')
if aslist: break
elif type(result) is not dict:
aslist = not hasattr(result, 'typecode')
result = (result,)
tc = TC.Any(pname=what+'Response', aslist=aslist)
else:
# if this is an Array, call handler with list
# if this is an Struct, call handler with dict
tp = _find_type(ps.body_root)
isarray = ((type(tp) in (tuple,list) and tp[1] == 'Array') or _find_arraytype(ps.body_root))
data = _child_elements(ps.body_root)
tc = TC.Any()
if isarray and len(data) == 0:
result = handler()
elif isarray:
try: arg = [ tc.parse(e, ps) for e in data ]
except EvaluateException, e:
#SendFault(FaultFromZSIException(e), **kw)
SendFault(RuntimeError("THIS IS AN ARRAY: %s" %isarray))
return
result = handler(*arg)
else:
try: kwarg = dict([ (str(e.localName),tc.parse(e, ps)) for e in data ])
except EvaluateException, e:
SendFault(FaultFromZSIException(e), **kw)
return
result = handler(**kwarg)
# reponse typecode
#tc = getattr(result, 'typecode', TC.Any(pname=what+'Response'))
tc = TC.Any(pname=what+'Response')
sw = SoapWriter(nsdict=nsdict)
sw.serialize(result, tc)
return SendResponse(str(sw), **kw)
except Fault, e:
return SendFault(e, **kw)
except Exception, e:
# Something went wrong, send a fault.
return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)
def _ModPythonSendXML(text, code=200, **kw):
req = kw['request']
req.content_type = 'text/xml'
req.content_length = len(text)
req.send_http_header()
req.write(text)
def _ModPythonSendFault(f, **kw):
_ModPythonSendXML(f.AsSOAP(), 500, **kw)
def _JonPySendFault(f, **kw):
_JonPySendXML(f.AsSOAP(), 500, **kw)
def _JonPySendXML(text, code=200, **kw):
req = kw['request']
req.set_header("Content-Type", 'text/xml; charset="utf-8"')
req.set_header("Content-Length", str(len(text)))
req.write(text)
def _CGISendXML(text, code=200, **kw):
print 'Status: %d' % code
print 'Content-Type: text/xml; charset="utf-8"'
print 'Content-Length: %d' % len(text)
print ''
print text
def _CGISendFault(f, **kw):
_CGISendXML(f.AsSOAP(), 500, **kw)
class SOAPRequestHandler(BaseHTTPRequestHandler):
'''SOAP handler.
'''
server_version = 'ZSI/1.1 ' + BaseHTTPRequestHandler.server_version
def send_xml(self, text, code=200):
'''Send some XML.
'''
self.send_response(code)
self.send_header('Content-type', 'text/xml; charset="utf-8"')
self.send_header('Content-Length', str(len(text)))
self.end_headers()
self.wfile.write(text)
self.wfile.flush()
def send_fault(self, f, code=500):
'''Send a fault.
'''
self.send_xml(f.AsSOAP(), code)
def do_POST(self):
'''The POST command.
'''
try:
ct = self.headers['content-type']
if ct.startswith('multipart/'):
cid = resolvers.MIMEResolver(ct, self.rfile)
xml = cid.GetSOAPPart()
ps = ParsedSoap(xml, resolver=cid.Resolve)
else:
length = int(self.headers['content-length'])
ps = ParsedSoap(self.rfile.read(length))
except ParseException, e:
self.send_fault(FaultFromZSIException(e))
return
except Exception, e:
# Faulted while processing; assume it's in the header.
self.send_fault(FaultFromException(e, 1, sys.exc_info()[2]))
return
_Dispatch(ps, self.server.modules, self.send_xml, self.send_fault,
docstyle=self.server.docstyle, nsdict=self.server.nsdict,
typesmodule=self.server.typesmodule, rpc=self.server.rpc)
def AsServer(port=80, modules=None, docstyle=False, nsdict={}, typesmodule=None,
rpc=False, addr=''):
address = (addr, port)
httpd = HTTPServer(address, SOAPRequestHandler)
httpd.modules = modules
httpd.docstyle = docstyle
httpd.nsdict = nsdict
httpd.typesmodule = typesmodule
httpd.rpc = rpc
httpd.serve_forever()
def AsCGI(nsdict={}, typesmodule=None, rpc=False, modules=None):
'''Dispatch within a CGI script.
'''
if os.environ.get('REQUEST_METHOD') != 'POST':
_CGISendFault(Fault(Fault.Client, 'Must use POST'))
return
ct = os.environ['CONTENT_TYPE']
try:
if ct.startswith('multipart/'):
cid = resolvers.MIMEResolver(ct, sys.stdin)
xml = cid.GetSOAPPart()
ps = ParsedSoap(xml, resolver=cid.Resolve)
else:
length = int(os.environ['CONTENT_LENGTH'])
ps = ParsedSoap(sys.stdin.read(length))
except ParseException, e:
_CGISendFault(FaultFromZSIException(e))
return
_Dispatch(ps, modules, _CGISendXML, _CGISendFault, nsdict=nsdict,
typesmodule=typesmodule, rpc=rpc)
def AsHandler(request=None, modules=None, **kw):
'''Dispatch from within ModPython.'''
ps = ParsedSoap(request)
kw['request'] = request
_Dispatch(ps, modules, _ModPythonSendXML, _ModPythonSendFault, **kw)
def AsJonPy(request=None, modules=None, **kw):
'''Dispatch within a jonpy CGI/FastCGI script.
'''
kw['request'] = request
if request.environ.get('REQUEST_METHOD') != 'POST':
_JonPySendFault(Fault(Fault.Client, 'Must use POST'), **kw)
return
ct = request.environ['CONTENT_TYPE']
try:
if ct.startswith('multipart/'):
cid = resolvers.MIMEResolver(ct, request.stdin)
xml = cid.GetSOAPPart()
ps = ParsedSoap(xml, resolver=cid.Resolve)
else:
length = int(request.environ['CONTENT_LENGTH'])
ps = ParsedSoap(request.stdin.read(length))
except ParseException, e:
_JonPySendFault(FaultFromZSIException(e), **kw)
return
_Dispatch(ps, modules, _JonPySendXML, _JonPySendFault, **kw)
if __name__ == '__main__': print _copyright | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/dispatch.py | dispatch.py |
from ZSI import _copyright, _children, _child_elements, \
_inttypes, _stringtypes, _seqtypes, _find_arraytype, _find_href, \
_find_type, _find_xmlns_prefix, _get_idstr, EvaluateException, \
ParseException
from TC import _get_element_nsuri_name, \
_get_xsitype, TypeCode, Any, AnyElement, AnyType, \
Nilled, UNBOUNDED
from schema import ElementDeclaration, TypeDefinition, \
_get_substitute_element, _get_type_definition
from ZSI.wstools.Namespaces import SCHEMA, SOAP
from ZSI.wstools.Utility import SplitQName
from ZSI.wstools.logging import getLogger as _GetLogger
import re, types
_find_arrayoffset = lambda E: E.getAttributeNS(SOAP.ENC, "offset")
_find_arrayposition = lambda E: E.getAttributeNS(SOAP.ENC, "position")
_offset_pat = re.compile(r'\[[0-9]+\]')
_position_pat = _offset_pat
def _check_typecode_list(ofwhat, tcname):
'''Check a list of typecodes for compliance with Struct
requirements.'''
for o in ofwhat:
if callable(o): #skip if _Mirage
continue
if not isinstance(o, TypeCode):
raise TypeError(
tcname + ' ofwhat outside the TypeCode hierarchy, ' +
str(o.__class__))
if o.pname is None and not isinstance(o, AnyElement):
raise TypeError(tcname + ' element ' + str(o) + ' has no name')
def _get_type_or_substitute(typecode, pyobj, sw, elt):
'''return typecode or substitute type for wildcard or
derived type. For serialization only.
'''
sub = getattr(pyobj, 'typecode', typecode)
if sub is typecode or sub is None:
return typecode
# Element WildCard
if isinstance(typecode, AnyElement):
return sub
# Global Element Declaration
if isinstance(sub, ElementDeclaration):
if (typecode.nspname,typecode.pname) == (sub.nspname,sub.pname):
raise TypeError(\
'bad usage, failed to serialize element reference (%s, %s), in: %s' %
(typecode.nspname, typecode.pname, sw.Backtrace(elt),))
raise TypeError(\
'failed to serialize (%s, %s) illegal sub GED (%s,%s): %s' %
(typecode.nspname, typecode.pname, sub.nspname, sub.pname,
sw.Backtrace(elt),))
# Local Element
if not isinstance(typecode, AnyType) and not isinstance(sub, typecode.__class__):
raise TypeError(\
'failed to serialize substitute %s for %s, not derivation: %s' %
(sub, typecode, sw.Backtrace(elt),))
sub.nspname = typecode.nspname
sub.pname = typecode.pname
sub.aname = typecode.aname
sub.minOccurs = 1
sub.maxOccurs = 1
return sub
def _get_any_instances(ofwhat, d):
'''Run thru list ofwhat.anames and find unmatched keys in value
dictionary d. Assume these are element wildcard instances.
'''
any_keys = []
anames = map(lambda what: what.aname, ofwhat)
for aname,pyobj in d.items():
if isinstance(pyobj, AnyType) or aname in anames or pyobj is None:
continue
any_keys.append(aname)
return any_keys
class ComplexType(TypeCode):
'''Represents an element of complexType, potentially containing other
elements.
'''
logger = _GetLogger('ZSI.TCcompound.ComplexType')
def __init__(self, pyclass, ofwhat, pname=None, inorder=False, inline=False,
mutable=True, mixed=False, mixed_aname='_text', **kw):
'''pyclass -- the Python class to hold the fields
ofwhat -- a list of fields to be in the complexType
inorder -- fields must be in exact order or not
inline -- don't href/id when serializing
mutable -- object could change between multiple serializations
type -- the (URI,localname) of the datatype
mixed -- mixed content model? True/False
mixed_aname -- if mixed is True, specify text content here. Default _text
'''
TypeCode.__init__(self, pname, pyclass=pyclass, **kw)
self.inorder = inorder
self.inline = inline
self.mutable = mutable
self.mixed = mixed
self.mixed_aname = None
if mixed is True:
self.mixed_aname = mixed_aname
if self.mutable is True: self.inline = True
self.type = kw.get('type') or _get_xsitype(self)
t = type(ofwhat)
if t not in _seqtypes:
raise TypeError(
'Struct ofwhat must be list or sequence, not ' + str(t))
self.ofwhat = tuple(ofwhat)
if TypeCode.typechecks:
# XXX Not sure how to determine if new-style class..
if self.pyclass is not None and \
type(self.pyclass) is not types.ClassType and not isinstance(self.pyclass, object):
raise TypeError('pyclass must be None or an old-style/new-style class, not ' +
str(type(self.pyclass)))
_check_typecode_list(self.ofwhat, 'ComplexType')
def parse(self, elt, ps):
debug = self.logger.debugOn()
debug and self.logger.debug('parse')
xtype = self.checkname(elt, ps)
if self.type and xtype not in [ self.type, (None,None) ]:
if not isinstance(self, TypeDefinition):
raise EvaluateException(\
'ComplexType for %s has wrong type(%s), looking for %s' %
(self.pname, self.checktype(elt,ps), self.type),
ps.Backtrace(elt))
else:
#TODO: mabye change MRO to handle this
debug and self.logger.debug('delegate to substitute type')
what = TypeDefinition.getSubstituteType(self, elt, ps)
return what.parse(elt, ps)
href = _find_href(elt)
if href:
if _children(elt):
raise EvaluateException('Struct has content and HREF',
ps.Backtrace(elt))
elt = ps.FindLocalHREF(href, elt)
c = _child_elements(elt)
count = len(c)
if self.nilled(elt, ps): return Nilled
# Create the object.
v = {}
# parse all attributes contained in attribute_typecode_dict (user-defined attributes),
# the values (if not None) will be keyed in self.attributes dictionary.
attributes = self.parse_attributes(elt, ps)
if attributes:
v[self.attrs_aname] = attributes
#MIXED
if self.mixed is True:
v[self.mixed_aname] = self.simple_value(elt,ps, mixed=True)
# Clone list of kids (we null it out as we process)
c, crange = c[:], range(len(c))
# Loop over all items we're expecting
if debug:
self.logger.debug("ofwhat: %s",str(self.ofwhat))
any = None
for i,what in [ (i, self.ofwhat[i]) for i in range(len(self.ofwhat)) ]:
# retrieve typecode if it is hidden
if callable(what): what = what()
# Loop over all available kids
if debug:
self.logger.debug("what: (%s,%s)", what.nspname, what.pname)
for j,c_elt in [ (j, c[j]) for j in crange if c[j] ]:
if debug:
self.logger.debug("child node: (%s,%s)", c_elt.namespaceURI,
c_elt.tagName)
if what.name_match(c_elt):
# Parse value, and mark this one done.
try:
value = what.parse(c_elt, ps)
except EvaluateException, e:
#what = _get_substitute_element(c_elt, what)
#value = what.parse(c_elt, ps)
raise
if what.maxOccurs > 1:
if v.has_key(what.aname):
v[what.aname].append(value)
else:
v[what.aname] = [value]
c[j] = None
continue
else:
v[what.aname] = value
c[j] = None
break
else:
if debug:
self.logger.debug("no element (%s,%s)",
what.nspname, what.pname)
# No match; if it was supposed to be here, that's an error.
if self.inorder is True and i == j:
raise EvaluateException('Out of order complexType',
ps.Backtrace(c_elt))
else:
# only supporting 1 <any> declaration in content.
if isinstance(what,AnyElement):
any = what
elif hasattr(what, 'default'):
v[what.aname] = what.default
elif what.minOccurs > 0 and not v.has_key(what.aname):
raise EvaluateException('Element "' + what.aname + \
'" missing from complexType', ps.Backtrace(elt))
# Look for wildcards and unprocessed children
# XXX Stick all this stuff in "any", hope for no collisions
if any is not None:
occurs = 0
v[any.aname] = []
for j,c_elt in [ (j, c[j]) for j in crange if c[j] ]:
value = any.parse(c_elt, ps)
if any.maxOccurs == UNBOUNDED or any.maxOccurs > 1:
v[any.aname].append(value)
else:
v[any.aname] = value
occurs += 1
# No such thing as nillable <any>
if any.maxOccurs == 1 and occurs == 0:
v[any.aname] = None
elif occurs < any.minOccurs or (any.maxOccurs!=UNBOUNDED and any.maxOccurs<occurs):
raise EvaluateException('occurances of <any> elements(#%d) bound by (%d,%s)' %(
occurs, any.minOccurs,str(any.maxOccurs)), ps.Backtrace(elt))
if not self.pyclass:
return v
# type definition must be informed of element tag (nspname,pname),
# element declaration is initialized with a tag.
try:
pyobj = self.pyclass()
except Exception, e:
raise TypeError("Constructing element (%s,%s) with pyclass(%s), %s" \
%(self.nspname, self.pname, self.pyclass.__name__, str(e)))
for key in v.keys():
setattr(pyobj, key, v[key])
return pyobj
def serialize(self, elt, sw, pyobj, inline=False, name=None, **kw):
if inline or self.inline:
self.cb(elt, sw, pyobj, name=name, **kw)
else:
objid = _get_idstr(pyobj)
ns,n = self.get_name(name, objid)
el = elt.createAppendElement(ns, n)
el.setAttributeNS(None, 'href', "#%s" %objid)
sw.AddCallback(self.cb, elt, sw, pyobj)
def cb(self, elt, sw, pyobj, name=None, **kw):
debug = self.logger.debugOn()
if debug:
self.logger.debug("cb: %s" %str(self.ofwhat))
objid = _get_idstr(pyobj)
ns,n = self.get_name(name, objid)
if pyobj is None:
if self.nillable is True:
elem = elt.createAppendElement(ns, n)
self.serialize_as_nil(elem)
return
raise EvaluateException, 'element(%s,%s) is not nillable(%s)' %(
self.nspname,self.pname,self.nillable)
if self.mutable is False and sw.Known(pyobj):
return
if debug:
self.logger.debug("element: (%s, %s)", str(ns), n)
if n is not None:
elem = elt.createAppendElement(ns, n)
self.set_attributes(elem, pyobj)
if kw.get('typed', self.typed) is True:
self.set_attribute_xsi_type(elem)
#MIXED For now just stick it in front.
if self.mixed is True and self.mixed_aname is not None:
if hasattr(pyobj, self.mixed_aname):
textContent = getattr(pyobj, self.mixed_aname)
if hasattr(textContent, 'typecode'):
textContent.typecode.serialize_text_node(elem, sw, textContent)
elif type(textContent) in _stringtypes:
if debug:
self.logger.debug("mixed text content:\n\t%s",
textContent)
elem.createAppendTextNode(textContent)
else:
raise EvaluateException('mixed test content in element (%s,%s) must be a string type' %(
self.nspname,self.pname), sw.Backtrace(elt))
else:
if debug:
self.logger.debug("mixed NO text content in %s",
self.mixed_aname)
else:
#For information items w/o tagNames
# ie. model groups,SOAP-ENC:Header
elem = elt
if self.inline:
pass
elif not self.inline and self.unique:
raise EvaluateException('Not inline, but unique makes no sense. No href/id.',
sw.Backtrace(elt))
elif n is not None:
self.set_attribute_id(elem, objid)
if self.pyclass and type(self.pyclass) is type:
f = lambda attr: getattr(pyobj, attr, None)
elif self.pyclass:
d = pyobj.__dict__
f = lambda attr: d.get(attr)
else:
d = pyobj
f = lambda attr: pyobj.get(attr)
if TypeCode.typechecks and type(d) != types.DictType:
raise TypeError("Classless struct didn't get dictionary")
indx, lenofwhat = 0, len(self.ofwhat)
if debug:
self.logger.debug('element declaration (%s,%s)', self.nspname,
self.pname)
if self.type:
self.logger.debug('xsi:type definition (%s,%s)', self.type[0],
self.type[1])
else:
self.logger.warning('NO xsi:type')
while indx < lenofwhat:
occurs = 0
what = self.ofwhat[indx]
# retrieve typecode if hidden
if callable(what): what = what()
if debug:
self.logger.debug('serialize what -- %s',
what.__class__.__name__)
# No way to order <any> instances, so just grab any unmatched
# anames and serialize them. Only support one <any> in all content.
# Must be self-describing instances
# Regular handling of declared elements
aname = what.aname
v = f(aname)
indx += 1
if what.minOccurs == 0 and v is None:
continue
# Default to typecode, if self-describing instance, and check
# to make sure it is derived from what.
whatTC = what
if whatTC.maxOccurs > 1 and v is not None:
if type(v) not in _seqtypes:
raise EvaluateException('pyobj (%s,%s), aname "%s": maxOccurs %s, expecting a %s' %(
self.nspname,self.pname,what.aname,whatTC.maxOccurs,_seqtypes),
sw.Backtrace(elt))
for v2 in v:
occurs += 1
if occurs > whatTC.maxOccurs:
raise EvaluateException('occurances (%d) exceeded maxOccurs(%d) for <%s>' %(
occurs, whatTC.maxOccurs, what.pname),
sw.Backtrace(elt))
what = _get_type_or_substitute(whatTC, v2, sw, elt)
if debug and what is not whatTC:
self.logger.debug('substitute derived type: %s' %
what.__class__)
what.serialize(elem, sw, v2, **kw)
# try:
# what.serialize(elem, sw, v2, **kw)
# except Exception, e:
# raise EvaluateException('Serializing %s.%s, %s %s' %
# (n, whatTC.aname or '?', e.__class__.__name__, str(e)))
if occurs < whatTC.minOccurs:
raise EvaluateException(\
'occurances(%d) less than minOccurs(%d) for <%s>' %
(occurs, whatTC.minOccurs, what.pname), sw.Backtrace(elt))
continue
if v is not None or what.nillable is True:
what = _get_type_or_substitute(whatTC, v, sw, elt)
if debug and what is not whatTC:
self.logger.debug('substitute derived type: %s' %
what.__class__)
what.serialize(elem, sw, v, **kw)
# try:
# what.serialize(elem, sw, v, **kw)
# except (ParseException, EvaluateException), e:
# raise
# except Exception, e:
# raise EvaluateException('Serializing %s.%s, %s %s' %
# (n, whatTC.aname or '?', e.__class__.__name__, str(e)),
# sw.Backtrace(elt))
continue
raise EvaluateException('Got None for nillable(%s), minOccurs(%d) element (%s,%s), %s' %
(what.nillable, what.minOccurs, what.nspname, what.pname, elem),
sw.Backtrace(elt))
def setDerivedTypeContents(self, extensions=None, restrictions=None):
"""For derived types set appropriate parameter and
"""
if extensions:
ofwhat = list(self.ofwhat)
if type(extensions) in _seqtypes:
ofwhat += list(extensions)
else:
ofwhat.append(extensions)
elif restrictions:
if type(restrictions) in _seqtypes:
ofwhat = restrictions
else:
ofwhat = (restrictions,)
else:
return
self.ofwhat = tuple(ofwhat)
self.lenofwhat = len(self.ofwhat)
class Struct(ComplexType):
'''Struct is a complex type for accessors identified by name.
Constraint: No element may have the same name as any other,
nor may any element have a maxOccurs > 1.
<xs:group name="Struct" >
<xs:sequence>
<xs:any namespace="##any" minOccurs="0" maxOccurs="unbounded" processContents="lax" />
</xs:sequence>
</xs:group>
<xs:complexType name="Struct" >
<xs:group ref="tns:Struct" minOccurs="0" />
<xs:attributeGroup ref="tns:commonAttributes"/>
</xs:complexType>
'''
logger = _GetLogger('ZSI.TCcompound.Struct')
def __init__(self, pyclass, ofwhat, pname=None, inorder=False, inline=False,
mutable=True, **kw):
'''pyclass -- the Python class to hold the fields
ofwhat -- a list of fields to be in the struct
inorder -- fields must be in exact order or not
inline -- don't href/id when serializing
mutable -- object could change between multiple serializations
'''
ComplexType.__init__(self, pyclass, ofwhat, pname=pname,
inorder=inorder, inline=inline, mutable=mutable,
**kw
)
# Check Constraints
whats = map(lambda what: (what.nspname,what.pname), self.ofwhat)
for idx in range(len(self.ofwhat)):
what = self.ofwhat[idx]
key = (what.nspname,what.pname)
if not isinstance(what, AnyElement) and what.maxOccurs > 1:
raise TypeError,\
'Constraint: no element can have a maxOccurs>1'
if key in whats[idx+1:]:
raise TypeError,\
'Constraint: No element may have the same name as any other'
class Array(TypeCode):
'''An array.
atype -- arrayType, (namespace,ncname)
mutable -- object could change between multiple serializations
undeclared -- do not serialize/parse arrayType attribute.
'''
logger = _GetLogger('ZSI.TCcompound.Array')
def __init__(self, atype, ofwhat, pname=None, dimensions=1, fill=None,
sparse=False, mutable=False, size=None, nooffset=0, undeclared=False,
childnames=None, **kw):
TypeCode.__init__(self, pname, **kw)
self.dimensions = dimensions
self.atype = atype
if undeclared is False and self.atype[1].endswith(']') is False:
self.atype = (self.atype[0], '%s[]' %self.atype[1])
# Support multiple dimensions
if self.dimensions != 1:
raise TypeError("Only single-dimensioned arrays supported")
self.fill = fill
self.sparse = sparse
#if self.sparse: ofwhat.minOccurs = 0
self.mutable = mutable
self.size = size
self.nooffset = nooffset
self.undeclared = undeclared
self.childnames = childnames
if self.size:
t = type(self.size)
if t in _inttypes:
self.size = (self.size,)
elif t in _seqtypes:
self.size = tuple(self.size)
elif TypeCode.typechecks:
raise TypeError('Size must be integer or list, not ' + str(t))
if TypeCode.typechecks:
if self.undeclared is False and type(atype) not in _seqtypes and len(atype) == 2:
raise TypeError("Array type must be a sequence of len 2.")
t = type(ofwhat)
if not isinstance(ofwhat, TypeCode):
raise TypeError(
'Array ofwhat outside the TypeCode hierarchy, ' +
str(ofwhat.__class__))
if self.size:
if len(self.size) != self.dimensions:
raise TypeError('Array dimension/size mismatch')
for s in self.size:
if type(s) not in _inttypes:
raise TypeError('Array size "' + str(s) +
'" is not an integer.')
self.ofwhat = ofwhat
def parse_offset(self, elt, ps):
o = _find_arrayoffset(elt)
if not o: return 0
if not _offset_pat.match(o):
raise EvaluateException('Bad offset "' + o + '"',
ps.Backtrace(elt))
return int(o[1:-1])
def parse_position(self, elt, ps):
o = _find_arrayposition(elt)
if not o: return None
if o.find(','):
raise EvaluateException('Sorry, no multi-dimensional arrays',
ps.Backtrace(elt))
if not _position_pat.match(o):
raise EvaluateException('Bad array position "' + o + '"',
ps.Backtrace(elt))
return int(o[-1:1])
def parse(self, elt, ps):
href = _find_href(elt)
if href:
if _children(elt):
raise EvaluateException('Array has content and HREF',
ps.Backtrace(elt))
elt = ps.FindLocalHREF(href, elt)
if self.nilled(elt, ps): return Nilled
if not _find_arraytype(elt) and self.undeclared is False:
raise EvaluateException('Array expected', ps.Backtrace(elt))
t = _find_type(elt)
if t:
pass # XXX should check the type, but parsing that is hairy.
offset = self.parse_offset(elt, ps)
v, vlen = [], 0
if offset and not self.sparse:
while vlen < offset:
vlen += 1
v.append(self.fill)
for c in _child_elements(elt):
item = self.ofwhat.parse(c, ps)
position = self.parse_position(c, ps) or offset
if self.sparse:
v.append((position, item))
else:
while offset < position:
offset += 1
v.append(self.fill)
v.append(item)
offset += 1
return v
def serialize(self, elt, sw, pyobj, name=None, childnames=None, **kw):
debug = self.logger.debugOn()
if debug:
self.logger.debug("serialize: %r" %pyobj)
if self.mutable is False and sw.Known(pyobj): return
objid = _get_idstr(pyobj)
ns,n = self.get_name(name, objid)
el = elt.createAppendElement(ns, n)
# nillable
if self.nillable is True and pyobj is None:
self.serialize_as_nil(el)
return None
# other attributes
self.set_attributes(el, pyobj)
# soap href attribute
unique = self.unique or kw.get('unique', False)
if unique is False and sw.Known(pyobj):
self.set_attribute_href(el, objid)
return None
# xsi:type attribute
if kw.get('typed', self.typed) is True:
self.set_attribute_xsi_type(el, **kw)
# soap id attribute
if self.unique is False:
self.set_attribute_id(el, objid)
offset = 0
if self.sparse is False and self.nooffset is False:
offset, end = 0, len(pyobj)
while offset < end and pyobj[offset] == self.fill:
offset += 1
if offset:
el.setAttributeNS(SOAP.ENC, 'offset', '[%d]' %offset)
if self.undeclared is False:
el.setAttributeNS(SOAP.ENC, 'arrayType',
'%s:%s' %(el.getPrefix(self.atype[0]), self.atype[1])
)
if debug:
self.logger.debug("ofwhat: %r" %self.ofwhat)
d = {}
kn = childnames or self.childnames
if kn:
d['name'] = kn
elif not self.ofwhat.aname:
d['name'] = 'element'
if self.sparse is False:
for e in pyobj[offset:]: self.ofwhat.serialize(el, sw, e, **d)
else:
position = 0
for pos, v in pyobj:
if pos != position:
el.setAttributeNS(SOAP.ENC, 'position', '[%d]' %pos)
position = pos
self.ofwhat.serialize(el, sw, v, **d)
position += 1
if __name__ == '__main__': print _copyright | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/TCcompound.py | TCcompound.py |
# contains text container classes for new generation generator
# $Id: containers.py 1276 2006-10-23 23:18:07Z boverhof $
import types
from utility import StringWriter, TextProtect, TextProtectAttributeName,\
GetPartsSubNames
from utility import NamespaceAliasDict as NAD, NCName_to_ClassName as NC_to_CN
import ZSI
from ZSI.TC import _is_xsd_or_soap_ns
from ZSI.wstools import XMLSchema, WSDLTools
from ZSI.wstools.Namespaces import SCHEMA, SOAP, WSDL
from ZSI.wstools.logging import getLogger as _GetLogger
from ZSI.typeinterpreter import BaseTypeInterpreter
from ZSI.generate import WSISpec, WSInteropError, Wsdl2PythonError,\
WsdlGeneratorError, WSDLFormatError
ID1 = ' '
ID2 = 2*ID1
ID3 = 3*ID1
ID4 = 4*ID1
ID5 = 5*ID1
ID6 = 6*ID1
KW = {'ID1':ID1, 'ID2':ID2, 'ID3':ID3,'ID4':ID4, 'ID5':ID5, 'ID6':ID6,}
DEC = '_Dec'
DEF = '_Def'
"""
type_class_name -- function to return the name formatted as a type class.
element_class_name -- function to return the name formatted as an element class.
"""
type_class_name = lambda n: '%s%s' %(NC_to_CN(n), DEF)
element_class_name = lambda n: '%s%s' %(NC_to_CN(n), DEC)
def IsRPC(item):
"""item -- OperationBinding instance.
"""
if not isinstance(item, WSDLTools.OperationBinding):
raise TypeError, 'IsRPC takes 1 argument of type WSDLTools.OperationBinding'
soapbinding = item.getBinding().findBinding(WSDLTools.SoapBinding)
sob = item.findBinding(WSDLTools.SoapOperationBinding)
style = soapbinding.style
if sob is not None:
style = sob.style or soapbinding.style
return style == 'rpc'
def IsLiteral(item):
"""item -- MessageRoleBinding instance.
"""
if not isinstance(item, WSDLTools.MessageRoleBinding):
raise TypeError, 'IsLiteral takes 1 argument of type WSDLTools.MessageRoleBinding'
sbb = None
if item.type == 'input' or item.type == 'output':
sbb = item.findBinding(WSDLTools.SoapBodyBinding)
if sbb is None:
raise ValueError, 'Missing soap:body binding.'
return sbb.use == 'literal'
def SetTypeNameFunc(func):
global type_class_name
type_class_name = func
def SetElementNameFunc(func):
global element_class_name
element_class_name = func
def GetClassNameFromSchemaItem(item,do_extended=False):
'''
'''
assert isinstance(item, XMLSchema.XMLSchemaComponent), 'must be a schema item.'
alias = NAD.getAlias(item.getTargetNamespace())
if item.isDefinition() is True:
return '%s.%s' %(alias, NC_to_CN('%s' %type_class_name(item.getAttributeName())))
return None
def FromMessageGetSimpleElementDeclaration(message):
'''If message consists of one part with an element attribute,
and this element is a simpleType return a string representing
the python type, else return None.
'''
assert isinstance(message, WSDLTools.Message), 'expecting WSDLTools.Message'
if len(message.parts) == 1 and message.parts[0].element is not None:
part = message.parts[0]
nsuri,name = part.element
wsdl = message.getWSDL()
types = wsdl.types
if types.has_key(nsuri) and types[nsuri].elements.has_key(name):
e = types[nsuri].elements[name]
if isinstance(e, XMLSchema.ElementDeclaration) is True and e.getAttribute('type'):
typ = e.getAttribute('type')
bt = BaseTypeInterpreter()
ptype = bt.get_pythontype(typ[1], typ[0])
return ptype
return None
class AttributeMixIn:
'''for containers that can declare attributes.
Class Attributes:
attribute_typecode -- typecode attribute name typecode dict
built_in_refs -- attribute references that point to built-in
types. Skip resolving them into attribute declarations.
'''
attribute_typecode = 'self.attribute_typecode_dict'
built_in_refs = [(SOAP.ENC, 'arrayType'),]
def _setAttributes(self, attributes):
'''parameters
attributes -- a flat list of all attributes,
from this list all items in attribute_typecode_dict will
be generated into attrComponents.
returns a list of strings representing the attribute_typecode_dict.
'''
atd = self.attribute_typecode
atd_list = formatted_attribute_list = []
if not attributes:
return formatted_attribute_list
atd_list.append('# attribute handling code')
for a in attributes:
if a.isWildCard() and a.isDeclaration():
atd_list.append(\
'%s[("%s","anyAttribute")] = ZSI.TC.AnyElement()'\
% (atd, SCHEMA.XSD3)
)
elif a.isDeclaration():
tdef = a.getTypeDefinition('type')
if tdef is not None:
tc = '%s.%s(None)' %(NAD.getAlias(tdef.getTargetNamespace()),
self.mangle(type_class_name(tdef.getAttributeName()))
)
else:
# built-in
t = a.getAttribute('type')
try:
tc = BTI.get_typeclass(t[1], t[0])
except:
# hand back a string by default.
tc = ZSI.TC.String
if tc is not None:
tc = '%s()' %tc
key = None
if a.getAttribute('form') == 'qualified':
key = '("%s","%s")' % ( a.getTargetNamespace(),
a.getAttribute('name') )
elif a.getAttribute('form') == 'unqualified':
key = '"%s"' % a.getAttribute('name')
else:
raise ContainerError, \
'attribute form must be un/qualified %s' \
% a.getAttribute('form')
atd_list.append(\
'%s[%s] = %s' % (atd, key, tc)
)
elif a.isReference() and a.isAttributeGroup():
# flatten 'em out....
for ga in a.getAttributeGroup().getAttributeContent():
if not ga.isAttributeGroup():
attributes += (ga,)
continue
elif a.isReference():
try:
ga = a.getAttributeDeclaration()
except XMLSchema.SchemaError:
key = a.getAttribute('ref')
self.logger.debug('No schema item for attribute ref (%s, %s)' %key)
if key in self.built_in_refs: continue
raise
tp = None
if ga is not None:
tp = ga.getTypeDefinition('type')
key = '("%s","%s")' %(ga.getTargetNamespace(),
ga.getAttribute('name'))
if ga is None:
# TODO: probably SOAPENC:arrayType
key = '("%s","%s")' %(
a.getAttribute('ref').getTargetNamespace(),
a.getAttribute('ref').getName())
atd_list.append(\
'%s[%s] = ZSI.TC.String()' %(atd, key)
)
elif tp is None:
# built in simple type
try:
namespace,typeName = ga.getAttribute('type')
except TypeError, ex:
# TODO: attribute declaration could be anonymous type
# hack in something to work
atd_list.append(\
'%s[%s] = ZSI.TC.String()' %(atd, key)
)
else:
atd_list.append(\
'%s[%s] = %s()' %(atd, key,
BTI.get_typeclass(typeName, namespace))
)
else:
typeName = tp.getAttribute('name')
namespace = tp.getTargetNamespace()
alias = NAD.getAlias(namespace)
key = '("%s","%s")' \
% (ga.getTargetNamespace(),ga.getAttribute('name'))
atd_list.append(\
'%s[%s] = %s.%s(None)' \
% (atd, key, alias, type_class_name(typeName))
)
else:
raise TypeError, 'expecting an attribute: %s' %a.getItemTrace()
return formatted_attribute_list
class ContainerError(Exception):
pass
class ContainerBase:
'''Base class for all Containers.
func_aname -- function that takes name, and returns aname.
'''
func_aname = TextProtectAttributeName
func_aname = staticmethod(func_aname)
logger = _GetLogger("ContainerBase")
def __init__(self):
self.content = StringWriter('\n')
self.__setup = False
self.ns = None
def __str__(self):
return self.getvalue()
# - string content methods
def mangle(self, s):
'''class/variable name illegalities
'''
return TextProtect(s)
def write(self, s):
self.content.write(s)
def writeArray(self, a):
self.content.write('\n'.join(a))
def _setContent(self):
'''override in subclasses. formats the content in the desired way.
'''
raise NotImplementedError, 'abstract method not implemented'
def getvalue(self):
if not self.__setup:
self._setContent()
self.__setup = True
return self.content.getvalue()
# - namespace utility methods
def getNSAlias(self):
if self.ns:
return NAD.getAlias(self.ns)
raise ContainerError, 'no self.ns attr defined in %s' % self.__class__
def getNSModuleName(self):
if self.ns:
return NAD.getModuleName(self.ns)
raise ContainerError, 'no self.ns attr defined in %s' % self.__class__
def getAttributeName(self, name):
'''represents the aname
'''
if self.func_aname is None:
return name
assert callable(self.func_aname), \
'expecting callable method for attribute func_aname, not %s' %type(self.func_aname)
f = self.func_aname
return f(name)
# -- containers for services file components
class ServiceContainerBase(ContainerBase):
clientClassSuffix = "SOAP"
logger = _GetLogger("ServiceContainerBase")
class ServiceHeaderContainer(ServiceContainerBase):
imports = ['\nimport urlparse, types',
'from ZSI.TCcompound import ComplexType, Struct',
'from ZSI import client',
'import ZSI'
]
logger = _GetLogger("ServiceHeaderContainer")
def __init__(self, do_extended=False):
ServiceContainerBase.__init__(self)
self.basic = self.imports[:]
self.types = None
self.messages = None
self.extras = []
self.do_extended = do_extended
def setTypesModuleName(self, module):
self.types = module
def setMessagesModuleName(self, module):
self.messages = module
def appendImport(self, statement):
'''append additional import statement(s).
import_stament -- tuple or list or str
'''
if type(statement) in (list,tuple):
self.extras += statement
else:
self.extras.append(statement)
def _setContent(self):
if self.messages:
self.write('from %s import *' % self.messages)
if self.types:
self.write('from %s import *' % self.types)
imports = self.basic[:]
imports += self.extras
self.writeArray(imports)
class ServiceLocatorContainer(ServiceContainerBase):
logger = _GetLogger("ServiceLocatorContainer")
def __init__(self):
ServiceContainerBase.__init__(self)
self.serviceName = None
self.portInfo = []
self.locatorName = None
self.portMethods = []
def setUp(self, service):
assert isinstance(service, WSDLTools.Service), \
'expecting WDSLTools.Service instance.'
self.serviceName = service.name
for p in service.ports:
try:
ab = p.getAddressBinding()
except WSDLTools.WSDLError, ex:
self.logger.warning('Skip port(%s), missing address binding' %p.name)
continue
if isinstance(ab, WSDLTools.SoapAddressBinding) is False:
self.logger.warning('Skip port(%s), not a SOAP-1.1 address binding' %p.name)
continue
info = (p.getBinding().getPortType().name, p.getBinding().name, ab.location)
self.portInfo.append(info)
def getLocatorName(self):
'''return class name of generated locator.
'''
return self.locatorName
def getPortMethods(self):
'''list of get port accessor methods of generated locator class.
'''
return self.portMethods
def _setContent(self):
if not self.serviceName:
raise ContainerError, 'no service name defined!'
self.serviceName = self.mangle(self.serviceName)
self.locatorName = '%sLocator' %self.serviceName
locator = ['# Locator', 'class %s:' %self.locatorName, ]
self.portMethods = []
for p in self.portInfo:
ptName = NC_to_CN(p[0])
bName = NC_to_CN(p[1])
sAdd = p[2]
method = 'get%s' %ptName
pI = [
'%s%s_address = "%s"' % (ID1, ptName, sAdd),
'%sdef get%sAddress(self):' % (ID1, ptName),
'%sreturn %sLocator.%s_address' % (ID2,
self.serviceName,ptName),
'%sdef %s(self, url=None, **kw):' %(ID1, method),
'%sreturn %s%s(url or %sLocator.%s_address, **kw)' \
% (ID2, bName, self.clientClassSuffix, self.serviceName, ptName),
]
self.portMethods.append(method)
locator += pI
self.writeArray(locator)
class ServiceOperationContainer(ServiceContainerBase):
logger = _GetLogger("ServiceOperationContainer")
def __init__(self, useWSA=False, do_extended=False):
'''Parameters:
useWSA -- boolean, enable ws-addressing
do_extended -- boolean
'''
ServiceContainerBase.__init__(self)
self.useWSA = useWSA
self.do_extended = do_extended
def hasInput(self):
return self.inputName is not None
def hasOutput(self):
return self.outputName is not None
def isRPC(self):
return IsRPC(self.binding_operation)
def isLiteral(self, input=True):
msgrole = self.binding_operation.input
if input is False:
msgrole = self.binding_operation.output
return IsLiteral(msgrole)
def isSimpleType(self, input=True):
if input is False:
return self.outputSimpleType
return self.inputSimpleType
def getOperation(self):
return self.port.operations.get(self.name)
def getBOperation(self):
return self.port.get(self.name)
def getOperationName(self):
return self.name
def setUp(self, item):
'''
Parameters:
item -- WSDLTools BindingOperation instance.
'''
if not isinstance(item, WSDLTools.OperationBinding):
raise TypeError, 'Expecting WSDLTools Operation instance'
if not item.input:
raise WSDLFormatError('No <input/> in <binding name="%s"><operation name="%s">' %(
item.getBinding().name, item.name))
self.name = None
self.port = None
self.soapaction = None
self.inputName = None
self.outputName = None
self.inputSimpleType = None
self.outputSimpleType = None
self.inputAction = None
self.outputAction = None
self.port = port = item.getBinding().getPortType()
self._wsdl = item.getWSDL()
self.name = name = item.name
self.binding_operation = bop = item
op = port.operations.get(name)
if op is None:
raise WSDLFormatError(
'<portType name="%s"/> no match for <binding name="%s"><operation name="%s">' %(
port.name, item.getBinding().name, item.name))
soap_bop = bop.findBinding(WSDLTools.SoapOperationBinding)
if soap_bop is None:
raise SOAPBindingError, 'expecting SOAP Bindings'
self.soapaction = soap_bop.soapAction
sbody = bop.input.findBinding(WSDLTools.SoapBodyBinding)
if not sbody:
raise SOAPBindingError('Missing <binding name="%s"><operation name="%s"><input><soap:body>' %(
port.binding.name, bop.name))
self.encodingStyle = None
if sbody.use == 'encoded':
assert sbody.encodingStyle == SOAP.ENC,\
'Supporting encodingStyle=%s, not %s'%(SOAP.ENC, sbody.encodingStyle)
self.encodingStyle = sbody.encodingStyle
self.inputName = op.getInputMessage().name
self.inputSimpleType = \
FromMessageGetSimpleElementDeclaration(op.getInputMessage())
self.inputAction = op.getInputAction()
if bop.output is not None:
sbody = bop.output.findBinding(WSDLTools.SoapBodyBinding)
if not item.output:
raise WSDLFormatError, "Operation %s, no match for output binding" %name
self.outputName = op.getOutputMessage().name
self.outputSimpleType = \
FromMessageGetSimpleElementDeclaration(op.getOutputMessage())
self.outputAction = op.getOutputAction()
def _setContent(self):
'''create string representation of operation.
'''
kwstring = 'kw = {}'
tCheck = 'if isinstance(request, %s) is False:' % self.inputName
bindArgs = ''
if self.encodingStyle is not None:
bindArgs = 'encodingStyle="%s", ' %self.encodingStyle
if self.useWSA:
wsactionIn = 'wsaction = "%s"' % self.inputAction
wsactionOut = 'wsaction = "%s"' % self.outputAction
bindArgs += 'wsaction=wsaction, endPointReference=self.endPointReference, '
responseArgs = ', wsaction=wsaction'
else:
wsactionIn = '# no input wsaction'
wsactionOut = '# no output wsaction'
responseArgs = ''
bindArgs += '**kw)'
if self.do_extended:
inputName = self.getOperation().getInputMessage().name
wrap_str = ""
partsList = self.getOperation().getInputMessage().parts.values()
try:
subNames = GetPartsSubNames(partsList, self._wsdl)
except TypeError, ex:
raise Wsdl2PythonError,\
"Extended generation failure: only supports doc/lit, "\
+"and all element attributes (<message><part element="\
+"\"my:GED\"></message>) must refer to single global "\
+"element declaration with complexType content. "\
+"\n\n**** TRY WITHOUT EXTENDED ****\n"
args = []
for pa in subNames:
args += pa
for arg in args:
wrap_str += "%srequest.%s = %s\n" % (ID2,
self.getAttributeName(arg),
self.mangle(arg))
#args = [pa.name for pa in self.getOperation().getInputMessage().parts.values()]
argsStr = ",".join(args)
if len(argsStr) > 1: # add inital comma if args exist
argsStr = ", " + argsStr
method = [
'%s# op: %s' % (ID1, self.getOperation().getInputMessage()),
'%sdef %s(self%s):' % (ID1, self.name, argsStr),
'\n%srequest = %s()' % (ID2, self.inputName),
'%s' % (wrap_str),
'%s%s' % (ID2, kwstring),
'%s%s' % (ID2, wsactionIn),
'%sself.binding.Send(None, None, request, soapaction="%s", %s'\
%(ID2, self.soapaction, bindArgs),
]
else:
method = [
'%s# op: %s' % (ID1, self.name),
'%sdef %s(self, request):' % (ID1, self.name),
'%s%s' % (ID2, tCheck),
'%sraise TypeError, "%%s incorrect request type" %% (%s)' %(ID3, 'request.__class__'),
'%s%s' % (ID2, kwstring),
'%s%s' % (ID2, wsactionIn),
'%sself.binding.Send(None, None, request, soapaction="%s", %s'\
%(ID2, self.soapaction, bindArgs),
]
#
# BP 1.0: rpc/literal
# WSDL 1.1 Section 3.5 could be interpreted to mean the RPC response
# wrapper element must be named identical to the name of the
# wsdl:operation.
# R2729
#
# SOAP-1.1 Note: rpc/encoded
# Each parameter accessor has a name corresponding to the name of the
# parameter and type corresponding to the type of the parameter. The name of
# the return value accessor is not significant. Likewise, the name of the struct is
# not significant. However, a convention is to name it after the method name
# with the string "Response" appended.
#
if self.outputName:
response = ['%s%s' % (ID2, wsactionOut),]
if self.isRPC() and not self.isLiteral():
# rpc/encoded Replace wrapper name with None
response.append(\
'%stypecode = Struct(pname=None, ofwhat=%s.typecode.ofwhat, pyclass=%s.typecode.pyclass)' %(
ID2, self.outputName, self.outputName)
)
response.append(\
'%sresponse = self.binding.Receive(typecode%s)' %(
ID2, responseArgs)
)
else:
response.append(\
'%sresponse = self.binding.Receive(%s.typecode%s)' %(
ID2, self.outputName, responseArgs)
)
if self.outputSimpleType:
response.append('%sreturn %s(response)' %(ID2, self.outputName))
else:
if self.do_extended:
partsList = self.getOperation().getOutputMessage().parts.values()
subNames = GetPartsSubNames(partsList, self._wsdl)
args = []
for pa in subNames:
args += pa
for arg in args:
response.append('%s%s = response.%s' % (ID2, self.mangle(arg), self.getAttributeName(arg)) )
margs = ",".join(args)
response.append("%sreturn %s" % (ID2, margs) )
else:
response.append('%sreturn response' %ID2)
method += response
self.writeArray(method)
class ServiceOperationsClassContainer(ServiceContainerBase):
'''
class variables:
readerclass --
writerclass --
operationclass -- representation of each operation.
'''
readerclass = None
writerclass = None
operationclass = ServiceOperationContainer
logger = _GetLogger("ServiceOperationsClassContainer")
def __init__(self, useWSA=False, do_extended=False, wsdl=None):
'''Parameters:
name -- binding name
property -- resource properties
useWSA -- boolean, enable ws-addressing
name -- binding name
'''
ServiceContainerBase.__init__(self)
self.useWSA = useWSA
self.rProp = None
self.bName = None
self.operations = None
self.do_extended = do_extended
self._wsdl = wsdl # None unless do_extended == True
def setReaderClass(cls, className):
'''specify a reader class name, this must be imported
in service module.
'''
cls.readerclass = className
setReaderClass = classmethod(setReaderClass)
def setWriterClass(cls, className):
'''specify a writer class name, this must be imported
in service module.
'''
cls.writerclass = className
setWriterClass = classmethod(setWriterClass)
def setOperationClass(cls, className):
'''specify an operation container class name.
'''
cls.operationclass = className
setOperationClass = classmethod(setOperationClass)
def setUp(self, port):
'''This method finds all SOAP Binding Operations, it will skip
all bindings that are not SOAP.
port -- WSDL.Port instance
'''
assert isinstance(port, WSDLTools.Port), 'expecting WSDLTools Port instance'
self.operations = []
self.bName = port.getBinding().name
self.rProp = port.getBinding().getPortType().getResourceProperties()
soap_binding = port.getBinding().findBinding(WSDLTools.SoapBinding)
if soap_binding is None:
raise Wsdl2PythonError,\
'port(%s) missing WSDLTools.SoapBinding' %port.name
for bop in port.getBinding().operations:
soap_bop = bop.findBinding(WSDLTools.SoapOperationBinding)
if soap_bop is None:
self.logger.warning(\
'Skip port(%s) operation(%s) no SOAP Binding Operation'\
%(port.name, bop.name),
)
continue
#soapAction = soap_bop.soapAction
if bop.input is not None:
soapBodyBind = bop.input.findBinding(WSDLTools.SoapBodyBinding)
if soapBodyBind is None:
self.logger.warning(\
'Skip port(%s) operation(%s) Bindings(%s) not supported'\
%(port.name, bop.name, bop.extensions)
)
continue
op = port.getBinding().getPortType().operations.get(bop.name)
if op is None:
raise Wsdl2PythonError,\
'no matching portType/Binding operation(%s)' % bop.name
c = self.operationclass(useWSA=self.useWSA,
do_extended=self.do_extended)
c.setUp(bop)
self.operations.append(c)
def _setContent(self):
if self.useWSA is True:
ctorArgs = 'endPointReference=None, **kw'
epr = 'self.endPointReference = endPointReference'
else:
ctorArgs = '**kw'
epr = '# no ws-addressing'
if self.rProp:
rprop = 'kw.setdefault("ResourceProperties", ("%s","%s"))'\
%(self.rProp[0], self.rProp[1])
else:
rprop = '# no resource properties'
methods = [
'# Methods',
'class %s%s:' % (NC_to_CN(self.bName), self.clientClassSuffix),
'%sdef __init__(self, url, %s):' % (ID1, ctorArgs),
'%skw.setdefault("readerclass", %s)' % (ID2, self.readerclass),
'%skw.setdefault("writerclass", %s)' % (ID2, self.writerclass),
'%s%s' % (ID2, rprop),
'%sself.binding = client.Binding(url=url, **kw)' %ID2,
'%s%s' % (ID2,epr),
]
for op in self.operations:
methods += [ op.getvalue() ]
self.writeArray(methods)
class MessageContainerInterface:
logger = _GetLogger("MessageContainerInterface")
def setUp(self, port, soc, input):
'''sets the attribute _simple which represents a
primitive type message represents, or None if not primitive.
soc -- WSDLTools.ServiceOperationContainer instance
port -- WSDLTools.Port instance
input-- boolean, input messasge or output message of operation.
'''
raise NotImplementedError, 'Message container must implemented setUp.'
class ServiceDocumentLiteralMessageContainer(ServiceContainerBase, MessageContainerInterface):
logger = _GetLogger("ServiceDocumentLiteralMessageContainer")
def __init__(self, do_extended=False):
ServiceContainerBase.__init__(self)
self.do_extended=do_extended
def setUp(self, port, soc, input):
content = self.content
# TODO: check soapbody for part name
simple = self._simple = soc.isSimpleType(soc.getOperationName())
name = soc.getOperationName()
# Document/literal
operation = port.getBinding().getPortType().operations.get(name)
bop = port.getBinding().operations.get(name)
soapBodyBind = None
if input is True:
soapBodyBind = bop.input.findBinding(WSDLTools.SoapBodyBinding)
message = operation.getInputMessage()
else:
soapBodyBind = bop.output.findBinding(WSDLTools.SoapBodyBinding)
message = operation.getOutputMessage()
# using underlying data structure to avoid phantom problem.
# parts = message.parts.data.values()
# if len(parts) > 1:
# raise Wsdl2PythonError, 'not suporting multi part doc/lit msgs'
if len(message.parts) == 0:
raise Wsdl2PythonError, 'must specify part for doc/lit msg'
p = None
if soapBodyBind.parts is not None:
if len(soapBodyBind.parts) > 1:
raise Wsdl2PythonError,\
'not supporting multiple parts in soap body'
if len(soapBodyBind.parts) == 0:
return
p = message.parts.get(soapBodyBind.parts[0])
# XXX: Allow for some slop
p = p or message.parts[0]
if p.type:
raise Wsdl2PythonError, 'no doc/lit suport for <part type>'
if not p.element:
return
content.ns = p.element[0]
content.pName = p.element[1]
content.mName = message.name
def _setContent(self):
'''create string representation of doc/lit message container. If
message element is simple(primitive), use python type as base class.
'''
try:
simple = self._simple
except AttributeError:
raise RuntimeError, 'call setUp first'
# TODO: Hidden contract. Must set self.ns before getNSAlias...
# File "/usr/local/python/lib/python2.4/site-packages/ZSI/generate/containers.py", line 625, in _setContent
# kw['message'],kw['prefix'],kw['typecode'] = \
# File "/usr/local/python/lib/python2.4/site-packages/ZSI/generate/containers.py", line 128, in getNSAlias
# raise ContainerError, 'no self.ns attr defined in %s' % self.__class__
# ZSI.generate.containers.ContainerError: no self.ns attr defined in ZSI.generate.containers.ServiceDocumentLiteralMessageContainer
#
self.ns = self.content.ns
kw = KW.copy()
kw['message'],kw['prefix'],kw['typecode'] = \
self.content.mName, self.getNSAlias(), element_class_name(self.content.pName)
# These messsages are just global element declarations
self.writeArray(['%(message)s = %(prefix)s.%(typecode)s().pyclass' %kw])
class ServiceRPCEncodedMessageContainer(ServiceContainerBase, MessageContainerInterface):
logger = _GetLogger("ServiceRPCEncodedMessageContainer")
def setUp(self, port, soc, input):
'''
Instance Data:
op -- WSDLTools Operation instance
bop -- WSDLTools BindingOperation instance
input -- boolean input/output
'''
name = soc.getOperationName()
bop = port.getBinding().operations.get(name)
op = port.getBinding().getPortType().operations.get(name)
assert op is not None, 'port has no operation %s' %name
assert bop is not None, 'port has no binding operation %s' %name
self.input = input
self.op = op
self.bop = bop
def _setContent(self):
try:
self.op
except AttributeError:
raise RuntimeError, 'call setUp first'
pname = self.op.name
msgRole = self.op.input
msgRoleB = self.bop.input
if self.input is False:
pname = '%sResponse' %self.op.name
msgRole = self.op.output
msgRoleB = self.bop.output
sbody = msgRoleB.findBinding(WSDLTools.SoapBodyBinding)
if not sbody or not sbody.namespace:
raise WSInteropError, WSISpec.R2717
assert sbody.use == 'encoded', 'Expecting use=="encoded"'
encodingStyle = sbody.encodingStyle
assert encodingStyle == SOAP.ENC,\
'Supporting encodingStyle=%s, not %s' %(SOAP.ENC, encodingStyle)
namespace = sbody.namespace
tcb = MessageTypecodeContainer(\
tuple(msgRole.getMessage().parts.list),
)
ofwhat = '[%s]' %tcb.getTypecodeList()
pyclass = msgRole.getMessage().name
fdict = KW.copy()
fdict['nspname'] = sbody.namespace
fdict['pname'] = pname
fdict['pyclass'] = None
fdict['ofwhat'] = ofwhat
fdict['encoded'] = namespace
#if self.input is False:
# fdict['typecode'] = \
# 'Struct(pname=None, ofwhat=%(ofwhat)s, pyclass=%(pyclass)s, encoded="%(encoded)s")'
#else:
fdict['typecode'] = \
'Struct(pname=("%(nspname)s","%(pname)s"), ofwhat=%(ofwhat)s, pyclass=%(pyclass)s, encoded="%(encoded)s")'
message = ['class %(pyclass)s:',
'%(ID1)sdef __init__(self):']
for aname in tcb.getAttributeNames():
message.append('%(ID2)sself.' + aname +' = None')
message.append('%(ID2)sreturn')
# TODO: This isn't a TypecodeContainerBase instance but it
# certaintly generates a pyclass and typecode.
#if self.metaclass is None:
if TypecodeContainerBase.metaclass is None:
fdict['pyclass'] = pyclass
fdict['typecode'] = fdict['typecode'] %fdict
message.append('%(pyclass)s.typecode = %(typecode)s')
else:
# Need typecode to be available when class is constructed.
fdict['typecode'] = fdict['typecode'] %fdict
fdict['pyclass'] = pyclass
fdict['metaclass'] = TypecodeContainerBase.metaclass
message.insert(0, '_%(pyclass)sTypecode = %(typecode)s')
message.insert(2, '%(ID1)stypecode = _%(pyclass)sTypecode')
message.insert(3, '%(ID1)s__metaclass__ = %(metaclass)s')
message.append('%(pyclass)s.typecode.pyclass = %(pyclass)s')
self.writeArray(map(lambda l: l %fdict, message))
class ServiceRPCLiteralMessageContainer(ServiceContainerBase, MessageContainerInterface):
logger = _GetLogger("ServiceRPCLiteralMessageContainer")
def setUp(self, port, soc, input):
'''
Instance Data:
op -- WSDLTools Operation instance
bop -- WSDLTools BindingOperation instance
input -- boolean input/output
'''
name = soc.getOperationName()
bop = port.getBinding().operations.get(name)
op = port.getBinding().getPortType().operations.get(name)
assert op is not None, 'port has no operation %s' %name
assert bop is not None, 'port has no binding operation %s' %name
self.op = op
self.bop = bop
self.input = input
def _setContent(self):
try:
self.op
except AttributeError:
raise RuntimeError, 'call setUp first'
operation = self.op
input = self.input
pname = operation.name
msgRole = operation.input
msgRoleB = self.bop.input
if input is False:
pname = '%sResponse' %operation.name
msgRole = operation.output
msgRoleB = self.bop.output
sbody = msgRoleB.findBinding(WSDLTools.SoapBodyBinding)
if not sbody or not sbody.namespace:
raise WSInteropError, WSISpec.R2717
namespace = sbody.namespace
tcb = MessageTypecodeContainer(\
tuple(msgRole.getMessage().parts.list),
)
ofwhat = '[%s]' %tcb.getTypecodeList()
pyclass = msgRole.getMessage().name
fdict = KW.copy()
fdict['nspname'] = sbody.namespace
fdict['pname'] = pname
fdict['pyclass'] = None
fdict['ofwhat'] = ofwhat
fdict['encoded'] = namespace
fdict['typecode'] = \
'Struct(pname=("%(nspname)s","%(pname)s"), ofwhat=%(ofwhat)s, pyclass=%(pyclass)s, encoded="%(encoded)s")'
message = ['class %(pyclass)s:',
'%(ID1)sdef __init__(self):']
for aname in tcb.getAttributeNames():
message.append('%(ID2)sself.' + aname +' = None')
message.append('%(ID2)sreturn')
# TODO: This isn't a TypecodeContainerBase instance but it
# certaintly generates a pyclass and typecode.
#if self.metaclass is None:
if TypecodeContainerBase.metaclass is None:
fdict['pyclass'] = pyclass
fdict['typecode'] = fdict['typecode'] %fdict
message.append('%(pyclass)s.typecode = %(typecode)s')
else:
# Need typecode to be available when class is constructed.
fdict['typecode'] = fdict['typecode'] %fdict
fdict['pyclass'] = pyclass
fdict['metaclass'] = TypecodeContainerBase.metaclass
message.insert(0, '_%(pyclass)sTypecode = %(typecode)s')
message.insert(2, '%(ID1)stypecode = _%(pyclass)sTypecode')
message.insert(3, '%(ID1)s__metaclass__ = %(metaclass)s')
message.append('%(pyclass)s.typecode.pyclass = %(pyclass)s')
self.writeArray(map(lambda l: l %fdict, message))
TypesContainerBase = ContainerBase
class TypesHeaderContainer(TypesContainerBase):
'''imports for all generated types modules.
'''
imports = [
'import ZSI',
'import ZSI.TCcompound',
'from ZSI.schema import LocalElementDeclaration, ElementDeclaration, TypeDefinition, GTD, GED',
]
logger = _GetLogger("TypesHeaderContainer")
def _setContent(self):
self.writeArray(TypesHeaderContainer.imports)
NamespaceClassContainerBase = TypesContainerBase
class NamespaceClassHeaderContainer(NamespaceClassContainerBase):
logger = _GetLogger("NamespaceClassHeaderContainer")
def _setContent(self):
head = [
'#' * 30,
'# targetNamespace',
'# %s' % self.ns,
'#' * 30 + '\n',
'class %s:' % self.getNSAlias(),
'%stargetNamespace = "%s"' % (ID1, self.ns)
]
self.writeArray(head)
class NamespaceClassFooterContainer(NamespaceClassContainerBase):
logger = _GetLogger("NamespaceClassFooterContainer")
def _setContent(self):
foot = [
'# end class %s (tns: %s)' % (self.getNSAlias(), self.ns),
]
self.writeArray(foot)
BTI = BaseTypeInterpreter()
class TypecodeContainerBase(TypesContainerBase):
'''Base class for all classes representing anything
with element content.
class variables:
mixed_content_aname -- text content will be placed in this attribute.
attributes_aname -- attributes will be placed in this attribute.
metaclass -- set this attribute to specify a pyclass __metaclass__
'''
mixed_content_aname = 'text'
attributes_aname = 'attrs'
metaclass = None
lazy = False
logger = _GetLogger("TypecodeContainerBase")
def __init__(self, do_extended=False, extPyClasses=None):
TypesContainerBase.__init__(self)
self.name = None
# attrs for model groups and others with elements, tclists, etc...
self.allOptional = False
self.mgContent = None
self.contentFlattened = False
self.elementAttrs = []
self.tcListElements = []
self.tcListSet = False
self.localTypes = []
# used when processing nested anonymous types
self.parentClass = None
# used when processing attribute content
self.mixed = False
self.extraFlags = ''
self.attrComponents = None
# --> EXTENDED
# Used if an external pyclass was specified for this type.
self.do_extended = do_extended
if extPyClasses is None:
self.extPyClasses = {}
else:
self.extPyClasses = extPyClasses
# <--
def getvalue(self):
out = ContainerBase.getvalue(self)
for item in self.localTypes:
content = None
assert True is item.isElement() is item.isLocal(), 'expecting local elements only'
etp = item.content
qName = item.getAttribute('type')
if not qName:
etp = item.content
local = True
else:
etp = item.getTypeDefinition('type')
if etp is None:
if local is True:
content = ElementLocalComplexTypeContainer(do_extended=self.do_extended)
else:
content = ElementSimpleTypeContainer()
elif etp.isLocal() is False:
content = ElementGlobalDefContainer()
elif etp.isSimple() is True:
content = ElementLocalSimpleTypeContainer()
elif etp.isComplex():
content = ElementLocalComplexTypeContainer(do_extended=self.do_extended)
else:
raise Wsdl2PythonError, "Unknown element declaration: %s" %item.getItemTrace()
content.setUp(item)
out += '\n\n'
if self.parentClass:
content.parentClass = \
'%s.%s' %(self.parentClass, self.getClassName())
else:
content.parentClass = '%s.%s' %(self.getNSAlias(), self.getClassName())
for l in content.getvalue().split('\n'):
if l: out += '%s%s\n' % (ID1, l)
else: out += '\n'
out += '\n\n'
return out
def getAttributeName(self, name):
'''represents the aname
'''
if self.func_aname is None:
return name
assert callable(self.func_aname), \
'expecting callable method for attribute func_aname, not %s' %type(self.func_aname)
f = self.func_aname
return f(name)
def getMixedTextAName(self):
'''returns an aname representing mixed text content.
'''
return self.getAttributeName(self.mixed_content_aname)
def getClassName(self):
if not self.name:
raise ContainerError, 'self.name not defined!'
if not hasattr(self.__class__, 'type'):
raise ContainerError, 'container type not defined!'
#suffix = self.__class__.type
if self.__class__.type == DEF:
classname = type_class_name(self.name)
elif self.__class__.type == DEC:
classname = element_class_name(self.name)
return self.mangle( classname )
# --> EXTENDED
def hasExtPyClass(self):
if self.name in self.extPyClasses:
return True
else:
return False
# <--
def getPyClass(self):
'''Name of generated inner class that will be specified as pyclass.
'''
# --> EXTENDED
if self.hasExtPyClass():
classInfo = self.extPyClasses[self.name]
return ".".join(classInfo)
# <--
return 'Holder'
def getPyClassDefinition(self):
'''Return a list containing pyclass definition.
'''
kw = KW.copy()
# --> EXTENDED
if self.hasExtPyClass():
classInfo = self.extPyClasses[self.name]
kw['classInfo'] = classInfo[0]
return ["%(ID3)simport %(classInfo)s" %kw ]
# <--
kw['pyclass'] = self.getPyClass()
definition = []
definition.append('%(ID3)sclass %(pyclass)s:' %kw)
if self.metaclass is not None:
kw['type'] = self.metaclass
definition.append('%(ID4)s__metaclass__ = %(type)s' %kw)
definition.append('%(ID4)stypecode = self' %kw)
#TODO: Remove pyclass holder __init__ -->
definition.append('%(ID4)sdef __init__(self):' %kw)
definition.append('%(ID5)s# pyclass' %kw)
# JRB HACK need to call _setElements via getElements
self._setUpElements()
# JRB HACK need to indent additional one level
for el in self.elementAttrs:
kw['element'] = el
definition.append('%(ID2)s%(element)s' %kw)
definition.append('%(ID5)sreturn' %kw)
# <--
# pyclass descriptive name
if self.name is not None:
kw['name'] = self.name
definition.append(\
'%(ID3)s%(pyclass)s.__name__ = "%(name)s_Holder"' %kw
)
return definition
def nsuriLogic(self):
'''set a variable "ns" that represents the targetNamespace in
which this item is defined. Used for namespacing local elements.
'''
if self.parentClass:
return 'ns = %s.%s.schema' %(self.parentClass, self.getClassName())
return 'ns = %s.%s.schema' %(self.getNSAlias(), self.getClassName())
def schemaTag(self):
if self.ns is not None:
return 'schema = "%s"' % self.ns
raise ContainerError, 'failed to set schema targetNamespace(%s)' %(self.__class__)
def typeTag(self):
if self.name is not None:
return 'type = (schema, "%s")' % self.name
raise ContainerError, 'failed to set type name(%s)' %(self.__class__)
def literalTag(self):
if self.name is not None:
return 'literal = "%s"' % self.name
raise ContainerError, 'failed to set element name(%s)' %(self.__class__)
def getExtraFlags(self):
if self.mixed:
self.extraFlags += 'mixed=True, mixed_aname="%s", ' %self.getMixedTextAName()
return self.extraFlags
def simpleConstructor(self, superclass=None):
if superclass:
return '%s.__init__(self, **kw)' % superclass
else:
return 'def __init__(self, **kw):'
def pnameConstructor(self, superclass=None):
if superclass:
return '%s.__init__(self, pname, **kw)' % superclass
else:
return 'def __init__(self, pname, **kw):'
def _setUpElements(self):
"""TODO: Remove this method
This method ONLY sets up the instance attributes.
Dependency instance attribute:
mgContent -- expected to be either a complex definition
with model group content, a model group, or model group
content. TODO: should only support the first two.
"""
self.logger.debug("_setUpElements: %s" %self._item.getItemTrace())
if hasattr(self, '_done'):
#return '\n'.join(self.elementAttrs)
return
self._done = True
flat = []
content = self.mgContent
if type(self.mgContent) is not tuple:
mg = self.mgContent
if not mg.isModelGroup():
mg = mg.content
content = mg.content
if mg.isAll():
flat = content
content = []
elif mg.isModelGroup() and mg.isDefinition():
mg = mg.content
content = mg.content
idx = 0
content = list(content)
while idx < len(content):
c = orig = content[idx]
if c.isElement():
flat.append(c)
idx += 1
continue
if c.isReference() and c.isModelGroup():
c = c.getModelGroupReference()
if c.isDefinition() and c.isModelGroup():
c = c.content
if c.isSequence() or c.isChoice():
begIdx = idx
endIdx = begIdx + len(c.content)
for i in range(begIdx, endIdx):
content.insert(i, c.content[i-begIdx])
content.remove(orig)
continue
raise ContainerError, 'unexpected schema item: %s' %c.getItemTrace()
for c in flat:
if c.isDeclaration() and c.isElement():
defaultValue = "None"
parent = c
defs = []
# stop recursion via global ModelGroupDefinition
while defs.count(parent) <= 1:
maxOccurs = parent.getAttribute('maxOccurs')
if maxOccurs == 'unbounded' or int(maxOccurs) > 1:
defaultValue = "[]"
break
parent = parent._parent()
if not parent.isModelGroup():
break
if parent.isReference():
parent = parent.getModelGroupReference()
if parent.isDefinition():
parent = parent.content
defs.append(parent)
if None == c.getAttribute('name') and c.isWildCard():
e = '%sself.%s = %s' %(ID3,
self.getAttributeName('any'), defaultValue)
else:
e = '%sself.%s = %s' %(ID3,
self.getAttributeName(c.getAttribute('name')), defaultValue)
self.elementAttrs.append(e)
continue
# TODO: This seems wrong
if c.isReference():
e = '%sself._%s = None' %(ID3,
self.mangle(c.getAttribute('ref')[1]))
self.elementAttrs.append(e)
continue
raise ContainerError, 'unexpected item: %s' % c.getItemTrace()
#return '\n'.join(self.elementAttrs)
return
def _setTypecodeList(self):
"""generates ofwhat content, minOccurs/maxOccurs facet generation.
Dependency instance attribute:
mgContent -- expected to be either a complex definition
with model group content, a model group, or model group
content. TODO: should only support the first two.
localTypes -- produce local class definitions later
tcListElements -- elements, local/global
"""
self.logger.debug("_setTypecodeList(%r): %s" %
(self.mgContent, self._item.getItemTrace()))
flat = []
content = self.mgContent
#TODO: too much slop permitted here, impossible
# to tell what is going on.
if type(content) is not tuple:
mg = content
if not mg.isModelGroup():
raise Wsdl2PythonErr("Expecting ModelGroup: %s" %
mg.getItemTrace())
self.logger.debug("ModelGroup(%r) contents(%r): %s" %
(mg, mg.content, mg.getItemTrace()))
#<group ref>
if mg.isReference():
raise RuntimeError("Unexpected modelGroup reference: %s" %
mg.getItemTrace())
#<group name>
if mg.isDefinition():
mg = mg.content
if mg.isAll():
flat = mg.content
content = []
elif mg.isSequence():
content = mg.content
elif mg.isChoice():
content = mg.content
else:
raise RuntimeError("Unknown schema item")
idx = 0
content = list(content)
self.logger.debug("content: %r" %content)
while idx < len(content):
c = orig = content[idx]
if c.isElement():
flat.append(c)
idx += 1
continue
if c.isReference() and c.isModelGroup():
c = c.getModelGroupReference()
if c.isDefinition() and c.isModelGroup():
c = c.content
if c.isSequence() or c.isChoice():
begIdx = idx
endIdx = begIdx + len(c.content)
for i in range(begIdx, endIdx):
content.insert(i, c.content[i-begIdx])
content.remove(orig)
continue
raise ContainerError, 'unexpected schema item: %s' %c.getItemTrace()
# TODO: Need to store "parents" in a dict[id] = list(),
# because cannot follow references, but not currently
# a big concern.
self.logger.debug("flat: %r" %list(flat))
for c in flat:
tc = TcListComponentContainer()
# TODO: Remove _getOccurs
min,max,nil = self._getOccurs(c)
min = max = None
maxOccurs = 1
parent = c
defs = []
# stop recursion via global ModelGroupDefinition
while defs.count(parent) <= 1:
max = parent.getAttribute('maxOccurs')
if max == 'unbounded':
maxOccurs = '"%s"' %max
break
maxOccurs = int(max) * maxOccurs
parent = parent._parent()
if not parent.isModelGroup():
break
if parent.isReference():
parent = parent.getModelGroupReference()
if parent.isDefinition():
parent = parent.content
defs.append(parent)
del defs
parent = c
while 1:
minOccurs = int(parent.getAttribute('minOccurs'))
if minOccurs == 0 or parent.isChoice():
minOccurs = 0
break
parent = parent._parent()
if not parent.isModelGroup():
minOccurs = int(c.getAttribute('minOccurs'))
break
if parent.isReference():
parent = parent.getModelGroupReference()
if parent.isDefinition():
parent = parent.content
tc.setOccurs(minOccurs, maxOccurs, nil)
processContents = self._getProcessContents(c)
tc.setProcessContents(processContents)
if c.isDeclaration() and c.isElement():
global_type = c.getAttribute('type')
content = getattr(c, 'content', None)
if c.isLocal() and c.isQualified() is False:
tc.unQualified()
if c.isWildCard():
tc.setStyleAnyElement()
elif global_type is not None:
tc.name = c.getAttribute('name')
ns = global_type[0]
if ns in SCHEMA.XSD_LIST:
tpc = BTI.get_typeclass(global_type[1],global_type[0])
tc.klass = tpc
# elif (self.ns,self.name) == global_type:
# # elif self._isRecursiveElement(c)
# # TODO: Remove this, it only works for 1 level.
# tc.setStyleRecursion()
else:
tc.setGlobalType(*global_type)
# tc.klass = '%s.%s' % (NAD.getAlias(ns),
# type_class_name(global_type[1]))
del ns
elif content is not None and content.isLocal() and content.isComplex():
tc.name = c.getAttribute('name')
tc.klass = 'self.__class__.%s' % (element_class_name(tc.name))
#TODO: Not an element reference, confusing nomenclature
tc.setStyleElementReference()
self.localTypes.append(c)
elif content is not None and content.isLocal() and content.isSimple():
# Local Simple Type
tc.name = c.getAttribute('name')
tc.klass = 'self.__class__.%s' % (element_class_name(tc.name))
#TODO: Not an element reference, confusing nomenclature
tc.setStyleElementReference()
self.localTypes.append(c)
else:
raise ContainerError, 'unexpected item: %s' % c.getItemTrace()
elif c.isReference():
# element references
ref = c.getAttribute('ref')
# tc.klass = '%s.%s' % (NAD.getAlias(ref[0]),
# element_class_name(ref[1]) )
tc.setStyleElementReference()
tc.setGlobalType(*ref)
else:
raise ContainerError, 'unexpected item: %s' % c.getItemTrace()
self.tcListElements.append(tc)
def getTypecodeList(self):
if not self.tcListSet:
# self._flattenContent()
self._setTypecodeList()
self.tcListSet = True
list = []
for e in self.tcListElements:
list.append(str(e))
return ', '.join(list)
# the following _methods() are utility methods used during
# TCList generation, et al.
def _getOccurs(self, e):
nillable = e.getAttribute('nillable')
if nillable == 'true':
nillable = True
else:
nillable = False
maxOccurs = e.getAttribute('maxOccurs')
if maxOccurs == 'unbounded':
maxOccurs = '"%s"' %maxOccurs
minOccurs = e.getAttribute('minOccurs')
if self.allOptional is True:
#JRB Hack
minOccurs = '0'
maxOccurs = '"unbounded"'
return minOccurs,maxOccurs,nillable
def _getProcessContents(self, e):
processContents = e.getAttribute('processContents')
return processContents
def getBasesLogic(self, indent):
try:
prefix = NAD.getAlias(self.sKlassNS)
except WsdlGeneratorError, ex:
# XSD or SOAP
raise
bases = []
bases.append(\
'if %s.%s not in %s.%s.__bases__:'\
%(NAD.getAlias(self.sKlassNS), type_class_name(self.sKlass), self.getNSAlias(), self.getClassName()),
)
bases.append(\
'%sbases = list(%s.%s.__bases__)'\
%(ID1,self.getNSAlias(),self.getClassName()),
)
bases.append(\
'%sbases.insert(0, %s.%s)'\
%(ID1,NAD.getAlias(self.sKlassNS), type_class_name(self.sKlass) ),
)
bases.append(\
'%s%s.%s.__bases__ = tuple(bases)'\
%(ID1, self.getNSAlias(), self.getClassName())
)
s = ''
for b in bases:
s += '%s%s\n' % (indent, b)
return s
class MessageTypecodeContainer(TypecodeContainerBase):
'''Used for RPC style messages, where we have
serveral parts serialized within a rpc wrapper name.
'''
logger = _GetLogger("MessageTypecodeContainer")
def __init__(self, parts=None):
TypecodeContainerBase.__init__(self)
self.mgContent = parts
def _getOccurs(self, e):
'''return a 3 item tuple
'''
minOccurs = maxOccurs = '1'
nillable = True
return minOccurs,maxOccurs,nillable
def _setTypecodeList(self):
self.logger.debug("_setTypecodeList: %s" %
str(self.mgContent))
assert type(self.mgContent) is tuple,\
'expecting tuple for mgContent not: %s' %type(self.mgContent)
for p in self.mgContent:
# JRB
# not sure what needs to be set for tc, this should be
# the job of the constructor or a setUp method.
min,max,nil = self._getOccurs(p)
if p.element:
raise WSInteropError, WSISpec.R2203
elif p.type:
nsuri,name = p.type
tc = RPCMessageTcListComponentContainer(qualified=False)
tc.setOccurs(min, max, nil)
tc.name = p.name
if nsuri in SCHEMA.XSD_LIST:
tpc = BTI.get_typeclass(name, nsuri)
tc.klass = tpc
else:
tc.klass = '%s.%s' % (NAD.getAlias(nsuri), type_class_name(name) )
else:
raise ContainerError, 'part must define an element or type attribute'
self.tcListElements.append(tc)
def getTypecodeList(self):
if not self.tcListSet:
self._setTypecodeList()
self.tcListSet = True
list = []
for e in self.tcListElements:
list.append(str(e))
return ', '.join(list)
def getAttributeNames(self):
'''returns a list of anames representing the parts
of the message.
'''
return map(lambda e: self.getAttributeName(e.name), self.tcListElements)
def setParts(self, parts):
self.mgContent = parts
class TcListComponentContainer(ContainerBase):
'''Encapsulates a single value in the TClist list.
it inherits TypecodeContainerBase only to get the mangle() method,
it does not call the baseclass ctor.
TODO: Change this inheritance scheme.
'''
logger = _GetLogger("TcListComponentContainer")
def __init__(self, qualified=True):
'''
qualified -- qualify element. All GEDs should be qualified,
but local element declarations qualified if form attribute
is qualified, else they are unqualified. Only relevant for
standard style.
'''
#TypecodeContainerBase.__init__(self)
ContainerBase.__init__(self)
self.qualified = qualified
self.name = None
self.klass = None
self.global_type = None
self.min = None
self.max = None
self.nil = None
self.style = None
self.setStyleElementDeclaration()
def setOccurs(self, min, max, nil):
self.min = min
self.max = max
self.nil = nil
def setProcessContents(self, processContents):
self.processContents = processContents
def setGlobalType(self, namespace, name):
self.global_type = (namespace, name)
def setStyleElementDeclaration(self):
'''set the element style.
standard -- GED or local element
'''
self.style = 'standard'
def setStyleElementReference(self):
'''set the element style.
ref -- element reference
'''
self.style = 'ref'
def setStyleAnyElement(self):
'''set the element style.
anyElement -- <any> element wildcard
'''
self.name = 'any'
self.style = 'anyElement'
# def setStyleRecursion(self):
# '''TODO: Remove. good for 1 level
# '''
# self.style = 'recursion'
def unQualified(self):
'''Do not qualify element.
'''
self.qualified = False
def _getOccurs(self):
return 'minOccurs=%s, maxOccurs=%s, nillable=%s' \
% (self.min, self.max, self.nil)
def _getProcessContents(self):
return 'processContents="%s"' \
% (self.processContents)
def _getvalue(self):
kw = {'occurs':self._getOccurs(),
'aname':self.getAttributeName(self.name),
'klass':self.klass,
'lazy':TypecodeContainerBase.lazy,
'typed':'typed=False',
'encoded':'encoded=kw.get("encoded")'}
gt = self.global_type
if gt is not None:
kw['nsuri'],kw['type'] = gt
if self.style == 'standard':
kw['pname'] = '"%s"' %self.name
if self.qualified is True:
kw['pname'] = '(ns,"%s")' %self.name
if gt is None:
return '%(klass)s(pname=%(pname)s, aname="%(aname)s", %(occurs)s, %(typed)s, %(encoded)s)' %kw
return 'GTD("%(nsuri)s","%(type)s",lazy=%(lazy)s)(pname=%(pname)s, aname="%(aname)s", %(occurs)s, %(typed)s, %(encoded)s)' %kw
if self.style == 'ref':
if gt is None:
return '%(klass)s(%(occurs)s, %(encoded)s)' %kw
return 'GED("%(nsuri)s","%(type)s",lazy=%(lazy)s, isref=True)(%(occurs)s, %(encoded)s)' %kw
kw['process'] = self._getProcessContents()
if self.style == 'anyElement':
return 'ZSI.TC.AnyElement(aname="%(aname)s", %(occurs)s, %(process)s)' %kw
# if self.style == 'recursion':
# return 'ZSI.TC.AnyElement(aname="%(aname)s", %(occurs)s, %(process)s)' %kw
raise RuntimeError, 'Must set style for typecode list generation'
def __str__(self):
return self._getvalue()
class RPCMessageTcListComponentContainer(TcListComponentContainer):
'''Container for rpc/literal rpc/encoded message typecode.
'''
logger = _GetLogger("RPCMessageTcListComponentContainer")
def __init__(self, qualified=True, encoded=None):
'''
encoded -- encoded namespaceURI, if None treat as rpc/literal.
'''
TcListComponentContainer.__init__(self, qualified=qualified)
self._encoded = encoded
def _getvalue(self):
encoded = self._encoded
if encoded is not None:
encoded = '"%s"' %self._encoded
if self.style == 'standard':
pname = '"%s"' %self.name
if self.qualified is True:
pname = '(ns,"%s")' %self.name
return '%s(pname=%s, aname="%s", typed=False, encoded=%s, %s)' \
%(self.klass, pname, self.getAttributeName(self.name),
encoded, self._getOccurs())
elif self.style == 'ref':
return '%s(encoded=%s, %s)' % (self.klass, encoded, self._getOccurs())
elif self.style == 'anyElement':
return 'ZSI.TC.AnyElement(aname="%s", %s, %s)' \
%(self.getAttributeName(self.name), self._getOccurs(), self._getProcessContents())
# elif self.style == 'recursion':
# return 'ZSI.TC.AnyElement(aname="%s", %s, %s)' \
# % (self.getAttributeName(self.name), self._getOccurs(), self._getProcessContents())
raise RuntimeError('Must set style(%s) for typecode list generation' %
self.style)
class ElementSimpleTypeContainer(TypecodeContainerBase):
type = DEC
logger = _GetLogger("ElementSimpleTypeContainer")
def _setContent(self):
aname = self.getAttributeName(self.name)
pyclass = self.pyclass
# bool cannot be subclassed
if pyclass == 'bool': pyclass = 'int'
kw = KW.copy()
kw.update(dict(aname=aname, ns=self.ns, name=self.name,
subclass=self.sKlass,literal=self.literalTag(),
schema=self.schemaTag(), init=self.simpleConstructor(),
klass=self.getClassName(), element="ElementDeclaration"))
if self.local:
kw['element'] = 'LocalElementDeclaration'
element = map(lambda i: i %kw, [
'%(ID1)sclass %(klass)s(%(subclass)s, %(element)s):',
'%(ID2)s%(literal)s',
'%(ID2)s%(schema)s',
'%(ID2)s%(init)s',
'%(ID3)skw["pname"] = ("%(ns)s","%(name)s")',
'%(ID3)skw["aname"] = "%(aname)s"',
]
)
# TODO: What about getPyClass and getPyClassDefinition?
# I want to add pyclass metaclass here but this needs to be
# corrected first.
#
# anyType (?others) has no pyclass.
app = element.append
if pyclass is not None:
app('%sclass IHolder(%s): typecode=self' % (ID3, pyclass),)
app('%skw["pyclass"] = IHolder' %(ID3),)
app('%sIHolder.__name__ = "%s_immutable_holder"' %(ID3, aname),)
app('%s%s' % (ID3, self.simpleConstructor(self.sKlass)),)
self.writeArray(element)
def setUp(self, tp):
self._item = tp
self.local = tp.isLocal()
try:
self.name = tp.getAttribute('name')
self.ns = tp.getTargetNamespace()
qName = tp.getAttribute('type')
except Exception, ex:
raise Wsdl2PythonError('Error occured processing element: %s' %(
tp.getItemTrace()), *ex.args)
if qName is None:
raise Wsdl2PythonError('Missing QName for element type attribute: %s' %tp.getItemTrace())
tns,local = qName.getTargetNamespace(),qName.getName()
self.sKlass = BTI.get_typeclass(local, tns)
if self.sKlass is None:
raise Wsdl2PythonError('No built-in typecode for type definition("%s","%s"): %s' %(tns,local,tp.getItemTrace()))
try:
self.pyclass = BTI.get_pythontype(None, None, typeclass=self.sKlass)
except Exception, ex:
raise Wsdl2PythonError('Error occured processing element: %s' %(
tp.getItemTrace()), *ex.args)
class ElementLocalSimpleTypeContainer(TypecodeContainerBase):
'''local simpleType container
'''
type = DEC
logger = _GetLogger("ElementLocalSimpleTypeContainer")
def _setContent(self):
kw = KW.copy()
kw.update(dict(aname=self.getAttributeName(self.name), ns=self.ns, name=self.name,
subclass=self.sKlass,literal=self.literalTag(),
schema=self.schemaTag(), init=self.simpleConstructor(),
klass=self.getClassName(), element="ElementDeclaration",
baseinit=self.simpleConstructor(self.sKlass)))
if self.local:
kw['element'] = 'LocalElementDeclaration'
element = map(lambda i: i %kw, [
'%(ID1)sclass %(klass)s(%(subclass)s, %(element)s):',
'%(ID2)s%(literal)s',
'%(ID2)s%(schema)s',
'%(ID2)s%(init)s',
'%(ID3)skw["pname"] = ("%(ns)s","%(name)s")',
'%(ID3)skw["aname"] = "%(aname)s"',
'%(ID3)s%(baseinit)s',
]
)
self.writeArray(element)
def setUp(self, tp):
self._item = tp
assert tp.isElement() is True and tp.content is not None and \
tp.content.isLocal() is True and tp.content.isSimple() is True ,\
'expecting local simple type: %s' %tp.getItemTrace()
self.local = tp.isLocal()
self.name = tp.getAttribute('name')
self.ns = tp.getTargetNamespace()
content = tp.content.content
if content.isRestriction():
try:
base = content.getTypeDefinition()
except XMLSchema.SchemaError, ex:
base = None
qName = content.getAttributeBase()
if base is None:
self.sKlass = BTI.get_typeclass(qName[1], qName[0])
return
raise Wsdl2PythonError, 'unsupported local simpleType restriction: %s' \
%tp.content.getItemTrace()
if content.isList():
try:
base = content.getTypeDefinition()
except XMLSchema.SchemaError, ex:
base = None
if base is None:
qName = content.getItemType()
self.sKlass = BTI.get_typeclass(qName[1], qName[0])
return
raise Wsdl2PythonError, 'unsupported local simpleType List: %s' \
%tp.content.getItemTrace()
if content.isUnion():
raise Wsdl2PythonError, 'unsupported local simpleType Union: %s' \
%tp.content.getItemTrace()
raise Wsdl2PythonError, 'unexpected schema item: %s' \
%tp.content.getItemTrace()
class ElementLocalComplexTypeContainer(TypecodeContainerBase, AttributeMixIn):
type = DEC
logger = _GetLogger("ElementLocalComplexTypeContainer")
def _setContent(self):
kw = KW.copy()
try:
kw.update(dict(klass=self.getClassName(),
subclass='ZSI.TCcompound.ComplexType',
element='ElementDeclaration',
literal=self.literalTag(),
schema=self.schemaTag(),
init=self.simpleConstructor(),
ns=self.ns, name=self.name,
aname=self.getAttributeName(self.name),
nsurilogic=self.nsuriLogic(),
ofwhat=self.getTypecodeList(),
atypecode=self.attribute_typecode,
pyclass=self.getPyClass(),
))
except Exception, ex:
args = ['Failure processing an element w/local complexType: %s' %(
self._item.getItemTrace())]
args += ex.args
ex.args = tuple(args)
raise
if self.local:
kw['element'] = 'LocalElementDeclaration'
element = [
'%(ID1)sclass %(klass)s(%(subclass)s, %(element)s):',
'%(ID2)s%(literal)s',
'%(ID2)s%(schema)s',
'%(ID2)s%(init)s',
'%(ID3)s%(nsurilogic)s',
'%(ID3)sTClist = [%(ofwhat)s]',
'%(ID3)skw["pname"] = ("%(ns)s","%(name)s")',
'%(ID3)skw["aname"] = "%(aname)s"',
'%(ID3)s%(atypecode)s = {}',
'%(ID3)sZSI.TCcompound.ComplexType.__init__(self,None,TClist,inorder=0,**kw)',
]
for l in self.attrComponents: element.append('%(ID3)s'+str(l))
element += self.getPyClassDefinition()
element.append('%(ID3)sself.pyclass = %(pyclass)s' %kw)
self.writeArray(map(lambda l: l %kw, element))
def setUp(self, tp):
'''
{'xsd':['annotation', 'simpleContent', 'complexContent',\
'group', 'all', 'choice', 'sequence', 'attribute', 'attributeGroup',\
'anyAttribute', 'any']}
'''
#
# TODO: Need a Recursive solution, this is incomplete will ignore many
# extensions, restrictions, etc.
#
self._item = tp
# JRB HACK SUPPORTING element/no content.
assert tp.isElement() is True and \
(tp.content is None or (tp.content.isComplex() is True and tp.content.isLocal() is True)),\
'expecting element w/local complexType not: %s' %tp.content.getItemTrace()
self.name = tp.getAttribute('name')
self.ns = tp.getTargetNamespace()
self.local = tp.isLocal()
complex = tp.content
# JRB HACK SUPPORTING element/no content.
if complex is None:
self.mgContent = ()
return
#attributeContent = complex.getAttributeContent()
#self.mgContent = None
if complex.content is None:
self.mgContent = ()
self.attrComponents = self._setAttributes(complex.getAttributeContent())
return
is_simple = complex.content.isSimple()
if is_simple and complex.content.content.isExtension():
# TODO: Not really supported just passing thru
self.mgContent = ()
self.attrComponents = self._setAttributes(complex.getAttributeContent())
return
if is_simple and complex.content.content.isRestriction():
# TODO: Not really supported just passing thru
self.mgContent = ()
self.attrComponents = self._setAttributes(complex.getAttributeContent())
return
if is_simple:
raise ContainerError, 'not implemented local complexType/simpleContent: %s'\
%tp.getItemTrace()
is_complex = complex.content.isComplex()
if is_complex and complex.content.content is None:
# TODO: Recursion...
self.mgContent = ()
self.attrComponents = self._setAttributes(complex.getAttributeContent())
return
if (is_complex and complex.content.content.isExtension() and
complex.content.content.content is not None and
complex.content.content.content.isModelGroup()):
self.mgContent = complex.content.content.content.content
self.attrComponents = self._setAttributes(
complex.content.content.getAttributeContent()
)
return
if (is_complex and complex.content.content.isRestriction() and
complex.content.content.content is not None and
complex.content.content.content.isModelGroup()):
self.mgContent = complex.content.content.content.content
self.attrComponents = self._setAttributes(
complex.content.content.getAttributeContent()
)
return
if is_complex:
self.mgContent = ()
self.attrComponents = self._setAttributes(complex.getAttributeContent())
return
if complex.content.isModelGroup():
self.mgContent = complex.content.content
self.attrComponents = self._setAttributes(complex.getAttributeContent())
return
# TODO: Scary Fallthru
self.mgContent = ()
self.attrComponents = self._setAttributes(complex.getAttributeContent())
class ElementGlobalDefContainer(TypecodeContainerBase):
type = DEC
logger = _GetLogger("ElementGlobalDefContainer")
def _setContent(self):
'''GED defines element name, so also define typecode aname
'''
kw = KW.copy()
try:
kw.update(dict(klass=self.getClassName(),
element='ElementDeclaration',
literal=self.literalTag(),
schema=self.schemaTag(),
init=self.simpleConstructor(),
ns=self.ns, name=self.name,
aname=self.getAttributeName(self.name),
baseslogic=self.getBasesLogic(ID3),
#ofwhat=self.getTypecodeList(),
#atypecode=self.attribute_typecode,
#pyclass=self.getPyClass(),
alias=NAD.getAlias(self.sKlassNS),
subclass=type_class_name(self.sKlass),
))
except Exception, ex:
args = ['Failure processing an element w/local complexType: %s' %(
self._item.getItemTrace())]
args += ex.args
ex.args = tuple(args)
raise
if self.local:
kw['element'] = 'LocalElementDeclaration'
element = [
'%(ID1)sclass %(klass)s(%(element)s):',
'%(ID2)s%(literal)s',
'%(ID2)s%(schema)s',
'%(ID2)s%(init)s',
'%(ID3)skw["pname"] = ("%(ns)s","%(name)s")',
'%(ID3)skw["aname"] = "%(aname)s"',
'%(baseslogic)s',
'%(ID3)s%(alias)s.%(subclass)s.__init__(self, **kw)',
'%(ID3)sif self.pyclass is not None: self.pyclass.__name__ = "%(klass)s_Holder"',
]
self.writeArray(map(lambda l: l %kw, element))
def setUp(self, element):
# Save for debugging
self._item = element
self.local = element.isLocal()
self.name = element.getAttribute('name')
self.ns = element.getTargetNamespace()
tp = element.getTypeDefinition('type')
self.sKlass = tp.getAttribute('name')
self.sKlassNS = tp.getTargetNamespace()
class ComplexTypeComplexContentContainer(TypecodeContainerBase, AttributeMixIn):
'''Represents ComplexType with ComplexContent.
'''
type = DEF
logger = _GetLogger("ComplexTypeComplexContentContainer")
def __init__(self, do_extended=False):
TypecodeContainerBase.__init__(self, do_extended=do_extended)
def setUp(self, tp):
'''complexContent/[extension,restriction]
restriction
extension
extType -- used in figuring attrs for extensions
'''
self._item = tp
assert tp.content.isComplex() is True and \
(tp.content.content.isRestriction() or tp.content.content.isExtension() is True),\
'expecting complexContent/[extension,restriction]'
self.extType = None
self.restriction = False
self.extension = False
self._kw_array = None
self._is_array = False
self.name = tp.getAttribute('name')
self.ns = tp.getTargetNamespace()
# xxx: what is this for?
#self.attribute_typecode = 'attributes'
derivation = tp.content.content
# Defined in Schema instance?
try:
base = derivation.getTypeDefinition('base')
except XMLSchema.SchemaError, ex:
base = None
# anyType, arrayType, etc...
if base is None:
base = derivation.getAttributeQName('base')
if base is None:
raise ContainerError, 'Unsupported derivation: %s'\
%derivation.getItemTrace()
if base != (SOAP.ENC,'Array') and base != (SCHEMA.XSD3,'anyType'):
raise ContainerError, 'Unsupported base(%s): %s' %(
base, derivation.getItemTrace()
)
if base == (SOAP.ENC,'Array'):
# SOAP-ENC:Array expecting arrayType attribute reference
self.logger.debug("Derivation of soapenc:Array")
self._is_array = True
self._kw_array = {'atype':None, 'id3':ID3, 'ofwhat':None}
self.sKlass = BTI.get_typeclass(base[1], base[0])
self.sKlassNS = base[0]
attr = None
for a in derivation.getAttributeContent():
assert a.isAttribute() is True,\
'only attribute content expected: %s' %a.getItemTrace()
if a.isReference() is True:
if a.getAttribute('ref') == (SOAP.ENC,'arrayType'):
self._kw_array['atype'] = a.getAttributeQName((WSDL.BASE, 'arrayType'))
attr = a
break
qname = self._kw_array.get('atype')
if attr is not None:
qname = self._kw_array.get('atype')
ncname = qname[1].strip('[]')
namespace = qname[0]
try:
ofwhat = attr.getSchemaItem(XMLSchema.TYPES, namespace, ncname)
except XMLSchema.SchemaError, ex:
ofwhat = None
if ofwhat is None:
self._kw_array['ofwhat'] = BTI.get_typeclass(ncname, namespace)
else:
self._kw_array['ofwhat'] = GetClassNameFromSchemaItem(ofwhat, do_extended=self.do_extended)
if self._kw_array['ofwhat'] is None:
raise ContainerError, 'For Array could not resolve ofwhat typecode(%s,%s): %s'\
%(namespace, ncname, derivation.getItemTrace())
self.logger.debug('Attribute soapenc:arrayType="%s"' %
str(self._kw_array['ofwhat']))
elif isinstance(base, XMLSchema.XMLSchemaComponent):
self.sKlass = base.getAttribute('name')
self.sKlassNS = base.getTargetNamespace()
else:
# TypeDescriptionComponent
self.sKlass = base.getName()
self.sKlassNS = base.getTargetNamespace()
attrs = []
if derivation.isRestriction():
self.restriction = True
self.extension = False
# derivation.getAttributeContent subset of tp.getAttributeContent
attrs += derivation.getAttributeContent() or ()
else:
self.restriction = False
self.extension = True
attrs += tp.getAttributeContent() or ()
if isinstance(derivation, XMLSchema.XMLSchemaComponent):
attrs += derivation.getAttributeContent() or ()
# XXX: not sure what this is doing
if attrs:
self.extType = derivation
if derivation.content is not None \
and derivation.content.isModelGroup():
group = derivation.content
if group.isReference():
group = group.getModelGroupReference()
self.mgContent = group.content
elif derivation.content:
raise Wsdl2PythonError, \
'expecting model group, not: %s' %derivation.content.getItemTrace()
else:
self.mgContent = ()
self.attrComponents = self._setAttributes(tuple(attrs))
def _setContent(self):
'''JRB What is the difference between instance data
ns, name, -- type definition?
sKlass, sKlassNS? -- element declaration?
'''
kw = KW.copy()
definition = []
if self._is_array:
# SOAP-ENC:Array
if _is_xsd_or_soap_ns(self.sKlassNS) is False and self.sKlass == 'Array':
raise ContainerError, 'unknown type: (%s,%s)'\
%(self.sKlass, self.sKlassNS)
# No need to xsi:type array items since specify with
# SOAP-ENC:arrayType attribute.
definition += [\
'%sclass %s(ZSI.TC.Array, TypeDefinition):' % (ID1, self.getClassName()),
'%s#complexType/complexContent base="SOAP-ENC:Array"' %(ID2),
'%s%s' % (ID2, self.schemaTag()),
'%s%s' % (ID2, self.typeTag()),
'%s%s' % (ID2, self.pnameConstructor()),
'%(id3)sofwhat = %(ofwhat)s(None, typed=False)' %self._kw_array,
'%(id3)satype = %(atype)s' %self._kw_array,
'%s%s.__init__(self, atype, ofwhat, pname=pname, childnames=\'item\', **kw)'
%(ID3, self.sKlass),
]
self.writeArray(definition)
return
definition += [\
'%sclass %s(TypeDefinition):' % (ID1, self.getClassName()),
'%s%s' % (ID2, self.schemaTag()),
'%s%s' % (ID2, self.typeTag()),
'%s%s' % (ID2, self.pnameConstructor()),
'%s%s' % (ID3, self.nsuriLogic()),
'%sTClist = [%s]' % (ID3, self.getTypecodeList()),
]
definition.append(
'%(ID3)sattributes = %(atc)s = attributes or {}' %{
'ID3':ID3, 'atc':self.attribute_typecode}
)
#
# Special case: anyType restriction
isAnyType = (self.sKlassNS, self.sKlass) == (SCHEMA.XSD3, 'anyType')
if isAnyType:
del definition[0]
definition.insert(0,
'%sclass %s(ZSI.TC.ComplexType, TypeDefinition):' % (
ID1, self.getClassName())
)
definition.insert(1,
'%s#complexType/complexContent restrict anyType' %(
ID2)
)
# derived type support
definition.append('%sif extend: TClist += ofwhat'%(ID3))
definition.append('%sif restrict: TClist = ofwhat' %(ID3))
if len(self.attrComponents) > 0:
definition.append('%selse:' %(ID3))
for l in self.attrComponents:
definition.append('%s%s'%(ID4, l))
if isAnyType:
definition.append(\
'%sZSI.TC.ComplexType.__init__(self, None, TClist, pname=pname, **kw)' %(
ID3),
)
# pyclass class definition
definition += self.getPyClassDefinition()
kw['pyclass'] = self.getPyClass()
definition.append('%(ID3)sself.pyclass = %(pyclass)s' %kw)
self.writeArray(definition)
return
for l in self.attrComponents:
definition.append('%s%s'%(ID3, l))
definition.append('%s' % self.getBasesLogic(ID3))
prefix = NAD.getAlias(self.sKlassNS)
typeClassName = type_class_name(self.sKlass)
if self.restriction:
definition.append(\
'%s%s.%s.__init__(self, pname, ofwhat=TClist, restrict=True, **kw)' %(
ID3, prefix, typeClassName),
)
definition.insert(1, '%s#complexType/complexContent restriction' %ID2)
self.writeArray(definition)
return
if self.extension:
definition.append(\
'%s%s.%s.__init__(self, pname, ofwhat=TClist, extend=True, attributes=attributes, **kw)'%(
ID3, prefix, typeClassName),
)
definition.insert(1, '%s#complexType/complexContent extension' %(ID2))
self.writeArray(definition)
return
raise Wsdl2PythonError,\
'ComplexContent must be a restriction or extension'
def pnameConstructor(self, superclass=None):
if superclass:
return '%s.__init__(self, pname, ofwhat=(), extend=False, restrict=False, attributes=None, **kw)' % superclass
return 'def __init__(self, pname, ofwhat=(), extend=False, restrict=False, attributes=None, **kw):'
class ComplexTypeContainer(TypecodeContainerBase, AttributeMixIn):
'''Represents a global complexType definition.
'''
type = DEF
logger = _GetLogger("ComplexTypeContainer")
def setUp(self, tp, empty=False):
'''Problematic, loose all model group information.
<all>, <choice>, <sequence> ..
tp -- type definition
empty -- no model group, just use as a dummy holder.
'''
self._item = tp
self.name = tp.getAttribute('name')
self.ns = tp.getTargetNamespace()
self.mixed = tp.isMixed()
self.mgContent = ()
self.attrComponents = self._setAttributes(tp.getAttributeContent())
# Save reference to type for debugging
self._item = tp
if empty:
return
model = tp.content
if model.isReference():
model = model.getModelGroupReference()
if model is None:
return
if model.content is None:
return
# sequence, all or choice
#self.mgContent = model.content
self.mgContent = model
def _setContent(self):
try:
definition = [
'%sclass %s(ZSI.TCcompound.ComplexType, TypeDefinition):'
% (ID1, self.getClassName()),
'%s%s' % (ID2, self.schemaTag()),
'%s%s' % (ID2, self.typeTag()),
'%s%s' % (ID2, self.pnameConstructor()),
#'%s' % self.getElements(),
'%s%s' % (ID3, self.nsuriLogic()),
'%sTClist = [%s]' % (ID3, self.getTypecodeList()),
]
except Exception, ex:
args = ["Failure processing %s" %self._item.getItemTrace()]
args += ex.args
ex.args = tuple(args)
raise
definition.append('%s%s = attributes or {}' %(ID3,
self.attribute_typecode))
# IF EXTEND
definition.append('%sif extend: TClist += ofwhat'%(ID3))
# IF RESTRICT
definition.append('%sif restrict: TClist = ofwhat' %(ID3))
# ELSE
if len(self.attrComponents) > 0:
definition.append('%selse:' %(ID3))
for l in self.attrComponents: definition.append('%s%s'%(ID4, l))
definition.append(\
'%sZSI.TCcompound.ComplexType.__init__(self, None, TClist, pname=pname, inorder=0, %s**kw)' \
%(ID3, self.getExtraFlags())
)
# pyclass class definition
definition += self.getPyClassDefinition()
# set pyclass
kw = KW.copy()
kw['pyclass'] = self.getPyClass()
definition.append('%(ID3)sself.pyclass = %(pyclass)s' %kw)
self.writeArray(definition)
def pnameConstructor(self, superclass=None):
''' TODO: Logic is a little tricky. If superclass is ComplexType this is not used.
'''
if superclass:
return '%s.__init__(self, pname, ofwhat=(), attributes=None, extend=False, restrict=False, **kw)' % superclass
return 'def __init__(self, pname, ofwhat=(), attributes=None, extend=False, restrict=False, **kw):'
class SimpleTypeContainer(TypecodeContainerBase):
type = DEF
logger = _GetLogger("SimpleTypeContainer")
def __init__(self):
'''
Instance Data From TypecodeContainerBase NOT USED...
mgContent
'''
TypecodeContainerBase.__init__(self)
def setUp(self, tp):
raise NotImplementedError, 'abstract method not implemented'
def _setContent(self, tp):
raise NotImplementedError, 'abstract method not implemented'
def getPythonType(self):
pyclass = eval(str(self.sKlass))
if issubclass(pyclass, ZSI.TC.String):
return 'str'
if issubclass(pyclass, ZSI.TC.Ilong) or issubclass(pyclass, ZSI.TC.IunsignedLong):
return 'long'
if issubclass(pyclass, ZSI.TC.Boolean) or issubclass(pyclass, ZSI.TC.Integer):
return 'int'
if issubclass(pyclass, ZSI.TC.Decimal):
return 'float'
if issubclass(pyclass, ZSI.TC.Gregorian) or issubclass(pyclass, ZSI.TC.Duration):
return 'tuple'
return None
def getPyClassDefinition(self):
definition = []
pt = self.getPythonType()
if pt is not None:
definition.append('%sclass %s(%s):' %(ID3,self.getPyClass(),pt))
definition.append('%stypecode = self' %ID4)
return definition
class RestrictionContainer(SimpleTypeContainer):
'''
simpleType/restriction
'''
logger = _GetLogger("RestrictionContainer")
def setUp(self, tp):
self._item = tp
assert tp.isSimple() is True and tp.isDefinition() is True and \
tp.content.isRestriction() is True,\
'expecting simpleType restriction, not: %s' %tp.getItemTrace()
if tp.content is None:
raise Wsdl2PythonError, \
'empty simpleType defintion: %s' %tp.getItemTrace()
self.name = tp.getAttribute('name')
self.ns = tp.getTargetNamespace()
self.sKlass = None
base = tp.content.getAttribute('base')
if base is not None:
try:
item = tp.content.getTypeDefinition('base')
except XMLSchema.SchemaError, ex:
pass
if item is None:
self.sKlass = BTI.get_typeclass(base.getName(), base.getTargetNamespace())
if self.sKlass is not None:
return
raise Wsdl2PythonError('no built-in type nor schema instance type for base attribute("%s","%s"): %s' %(
base.getTargetNamespace(), base.getName(), tp.getItemTrace()))
raise Wsdl2PythonError, \
'Not Supporting simpleType/Restriction w/User-Defined Base: %s %s' %(tp.getItemTrace(),item.getItemTrace())
sc = tp.content.getSimpleTypeContent()
if sc is not None and True is sc.isSimple() is sc.isLocal() is sc.isDefinition():
base = None
if sc.content.isRestriction() is True:
try:
item = tp.content.getTypeDefinition('base')
except XMLSchema.SchemaError, ex:
pass
if item is None:
base = sc.content.getAttribute('base')
if base is not None:
self.sKlass = BTI.get_typeclass(base.getTargetNamespace(), base.getName())
return
raise Wsdl2PythonError, \
'Not Supporting simpleType/Restriction w/User-Defined Base: '\
%item.getItemTrace()
raise Wsdl2PythonError, \
'Not Supporting simpleType/Restriction w/User-Defined Base: '\
%item.getItemTrace()
if sc.content.isList() is True:
raise Wsdl2PythonError, \
'iction base in subtypes: %s'\
%sc.getItemTrace()
if sc.content.isUnion() is True:
raise Wsdl2PythonError, \
'could not get restriction base in subtypes: %s'\
%sc.getItemTrace()
return
raise Wsdl2PythonError, 'No Restriction @base/simpleType: %s' %tp.getItemTrace()
def _setContent(self):
definition = [
'%sclass %s(%s, TypeDefinition):' %(ID1, self.getClassName(),
self.sKlass),
'%s%s' % (ID2, self.schemaTag()),
'%s%s' % (ID2, self.typeTag()),
'%s%s' % (ID2, self.pnameConstructor()),
]
if self.getPythonType() is None:
definition.append('%s%s.__init__(self, pname, **kw)' %(ID3,
self.sKlass))
else:
definition.append('%s%s.__init__(self, pname, pyclass=None, **kw)' \
%(ID3, self.sKlass,))
# pyclass class definition
definition += self.getPyClassDefinition()
# set pyclass
kw = KW.copy()
kw['pyclass'] = self.getPyClass()
definition.append('%(ID3)sself.pyclass = %(pyclass)s' %kw)
self.writeArray(definition)
class ComplexTypeSimpleContentContainer(SimpleTypeContainer, AttributeMixIn):
'''Represents a ComplexType with simpleContent.
'''
type = DEF
logger = _GetLogger("ComplexTypeSimpleContentContainer")
def setUp(self, tp):
'''tp -- complexType/simpleContent/[Exention,Restriction]
'''
self._item = tp
assert tp.isComplex() is True and tp.content.isSimple() is True,\
'expecting complexType/simpleContent not: %s' %tp.content.getItemTrace()
simple = tp.content
dv = simple.content
assert dv.isExtension() is True or dv.isRestriction() is True,\
'expecting complexType/simpleContent/[Extension,Restriction] not: %s' \
%tp.content.getItemTrace()
self.name = tp.getAttribute('name')
self.ns = tp.getTargetNamespace()
# TODO: Why is this being set?
self.content.attributeContent = dv.getAttributeContent()
base = dv.getAttribute('base')
if base is not None:
self.sKlass = BTI.get_typeclass( base[1], base[0] )
if not self.sKlass:
self.sKlass,self.sKlassNS = base[1], base[0]
self.attrComponents = self._setAttributes(
self.content.attributeContent
)
return
raise Wsdl2PythonError,\
'simple content derivation bad base attribute: ' %tp.getItemTrace()
def _setContent(self):
# TODO: Add derivation logic to constructors.
if type(self.sKlass) in (types.ClassType, type):
definition = [
'%sclass %s(%s, TypeDefinition):' \
% (ID1, self.getClassName(), self.sKlass),
'%s# ComplexType/SimpleContent derivation of built-in type' %ID2,
'%s%s' % (ID2, self.schemaTag()),
'%s%s' % (ID2, self.typeTag()),
'%s%s' % (ID2, self.pnameConstructor()),
'%sif getattr(self, "attribute_typecode_dict", None) is None: %s = {}' %(
ID3, self.attribute_typecode),
]
for l in self.attrComponents:
definition.append('%s%s'%(ID3, l))
definition.append('%s%s.__init__(self, pname, **kw)' %(ID3, self.sKlass))
if self.getPythonType() is not None:
definition += self.getPyClassDefinition()
kw = KW.copy()
kw['pyclass'] = self.getPyClass()
definition.append('%(ID3)sself.pyclass = %(pyclass)s' %kw)
self.writeArray(definition)
return
definition = [
'%sclass %s(TypeDefinition):' % (ID1, self.getClassName()),
'%s# ComplexType/SimpleContent derivation of user-defined type' %ID2,
'%s%s' % (ID2, self.schemaTag()),
'%s%s' % (ID2, self.typeTag()),
'%s%s' % (ID2, self.pnameConstructor()),
'%s%s' % (ID3, self.nsuriLogic()),
'%s' % self.getBasesLogic(ID3),
'%sif getattr(self, "attribute_typecode_dict", None) is None: %s = {}' %(
ID3, self.attribute_typecode),
]
for l in self.attrComponents:
definition.append('%s%s'%(ID3, l))
definition.append('%s%s.%s.__init__(self, pname, **kw)' %(
ID3, NAD.getAlias(self.sKlassNS), type_class_name(self.sKlass)))
self.writeArray(definition)
def getPyClassDefinition(self):
definition = []
pt = self.getPythonType()
if pt is not None:
definition.append('%sclass %s(%s):' %(ID3,self.getPyClass(),pt))
if self.metaclass is not None:
definition.append('%s__metaclass__ = %s' %(ID4, self.metaclass))
definition.append('%stypecode = self' %ID4)
return definition
class UnionContainer(SimpleTypeContainer):
'''SimpleType Union
'''
type = DEF
logger = _GetLogger("UnionContainer")
def __init__(self):
SimpleTypeContainer.__init__(self)
self.memberTypes = None
def setUp(self, tp):
self._item = tp
if tp.content.isUnion() is False:
raise ContainerError, 'content must be a Union: %s' %tp.getItemTrace()
self.name = tp.getAttribute('name')
self.ns = tp.getTargetNamespace()
self.sKlass = 'ZSI.TC.Union'
self.memberTypes = tp.content.getAttribute('memberTypes')
def _setContent(self):
definition = [
'%sclass %s(%s, TypeDefinition):' \
% (ID1, self.getClassName(), self.sKlass),
'%smemberTypes = %s' % (ID2, self.memberTypes),
'%s%s' % (ID2, self.schemaTag()),
'%s%s' % (ID2, self.typeTag()),
'%s%s' % (ID2, self.pnameConstructor()),
'%s%s' % (ID3, self.pnameConstructor(self.sKlass)),
]
# TODO: Union pyclass is None
self.writeArray(definition)
class ListContainer(SimpleTypeContainer):
'''SimpleType List
'''
type = DEF
logger = _GetLogger("ListContainer")
def setUp(self, tp):
self._item = tp
if tp.content.isList() is False:
raise ContainerError, 'content must be a List: %s' %tp.getItemTrace()
self.name = tp.getAttribute('name')
self.ns = tp.getTargetNamespace()
self.sKlass = 'ZSI.TC.List'
self.itemType = tp.content.getAttribute('itemType')
def _setContent(self):
definition = [
'%sclass %s(%s, TypeDefinition):' \
% (ID1, self.getClassName(), self.sKlass),
'%sitemType = %s' % (ID2, self.itemType),
'%s%s' % (ID2, self.schemaTag()),
'%s%s' % (ID2, self.typeTag()),
'%s%s' % (ID2, self.pnameConstructor()),
'%s%s' % (ID3, self.pnameConstructor(self.sKlass)),
]
self.writeArray(definition) | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/generate/containers.py | containers.py |
import pydoc, sys, warnings
from ZSI import TC
# If function.__name__ is read-only, fail
def _x(): return
try:
_x.func_name = '_y'
except:
raise RuntimeError,\
'use python-2.4 or later, cannot set function names in python "%s"'\
%sys.version
del _x
#def GetNil(typecode=None):
# """returns the nilled element, use to set an element
# as nilled for immutable instance.
# """
#
# nil = TC.Nilled()
# if typecode is not None: nil.typecode = typecode
# return nil
#
#
#def GetNilAsSelf(cls, typecode=None):
# """returns the nilled element with typecode specified,
# use returned instance to set this element as nilled.
#
# Key Word Parameters:
# typecode -- use to specify a derived type or wildcard as nilled.
# """
# if typecode is not None and not isinstance(typecode, TC.TypeCode):
# raise TypeError, "Expecting a TypeCode instance"
#
# nil = TC.Nilled()
# nil.typecode = typecode or cls.typecode
# return nil
class pyclass_type(type):
"""Stability: Unstable
type for pyclasses used with typecodes. expects the typecode to
be available in the classdict. creates python properties for accessing
and setting the elements specified in the ofwhat list, and factory methods
for constructing the elements.
Known Limitations:
1)Uses XML Schema element names directly to create method names,
using characters in this set will cause Syntax Errors:
(NCNAME)-(letter U digit U "_")
"""
def __new__(cls, classname, bases, classdict):
"""
"""
#import new
typecode = classdict.get('typecode')
assert typecode is not None, 'MUST HAVE A TYPECODE.'
# Assume this means immutable type. ie. str
if len(bases) > 0:
#classdict['new_Nill'] = classmethod(GetNilAsSelf)
pass
# Assume this means mutable type. ie. ofwhat.
else:
assert hasattr(typecode, 'ofwhat'), 'typecode has no ofwhat list??'
assert hasattr(typecode, 'attribute_typecode_dict'),\
'typecode has no attribute_typecode_dict??'
#classdict['new_Nill'] = staticmethod(GetNil)
if typecode.mixed:
get,set = cls.__create_text_functions_from_what(typecode)
if classdict.has_key(get.__name__):
raise AttributeError,\
'attribute %s previously defined.' %get.__name__
if classdict.has_key(set.__name__):
raise AttributeError,\
'attribute %s previously defined.' %set.__name__
classdict[get.__name__] = get
classdict[set.__name__] = set
for what in typecode.ofwhat:
get,set,new_func = cls.__create_functions_from_what(what)
if classdict.has_key(get.__name__):
raise AttributeError,\
'attribute %s previously defined.' %get.__name__
classdict[get.__name__] = get
if classdict.has_key(set.__name__):
raise AttributeError,\
'attribute %s previously defined.' %set.__name__
classdict[set.__name__] = set
if new_func is not None:
if classdict.has_key(new_func.__name__):
raise AttributeError,\
'attribute %s previously defined.' %new_func.__name__
classdict[new_func.__name__] = new_func
assert not classdict.has_key(what.pname),\
'collision with pname="%s", bail..' %what.pname
pname = what.pname
if pname is None and isinstance(what, TC.AnyElement): pname = 'any'
assert pname is not None, 'Element with no name: %s' %what
# TODO: for pname if keyword just uppercase first letter.
#if pydoc.Helper.keywords.has_key(pname):
pname = pname[0].upper() + pname[1:]
assert not pydoc.Helper.keywords.has_key(pname), 'unexpected keyword: %s' %pname
classdict[pname] =\
property(get, set, None,
'property for element (%s,%s), minOccurs="%s" maxOccurs="%s" nillable="%s"'\
%(what.nspname,what.pname,what.minOccurs,what.maxOccurs,what.nillable)
)
#
# mutable type <complexType> complexContent | modelGroup
# or immutable type <complexType> simpleContent (float, str, etc)
#
if hasattr(typecode, 'attribute_typecode_dict'):
attribute_typecode_dict = typecode.attribute_typecode_dict or {}
for key,what in attribute_typecode_dict.items():
get,set = cls.__create_attr_functions_from_what(key, what)
if classdict.has_key(get.__name__):
raise AttributeError,\
'attribute %s previously defined.' %get.__name__
if classdict.has_key(set.__name__):
raise AttributeError,\
'attribute %s previously defined.' %set.__name__
classdict[get.__name__] = get
classdict[set.__name__] = set
return type.__new__(cls,classname,bases,classdict)
def __create_functions_from_what(what):
if not callable(what):
def get(self):
return getattr(self, what.aname)
if what.maxOccurs > 1:
def set(self, value):
if not (value is None or hasattr(value, '__iter__')):
raise TypeError, 'expecting an iterable instance'
setattr(self, what.aname, value)
else:
def set(self, value):
setattr(self, what.aname, value)
else:
def get(self):
return getattr(self, what().aname)
if what.maxOccurs > 1:
def set(self, value):
if not (value is None or hasattr(value, '__iter__')):
raise TypeError, 'expecting an iterable instance'
setattr(self, what().aname, value)
else:
def set(self, value):
setattr(self, what().aname, value)
#
# new factory function
# if pyclass is None, skip
#
if not callable(what) and getattr(what, 'pyclass', None) is None:
new_func = None
elif (isinstance(what, TC.ComplexType) or
isinstance(what, TC.Array)):
def new_func(self):
'''returns a mutable type
'''
return what.pyclass()
elif not callable(what):
def new_func(self, value):
'''value -- initialize value
returns an immutable type
'''
return what.pyclass(value)
elif (issubclass(what.klass, TC.ComplexType) or
issubclass(what.klass, TC.Array)):
def new_func(self):
'''returns a mutable type or None (if no pyclass).
'''
p = what().pyclass
if p is None: return
return p()
else:
def new_func(self, value=None):
'''if simpleType provide initialization value, else
if complexType value should be left as None.
Parameters:
value -- initialize value or None
returns a mutable instance (value is None)
or an immutable instance or None (if no pyclass)
'''
p = what().pyclass
if p is None: return
if value is None: return p()
return p(value)
#TODO: sub all illegal characters in set
# (NCNAME)-(letter U digit U "_")
if new_func is not None:
new_func.__name__ = 'new_%s' %what.pname
get.func_name = 'get_element_%s' %what.pname
set.func_name = 'set_element_%s' %what.pname
return get,set,new_func
__create_functions_from_what = staticmethod(__create_functions_from_what)
def __create_attr_functions_from_what(key, what):
def get(self):
'''returns attribute value for attribute %s, else None.
''' %str(key)
return getattr(self, what.attrs_aname, {}).get(key, None)
def set(self, value):
'''set value for attribute %s.
value -- initialize value, immutable type
''' %str(key)
if not hasattr(self, what.attrs_aname):
setattr(self, what.attrs_aname, {})
getattr(self, what.attrs_aname)[key] = value
#TODO: sub all illegal characters in set
# (NCNAME)-(letter U digit U "_")
if type(key) in (tuple, list):
get.__name__ = 'get_attribute_%s' %key[1]
set.__name__ = 'set_attribute_%s' %key[1]
else:
get.__name__ = 'get_attribute_%s' %key
set.__name__ = 'set_attribute_%s' %key
return get,set
__create_attr_functions_from_what = \
staticmethod(__create_attr_functions_from_what)
def __create_text_functions_from_what(what):
def get(self):
'''returns text content, else None.
'''
return getattr(self, what.mixed_aname, None)
get.im_func = 'get_text'
def set(self, value):
'''set text content.
value -- initialize value, immutable type
'''
setattr(self, what.mixed_aname, value)
get.im_func = 'set_text'
return get,set
__create_text_functions_from_what = \
staticmethod(__create_text_functions_from_what) | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/generate/pyclass.py | pyclass.py |
import exceptions, sys, optparse, os, warnings
from operator import xor
import ZSI
from ConfigParser import ConfigParser
from ZSI.generate.wsdl2python import WriteServiceModule, ServiceDescription
from ZSI.wstools import WSDLTools, XMLSchema
from ZSI.wstools.logging import setBasicLoggerDEBUG
from ZSI.generate import containers, utility
from ZSI.generate.utility import NCName_to_ClassName as NC_to_CN, TextProtect
from ZSI.generate.wsdl2dispatch import ServiceModuleWriter as ServiceDescription
from ZSI.generate.wsdl2dispatch import DelAuthServiceModuleWriter as DelAuthServiceDescription
from ZSI.generate.wsdl2dispatch import WSAServiceModuleWriter as ServiceDescriptionWSA
from ZSI.generate.wsdl2dispatch import DelAuthWSAServiceModuleWriter as DelAuthServiceDescriptionWSA
warnings.filterwarnings('ignore', '', exceptions.UserWarning)
def SetDebugCallback(option, opt, value, parser, *args, **kwargs):
setBasicLoggerDEBUG()
warnings.resetwarnings()
def SetPyclassMetaclass(option, opt, value, parser, *args, **kwargs):
"""set up pyclass metaclass for complexTypes"""
from ZSI.generate.containers import ServiceHeaderContainer, TypecodeContainerBase, TypesHeaderContainer
TypecodeContainerBase.metaclass = kwargs['metaclass']
TypesHeaderContainer.imports.append(\
'from %(module)s import %(metaclass)s' %kwargs
)
ServiceHeaderContainer.imports.append(\
'from %(module)s import %(metaclass)s' %kwargs
)
def SetUpTwistedClient(option, opt, value, parser, *args, **kwargs):
from ZSI.generate.containers import ServiceHeaderContainer
ServiceHeaderContainer.imports.remove('from ZSI import client')
ServiceHeaderContainer.imports.append('from ZSI.twisted import client')
def SetUpLazyEvaluation(option, opt, value, parser, *args, **kwargs):
from ZSI.generate.containers import TypecodeContainerBase
TypecodeContainerBase.lazy = True
def formatSchemaObject(fname, schemaObj):
""" In the case of a 'schema only' generation (-s) this creates
a fake wsdl object that will function w/in the adapters
and allow the generator to do what it needs to do.
"""
class fake:
pass
f = fake()
if fname.rfind('/'):
tmp = fname[fname.rfind('/') + 1 :].split('.')
else:
tmp = fname.split('.')
f.name = tmp[0] + '_' + tmp[1]
f.types = { schemaObj.targetNamespace : schemaObj }
return f
def wsdl2py(args=None):
"""
A utility for automatically generating client interface code from a wsdl
definition, and a set of classes representing element declarations and
type definitions. This will produce two files in the current working
directory named after the wsdl definition name.
eg. <definition name='SampleService'>
SampleService.py
SampleService_types.py
"""
op = optparse.OptionParser(usage="usage: %prog [options]",
description=wsdl2py.__doc__)
# Basic options
op.add_option("-f", "--file",
action="store", dest="file", default=None, type="string",
help="FILE to load wsdl from")
op.add_option("-u", "--url",
action="store", dest="url", default=None, type="string",
help="URL to load wsdl from")
op.add_option("-x", "--schema",
action="store_true", dest="schema", default=False,
help="process just the schema from an xsd file [no services]")
op.add_option("-d", "--debug",
action="callback", callback=SetDebugCallback,
help="debug output")
# WS Options
op.add_option("-a", "--address",
action="store_true", dest="address", default=False,
help="ws-addressing support, must include WS-Addressing schema.")
# pyclass Metaclass
op.add_option("-b", "--complexType",
action="callback", callback=SetPyclassMetaclass,
callback_kwargs={'module':'ZSI.generate.pyclass',
'metaclass':'pyclass_type'},
help="add convenience functions for complexTypes, including Getters, Setters, factory methods, and properties (via metaclass). *** DONT USE WITH --simple-naming ***")
# Lazy Evaluation of Typecodes (done at serialization/parsing when needed).
op.add_option("-l", "--lazy",
action="callback", callback=SetUpLazyEvaluation,
callback_kwargs={},
help="EXPERIMENTAL: recursion error solution, lazy evalution of typecodes")
# Use Twisted
op.add_option("-w", "--twisted",
action="callback", callback=SetUpTwistedClient,
callback_kwargs={'module':'ZSI.generate.pyclass',
'metaclass':'pyclass_type'},
help="generate a twisted.web client, dependencies python>=2.4, Twisted>=2.0.0, TwistedWeb>=0.5.0")
# Extended generation options
op.add_option("-e", "--extended",
action="store_true", dest="extended", default=False,
help="Do Extended code generation.")
op.add_option("-z", "--aname",
action="store", dest="aname", default=None, type="string",
help="pass in a function for attribute name creation")
op.add_option("-t", "--types",
action="store", dest="types", default=None, type="string",
help="file to load types from")
op.add_option("-o", "--output-dir",
action="store", dest="output_dir", default=".", type="string",
help="Write generated files to OUTPUT_DIR")
op.add_option("-s", "--simple-naming",
action="store_true", dest="simple_naming", default=False,
help="Simplify generated naming.")
op.add_option("-c", "--clientClassSuffix",
action="store", dest="clientClassSuffix", default=None, type="string",
help="Suffix to use for service client class (default \"SOAP\")")
op.add_option("-m", "--pyclassMapModule",
action="store", dest="pyclassMapModule", default=None, type="string",
help="Python file that maps external python classes to a schema type. The classes are used as the \"pyclass\" for that type. The module should contain a dict() called mapping in the format: mapping = {schemaTypeName:(moduleName.py,className) }")
if args is None:
(options, args) = op.parse_args()
else:
(options, args) = op.parse_args(args)
if not xor(options.file is None, options.url is None):
print 'Must specify either --file or --url option'
sys.exit(os.EX_USAGE)
location = options.file
if options.url is not None:
location = options.url
if options.schema is True:
reader = XMLSchema.SchemaReader(base_url=location)
else:
reader = WSDLTools.WSDLReader()
load = reader.loadFromFile
if options.url is not None:
load = reader.loadFromURL
wsdl = None
try:
wsdl = load(location)
except Exception, e:
print "Error loading %s: \n\t%s" % (location, e)
# exit code UNIX specific, Windows?
sys.exit(os.EX_NOINPUT)
if options.simple_naming:
# Use a different client suffix
WriteServiceModule.client_module_suffix = "_client"
# Write messages definitions to a separate file.
ServiceDescription.separate_messages = True
# Use more simple type and element class names
containers.SetTypeNameFunc( lambda n: '%s_' %(NC_to_CN(n)) )
containers.SetElementNameFunc( lambda n: '%s' %(NC_to_CN(n)) )
# Don't add "_" to the attribute name (remove when --aname works well)
containers.ContainerBase.func_aname = lambda instnc,n: TextProtect(str(n))
# write out the modules with their names rather than their number.
utility.namespace_name = lambda cls, ns: utility.Namespace2ModuleName(ns)
if options.clientClassSuffix:
from ZSI.generate.containers import ServiceContainerBase
ServiceContainerBase.clientClassSuffix = options.clientClassSuffix
if options.schema is True:
wsdl = formatSchemaObject(location, wsdl)
if options.aname is not None:
args = options.aname.rsplit('.',1)
assert len(args) == 2, 'expecting module.function'
# The following exec causes a syntax error.
#exec('from %s import %s as FUNC' %(args[0],args[1]))
assert callable(FUNC),\
'%s must be a callable method with one string parameter' %options.aname
from ZSI.generate.containers import TypecodeContainerBase
TypecodeContainerBase.func_aname = staticmethod(FUNC)
if options.pyclassMapModule != None:
mod = __import__(options.pyclassMapModule)
components = options.pyclassMapModule.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
extPyClasses = mod.mapping
else:
extPyClasses = None
wsm = WriteServiceModule(wsdl, addressing=options.address, do_extended=options.extended, extPyClasses=extPyClasses)
if options.types != None:
wsm.setTypesModuleName(options.types)
if options.schema is False:
fd = open(os.path.join(options.output_dir, '%s.py' %wsm.getClientModuleName()), 'w+')
# simple naming writes the messages to a separate file
if not options.simple_naming:
wsm.writeClient(fd)
else: # provide a separate file to store messages to.
msg_fd = open(os.path.join(options.output_dir, '%s.py' %wsm.getMessagesModuleName()), 'w+')
wsm.writeClient(fd, msg_fd=msg_fd)
msg_fd.close()
fd.close()
fd = open( os.path.join(options.output_dir, '%s.py' %wsm.getTypesModuleName()), 'w+')
wsm.writeTypes(fd)
fd.close()
def wsdl2dispatch(args=None):
"""
wsdl2dispatch
A utility for automatically generating service skeleton code from a wsdl
definition.
"""
op = optparse.OptionParser()
op.add_option("-f", "--file",
action="store", dest="file", default=None, type="string",
help="file to load wsdl from")
op.add_option("-u", "--url",
action="store", dest="url", default=None, type="string",
help="URL to load wsdl from")
op.add_option("-a", "--address",
action="store_true", dest="address", default=False,
help="ws-addressing support, must include WS-Addressing schema.")
op.add_option("-e", "--extended",
action="store_true", dest="extended", default=False,
help="Extended code generation.")
op.add_option("-d", "--debug",
action="callback", callback=SetDebugCallback,
help="debug output")
op.add_option("-t", "--types",
action="store", dest="types", default=None, type="string",
help="Write generated files to OUTPUT_DIR")
op.add_option("-o", "--output-dir",
action="store", dest="output_dir", default=".", type="string",
help="file to load types from")
op.add_option("-s", "--simple-naming",
action="store_true", dest="simple_naming", default=False,
help="Simplify generated naming.")
if args is None:
(options, args) = op.parse_args()
else:
(options, args) = op.parse_args(args)
if options.simple_naming:
ServiceDescription.server_module_suffix = '_interface'
ServiceDescription.func_aname = lambda instnc,n: TextProtect(n)
ServiceDescription.separate_messages = True
# use module names rather than their number.
utility.namespace_name = lambda cls, ns: utility.Namespace2ModuleName(ns)
reader = WSDLTools.WSDLReader()
wsdl = None
if options.file is not None:
wsdl = reader.loadFromFile(options.file)
elif options.url is not None:
wsdl = reader.loadFromURL(options.url)
assert wsdl is not None, 'Must specify WSDL either with --file or --url'
ss = None
if options.address is True:
if options.extended:
ss = DelAuthServiceDescriptionWSA(do_extended=options.extended)
else:
ss = ServiceDescriptionWSA(do_extended=options.extended)
else:
if options.extended:
ss = DelAuthServiceDescription(do_extended=options.extended)
else:
ss = ServiceDescription(do_extended=options.extended)
ss.fromWSDL(wsdl)
fd = open( os.path.join(options.output_dir, ss.getServiceModuleName()+'.py'), 'w+')
ss.write(fd)
fd.close() | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/generate/commands.py | commands.py |
# main generator engine for new generation generator
# $Id: wsdl2python.py 1203 2006-05-03 00:13:20Z boverhof $
import os
from ZSI import _get_idstr
from ZSI.wstools.logging import getLogger as _GetLogger
from ZSI.wstools import WSDLTools
from ZSI.wstools.WSDLTools import SoapAddressBinding,\
SoapBodyBinding, SoapBinding,MimeContentBinding,\
HttpUrlEncodedBinding
from ZSI.wstools.XMLSchema import SchemaReader, ElementDeclaration, SchemaError
from ZSI.typeinterpreter import BaseTypeInterpreter
from ZSI.generate import WsdlGeneratorError, Wsdl2PythonError
from containers import *
from ZSI.generate import utility
from ZSI.generate.utility import NamespaceAliasDict as NAD
from ZSI.generate.utility import GetModuleBaseNameFromWSDL
"""
classes:
WriteServiceModule
-- composes/writes out client stubs and types module.
ServiceDescription
-- represents a single WSDL service.
MessageWriter
-- represents a single WSDL Message and associated bindings
of the port/binding.
SchemaDescription
-- generates classes for defs and decs in the schema instance.
TypeWriter
-- represents a type definition.
ElementWriter
-- represents a element declaration.
"""
class WriteServiceModule:
"""top level driver class invoked by wsd2py
class variables:
client_module_suffix -- suffix of client module.
types_module_suffix -- suffix of types module.
"""
client_module_suffix = '_services'
messages_module_suffix = '_messages'
types_module_suffix = '_services_types'
logger = _GetLogger("WriteServiceModule")
def __init__(self, wsdl, addressing=False, notification=False,
do_extended=False, extPyClasses=None, configParser = None):
self._wsdl = wsdl
self._addressing = addressing
self._notification = notification
self._configParser = configParser
self.usedNamespaces = None
self.services = []
self.client_module_path = None
self.types_module_name = None
self.types_module_path = None
self.messages_module_path = None # used in extended generation
self.do_extended = do_extended
self.extPyClasses = extPyClasses
def getClientModuleName(self):
"""client module name.
"""
name = GetModuleBaseNameFromWSDL(self._wsdl)
if not name:
raise WsdlGeneratorError, 'could not determine a service name'
if self.client_module_suffix is None:
return name
return '%s%s' %(name, self.client_module_suffix)
def getMessagesModuleName(self):
name = GetModuleBaseNameFromWSDL(self._wsdl)
if not name:
raise WsdlGeneratorError, 'could not determine a service name'
if self.messages_module_suffix is None:
return name
if len(self.messages_module_suffix) == 0:
return self.getClientModuleName()
return '%s%s' %(name, self.messages_module_suffix)
def setTypesModuleName(self, name):
self.types_module_name = name
def getTypesModuleName(self):
"""types module name.
"""
if self.types_module_name is not None:
return self.types_module_name
name = GetModuleBaseNameFromWSDL(self._wsdl)
if not name:
raise WsdlGeneratorError, 'could not determine a service name'
if self.types_module_suffix is None:
return name
return '%s%s' %(name, self.types_module_suffix)
def setClientModulePath(self, path):
"""setup module path to where client module before calling fromWsdl.
module path to types module eg. MyApp.client
"""
self.client_module_path = path
def getTypesModulePath(self):
"""module path to types module eg. MyApp.types
"""
return self.types_module_path
def getMessagesModulePath(self):
'''module path to messages module
same as types path
'''
return self.messages_module_path
def setTypesModulePath(self, path):
"""setup module path to where service module before calling fromWsdl.
module path to types module eg. MyApp.types
"""
self.types_module_path = path
def setMessagesModulePath(self, path):
"""setup module path to where message module before calling fromWsdl.
module path to types module eg. MyApp.types
"""
self.messages_module_path = path
def gatherNamespaces(self):
'''This method must execute once.. Grab all schemas
representing each targetNamespace.
'''
if self.usedNamespaces is not None:
return
self.logger.debug('gatherNamespaces')
self.usedNamespaces = {}
# Add all schemas defined in wsdl
# to used namespace and to the Alias dict
for schema in self._wsdl.types.values():
tns = schema.getTargetNamespace()
self.logger.debug('Register schema(%s) -- TNS(%s)'\
%(_get_idstr(schema), tns),)
if self.usedNamespaces.has_key(tns) is False:
self.usedNamespaces[tns] = []
self.usedNamespaces[tns].append(schema)
NAD.add(tns)
# Add all xsd:import schema instances
# to used namespace and to the Alias dict
for k,v in SchemaReader.namespaceToSchema.items():
self.logger.debug('Register schema(%s) -- TNS(%s)'\
%(_get_idstr(v), k),)
if self.usedNamespaces.has_key(k) is False:
self.usedNamespaces[k] = []
self.usedNamespaces[k].append(v)
NAD.add(k)
def writeClient(self, fd, sdClass=None, msg_fd=None, **kw):
"""write out client module to file descriptor.
Parameters and Keywords arguments:
fd -- file descriptor
msg_fd -- optional messsages module file descriptor
sdClass -- service description class name
imports -- list of imports
readerclass -- class name of ParsedSoap reader
writerclass -- class name of SoapWriter writer
"""
sdClass = sdClass or ServiceDescription
assert issubclass(sdClass, ServiceDescription), \
'parameter sdClass must subclass ServiceDescription'
header = '%s \n# %s.py \n# generated by %s\n%s\n\n'\
%('#'*50, self.getClientModuleName(), self.__module__, '#'*50)
fd.write(header)
if msg_fd is not None:
# TODO: Why is this not getMessagesModuleName?
msg_filename = str(self.getClientModuleName()).replace("client", "messages")
if self.getMessagesModulePath() is not None:
msg_filename = os.path.join(self.getMessagesModulePath(), msg_filename)
messages_header = header.replace("client", "messages")
msg_fd.write(messages_header)
self.services = []
for service in self._wsdl.services:
sd = sdClass(self._addressing, do_extended=self.do_extended, wsdl=self._wsdl)
if len(self._wsdl.types) > 0:
sd.setTypesModuleName(self.getTypesModuleName(), self.getTypesModulePath())
sd.setMessagesModuleName(self.getMessagesModuleName(), self.getMessagesModulePath())
self.gatherNamespaces()
sd.fromWsdl(service, **kw)
sd.write(fd,msg_fd)
self.services.append(sd)
def writeTypes(self, fd):
"""write out types module to file descriptor.
"""
header = '%s \n# %s.py \n# generated by %s\n%s\n\n'\
%('#'*50, self.getTypesModuleName(), self.__module__, '#'*50)
fd.write(header)
print >>fd, TypesHeaderContainer()
self.gatherNamespaces()
for l in self.usedNamespaces.values():
sd = SchemaDescription(do_extended=self.do_extended, extPyClasses=self.extPyClasses)
for schema in l:
sd.fromSchema(schema)
sd.write(fd)
class ServiceDescription:
"""client interface - locator, port, etc classes"""
separate_messages = False
logger = _GetLogger("ServiceDescription")
def __init__(self, addressing=False, do_extended=False, wsdl=None):
self.typesModuleName = None
self.messagesModuleName = None
self.wsAddressing = addressing
self.imports = ServiceHeaderContainer()
self.messagesImports = ServiceHeaderContainer()
self.locator = ServiceLocatorContainer()
self.methods = []
self.messages = []
self.do_extended=do_extended
self._wsdl = wsdl # None unless do_extended == True
def setTypesModuleName(self, name, modulePath=None):
"""The types module to be imported.
Parameters
name -- name of types module
modulePath -- optional path where module is located.
"""
self.typesModuleName = '%s' %name
if modulePath is not None:
self.typesModuleName = '%s.%s' %(modulePath,name)
def setMessagesModuleName(self, name, modulePath=None):
'''The types module to be imported.
Parameters
name -- name of types module
modulePath -- optional path where module is located.
'''
self.messagesModuleName = '%s' %name
if modulePath is not None:
self.messagesModuleName = '%s.%s' %(modulePath,name)
def fromWsdl(self, service, **kw):
self.imports.setTypesModuleName(self.typesModuleName)
if self.separate_messages:
self.messagesImports.setMessagesModuleName(self.messagesModuleName)
self.imports.appendImport(kw.get('imports', []))
self.locator.setUp(service)
for port in service.ports:
sop_container = ServiceOperationsClassContainer(useWSA=self.wsAddressing, do_extended=self.do_extended, wsdl=self._wsdl)
try:
sop_container.setUp(port)
except Wsdl2PythonError, ex:
self.logger.warning('Skipping port(%s)' %port.name)
if len(ex.args):
self.logger.warning(ex.args[0])
else:
sop_container.setReaderClass(kw.get('readerclass'))
sop_container.setWriterClass(kw.get('writerclass'))
for soc in sop_container.operations:
if soc.hasInput() is True:
mw = MessageWriter(do_extended=self.do_extended)
mw.setUp(soc, port, input=True)
self.messages.append(mw)
if soc.hasOutput() is True:
mw = MessageWriter(do_extended=self.do_extended)
mw.setUp(soc, port, input=False)
self.messages.append(mw)
self.methods.append(sop_container)
def write(self, fd, msg_fd=None):
"""write out module to file descriptor.
fd -- file descriptor to write out service description.
msg_fd -- optional file descriptor for messages module.
"""
if msg_fd != None:
print >>fd, self.messagesImports
print >>msg_fd, self.imports
else:
print >>fd, self.imports
print >>fd, self.locator
for m in self.methods:
print >>fd, m
if msg_fd != None:
for m in self.messages:
print >>msg_fd, m
else:
for m in self.messages:
print >>fd, m
class MessageWriter:
logger = _GetLogger("MessageWriter")
def __init__(self, do_extended=False):
"""Representation of a WSDL Message and associated WSDL Binding.
operation --
boperation --
input --
rpc --
literal --
simple --
"""
self.content = None
self.do_extended = do_extended
def __str__(self):
if not self.content:
raise Wsdl2PythonError, 'Must call setUp.'
return self.content.getvalue()
def setUp(self, soc, port, input=False):
assert isinstance(soc, ServiceOperationContainer),\
'expecting a ServiceOperationContainer instance'
assert isinstance(port, WSDLTools.Port),\
'expecting a WSDL.Port instance'
rpc,literal = soc.isRPC(), soc.isLiteral(input)
kw,klass = {}, None
if rpc and literal:
klass = ServiceRPCLiteralMessageContainer
elif not rpc and literal:
kw['do_extended'] = self.do_extended
klass = ServiceDocumentLiteralMessageContainer
elif rpc and not literal:
klass = ServiceRPCEncodedMessageContainer
else:
raise WsdlGeneratorError, 'doc/enc not supported.'
self.content = klass(**kw)
self.content.setUp(port, soc, input)
class SchemaDescription:
"""generates classes for defs and decs in the schema instance.
"""
logger = _GetLogger("SchemaDescription")
def __init__(self, do_extended=False, extPyClasses=None):
self.classHead = NamespaceClassHeaderContainer()
self.classFoot = NamespaceClassFooterContainer()
self.items = []
self.__types = []
self.__elements = []
self.targetNamespace = None
self.do_extended=do_extended
self.extPyClasses = extPyClasses
def fromSchema(self, schema):
''' Can be called multiple times, but will not redefine a
previously defined type definition or element declaration.
'''
ns = schema.getTargetNamespace()
assert self.targetNamespace is None or self.targetNamespace == ns,\
'SchemaDescription instance represents %s, not %s'\
%(self.targetNamespace, ns)
if self.targetNamespace is None:
self.targetNamespace = ns
self.classHead.ns = self.classFoot.ns = ns
for item in [t for t in schema.types if t.getAttributeName() not in self.__types]:
self.__types.append(item.getAttributeName())
self.items.append(TypeWriter(do_extended=self.do_extended, extPyClasses=self.extPyClasses))
self.items[-1].fromSchemaItem(item)
for item in [e for e in schema.elements if e.getAttributeName() not in self.__elements]:
self.__elements.append(item.getAttributeName())
self.items.append(ElementWriter(do_extended=self.do_extended))
self.items[-1].fromSchemaItem(item)
def getTypes(self):
return self.__types
def getElements(self):
return self.__elements
def write(self, fd):
"""write out to file descriptor.
"""
print >>fd, self.classHead
for t in self.items:
print >>fd, t
print >>fd, self.classFoot
class SchemaItemWriter:
"""contains/generates a single declaration"""
logger = _GetLogger("SchemaItemWriter")
def __init__(self, do_extended=False, extPyClasses=None):
self.content = None
self.do_extended=do_extended
self.extPyClasses=extPyClasses
def __str__(self):
'''this appears to set up whatever is in self.content.localElements,
local elements simpleType|complexType.
'''
assert self.content is not None, 'Must call fromSchemaItem to setup.'
return str(self.content)
def fromSchemaItem(self, item):
raise NotImplementedError, ''
class ElementWriter(SchemaItemWriter):
"""contains/generates a single declaration"""
logger = _GetLogger("ElementWriter")
def fromSchemaItem(self, item):
"""set up global elements.
"""
if item.isElement() is False or item.isLocal() is True:
raise TypeError, 'expecting global element declaration: %s' %item.getItemTrace()
local = False
qName = item.getAttribute('type')
if not qName:
etp = item.content
local = True
else:
etp = item.getTypeDefinition('type')
if etp is None:
if local is True:
self.content = ElementLocalComplexTypeContainer(do_extended=self.do_extended)
else:
self.content = ElementSimpleTypeContainer()
elif etp.isLocal() is False:
self.content = ElementGlobalDefContainer()
elif etp.isSimple() is True:
self.content = ElementLocalSimpleTypeContainer()
elif etp.isComplex():
self.content = ElementLocalComplexTypeContainer(do_extended=self.do_extended)
else:
raise Wsdl2PythonError, "Unknown element declaration: %s" %item.getItemTrace()
self.logger.debug('ElementWriter setUp container "%r", Schema Item "%s"' %(
self.content, item.getItemTrace()))
self.content.setUp(item)
class TypeWriter(SchemaItemWriter):
"""contains/generates a single definition"""
logger = _GetLogger("TypeWriter")
def fromSchemaItem(self, item):
if item.isDefinition() is False or item.isLocal() is True:
raise TypeError, \
'expecting global type definition not: %s' %item.getItemTrace()
self.content = None
if item.isSimple():
if item.content.isRestriction():
self.content = RestrictionContainer()
elif item.content.isUnion():
self.content = UnionContainer()
elif item.content.isList():
self.content = ListContainer()
else:
raise Wsdl2PythonError,\
'unknown simple type definition: %s' %item.getItemTrace()
self.content.setUp(item)
return
if item.isComplex():
kw = {}
if item.content is None or item.content.isModelGroup():
self.content = \
ComplexTypeContainer(\
do_extended=self.do_extended,
extPyClasses=self.extPyClasses
)
kw['empty'] = item.content is None
elif item.content.isSimple():
self.content = ComplexTypeSimpleContentContainer()
elif item.content.isComplex():
self.content = \
ComplexTypeComplexContentContainer(\
do_extended=self.do_extended
)
else:
raise Wsdl2PythonError,\
'unknown complex type definition: %s' %item.getItemTrace()
self.logger.debug('TypeWriter setUp container "%r", Schema Item "%s"' %(
self.content, item.getItemTrace()))
try:
self.content.setUp(item, **kw)
except Exception, ex:
args = ['Failure in setUp: %s' %item.getItemTrace()]
args += ex.args
ex.args = tuple(args)
raise
return
raise TypeError,\
'expecting SimpleType or ComplexType: %s' %item.getItemTrace() | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/generate/wsdl2python.py | wsdl2python.py |
from cStringIO import StringIO
import ZSI, string, sys, getopt, urlparse, types, warnings
from ZSI.wstools import WSDLTools
from ZSI.generate.wsdl2python import WriteServiceModule, MessageTypecodeContainer
from ZSI.ServiceContainer import ServiceSOAPBinding, SimpleWSResource
from ZSI.generate.utility import TextProtect, GetModuleBaseNameFromWSDL, NCName_to_ClassName, GetPartsSubNames, TextProtectAttributeName
from ZSI.generate import WsdlGeneratorError, Wsdl2PythonError
from ZSI.generate.wsdl2python import SchemaDescription
# Split last token
rsplit = lambda x,sep,: (x[:x.rfind(sep)], x[x.rfind(sep)+1:],)
if sys.version_info[0:2] == (2, 4, 0, 'final', 0)[0:2]:
rsplit = lambda x,sep,: x.rsplit(sep, 1)
class SOAPService:
def __init__(self, service):
self.classdef = StringIO()
self.initdef = StringIO()
self.location = ''
self.methods = []
def newMethod(self):
'''name -- operation name
'''
self.methods.append(StringIO())
return self.methods[-1]
class ServiceModuleWriter:
'''Creates a skeleton for a SOAP service instance.
'''
indent = ' '*4
server_module_suffix = '_services_server'
func_aname = TextProtectAttributeName
func_aname = staticmethod(func_aname)
separate_messages = False # Whether to write message definitions into a separate file.
def __init__(self, base=ServiceSOAPBinding, prefix='soap', service_class=SOAPService, do_extended=False):
'''
parameters:
base -- either a class definition, or a str representing a qualified class name.
prefix -- method prefix.
'''
self.wsdl = None
self.base_class = base
self.method_prefix = prefix
self._service_class = SOAPService
self.header = None
self.imports = None
self._services = None
self.client_module_path = None
self.client_module_name = None
self.messages_module_name = None
self.do_extended = do_extended
def reset(self):
self.header = StringIO()
self.imports = StringIO()
self._services = {}
def _getBaseClassName(self):
'''return base class name, do not override.
'''
if type(self.base_class) is types.ClassType:
return self.base_class.__name__
return rsplit(self.base_class, '.')[-1]
def _getBaseClassModule(self):
'''return base class module, do not override.
'''
if type(self.base_class) is types.ClassType:
return self.base_class.__module__
if self.base_class.find('.') >= 0:
return rsplit(self.base_class, '.')[0]
return None
def getIndent(self, level=1):
'''return indent.
'''
assert 0 < level < 10, 'bad indent level %d' %level
return self.indent*level
def getMethodName(self, method):
'''return method name.
'''
return '%s_%s' %(self.method_prefix, TextProtect(method))
def getClassName(self, name):
'''return class name.
'''
return NCName_to_ClassName(name)
def setClientModuleName(self, name):
self.client_module_name = name
def getClientModuleName(self):
'''return module name.
'''
assert self.wsdl is not None, 'initialize, call fromWSDL'
if self.client_module_name is not None:
return self.client_module_name
wsm = WriteServiceModule(self.wsdl, do_extended=self.do_extended)
return wsm.getClientModuleName()
def getMessagesModuleName(self):
'''return module name.
'''
assert self.wsdl is not None, 'initialize, call fromWSDL'
if self.messages_module_name is not None:
return self.messages_module_name
wsm = WriteServiceModule(self.wsdl, do_extended=self.do_extended)
return wsm.getMessagesModuleName()
def getServiceModuleName(self):
'''return module name.
'''
name = GetModuleBaseNameFromWSDL(self.wsdl)
if not name:
raise WsdlGeneratorError, 'could not determine a service name'
if self.server_module_suffix is None:
return name
return '%s%s' %(name, self.server_module_suffix)
def getClientModulePath(self):
return self.client_module_path
def setClientModulePath(self, path):
'''setup module path to where client module before calling fromWSDL.
'''
self.client_module_path = path
def setUpClassDef(self, service):
'''set class definition and class variables.
service -- ServiceDescription instance
'''
assert isinstance(service, WSDLTools.Service) is True,\
'expecting WSDLTools.Service instance.'
s = self._services[service.name].classdef
print >>s, 'class %s(%s):' %(self.getClassName(service.name), self._getBaseClassName())
print >>s, '%ssoapAction = {}' % self.getIndent(level=1)
print >>s, '%sroot = {}' % self.getIndent(level=1)
print >>s, "%s_wsdl = \"\"\"%s\"\"\"" % (self.getIndent(level=1), self.raw_wsdl)
def setUpImports(self):
'''set import statements
'''
path = self.getClientModulePath()
i = self.imports
if path is None:
if self.separate_messages:
print >>i, 'from %s import *' %self.getMessagesModuleName()
else:
print >>i, 'from %s import *' %self.getClientModuleName()
else:
if self.separate_messages:
print >>i, 'from %s.%s import *' %(path, self.getMessagesModuleName())
else:
print >>i, 'from %s.%s import *' %(path, self.getClientModuleName())
mod = self._getBaseClassModule()
name = self._getBaseClassName()
if mod is None:
print >>i, 'import %s' %name
else:
print >>i, 'from %s import %s' %(mod, name)
def setUpInitDef(self, service):
'''set __init__ function
'''
assert isinstance(service, WSDLTools.Service), 'expecting WSDLTools.Service instance.'
sd = self._services[service.name]
d = sd.initdef
if sd.location is not None:
scheme,netloc,path,params,query,fragment = urlparse.urlparse(sd.location)
print >>d, '%sdef __init__(self, post=\'%s\', **kw):' %(self.getIndent(level=1), path)
else:
print >>d, '%sdef __init__(self, post, **kw):' %self.getIndent(level=1)
print >>d, '%s%s.__init__(self, post)' %(self.getIndent(level=2),self._getBaseClassName())
def mangle(self, name):
return TextProtect(name)
def getAttributeName(self, name):
return self.func_aname(name)
def setUpMethods(self, port):
'''set up all methods representing the port operations.
Parameters:
port -- Port that defines the operations.
'''
assert isinstance(port, WSDLTools.Port), \
'expecting WSDLTools.Port not: ' %type(port)
sd = self._services.get(port.getService().name)
assert sd is not None, 'failed to initialize.'
binding = port.getBinding()
portType = port.getPortType()
action_in = ''
for bop in binding.operations:
try:
op = portType.operations[bop.name]
except KeyError, ex:
raise WsdlGeneratorError,\
'Port(%s) PortType(%s) missing operation(%s) defined in Binding(%s)' \
%(port.name,portType.name,bop.name,binding.name)
for ext in bop.extensions:
if isinstance(ext, WSDLTools.SoapOperationBinding):
action_in = ext.soapAction
break
else:
warnings.warn('Port(%s) operation(%s) defined in Binding(%s) missing soapAction' \
%(port.name,op.name,binding.name)
)
msgin = op.getInputMessage()
msgin_name = TextProtect(msgin.name)
method_name = self.getMethodName(op.name)
m = sd.newMethod()
print >>m, '%sdef %s(self, ps):' %(self.getIndent(level=1), method_name)
if msgin is not None:
print >>m, '%sself.request = ps.Parse(%s.typecode)' %(self.getIndent(level=2), msgin_name)
else:
print >>m, '%s# NO input' %self.getIndent(level=2)
msgout = op.getOutputMessage()
if self.do_extended:
input_args = msgin.parts.values()
iargs = ["%s" % x.name for x in input_args]
if msgout is not None:
output_args = msgout.parts.values()
else:
output_args = []
oargs = ["%s" % x.name for x in output_args]
if output_args:
if len(output_args) > 1:
print "Message has more than one return value (Bad Design)."
output_args = "(%s)" % output_args
else:
output_args = ""
# Get arg list
iSubNames = GetPartsSubNames(msgin.parts.values(), self.wsdl)
for i in range( len(iargs) ): # should only be one part to messages here anyway
argSubNames = iSubNames[i]
if len(argSubNames) > 0:
subNamesStr = "self.request." + ", self.request.".join(map(self.getAttributeName, argSubNames))
if len(argSubNames) > 1:
subNamesStr = "(" + subNamesStr + ")"
print >>m, "%s%s = %s" % (self.getIndent(level=2), iargs[i], subNamesStr)
print >>m, "\n%s# If we have an implementation object use it" % (self.getIndent(level=2))
print >>m, "%sif hasattr(self,'impl'):" % (self.getIndent(level=2))
iargsStrList = []
for arg in iargs:
argSubNames = iSubNames[i]
if len(argSubNames) > 0:
if len(argSubNames) > 1:
for i in range(len(argSubNames)):
iargsStrList.append( arg + "[%i]" % i )
else:
iargsStrList.append( arg )
iargsStr = ",".join(iargsStrList)
oargsStr = ", ".join(oargs)
if len(oargsStr) > 0:
oargsStr += " = "
print >>m, "%s%sself.impl.%s(%s)" % (self.getIndent(level=3), oargsStr, op.name, iargsStr)
if msgout is not None:
msgout_name = TextProtect(msgout.name)
if self.do_extended:
print >>m, '\n%sresult = %s()' %(self.getIndent(level=2), msgout_name)
oSubNames = GetPartsSubNames(msgout.parts.values(), self.wsdl)
if (len(oSubNames) > 0) and (len(oSubNames[0]) > 0):
print >>m, "%s# If we have an implementation object, copy the result " % (self.getIndent(level=2))
print >>m, "%sif hasattr(self,'impl'):" % (self.getIndent(level=2))
# copy result's members
for i in range( len(oargs) ): # should only be one part messages here anyway
oargSubNames = oSubNames[i]
if len(oargSubNames) > 1:
print >>m, '%s# Should have a tuple of %i args' %(self.getIndent(level=3), len(oargSubNames))
for j in range(len(oargSubNames)):
oargSubName = oargSubNames[j]
print >>m, '%sresult.%s = %s[%i]' %(self.getIndent(level=3), self.getAttributeName(oargSubName), oargs[i], j)
elif len(oargSubNames) == 1:
oargSubName = oargSubNames[0]
print >>m, '%sresult.%s = %s' %(self.getIndent(level=3), self.getAttributeName(oargSubName), oargs[i])
else:
raise Exception("The subnames within message " + msgout_name + "'s part were not found. Message is the output of operation " + op.name)
print >>m, '%sreturn result' %(self.getIndent(level=2))
else:
print >>m, '%sreturn %s()' %(self.getIndent(level=2), msgout_name)
else:
print >>m, '%s# NO output' % self.getIndent(level=2)
print >>m, '%sreturn None' % self.getIndent(level=2)
print >>m, ''
print >>m, '%ssoapAction[\'%s\'] = \'%s\'' %(self.getIndent(level=1), action_in, method_name)
print >>m, '%sroot[(%s.typecode.nspname,%s.typecode.pname)] = \'%s\'' \
%(self.getIndent(level=1), msgin_name, msgin_name, method_name)
return
def setUpHeader(self):
print >>self.header, '##################################################'
print >>self.header, '# %s.py' %self.getServiceModuleName()
print >>self.header, '# Generated by %s' %(self.__class__)
print >>self.header, '#'
print >>self.header, '##################################################'
def write(self, fd=sys.stdout):
'''write out to file descriptor,
should not need to override.
'''
print >>fd, self.header.getvalue()
print >>fd, self.imports.getvalue()
for k,v in self._services.items():
print >>fd, v.classdef.getvalue()
print >>fd, v.initdef.getvalue()
for s in v.methods:
print >>fd, s.getvalue()
def fromWSDL(self, wsdl):
'''setup the service description from WSDL,
should not need to override.
'''
assert isinstance(wsdl, WSDLTools.WSDL), 'expecting WSDL instance'
if len(wsdl.services) == 0:
raise WsdlGeneratorError, 'No service defined'
self.reset()
self.wsdl = wsdl
self.raw_wsdl = wsdl.document.toxml().replace("\"", "\\\"")
self.setUpHeader()
self.setUpImports()
for service in wsdl.services:
sd = self._service_class(service.name)
self._services[service.name] = sd
for port in service.ports:
for e in port.extensions:
if isinstance(e, WSDLTools.SoapAddressBinding):
sd.location = e.location
self.setUpMethods(port)
self.setUpClassDef(service)
self.setUpInitDef(service)
class WSAServiceModuleWriter(ServiceModuleWriter):
'''Creates a skeleton for a WS-Address service instance.
'''
def __init__(self, base=SimpleWSResource, prefix='wsa', service_class=SOAPService, strict=True):
'''
Parameters:
strict -- check that soapAction and input ws-action do not collide.
'''
ServiceModuleWriter.__init__(self, base, prefix, service_class)
self.strict = strict
def createMethodBody(msgInName, msgOutName, **kw):
'''return a tuple of strings containing the body of a method.
msgInName -- None or a str
msgOutName -- None or a str
'''
body = []
if msgInName is not None:
body.append('self.request = ps.Parse(%s.typecode)' %msgInName)
if msgOutName is not None:
body.append('return %s()' %msgOutName)
else:
body.append('return None')
return tuple(body)
createMethodBody = staticmethod(createMethodBody)
def setUpClassDef(self, service):
'''use soapAction dict for WS-Action input, setup wsAction
dict for grabbing WS-Action output values.
'''
assert isinstance(service, WSDLTools.Service), 'expecting WSDLTools.Service instance'
s = self._services[service.name].classdef
print >>s, 'class %s(%s):' %(self.getClassName(service.name), self._getBaseClassName())
print >>s, '%ssoapAction = {}' % self.getIndent(level=1)
print >>s, '%swsAction = {}' % self.getIndent(level=1)
print >>s, '%sroot = {}' % self.getIndent(level=1)
def setUpMethods(self, port):
'''set up all methods representing the port operations.
Parameters:
port -- Port that defines the operations.
'''
assert isinstance(port, WSDLTools.Port), \
'expecting WSDLTools.Port not: ' %type(port)
binding = port.getBinding()
portType = port.getPortType()
service = port.getService()
s = self._services[service.name]
for bop in binding.operations:
try:
op = portType.operations[bop.name]
except KeyError, ex:
raise WsdlGeneratorError,\
'Port(%s) PortType(%s) missing operation(%s) defined in Binding(%s)' \
%(port.name, portType.name, op.name, binding.name)
soap_action = wsaction_in = wsaction_out = None
if op.input is not None:
wsaction_in = op.getInputAction()
if op.output is not None:
wsaction_out = op.getOutputAction()
for ext in bop.extensions:
if isinstance(ext, WSDLTools.SoapOperationBinding) is False: continue
soap_action = ext.soapAction
if wsaction_in is None: break
if wsaction_in == soap_action: break
if self.strict is False:
warnings.warn(\
'Port(%s) operation(%s) in Binding(%s) soapAction(%s) != WS-Action(%s)' \
%(port.name, op.name, binding.name, soap_action, wsaction_in),
)
break
raise WsdlGeneratorError,\
'Port(%s) operation(%s) in Binding(%s) soapAction(%s) MUST match WS-Action(%s)' \
%(port.name, op.name, binding.name, soap_action, wsaction_in)
method_name = self.getMethodName(op.name)
m = s.newMethod()
print >>m, '%sdef %s(self, ps, address):' %(self.getIndent(level=1), method_name)
msgin_name = msgout_name = None
msgin,msgout = op.getInputMessage(),op.getOutputMessage()
if msgin is not None:
msgin_name = TextProtect(msgin.name)
if msgout is not None:
msgout_name = TextProtect(msgout.name)
indent = self.getIndent(level=2)
for l in self.createMethodBody(msgin_name, msgout_name):
print >>m, indent + l
print >>m, ''
print >>m, '%ssoapAction[\'%s\'] = \'%s\'' %(self.getIndent(level=1), wsaction_in, method_name)
print >>m, '%swsAction[\'%s\'] = \'%s\'' %(self.getIndent(level=1), method_name, wsaction_out)
print >>m, '%sroot[(%s.typecode.nspname,%s.typecode.pname)] = \'%s\'' \
%(self.getIndent(level=1), msgin_name, msgin_name, method_name)
class DelAuthServiceModuleWriter(ServiceModuleWriter):
''' Includes the generation of lines to call an authorization method on the server side
if an authorization function has been defined.
'''
def __init__(self, base=ServiceSOAPBinding, prefix='soap', service_class=SOAPService, do_extended=False):
ServiceModuleWriter.__init__(self, base=base, prefix=prefix, service_class=service_class, do_extended=do_extended)
def fromWSDL(self, wsdl):
ServiceModuleWriter.fromWSDL(self, wsdl)
for service in wsdl.services:
self.setUpAuthDef(service)
def setUpInitDef(self, service):
ServiceModuleWriter.setUpInitDef(self, service)
sd = self._services[service.name]
d = sd.initdef
print >>d, '%sif kw.has_key(\'impl\'):' % self.getIndent(level=2)
print >>d, '%sself.impl = kw[\'impl\']' % self.getIndent(level=3)
print >>d, '%sself.auth_method_name = None' % self.getIndent(level=2)
print >>d, '%sif kw.has_key(\'auth_method_name\'):' % self.getIndent(level=2)
print >>d, '%sself.auth_method_name = kw[\'auth_method_name\']' % self.getIndent(level=3)
def setUpAuthDef(self, service):
'''set __auth__ function
'''
sd = self._services[service.name]
e = sd.initdef
print >>e, "%sdef authorize(self, auth_info, post, action):" % self.getIndent(level=1)
print >>e, "%sif self.auth_method_name and hasattr(self.impl, self.auth_method_name):" % self.getIndent(level=2)
print >>e, "%sreturn getattr(self.impl, self.auth_method_name)(auth_info, post, action)" % self.getIndent(level=3)
print >>e, "%selse:" % self.getIndent(level=2)
print >>e, "%sreturn 1" % self.getIndent(level=3)
class DelAuthWSAServiceModuleWriter(WSAServiceModuleWriter):
def __init__(self, base=SimpleWSResource, prefix='wsa', service_class=SOAPService, strict=True):
WSAServiceModuleWriter.__init__(self, base=base, prefix=prefix, service_class=service_class, strict=strict)
def fromWSDL(self, wsdl):
WSAServiceModuleWriter.fromWSDL(self, wsdl)
for service in wsdl.services:
self.setUpAuthDef(service)
def setUpInitDef(self, service):
WSAServiceModuleWriter.setUpInitDef(self, service)
sd = self._services[service.name]
d = sd.initdef
print >>d, '%sif kw.has_key(\'impl\'):' % self.getIndent(level=2)
print >>d, '%sself.impl = kw[\'impl\']' % self.getIndent(level=3)
print >>d, '%sif kw.has_key(\'auth_method_name\'):' % self.getIndent(level=2)
print >>d, '%sself.auth_method_name = kw[\'auth_method_name\']' % self.getIndent(level=3)
def setUpAuthDef(self, service):
'''set __auth__ function
'''
sd = self._services[service.name]
e = sd.initdef
print >>e, "%sdef authorize(self, auth_info, post, action):" % self.getIndent(level=1)
print >>e, "%sif self.auth_method_name and hasattr(self.impl, self.auth_method_name):" % self.getIndent(level=2)
print >>e, "%sreturn getattr(self.impl, self.auth_method_name)(auth_info, post, action)" % self.getIndent(level=3)
print >>e, "%selse:" % self.getIndent(level=2)
print >>e, "%sreturn 1" % self.getIndent(level=3) | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/generate/wsdl2dispatch.py | wsdl2dispatch.py |
#XXX tuple instances (in Python 2.2) contain also:
# __class__, __delattr__, __getattribute__, __hash__, __new__,
# __reduce__, __setattr__, __str__
# What about these?
class UserTuple:
def __init__(self, inittuple=None):
self.data = ()
if inittuple is not None:
# XXX should this accept an arbitrary sequence?
if type(inittuple) == type(self.data):
self.data = inittuple
elif isinstance(inittuple, UserTuple):
# this results in
# self.data is inittuple.data
# but that's ok for tuples because they are
# immutable. (Builtin tuples behave the same.)
self.data = inittuple.data[:]
else:
# the same applies here; (t is tuple(t)) == 1
self.data = tuple(inittuple)
def __repr__(self): return repr(self.data)
def __lt__(self, other): return self.data < self.__cast(other)
def __le__(self, other): return self.data <= self.__cast(other)
def __eq__(self, other): return self.data == self.__cast(other)
def __ne__(self, other): return self.data != self.__cast(other)
def __gt__(self, other): return self.data > self.__cast(other)
def __ge__(self, other): return self.data >= self.__cast(other)
def __cast(self, other):
if isinstance(other, UserTuple): return other.data
else: return other
def __cmp__(self, other):
return cmp(self.data, self.__cast(other))
def __contains__(self, item): return item in self.data
def __len__(self): return len(self.data)
def __getitem__(self, i): return self.data[i]
def __getslice__(self, i, j):
i = max(i, 0); j = max(j, 0)
return self.__class__(self.data[i:j])
def __add__(self, other):
if isinstance(other, UserTuple):
return self.__class__(self.data + other.data)
elif isinstance(other, type(self.data)):
return self.__class__(self.data + other)
else:
return self.__class__(self.data + tuple(other))
# dir( () ) contains no __radd__ (at least in Python 2.2)
def __mul__(self, n):
return self.__class__(self.data*n)
__rmul__ = __mul__ | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/wstools/UserTuple.py | UserTuple.py |
"""Logging"""
ident = "$Id: logging.py 1204 2006-05-03 00:13:47Z boverhof $"
import sys
WARN = 1
DEBUG = 2
class ILogger:
'''Logger interface, by default this class
will be used and logging calls are no-ops.
'''
level = 0
def __init__(self, msg):
return
def warning(self, *args):
return
def debug(self, *args):
return
def error(self, *args):
return
def setLevel(cls, level):
cls.level = level
setLevel = classmethod(setLevel)
debugOn = lambda self: self.level >= DEBUG
warnOn = lambda self: self.level >= WARN
class BasicLogger(ILogger):
last = ''
def __init__(self, msg, out=sys.stdout):
self.msg, self.out = msg, out
def warning(self, msg, *args):
if self.warnOn() is False: return
if BasicLogger.last != self.msg:
BasicLogger.last = self.msg
print >>self, "---- ", self.msg, " ----"
print >>self, " %s " %BasicLogger.WARN,
print >>self, msg %args
WARN = '[WARN]'
def debug(self, msg, *args):
if self.debugOn() is False: return
if BasicLogger.last != self.msg:
BasicLogger.last = self.msg
print >>self, "---- ", self.msg, " ----"
print >>self, " %s " %BasicLogger.DEBUG,
print >>self, msg %args
DEBUG = '[DEBUG]'
def error(self, msg, *args):
if BasicLogger.last != self.msg:
BasicLogger.last = self.msg
print >>self, "---- ", self.msg, " ----"
print >>self, " %s " %BasicLogger.ERROR,
print >>self, msg %args
ERROR = '[ERROR]'
def write(self, *args):
'''Write convenience function; writes strings.
'''
for s in args: self.out.write(s)
_LoggerClass = BasicLogger
def setBasicLogger():
'''Use Basic Logger.
'''
setLoggerClass(BasicLogger)
BasicLogger.setLevel(0)
def setBasicLoggerWARN():
'''Use Basic Logger.
'''
setLoggerClass(BasicLogger)
BasicLogger.setLevel(WARN)
def setBasicLoggerDEBUG():
'''Use Basic Logger.
'''
setLoggerClass(BasicLogger)
BasicLogger.setLevel(DEBUG)
def setLoggerClass(loggingClass):
'''Set Logging Class.
'''
assert issubclass(loggingClass, ILogger), 'loggingClass must subclass ILogger'
global _LoggerClass
_LoggerClass = loggingClass
def setLevel(level=0):
'''Set Global Logging Level.
'''
ILogger.level = level
def getLevel():
return ILogger.level
def getLogger(msg):
'''Return instance of Logging class.
'''
return _LoggerClass(msg) | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/wstools/logging.py | logging.py |
ident = "$Id: TimeoutSocket.py 237 2003-05-20 21:10:14Z warnes $"
import string, socket, select, errno
WSAEINVAL = getattr(errno, 'WSAEINVAL', 10022)
class TimeoutSocket:
"""A socket imposter that supports timeout limits."""
def __init__(self, timeout=20, sock=None):
self.timeout = float(timeout)
self.inbuf = ''
if sock is None:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock = sock
self.sock.setblocking(0)
self._rbuf = ''
self._wbuf = ''
def __getattr__(self, name):
# Delegate to real socket attributes.
return getattr(self.sock, name)
def connect(self, *addr):
timeout = self.timeout
sock = self.sock
try:
# Non-blocking mode
sock.setblocking(0)
apply(sock.connect, addr)
sock.setblocking(timeout != 0)
return 1
except socket.error,why:
if not timeout:
raise
sock.setblocking(1)
if len(why.args) == 1:
code = 0
else:
code, why = why
if code not in (
errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK
):
raise
r,w,e = select.select([],[sock],[],timeout)
if w:
try:
apply(sock.connect, addr)
return 1
except socket.error,why:
if len(why.args) == 1:
code = 0
else:
code, why = why
if code in (errno.EISCONN, WSAEINVAL):
return 1
raise
raise TimeoutError('socket connect() timeout.')
def send(self, data, flags=0):
total = len(data)
next = 0
while 1:
r, w, e = select.select([],[self.sock], [], self.timeout)
if w:
buff = data[next:next + 8192]
sent = self.sock.send(buff, flags)
next = next + sent
if next == total:
return total
continue
raise TimeoutError('socket send() timeout.')
def recv(self, amt, flags=0):
if select.select([self.sock], [], [], self.timeout)[0]:
return self.sock.recv(amt, flags)
raise TimeoutError('socket recv() timeout.')
buffsize = 4096
handles = 1
def makefile(self, mode="r", buffsize=-1):
self.handles = self.handles + 1
self.mode = mode
return self
def close(self):
self.handles = self.handles - 1
if self.handles == 0 and self.sock.fileno() >= 0:
self.sock.close()
def read(self, n=-1):
if not isinstance(n, type(1)):
n = -1
if n >= 0:
k = len(self._rbuf)
if n <= k:
data = self._rbuf[:n]
self._rbuf = self._rbuf[n:]
return data
n = n - k
L = [self._rbuf]
self._rbuf = ""
while n > 0:
new = self.recv(max(n, self.buffsize))
if not new: break
k = len(new)
if k > n:
L.append(new[:n])
self._rbuf = new[n:]
break
L.append(new)
n = n - k
return "".join(L)
k = max(4096, self.buffsize)
L = [self._rbuf]
self._rbuf = ""
while 1:
new = self.recv(k)
if not new: break
L.append(new)
k = min(k*2, 1024**2)
return "".join(L)
def readline(self, limit=-1):
data = ""
i = self._rbuf.find('\n')
while i < 0 and not (0 < limit <= len(self._rbuf)):
new = self.recv(self.buffsize)
if not new: break
i = new.find('\n')
if i >= 0: i = i + len(self._rbuf)
self._rbuf = self._rbuf + new
if i < 0: i = len(self._rbuf)
else: i = i+1
if 0 <= limit < len(self._rbuf): i = limit
data, self._rbuf = self._rbuf[:i], self._rbuf[i:]
return data
def readlines(self, sizehint = 0):
total = 0
list = []
while 1:
line = self.readline()
if not line: break
list.append(line)
total += len(line)
if sizehint and total >= sizehint:
break
return list
def writelines(self, list):
self.send(''.join(list))
def write(self, data):
self.send(data)
def flush(self):
pass
class TimeoutError(Exception):
pass | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/wstools/TimeoutSocket.py | TimeoutSocket.py |
ident = "$Id: XMLname.py 954 2005-02-16 14:45:37Z warnes $"
from re import *
def _NCNameChar(x):
return x.isalpha() or x.isdigit() or x=="." or x=='-' or x=="_"
def _NCNameStartChar(x):
return x.isalpha() or x=="_"
def _toUnicodeHex(x):
hexval = hex(ord(x[0]))[2:]
hexlen = len(hexval)
# Make hexval have either 4 or 8 digits by prepending 0's
if (hexlen==1): hexval = "000" + hexval
elif (hexlen==2): hexval = "00" + hexval
elif (hexlen==3): hexval = "0" + hexval
elif (hexlen==4): hexval = "" + hexval
elif (hexlen==5): hexval = "000" + hexval
elif (hexlen==6): hexval = "00" + hexval
elif (hexlen==7): hexval = "0" + hexval
elif (hexlen==8): hexval = "" + hexval
else: raise Exception, "Illegal Value returned from hex(ord(x))"
return "_x"+ hexval + "_"
def _fromUnicodeHex(x):
return eval( r'u"\u'+x[2:-1]+'"' )
def toXMLname(string):
"""Convert string to a XML name."""
if string.find(':') != -1 :
(prefix, localname) = string.split(':',1)
else:
prefix = None
localname = string
T = unicode(localname)
N = len(localname)
X = [];
for i in range(N) :
if i< N-1 and T[i]==u'_' and T[i+1]==u'x':
X.append(u'_x005F_')
elif i==0 and N >= 3 and \
( T[0]==u'x' or T[0]==u'X' ) and \
( T[1]==u'm' or T[1]==u'M' ) and \
( T[2]==u'l' or T[2]==u'L' ):
X.append(u'_xFFFF_' + T[0])
elif (not _NCNameChar(T[i])) or (i==0 and not _NCNameStartChar(T[i])):
X.append(_toUnicodeHex(T[i]))
else:
X.append(T[i])
if prefix:
return "%s:%s" % (prefix, u''.join(X))
return u''.join(X)
def fromXMLname(string):
"""Convert XML name to unicode string."""
retval = sub(r'_xFFFF_','', string )
def fun( matchobj ):
return _fromUnicodeHex( matchobj.group(0) )
retval = sub(r'_x[0-9A-Za-z]+_', fun, retval )
return retval | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/wstools/XMLname.py | XMLname.py |
ident = "$Id: Namespaces.py 1160 2006-03-17 19:28:11Z boverhof $"
try:
from xml.ns import SOAP, SCHEMA, WSDL, XMLNS, DSIG, ENCRYPTION
DSIG.C14N = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"
except:
class SOAP:
ENV = "http://schemas.xmlsoap.org/soap/envelope/"
ENC = "http://schemas.xmlsoap.org/soap/encoding/"
ACTOR_NEXT = "http://schemas.xmlsoap.org/soap/actor/next"
class SCHEMA:
XSD1 = "http://www.w3.org/1999/XMLSchema"
XSD2 = "http://www.w3.org/2000/10/XMLSchema"
XSD3 = "http://www.w3.org/2001/XMLSchema"
XSD_LIST = [ XSD1, XSD2, XSD3 ]
XSI1 = "http://www.w3.org/1999/XMLSchema-instance"
XSI2 = "http://www.w3.org/2000/10/XMLSchema-instance"
XSI3 = "http://www.w3.org/2001/XMLSchema-instance"
XSI_LIST = [ XSI1, XSI2, XSI3 ]
BASE = XSD3
class WSDL:
BASE = "http://schemas.xmlsoap.org/wsdl/"
BIND_HTTP = "http://schemas.xmlsoap.org/wsdl/http/"
BIND_MIME = "http://schemas.xmlsoap.org/wsdl/mime/"
BIND_SOAP = "http://schemas.xmlsoap.org/wsdl/soap/"
BIND_SOAP12 = "http://schemas.xmlsoap.org/wsdl/soap12/"
class XMLNS:
BASE = "http://www.w3.org/2000/xmlns/"
XML = "http://www.w3.org/XML/1998/namespace"
HTML = "http://www.w3.org/TR/REC-html40"
class DSIG:
BASE = "http://www.w3.org/2000/09/xmldsig#"
C14N = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"
C14N_COMM = "http://www.w3.org/TR/2000/CR-xml-c14n-20010315#WithComments"
C14N_EXCL = "http://www.w3.org/2001/10/xml-exc-c14n#"
DIGEST_MD2 = "http://www.w3.org/2000/09/xmldsig#md2"
DIGEST_MD5 = "http://www.w3.org/2000/09/xmldsig#md5"
DIGEST_SHA1 = "http://www.w3.org/2000/09/xmldsig#sha1"
ENC_BASE64 = "http://www.w3.org/2000/09/xmldsig#base64"
ENVELOPED = "http://www.w3.org/2000/09/xmldsig#enveloped-signature"
HMAC_SHA1 = "http://www.w3.org/2000/09/xmldsig#hmac-sha1"
SIG_DSA_SHA1 = "http://www.w3.org/2000/09/xmldsig#dsa-sha1"
SIG_RSA_SHA1 = "http://www.w3.org/2000/09/xmldsig#rsa-sha1"
XPATH = "http://www.w3.org/TR/1999/REC-xpath-19991116"
XSLT = "http://www.w3.org/TR/1999/REC-xslt-19991116"
class ENCRYPTION:
BASE = "http://www.w3.org/2001/04/xmlenc#"
BLOCK_3DES = "http://www.w3.org/2001/04/xmlenc#des-cbc"
BLOCK_AES128 = "http://www.w3.org/2001/04/xmlenc#aes128-cbc"
BLOCK_AES192 = "http://www.w3.org/2001/04/xmlenc#aes192-cbc"
BLOCK_AES256 = "http://www.w3.org/2001/04/xmlenc#aes256-cbc"
DIGEST_RIPEMD160 = "http://www.w3.org/2001/04/xmlenc#ripemd160"
DIGEST_SHA256 = "http://www.w3.org/2001/04/xmlenc#sha256"
DIGEST_SHA512 = "http://www.w3.org/2001/04/xmlenc#sha512"
KA_DH = "http://www.w3.org/2001/04/xmlenc#dh"
KT_RSA_1_5 = "http://www.w3.org/2001/04/xmlenc#rsa-1_5"
KT_RSA_OAEP = "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"
STREAM_ARCFOUR = "http://www.w3.org/2001/04/xmlenc#arcfour"
WRAP_3DES = "http://www.w3.org/2001/04/xmlenc#kw-3des"
WRAP_AES128 = "http://www.w3.org/2001/04/xmlenc#kw-aes128"
WRAP_AES192 = "http://www.w3.org/2001/04/xmlenc#kw-aes192"
WRAP_AES256 = "http://www.w3.org/2001/04/xmlenc#kw-aes256"
class WSRF_V1_2:
'''OASIS WSRF Specifications Version 1.2
'''
class LIFETIME:
XSD_DRAFT1 = "http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-ResourceLifetime-1.2-draft-01.xsd"
XSD_DRAFT4 = "http://docs.oasis-open.org/wsrf/2004/11/wsrf-WS-ResourceLifetime-1.2-draft-04.xsd"
WSDL_DRAFT1 = "http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-ResourceLifetime-1.2-draft-01.wsdl"
WSDL_DRAFT4 = "http://docs.oasis-open.org/wsrf/2004/11/wsrf-WS-ResourceLifetime-1.2-draft-04.wsdl"
LATEST = WSDL_DRAFT4
WSDL_LIST = (WSDL_DRAFT1, WSDL_DRAFT4)
XSD_LIST = (XSD_DRAFT1, XSD_DRAFT4)
class PROPERTIES:
XSD_DRAFT1 = "http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-ResourceProperties-1.2-draft-01.xsd"
XSD_DRAFT5 = "http://docs.oasis-open.org/wsrf/2004/11/wsrf-WS-ResourceProperties-1.2-draft-05.xsd"
WSDL_DRAFT1 = "http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-ResourceProperties-1.2-draft-01.wsdl"
WSDL_DRAFT5 = "http://docs.oasis-open.org/wsrf/2004/11/wsrf-WS-ResourceProperties-1.2-draft-05.wsdl"
LATEST = WSDL_DRAFT5
WSDL_LIST = (WSDL_DRAFT1, WSDL_DRAFT5)
XSD_LIST = (XSD_DRAFT1, XSD_DRAFT5)
class BASENOTIFICATION:
XSD_DRAFT1 = "http://docs.oasis-open.org/wsn/2004/06/wsn-WS-BaseNotification-1.2-draft-01.xsd"
WSDL_DRAFT1 = "http://docs.oasis-open.org/wsn/2004/06/wsn-WS-BaseNotification-1.2-draft-01.wsdl"
LATEST = WSDL_DRAFT1
WSDL_LIST = (WSDL_DRAFT1,)
XSD_LIST = (XSD_DRAFT1,)
class BASEFAULTS:
XSD_DRAFT1 = "http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-BaseFaults-1.2-draft-01.xsd"
XSD_DRAFT3 = "http://docs.oasis-open.org/wsrf/2004/11/wsrf-WS-BaseFaults-1.2-draft-03.xsd"
#LATEST = DRAFT3
#WSDL_LIST = (WSDL_DRAFT1, WSDL_DRAFT3)
XSD_LIST = (XSD_DRAFT1, XSD_DRAFT3)
WSRF = WSRF_V1_2
WSRFLIST = (WSRF_V1_2,)
class OASIS:
'''URLs for Oasis specifications
'''
WSSE = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
UTILITY = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
class X509TOKEN:
Base64Binary = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary"
STRTransform = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0"
PKCS7 = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#PKCS7"
X509 = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509"
X509PKIPathv1 = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509PKIPathv1"
X509v3SubjectKeyIdentifier = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3SubjectKeyIdentifier"
LIFETIME = WSRF_V1_2.LIFETIME.XSD_DRAFT1
PROPERTIES = WSRF_V1_2.PROPERTIES.XSD_DRAFT1
BASENOTIFICATION = WSRF_V1_2.BASENOTIFICATION.XSD_DRAFT1
BASEFAULTS = WSRF_V1_2.BASEFAULTS.XSD_DRAFT1
class WSTRUST:
BASE = "http://schemas.xmlsoap.org/ws/2004/04/trust"
ISSUE = "http://schemas.xmlsoap.org/ws/2004/04/trust/Issue"
class WSSE:
BASE = "http://schemas.xmlsoap.org/ws/2002/04/secext"
TRUST = WSTRUST.BASE
class WSU:
BASE = "http://schemas.xmlsoap.org/ws/2002/04/utility"
UTILITY = "http://schemas.xmlsoap.org/ws/2002/07/utility"
class WSR:
PROPERTIES = "http://www.ibm.com/xmlns/stdwip/web-services/WS-ResourceProperties"
LIFETIME = "http://www.ibm.com/xmlns/stdwip/web-services/WS-ResourceLifetime"
class WSA200408:
ADDRESS = "http://schemas.xmlsoap.org/ws/2004/08/addressing"
ANONYMOUS = "%s/role/anonymous" %ADDRESS
FAULT = "%s/fault" %ADDRESS
class WSA200403:
ADDRESS = "http://schemas.xmlsoap.org/ws/2004/03/addressing"
ANONYMOUS = "%s/role/anonymous" %ADDRESS
FAULT = "%s/fault" %ADDRESS
class WSA200303:
ADDRESS = "http://schemas.xmlsoap.org/ws/2003/03/addressing"
ANONYMOUS = "%s/role/anonymous" %ADDRESS
FAULT = None
WSA = WSA200408
WSA_LIST = (WSA200408, WSA200403, WSA200303)
class WSP:
POLICY = "http://schemas.xmlsoap.org/ws/2002/12/policy"
class BEA:
SECCONV = "http://schemas.xmlsoap.org/ws/2004/04/sc"
SCTOKEN = "http://schemas.xmlsoap.org/ws/2004/04/security/sc/sct"
class GLOBUS:
SECCONV = "http://wsrf.globus.org/core/2004/07/security/secconv"
CORE = "http://www.globus.org/namespaces/2004/06/core"
SIG = "http://www.globus.org/2002/04/xmlenc#gssapi-sign"
TOKEN = "http://www.globus.org/ws/2004/09/security/sc#GSSAPI_GSI_TOKEN"
ZSI_SCHEMA_URI = 'http://www.zolera.com/schemas/ZSI/' | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/wstools/Namespaces.py | Namespaces.py |
ident = "$Id: XMLSchema.py 1207 2006-05-04 18:34:01Z boverhof $"
import types, weakref, sys, warnings
from Namespaces import SCHEMA, XMLNS
from Utility import DOM, DOMException, Collection, SplitQName, basejoin
from StringIO import StringIO
# If we have no threading, this should be a no-op
try:
from threading import RLock
except ImportError:
class RLock:
def acquire():
pass
def release():
pass
#
# Collections in XMLSchema class
#
TYPES = 'types'
ATTRIBUTE_GROUPS = 'attr_groups'
ATTRIBUTES = 'attr_decl'
ELEMENTS = 'elements'
MODEL_GROUPS = 'model_groups'
def GetSchema(component):
"""convience function for finding the parent XMLSchema instance.
"""
parent = component
while not isinstance(parent, XMLSchema):
parent = parent._parent()
return parent
class SchemaReader:
"""A SchemaReader creates XMLSchema objects from urls and xml data.
"""
namespaceToSchema = {}
def __init__(self, domReader=None, base_url=None):
"""domReader -- class must implement DOMAdapterInterface
base_url -- base url string
"""
self.__base_url = base_url
self.__readerClass = domReader
if not self.__readerClass:
self.__readerClass = DOMAdapter
self._includes = {}
self._imports = {}
def __setImports(self, schema):
"""Add dictionary of imports to schema instance.
schema -- XMLSchema instance
"""
for ns,val in schema.imports.items():
if self._imports.has_key(ns):
schema.addImportSchema(self._imports[ns])
def __setIncludes(self, schema):
"""Add dictionary of includes to schema instance.
schema -- XMLSchema instance
"""
for schemaLocation, val in schema.includes.items():
if self._includes.has_key(schemaLocation):
schema.addIncludeSchema(self._imports[schemaLocation])
def addSchemaByLocation(self, location, schema):
"""provide reader with schema document for a location.
"""
self._includes[location] = schema
def addSchemaByNamespace(self, schema):
"""provide reader with schema document for a targetNamespace.
"""
self._imports[schema.targetNamespace] = schema
def loadFromNode(self, parent, element):
"""element -- DOM node or document
parent -- WSDLAdapter instance
"""
reader = self.__readerClass(element)
schema = XMLSchema(parent)
#HACK to keep a reference
schema.wsdl = parent
schema.setBaseUrl(self.__base_url)
schema.load(reader)
return schema
def loadFromStream(self, file, url=None):
"""Return an XMLSchema instance loaded from a file object.
file -- file object
url -- base location for resolving imports/includes.
"""
reader = self.__readerClass()
reader.loadDocument(file)
schema = XMLSchema()
if url is not None:
schema.setBaseUrl(url)
schema.load(reader)
self.__setIncludes(schema)
self.__setImports(schema)
return schema
def loadFromString(self, data):
"""Return an XMLSchema instance loaded from an XML string.
data -- XML string
"""
return self.loadFromStream(StringIO(data))
def loadFromURL(self, url, schema=None):
"""Return an XMLSchema instance loaded from the given url.
url -- URL to dereference
schema -- Optional XMLSchema instance.
"""
reader = self.__readerClass()
if self.__base_url:
url = basejoin(self.__base_url,url)
reader.loadFromURL(url)
schema = schema or XMLSchema()
schema.setBaseUrl(url)
schema.load(reader)
self.__setIncludes(schema)
self.__setImports(schema)
return schema
def loadFromFile(self, filename):
"""Return an XMLSchema instance loaded from the given file.
filename -- name of file to open
"""
if self.__base_url:
filename = basejoin(self.__base_url,filename)
file = open(filename, 'rb')
try:
schema = self.loadFromStream(file, filename)
finally:
file.close()
return schema
class SchemaError(Exception):
pass
###########################
# DOM Utility Adapters
##########################
class DOMAdapterInterface:
def hasattr(self, attr, ns=None):
"""return true if node has attribute
attr -- attribute to check for
ns -- namespace of attribute, by default None
"""
raise NotImplementedError, 'adapter method not implemented'
def getContentList(self, *contents):
"""returns an ordered list of child nodes
*contents -- list of node names to return
"""
raise NotImplementedError, 'adapter method not implemented'
def setAttributeDictionary(self, attributes):
"""set attribute dictionary
"""
raise NotImplementedError, 'adapter method not implemented'
def getAttributeDictionary(self):
"""returns a dict of node's attributes
"""
raise NotImplementedError, 'adapter method not implemented'
def getNamespace(self, prefix):
"""returns namespace referenced by prefix.
"""
raise NotImplementedError, 'adapter method not implemented'
def getTagName(self):
"""returns tagName of node
"""
raise NotImplementedError, 'adapter method not implemented'
def getParentNode(self):
"""returns parent element in DOMAdapter or None
"""
raise NotImplementedError, 'adapter method not implemented'
def loadDocument(self, file):
"""load a Document from a file object
file --
"""
raise NotImplementedError, 'adapter method not implemented'
def loadFromURL(self, url):
"""load a Document from an url
url -- URL to dereference
"""
raise NotImplementedError, 'adapter method not implemented'
class DOMAdapter(DOMAdapterInterface):
"""Adapter for ZSI.Utility.DOM
"""
def __init__(self, node=None):
"""Reset all instance variables.
element -- DOM document, node, or None
"""
if hasattr(node, 'documentElement'):
self.__node = node.documentElement
else:
self.__node = node
self.__attributes = None
def getNode(self):
return self.__node
def hasattr(self, attr, ns=None):
"""attr -- attribute
ns -- optional namespace, None means unprefixed attribute.
"""
if not self.__attributes:
self.setAttributeDictionary()
if ns:
return self.__attributes.get(ns,{}).has_key(attr)
return self.__attributes.has_key(attr)
def getContentList(self, *contents):
nodes = []
ELEMENT_NODE = self.__node.ELEMENT_NODE
for child in DOM.getElements(self.__node, None):
if child.nodeType == ELEMENT_NODE and\
SplitQName(child.tagName)[1] in contents:
nodes.append(child)
return map(self.__class__, nodes)
def setAttributeDictionary(self):
self.__attributes = {}
for v in self.__node._attrs.values():
self.__attributes[v.nodeName] = v.nodeValue
def getAttributeDictionary(self):
if not self.__attributes:
self.setAttributeDictionary()
return self.__attributes
def getTagName(self):
return self.__node.tagName
def getParentNode(self):
if self.__node.parentNode.nodeType == self.__node.ELEMENT_NODE:
return DOMAdapter(self.__node.parentNode)
return None
def getNamespace(self, prefix):
"""prefix -- deference namespace prefix in node's context.
Ascends parent nodes until found.
"""
namespace = None
if prefix == 'xmlns':
namespace = DOM.findDefaultNS(prefix, self.__node)
else:
try:
namespace = DOM.findNamespaceURI(prefix, self.__node)
except DOMException, ex:
if prefix != 'xml':
raise SchemaError, '%s namespace not declared for %s'\
%(prefix, self.__node._get_tagName())
namespace = XMLNS.XML
return namespace
def loadDocument(self, file):
self.__node = DOM.loadDocument(file)
if hasattr(self.__node, 'documentElement'):
self.__node = self.__node.documentElement
def loadFromURL(self, url):
self.__node = DOM.loadFromURL(url)
if hasattr(self.__node, 'documentElement'):
self.__node = self.__node.documentElement
class XMLBase:
""" These class variables are for string indentation.
"""
tag = None
__indent = 0
__rlock = RLock()
def __str__(self):
XMLBase.__rlock.acquire()
XMLBase.__indent += 1
tmp = "<" + str(self.__class__) + '>\n'
for k,v in self.__dict__.items():
tmp += "%s* %s = %s\n" %(XMLBase.__indent*' ', k, v)
XMLBase.__indent -= 1
XMLBase.__rlock.release()
return tmp
"""Marker Interface: can determine something about an instances properties by using
the provided convenience functions.
"""
class DefinitionMarker:
"""marker for definitions
"""
pass
class DeclarationMarker:
"""marker for declarations
"""
pass
class AttributeMarker:
"""marker for attributes
"""
pass
class AttributeGroupMarker:
"""marker for attribute groups
"""
pass
class WildCardMarker:
"""marker for wildcards
"""
pass
class ElementMarker:
"""marker for wildcards
"""
pass
class ReferenceMarker:
"""marker for references
"""
pass
class ModelGroupMarker:
"""marker for model groups
"""
pass
class AllMarker(ModelGroupMarker):
"""marker for all model group
"""
pass
class ChoiceMarker(ModelGroupMarker):
"""marker for choice model group
"""
pass
class SequenceMarker(ModelGroupMarker):
"""marker for sequence model group
"""
pass
class ExtensionMarker:
"""marker for extensions
"""
pass
class RestrictionMarker:
"""marker for restrictions
"""
facets = ['enumeration', 'length', 'maxExclusive', 'maxInclusive',\
'maxLength', 'minExclusive', 'minInclusive', 'minLength',\
'pattern', 'fractionDigits', 'totalDigits', 'whiteSpace']
class SimpleMarker:
"""marker for simple type information
"""
pass
class ListMarker:
"""marker for simple type list
"""
pass
class UnionMarker:
"""marker for simple type Union
"""
pass
class ComplexMarker:
"""marker for complex type information
"""
pass
class LocalMarker:
"""marker for complex type information
"""
pass
class MarkerInterface:
def isDefinition(self):
return isinstance(self, DefinitionMarker)
def isDeclaration(self):
return isinstance(self, DeclarationMarker)
def isAttribute(self):
return isinstance(self, AttributeMarker)
def isAttributeGroup(self):
return isinstance(self, AttributeGroupMarker)
def isElement(self):
return isinstance(self, ElementMarker)
def isReference(self):
return isinstance(self, ReferenceMarker)
def isWildCard(self):
return isinstance(self, WildCardMarker)
def isModelGroup(self):
return isinstance(self, ModelGroupMarker)
def isAll(self):
return isinstance(self, AllMarker)
def isChoice(self):
return isinstance(self, ChoiceMarker)
def isSequence(self):
return isinstance(self, SequenceMarker)
def isExtension(self):
return isinstance(self, ExtensionMarker)
def isRestriction(self):
return isinstance(self, RestrictionMarker)
def isSimple(self):
return isinstance(self, SimpleMarker)
def isComplex(self):
return isinstance(self, ComplexMarker)
def isLocal(self):
return isinstance(self, LocalMarker)
def isList(self):
return isinstance(self, ListMarker)
def isUnion(self):
return isinstance(self, UnionMarker)
##########################################################
# Schema Components
#########################################################
class XMLSchemaComponent(XMLBase, MarkerInterface):
"""
class variables:
required -- list of required attributes
attributes -- dict of default attribute values, including None.
Value can be a function for runtime dependencies.
contents -- dict of namespace keyed content lists.
'xsd' content of xsd namespace.
xmlns_key -- key for declared xmlns namespace.
xmlns -- xmlns is special prefix for namespace dictionary
xml -- special xml prefix for xml namespace.
"""
required = []
attributes = {}
contents = {}
xmlns_key = ''
xmlns = 'xmlns'
xml = 'xml'
def __init__(self, parent=None):
"""parent -- parent instance
instance variables:
attributes -- dictionary of node's attributes
"""
self.attributes = None
self._parent = parent
if self._parent:
self._parent = weakref.ref(parent)
if not self.__class__ == XMLSchemaComponent\
and not (type(self.__class__.required) == type(XMLSchemaComponent.required)\
and type(self.__class__.attributes) == type(XMLSchemaComponent.attributes)\
and type(self.__class__.contents) == type(XMLSchemaComponent.contents)):
raise RuntimeError, 'Bad type for a class variable in %s' %self.__class__
def getItemTrace(self):
"""Returns a node trace up to the <schema> item.
"""
item, path, name, ref = self, [], 'name', 'ref'
while not isinstance(item,XMLSchema) and not isinstance(item,WSDLToolsAdapter):
attr = item.getAttribute(name)
if attr is None:
attr = item.getAttribute(ref)
if attr is None: path.append('<%s>' %(item.tag))
else: path.append('<%s ref="%s">' %(item.tag, attr))
else:
path.append('<%s name="%s">' %(item.tag,attr))
item = item._parent()
try:
tns = item.getTargetNamespace()
except:
tns = ''
path.append('<%s targetNamespace="%s">' %(item.tag, tns))
path.reverse()
return ''.join(path)
def getTargetNamespace(self):
"""return targetNamespace
"""
parent = self
targetNamespace = 'targetNamespace'
tns = self.attributes.get(targetNamespace)
while not tns:
parent = parent._parent()
tns = parent.attributes.get(targetNamespace)
return tns
def getAttributeDeclaration(self, attribute):
"""attribute -- attribute with a QName value (eg. type).
collection -- check types collection in parent Schema instance
"""
return self.getQNameAttribute(ATTRIBUTES, attribute)
def getAttributeGroup(self, attribute):
"""attribute -- attribute with a QName value (eg. type).
collection -- check types collection in parent Schema instance
"""
return self.getQNameAttribute(ATTRIBUTE_GROUPS, attribute)
def getTypeDefinition(self, attribute):
"""attribute -- attribute with a QName value (eg. type).
collection -- check types collection in parent Schema instance
"""
return self.getQNameAttribute(TYPES, attribute)
def getElementDeclaration(self, attribute):
"""attribute -- attribute with a QName value (eg. element).
collection -- check elements collection in parent Schema instance.
"""
return self.getQNameAttribute(ELEMENTS, attribute)
def getModelGroup(self, attribute):
"""attribute -- attribute with a QName value (eg. ref).
collection -- check model_group collection in parent Schema instance.
"""
return self.getQNameAttribute(MODEL_GROUPS, attribute)
def getQNameAttribute(self, collection, attribute):
"""returns object instance representing QName --> (namespace,name),
or if does not exist return None.
attribute -- an information item attribute, with a QName value.
collection -- collection in parent Schema instance to search.
"""
obj = None
tdc = self.getAttributeQName(attribute)
if tdc:
obj = self.getSchemaItem(collection, tdc.getTargetNamespace(), tdc.getName())
return obj
def getSchemaItem(self, collection, namespace, name):
"""returns object instance representing namespace, name,
or if does not exist return None.
namespace -- namespace item defined in.
name -- name of item.
collection -- collection in parent Schema instance to search.
"""
parent = GetSchema(self)
if parent.targetNamespace == namespace:
try:
obj = getattr(parent, collection)[name]
except KeyError, ex:
raise KeyError, 'targetNamespace(%s) collection(%s) has no item(%s)'\
%(namespace, collection, name)
return obj
if not parent.imports.has_key(namespace):
return None
# Lazy Eval
schema = parent.imports[namespace]
if not isinstance(schema, XMLSchema):
schema = schema.getSchema()
if schema is not None:
parent.imports[namespace] = schema
if schema is None:
raise SchemaError, 'no schema instance for imported namespace (%s).'\
%(namespace)
if not isinstance(schema, XMLSchema):
raise TypeError, 'expecting XMLSchema instance not "%r"' %schema
try:
obj = getattr(schema, collection)[name]
except KeyError, ex:
raise KeyError, 'targetNamespace(%s) collection(%s) has no item(%s)'\
%(namespace, collection, name)
return obj
def getXMLNS(self, prefix=None):
"""deference prefix or by default xmlns, returns namespace.
"""
if prefix == XMLSchemaComponent.xml:
return XMLNS.XML
parent = self
ns = self.attributes[XMLSchemaComponent.xmlns].get(prefix or\
XMLSchemaComponent.xmlns_key)
while not ns:
parent = parent._parent()
ns = parent.attributes[XMLSchemaComponent.xmlns].get(prefix or\
XMLSchemaComponent.xmlns_key)
if not ns and isinstance(parent, WSDLToolsAdapter):
if prefix is None:
return ''
raise SchemaError, 'unknown prefix %s' %prefix
return ns
def getAttribute(self, attribute):
"""return requested attribute value or None
"""
if type(attribute) in (list, tuple):
if len(attribute) != 2:
raise LookupError, 'To access attributes must use name or (namespace,name)'
return self.attributes.get(attribute[0]).get(attribute[1])
return self.attributes.get(attribute)
def getAttributeQName(self, attribute):
"""return requested attribute value as (namespace,name) or None
"""
qname = self.getAttribute(attribute)
if isinstance(qname, TypeDescriptionComponent) is True:
return qname
if qname is None:
return None
prefix,ncname = SplitQName(qname)
namespace = self.getXMLNS(prefix)
return TypeDescriptionComponent((namespace,ncname))
def getAttributeName(self):
"""return attribute name or None
"""
return self.getAttribute('name')
def setAttributes(self, node):
"""Sets up attribute dictionary, checks for required attributes and
sets default attribute values. attr is for default attribute values
determined at runtime.
structure of attributes dictionary
['xmlns'][xmlns_key] -- xmlns namespace
['xmlns'][prefix] -- declared namespace prefix
[namespace][prefix] -- attributes declared in a namespace
[attribute] -- attributes w/o prefix, default namespaces do
not directly apply to attributes, ie Name can't collide
with QName.
"""
self.attributes = {XMLSchemaComponent.xmlns:{}}
for k,v in node.getAttributeDictionary().items():
prefix,value = SplitQName(k)
if value == XMLSchemaComponent.xmlns:
self.attributes[value][prefix or XMLSchemaComponent.xmlns_key] = v
elif prefix:
ns = node.getNamespace(prefix)
if not ns:
raise SchemaError, 'no namespace for attribute prefix %s'\
%prefix
if not self.attributes.has_key(ns):
self.attributes[ns] = {}
elif self.attributes[ns].has_key(value):
raise SchemaError, 'attribute %s declared multiple times in %s'\
%(value, ns)
self.attributes[ns][value] = v
elif not self.attributes.has_key(value):
self.attributes[value] = v
else:
raise SchemaError, 'attribute %s declared multiple times' %value
if not isinstance(self, WSDLToolsAdapter):
self.__checkAttributes()
self.__setAttributeDefaults()
#set QNames
for k in ['type', 'element', 'base', 'ref', 'substitutionGroup', 'itemType']:
if self.attributes.has_key(k):
prefix, value = SplitQName(self.attributes.get(k))
self.attributes[k] = \
TypeDescriptionComponent((self.getXMLNS(prefix), value))
#Union, memberTypes is a whitespace separated list of QNames
for k in ['memberTypes']:
if self.attributes.has_key(k):
qnames = self.attributes[k]
self.attributes[k] = []
for qname in qnames.split():
prefix, value = SplitQName(qname)
self.attributes['memberTypes'].append(\
TypeDescriptionComponent(\
(self.getXMLNS(prefix), value)))
def getContents(self, node):
"""retrieve xsd contents
"""
return node.getContentList(*self.__class__.contents['xsd'])
def __setAttributeDefaults(self):
"""Looks for default values for unset attributes. If
class variable representing attribute is None, then
it must be defined as an instance variable.
"""
for k,v in self.__class__.attributes.items():
if v is not None and self.attributes.has_key(k) is False:
if isinstance(v, types.FunctionType):
self.attributes[k] = v(self)
else:
self.attributes[k] = v
def __checkAttributes(self):
"""Checks that required attributes have been defined,
attributes w/default cannot be required. Checks
all defined attributes are legal, attribute
references are not subject to this test.
"""
for a in self.__class__.required:
if not self.attributes.has_key(a):
raise SchemaError,\
'class instance %s, missing required attribute %s'\
%(self.__class__, a)
for a,v in self.attributes.items():
# attribute #other, ie. not in empty namespace
if type(v) is dict:
continue
# predefined prefixes xmlns, xml
if a in (XMLSchemaComponent.xmlns, XMLNS.XML):
continue
if (a not in self.__class__.attributes.keys()) and not\
(self.isAttribute() and self.isReference()):
raise SchemaError, '%s, unknown attribute(%s,%s)' \
%(self.getItemTrace(), a, self.attributes[a])
class WSDLToolsAdapter(XMLSchemaComponent):
"""WSDL Adapter to grab the attributes from the wsdl document node.
"""
attributes = {'name':None, 'targetNamespace':None}
tag = 'definitions'
def __init__(self, wsdl):
XMLSchemaComponent.__init__(self, parent=wsdl)
self.setAttributes(DOMAdapter(wsdl.document))
def getImportSchemas(self):
"""returns WSDLTools.WSDL types Collection
"""
return self._parent().types
class Notation(XMLSchemaComponent):
"""<notation>
parent:
schema
attributes:
id -- ID
name -- NCName, Required
public -- token, Required
system -- anyURI
contents:
annotation?
"""
required = ['name', 'public']
attributes = {'id':None, 'name':None, 'public':None, 'system':None}
contents = {'xsd':('annotation')}
tag = 'notation'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
for i in contents:
component = SplitQName(i.getTagName())[1]
if component == 'annotation' and not self.annotation:
self.annotation = Annotation(self)
self.annotation.fromDom(i)
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
class Annotation(XMLSchemaComponent):
"""<annotation>
parent:
all,any,anyAttribute,attribute,attributeGroup,choice,complexContent,
complexType,element,extension,field,group,import,include,key,keyref,
list,notation,redefine,restriction,schema,selector,simpleContent,
simpleType,union,unique
attributes:
id -- ID
contents:
(documentation | appinfo)*
"""
attributes = {'id':None}
contents = {'xsd':('documentation', 'appinfo')}
tag = 'annotation'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.content = None
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
content = []
for i in contents:
component = SplitQName(i.getTagName())[1]
if component == 'documentation':
#print_debug('class %s, documentation skipped' %self.__class__, 5)
continue
elif component == 'appinfo':
#print_debug('class %s, appinfo skipped' %self.__class__, 5)
continue
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
self.content = tuple(content)
class Documentation(XMLSchemaComponent):
"""<documentation>
parent:
annotation
attributes:
source, anyURI
xml:lang, language
contents:
mixed, any
"""
attributes = {'source':None, 'xml:lang':None}
contents = {'xsd':('mixed', 'any')}
tag = 'documentation'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.content = None
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
content = []
for i in contents:
component = SplitQName(i.getTagName())[1]
if component == 'mixed':
#print_debug('class %s, mixed skipped' %self.__class__, 5)
continue
elif component == 'any':
#print_debug('class %s, any skipped' %self.__class__, 5)
continue
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
self.content = tuple(content)
class Appinfo(XMLSchemaComponent):
"""<appinfo>
parent:
annotation
attributes:
source, anyURI
contents:
mixed, any
"""
attributes = {'source':None, 'anyURI':None}
contents = {'xsd':('mixed', 'any')}
tag = 'appinfo'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.content = None
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
content = []
for i in contents:
component = SplitQName(i.getTagName())[1]
if component == 'mixed':
#print_debug('class %s, mixed skipped' %self.__class__, 5)
continue
elif component == 'any':
#print_debug('class %s, any skipped' %self.__class__, 5)
continue
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
self.content = tuple(content)
class XMLSchemaFake:
# This is temporary, for the benefit of WSDL until the real thing works.
def __init__(self, element):
self.targetNamespace = DOM.getAttr(element, 'targetNamespace')
self.element = element
class XMLSchema(XMLSchemaComponent):
"""A schema is a collection of schema components derived from one
or more schema documents, that is, one or more <schema> element
information items. It represents the abstract notion of a schema
rather than a single schema document (or other representation).
<schema>
parent:
ROOT
attributes:
id -- ID
version -- token
xml:lang -- language
targetNamespace -- anyURI
attributeFormDefault -- 'qualified' | 'unqualified', 'unqualified'
elementFormDefault -- 'qualified' | 'unqualified', 'unqualified'
blockDefault -- '#all' | list of
('substitution | 'extension' | 'restriction')
finalDefault -- '#all' | list of
('extension' | 'restriction' | 'list' | 'union')
contents:
((include | import | redefine | annotation)*,
(attribute, attributeGroup, complexType, element, group,
notation, simpleType)*, annotation*)*
attributes -- schema attributes
imports -- import statements
includes -- include statements
redefines --
types -- global simpleType, complexType definitions
elements -- global element declarations
attr_decl -- global attribute declarations
attr_groups -- attribute Groups
model_groups -- model Groups
notations -- global notations
"""
attributes = {'id':None,
'version':None,
'xml:lang':None,
'targetNamespace':None,
'attributeFormDefault':'unqualified',
'elementFormDefault':'unqualified',
'blockDefault':None,
'finalDefault':None}
contents = {'xsd':('include', 'import', 'redefine', 'annotation',
'attribute', 'attributeGroup', 'complexType',
'element', 'group', 'notation', 'simpleType',
'annotation')}
empty_namespace = ''
tag = 'schema'
def __init__(self, parent=None):
"""parent --
instance variables:
targetNamespace -- schema's declared targetNamespace, or empty string.
_imported_schemas -- namespace keyed dict of schema dependencies, if
a schema is provided instance will not resolve import statement.
_included_schemas -- schemaLocation keyed dict of component schemas,
if schema is provided instance will not resolve include statement.
_base_url -- needed for relative URLs support, only works with URLs
relative to initial document.
includes -- collection of include statements
imports -- collection of import statements
elements -- collection of global element declarations
types -- collection of global type definitions
attr_decl -- collection of global attribute declarations
attr_groups -- collection of global attribute group definitions
model_groups -- collection of model group definitions
notations -- collection of notations
"""
self.__node = None
self.targetNamespace = None
XMLSchemaComponent.__init__(self, parent)
f = lambda k: k.attributes['name']
ns = lambda k: k.attributes['namespace']
sl = lambda k: k.attributes['schemaLocation']
self.includes = Collection(self, key=sl)
self.imports = Collection(self, key=ns)
self.elements = Collection(self, key=f)
self.types = Collection(self, key=f)
self.attr_decl = Collection(self, key=f)
self.attr_groups = Collection(self, key=f)
self.model_groups = Collection(self, key=f)
self.notations = Collection(self, key=f)
self._imported_schemas = {}
self._included_schemas = {}
self._base_url = None
def getNode(self):
"""
Interacting with the underlying DOM tree.
"""
return self.__node
def addImportSchema(self, schema):
"""for resolving import statements in Schema instance
schema -- schema instance
_imported_schemas
"""
if not isinstance(schema, XMLSchema):
raise TypeError, 'expecting a Schema instance'
if schema.targetNamespace != self.targetNamespace:
self._imported_schemas[schema.targetNamespace] = schema
else:
raise SchemaError, 'import schema bad targetNamespace'
def addIncludeSchema(self, schemaLocation, schema):
"""for resolving include statements in Schema instance
schemaLocation -- schema location
schema -- schema instance
_included_schemas
"""
if not isinstance(schema, XMLSchema):
raise TypeError, 'expecting a Schema instance'
if not schema.targetNamespace or\
schema.targetNamespace == self.targetNamespace:
self._included_schemas[schemaLocation] = schema
else:
raise SchemaError, 'include schema bad targetNamespace'
def setImportSchemas(self, schema_dict):
"""set the import schema dictionary, which is used to
reference depedent schemas.
"""
self._imported_schemas = schema_dict
def getImportSchemas(self):
"""get the import schema dictionary, which is used to
reference depedent schemas.
"""
return self._imported_schemas
def getSchemaNamespacesToImport(self):
"""returns tuple of namespaces the schema instance has declared
itself to be depedent upon.
"""
return tuple(self.includes.keys())
def setIncludeSchemas(self, schema_dict):
"""set the include schema dictionary, which is keyed with
schemaLocation (uri).
This is a means of providing
schemas to the current schema for content inclusion.
"""
self._included_schemas = schema_dict
def getIncludeSchemas(self):
"""get the include schema dictionary, which is keyed with
schemaLocation (uri).
"""
return self._included_schemas
def getBaseUrl(self):
"""get base url, used for normalizing all relative uri's
"""
return self._base_url
def setBaseUrl(self, url):
"""set base url, used for normalizing all relative uri's
"""
self._base_url = url
def getElementFormDefault(self):
"""return elementFormDefault attribute
"""
return self.attributes.get('elementFormDefault')
def isElementFormDefaultQualified(self):
return self.attributes.get('elementFormDefault') == 'qualified'
def getAttributeFormDefault(self):
"""return attributeFormDefault attribute
"""
return self.attributes.get('attributeFormDefault')
def getBlockDefault(self):
"""return blockDefault attribute
"""
return self.attributes.get('blockDefault')
def getFinalDefault(self):
"""return finalDefault attribute
"""
return self.attributes.get('finalDefault')
def load(self, node, location=None):
self.__node = node
pnode = node.getParentNode()
if pnode:
pname = SplitQName(pnode.getTagName())[1]
if pname == 'types':
attributes = {}
self.setAttributes(pnode)
attributes.update(self.attributes)
self.setAttributes(node)
for k,v in attributes['xmlns'].items():
if not self.attributes['xmlns'].has_key(k):
self.attributes['xmlns'][k] = v
else:
self.setAttributes(node)
else:
self.setAttributes(node)
self.targetNamespace = self.getTargetNamespace()
for childNode in self.getContents(node):
component = SplitQName(childNode.getTagName())[1]
if component == 'include':
tp = self.__class__.Include(self)
tp.fromDom(childNode)
sl = tp.attributes['schemaLocation']
schema = tp.getSchema()
if not self.getIncludeSchemas().has_key(sl):
self.addIncludeSchema(sl, schema)
self.includes[sl] = tp
pn = childNode.getParentNode().getNode()
pn.removeChild(childNode.getNode())
for child in schema.getNode().getNode().childNodes:
pn.appendChild(child.cloneNode(1))
for collection in ['imports','elements','types',
'attr_decl','attr_groups','model_groups',
'notations']:
for k,v in getattr(schema,collection).items():
if not getattr(self,collection).has_key(k):
v._parent = weakref.ref(self)
getattr(self,collection)[k] = v
else:
warnings.warn("Not keeping schema component.")
elif component == 'import':
slocd = SchemaReader.namespaceToSchema
tp = self.__class__.Import(self)
tp.fromDom(childNode)
import_ns = tp.getAttribute('namespace') or\
self.__class__.empty_namespace
schema = slocd.get(import_ns)
if schema is None:
schema = XMLSchema()
slocd[import_ns] = schema
try:
tp.loadSchema(schema)
except SchemaError:
# Dependency declaration, hopefully implementation
# is aware of this namespace (eg. SOAP,WSDL,?)
#warnings.warn(\
# '<import namespace="%s" schemaLocation=?>, %s'\
# %(import_ns, 'failed to load schema instance')
#)
del slocd[import_ns]
class LazyEval(str):
'''Lazy evaluation of import, replace entry in self.imports.'''
def getSchema(namespace):
schema = slocd.get(namespace)
if schema is None:
parent = self._parent()
wstypes = parent
if isinstance(parent, WSDLToolsAdapter):
wstypes = parent.getImportSchemas()
schema = wstypes.get(namespace)
if isinstance(schema, XMLSchema):
self.imports[namespace] = schema
return schema
return None
self.imports[import_ns] = LazyEval(import_ns)
continue
else:
tp._schema = schema
if self.getImportSchemas().has_key(import_ns):
warnings.warn(\
'Detected multiple imports of the namespace "%s" '\
%import_ns)
self.addImportSchema(schema)
# spec says can have multiple imports of same namespace
# but purpose of import is just dependency declaration.
self.imports[import_ns] = tp
elif component == 'redefine':
warnings.warn('redefine is ignored')
elif component == 'annotation':
warnings.warn('annotation is ignored')
elif component == 'attribute':
tp = AttributeDeclaration(self)
tp.fromDom(childNode)
self.attr_decl[tp.getAttribute('name')] = tp
elif component == 'attributeGroup':
tp = AttributeGroupDefinition(self)
tp.fromDom(childNode)
self.attr_groups[tp.getAttribute('name')] = tp
elif component == 'element':
tp = ElementDeclaration(self)
tp.fromDom(childNode)
self.elements[tp.getAttribute('name')] = tp
elif component == 'group':
tp = ModelGroupDefinition(self)
tp.fromDom(childNode)
self.model_groups[tp.getAttribute('name')] = tp
elif component == 'notation':
tp = Notation(self)
tp.fromDom(childNode)
self.notations[tp.getAttribute('name')] = tp
elif component == 'complexType':
tp = ComplexType(self)
tp.fromDom(childNode)
self.types[tp.getAttribute('name')] = tp
elif component == 'simpleType':
tp = SimpleType(self)
tp.fromDom(childNode)
self.types[tp.getAttribute('name')] = tp
else:
break
class Import(XMLSchemaComponent):
"""<import>
parent:
schema
attributes:
id -- ID
namespace -- anyURI
schemaLocation -- anyURI
contents:
annotation?
"""
attributes = {'id':None,
'namespace':None,
'schemaLocation':None}
contents = {'xsd':['annotation']}
tag = 'import'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
self._schema = None
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
if self.attributes['namespace'] == self.getTargetNamespace():
raise SchemaError, 'namespace of schema and import match'
for i in contents:
component = SplitQName(i.getTagName())[1]
if component == 'annotation' and not self.annotation:
self.annotation = Annotation(self)
self.annotation.fromDom(i)
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
def getSchema(self):
"""if schema is not defined, first look for a Schema class instance
in parent Schema. Else if not defined resolve schemaLocation
and create a new Schema class instance, and keep a hard reference.
"""
if not self._schema:
ns = self.attributes['namespace']
schema = self._parent().getImportSchemas().get(ns)
if not schema and self._parent()._parent:
schema = self._parent()._parent().getImportSchemas().get(ns)
if not schema:
url = self.attributes.get('schemaLocation')
if not url:
raise SchemaError, 'namespace(%s) is unknown' %ns
base_url = self._parent().getBaseUrl()
reader = SchemaReader(base_url=base_url)
reader._imports = self._parent().getImportSchemas()
reader._includes = self._parent().getIncludeSchemas()
self._schema = reader.loadFromURL(url)
return self._schema or schema
def loadSchema(self, schema):
"""
"""
base_url = self._parent().getBaseUrl()
reader = SchemaReader(base_url=base_url)
reader._imports = self._parent().getImportSchemas()
reader._includes = self._parent().getIncludeSchemas()
self._schema = schema
if not self.attributes.has_key('schemaLocation'):
raise SchemaError, 'no schemaLocation'
reader.loadFromURL(self.attributes.get('schemaLocation'), schema)
class Include(XMLSchemaComponent):
"""<include schemaLocation>
parent:
schema
attributes:
id -- ID
schemaLocation -- anyURI, required
contents:
annotation?
"""
required = ['schemaLocation']
attributes = {'id':None,
'schemaLocation':None}
contents = {'xsd':['annotation']}
tag = 'include'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
self._schema = None
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
for i in contents:
component = SplitQName(i.getTagName())[1]
if component == 'annotation' and not self.annotation:
self.annotation = Annotation(self)
self.annotation.fromDom(i)
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
def getSchema(self):
"""if schema is not defined, first look for a Schema class instance
in parent Schema. Else if not defined resolve schemaLocation
and create a new Schema class instance.
"""
if not self._schema:
schema = self._parent()
self._schema = schema.getIncludeSchemas().get(\
self.attributes['schemaLocation']
)
if not self._schema:
url = self.attributes['schemaLocation']
reader = SchemaReader(base_url=schema.getBaseUrl())
reader._imports = schema.getImportSchemas()
reader._includes = schema.getIncludeSchemas()
# create schema before loading so chameleon include
# will evalute targetNamespace correctly.
self._schema = XMLSchema(schema)
reader.loadFromURL(url, self._schema)
return self._schema
class AttributeDeclaration(XMLSchemaComponent,\
AttributeMarker,\
DeclarationMarker):
"""<attribute name>
parent:
schema
attributes:
id -- ID
name -- NCName, required
type -- QName
default -- string
fixed -- string
contents:
annotation?, simpleType?
"""
required = ['name']
attributes = {'id':None,
'name':None,
'type':None,
'default':None,
'fixed':None}
contents = {'xsd':['annotation','simpleType']}
tag = 'attribute'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
self.content = None
def fromDom(self, node):
""" No list or union support
"""
self.setAttributes(node)
contents = self.getContents(node)
for i in contents:
component = SplitQName(i.getTagName())[1]
if component == 'annotation' and not self.annotation:
self.annotation = Annotation(self)
self.annotation.fromDom(i)
elif component == 'simpleType':
self.content = AnonymousSimpleType(self)
self.content.fromDom(i)
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
class LocalAttributeDeclaration(AttributeDeclaration,\
AttributeMarker,\
LocalMarker,\
DeclarationMarker):
"""<attribute name>
parent:
complexType, restriction, extension, attributeGroup
attributes:
id -- ID
name -- NCName, required
type -- QName
form -- ('qualified' | 'unqualified'), schema.attributeFormDefault
use -- ('optional' | 'prohibited' | 'required'), optional
default -- string
fixed -- string
contents:
annotation?, simpleType?
"""
required = ['name']
attributes = {'id':None,
'name':None,
'type':None,
'form':lambda self: GetSchema(self).getAttributeFormDefault(),
'use':'optional',
'default':None,
'fixed':None}
contents = {'xsd':['annotation','simpleType']}
def __init__(self, parent):
AttributeDeclaration.__init__(self, parent)
self.annotation = None
self.content = None
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
for i in contents:
component = SplitQName(i.getTagName())[1]
if component == 'annotation' and not self.annotation:
self.annotation = Annotation(self)
self.annotation.fromDom(i)
elif component == 'simpleType':
self.content = AnonymousSimpleType(self)
self.content.fromDom(i)
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
class AttributeWildCard(XMLSchemaComponent,\
AttributeMarker,\
DeclarationMarker,\
WildCardMarker):
"""<anyAttribute>
parents:
complexType, restriction, extension, attributeGroup
attributes:
id -- ID
namespace -- '##any' | '##other' |
(anyURI* | '##targetNamespace' | '##local'), ##any
processContents -- 'lax' | 'skip' | 'strict', strict
contents:
annotation?
"""
attributes = {'id':None,
'namespace':'##any',
'processContents':'strict'}
contents = {'xsd':['annotation']}
tag = 'anyAttribute'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
for i in contents:
component = SplitQName(i.getTagName())[1]
if component == 'annotation' and not self.annotation:
self.annotation = Annotation(self)
self.annotation.fromDom(i)
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
class AttributeReference(XMLSchemaComponent,\
AttributeMarker,\
ReferenceMarker):
"""<attribute ref>
parents:
complexType, restriction, extension, attributeGroup
attributes:
id -- ID
ref -- QName, required
use -- ('optional' | 'prohibited' | 'required'), optional
default -- string
fixed -- string
contents:
annotation?
"""
required = ['ref']
attributes = {'id':None,
'ref':None,
'use':'optional',
'default':None,
'fixed':None}
contents = {'xsd':['annotation']}
tag = 'attribute'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
def getAttributeDeclaration(self, attribute='ref'):
return XMLSchemaComponent.getAttributeDeclaration(self, attribute)
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
for i in contents:
component = SplitQName(i.getTagName())[1]
if component == 'annotation' and not self.annotation:
self.annotation = Annotation(self)
self.annotation.fromDom(i)
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
class AttributeGroupDefinition(XMLSchemaComponent,\
AttributeGroupMarker,\
DefinitionMarker):
"""<attributeGroup name>
parents:
schema, redefine
attributes:
id -- ID
name -- NCName, required
contents:
annotation?, (attribute | attributeGroup)*, anyAttribute?
"""
required = ['name']
attributes = {'id':None,
'name':None}
contents = {'xsd':['annotation', 'attribute', 'attributeGroup', 'anyAttribute']}
tag = 'attributeGroup'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
self.attr_content = None
def getAttributeContent(self):
return self.attr_content
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
content = []
for indx in range(len(contents)):
component = SplitQName(contents[indx].getTagName())[1]
if (component == 'annotation') and (not indx):
self.annotation = Annotation(self)
self.annotation.fromDom(contents[indx])
elif component == 'attribute':
if contents[indx].hasattr('name'):
content.append(LocalAttributeDeclaration(self))
elif contents[indx].hasattr('ref'):
content.append(AttributeReference(self))
else:
raise SchemaError, 'Unknown attribute type'
content[-1].fromDom(contents[indx])
elif component == 'attributeGroup':
content.append(AttributeGroupReference(self))
content[-1].fromDom(contents[indx])
elif component == 'anyAttribute':
if len(contents) != indx+1:
raise SchemaError, 'anyAttribute is out of order in %s' %self.getItemTrace()
content.append(AttributeWildCard(self))
content[-1].fromDom(contents[indx])
else:
raise SchemaError, 'Unknown component (%s)' %(contents[indx].getTagName())
self.attr_content = tuple(content)
class AttributeGroupReference(XMLSchemaComponent,\
AttributeGroupMarker,\
ReferenceMarker):
"""<attributeGroup ref>
parents:
complexType, restriction, extension, attributeGroup
attributes:
id -- ID
ref -- QName, required
contents:
annotation?
"""
required = ['ref']
attributes = {'id':None,
'ref':None}
contents = {'xsd':['annotation']}
tag = 'attributeGroup'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
def getAttributeGroup(self, attribute='ref'):
"""attribute -- attribute with a QName value (eg. type).
collection -- check types collection in parent Schema instance
"""
return XMLSchemaComponent.getAttributeGroup(self, attribute)
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
for i in contents:
component = SplitQName(i.getTagName())[1]
if component == 'annotation' and not self.annotation:
self.annotation = Annotation(self)
self.annotation.fromDom(i)
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
######################################################
# Elements
#####################################################
class IdentityConstrants(XMLSchemaComponent):
"""Allow one to uniquely identify nodes in a document and ensure the
integrity of references between them.
attributes -- dictionary of attributes
selector -- XPath to selected nodes
fields -- list of XPath to key field
"""
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.selector = None
self.fields = None
self.annotation = None
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
fields = []
for i in contents:
component = SplitQName(i.getTagName())[1]
if component in self.__class__.contents['xsd']:
if component == 'annotation' and not self.annotation:
self.annotation = Annotation(self)
self.annotation.fromDom(i)
elif component == 'selector':
self.selector = self.Selector(self)
self.selector.fromDom(i)
continue
elif component == 'field':
fields.append(self.Field(self))
fields[-1].fromDom(i)
continue
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
self.fields = tuple(fields)
class Constraint(XMLSchemaComponent):
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
for i in contents:
component = SplitQName(i.getTagName())[1]
if component in self.__class__.contents['xsd']:
if component == 'annotation' and not self.annotation:
self.annotation = Annotation(self)
self.annotation.fromDom(i)
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
class Selector(Constraint):
"""<selector xpath>
parent:
unique, key, keyref
attributes:
id -- ID
xpath -- XPath subset, required
contents:
annotation?
"""
required = ['xpath']
attributes = {'id':None,
'xpath':None}
contents = {'xsd':['annotation']}
tag = 'selector'
class Field(Constraint):
"""<field xpath>
parent:
unique, key, keyref
attributes:
id -- ID
xpath -- XPath subset, required
contents:
annotation?
"""
required = ['xpath']
attributes = {'id':None,
'xpath':None}
contents = {'xsd':['annotation']}
tag = 'field'
class Unique(IdentityConstrants):
"""<unique name> Enforce fields are unique w/i a specified scope.
parent:
element
attributes:
id -- ID
name -- NCName, required
contents:
annotation?, selector, field+
"""
required = ['name']
attributes = {'id':None,
'name':None}
contents = {'xsd':['annotation', 'selector', 'field']}
tag = 'unique'
class Key(IdentityConstrants):
"""<key name> Enforce fields are unique w/i a specified scope, and all
field values are present w/i document. Fields cannot
be nillable.
parent:
element
attributes:
id -- ID
name -- NCName, required
contents:
annotation?, selector, field+
"""
required = ['name']
attributes = {'id':None,
'name':None}
contents = {'xsd':['annotation', 'selector', 'field']}
tag = 'key'
class KeyRef(IdentityConstrants):
"""<keyref name refer> Ensure a match between two sets of values in an
instance.
parent:
element
attributes:
id -- ID
name -- NCName, required
refer -- QName, required
contents:
annotation?, selector, field+
"""
required = ['name', 'refer']
attributes = {'id':None,
'name':None,
'refer':None}
contents = {'xsd':['annotation', 'selector', 'field']}
tag = 'keyref'
class ElementDeclaration(XMLSchemaComponent,\
ElementMarker,\
DeclarationMarker):
"""<element name>
parents:
schema
attributes:
id -- ID
name -- NCName, required
type -- QName
default -- string
fixed -- string
nillable -- boolean, false
abstract -- boolean, false
substitutionGroup -- QName
block -- ('#all' | ('substition' | 'extension' | 'restriction')*),
schema.blockDefault
final -- ('#all' | ('extension' | 'restriction')*),
schema.finalDefault
contents:
annotation?, (simpleType,complexType)?, (key | keyref | unique)*
"""
required = ['name']
attributes = {'id':None,
'name':None,
'type':None,
'default':None,
'fixed':None,
'nillable':0,
'abstract':0,
'substitutionGroup':None,
'block':lambda self: self._parent().getBlockDefault(),
'final':lambda self: self._parent().getFinalDefault()}
contents = {'xsd':['annotation', 'simpleType', 'complexType', 'key',\
'keyref', 'unique']}
tag = 'element'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
self.content = None
self.constraints = ()
def isQualified(self):
"""Global elements are always qualified.
"""
return True
def getAttribute(self, attribute):
"""return attribute.
If attribute is type and it's None, and no simple or complex content,
return the default type "xsd:anyType"
"""
value = XMLSchemaComponent.getAttribute(self, attribute)
if attribute != 'type' or value is not None:
return value
if self.content is not None:
return None
parent = self
while 1:
nsdict = parent.attributes[XMLSchemaComponent.xmlns]
for k,v in nsdict.items():
if v not in SCHEMA.XSD_LIST: continue
return TypeDescriptionComponent((v, 'anyType'))
if isinstance(parent, WSDLToolsAdapter)\
or not hasattr(parent, '_parent'):
break
parent = parent._parent()
raise SchemaError, 'failed to locate the XSD namespace'
def getElementDeclaration(self, attribute):
raise Warning, 'invalid operation for <%s>' %self.tag
def getTypeDefinition(self, attribute=None):
"""If attribute is None, "type" is assumed, return the corresponding
representation of the global type definition (TypeDefinition),
or the local definition if don't find "type". To maintain backwards
compat, if attribute is provided call base class method.
"""
if attribute:
return XMLSchemaComponent.getTypeDefinition(self, attribute)
gt = XMLSchemaComponent.getTypeDefinition(self, 'type')
if gt:
return gt
return self.content
def getConstraints(self):
return self._constraints
def setConstraints(self, constraints):
self._constraints = tuple(constraints)
constraints = property(getConstraints, setConstraints, None, "tuple of key, keyref, unique constraints")
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
constraints = []
for i in contents:
component = SplitQName(i.getTagName())[1]
if component in self.__class__.contents['xsd']:
if component == 'annotation' and not self.annotation:
self.annotation = Annotation(self)
self.annotation.fromDom(i)
elif component == 'simpleType' and not self.content:
self.content = AnonymousSimpleType(self)
self.content.fromDom(i)
elif component == 'complexType' and not self.content:
self.content = LocalComplexType(self)
self.content.fromDom(i)
elif component == 'key':
constraints.append(Key(self))
constraints[-1].fromDom(i)
elif component == 'keyref':
constraints.append(KeyRef(self))
constraints[-1].fromDom(i)
elif component == 'unique':
constraints.append(Unique(self))
constraints[-1].fromDom(i)
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
self.constraints = constraints
class LocalElementDeclaration(ElementDeclaration,\
LocalMarker):
"""<element>
parents:
all, choice, sequence
attributes:
id -- ID
name -- NCName, required
form -- ('qualified' | 'unqualified'), schema.elementFormDefault
type -- QName
minOccurs -- Whole Number, 1
maxOccurs -- (Whole Number | 'unbounded'), 1
default -- string
fixed -- string
nillable -- boolean, false
block -- ('#all' | ('extension' | 'restriction')*), schema.blockDefault
contents:
annotation?, (simpleType,complexType)?, (key | keyref | unique)*
"""
required = ['name']
attributes = {'id':None,
'name':None,
'form':lambda self: GetSchema(self).getElementFormDefault(),
'type':None,
'minOccurs':'1',
'maxOccurs':'1',
'default':None,
'fixed':None,
'nillable':0,
'abstract':0,
'block':lambda self: GetSchema(self).getBlockDefault()}
contents = {'xsd':['annotation', 'simpleType', 'complexType', 'key',\
'keyref', 'unique']}
def isQualified(self):
"""
Local elements can be qualified or unqualifed according
to the attribute form, or the elementFormDefault. By default
local elements are unqualified.
"""
form = self.getAttribute('form')
if form == 'qualified':
return True
if form == 'unqualified':
return False
raise SchemaError, 'Bad form (%s) for element: %s' %(form, self.getItemTrace())
class ElementReference(XMLSchemaComponent,\
ElementMarker,\
ReferenceMarker):
"""<element ref>
parents:
all, choice, sequence
attributes:
id -- ID
ref -- QName, required
minOccurs -- Whole Number, 1
maxOccurs -- (Whole Number | 'unbounded'), 1
contents:
annotation?
"""
required = ['ref']
attributes = {'id':None,
'ref':None,
'minOccurs':'1',
'maxOccurs':'1'}
contents = {'xsd':['annotation']}
tag = 'element'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
def getElementDeclaration(self, attribute=None):
"""If attribute is None, "ref" is assumed, return the corresponding
representation of the global element declaration (ElementDeclaration),
To maintain backwards compat, if attribute is provided call base class method.
"""
if attribute:
return XMLSchemaComponent.getElementDeclaration(self, attribute)
return XMLSchemaComponent.getElementDeclaration(self, 'ref')
def fromDom(self, node):
self.annotation = None
self.setAttributes(node)
for i in self.getContents(node):
component = SplitQName(i.getTagName())[1]
if component in self.__class__.contents['xsd']:
if component == 'annotation' and not self.annotation:
self.annotation = Annotation(self)
self.annotation.fromDom(i)
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
class ElementWildCard(LocalElementDeclaration, WildCardMarker):
"""<any>
parents:
choice, sequence
attributes:
id -- ID
minOccurs -- Whole Number, 1
maxOccurs -- (Whole Number | 'unbounded'), 1
namespace -- '##any' | '##other' |
(anyURI* | '##targetNamespace' | '##local'), ##any
processContents -- 'lax' | 'skip' | 'strict', strict
contents:
annotation?
"""
required = []
attributes = {'id':None,
'minOccurs':'1',
'maxOccurs':'1',
'namespace':'##any',
'processContents':'strict'}
contents = {'xsd':['annotation']}
tag = 'any'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
def isQualified(self):
"""
Global elements are always qualified, but if processContents
are not strict could have dynamically generated local elements.
"""
return GetSchema(self).isElementFormDefaultQualified()
def getAttribute(self, attribute):
"""return attribute.
"""
return XMLSchemaComponent.getAttribute(self, attribute)
def getTypeDefinition(self, attribute):
raise Warning, 'invalid operation for <%s>' % self.tag
def fromDom(self, node):
self.annotation = None
self.setAttributes(node)
for i in self.getContents(node):
component = SplitQName(i.getTagName())[1]
if component in self.__class__.contents['xsd']:
if component == 'annotation' and not self.annotation:
self.annotation = Annotation(self)
self.annotation.fromDom(i)
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
######################################################
# Model Groups
#####################################################
class Sequence(XMLSchemaComponent,\
SequenceMarker):
"""<sequence>
parents:
complexType, extension, restriction, group, choice, sequence
attributes:
id -- ID
minOccurs -- Whole Number, 1
maxOccurs -- (Whole Number | 'unbounded'), 1
contents:
annotation?, (element | group | choice | sequence | any)*
"""
attributes = {'id':None,
'minOccurs':'1',
'maxOccurs':'1'}
contents = {'xsd':['annotation', 'element', 'group', 'choice', 'sequence',\
'any']}
tag = 'sequence'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
self.content = None
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
content = []
for i in contents:
component = SplitQName(i.getTagName())[1]
if component in self.__class__.contents['xsd']:
if component == 'annotation' and not self.annotation:
self.annotation = Annotation(self)
self.annotation.fromDom(i)
continue
elif component == 'element':
if i.hasattr('ref'):
content.append(ElementReference(self))
else:
content.append(LocalElementDeclaration(self))
elif component == 'group':
content.append(ModelGroupReference(self))
elif component == 'choice':
content.append(Choice(self))
elif component == 'sequence':
content.append(Sequence(self))
elif component == 'any':
content.append(ElementWildCard(self))
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
content[-1].fromDom(i)
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
self.content = tuple(content)
class All(XMLSchemaComponent,\
AllMarker):
"""<all>
parents:
complexType, extension, restriction, group
attributes:
id -- ID
minOccurs -- '0' | '1', 1
maxOccurs -- '1', 1
contents:
annotation?, element*
"""
attributes = {'id':None,
'minOccurs':'1',
'maxOccurs':'1'}
contents = {'xsd':['annotation', 'element']}
tag = 'all'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
self.content = None
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
content = []
for i in contents:
component = SplitQName(i.getTagName())[1]
if component in self.__class__.contents['xsd']:
if component == 'annotation' and not self.annotation:
self.annotation = Annotation(self)
self.annotation.fromDom(i)
continue
elif component == 'element':
if i.hasattr('ref'):
content.append(ElementReference(self))
else:
content.append(LocalElementDeclaration(self))
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
content[-1].fromDom(i)
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
self.content = tuple(content)
class Choice(XMLSchemaComponent,\
ChoiceMarker):
"""<choice>
parents:
complexType, extension, restriction, group, choice, sequence
attributes:
id -- ID
minOccurs -- Whole Number, 1
maxOccurs -- (Whole Number | 'unbounded'), 1
contents:
annotation?, (element | group | choice | sequence | any)*
"""
attributes = {'id':None,
'minOccurs':'1',
'maxOccurs':'1'}
contents = {'xsd':['annotation', 'element', 'group', 'choice', 'sequence',\
'any']}
tag = 'choice'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
self.content = None
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
content = []
for i in contents:
component = SplitQName(i.getTagName())[1]
if component in self.__class__.contents['xsd']:
if component == 'annotation' and not self.annotation:
self.annotation = Annotation(self)
self.annotation.fromDom(i)
continue
elif component == 'element':
if i.hasattr('ref'):
content.append(ElementReference(self))
else:
content.append(LocalElementDeclaration(self))
elif component == 'group':
content.append(ModelGroupReference(self))
elif component == 'choice':
content.append(Choice(self))
elif component == 'sequence':
content.append(Sequence(self))
elif component == 'any':
content.append(ElementWildCard(self))
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
content[-1].fromDom(i)
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
self.content = tuple(content)
class ModelGroupDefinition(XMLSchemaComponent,\
ModelGroupMarker,\
DefinitionMarker):
"""<group name>
parents:
redefine, schema
attributes:
id -- ID
name -- NCName, required
contents:
annotation?, (all | choice | sequence)?
"""
required = ['name']
attributes = {'id':None,
'name':None}
contents = {'xsd':['annotation', 'all', 'choice', 'sequence']}
tag = 'group'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
self.content = None
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
for i in contents:
component = SplitQName(i.getTagName())[1]
if component in self.__class__.contents['xsd']:
if component == 'annotation' and not self.annotation:
self.annotation = Annotation(self)
self.annotation.fromDom(i)
continue
elif component == 'all' and not self.content:
self.content = All(self)
elif component == 'choice' and not self.content:
self.content = Choice(self)
elif component == 'sequence' and not self.content:
self.content = Sequence(self)
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
self.content.fromDom(i)
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
class ModelGroupReference(XMLSchemaComponent,\
ModelGroupMarker,\
ReferenceMarker):
"""<group ref>
parents:
choice, complexType, extension, restriction, sequence
attributes:
id -- ID
ref -- NCName, required
minOccurs -- Whole Number, 1
maxOccurs -- (Whole Number | 'unbounded'), 1
contents:
annotation?
"""
required = ['ref']
attributes = {'id':None,
'ref':None,
'minOccurs':'1',
'maxOccurs':'1'}
contents = {'xsd':['annotation']}
tag = 'group'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
def getModelGroupReference(self):
return self.getModelGroup('ref')
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
for i in contents:
component = SplitQName(i.getTagName())[1]
if component in self.__class__.contents['xsd']:
if component == 'annotation' and not self.annotation:
self.annotation = Annotation(self)
self.annotation.fromDom(i)
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
class ComplexType(XMLSchemaComponent,\
DefinitionMarker,\
ComplexMarker):
"""<complexType name>
parents:
redefine, schema
attributes:
id -- ID
name -- NCName, required
mixed -- boolean, false
abstract -- boolean, false
block -- ('#all' | ('extension' | 'restriction')*), schema.blockDefault
final -- ('#all' | ('extension' | 'restriction')*), schema.finalDefault
contents:
annotation?, (simpleContent | complexContent |
((group | all | choice | sequence)?, (attribute | attributeGroup)*, anyAttribute?))
"""
required = ['name']
attributes = {'id':None,
'name':None,
'mixed':0,
'abstract':0,
'block':lambda self: self._parent().getBlockDefault(),
'final':lambda self: self._parent().getFinalDefault()}
contents = {'xsd':['annotation', 'simpleContent', 'complexContent',\
'group', 'all', 'choice', 'sequence', 'attribute', 'attributeGroup',\
'anyAttribute', 'any']}
tag = 'complexType'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
self.content = None
self.attr_content = None
def isMixed(self):
m = self.getAttribute('mixed')
if m == 0 or m == False:
return False
if isinstance(m, basestring) is True:
if m in ('false', '0'):
return False
if m in ('true', '1'):
return True
raise SchemaError, 'invalid value for attribute mixed(%s): %s'\
%(m, self.getItemTrace())
def getAttributeContent(self):
return self.attr_content
def getElementDeclaration(self, attribute):
raise Warning, 'invalid operation for <%s>' %self.tag
def getTypeDefinition(self, attribute):
raise Warning, 'invalid operation for <%s>' %self.tag
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
indx = 0
num = len(contents)
if not num:
return
component = SplitQName(contents[indx].getTagName())[1]
if component == 'annotation':
self.annotation = Annotation(self)
self.annotation.fromDom(contents[indx])
indx += 1
component = SplitQName(contents[indx].getTagName())[1]
self.content = None
if component == 'simpleContent':
self.content = self.__class__.SimpleContent(self)
self.content.fromDom(contents[indx])
elif component == 'complexContent':
self.content = self.__class__.ComplexContent(self)
self.content.fromDom(contents[indx])
else:
if component == 'all':
self.content = All(self)
elif component == 'choice':
self.content = Choice(self)
elif component == 'sequence':
self.content = Sequence(self)
elif component == 'group':
self.content = ModelGroupReference(self)
if self.content:
self.content.fromDom(contents[indx])
indx += 1
self.attr_content = []
while indx < num:
component = SplitQName(contents[indx].getTagName())[1]
if component == 'attribute':
if contents[indx].hasattr('ref'):
self.attr_content.append(AttributeReference(self))
else:
self.attr_content.append(LocalAttributeDeclaration(self))
elif component == 'attributeGroup':
self.attr_content.append(AttributeGroupReference(self))
elif component == 'anyAttribute':
self.attr_content.append(AttributeWildCard(self))
else:
raise SchemaError, 'Unknown component (%s): %s' \
%(contents[indx].getTagName(),self.getItemTrace())
self.attr_content[-1].fromDom(contents[indx])
indx += 1
class _DerivedType(XMLSchemaComponent):
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
# XXX remove attribute derivation, inconsistent
self.derivation = None
self.content = None
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
for i in contents:
component = SplitQName(i.getTagName())[1]
if component in self.__class__.contents['xsd']:
if component == 'annotation' and not self.annotation:
self.annotation = Annotation(self)
self.annotation.fromDom(i)
continue
elif component == 'restriction' and not self.derivation:
self.derivation = self.__class__.Restriction(self)
elif component == 'extension' and not self.derivation:
self.derivation = self.__class__.Extension(self)
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
self.derivation.fromDom(i)
self.content = self.derivation
class ComplexContent(_DerivedType,\
ComplexMarker):
"""<complexContent>
parents:
complexType
attributes:
id -- ID
mixed -- boolean, false
contents:
annotation?, (restriction | extension)
"""
attributes = {'id':None,
'mixed':0}
contents = {'xsd':['annotation', 'restriction', 'extension']}
tag = 'complexContent'
def isMixed(self):
m = self.getAttribute('mixed')
if m == 0 or m == False:
return False
if isinstance(m, basestring) is True:
if m in ('false', '0'):
return False
if m in ('true', '1'):
return True
raise SchemaError, 'invalid value for attribute mixed(%s): %s'\
%(m, self.getItemTrace())
class _DerivationBase(XMLSchemaComponent):
"""<extension>,<restriction>
parents:
complexContent
attributes:
id -- ID
base -- QName, required
contents:
annotation?, (group | all | choice | sequence)?,
(attribute | attributeGroup)*, anyAttribute?
"""
required = ['base']
attributes = {'id':None,
'base':None }
contents = {'xsd':['annotation', 'group', 'all', 'choice',\
'sequence', 'attribute', 'attributeGroup', 'anyAttribute']}
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
self.content = None
self.attr_content = None
def getAttributeContent(self):
return self.attr_content
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
indx = 0
num = len(contents)
#XXX ugly
if not num:
return
component = SplitQName(contents[indx].getTagName())[1]
if component == 'annotation':
self.annotation = Annotation(self)
self.annotation.fromDom(contents[indx])
indx += 1
component = SplitQName(contents[indx].getTagName())[1]
if component == 'all':
self.content = All(self)
self.content.fromDom(contents[indx])
indx += 1
elif component == 'choice':
self.content = Choice(self)
self.content.fromDom(contents[indx])
indx += 1
elif component == 'sequence':
self.content = Sequence(self)
self.content.fromDom(contents[indx])
indx += 1
elif component == 'group':
self.content = ModelGroupReference(self)
self.content.fromDom(contents[indx])
indx += 1
else:
self.content = None
self.attr_content = []
while indx < num:
component = SplitQName(contents[indx].getTagName())[1]
if component == 'attribute':
if contents[indx].hasattr('ref'):
self.attr_content.append(AttributeReference(self))
else:
self.attr_content.append(LocalAttributeDeclaration(self))
elif component == 'attributeGroup':
if contents[indx].hasattr('ref'):
self.attr_content.append(AttributeGroupReference(self))
else:
self.attr_content.append(AttributeGroupDefinition(self))
elif component == 'anyAttribute':
self.attr_content.append(AttributeWildCard(self))
else:
raise SchemaError, 'Unknown component (%s)' %(contents[indx].getTagName())
self.attr_content[-1].fromDom(contents[indx])
indx += 1
class Extension(_DerivationBase,
ExtensionMarker):
"""<extension base>
parents:
complexContent
attributes:
id -- ID
base -- QName, required
contents:
annotation?, (group | all | choice | sequence)?,
(attribute | attributeGroup)*, anyAttribute?
"""
tag = 'extension'
class Restriction(_DerivationBase,\
RestrictionMarker):
"""<restriction base>
parents:
complexContent
attributes:
id -- ID
base -- QName, required
contents:
annotation?, (group | all | choice | sequence)?,
(attribute | attributeGroup)*, anyAttribute?
"""
tag = 'restriction'
class SimpleContent(_DerivedType,\
SimpleMarker):
"""<simpleContent>
parents:
complexType
attributes:
id -- ID
contents:
annotation?, (restriction | extension)
"""
attributes = {'id':None}
contents = {'xsd':['annotation', 'restriction', 'extension']}
tag = 'simpleContent'
class Extension(XMLSchemaComponent,\
ExtensionMarker):
"""<extension base>
parents:
simpleContent
attributes:
id -- ID
base -- QName, required
contents:
annotation?, (attribute | attributeGroup)*, anyAttribute?
"""
required = ['base']
attributes = {'id':None,
'base':None }
contents = {'xsd':['annotation', 'attribute', 'attributeGroup',
'anyAttribute']}
tag = 'extension'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
self.attr_content = None
def getAttributeContent(self):
return self.attr_content
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
indx = 0
num = len(contents)
if num:
component = SplitQName(contents[indx].getTagName())[1]
if component == 'annotation':
self.annotation = Annotation(self)
self.annotation.fromDom(contents[indx])
indx += 1
component = SplitQName(contents[indx].getTagName())[1]
content = []
while indx < num:
component = SplitQName(contents[indx].getTagName())[1]
if component == 'attribute':
if contents[indx].hasattr('ref'):
content.append(AttributeReference(self))
else:
content.append(LocalAttributeDeclaration(self))
elif component == 'attributeGroup':
content.append(AttributeGroupReference(self))
elif component == 'anyAttribute':
content.append(AttributeWildCard(self))
else:
raise SchemaError, 'Unknown component (%s)'\
%(contents[indx].getTagName())
content[-1].fromDom(contents[indx])
indx += 1
self.attr_content = tuple(content)
class Restriction(XMLSchemaComponent,\
RestrictionMarker):
"""<restriction base>
parents:
simpleContent
attributes:
id -- ID
base -- QName, required
contents:
annotation?, simpleType?, (enumeration | length |
maxExclusive | maxInclusive | maxLength | minExclusive |
minInclusive | minLength | pattern | fractionDigits |
totalDigits | whiteSpace)*, (attribute | attributeGroup)*,
anyAttribute?
"""
required = ['base']
attributes = {'id':None,
'base':None }
contents = {'xsd':['annotation', 'simpleType', 'attribute',\
'attributeGroup', 'anyAttribute'] + RestrictionMarker.facets}
tag = 'restriction'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
self.content = None
self.attr_content = None
def getAttributeContent(self):
return self.attr_content
def fromDom(self, node):
self.content = []
self.setAttributes(node)
contents = self.getContents(node)
indx = 0
num = len(contents)
component = SplitQName(contents[indx].getTagName())[1]
if component == 'annotation':
self.annotation = Annotation(self)
self.annotation.fromDom(contents[indx])
indx += 1
component = SplitQName(contents[indx].getTagName())[1]
content = []
while indx < num:
component = SplitQName(contents[indx].getTagName())[1]
if component == 'attribute':
if contents[indx].hasattr('ref'):
content.append(AttributeReference(self))
else:
content.append(LocalAttributeDeclaration(self))
elif component == 'attributeGroup':
content.append(AttributeGroupReference(self))
elif component == 'anyAttribute':
content.append(AttributeWildCard(self))
elif component == 'simpleType':
self.content.append(AnonymousSimpleType(self))
self.content[-1].fromDom(contents[indx])
else:
raise SchemaError, 'Unknown component (%s)'\
%(contents[indx].getTagName())
content[-1].fromDom(contents[indx])
indx += 1
self.attr_content = tuple(content)
class LocalComplexType(ComplexType,\
LocalMarker):
"""<complexType>
parents:
element
attributes:
id -- ID
mixed -- boolean, false
contents:
annotation?, (simpleContent | complexContent |
((group | all | choice | sequence)?, (attribute | attributeGroup)*, anyAttribute?))
"""
required = []
attributes = {'id':None,
'mixed':0}
tag = 'complexType'
class SimpleType(XMLSchemaComponent,\
DefinitionMarker,\
SimpleMarker):
"""<simpleType name>
parents:
redefine, schema
attributes:
id -- ID
name -- NCName, required
final -- ('#all' | ('extension' | 'restriction' | 'list' | 'union')*),
schema.finalDefault
contents:
annotation?, (restriction | list | union)
"""
required = ['name']
attributes = {'id':None,
'name':None,
'final':lambda self: self._parent().getFinalDefault()}
contents = {'xsd':['annotation', 'restriction', 'list', 'union']}
tag = 'simpleType'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
self.content = None
def getElementDeclaration(self, attribute):
raise Warning, 'invalid operation for <%s>' %self.tag
def getTypeDefinition(self, attribute):
raise Warning, 'invalid operation for <%s>' %self.tag
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
for child in contents:
component = SplitQName(child.getTagName())[1]
if component == 'annotation':
self.annotation = Annotation(self)
self.annotation.fromDom(child)
continue
break
else:
return
if component == 'restriction':
self.content = self.__class__.Restriction(self)
elif component == 'list':
self.content = self.__class__.List(self)
elif component == 'union':
self.content = self.__class__.Union(self)
else:
raise SchemaError, 'Unknown component (%s)' %(component)
self.content.fromDom(child)
class Restriction(XMLSchemaComponent,\
RestrictionMarker):
"""<restriction base>
parents:
simpleType
attributes:
id -- ID
base -- QName, required or simpleType child
contents:
annotation?, simpleType?, (enumeration | length |
maxExclusive | maxInclusive | maxLength | minExclusive |
minInclusive | minLength | pattern | fractionDigits |
totalDigits | whiteSpace)*
"""
attributes = {'id':None,
'base':None }
contents = {'xsd':['annotation', 'simpleType']+RestrictionMarker.facets}
tag = 'restriction'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
self.content = None
self.facets = None
def getAttributeBase(self):
return XMLSchemaComponent.getAttribute(self, 'base')
def getTypeDefinition(self, attribute='base'):
return XMLSchemaComponent.getTypeDefinition(self, attribute)
def getSimpleTypeContent(self):
for el in self.content:
if el.isSimple(): return el
return None
def fromDom(self, node):
self.facets = []
self.setAttributes(node)
contents = self.getContents(node)
content = []
for indx in range(len(contents)):
component = SplitQName(contents[indx].getTagName())[1]
if (component == 'annotation') and (not indx):
self.annotation = Annotation(self)
self.annotation.fromDom(contents[indx])
continue
elif (component == 'simpleType') and (not indx or indx == 1):
content.append(AnonymousSimpleType(self))
content[-1].fromDom(contents[indx])
elif component in RestrictionMarker.facets:
self.facets.append(contents[indx])
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
self.content = tuple(content)
class Union(XMLSchemaComponent,
UnionMarker):
"""<union>
parents:
simpleType
attributes:
id -- ID
memberTypes -- list of QNames, required or simpleType child.
contents:
annotation?, simpleType*
"""
attributes = {'id':None,
'memberTypes':None }
contents = {'xsd':['annotation', 'simpleType']}
tag = 'union'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
self.content = None
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
content = []
for indx in range(len(contents)):
component = SplitQName(contents[indx].getTagName())[1]
if (component == 'annotation') and (not indx):
self.annotation = Annotation(self)
self.annotation.fromDom(contents[indx])
elif (component == 'simpleType'):
content.append(AnonymousSimpleType(self))
content[-1].fromDom(contents[indx])
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
self.content = tuple(content)
class List(XMLSchemaComponent,
ListMarker):
"""<list>
parents:
simpleType
attributes:
id -- ID
itemType -- QName, required or simpleType child.
contents:
annotation?, simpleType?
"""
attributes = {'id':None,
'itemType':None }
contents = {'xsd':['annotation', 'simpleType']}
tag = 'list'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
self.content = None
def getItemType(self):
return self.attributes.get('itemType')
def getTypeDefinition(self, attribute='itemType'):
"""
return the type refered to by itemType attribute or
the simpleType content. If returns None, then the
type refered to by itemType is primitive.
"""
tp = XMLSchemaComponent.getTypeDefinition(self, attribute)
return tp or self.content
def fromDom(self, node):
self.annotation = None
self.content = None
self.setAttributes(node)
contents = self.getContents(node)
for indx in range(len(contents)):
component = SplitQName(contents[indx].getTagName())[1]
if (component == 'annotation') and (not indx):
self.annotation = Annotation(self)
self.annotation.fromDom(contents[indx])
elif (component == 'simpleType'):
self.content = AnonymousSimpleType(self)
self.content.fromDom(contents[indx])
break
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
class AnonymousSimpleType(SimpleType,\
SimpleMarker,\
LocalMarker):
"""<simpleType>
parents:
attribute, element, list, restriction, union
attributes:
id -- ID
contents:
annotation?, (restriction | list | union)
"""
required = []
attributes = {'id':None}
tag = 'simpleType'
class Redefine:
"""<redefine>
parents:
attributes:
contents:
"""
tag = 'redefine'
###########################
###########################
if sys.version_info[:2] >= (2, 2):
tupleClass = tuple
else:
import UserTuple
tupleClass = UserTuple.UserTuple
class TypeDescriptionComponent(tupleClass):
"""Tuple of length 2, consisting of
a namespace and unprefixed name.
"""
def __init__(self, args):
"""args -- (namespace, name)
Remove the name's prefix, irrelevant.
"""
if len(args) != 2:
raise TypeError, 'expecting tuple (namespace, name), got %s' %args
elif args[1].find(':') >= 0:
args = (args[0], SplitQName(args[1])[1])
tuple.__init__(self, args)
return
def getTargetNamespace(self):
return self[0]
def getName(self):
return self[1] | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/wstools/XMLSchema.py | XMLSchema.py |
ident = "$Id: Utility.py 1116 2006-01-24 20:51:57Z boverhof $"
import sys, types, httplib, smtplib, urllib, socket, weakref
from os.path import isfile
from string import join, strip, split
from UserDict import UserDict
from cStringIO import StringIO
from TimeoutSocket import TimeoutSocket, TimeoutError
from urlparse import urlparse
from httplib import HTTPConnection, HTTPSConnection
from exceptions import Exception
try:
from ZSI import _get_idstr
except:
def _get_idstr(pyobj):
'''Python 2.3.x generates a FutureWarning for negative IDs, so
we use a different prefix character to ensure uniqueness, and
call abs() to avoid the warning.'''
x = id(pyobj)
if x < 0:
return 'x%x' % abs(x)
return 'o%x' % x
import xml.dom.minidom
from xml.dom import Node
import logging
from c14n import Canonicalize
from Namespaces import SCHEMA, SOAP, XMLNS, ZSI_SCHEMA_URI
try:
from xml.dom.ext import SplitQName
except:
def SplitQName(qname):
'''SplitQName(qname) -> (string, string)
Split Qualified Name into a tuple of len 2, consisting
of the prefix and the local name.
(prefix, localName)
Special Cases:
xmlns -- (localName, 'xmlns')
None -- (None, localName)
'''
l = qname.split(':')
if len(l) == 1:
l.insert(0, None)
elif len(l) == 2:
if l[0] == 'xmlns':
l.reverse()
else:
return
return tuple(l)
#
# python2.3 urllib.basejoin does not remove current directory ./
# from path and this causes problems on subsequent basejoins.
#
basejoin = urllib.basejoin
if sys.version_info[0:2] < (2, 4, 0, 'final', 0)[0:2]:
#basejoin = lambda base,url: urllib.basejoin(base,url.lstrip('./'))
token = './'
def basejoin(base, url):
if url.startswith(token) is True:
return urllib.basejoin(base,url[2:])
return urllib.basejoin(base,url)
class NamespaceError(Exception):
"""Used to indicate a Namespace Error."""
class RecursionError(Exception):
"""Used to indicate a HTTP redirect recursion."""
class ParseError(Exception):
"""Used to indicate a XML parsing error."""
class DOMException(Exception):
"""Used to indicate a problem processing DOM."""
class Base:
"""Base class for instance level Logging"""
def __init__(self, module=__name__):
self.logger = logging.getLogger('%s-%s(%s)' %(module, self.__class__, _get_idstr(self)))
class HTTPResponse:
"""Captures the information in an HTTP response message."""
def __init__(self, response):
self.status = response.status
self.reason = response.reason
self.headers = response.msg
self.body = response.read() or None
response.close()
class TimeoutHTTP(HTTPConnection):
"""A custom http connection object that supports socket timeout."""
def __init__(self, host, port=None, timeout=20):
HTTPConnection.__init__(self, host, port)
self.timeout = timeout
def connect(self):
self.sock = TimeoutSocket(self.timeout)
self.sock.connect((self.host, self.port))
class TimeoutHTTPS(HTTPSConnection):
"""A custom https object that supports socket timeout. Note that this
is not really complete. The builtin SSL support in the Python socket
module requires a real socket (type) to be passed in to be hooked to
SSL. That means our fake socket won't work and our timeout hacks are
bypassed for send and recv calls. Since our hack _is_ in place at
connect() time, it should at least provide some timeout protection."""
def __init__(self, host, port=None, timeout=20, **kwargs):
HTTPSConnection.__init__(self, str(host), port, **kwargs)
self.timeout = timeout
def connect(self):
sock = TimeoutSocket(self.timeout)
sock.connect((self.host, self.port))
realsock = getattr(sock.sock, '_sock', sock.sock)
ssl = socket.ssl(realsock, self.key_file, self.cert_file)
self.sock = httplib.FakeSocket(sock, ssl)
def urlopen(url, timeout=20, redirects=None):
"""A minimal urlopen replacement hack that supports timeouts for http.
Note that this supports GET only."""
scheme, host, path, params, query, frag = urlparse(url)
if not scheme in ('http', 'https'):
return urllib.urlopen(url)
if params: path = '%s;%s' % (path, params)
if query: path = '%s?%s' % (path, query)
if frag: path = '%s#%s' % (path, frag)
if scheme == 'https':
# If ssl is not compiled into Python, you will not get an exception
# until a conn.endheaders() call. We need to know sooner, so use
# getattr.
if hasattr(socket, 'ssl'):
conn = TimeoutHTTPS(host, None, timeout)
else:
import M2Crypto
ctx = M2Crypto.SSL.Context()
ctx.set_session_timeout(timeout)
conn = M2Crypto.httpslib.HTTPSConnection(host, ssl_context=ctx)
#conn.set_debuglevel(1)
else:
conn = TimeoutHTTP(host, None, timeout)
conn.putrequest('GET', path)
conn.putheader('Connection', 'close')
conn.endheaders()
response = None
while 1:
response = conn.getresponse()
if response.status != 100:
break
conn._HTTPConnection__state = httplib._CS_REQ_SENT
conn._HTTPConnection__response = None
status = response.status
# If we get an HTTP redirect, we will follow it automatically.
if status >= 300 and status < 400:
location = response.msg.getheader('location')
if location is not None:
response.close()
if redirects is not None and redirects.has_key(location):
raise RecursionError(
'Circular HTTP redirection detected.'
)
if redirects is None:
redirects = {}
redirects[location] = 1
return urlopen(location, timeout, redirects)
raise HTTPResponse(response)
if not (status >= 200 and status < 300):
raise HTTPResponse(response)
body = StringIO(response.read())
response.close()
return body
class DOM:
"""The DOM singleton defines a number of XML related constants and
provides a number of utility methods for DOM related tasks. It
also provides some basic abstractions so that the rest of the
package need not care about actual DOM implementation in use."""
# Namespace stuff related to the SOAP specification.
NS_SOAP_ENV_1_1 = 'http://schemas.xmlsoap.org/soap/envelope/'
NS_SOAP_ENC_1_1 = 'http://schemas.xmlsoap.org/soap/encoding/'
NS_SOAP_ENV_1_2 = 'http://www.w3.org/2001/06/soap-envelope'
NS_SOAP_ENC_1_2 = 'http://www.w3.org/2001/06/soap-encoding'
NS_SOAP_ENV_ALL = (NS_SOAP_ENV_1_1, NS_SOAP_ENV_1_2)
NS_SOAP_ENC_ALL = (NS_SOAP_ENC_1_1, NS_SOAP_ENC_1_2)
NS_SOAP_ENV = NS_SOAP_ENV_1_1
NS_SOAP_ENC = NS_SOAP_ENC_1_1
_soap_uri_mapping = {
NS_SOAP_ENV_1_1 : '1.1',
NS_SOAP_ENV_1_2 : '1.2',
}
SOAP_ACTOR_NEXT_1_1 = 'http://schemas.xmlsoap.org/soap/actor/next'
SOAP_ACTOR_NEXT_1_2 = 'http://www.w3.org/2001/06/soap-envelope/actor/next'
SOAP_ACTOR_NEXT_ALL = (SOAP_ACTOR_NEXT_1_1, SOAP_ACTOR_NEXT_1_2)
def SOAPUriToVersion(self, uri):
"""Return the SOAP version related to an envelope uri."""
value = self._soap_uri_mapping.get(uri)
if value is not None:
return value
raise ValueError(
'Unsupported SOAP envelope uri: %s' % uri
)
def GetSOAPEnvUri(self, version):
"""Return the appropriate SOAP envelope uri for a given
human-friendly SOAP version string (e.g. '1.1')."""
attrname = 'NS_SOAP_ENV_%s' % join(split(version, '.'), '_')
value = getattr(self, attrname, None)
if value is not None:
return value
raise ValueError(
'Unsupported SOAP version: %s' % version
)
def GetSOAPEncUri(self, version):
"""Return the appropriate SOAP encoding uri for a given
human-friendly SOAP version string (e.g. '1.1')."""
attrname = 'NS_SOAP_ENC_%s' % join(split(version, '.'), '_')
value = getattr(self, attrname, None)
if value is not None:
return value
raise ValueError(
'Unsupported SOAP version: %s' % version
)
def GetSOAPActorNextUri(self, version):
"""Return the right special next-actor uri for a given
human-friendly SOAP version string (e.g. '1.1')."""
attrname = 'SOAP_ACTOR_NEXT_%s' % join(split(version, '.'), '_')
value = getattr(self, attrname, None)
if value is not None:
return value
raise ValueError(
'Unsupported SOAP version: %s' % version
)
# Namespace stuff related to XML Schema.
NS_XSD_99 = 'http://www.w3.org/1999/XMLSchema'
NS_XSI_99 = 'http://www.w3.org/1999/XMLSchema-instance'
NS_XSD_00 = 'http://www.w3.org/2000/10/XMLSchema'
NS_XSI_00 = 'http://www.w3.org/2000/10/XMLSchema-instance'
NS_XSD_01 = 'http://www.w3.org/2001/XMLSchema'
NS_XSI_01 = 'http://www.w3.org/2001/XMLSchema-instance'
NS_XSD_ALL = (NS_XSD_99, NS_XSD_00, NS_XSD_01)
NS_XSI_ALL = (NS_XSI_99, NS_XSI_00, NS_XSI_01)
NS_XSD = NS_XSD_01
NS_XSI = NS_XSI_01
_xsd_uri_mapping = {
NS_XSD_99 : NS_XSI_99,
NS_XSD_00 : NS_XSI_00,
NS_XSD_01 : NS_XSI_01,
}
for key, value in _xsd_uri_mapping.items():
_xsd_uri_mapping[value] = key
def InstanceUriForSchemaUri(self, uri):
"""Return the appropriate matching XML Schema instance uri for
the given XML Schema namespace uri."""
return self._xsd_uri_mapping.get(uri)
def SchemaUriForInstanceUri(self, uri):
"""Return the appropriate matching XML Schema namespace uri for
the given XML Schema instance namespace uri."""
return self._xsd_uri_mapping.get(uri)
# Namespace stuff related to WSDL.
NS_WSDL_1_1 = 'http://schemas.xmlsoap.org/wsdl/'
NS_WSDL_ALL = (NS_WSDL_1_1,)
NS_WSDL = NS_WSDL_1_1
NS_SOAP_BINDING_1_1 = 'http://schemas.xmlsoap.org/wsdl/soap/'
NS_HTTP_BINDING_1_1 = 'http://schemas.xmlsoap.org/wsdl/http/'
NS_MIME_BINDING_1_1 = 'http://schemas.xmlsoap.org/wsdl/mime/'
NS_SOAP_BINDING_ALL = (NS_SOAP_BINDING_1_1,)
NS_HTTP_BINDING_ALL = (NS_HTTP_BINDING_1_1,)
NS_MIME_BINDING_ALL = (NS_MIME_BINDING_1_1,)
NS_SOAP_BINDING = NS_SOAP_BINDING_1_1
NS_HTTP_BINDING = NS_HTTP_BINDING_1_1
NS_MIME_BINDING = NS_MIME_BINDING_1_1
NS_SOAP_HTTP_1_1 = 'http://schemas.xmlsoap.org/soap/http'
NS_SOAP_HTTP_ALL = (NS_SOAP_HTTP_1_1,)
NS_SOAP_HTTP = NS_SOAP_HTTP_1_1
_wsdl_uri_mapping = {
NS_WSDL_1_1 : '1.1',
}
def WSDLUriToVersion(self, uri):
"""Return the WSDL version related to a WSDL namespace uri."""
value = self._wsdl_uri_mapping.get(uri)
if value is not None:
return value
raise ValueError(
'Unsupported SOAP envelope uri: %s' % uri
)
def GetWSDLUri(self, version):
attr = 'NS_WSDL_%s' % join(split(version, '.'), '_')
value = getattr(self, attr, None)
if value is not None:
return value
raise ValueError(
'Unsupported WSDL version: %s' % version
)
def GetWSDLSoapBindingUri(self, version):
attr = 'NS_SOAP_BINDING_%s' % join(split(version, '.'), '_')
value = getattr(self, attr, None)
if value is not None:
return value
raise ValueError(
'Unsupported WSDL version: %s' % version
)
def GetWSDLHttpBindingUri(self, version):
attr = 'NS_HTTP_BINDING_%s' % join(split(version, '.'), '_')
value = getattr(self, attr, None)
if value is not None:
return value
raise ValueError(
'Unsupported WSDL version: %s' % version
)
def GetWSDLMimeBindingUri(self, version):
attr = 'NS_MIME_BINDING_%s' % join(split(version, '.'), '_')
value = getattr(self, attr, None)
if value is not None:
return value
raise ValueError(
'Unsupported WSDL version: %s' % version
)
def GetWSDLHttpTransportUri(self, version):
attr = 'NS_SOAP_HTTP_%s' % join(split(version, '.'), '_')
value = getattr(self, attr, None)
if value is not None:
return value
raise ValueError(
'Unsupported WSDL version: %s' % version
)
# Other xml namespace constants.
NS_XMLNS = 'http://www.w3.org/2000/xmlns/'
def isElement(self, node, name, nsuri=None):
"""Return true if the given node is an element with the given
name and optional namespace uri."""
if node.nodeType != node.ELEMENT_NODE:
return 0
return node.localName == name and \
(nsuri is None or self.nsUriMatch(node.namespaceURI, nsuri))
def getElement(self, node, name, nsuri=None, default=join):
"""Return the first child of node with a matching name and
namespace uri, or the default if one is provided."""
nsmatch = self.nsUriMatch
ELEMENT_NODE = node.ELEMENT_NODE
for child in node.childNodes:
if child.nodeType == ELEMENT_NODE:
if ((child.localName == name or name is None) and
(nsuri is None or nsmatch(child.namespaceURI, nsuri))
):
return child
if default is not join:
return default
raise KeyError, name
def getElementById(self, node, id, default=join):
"""Return the first child of node matching an id reference."""
attrget = self.getAttr
ELEMENT_NODE = node.ELEMENT_NODE
for child in node.childNodes:
if child.nodeType == ELEMENT_NODE:
if attrget(child, 'id') == id:
return child
if default is not join:
return default
raise KeyError, name
def getMappingById(self, document, depth=None, element=None,
mapping=None, level=1):
"""Create an id -> element mapping of those elements within a
document that define an id attribute. The depth of the search
may be controlled by using the (1-based) depth argument."""
if document is not None:
element = document.documentElement
mapping = {}
attr = element._attrs.get('id', None)
if attr is not None:
mapping[attr.value] = element
if depth is None or depth > level:
level = level + 1
ELEMENT_NODE = element.ELEMENT_NODE
for child in element.childNodes:
if child.nodeType == ELEMENT_NODE:
self.getMappingById(None, depth, child, mapping, level)
return mapping
def getElements(self, node, name, nsuri=None):
"""Return a sequence of the child elements of the given node that
match the given name and optional namespace uri."""
nsmatch = self.nsUriMatch
result = []
ELEMENT_NODE = node.ELEMENT_NODE
for child in node.childNodes:
if child.nodeType == ELEMENT_NODE:
if ((child.localName == name or name is None) and (
(nsuri is None) or nsmatch(child.namespaceURI, nsuri))):
result.append(child)
return result
def hasAttr(self, node, name, nsuri=None):
"""Return true if element has attribute with the given name and
optional nsuri. If nsuri is not specified, returns true if an
attribute exists with the given name with any namespace."""
if nsuri is None:
if node.hasAttribute(name):
return True
return False
return node.hasAttributeNS(nsuri, name)
def getAttr(self, node, name, nsuri=None, default=join):
"""Return the value of the attribute named 'name' with the
optional nsuri, or the default if one is specified. If
nsuri is not specified, an attribute that matches the
given name will be returned regardless of namespace."""
if nsuri is None:
result = node._attrs.get(name, None)
if result is None:
for item in node._attrsNS.keys():
if item[1] == name:
result = node._attrsNS[item]
break
else:
result = node._attrsNS.get((nsuri, name), None)
if result is not None:
return result.value
if default is not join:
return default
return ''
def getAttrs(self, node):
"""Return a Collection of all attributes
"""
attrs = {}
for k,v in node._attrs.items():
attrs[k] = v.value
return attrs
def getElementText(self, node, preserve_ws=None):
"""Return the text value of an xml element node. Leading and trailing
whitespace is stripped from the value unless the preserve_ws flag
is passed with a true value."""
result = []
for child in node.childNodes:
nodetype = child.nodeType
if nodetype == child.TEXT_NODE or \
nodetype == child.CDATA_SECTION_NODE:
result.append(child.nodeValue)
value = join(result, '')
if preserve_ws is None:
value = strip(value)
return value
def findNamespaceURI(self, prefix, node):
"""Find a namespace uri given a prefix and a context node."""
attrkey = (self.NS_XMLNS, prefix)
DOCUMENT_NODE = node.DOCUMENT_NODE
ELEMENT_NODE = node.ELEMENT_NODE
while 1:
if node is None:
raise DOMException('Value for prefix %s not found.' % prefix)
if node.nodeType != ELEMENT_NODE:
node = node.parentNode
continue
result = node._attrsNS.get(attrkey, None)
if result is not None:
return result.value
if hasattr(node, '__imported__'):
raise DOMException('Value for prefix %s not found.' % prefix)
node = node.parentNode
if node.nodeType == DOCUMENT_NODE:
raise DOMException('Value for prefix %s not found.' % prefix)
def findDefaultNS(self, node):
"""Return the current default namespace uri for the given node."""
attrkey = (self.NS_XMLNS, 'xmlns')
DOCUMENT_NODE = node.DOCUMENT_NODE
ELEMENT_NODE = node.ELEMENT_NODE
while 1:
if node.nodeType != ELEMENT_NODE:
node = node.parentNode
continue
result = node._attrsNS.get(attrkey, None)
if result is not None:
return result.value
if hasattr(node, '__imported__'):
raise DOMException('Cannot determine default namespace.')
node = node.parentNode
if node.nodeType == DOCUMENT_NODE:
raise DOMException('Cannot determine default namespace.')
def findTargetNS(self, node):
"""Return the defined target namespace uri for the given node."""
attrget = self.getAttr
attrkey = (self.NS_XMLNS, 'xmlns')
DOCUMENT_NODE = node.DOCUMENT_NODE
ELEMENT_NODE = node.ELEMENT_NODE
while 1:
if node.nodeType != ELEMENT_NODE:
node = node.parentNode
continue
result = attrget(node, 'targetNamespace', default=None)
if result is not None:
return result
node = node.parentNode
if node.nodeType == DOCUMENT_NODE:
raise DOMException('Cannot determine target namespace.')
def getTypeRef(self, element):
"""Return (namespaceURI, name) for a type attribue of the given
element, or None if the element does not have a type attribute."""
typeattr = self.getAttr(element, 'type', default=None)
if typeattr is None:
return None
parts = typeattr.split(':', 1)
if len(parts) == 2:
nsuri = self.findNamespaceURI(parts[0], element)
else:
nsuri = self.findDefaultNS(element)
return (nsuri, parts[1])
def importNode(self, document, node, deep=0):
"""Implements (well enough for our purposes) DOM node import."""
nodetype = node.nodeType
if nodetype in (node.DOCUMENT_NODE, node.DOCUMENT_TYPE_NODE):
raise DOMException('Illegal node type for importNode')
if nodetype == node.ENTITY_REFERENCE_NODE:
deep = 0
clone = node.cloneNode(deep)
self._setOwnerDoc(document, clone)
clone.__imported__ = 1
return clone
def _setOwnerDoc(self, document, node):
node.ownerDocument = document
for child in node.childNodes:
self._setOwnerDoc(document, child)
def nsUriMatch(self, value, wanted, strict=0, tt=type(())):
"""Return a true value if two namespace uri values match."""
if value == wanted or (type(wanted) is tt) and value in wanted:
return 1
if not strict and value is not None:
wanted = type(wanted) is tt and wanted or (wanted,)
value = value[-1:] != '/' and value or value[:-1]
for item in wanted:
if item == value or item[:-1] == value:
return 1
return 0
def createDocument(self, nsuri, qname, doctype=None):
"""Create a new writable DOM document object."""
impl = xml.dom.minidom.getDOMImplementation()
return impl.createDocument(nsuri, qname, doctype)
def loadDocument(self, data):
"""Load an xml file from a file-like object and return a DOM
document instance."""
return xml.dom.minidom.parse(data)
def loadFromURL(self, url):
"""Load an xml file from a URL and return a DOM document."""
if isfile(url) is True:
file = open(url, 'r')
else:
file = urlopen(url)
try:
result = self.loadDocument(file)
except Exception, ex:
file.close()
raise ParseError(('Failed to load document %s' %url,) + ex.args)
else:
file.close()
return result
DOM = DOM()
class MessageInterface:
'''Higher Level Interface, delegates to DOM singleton, must
be subclassed and implement all methods that throw NotImplementedError.
'''
def __init__(self, sw):
'''Constructor, May be extended, do not override.
sw -- soapWriter instance
'''
self.sw = None
if type(sw) != weakref.ReferenceType and sw is not None:
self.sw = weakref.ref(sw)
else:
self.sw = sw
def AddCallback(self, func, *arglist):
self.sw().AddCallback(func, *arglist)
def Known(self, obj):
return self.sw().Known(obj)
def Forget(self, obj):
return self.sw().Forget(obj)
def canonicalize(self):
'''canonicalize the underlying DOM, and return as string.
'''
raise NotImplementedError, ''
def createDocument(self, namespaceURI=SOAP.ENV, localName='Envelope'):
'''create Document
'''
raise NotImplementedError, ''
def createAppendElement(self, namespaceURI, localName):
'''create and append element(namespaceURI,localName), and return
the node.
'''
raise NotImplementedError, ''
def findNamespaceURI(self, qualifiedName):
raise NotImplementedError, ''
def resolvePrefix(self, prefix):
raise NotImplementedError, ''
def setAttributeNS(self, namespaceURI, localName, value):
'''set attribute (namespaceURI, localName)=value
'''
raise NotImplementedError, ''
def setAttributeType(self, namespaceURI, localName):
'''set attribute xsi:type=(namespaceURI, localName)
'''
raise NotImplementedError, ''
def setNamespaceAttribute(self, namespaceURI, prefix):
'''set namespace attribute xmlns:prefix=namespaceURI
'''
raise NotImplementedError, ''
class ElementProxy(Base, MessageInterface):
'''
'''
_soap_env_prefix = 'SOAP-ENV'
_soap_enc_prefix = 'SOAP-ENC'
_zsi_prefix = 'ZSI'
_xsd_prefix = 'xsd'
_xsi_prefix = 'xsi'
_xml_prefix = 'xml'
_xmlns_prefix = 'xmlns'
_soap_env_nsuri = SOAP.ENV
_soap_enc_nsuri = SOAP.ENC
_zsi_nsuri = ZSI_SCHEMA_URI
_xsd_nsuri = SCHEMA.XSD3
_xsi_nsuri = SCHEMA.XSI3
_xml_nsuri = XMLNS.XML
_xmlns_nsuri = XMLNS.BASE
standard_ns = {\
_xml_prefix:_xml_nsuri,
_xmlns_prefix:_xmlns_nsuri
}
reserved_ns = {\
_soap_env_prefix:_soap_env_nsuri,
_soap_enc_prefix:_soap_enc_nsuri,
_zsi_prefix:_zsi_nsuri,
_xsd_prefix:_xsd_nsuri,
_xsi_prefix:_xsi_nsuri,
}
name = None
namespaceURI = None
def __init__(self, sw, message=None):
'''Initialize.
sw -- SoapWriter
'''
self._indx = 0
MessageInterface.__init__(self, sw)
Base.__init__(self)
self._dom = DOM
self.node = None
if type(message) in (types.StringType,types.UnicodeType):
self.loadFromString(message)
elif isinstance(message, ElementProxy):
self.node = message._getNode()
else:
self.node = message
self.processorNss = self.standard_ns.copy()
self.processorNss.update(self.reserved_ns)
def __str__(self):
return self.toString()
def evaluate(self, expression, processorNss=None):
'''expression -- XPath compiled expression
'''
from Ft.Xml import XPath
if not processorNss:
context = XPath.Context.Context(self.node, processorNss=self.processorNss)
else:
context = XPath.Context.Context(self.node, processorNss=processorNss)
nodes = expression.evaluate(context)
return map(lambda node: ElementProxy(self.sw,node), nodes)
#############################################
# Methods for checking/setting the
# classes (namespaceURI,name) node.
#############################################
def checkNode(self, namespaceURI=None, localName=None):
'''
namespaceURI -- namespace of element
localName -- local name of element
'''
namespaceURI = namespaceURI or self.namespaceURI
localName = localName or self.name
check = False
if localName and self.node:
check = self._dom.isElement(self.node, localName, namespaceURI)
if not check:
raise NamespaceError, 'unexpected node type %s, expecting %s' %(self.node, localName)
def setNode(self, node=None):
if node:
if isinstance(node, ElementProxy):
self.node = node._getNode()
else:
self.node = node
elif self.node:
node = self._dom.getElement(self.node, self.name, self.namespaceURI, default=None)
if not node:
raise NamespaceError, 'cant find element (%s,%s)' %(self.namespaceURI,self.name)
self.node = node
else:
#self.node = self._dom.create(self.node, self.name, self.namespaceURI, default=None)
self.createDocument(self.namespaceURI, localName=self.name, doctype=None)
self.checkNode()
#############################################
# Wrapper Methods for direct DOM Element Node access
#############################################
def _getNode(self):
return self.node
def _getElements(self):
return self._dom.getElements(self.node, name=None)
def _getOwnerDocument(self):
return self.node.ownerDocument or self.node
def _getUniquePrefix(self):
'''I guess we need to resolve all potential prefixes
because when the current node is attached it copies the
namespaces into the parent node.
'''
while 1:
self._indx += 1
prefix = 'ns%d' %self._indx
try:
self._dom.findNamespaceURI(prefix, self._getNode())
except DOMException, ex:
break
return prefix
def _getPrefix(self, node, nsuri):
'''
Keyword arguments:
node -- DOM Element Node
nsuri -- namespace of attribute value
'''
try:
if node and (node.nodeType == node.ELEMENT_NODE) and \
(nsuri == self._dom.findDefaultNS(node)):
return None
except DOMException, ex:
pass
if nsuri == XMLNS.XML:
return self._xml_prefix
if node.nodeType == Node.ELEMENT_NODE:
for attr in node.attributes.values():
if attr.namespaceURI == XMLNS.BASE \
and nsuri == attr.value:
return attr.localName
else:
if node.parentNode:
return self._getPrefix(node.parentNode, nsuri)
raise NamespaceError, 'namespaceURI "%s" is not defined' %nsuri
def _appendChild(self, node):
'''
Keyword arguments:
node -- DOM Element Node
'''
if node is None:
raise TypeError, 'node is None'
self.node.appendChild(node)
def _insertBefore(self, newChild, refChild):
'''
Keyword arguments:
child -- DOM Element Node to insert
refChild -- DOM Element Node
'''
self.node.insertBefore(newChild, refChild)
def _setAttributeNS(self, namespaceURI, qualifiedName, value):
'''
Keyword arguments:
namespaceURI -- namespace of attribute
qualifiedName -- qualified name of new attribute value
value -- value of attribute
'''
self.node.setAttributeNS(namespaceURI, qualifiedName, value)
#############################################
#General Methods
#############################################
def isFault(self):
'''check to see if this is a soap:fault message.
'''
return False
def getPrefix(self, namespaceURI):
try:
prefix = self._getPrefix(node=self.node, nsuri=namespaceURI)
except NamespaceError, ex:
prefix = self._getUniquePrefix()
self.setNamespaceAttribute(prefix, namespaceURI)
return prefix
def getDocument(self):
return self._getOwnerDocument()
def setDocument(self, document):
self.node = document
def importFromString(self, xmlString):
doc = self._dom.loadDocument(StringIO(xmlString))
node = self._dom.getElement(doc, name=None)
clone = self.importNode(node)
self._appendChild(clone)
def importNode(self, node):
if isinstance(node, ElementProxy):
node = node._getNode()
return self._dom.importNode(self._getOwnerDocument(), node, deep=1)
def loadFromString(self, data):
self.node = self._dom.loadDocument(StringIO(data))
def canonicalize(self):
return Canonicalize(self.node)
def toString(self):
return self.canonicalize()
def createDocument(self, namespaceURI, localName, doctype=None):
'''If specified must be a SOAP envelope, else may contruct an empty document.
'''
prefix = self._soap_env_prefix
if namespaceURI == self.reserved_ns[prefix]:
qualifiedName = '%s:%s' %(prefix,localName)
elif namespaceURI is localName is None:
self.node = self._dom.createDocument(None,None,None)
return
else:
raise KeyError, 'only support creation of document in %s' %self.reserved_ns[prefix]
document = self._dom.createDocument(nsuri=namespaceURI, qname=qualifiedName, doctype=doctype)
self.node = document.childNodes[0]
#set up reserved namespace attributes
for prefix,nsuri in self.reserved_ns.items():
self._setAttributeNS(namespaceURI=self._xmlns_nsuri,
qualifiedName='%s:%s' %(self._xmlns_prefix,prefix),
value=nsuri)
#############################################
#Methods for attributes
#############################################
def hasAttribute(self, namespaceURI, localName):
return self._dom.hasAttr(self._getNode(), name=localName, nsuri=namespaceURI)
def setAttributeType(self, namespaceURI, localName):
'''set xsi:type
Keyword arguments:
namespaceURI -- namespace of attribute value
localName -- name of new attribute value
'''
self.logger.debug('setAttributeType: (%s,%s)', namespaceURI, localName)
value = localName
if namespaceURI:
value = '%s:%s' %(self.getPrefix(namespaceURI),localName)
xsi_prefix = self.getPrefix(self._xsi_nsuri)
self._setAttributeNS(self._xsi_nsuri, '%s:type' %xsi_prefix, value)
def createAttributeNS(self, namespace, name, value):
document = self._getOwnerDocument()
attrNode = document.createAttributeNS(namespace, name, value)
def setAttributeNS(self, namespaceURI, localName, value):
'''
Keyword arguments:
namespaceURI -- namespace of attribute to create, None is for
attributes in no namespace.
localName -- local name of new attribute
value -- value of new attribute
'''
prefix = None
if namespaceURI:
try:
prefix = self.getPrefix(namespaceURI)
except KeyError, ex:
prefix = 'ns2'
self.setNamespaceAttribute(prefix, namespaceURI)
qualifiedName = localName
if prefix:
qualifiedName = '%s:%s' %(prefix, localName)
self._setAttributeNS(namespaceURI, qualifiedName, value)
def setNamespaceAttribute(self, prefix, namespaceURI):
'''
Keyword arguments:
prefix -- xmlns prefix
namespaceURI -- value of prefix
'''
self._setAttributeNS(XMLNS.BASE, 'xmlns:%s' %prefix, namespaceURI)
#############################################
#Methods for elements
#############################################
def createElementNS(self, namespace, qname):
'''
Keyword arguments:
namespace -- namespace of element to create
qname -- qualified name of new element
'''
document = self._getOwnerDocument()
node = document.createElementNS(namespace, qname)
return ElementProxy(self.sw, node)
def createAppendSetElement(self, namespaceURI, localName, prefix=None):
'''Create a new element (namespaceURI,name), append it
to current node, then set it to be the current node.
Keyword arguments:
namespaceURI -- namespace of element to create
localName -- local name of new element
prefix -- if namespaceURI is not defined, declare prefix. defaults
to 'ns1' if left unspecified.
'''
node = self.createAppendElement(namespaceURI, localName, prefix=None)
node=node._getNode()
self._setNode(node._getNode())
def createAppendElement(self, namespaceURI, localName, prefix=None):
'''Create a new element (namespaceURI,name), append it
to current node, and return the newly created node.
Keyword arguments:
namespaceURI -- namespace of element to create
localName -- local name of new element
prefix -- if namespaceURI is not defined, declare prefix. defaults
to 'ns1' if left unspecified.
'''
declare = False
qualifiedName = localName
if namespaceURI:
try:
prefix = self.getPrefix(namespaceURI)
except:
declare = True
prefix = prefix or self._getUniquePrefix()
if prefix:
qualifiedName = '%s:%s' %(prefix, localName)
node = self.createElementNS(namespaceURI, qualifiedName)
if declare:
node._setAttributeNS(XMLNS.BASE, 'xmlns:%s' %prefix, namespaceURI)
self._appendChild(node=node._getNode())
return node
def createInsertBefore(self, namespaceURI, localName, refChild):
qualifiedName = localName
prefix = self.getPrefix(namespaceURI)
if prefix:
qualifiedName = '%s:%s' %(prefix, localName)
node = self.createElementNS(namespaceURI, qualifiedName)
self._insertBefore(newChild=node._getNode(), refChild=refChild._getNode())
return node
def getElement(self, namespaceURI, localName):
'''
Keyword arguments:
namespaceURI -- namespace of element
localName -- local name of element
'''
node = self._dom.getElement(self.node, localName, namespaceURI, default=None)
if node:
return ElementProxy(self.sw, node)
return None
def getAttributeValue(self, namespaceURI, localName):
'''
Keyword arguments:
namespaceURI -- namespace of attribute
localName -- local name of attribute
'''
if self.hasAttribute(namespaceURI, localName):
attr = self.node.getAttributeNodeNS(namespaceURI,localName)
return attr.value
return None
def getValue(self):
return self._dom.getElementText(self.node, preserve_ws=True)
#############################################
#Methods for text nodes
#############################################
def createAppendTextNode(self, pyobj):
node = self.createTextNode(pyobj)
self._appendChild(node=node._getNode())
return node
def createTextNode(self, pyobj):
document = self._getOwnerDocument()
node = document.createTextNode(pyobj)
return ElementProxy(self.sw, node)
#############################################
#Methods for retrieving namespaceURI's
#############################################
def findNamespaceURI(self, qualifiedName):
parts = SplitQName(qualifiedName)
element = self._getNode()
if len(parts) == 1:
return (self._dom.findTargetNS(element), value)
return self._dom.findNamespaceURI(parts[0], element)
def resolvePrefix(self, prefix):
element = self._getNode()
return self._dom.findNamespaceURI(prefix, element)
def getSOAPEnvURI(self):
return self._soap_env_nsuri
def isEmpty(self):
return not self.node
class Collection(UserDict):
"""Helper class for maintaining ordered named collections."""
default = lambda self,k: k.name
def __init__(self, parent, key=None):
UserDict.__init__(self)
self.parent = weakref.ref(parent)
self.list = []
self._func = key or self.default
def __getitem__(self, key):
if type(key) is type(1):
return self.list[key]
return self.data[key]
def __setitem__(self, key, item):
item.parent = weakref.ref(self)
self.list.append(item)
self.data[key] = item
def keys(self):
return map(lambda i: self._func(i), self.list)
def items(self):
return map(lambda i: (self._func(i), i), self.list)
def values(self):
return self.list
class CollectionNS(UserDict):
"""Helper class for maintaining ordered named collections."""
default = lambda self,k: k.name
def __init__(self, parent, key=None):
UserDict.__init__(self)
self.parent = weakref.ref(parent)
self.targetNamespace = None
self.list = []
self._func = key or self.default
def __getitem__(self, key):
self.targetNamespace = self.parent().targetNamespace
if type(key) is types.IntType:
return self.list[key]
elif self.__isSequence(key):
nsuri,name = key
return self.data[nsuri][name]
return self.data[self.parent().targetNamespace][key]
def __setitem__(self, key, item):
item.parent = weakref.ref(self)
self.list.append(item)
targetNamespace = getattr(item, 'targetNamespace', self.parent().targetNamespace)
if not self.data.has_key(targetNamespace):
self.data[targetNamespace] = {}
self.data[targetNamespace][key] = item
def __isSequence(self, key):
return (type(key) in (types.TupleType,types.ListType) and len(key) == 2)
def keys(self):
keys = []
for tns in self.data.keys():
keys.append(map(lambda i: (tns,self._func(i)), self.data[tns].values()))
return keys
def items(self):
return map(lambda i: (self._func(i), i), self.list)
def values(self):
return self.list
# This is a runtime guerilla patch for pulldom (used by minidom) so
# that xml namespace declaration attributes are not lost in parsing.
# We need them to do correct QName linking for XML Schema and WSDL.
# The patch has been submitted to SF for the next Python version.
from xml.dom.pulldom import PullDOM, START_ELEMENT
if 1:
def startPrefixMapping(self, prefix, uri):
if not hasattr(self, '_xmlns_attrs'):
self._xmlns_attrs = []
self._xmlns_attrs.append((prefix or 'xmlns', uri))
self._ns_contexts.append(self._current_context.copy())
self._current_context[uri] = prefix or ''
PullDOM.startPrefixMapping = startPrefixMapping
def startElementNS(self, name, tagName , attrs):
# Retrieve xml namespace declaration attributes.
xmlns_uri = 'http://www.w3.org/2000/xmlns/'
xmlns_attrs = getattr(self, '_xmlns_attrs', None)
if xmlns_attrs is not None:
for aname, value in xmlns_attrs:
attrs._attrs[(xmlns_uri, aname)] = value
self._xmlns_attrs = []
uri, localname = name
if uri:
# When using namespaces, the reader may or may not
# provide us with the original name. If not, create
# *a* valid tagName from the current context.
if tagName is None:
prefix = self._current_context[uri]
if prefix:
tagName = prefix + ":" + localname
else:
tagName = localname
if self.document:
node = self.document.createElementNS(uri, tagName)
else:
node = self.buildDocument(uri, tagName)
else:
# When the tagname is not prefixed, it just appears as
# localname
if self.document:
node = self.document.createElement(localname)
else:
node = self.buildDocument(None, localname)
for aname,value in attrs.items():
a_uri, a_localname = aname
if a_uri == xmlns_uri:
if a_localname == 'xmlns':
qname = a_localname
else:
qname = 'xmlns:' + a_localname
attr = self.document.createAttributeNS(a_uri, qname)
node.setAttributeNodeNS(attr)
elif a_uri:
prefix = self._current_context[a_uri]
if prefix:
qname = prefix + ":" + a_localname
else:
qname = a_localname
attr = self.document.createAttributeNS(a_uri, qname)
node.setAttributeNodeNS(attr)
else:
attr = self.document.createAttribute(a_localname)
node.setAttributeNode(attr)
attr.value = value
self.lastEvent[1] = [(START_ELEMENT, node), None]
self.lastEvent = self.lastEvent[1]
self.push(node)
PullDOM.startElementNS = startElementNS
#
# This is a runtime guerilla patch for minidom so
# that xmlns prefixed attributes dont raise AttributeErrors
# during cloning.
#
# Namespace declarations can appear in any start-tag, must look for xmlns
# prefixed attribute names during cloning.
#
# key (attr.namespaceURI, tag)
# ('http://www.w3.org/2000/xmlns/', u'xsd') <xml.dom.minidom.Attr instance at 0x82227c4>
# ('http://www.w3.org/2000/xmlns/', 'xmlns') <xml.dom.minidom.Attr instance at 0x8414b3c>
#
# xml.dom.minidom.Attr.nodeName = xmlns:xsd
# xml.dom.minidom.Attr.value = = http://www.w3.org/2001/XMLSchema
if 1:
def _clone_node(node, deep, newOwnerDocument):
"""
Clone a node and give it the new owner document.
Called by Node.cloneNode and Document.importNode
"""
if node.ownerDocument.isSameNode(newOwnerDocument):
operation = xml.dom.UserDataHandler.NODE_CLONED
else:
operation = xml.dom.UserDataHandler.NODE_IMPORTED
if node.nodeType == xml.dom.minidom.Node.ELEMENT_NODE:
clone = newOwnerDocument.createElementNS(node.namespaceURI,
node.nodeName)
for attr in node.attributes.values():
clone.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.value)
prefix, tag = xml.dom.minidom._nssplit(attr.nodeName)
if prefix == 'xmlns':
a = clone.getAttributeNodeNS(attr.namespaceURI, tag)
elif prefix:
a = clone.getAttributeNodeNS(attr.namespaceURI, tag)
else:
a = clone.getAttributeNodeNS(attr.namespaceURI, attr.nodeName)
a.specified = attr.specified
if deep:
for child in node.childNodes:
c = xml.dom.minidom._clone_node(child, deep, newOwnerDocument)
clone.appendChild(c)
elif node.nodeType == xml.dom.minidom.Node.DOCUMENT_FRAGMENT_NODE:
clone = newOwnerDocument.createDocumentFragment()
if deep:
for child in node.childNodes:
c = xml.dom.minidom._clone_node(child, deep, newOwnerDocument)
clone.appendChild(c)
elif node.nodeType == xml.dom.minidom.Node.TEXT_NODE:
clone = newOwnerDocument.createTextNode(node.data)
elif node.nodeType == xml.dom.minidom.Node.CDATA_SECTION_NODE:
clone = newOwnerDocument.createCDATASection(node.data)
elif node.nodeType == xml.dom.minidom.Node.PROCESSING_INSTRUCTION_NODE:
clone = newOwnerDocument.createProcessingInstruction(node.target,
node.data)
elif node.nodeType == xml.dom.minidom.Node.COMMENT_NODE:
clone = newOwnerDocument.createComment(node.data)
elif node.nodeType == xml.dom.minidom.Node.ATTRIBUTE_NODE:
clone = newOwnerDocument.createAttributeNS(node.namespaceURI,
node.nodeName)
clone.specified = True
clone.value = node.value
elif node.nodeType == xml.dom.minidom.Node.DOCUMENT_TYPE_NODE:
assert node.ownerDocument is not newOwnerDocument
operation = xml.dom.UserDataHandler.NODE_IMPORTED
clone = newOwnerDocument.implementation.createDocumentType(
node.name, node.publicId, node.systemId)
clone.ownerDocument = newOwnerDocument
if deep:
clone.entities._seq = []
clone.notations._seq = []
for n in node.notations._seq:
notation = xml.dom.minidom.Notation(n.nodeName, n.publicId, n.systemId)
notation.ownerDocument = newOwnerDocument
clone.notations._seq.append(notation)
if hasattr(n, '_call_user_data_handler'):
n._call_user_data_handler(operation, n, notation)
for e in node.entities._seq:
entity = xml.dom.minidom.Entity(e.nodeName, e.publicId, e.systemId,
e.notationName)
entity.actualEncoding = e.actualEncoding
entity.encoding = e.encoding
entity.version = e.version
entity.ownerDocument = newOwnerDocument
clone.entities._seq.append(entity)
if hasattr(e, '_call_user_data_handler'):
e._call_user_data_handler(operation, n, entity)
else:
# Note the cloning of Document and DocumentType nodes is
# implemenetation specific. minidom handles those cases
# directly in the cloneNode() methods.
raise xml.dom.NotSupportedErr("Cannot clone node %s" % repr(node))
# Check for _call_user_data_handler() since this could conceivably
# used with other DOM implementations (one of the FourThought
# DOMs, perhaps?).
if hasattr(node, '_call_user_data_handler'):
node._call_user_data_handler(operation, node, clone)
return clone
xml.dom.minidom._clone_node = _clone_node | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/wstools/Utility.py | Utility.py |
_copyright = '''Copyright 2001, Zolera Systems Inc. All Rights Reserved.
Copyright 2001, MIT. All Rights Reserved.
Distributed under the terms of:
Python 2.0 License or later.
http://www.python.org/2.0.1/license.html
or
W3C Software License
http://www.w3.org/Consortium/Legal/copyright-software-19980720
'''
import string
from xml.dom import Node
try:
from xml.ns import XMLNS
except:
class XMLNS:
BASE = "http://www.w3.org/2000/xmlns/"
XML = "http://www.w3.org/XML/1998/namespace"
try:
import cStringIO
StringIO = cStringIO
except ImportError:
import StringIO
_attrs = lambda E: (E.attributes and E.attributes.values()) or []
_children = lambda E: E.childNodes or []
_IN_XML_NS = lambda n: n.name.startswith("xmlns")
_inclusive = lambda n: n.unsuppressedPrefixes == None
# Does a document/PI has lesser/greater document order than the
# first element?
_LesserElement, _Element, _GreaterElement = range(3)
def _sorter(n1,n2):
'''_sorter(n1,n2) -> int
Sorting predicate for non-NS attributes.'''
i = cmp(n1.namespaceURI, n2.namespaceURI)
if i: return i
return cmp(n1.localName, n2.localName)
def _sorter_ns(n1,n2):
'''_sorter_ns((n,v),(n,v)) -> int
"(an empty namespace URI is lexicographically least)."'''
if n1[0] == 'xmlns': return -1
if n2[0] == 'xmlns': return 1
return cmp(n1[0], n2[0])
def _utilized(n, node, other_attrs, unsuppressedPrefixes):
'''_utilized(n, node, other_attrs, unsuppressedPrefixes) -> boolean
Return true if that nodespace is utilized within the node'''
if n.startswith('xmlns:'):
n = n[6:]
elif n.startswith('xmlns'):
n = n[5:]
if (n=="" and node.prefix in ["#default", None]) or \
n == node.prefix or n in unsuppressedPrefixes:
return 1
for attr in other_attrs:
if n == attr.prefix: return 1
# For exclusive need to look at attributes
if unsuppressedPrefixes is not None:
for attr in _attrs(node):
if n == attr.prefix: return 1
return 0
def _inclusiveNamespacePrefixes(node, context, unsuppressedPrefixes):
'''http://www.w3.org/TR/xml-exc-c14n/
InclusiveNamespaces PrefixList parameter, which lists namespace prefixes that
are handled in the manner described by the Canonical XML Recommendation'''
inclusive = []
if node.prefix:
usedPrefixes = ['xmlns:%s' %node.prefix]
else:
usedPrefixes = ['xmlns']
for a in _attrs(node):
if a.nodeName.startswith('xmlns') or not a.prefix: continue
usedPrefixes.append('xmlns:%s' %a.prefix)
unused_namespace_dict = {}
for attr in context:
n = attr.nodeName
if n in unsuppressedPrefixes:
inclusive.append(attr)
elif n.startswith('xmlns:') and n[6:] in unsuppressedPrefixes:
inclusive.append(attr)
elif n.startswith('xmlns') and n[5:] in unsuppressedPrefixes:
inclusive.append(attr)
elif attr.nodeName in usedPrefixes:
inclusive.append(attr)
elif n.startswith('xmlns:'):
unused_namespace_dict[n] = attr.value
return inclusive, unused_namespace_dict
#_in_subset = lambda subset, node: not subset or node in subset
_in_subset = lambda subset, node: subset is None or node in subset # rich's tweak
class _implementation:
'''Implementation class for C14N. This accompanies a node during it's
processing and includes the parameters and processing state.'''
# Handler for each node type; populated during module instantiation.
handlers = {}
def __init__(self, node, write, **kw):
'''Create and run the implementation.'''
self.write = write
self.subset = kw.get('subset')
self.comments = kw.get('comments', 0)
self.unsuppressedPrefixes = kw.get('unsuppressedPrefixes')
nsdict = kw.get('nsdict', { 'xml': XMLNS.XML, 'xmlns': XMLNS.BASE })
# Processing state.
self.state = (nsdict, {'xml':''}, {}, {}) #0422
if node.nodeType == Node.DOCUMENT_NODE:
self._do_document(node)
elif node.nodeType == Node.ELEMENT_NODE:
self.documentOrder = _Element # At document element
if not _inclusive(self):
inherited,unused = _inclusiveNamespacePrefixes(node, self._inherit_context(node),
self.unsuppressedPrefixes)
self._do_element(node, inherited, unused=unused)
else:
inherited = self._inherit_context(node)
self._do_element(node, inherited)
elif node.nodeType == Node.DOCUMENT_TYPE_NODE:
pass
else:
raise TypeError, str(node)
def _inherit_context(self, node):
'''_inherit_context(self, node) -> list
Scan ancestors of attribute and namespace context. Used only
for single element node canonicalization, not for subset
canonicalization.'''
# Collect the initial list of xml:foo attributes.
xmlattrs = filter(_IN_XML_NS, _attrs(node))
# Walk up and get all xml:XXX attributes we inherit.
inherited, parent = [], node.parentNode
while parent and parent.nodeType == Node.ELEMENT_NODE:
for a in filter(_IN_XML_NS, _attrs(parent)):
n = a.localName
if n not in xmlattrs:
xmlattrs.append(n)
inherited.append(a)
parent = parent.parentNode
return inherited
def _do_document(self, node):
'''_do_document(self, node) -> None
Process a document node. documentOrder holds whether the document
element has been encountered such that PIs/comments can be written
as specified.'''
self.documentOrder = _LesserElement
for child in node.childNodes:
if child.nodeType == Node.ELEMENT_NODE:
self.documentOrder = _Element # At document element
self._do_element(child)
self.documentOrder = _GreaterElement # After document element
elif child.nodeType == Node.PROCESSING_INSTRUCTION_NODE:
self._do_pi(child)
elif child.nodeType == Node.COMMENT_NODE:
self._do_comment(child)
elif child.nodeType == Node.DOCUMENT_TYPE_NODE:
pass
else:
raise TypeError, str(child)
handlers[Node.DOCUMENT_NODE] = _do_document
def _do_text(self, node):
'''_do_text(self, node) -> None
Process a text or CDATA node. Render various special characters
as their C14N entity representations.'''
if not _in_subset(self.subset, node): return
s = string.replace(node.data, "&", "&")
s = string.replace(s, "<", "<")
s = string.replace(s, ">", ">")
s = string.replace(s, "\015", "
")
if s: self.write(s)
handlers[Node.TEXT_NODE] = _do_text
handlers[Node.CDATA_SECTION_NODE] = _do_text
def _do_pi(self, node):
'''_do_pi(self, node) -> None
Process a PI node. Render a leading or trailing #xA if the
document order of the PI is greater or lesser (respectively)
than the document element.
'''
if not _in_subset(self.subset, node): return
W = self.write
if self.documentOrder == _GreaterElement: W('\n')
W('<?')
W(node.nodeName)
s = node.data
if s:
W(' ')
W(s)
W('?>')
if self.documentOrder == _LesserElement: W('\n')
handlers[Node.PROCESSING_INSTRUCTION_NODE] = _do_pi
def _do_comment(self, node):
'''_do_comment(self, node) -> None
Process a comment node. Render a leading or trailing #xA if the
document order of the comment is greater or lesser (respectively)
than the document element.
'''
if not _in_subset(self.subset, node): return
if self.comments:
W = self.write
if self.documentOrder == _GreaterElement: W('\n')
W('<!--')
W(node.data)
W('-->')
if self.documentOrder == _LesserElement: W('\n')
handlers[Node.COMMENT_NODE] = _do_comment
def _do_attr(self, n, value):
''''_do_attr(self, node) -> None
Process an attribute.'''
W = self.write
W(' ')
W(n)
W('="')
s = string.replace(value, "&", "&")
s = string.replace(s, "<", "<")
s = string.replace(s, '"', '"')
s = string.replace(s, '\011', '	')
s = string.replace(s, '\012', '
')
s = string.replace(s, '\015', '
')
W(s)
W('"')
def _do_element(self, node, initial_other_attrs = [], unused = None):
'''_do_element(self, node, initial_other_attrs = [], unused = {}) -> None
Process an element (and its children).'''
# Get state (from the stack) make local copies.
# ns_parent -- NS declarations in parent
# ns_rendered -- NS nodes rendered by ancestors
# ns_local -- NS declarations relevant to this element
# xml_attrs -- Attributes in XML namespace from parent
# xml_attrs_local -- Local attributes in XML namespace.
# ns_unused_inherited -- not rendered namespaces, used for exclusive
ns_parent, ns_rendered, xml_attrs = \
self.state[0], self.state[1].copy(), self.state[2].copy() #0422
ns_unused_inherited = unused
if unused is None:
ns_unused_inherited = self.state[3].copy()
ns_local = ns_parent.copy()
inclusive = _inclusive(self)
xml_attrs_local = {}
# Divide attributes into NS, XML, and others.
other_attrs = []
in_subset = _in_subset(self.subset, node)
for a in initial_other_attrs + _attrs(node):
if a.namespaceURI == XMLNS.BASE:
n = a.nodeName
if n == "xmlns:": n = "xmlns" # DOM bug workaround
ns_local[n] = a.nodeValue
elif a.namespaceURI == XMLNS.XML:
if inclusive or (in_subset and _in_subset(self.subset, a)): #020925 Test to see if attribute node in subset
xml_attrs_local[a.nodeName] = a #0426
else:
if _in_subset(self.subset, a): #020925 Test to see if attribute node in subset
other_attrs.append(a)
# # TODO: exclusive, might need to define xmlns:prefix here
# if not inclusive and a.prefix is not None and not ns_rendered.has_key('xmlns:%s' %a.prefix):
# ns_local['xmlns:%s' %a.prefix] = ??
#add local xml:foo attributes to ancestor's xml:foo attributes
xml_attrs.update(xml_attrs_local)
# Render the node
W, name = self.write, None
if in_subset:
name = node.nodeName
if not inclusive:
if node.prefix is not None:
prefix = 'xmlns:%s' %node.prefix
else:
prefix = 'xmlns'
if not ns_rendered.has_key(prefix) and not ns_local.has_key(prefix):
if not ns_unused_inherited.has_key(prefix):
raise RuntimeError,\
'For exclusive c14n, unable to map prefix "%s" in %s' %(
prefix, node)
ns_local[prefix] = ns_unused_inherited[prefix]
del ns_unused_inherited[prefix]
W('<')
W(name)
# Create list of NS attributes to render.
ns_to_render = []
for n,v in ns_local.items():
# If default namespace is XMLNS.BASE or empty,
# and if an ancestor was the same
if n == "xmlns" and v in [ XMLNS.BASE, '' ] \
and ns_rendered.get('xmlns') in [ XMLNS.BASE, '', None ]:
continue
# "omit namespace node with local name xml, which defines
# the xml prefix, if its string value is
# http://www.w3.org/XML/1998/namespace."
if n in ["xmlns:xml", "xml"] \
and v in [ 'http://www.w3.org/XML/1998/namespace' ]:
continue
# If not previously rendered
# and it's inclusive or utilized
if (n,v) not in ns_rendered.items():
if inclusive or _utilized(n, node, other_attrs, self.unsuppressedPrefixes):
ns_to_render.append((n, v))
elif not inclusive:
ns_unused_inherited[n] = v
# Sort and render the ns, marking what was rendered.
ns_to_render.sort(_sorter_ns)
for n,v in ns_to_render:
self._do_attr(n, v)
ns_rendered[n]=v #0417
# If exclusive or the parent is in the subset, add the local xml attributes
# Else, add all local and ancestor xml attributes
# Sort and render the attributes.
if not inclusive or _in_subset(self.subset,node.parentNode): #0426
other_attrs.extend(xml_attrs_local.values())
else:
other_attrs.extend(xml_attrs.values())
other_attrs.sort(_sorter)
for a in other_attrs:
self._do_attr(a.nodeName, a.value)
W('>')
# Push state, recurse, pop state.
state, self.state = self.state, (ns_local, ns_rendered, xml_attrs, ns_unused_inherited)
for c in _children(node):
_implementation.handlers[c.nodeType](self, c)
self.state = state
if name: W('</%s>' % name)
handlers[Node.ELEMENT_NODE] = _do_element
def Canonicalize(node, output=None, **kw):
'''Canonicalize(node, output=None, **kw) -> UTF-8
Canonicalize a DOM document/element node and all descendents.
Return the text; if output is specified then output.write will
be called to output the text and None will be returned
Keyword parameters:
nsdict: a dictionary of prefix:uri namespace entries
assumed to exist in the surrounding context
comments: keep comments if non-zero (default is 0)
subset: Canonical XML subsetting resulting from XPath
(default is [])
unsuppressedPrefixes: do exclusive C14N, and this specifies the
prefixes that should be inherited.
'''
if output:
apply(_implementation, (node, output.write), kw)
else:
s = StringIO.StringIO()
apply(_implementation, (node, s.write), kw)
return s.getvalue() | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/wstools/c14n.py | c14n.py |
ident = "$Id: WSDLTools.py 1122 2006-02-04 01:24:50Z boverhof $"
import weakref
from cStringIO import StringIO
from Namespaces import OASIS, XMLNS, WSA, WSA_LIST, WSRF_V1_2, WSRF
from Utility import Collection, CollectionNS, DOM, ElementProxy, basejoin
from XMLSchema import XMLSchema, SchemaReader, WSDLToolsAdapter
class WSDLReader:
"""A WSDLReader creates WSDL instances from urls and xml data."""
# Custom subclasses of WSDLReader may wish to implement a caching
# strategy or other optimizations. Because application needs vary
# so widely, we don't try to provide any caching by default.
def loadFromStream(self, stream, name=None):
"""Return a WSDL instance loaded from a stream object."""
document = DOM.loadDocument(stream)
wsdl = WSDL()
if name:
wsdl.location = name
elif hasattr(stream, 'name'):
wsdl.location = stream.name
wsdl.load(document)
return wsdl
def loadFromURL(self, url):
"""Return a WSDL instance loaded from the given url."""
document = DOM.loadFromURL(url)
wsdl = WSDL()
wsdl.location = url
wsdl.load(document)
return wsdl
def loadFromString(self, data):
"""Return a WSDL instance loaded from an xml string."""
return self.loadFromStream(StringIO(data))
def loadFromFile(self, filename):
"""Return a WSDL instance loaded from the given file."""
file = open(filename, 'rb')
try:
wsdl = self.loadFromStream(file)
finally:
file.close()
return wsdl
class WSDL:
"""A WSDL object models a WSDL service description. WSDL objects
may be created manually or loaded from an xml representation
using a WSDLReader instance."""
def __init__(self, targetNamespace=None, strict=1):
self.targetNamespace = targetNamespace or 'urn:this-document.wsdl'
self.documentation = ''
self.location = None
self.document = None
self.name = None
self.services = CollectionNS(self)
self.messages = CollectionNS(self)
self.portTypes = CollectionNS(self)
self.bindings = CollectionNS(self)
self.imports = Collection(self)
self.types = Types(self)
self.extensions = []
self.strict = strict
def __del__(self):
if self.document is not None:
self.document.unlink()
version = '1.1'
def addService(self, name, documentation='', targetNamespace=None):
if self.services.has_key(name):
raise WSDLError(
'Duplicate service element: %s' % name
)
item = Service(name, documentation)
if targetNamespace:
item.targetNamespace = targetNamespace
self.services[name] = item
return item
def addMessage(self, name, documentation='', targetNamespace=None):
if self.messages.has_key(name):
raise WSDLError(
'Duplicate message element: %s.' % name
)
item = Message(name, documentation)
if targetNamespace:
item.targetNamespace = targetNamespace
self.messages[name] = item
return item
def addPortType(self, name, documentation='', targetNamespace=None):
if self.portTypes.has_key(name):
raise WSDLError(
'Duplicate portType element: name'
)
item = PortType(name, documentation)
if targetNamespace:
item.targetNamespace = targetNamespace
self.portTypes[name] = item
return item
def addBinding(self, name, type, documentation='', targetNamespace=None):
if self.bindings.has_key(name):
raise WSDLError(
'Duplicate binding element: %s' % name
)
item = Binding(name, type, documentation)
if targetNamespace:
item.targetNamespace = targetNamespace
self.bindings[name] = item
return item
def addImport(self, namespace, location):
item = ImportElement(namespace, location)
self.imports[namespace] = item
return item
def toDom(self):
""" Generate a DOM representation of the WSDL instance.
Not dealing with generating XML Schema, thus the targetNamespace
of all XML Schema elements or types used by WSDL message parts
needs to be specified via import information items.
"""
namespaceURI = DOM.GetWSDLUri(self.version)
self.document = DOM.createDocument(namespaceURI ,'wsdl:definitions')
# Set up a couple prefixes for easy reading.
child = DOM.getElement(self.document, None)
child.setAttributeNS(None, 'targetNamespace', self.targetNamespace)
child.setAttributeNS(XMLNS.BASE, 'xmlns:wsdl', namespaceURI)
child.setAttributeNS(XMLNS.BASE, 'xmlns:xsd', 'http://www.w3.org/1999/XMLSchema')
child.setAttributeNS(XMLNS.BASE, 'xmlns:soap', 'http://schemas.xmlsoap.org/wsdl/soap/')
child.setAttributeNS(XMLNS.BASE, 'xmlns:tns', self.targetNamespace)
if self.name:
child.setAttributeNS(None, 'name', self.name)
# wsdl:import
for item in self.imports:
item.toDom()
# wsdl:message
for item in self.messages:
item.toDom()
# wsdl:portType
for item in self.portTypes:
item.toDom()
# wsdl:binding
for item in self.bindings:
item.toDom()
# wsdl:service
for item in self.services:
item.toDom()
def load(self, document):
# We save a reference to the DOM document to ensure that elements
# saved as "extensions" will continue to have a meaningful context
# for things like namespace references. The lifetime of the DOM
# document is bound to the lifetime of the WSDL instance.
self.document = document
definitions = DOM.getElement(document, 'definitions', None, None)
if definitions is None:
raise WSDLError(
'Missing <definitions> element.'
)
self.version = DOM.WSDLUriToVersion(definitions.namespaceURI)
NS_WSDL = DOM.GetWSDLUri(self.version)
self.targetNamespace = DOM.getAttr(definitions, 'targetNamespace',
None, None)
self.name = DOM.getAttr(definitions, 'name', None, None)
self.documentation = GetDocumentation(definitions)
#
# Retrieve all <wsdl:import>'s, append all children of imported
# document to main document. First iteration grab all original
# <wsdl:import>'s from document, second iteration grab all
# "imported" <wsdl:imports> from document, etc break out when
# no more <wsdl:import>'s.
#
imported = []
base_location = self.location
do_it = True
while do_it:
do_it = False
for element in DOM.getElements(definitions, 'import', NS_WSDL):
location = DOM.getAttr(element, 'location')
if base_location is not None:
location = basejoin(base_location, location)
if location not in imported:
do_it = True
self._import(document, element, base_location)
imported.append(location)
else:
definitions.removeChild(element)
base_location = None
#
# No more <wsdl:import>'s, now load up all other
# WSDL information items.
#
for element in DOM.getElements(definitions, None, None):
targetNamespace = DOM.getAttr(element, 'targetNamespace')
localName = element.localName
if not DOM.nsUriMatch(element.namespaceURI, NS_WSDL):
if localName == 'schema':
tns = DOM.getAttr(element, 'targetNamespace')
reader = SchemaReader(base_url=self.imports[tns].location)
schema = reader.loadFromNode(WSDLToolsAdapter(self),
element)
# schema.setBaseUrl(self.location)
self.types.addSchema(schema)
else:
self.extensions.append(element)
continue
elif localName == 'message':
name = DOM.getAttr(element, 'name')
docs = GetDocumentation(element)
message = self.addMessage(name, docs, targetNamespace)
parts = DOM.getElements(element, 'part', NS_WSDL)
message.load(parts)
continue
elif localName == 'portType':
name = DOM.getAttr(element, 'name')
docs = GetDocumentation(element)
ptype = self.addPortType(name, docs, targetNamespace)
#operations = DOM.getElements(element, 'operation', NS_WSDL)
#ptype.load(operations)
ptype.load(element)
continue
elif localName == 'binding':
name = DOM.getAttr(element, 'name')
type = DOM.getAttr(element, 'type', default=None)
if type is None:
raise WSDLError(
'Missing type attribute for binding %s.' % name
)
type = ParseQName(type, element)
docs = GetDocumentation(element)
binding = self.addBinding(name, type, docs, targetNamespace)
operations = DOM.getElements(element, 'operation', NS_WSDL)
binding.load(operations)
binding.load_ex(GetExtensions(element))
continue
elif localName == 'service':
name = DOM.getAttr(element, 'name')
docs = GetDocumentation(element)
service = self.addService(name, docs, targetNamespace)
ports = DOM.getElements(element, 'port', NS_WSDL)
service.load(ports)
service.load_ex(GetExtensions(element))
continue
elif localName == 'types':
self.types.documentation = GetDocumentation(element)
base_location = DOM.getAttr(element, 'base-location')
if base_location:
element.removeAttribute('base-location')
base_location = base_location or self.location
reader = SchemaReader(base_url=base_location)
for item in DOM.getElements(element, None, None):
if item.localName == 'schema':
schema = reader.loadFromNode(WSDLToolsAdapter(self), item)
# XXX <types> could have been imported
#schema.setBaseUrl(self.location)
schema.setBaseUrl(base_location)
self.types.addSchema(schema)
else:
self.types.addExtension(item)
# XXX remove the attribute
# element.removeAttribute('base-location')
continue
def _import(self, document, element, base_location=None):
'''Algo take <import> element's children, clone them,
and add them to the main document. Support for relative
locations is a bit complicated. The orig document context
is lost, so we need to store base location in DOM elements
representing <types>, by creating a special temporary
"base-location" attribute, and <import>, by resolving
the relative "location" and storing it as "location".
document -- document we are loading
element -- DOM Element representing <import>
base_location -- location of document from which this
<import> was gleaned.
'''
namespace = DOM.getAttr(element, 'namespace', default=None)
location = DOM.getAttr(element, 'location', default=None)
if namespace is None or location is None:
raise WSDLError(
'Invalid import element (missing namespace or location).'
)
if base_location:
location = basejoin(base_location, location)
element.setAttributeNS(None, 'location', location)
obimport = self.addImport(namespace, location)
obimport._loaded = 1
importdoc = DOM.loadFromURL(location)
try:
if location.find('#') > -1:
idref = location.split('#')[-1]
imported = DOM.getElementById(importdoc, idref)
else:
imported = importdoc.documentElement
if imported is None:
raise WSDLError(
'Import target element not found for: %s' % location
)
imported_tns = DOM.findTargetNS(imported)
if imported_tns != namespace:
return
if imported.localName == 'definitions':
imported_nodes = imported.childNodes
else:
imported_nodes = [imported]
parent = element.parentNode
parent.removeChild(element)
for node in imported_nodes:
if node.nodeType != node.ELEMENT_NODE:
continue
child = DOM.importNode(document, node, 1)
parent.appendChild(child)
child.setAttribute('targetNamespace', namespace)
attrsNS = imported._attrsNS
for attrkey in attrsNS.keys():
if attrkey[0] == DOM.NS_XMLNS:
attr = attrsNS[attrkey].cloneNode(1)
child.setAttributeNode(attr)
#XXX Quick Hack, should be in WSDL Namespace.
if child.localName == 'import':
rlocation = child.getAttributeNS(None, 'location')
alocation = basejoin(location, rlocation)
child.setAttribute('location', alocation)
elif child.localName == 'types':
child.setAttribute('base-location', location)
finally:
importdoc.unlink()
return location
class Element:
"""A class that provides common functions for WSDL element classes."""
def __init__(self, name=None, documentation=''):
self.name = name
self.documentation = documentation
self.extensions = []
def addExtension(self, item):
item.parent = weakref.ref(self)
self.extensions.append(item)
def getWSDL(self):
"""Return the WSDL object that contains this information item."""
parent = self
while 1:
# skip any collections
if isinstance(parent, WSDL):
return parent
try: parent = parent.parent()
except: break
return None
class ImportElement(Element):
def __init__(self, namespace, location):
self.namespace = namespace
self.location = location
# def getWSDL(self):
# """Return the WSDL object that contains this Message Part."""
# return self.parent().parent()
def toDom(self):
wsdl = self.getWSDL()
ep = ElementProxy(None, DOM.getElement(wsdl.document, None))
epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), 'import')
epc.setAttributeNS(None, 'namespace', self.namespace)
epc.setAttributeNS(None, 'location', self.location)
_loaded = None
class Types(Collection):
default = lambda self,k: k.targetNamespace
def __init__(self, parent):
Collection.__init__(self, parent)
self.documentation = ''
self.extensions = []
def addSchema(self, schema):
name = schema.targetNamespace
self[name] = schema
return schema
def addExtension(self, item):
self.extensions.append(item)
class Message(Element):
def __init__(self, name, documentation=''):
Element.__init__(self, name, documentation)
self.parts = Collection(self)
def addPart(self, name, type=None, element=None):
if self.parts.has_key(name):
raise WSDLError(
'Duplicate message part element: %s' % name
)
if type is None and element is None:
raise WSDLError(
'Missing type or element attribute for part: %s' % name
)
item = MessagePart(name)
item.element = element
item.type = type
self.parts[name] = item
return item
def load(self, elements):
for element in elements:
name = DOM.getAttr(element, 'name')
part = MessagePart(name)
self.parts[name] = part
elemref = DOM.getAttr(element, 'element', default=None)
typeref = DOM.getAttr(element, 'type', default=None)
if typeref is None and elemref is None:
raise WSDLError(
'No type or element attribute for part: %s' % name
)
if typeref is not None:
part.type = ParseTypeRef(typeref, element)
if elemref is not None:
part.element = ParseTypeRef(elemref, element)
# def getElementDeclaration(self):
# """Return the XMLSchema.ElementDeclaration instance or None"""
# element = None
# if self.element:
# nsuri,name = self.element
# wsdl = self.getWSDL()
# if wsdl.types.has_key(nsuri) and wsdl.types[nsuri].elements.has_key(name):
# element = wsdl.types[nsuri].elements[name]
# return element
#
# def getTypeDefinition(self):
# """Return the XMLSchema.TypeDefinition instance or None"""
# type = None
# if self.type:
# nsuri,name = self.type
# wsdl = self.getWSDL()
# if wsdl.types.has_key(nsuri) and wsdl.types[nsuri].types.has_key(name):
# type = wsdl.types[nsuri].types[name]
# return type
# def getWSDL(self):
# """Return the WSDL object that contains this Message Part."""
# return self.parent().parent()
def toDom(self):
wsdl = self.getWSDL()
ep = ElementProxy(None, DOM.getElement(wsdl.document, None))
epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), 'message')
epc.setAttributeNS(None, 'name', self.name)
for part in self.parts:
part.toDom(epc._getNode())
class MessagePart(Element):
def __init__(self, name):
Element.__init__(self, name, '')
self.element = None
self.type = None
# def getWSDL(self):
# """Return the WSDL object that contains this Message Part."""
# return self.parent().parent().parent().parent()
def getTypeDefinition(self):
wsdl = self.getWSDL()
nsuri,name = self.type
schema = wsdl.types.get(nsuri, {})
return schema.get(name)
def getElementDeclaration(self):
wsdl = self.getWSDL()
nsuri,name = self.element
schema = wsdl.types.get(nsuri, {})
return schema.get(name)
def toDom(self, node):
"""node -- node representing message"""
wsdl = self.getWSDL()
ep = ElementProxy(None, node)
epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), 'part')
epc.setAttributeNS(None, 'name', self.name)
if self.element is not None:
ns,name = self.element
prefix = epc.getPrefix(ns)
epc.setAttributeNS(None, 'element', '%s:%s'%(prefix,name))
elif self.type is not None:
ns,name = self.type
prefix = epc.getPrefix(ns)
epc.setAttributeNS(None, 'type', '%s:%s'%(prefix,name))
class PortType(Element):
'''PortType has a anyAttribute, thus must provide for an extensible
mechanism for supporting such attributes. ResourceProperties is
specified in WS-ResourceProperties. wsa:Action is specified in
WS-Address.
Instance Data:
name -- name attribute
resourceProperties -- optional. wsr:ResourceProperties attribute,
value is a QName this is Parsed into a (namespaceURI, name)
that represents a Global Element Declaration.
operations
'''
def __init__(self, name, documentation=''):
Element.__init__(self, name, documentation)
self.operations = Collection(self)
self.resourceProperties = None
# def getWSDL(self):
# return self.parent().parent()
def getTargetNamespace(self):
return self.targetNamespace or self.getWSDL().targetNamespace
def getResourceProperties(self):
return self.resourceProperties
def addOperation(self, name, documentation='', parameterOrder=None):
item = Operation(name, documentation, parameterOrder)
self.operations[name] = item
return item
def load(self, element):
self.name = DOM.getAttr(element, 'name')
self.documentation = GetDocumentation(element)
self.targetNamespace = DOM.getAttr(element, 'targetNamespace')
for nsuri in WSRF_V1_2.PROPERTIES.XSD_LIST:
if DOM.hasAttr(element, 'ResourceProperties', nsuri):
rpref = DOM.getAttr(element, 'ResourceProperties', nsuri)
self.resourceProperties = ParseQName(rpref, element)
NS_WSDL = DOM.GetWSDLUri(self.getWSDL().version)
elements = DOM.getElements(element, 'operation', NS_WSDL)
for element in elements:
name = DOM.getAttr(element, 'name')
docs = GetDocumentation(element)
param_order = DOM.getAttr(element, 'parameterOrder', default=None)
if param_order is not None:
param_order = param_order.split(' ')
operation = self.addOperation(name, docs, param_order)
item = DOM.getElement(element, 'input', None, None)
if item is not None:
name = DOM.getAttr(item, 'name')
docs = GetDocumentation(item)
msgref = DOM.getAttr(item, 'message')
message = ParseQName(msgref, item)
for WSA in WSA_LIST:
action = DOM.getAttr(item, 'Action', WSA.ADDRESS, None)
if action: break
operation.setInput(message, name, docs, action)
item = DOM.getElement(element, 'output', None, None)
if item is not None:
name = DOM.getAttr(item, 'name')
docs = GetDocumentation(item)
msgref = DOM.getAttr(item, 'message')
message = ParseQName(msgref, item)
for WSA in WSA_LIST:
action = DOM.getAttr(item, 'Action', WSA.ADDRESS, None)
if action: break
operation.setOutput(message, name, docs, action)
for item in DOM.getElements(element, 'fault', None):
name = DOM.getAttr(item, 'name')
docs = GetDocumentation(item)
msgref = DOM.getAttr(item, 'message')
message = ParseQName(msgref, item)
for WSA in WSA_LIST:
action = DOM.getAttr(item, 'Action', WSA.ADDRESS, None)
if action: break
operation.addFault(message, name, docs, action)
def toDom(self):
wsdl = self.getWSDL()
ep = ElementProxy(None, DOM.getElement(wsdl.document, None))
epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), 'portType')
epc.setAttributeNS(None, 'name', self.name)
if self.resourceProperties:
ns,name = self.resourceProperties
prefix = epc.getPrefix(ns)
epc.setAttributeNS(WSRF.PROPERTIES.LATEST, 'ResourceProperties',
'%s:%s'%(prefix,name))
for op in self.operations:
op.toDom(epc._getNode())
class Operation(Element):
def __init__(self, name, documentation='', parameterOrder=None):
Element.__init__(self, name, documentation)
self.parameterOrder = parameterOrder
self.faults = Collection(self)
self.input = None
self.output = None
def getWSDL(self):
"""Return the WSDL object that contains this Operation."""
return self.parent().parent().parent().parent()
def getPortType(self):
return self.parent().parent()
def getInputAction(self):
"""wsa:Action attribute"""
return GetWSAActionInput(self)
def getInputMessage(self):
if self.input is None:
return None
wsdl = self.getPortType().getWSDL()
return wsdl.messages[self.input.message]
def getOutputAction(self):
"""wsa:Action attribute"""
return GetWSAActionOutput(self)
def getOutputMessage(self):
if self.output is None:
return None
wsdl = self.getPortType().getWSDL()
return wsdl.messages[self.output.message]
def getFaultAction(self, name):
"""wsa:Action attribute"""
return GetWSAActionFault(self, name)
def getFaultMessage(self, name):
wsdl = self.getPortType().getWSDL()
return wsdl.messages[self.faults[name].message]
def addFault(self, message, name, documentation='', action=None):
if self.faults.has_key(name):
raise WSDLError(
'Duplicate fault element: %s' % name
)
item = MessageRole('fault', message, name, documentation, action)
self.faults[name] = item
return item
def setInput(self, message, name='', documentation='', action=None):
self.input = MessageRole('input', message, name, documentation, action)
self.input.parent = weakref.ref(self)
return self.input
def setOutput(self, message, name='', documentation='', action=None):
self.output = MessageRole('output', message, name, documentation, action)
self.output.parent = weakref.ref(self)
return self.output
def toDom(self, node):
wsdl = self.getWSDL()
ep = ElementProxy(None, node)
epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), 'operation')
epc.setAttributeNS(None, 'name', self.name)
node = epc._getNode()
if self.input:
self.input.toDom(node)
if self.output:
self.output.toDom(node)
for fault in self.faults:
fault.toDom(node)
class MessageRole(Element):
def __init__(self, type, message, name='', documentation='', action=None):
Element.__init__(self, name, documentation)
self.message = message
self.type = type
self.action = action
def getWSDL(self):
"""Return the WSDL object that contains this information item."""
parent = self
while 1:
# skip any collections
if isinstance(parent, WSDL):
return parent
try: parent = parent.parent()
except: break
return None
def getMessage(self):
"""Return the WSDL object that represents the attribute message
(namespaceURI, name) tuple
"""
wsdl = self.getWSDL()
return wsdl.messages[self.message]
def toDom(self, node):
wsdl = self.getWSDL()
ep = ElementProxy(None, node)
epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), self.type)
if not isinstance(self.message, basestring) and len(self.message) == 2:
ns,name = self.message
prefix = epc.getPrefix(ns)
epc.setAttributeNS(None, 'message', '%s:%s' %(prefix,name))
else:
epc.setAttributeNS(None, 'message', self.message)
if self.action:
epc.setAttributeNS(WSA.ADDRESS, 'Action', self.action)
if self.name:
epc.setAttributeNS(None, 'name', self.name)
class Binding(Element):
def __init__(self, name, type, documentation=''):
Element.__init__(self, name, documentation)
self.operations = Collection(self)
self.type = type
# def getWSDL(self):
# """Return the WSDL object that contains this binding."""
# return self.parent().parent()
def getPortType(self):
"""Return the PortType object associated with this binding."""
return self.getWSDL().portTypes[self.type]
def findBinding(self, kind):
for item in self.extensions:
if isinstance(item, kind):
return item
return None
def findBindings(self, kind):
return [ item for item in self.extensions if isinstance(item, kind) ]
def addOperationBinding(self, name, documentation=''):
item = OperationBinding(name, documentation)
self.operations[name] = item
return item
def load(self, elements):
for element in elements:
name = DOM.getAttr(element, 'name')
docs = GetDocumentation(element)
opbinding = self.addOperationBinding(name, docs)
opbinding.load_ex(GetExtensions(element))
item = DOM.getElement(element, 'input', None, None)
if item is not None:
#TODO: addInputBinding?
mbinding = MessageRoleBinding('input')
mbinding.documentation = GetDocumentation(item)
opbinding.input = mbinding
mbinding.load_ex(GetExtensions(item))
mbinding.parent = weakref.ref(opbinding)
item = DOM.getElement(element, 'output', None, None)
if item is not None:
mbinding = MessageRoleBinding('output')
mbinding.documentation = GetDocumentation(item)
opbinding.output = mbinding
mbinding.load_ex(GetExtensions(item))
mbinding.parent = weakref.ref(opbinding)
for item in DOM.getElements(element, 'fault', None):
name = DOM.getAttr(item, 'name')
mbinding = MessageRoleBinding('fault', name)
mbinding.documentation = GetDocumentation(item)
opbinding.faults[name] = mbinding
mbinding.load_ex(GetExtensions(item))
mbinding.parent = weakref.ref(opbinding)
def load_ex(self, elements):
for e in elements:
ns, name = e.namespaceURI, e.localName
if ns in DOM.NS_SOAP_BINDING_ALL and name == 'binding':
transport = DOM.getAttr(e, 'transport', default=None)
style = DOM.getAttr(e, 'style', default='document')
ob = SoapBinding(transport, style)
self.addExtension(ob)
continue
elif ns in DOM.NS_HTTP_BINDING_ALL and name == 'binding':
verb = DOM.getAttr(e, 'verb')
ob = HttpBinding(verb)
self.addExtension(ob)
continue
else:
self.addExtension(e)
def toDom(self):
wsdl = self.getWSDL()
ep = ElementProxy(None, DOM.getElement(wsdl.document, None))
epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), 'binding')
epc.setAttributeNS(None, 'name', self.name)
ns,name = self.type
prefix = epc.getPrefix(ns)
epc.setAttributeNS(None, 'type', '%s:%s' %(prefix,name))
node = epc._getNode()
for ext in self.extensions:
ext.toDom(node)
for op_binding in self.operations:
op_binding.toDom(node)
class OperationBinding(Element):
def __init__(self, name, documentation=''):
Element.__init__(self, name, documentation)
self.input = None
self.output = None
self.faults = Collection(self)
# def getWSDL(self):
# """Return the WSDL object that contains this binding."""
# return self.parent().parent().parent().parent()
def getBinding(self):
"""Return the parent Binding object of the operation binding."""
return self.parent().parent()
def getOperation(self):
"""Return the abstract Operation associated with this binding."""
return self.getBinding().getPortType().operations[self.name]
def findBinding(self, kind):
for item in self.extensions:
if isinstance(item, kind):
return item
return None
def findBindings(self, kind):
return [ item for item in self.extensions if isinstance(item, kind) ]
def addInputBinding(self, binding):
if self.input is None:
self.input = MessageRoleBinding('input')
self.input.parent = weakref.ref(self)
self.input.addExtension(binding)
return binding
def addOutputBinding(self, binding):
if self.output is None:
self.output = MessageRoleBinding('output')
self.output.parent = weakref.ref(self)
self.output.addExtension(binding)
return binding
def addFaultBinding(self, name, binding):
fault = self.get(name, None)
if fault is None:
fault = MessageRoleBinding('fault', name)
fault.addExtension(binding)
return binding
def load_ex(self, elements):
for e in elements:
ns, name = e.namespaceURI, e.localName
if ns in DOM.NS_SOAP_BINDING_ALL and name == 'operation':
soapaction = DOM.getAttr(e, 'soapAction', default=None)
style = DOM.getAttr(e, 'style', default=None)
ob = SoapOperationBinding(soapaction, style)
self.addExtension(ob)
continue
elif ns in DOM.NS_HTTP_BINDING_ALL and name == 'operation':
location = DOM.getAttr(e, 'location')
ob = HttpOperationBinding(location)
self.addExtension(ob)
continue
else:
self.addExtension(e)
def toDom(self, node):
wsdl = self.getWSDL()
ep = ElementProxy(None, node)
epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), 'operation')
epc.setAttributeNS(None, 'name', self.name)
node = epc._getNode()
for ext in self.extensions:
ext.toDom(node)
if self.input:
self.input.toDom(node)
if self.output:
self.output.toDom(node)
for fault in self.faults:
fault.toDom(node)
class MessageRoleBinding(Element):
def __init__(self, type, name='', documentation=''):
Element.__init__(self, name, documentation)
self.type = type
def findBinding(self, kind):
for item in self.extensions:
if isinstance(item, kind):
return item
return None
def findBindings(self, kind):
return [ item for item in self.extensions if isinstance(item, kind) ]
def load_ex(self, elements):
for e in elements:
ns, name = e.namespaceURI, e.localName
if ns in DOM.NS_SOAP_BINDING_ALL and name == 'body':
encstyle = DOM.getAttr(e, 'encodingStyle', default=None)
namespace = DOM.getAttr(e, 'namespace', default=None)
parts = DOM.getAttr(e, 'parts', default=None)
use = DOM.getAttr(e, 'use', default=None)
if use is None:
raise WSDLError(
'Invalid soap:body binding element.'
)
ob = SoapBodyBinding(use, namespace, encstyle, parts)
self.addExtension(ob)
continue
elif ns in DOM.NS_SOAP_BINDING_ALL and name == 'fault':
encstyle = DOM.getAttr(e, 'encodingStyle', default=None)
namespace = DOM.getAttr(e, 'namespace', default=None)
name = DOM.getAttr(e, 'name', default=None)
use = DOM.getAttr(e, 'use', default=None)
if use is None or name is None:
raise WSDLError(
'Invalid soap:fault binding element.'
)
ob = SoapFaultBinding(name, use, namespace, encstyle)
self.addExtension(ob)
continue
elif ns in DOM.NS_SOAP_BINDING_ALL and name in (
'header', 'headerfault'
):
encstyle = DOM.getAttr(e, 'encodingStyle', default=None)
namespace = DOM.getAttr(e, 'namespace', default=None)
message = DOM.getAttr(e, 'message')
part = DOM.getAttr(e, 'part')
use = DOM.getAttr(e, 'use')
if name == 'header':
_class = SoapHeaderBinding
else:
_class = SoapHeaderFaultBinding
message = ParseQName(message, e)
ob = _class(message, part, use, namespace, encstyle)
self.addExtension(ob)
continue
elif ns in DOM.NS_HTTP_BINDING_ALL and name == 'urlReplacement':
ob = HttpUrlReplacementBinding()
self.addExtension(ob)
continue
elif ns in DOM.NS_HTTP_BINDING_ALL and name == 'urlEncoded':
ob = HttpUrlEncodedBinding()
self.addExtension(ob)
continue
elif ns in DOM.NS_MIME_BINDING_ALL and name == 'multipartRelated':
ob = MimeMultipartRelatedBinding()
self.addExtension(ob)
ob.load_ex(GetExtensions(e))
continue
elif ns in DOM.NS_MIME_BINDING_ALL and name == 'content':
part = DOM.getAttr(e, 'part', default=None)
type = DOM.getAttr(e, 'type', default=None)
ob = MimeContentBinding(part, type)
self.addExtension(ob)
continue
elif ns in DOM.NS_MIME_BINDING_ALL and name == 'mimeXml':
part = DOM.getAttr(e, 'part', default=None)
ob = MimeXmlBinding(part)
self.addExtension(ob)
continue
else:
self.addExtension(e)
def toDom(self, node):
wsdl = self.getWSDL()
ep = ElementProxy(None, node)
epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), self.type)
node = epc._getNode()
for item in self.extensions:
if item: item.toDom(node)
class Service(Element):
def __init__(self, name, documentation=''):
Element.__init__(self, name, documentation)
self.ports = Collection(self)
def getWSDL(self):
return self.parent().parent()
def addPort(self, name, binding, documentation=''):
item = Port(name, binding, documentation)
self.ports[name] = item
return item
def load(self, elements):
for element in elements:
name = DOM.getAttr(element, 'name', default=None)
docs = GetDocumentation(element)
binding = DOM.getAttr(element, 'binding', default=None)
if name is None or binding is None:
raise WSDLError(
'Invalid port element.'
)
binding = ParseQName(binding, element)
port = self.addPort(name, binding, docs)
port.load_ex(GetExtensions(element))
def load_ex(self, elements):
for e in elements:
self.addExtension(e)
def toDom(self):
wsdl = self.getWSDL()
ep = ElementProxy(None, DOM.getElement(wsdl.document, None))
epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), "service")
epc.setAttributeNS(None, "name", self.name)
node = epc._getNode()
for port in self.ports:
port.toDom(node)
class Port(Element):
def __init__(self, name, binding, documentation=''):
Element.__init__(self, name, documentation)
self.binding = binding
# def getWSDL(self):
# return self.parent().parent().getWSDL()
def getService(self):
"""Return the Service object associated with this port."""
return self.parent().parent()
def getBinding(self):
"""Return the Binding object that is referenced by this port."""
wsdl = self.getService().getWSDL()
return wsdl.bindings[self.binding]
def getPortType(self):
"""Return the PortType object that is referenced by this port."""
wsdl = self.getService().getWSDL()
binding = wsdl.bindings[self.binding]
return wsdl.portTypes[binding.type]
def getAddressBinding(self):
"""A convenience method to obtain the extension element used
as the address binding for the port."""
for item in self.extensions:
if isinstance(item, SoapAddressBinding) or \
isinstance(item, HttpAddressBinding):
return item
raise WSDLError(
'No address binding found in port.'
)
def load_ex(self, elements):
for e in elements:
ns, name = e.namespaceURI, e.localName
if ns in DOM.NS_SOAP_BINDING_ALL and name == 'address':
location = DOM.getAttr(e, 'location', default=None)
ob = SoapAddressBinding(location)
self.addExtension(ob)
continue
elif ns in DOM.NS_HTTP_BINDING_ALL and name == 'address':
location = DOM.getAttr(e, 'location', default=None)
ob = HttpAddressBinding(location)
self.addExtension(ob)
continue
else:
self.addExtension(e)
def toDom(self, node):
wsdl = self.getWSDL()
ep = ElementProxy(None, node)
epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), "port")
epc.setAttributeNS(None, "name", self.name)
ns,name = self.binding
prefix = epc.getPrefix(ns)
epc.setAttributeNS(None, "binding", "%s:%s" %(prefix,name))
node = epc._getNode()
for ext in self.extensions:
ext.toDom(node)
class SoapBinding:
def __init__(self, transport, style='rpc'):
self.transport = transport
self.style = style
def getWSDL(self):
return self.parent().getWSDL()
def toDom(self, node):
wsdl = self.getWSDL()
ep = ElementProxy(None, node)
epc = ep.createAppendElement(DOM.GetWSDLSoapBindingUri(wsdl.version), 'binding')
if self.transport:
epc.setAttributeNS(None, "transport", self.transport)
if self.style:
epc.setAttributeNS(None, "style", self.style)
class SoapAddressBinding:
def __init__(self, location):
self.location = location
def getWSDL(self):
return self.parent().getWSDL()
def toDom(self, node):
wsdl = self.getWSDL()
ep = ElementProxy(None, node)
epc = ep.createAppendElement(DOM.GetWSDLSoapBindingUri(wsdl.version), 'address')
epc.setAttributeNS(None, "location", self.location)
class SoapOperationBinding:
def __init__(self, soapAction=None, style=None):
self.soapAction = soapAction
self.style = style
def getWSDL(self):
return self.parent().getWSDL()
def toDom(self, node):
wsdl = self.getWSDL()
ep = ElementProxy(None, node)
epc = ep.createAppendElement(DOM.GetWSDLSoapBindingUri(wsdl.version), 'operation')
if self.soapAction:
epc.setAttributeNS(None, 'soapAction', self.soapAction)
if self.style:
epc.setAttributeNS(None, 'style', self.style)
class SoapBodyBinding:
def __init__(self, use, namespace=None, encodingStyle=None, parts=None):
if not use in ('literal', 'encoded'):
raise WSDLError(
'Invalid use attribute value: %s' % use
)
self.encodingStyle = encodingStyle
self.namespace = namespace
if type(parts) in (type(''), type(u'')):
parts = parts.split()
self.parts = parts
self.use = use
def getWSDL(self):
return self.parent().getWSDL()
def toDom(self, node):
wsdl = self.getWSDL()
ep = ElementProxy(None, node)
epc = ep.createAppendElement(DOM.GetWSDLSoapBindingUri(wsdl.version), 'body')
epc.setAttributeNS(None, "use", self.use)
epc.setAttributeNS(None, "namespace", self.namespace)
class SoapFaultBinding:
def __init__(self, name, use, namespace=None, encodingStyle=None):
if not use in ('literal', 'encoded'):
raise WSDLError(
'Invalid use attribute value: %s' % use
)
self.encodingStyle = encodingStyle
self.namespace = namespace
self.name = name
self.use = use
def getWSDL(self):
return self.parent().getWSDL()
def toDom(self, node):
wsdl = self.getWSDL()
ep = ElementProxy(None, node)
epc = ep.createAppendElement(DOM.GetWSDLSoapBindingUri(wsdl.version), 'body')
epc.setAttributeNS(None, "use", self.use)
epc.setAttributeNS(None, "name", self.name)
if self.namespace is not None:
epc.setAttributeNS(None, "namespace", self.namespace)
if self.encodingStyle is not None:
epc.setAttributeNS(None, "encodingStyle", self.encodingStyle)
class SoapHeaderBinding:
def __init__(self, message, part, use, namespace=None, encodingStyle=None):
if not use in ('literal', 'encoded'):
raise WSDLError(
'Invalid use attribute value: %s' % use
)
self.encodingStyle = encodingStyle
self.namespace = namespace
self.message = message
self.part = part
self.use = use
tagname = 'header'
class SoapHeaderFaultBinding(SoapHeaderBinding):
tagname = 'headerfault'
class HttpBinding:
def __init__(self, verb):
self.verb = verb
class HttpAddressBinding:
def __init__(self, location):
self.location = location
class HttpOperationBinding:
def __init__(self, location):
self.location = location
class HttpUrlReplacementBinding:
pass
class HttpUrlEncodedBinding:
pass
class MimeContentBinding:
def __init__(self, part=None, type=None):
self.part = part
self.type = type
class MimeXmlBinding:
def __init__(self, part=None):
self.part = part
class MimeMultipartRelatedBinding:
def __init__(self):
self.parts = []
def load_ex(self, elements):
for e in elements:
ns, name = e.namespaceURI, e.localName
if ns in DOM.NS_MIME_BINDING_ALL and name == 'part':
self.parts.append(MimePartBinding())
continue
class MimePartBinding:
def __init__(self):
self.items = []
def load_ex(self, elements):
for e in elements:
ns, name = e.namespaceURI, e.localName
if ns in DOM.NS_MIME_BINDING_ALL and name == 'content':
part = DOM.getAttr(e, 'part', default=None)
type = DOM.getAttr(e, 'type', default=None)
ob = MimeContentBinding(part, type)
self.items.append(ob)
continue
elif ns in DOM.NS_MIME_BINDING_ALL and name == 'mimeXml':
part = DOM.getAttr(e, 'part', default=None)
ob = MimeXmlBinding(part)
self.items.append(ob)
continue
elif ns in DOM.NS_SOAP_BINDING_ALL and name == 'body':
encstyle = DOM.getAttr(e, 'encodingStyle', default=None)
namespace = DOM.getAttr(e, 'namespace', default=None)
parts = DOM.getAttr(e, 'parts', default=None)
use = DOM.getAttr(e, 'use', default=None)
if use is None:
raise WSDLError(
'Invalid soap:body binding element.'
)
ob = SoapBodyBinding(use, namespace, encstyle, parts)
self.items.append(ob)
continue
class WSDLError(Exception):
pass
def DeclareNSPrefix(writer, prefix, nsuri):
if writer.hasNSPrefix(nsuri):
return
writer.declareNSPrefix(prefix, nsuri)
def ParseTypeRef(value, element):
parts = value.split(':', 1)
if len(parts) == 1:
return (DOM.findTargetNS(element), value)
nsuri = DOM.findNamespaceURI(parts[0], element)
return (nsuri, parts[1])
def ParseQName(value, element):
nameref = value.split(':', 1)
if len(nameref) == 2:
nsuri = DOM.findNamespaceURI(nameref[0], element)
name = nameref[-1]
else:
nsuri = DOM.findTargetNS(element)
name = nameref[-1]
return nsuri, name
def GetDocumentation(element):
docnode = DOM.getElement(element, 'documentation', None, None)
if docnode is not None:
return DOM.getElementText(docnode)
return ''
def GetExtensions(element):
return [ item for item in DOM.getElements(element, None, None)
if item.namespaceURI != DOM.NS_WSDL ]
def GetWSAActionFault(operation, name):
"""Find wsa:Action attribute, and return value or WSA.FAULT
for the default.
"""
attr = operation.faults[name].action
if attr is not None:
return attr
return WSA.FAULT
def GetWSAActionInput(operation):
"""Find wsa:Action attribute, and return value or the default."""
attr = operation.input.action
if attr is not None:
return attr
portType = operation.getPortType()
targetNamespace = portType.getTargetNamespace()
ptName = portType.name
msgName = operation.input.name
if not msgName:
msgName = operation.name + 'Request'
if targetNamespace.endswith('/'):
return '%s%s/%s' %(targetNamespace, ptName, msgName)
return '%s/%s/%s' %(targetNamespace, ptName, msgName)
def GetWSAActionOutput(operation):
"""Find wsa:Action attribute, and return value or the default."""
attr = operation.output.action
if attr is not None:
return attr
targetNamespace = operation.getPortType().getTargetNamespace()
ptName = operation.getPortType().name
msgName = operation.output.name
if not msgName:
msgName = operation.name + 'Response'
if targetNamespace.endswith('/'):
return '%s%s/%s' %(targetNamespace, ptName, msgName)
return '%s/%s/%s' %(targetNamespace, ptName, msgName)
def FindExtensions(object, kind, t_type=type(())):
if isinstance(kind, t_type):
result = []
namespaceURI, name = kind
return [ item for item in object.extensions
if hasattr(item, 'nodeType') \
and DOM.nsUriMatch(namespaceURI, item.namespaceURI) \
and item.name == name ]
return [ item for item in object.extensions if isinstance(item, kind) ]
def FindExtension(object, kind, t_type=type(())):
if isinstance(kind, t_type):
namespaceURI, name = kind
for item in object.extensions:
if hasattr(item, 'nodeType') \
and DOM.nsUriMatch(namespaceURI, item.namespaceURI) \
and item.name == name:
return item
else:
for item in object.extensions:
if isinstance(item, kind):
return item
return None
class SOAPCallInfo:
"""SOAPCallInfo captures the important binding information about a
SOAP operation, in a structure that is easier to work with than
raw WSDL structures."""
def __init__(self, methodName):
self.methodName = methodName
self.inheaders = []
self.outheaders = []
self.inparams = []
self.outparams = []
self.retval = None
encodingStyle = DOM.NS_SOAP_ENC
documentation = ''
soapAction = None
transport = None
namespace = None
location = None
use = 'encoded'
style = 'rpc'
def addInParameter(self, name, type, namespace=None, element_type=0):
"""Add an input parameter description to the call info."""
parameter = ParameterInfo(name, type, namespace, element_type)
self.inparams.append(parameter)
return parameter
def addOutParameter(self, name, type, namespace=None, element_type=0):
"""Add an output parameter description to the call info."""
parameter = ParameterInfo(name, type, namespace, element_type)
self.outparams.append(parameter)
return parameter
def setReturnParameter(self, name, type, namespace=None, element_type=0):
"""Set the return parameter description for the call info."""
parameter = ParameterInfo(name, type, namespace, element_type)
self.retval = parameter
return parameter
def addInHeaderInfo(self, name, type, namespace, element_type=0,
mustUnderstand=0):
"""Add an input SOAP header description to the call info."""
headerinfo = HeaderInfo(name, type, namespace, element_type)
if mustUnderstand:
headerinfo.mustUnderstand = 1
self.inheaders.append(headerinfo)
return headerinfo
def addOutHeaderInfo(self, name, type, namespace, element_type=0,
mustUnderstand=0):
"""Add an output SOAP header description to the call info."""
headerinfo = HeaderInfo(name, type, namespace, element_type)
if mustUnderstand:
headerinfo.mustUnderstand = 1
self.outheaders.append(headerinfo)
return headerinfo
def getInParameters(self):
"""Return a sequence of the in parameters of the method."""
return self.inparams
def getOutParameters(self):
"""Return a sequence of the out parameters of the method."""
return self.outparams
def getReturnParameter(self):
"""Return param info about the return value of the method."""
return self.retval
def getInHeaders(self):
"""Return a sequence of the in headers of the method."""
return self.inheaders
def getOutHeaders(self):
"""Return a sequence of the out headers of the method."""
return self.outheaders
class ParameterInfo:
"""A ParameterInfo object captures parameter binding information."""
def __init__(self, name, type, namespace=None, element_type=0):
if element_type:
self.element_type = 1
if namespace is not None:
self.namespace = namespace
self.name = name
self.type = type
element_type = 0
namespace = None
default = None
class HeaderInfo(ParameterInfo):
"""A HeaderInfo object captures SOAP header binding information."""
def __init__(self, name, type, namespace, element_type=None):
ParameterInfo.__init__(self, name, type, namespace, element_type)
mustUnderstand = 0
actor = None
def callInfoFromWSDL(port, name):
"""Return a SOAPCallInfo given a WSDL port and operation name."""
wsdl = port.getService().getWSDL()
binding = port.getBinding()
portType = binding.getPortType()
operation = portType.operations[name]
opbinding = binding.operations[name]
messages = wsdl.messages
callinfo = SOAPCallInfo(name)
addrbinding = port.getAddressBinding()
if not isinstance(addrbinding, SoapAddressBinding):
raise ValueError, 'Unsupported binding type.'
callinfo.location = addrbinding.location
soapbinding = binding.findBinding(SoapBinding)
if soapbinding is None:
raise ValueError, 'Missing soap:binding element.'
callinfo.transport = soapbinding.transport
callinfo.style = soapbinding.style or 'document'
soap_op_binding = opbinding.findBinding(SoapOperationBinding)
if soap_op_binding is not None:
callinfo.soapAction = soap_op_binding.soapAction
callinfo.style = soap_op_binding.style or callinfo.style
parameterOrder = operation.parameterOrder
if operation.input is not None:
message = messages[operation.input.message]
msgrole = opbinding.input
mime = msgrole.findBinding(MimeMultipartRelatedBinding)
if mime is not None:
raise ValueError, 'Mime bindings are not supported.'
else:
for item in msgrole.findBindings(SoapHeaderBinding):
part = messages[item.message].parts[item.part]
header = callinfo.addInHeaderInfo(
part.name,
part.element or part.type,
item.namespace,
element_type = part.element and 1 or 0
)
header.encodingStyle = item.encodingStyle
body = msgrole.findBinding(SoapBodyBinding)
if body is None:
raise ValueError, 'Missing soap:body binding.'
callinfo.encodingStyle = body.encodingStyle
callinfo.namespace = body.namespace
callinfo.use = body.use
if body.parts is not None:
parts = []
for name in body.parts:
parts.append(message.parts[name])
else:
parts = message.parts.values()
for part in parts:
callinfo.addInParameter(
part.name,
part.element or part.type,
element_type = part.element and 1 or 0
)
if operation.output is not None:
try:
message = messages[operation.output.message]
except KeyError:
if self.strict:
raise RuntimeError(
"Recieved message not defined in the WSDL schema: %s" %
operation.output.message)
else:
message = wsdl.addMessage(operation.output.message)
print "Warning:", \
"Recieved message not defined in the WSDL schema.", \
"Adding it."
print "Message:", operation.output.message
msgrole = opbinding.output
mime = msgrole.findBinding(MimeMultipartRelatedBinding)
if mime is not None:
raise ValueError, 'Mime bindings are not supported.'
else:
for item in msgrole.findBindings(SoapHeaderBinding):
part = messages[item.message].parts[item.part]
header = callinfo.addOutHeaderInfo(
part.name,
part.element or part.type,
item.namespace,
element_type = part.element and 1 or 0
)
header.encodingStyle = item.encodingStyle
body = msgrole.findBinding(SoapBodyBinding)
if body is None:
raise ValueError, 'Missing soap:body binding.'
callinfo.encodingStyle = body.encodingStyle
callinfo.namespace = body.namespace
callinfo.use = body.use
if body.parts is not None:
parts = []
for name in body.parts:
parts.append(message.parts[name])
else:
parts = message.parts.values()
if parts:
for part in parts:
callinfo.addOutParameter(
part.name,
part.element or part.type,
element_type = part.element and 1 or 0
)
return callinfo | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/wstools/WSDLTools.py | WSDLTools.py |
import time
# twisted & related imports
from zope.interface import classProvides, implements, Interface
from twisted.web import client
from twisted.internet import defer
from twisted.internet import reactor
from twisted.python import log
from twisted.python.failure import Failure
from ZSI.parse import ParsedSoap
from ZSI.writer import SoapWriter
from ZSI.fault import FaultFromFaultMessage
from ZSI.wstools.Namespaces import WSA
from WSresource import HandlerChainInterface, CheckInputArgs
#
# Stability: Unstable
#
class HTTPPageGetter(client.HTTPPageGetter):
def handleStatus_500(self):
"""potentially a SOAP:Fault.
"""
log.err('HTTP Error 500')
def handleStatus_404(self):
"""client error, not found
"""
log.err('HTTP Error 404')
client.HTTPClientFactory.protocol = HTTPPageGetter
def getPage(url, contextFactory=None, *args, **kwargs):
"""Download a web page as a string.
Download a page. Return a deferred, which will callback with a
page (as a string) or errback with a description of the error.
See HTTPClientFactory to see what extra args can be passed.
"""
scheme, host, port, path = client._parse(url)
factory = client.HTTPClientFactory(url, *args, **kwargs)
if scheme == 'https':
if contextFactory is None:
raise RuntimeError, 'must provide a contextFactory'
conn = reactor.connectSSL(host, port, factory, contextFactory)
else:
conn = reactor.connectTCP(host, port, factory)
return factory
class ClientDataHandler:
"""
class variables:
readerClass -- factory class to create reader for ParsedSoap instances.
writerClass -- ElementProxy implementation to use for SoapWriter
instances.
"""
classProvides(HandlerChainInterface)
readerClass = None
writerClass = None
@classmethod
def processResponse(cls, soapdata, **kw):
"""called by deferred, returns pyobj representing reply.
Parameters and Key Words:
soapdata -- SOAP Data
replytype -- reply type of response
"""
if len(soapdata) == 0:
raise TypeError('Received empty response')
# log.msg("_" * 33, time.ctime(time.time()),
# "RESPONSE: \n%s" %soapdata, debug=True)
ps = ParsedSoap(soapdata, readerclass=cls.readerClass)
if ps.IsAFault() is True:
log.msg('Received SOAP:Fault', debug=True)
raise FaultFromFaultMessage(ps)
return ps
@classmethod
def processRequest(cls, obj, nsdict={}, header=True,
**kw):
tc = None
if kw.has_key('requesttypecode'):
tc = kw['requesttypecode']
elif kw.has_key('requestclass'):
tc = kw['requestclass'].typecode
else:
tc = getattr(obj.__class__, 'typecode', None)
sw = SoapWriter(nsdict=nsdict, header=header,
outputclass=cls.writerClass)
sw.serialize(obj, tc)
return sw
class WSAddressHandler:
"""Minimal WS-Address handler. Most of the logic is in
the ZSI.address.Address class.
class variables:
uri -- default WSA Addressing URI
"""
implements(HandlerChainInterface)
uri = WSA.ADDRESS
def processResponse(self, ps, wsaction=None, soapaction=None, **kw):
addr = self.address
addr.parse(ps)
action = addr.getAction()
if not action:
raise WSActionException('No WS-Action specified in Request')
if not soapaction:
return ps
soapaction = soapaction.strip('\'"')
if soapaction and soapaction != wsaction:
raise WSActionException(\
'SOAP Action("%s") must match WS-Action("%s") if specified.'%(
soapaction, wsaction)
)
return ps
def processRequest(self, sw, wsaction=None, url=None, endPointReference=None, **kw):
from ZSI.address import Address
if sw is None:
self.address = None
return
if not sw.header:
raise RuntimeError, 'expecting SOAP:Header'
self.address = addr = Address(url, wsAddressURI=self.uri)
addr.setRequest(endPointReference, wsaction)
addr.serialize(sw, typed=False)
return sw
class DefaultClientHandlerChain:
@CheckInputArgs(HandlerChainInterface)
def __init__(self, *handlers):
self.handlers = handlers
self.debug = len(log.theLogPublisher.observers) > 0
self.flow = None
@staticmethod
def parseResponse(ps, replytype):
return ps.Parse(replytype)
def processResponse(self, arg, replytype, **kw):
"""
Parameters:
arg -- deferred
replytype -- typecode
"""
if self.debug:
log.msg('--->PROCESS REQUEST\n%s' %arg, debug=1)
for h in self.handlers:
arg.addCallback(h.processResponse, **kw)
arg.addCallback(self.parseResponse, replytype)
def processRequest(self, arg, **kw):
"""
Parameters:
arg -- XML Soap data string
"""
if self.debug:
log.msg('===>PROCESS RESPONSE: %s' %str(arg), debug=1)
if arg is None:
return
for h in self.handlers:
arg = h.processRequest(arg, **kw)
s = str(arg)
if self.debug:
log.msg(s, debug=1)
return s
class DefaultClientHandlerChainFactory:
protocol = DefaultClientHandlerChain
@classmethod
def newInstance(cls):
return cls.protocol(ClientDataHandler)
class WSAddressClientHandlerChainFactory:
protocol = DefaultClientHandlerChain
@classmethod
def newInstance(cls):
return cls.protocol(ClientDataHandler,
WSAddressHandler())
class Binding:
"""Object that represents a binding (connection) to a SOAP server.
"""
agent='ZSI.twisted client'
factory = DefaultClientHandlerChainFactory
defer = False
def __init__(self, url=None, nsdict=None, contextFactory=None,
tracefile=None, **kw):
"""Initialize.
Keyword arguments include:
url -- URL of resource, POST is path
nsdict -- namespace entries to add
contextFactory -- security contexts
tracefile -- file to dump packet traces
"""
self.url = url
self.nsdict = nsdict or {}
self.contextFactory = contextFactory
self.http_headers = {'content-type': 'text/xml',}
self.trace = tracefile
def addHTTPHeader(self, key, value):
self.http_headers[key] = value
def getHTTPHeaders(self):
return self.http_headers
def Send(self, url, opname, pyobj, nsdict={}, soapaction=None, chain=None,
**kw):
"""Returns a ProcessingChain which needs to be passed to Receive if
Send is being called consecutively.
"""
url = url or self.url
cookies = None
if chain is not None:
cookies = chain.flow.cookies
d = {}
d.update(self.nsdict)
d.update(nsdict)
if soapaction is not None:
self.addHTTPHeader('SOAPAction', soapaction)
chain = self.factory.newInstance()
soapdata = chain.processRequest(pyobj, nsdict=nsdict,
soapaction=soapaction, **kw)
if self.trace:
print >>self.trace, "_" * 33, time.ctime(time.time()), "REQUEST:"
print >>self.trace, soapdata
f = getPage(str(url), contextFactory=self.contextFactory,
postdata=soapdata, agent=self.agent,
method='POST', headers=self.getHTTPHeaders(),
cookies=cookies)
if isinstance(f, Failure):
return f
chain.flow = f
self.chain = chain
return chain
def Receive(self, replytype, chain=None, **kw):
"""This method allows code to act in a synchronous manner, it waits to
return until the deferred fires but it doesn't prevent other queued
calls from being executed. Send must be called first, which sets up
the chain/factory.
WARNING: If defer is set to True, must either call Receive
immediately after Send (ie. no intervening Sends) or pass
chain in as a paramter.
Parameters:
replytype -- TypeCode
KeyWord Parameters:
chain -- processing chain, optional
"""
chain = chain or self.chain
d = chain.flow.deferred
if self.trace:
def trace(soapdata):
print >>self.trace, "_" * 33, time.ctime(time.time()), "RESPONSE:"
print >>self.trace, soapdata
return soapdata
d.addCallback(trace)
chain.processResponse(d, replytype, **kw)
if self.defer:
return d
failure = []
append = failure.append
def errback(result):
"""Used with Response method to suppress 'Unhandled error in
Deferred' messages by adding an errback.
"""
append(result)
return None
d.addErrback(errback)
# spin reactor
while not d.called:
reactor.runUntilCurrent()
t2 = reactor.timeout()
t = reactor.running and t2
reactor.doIteration(t)
pyobj = d.result
if len(failure):
failure[0].raiseException()
return pyobj
def trace():
if trace:
print >>trace, "_" * 33, time.ctime(time.time()), "RESPONSE:"
for i in (self.reply_code, self.reply_msg,):
print >>trace, str(i)
print >>trace, "-------"
print >>trace, str(self.reply_headers)
print >>trace, self.data | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/twisted/client.py | client.py |
import sys, time, warnings
import sha, base64
# twisted & related imports
from zope.interface import classProvides, implements, Interface
from twisted.python import log, failure
from twisted.web.error import NoResource
from twisted.web.server import NOT_DONE_YET
from twisted.internet import reactor
import twisted.web.http
import twisted.web.resource
# ZSI imports
from ZSI import _get_element_nsuri_name, EvaluateException, ParseException
from ZSI.parse import ParsedSoap
from ZSI.writer import SoapWriter
from ZSI.TC import _get_global_element_declaration as GED
from ZSI import fault
from ZSI.wstools.Namespaces import OASIS, DSIG
from WSresource import DefaultHandlerChain, HandlerChainInterface,\
WSAddressCallbackHandler, DataHandler, WSAddressHandler
#
# Global Element Declarations
#
UsernameTokenDec = GED(OASIS.WSSE, "UsernameToken")
SecurityDec = GED(OASIS.WSSE, "Security")
SignatureDec = GED(DSIG.BASE, "Signature")
PasswordDec = GED(OASIS.WSSE, "Password")
NonceDec = GED(OASIS.WSSE, "Nonce")
CreatedDec = GED(OASIS.UTILITY, "Created")
if None in [UsernameTokenDec,SecurityDec,SignatureDec,PasswordDec,NonceDec,CreatedDec]:
raise ImportError, 'required global element(s) unavailable: %s ' %({
(OASIS.WSSE, "UsernameToken"):UsernameTokenDec,
(OASIS.WSSE, "Security"):SecurityDec,
(DSIG.BASE, "Signature"):SignatureDec,
(OASIS.WSSE, "Password"):PasswordDec,
(OASIS.WSSE, "Nonce"):NonceDec,
(OASIS.UTILITY, "Created"):CreatedDec,
})
#
# Stability: Unstable, Untested, Not Finished.
#
class WSSecurityHandler:
"""Web Services Security: SOAP Message Security 1.0
Class Variables:
debug -- If True provide more detailed SOAP:Fault information to clients.
"""
classProvides(HandlerChainInterface)
debug = True
@classmethod
def processRequest(cls, ps, **kw):
if type(ps) is not ParsedSoap:
raise TypeError,'Expecting ParsedSoap instance'
security = ps.ParseHeaderElements([cls.securityDec])
# Assume all security headers are supposed to be processed here.
for pyobj in security or []:
for any in pyobj.Any or []:
if any.typecode is UsernameTokenDec:
try:
ps = cls.UsernameTokenProfileHandler.processRequest(ps, any)
except Exception, ex:
if cls.debug: raise
raise RuntimeError, 'Unauthorized Username/passphrase combination'
continue
if any.typecode is SignatureDec:
try:
ps = cls.SignatureHandler.processRequest(ps, any)
except Exception, ex:
if cls.debug: raise
raise RuntimeError, 'Invalid Security Header'
continue
raise RuntimeError, 'WS-Security, Unsupported token %s' %str(any)
return ps
@classmethod
def processResponse(cls, output, **kw):
return output
class UsernameTokenProfileHandler:
"""Web Services Security UsernameToken Profile 1.0
Class Variables:
targetNamespace --
"""
classProvides(HandlerChainInterface)
# Class Variables
targetNamespace = OASIS.WSSE
sweepInterval = 60*5
nonces = None
# Set to None to disable
PasswordText = targetNamespace + "#PasswordText"
PasswordDigest = targetNamespace + "#PasswordDigest"
# Override passwordCallback
passwordCallback = lambda cls,username: None
@classmethod
def sweep(cls, index):
"""remove nonces every sweepInterval.
Parameters:
index -- remove all nonces up to this index.
"""
if cls.nonces is None:
cls.nonces = []
seconds = cls.sweepInterval
cls.nonces = cls.nonces[index:]
reactor.callLater(seconds, cls.sweep, len(cls.nonces))
@classmethod
def processRequest(cls, ps, token, **kw):
"""
Parameters:
ps -- ParsedSoap instance
token -- UsernameToken pyclass instance
"""
if token.typecode is not UsernameTokenDec:
raise TypeError, 'expecting GED (%s,%s) representation.' %(
UsernameTokenDec.nspname, UsernameTokenDec.pname)
username = token.Username
# expecting only one password
# may have a nonce and a created
password = nonce = timestamp = None
for any in token.Any or []:
if any.typecode is PasswordDec:
password = any
continue
if any.typecode is NonceTypeDec:
nonce = any
continue
if any.typecode is CreatedTypeDec:
timestamp = any
continue
raise TypeError, 'UsernameTokenProfileHander unexpected %s' %str(any)
if password is None:
raise RuntimeError, 'Unauthorized, no password'
# TODO: not yet supporting complexType simpleContent in pyclass_type
attrs = getattr(password, password.typecode.attrs_aname, {})
pwtype = attrs.get('Type', cls.PasswordText)
# Clear Text Passwords
if cls.PasswordText is not None and pwtype == cls.PasswordText:
if password == cls.passwordCallback(username):
return ps
raise RuntimeError, 'Unauthorized, clear text password failed'
if cls.nonces is None: cls.sweep(0)
if nonce is not None:
if nonce in cls.nonces:
raise RuntimeError, 'Invalid Nonce'
# created was 10 seconds ago or sooner
if created is not None and created < time.gmtime(time.time()-10):
raise RuntimeError, 'UsernameToken created is expired'
cls.nonces.append(nonce)
# PasswordDigest, recommended that implemenations
# require a Nonce and Created
if cls.PasswordDigest is not None and pwtype == cls.PasswordDigest:
digest = sha.sha()
for i in (nonce, created, cls.passwordCallback(username)):
if i is None: continue
digest.update(i)
if password == base64.encodestring(digest.digest()).strip():
return ps
raise RuntimeError, 'Unauthorized, digest failed'
raise RuntimeError, 'Unauthorized, contents of UsernameToken unknown'
@classmethod
def processResponse(cls, output, **kw):
return output
@staticmethod
def hmac_sha1(xml):
return
class SignatureHandler:
"""Web Services Security UsernameToken Profile 1.0
"""
digestMethods = {
DSIG.BASE+"#sha1":sha.sha,
}
signingMethods = {
DSIG.BASE+"#hmac-sha1":hmac_sha1,
}
canonicalizationMethods = {
DSIG.C14N_EXCL:lambda node: Canonicalize(node, unsuppressedPrefixes=[]),
DSIG.C14N:lambda node: Canonicalize(node),
}
@classmethod
def processRequest(cls, ps, signature, **kw):
"""
Parameters:
ps -- ParsedSoap instance
signature -- Signature pyclass instance
"""
if token.typecode is not SignatureDec:
raise TypeError, 'expecting GED (%s,%s) representation.' %(
SignatureDec.nspname, SignatureDec.pname)
si = signature.SignedInfo
si.CanonicalizationMethod
calgo = si.CanonicalizationMethod.get_attribute_Algorithm()
for any in si.CanonicalizationMethod.Any:
pass
# Check Digest
si.Reference
context = XPath.Context.Context(ps.dom, processContents={'wsu':OASIS.UTILITY})
exp = XPath.Compile('//*[@wsu:Id="%s"]' %si.Reference.get_attribute_URI())
nodes = exp.evaluate(context)
if len(nodes) != 1:
raise RuntimeError, 'A SignedInfo Reference must refer to one node %s.' %(
si.Reference.get_attribute_URI())
try:
xml = cls.canonicalizeMethods[calgo](nodes[0])
except IndexError:
raise RuntimeError, 'Unsupported canonicalization algorithm'
try:
digest = cls.digestMethods[salgo]
except IndexError:
raise RuntimeError, 'unknown digestMethods Algorithm'
digestValue = base64.encodestring(digest(xml).digest()).strip()
if si.Reference.DigestValue != digestValue:
raise RuntimeError, 'digest does not match'
if si.Reference.Transforms:
pass
signature.KeyInfo
signature.KeyInfo.KeyName
signature.KeyInfo.KeyValue
signature.KeyInfo.RetrievalMethod
signature.KeyInfo.X509Data
signature.KeyInfo.PGPData
signature.KeyInfo.SPKIData
signature.KeyInfo.MgmtData
signature.KeyInfo.Any
signature.Object
# TODO: Check Signature
signature.SignatureValue
si.SignatureMethod
salgo = si.SignatureMethod.get_attribute_Algorithm()
if si.SignatureMethod.HMACOutputLength:
pass
for any in si.SignatureMethod.Any:
pass
# <SignedInfo><Reference URI="">
exp = XPath.Compile('//child::*[attribute::URI = "%s"]/..' %(
si.Reference.get_attribute_URI()))
nodes = exp.evaluate(context)
if len(nodes) != 1:
raise RuntimeError, 'A SignedInfo Reference must refer to one node %s.' %(
si.Reference.get_attribute_URI())
try:
xml = cls.canonicalizeMethods[calgo](nodes[0])
except IndexError:
raise RuntimeError, 'Unsupported canonicalization algorithm'
# TODO: Check SignatureValue
@classmethod
def processResponse(cls, output, **kw):
return output
class X509TokenProfileHandler:
"""Web Services Security UsernameToken Profile 1.0
"""
targetNamespace = DSIG.BASE
# Token Types
singleCertificate = targetNamespace + "#X509v3"
certificatePath = targetNamespace + "#X509PKIPathv1"
setCerticatesCRLs = targetNamespace + "#PKCS7"
@classmethod
def processRequest(cls, ps, signature, **kw):
return ps
"""
<element name="KeyInfo" type="ds:KeyInfoType"/>
<complexType name="KeyInfoType" mixed="true">
<choice maxOccurs="unbounded">
<element ref="ds:KeyName"/>
<element ref="ds:KeyValue"/>
<element ref="ds:RetrievalMethod"/>
<element ref="ds:X509Data"/>
<element ref="ds:PGPData"/>
<element ref="ds:SPKIData"/>
<element ref="ds:MgmtData"/>
<any processContents="lax" namespace="##other"/>
<!-- (1,1) elements from (0,unbounded) namespaces -->
</choice>
<attribute name="Id" type="ID" use="optional"/>
</complexType>
<element name="Signature" type="ds:SignatureType"/>
<complexType name="SignatureType">
<sequence>
<element ref="ds:SignedInfo"/>
<element ref="ds:SignatureValue"/>
<element ref="ds:KeyInfo" minOccurs="0"/>
<element ref="ds:Object" minOccurs="0" maxOccurs="unbounded"/>
</sequence>
<attribute name="Id" type="ID" use="optional"/>
</complexType>
<element name="SignatureValue" type="ds:SignatureValueType"/>
<complexType name="SignatureValueType">
<simpleContent>
<extension base="base64Binary">
<attribute name="Id" type="ID" use="optional"/>
</extension>
</simpleContent>
</complexType>
<!-- Start SignedInfo -->
<element name="SignedInfo" type="ds:SignedInfoType"/>
<complexType name="SignedInfoType">
<sequence>
<element ref="ds:CanonicalizationMethod"/>
<element ref="ds:SignatureMethod"/>
<element ref="ds:Reference" maxOccurs="unbounded"/>
</sequence>
<attribute name="Id" type="ID" use="optional"/>
</complexType>
"""
class WSSecurityHandlerChainFactory:
protocol = DefaultHandlerChain
@classmethod
def newInstance(cls):
return cls.protocol(WSAddressCallbackHandler, DataHandler,
WSSecurityHandler, WSAddressHandler()) | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/twisted/WSsecurity.py | WSsecurity.py |
import sys, warnings
# twisted & related imports
from zope.interface import classProvides, implements, Interface
from twisted.python import log, failure
from twisted.web.error import NoResource
from twisted.web.server import NOT_DONE_YET
import twisted.web.http
import twisted.web.resource
# ZSI imports
from ZSI import _get_element_nsuri_name, EvaluateException, ParseException
from ZSI.parse import ParsedSoap
from ZSI.writer import SoapWriter
from ZSI import fault
# WS-Address related imports
from ZSI.address import Address
from ZSI.ServiceContainer import WSActionException
#
# Stability: Unstable
#
class HandlerChainInterface(Interface):
def processRequest(self, input, **kw):
"""returns a representation of the request, the
last link in the chain must return a response
pyobj with a typecode attribute.
Parameters:
input --
Keyword Parameters:
request -- HTTPRequest instance
resource -- Resource instance
"""
def processResponse(self, output, **kw):
"""returns a string representing the soap response.
Parameters
output --
Keyword Parameters:
request -- HTTPRequest instance
resource -- Resource instance
"""
class CallbackChainInterface(Interface):
def processRequest(self, input, **kw):
"""returns a response pyobj with a typecode
attribute.
Parameters:
input --
Keyword Parameters:
request -- HTTPRequest instance
resource -- Resource instance
"""
class DataHandler:
"""
class variables:
readerClass -- factory class to create reader for ParsedSoap instances.
writerClass -- ElementProxy implementation to use for SoapWriter instances.
"""
classProvides(HandlerChainInterface)
readerClass = None
writerClass = None
@classmethod
def processRequest(cls, input, **kw):
return ParsedSoap(input, readerclass=cls.readerClass)
@classmethod
def processResponse(cls, output, **kw):
sw = SoapWriter(outputclass=cls.writerClass)
sw.serialize(output)
return sw
class DefaultCallbackHandler:
classProvides(CallbackChainInterface)
@classmethod
def processRequest(cls, ps, **kw):
"""invokes callback that should return a (request,response) tuple.
representing the SOAP request and response respectively.
ps -- ParsedSoap instance representing HTTP Body.
request -- twisted.web.server.Request
"""
resource = kw['resource']
request = kw['request']
method = getattr(resource, 'soap_%s' %
_get_element_nsuri_name(ps.body_root)[-1])
try:
req_pyobj,rsp_pyobj = method(ps, request=request)
except TypeError, ex:
log.err(
'ERROR: service %s is broken, method MUST return request, response'\
% cls.__name__
)
raise
except Exception, ex:
log.err('failure when calling bound method')
raise
return rsp_pyobj
class WSAddressHandler:
"""General WS-Address handler. This implementation depends on a
'wsAction' dictionary in the service stub which contains keys to
WS-Action values.
Implementation saves state on request response flow, so using this
handle is not reliable if execution is deferred between proceesRequest
and processResponse.
TODO: sink this up with wsdl2dispatch
TODO: reduce coupling with WSAddressCallbackHandler.
"""
implements(HandlerChainInterface)
def processRequest(self, ps, **kw):
# TODO: Clean this up
resource = kw['resource']
d = getattr(resource, 'root', None)
key = _get_element_nsuri_name(ps.body_root)
if d is None or d.has_key(key) is False:
raise RuntimeError,\
'Error looking for key(%s) in root dictionary(%s)' %(key, str(d))
self.op_name = d[key]
self.address = address = Address()
address.parse(ps)
action = address.getAction()
if not action:
raise WSActionException('No WS-Action specified in Request')
request = kw['request']
http_headers = request.getAllHeaders()
soap_action = http_headers.get('soapaction')
if soap_action and soap_action.strip('\'"') != action:
raise WSActionException(\
'SOAP Action("%s") must match WS-Action("%s") if specified.'\
%(soap_action,action)
)
# Save WS-Address in ParsedSoap instance.
ps.address = address
return ps
def processResponse(self, sw, **kw):
if sw is None:
self.address = None
return
request, resource = kw['request'], kw['resource']
if isinstance(request, twisted.web.http.Request) is False:
raise TypeError, '%s instance expected' %http.Request
d = getattr(resource, 'wsAction', None)
key = self.op_name
if d is None or d.has_key(key) is False:
raise WSActionNotSpecified,\
'Error looking for key(%s) in wsAction dictionary(%s)' %(key, str(d))
addressRsp = Address(action=d[key])
if request.transport.TLS == 0:
addressRsp.setResponseFromWSAddress(\
self.address, 'http://%s:%d%s' %(
request.host.host, request.host.port, request.path)
)
else:
addressRsp.setResponseFromWSAddress(\
self.address, 'https://%s:%d%s' %(
request.host.host, request.host.port, request.path)
)
addressRsp.serialize(sw, typed=False)
self.address = None
return sw
class WSAddressCallbackHandler:
classProvides(CallbackChainInterface)
@classmethod
def processRequest(cls, ps, **kw):
"""invokes callback that should return a (request,response) tuple.
representing the SOAP request and response respectively.
ps -- ParsedSoap instance representing HTTP Body.
request -- twisted.web.server.Request
"""
resource = kw['resource']
request = kw['request']
method = getattr(resource, 'wsa_%s' %
_get_element_nsuri_name(ps.body_root)[-1])
# TODO: grab ps.address, clean this up.
try:
req_pyobj,rsp_pyobj = method(ps, ps.address, request=request)
except TypeError, ex:
log.err(
'ERROR: service %s is broken, method MUST return request, response'\
%self.__class__.__name__
)
raise
except Exception, ex:
log.err('failure when calling bound method')
raise
return rsp_pyobj
def CheckInputArgs(*interfaces):
"""Must provide at least one interface, the last one may be repeated.
"""
l = len(interfaces)
def wrapper(func):
def check_args(self, *args, **kw):
for i in range(len(args)):
if (l > i and interfaces[i].providedBy(args[i])) or interfaces[-1].providedBy(args[i]):
continue
if l > i: raise TypeError, 'arg %s does not implement %s' %(args[i], interfaces[i])
raise TypeError, 'arg %s does not implement %s' %(args[i], interfaces[-1])
func(self, *args, **kw)
return check_args
return wrapper
class DefaultHandlerChain:
@CheckInputArgs(CallbackChainInterface, HandlerChainInterface)
def __init__(self, cb, *handlers):
self.handlercb = cb
self.handlers = handlers
self.debug = len(log.theLogPublisher.observers) > 0
def processRequest(self, arg, **kw):
if self.debug:
log.msg('--->PROCESS REQUEST\n%s' %arg, debug=1)
for h in self.handlers:
arg = h.processRequest(arg, **kw)
return self.handlercb.processRequest(arg, **kw)
def processResponse(self, arg, **kw):
if self.debug:
log.msg('===>PROCESS RESPONSE: %s' %str(arg), debug=1)
if arg is None:
return
for h in self.handlers:
arg = h.processResponse(arg, **kw)
s = str(arg)
if self.debug:
log.msg(s, debug=1)
return s
class DefaultHandlerChainFactory:
protocol = DefaultHandlerChain
@classmethod
def newInstance(cls):
return cls.protocol(DefaultCallbackHandler, DataHandler)
class WSAddressHandlerChainFactory:
protocol = DefaultHandlerChain
@classmethod
def newInstance(cls):
return cls.protocol(WSAddressCallbackHandler, DataHandler,
WSAddressHandler())
class WSResource(twisted.web.resource.Resource, object):
"""
class variables:
encoding --
factory -- hander chain, which has a factory method "newInstance"
that returns a
"""
encoding = "UTF-8"
factory = DefaultHandlerChainFactory
def __init__(self):
"""
"""
twisted.web.resource.Resource.__init__(self)
def _writeResponse(self, request, response, status=200):
"""
request -- request message
response --- response message
status -- HTTP Status
"""
request.setResponseCode(status)
if self.encoding is not None:
mimeType = 'text/xml; charset="%s"' % self.encoding
else:
mimeType = "text/xml"
request.setHeader("Content-type", mimeType)
request.setHeader("Content-length", str(len(response)))
request.write(response)
request.finish()
return NOT_DONE_YET
def _writeFault(self, request, ex):
"""
request -- request message
ex -- Exception
"""
response = None
response = fault.FaultFromException(ex, False, sys.exc_info()[2]).AsSOAP()
log.err('SOAP FAULT: %s' % response)
return self._writeResponse(request, response, status=500)
def render_POST(self, request):
"""Dispatch Method called by twisted render, creates a
request/response handler chain.
request -- twisted.web.server.Request
"""
chain = self.factory.newInstance()
data = request.content.read()
try:
pyobj = chain.processRequest(data, request=request, resource=self)
except Exception, ex:
return self._writeFault(request, ex)
try:
soap = chain.processResponse(pyobj, request=request, resource=self)
except Exception, ex:
return self._writeFault(request, ex)
if soap is not None:
return self._writeResponse(request, soap)
request.finish()
return NOT_DONE_YET | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/twisted/WSresource.py | WSresource.py |
import getopt, socket, sys
from cpackets import testlist
try:
(opts, args) = getopt.getopt(sys.argv[1:],
'h:lp:qst:w',
( 'host=', 'list', 'port=',
'quit', 'statusonly', 'test=', 'wsdl', 'help'))
except getopt.GetoptError, e:
print >>sys.stderr, sys.argv[0] + ': ' + str(e)
sys.exit(1)
if args:
print sys.argv[0] + ': Usage error; try --help.'
sys.exit(1)
hostname, portnum, tests, quitting, getwsdl, verbose = \
'localhost', 1122, [0,1], 0, 0, 1
for opt, val in opts:
if opt in [ '--help' ]:
print '''Options include:
--host HOST (-h HOST) Name of server host
--port PORT (-p PORT) Port server is listening on
--quit (-q) Send server a QUIT command
--testnum 1,2,3 (-t ...) Run comma-separated tests; use * or all for all
--list (-l) List tests (brief description)
--statusonly (-s) Do not output reply packets; just status code
--wsdl (-w) Get the WSDL file
Default is -h%s -p%d -t%s''' % \
(hostname, portnum, ','.join([str(x) for x in tests]))
sys.exit(0)
if opt in [ '-h', '--host' ]:
hostname = val
elif opt in [ '-p', '--port' ]:
portnum = int(val)
elif opt in [ '-s', '--statusonly' ]:
verbose = 0
elif opt in [ '-q', '--quit' ]:
quitting = 1
elif opt in [ '-t', '--testnum' ]:
if val in [ '*', 'all' ]:
tests = range(len(testlist))
else:
tests = [ int(t) for t in val.split(',') ]
elif opt in [ '-l', '--list' ]:
for i in range(len(testlist)):
print i, testlist[i][0]
sys.exit(0)
elif opt in [ '-w', '--wsdl' ]:
getwsdl = 1
if quitting:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((hostname, portnum))
except socket.error, e:
if e.args[1] == 'Connection refused': sys.exit(0)
raise
f = s.makefile('r+')
f.write('QUIT / HTTP/1.0\r\n')
f.flush()
sys.exit(0)
if getwsdl:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((hostname, portnum))
f = s.makefile('r+')
f.write('GET /wsdl HTTP/1.0\r\n\r\n')
f.flush()
status = f.readline()
print status,
while 1:
l = f.readline()
if l == '': break
print l,
sys.exit(0)
for T in tests:
descr, IN, header = testlist[T]
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((hostname, portnum))
f = s.makefile('r+')
print '-' * 60, '\n\n\n', T, descr
f.write('POST / HTTP/1.0\r\n')
f.write('SOAPAction: "http://soapinterop.org/"\r\n')
if header == None:
f.write('Content-type: text/xml; charset="utf-8"\r\n')
f.write('Content-Length: %d\r\n\r\n' % len(IN))
else:
f.write(header)
f.write(IN)
f.flush()
status = f.readline()
print status,
while 1:
l = f.readline()
if l == '': break
if verbose: print l,
f.close() | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/interop/client.py | client.py |
WSDL_DEFINITION = '''<?xml version="1.0"?>
<definitions name="InteropTest"
targetNamespace="http://soapinterop.org/"
xmlns="http://schemas.xmlsoap.org/wsdl/"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://soapinterop.org/">
<import
location="http://www.whitemesa.com/interop/InteropTest.wsdl"
namespace="http://soapinterop.org/xsd"/>
<import
location="http://www.whitemesa.com/interop/InteropTest.wsdl"
namespace="http://soapinterop.org/"/>
<import
location="http://www.whitemesa.com/interop/InteropTestB.wsdl"
namespace="http://soapinterop.org/"/>
<import
location="http://www.whitemesa.com/interop/echoHeaderBindings.wsdl"
namespace="http://soapinterop.org/"/>
<import
location="http://www.whitemesa.com/interop/InteropTestMap.wsdl"
namespace="http://soapinterop.org/"/>
<!-- DOCSTYLE; soon.
<import
location="http://www.whitemesa.com/interop/interopdoc.wsdl"
namespace="http://soapinterop.org/"/>
-->
<service name="interop">
<port name="TestSoap" binding="tns:InteropTestSoapBinding">
<soap:address location=">>>URL<<<"/>
</port>
<port name="TestSoapB" binding="tns:InteropTestSoapBindingB">
<soap:address location=">>>URL<<<"/>
</port>
<port name="EchoHeaderString" binding="tns:InteropEchoHeaderStringBinding">
<soap:address location=">>>URL<<<"/>
</port>
<port name="EchoHeaderStruct" binding="tns:InteropEchoHeaderStructBinding">
<soap:address location=">>>URL<<<"/>
</port>
<port name="TestSoapMap" binding="tns:InteropTestSoapBindingMap">
<soap:address location=">>>URL<<<"/>
</port>
<!-- DOCSTYLE; soon.
<port name="TestDoc" binding="tns:doc_test_binding">
<soap:address location=">>>URL<<<"/>
</port>
-->
</service>
</definitions>
'''
from ZSI import *
from ZSI import _copyright, _seqtypes
import types
class SOAPStruct:
def __init__(self, name):
pass
def __str__(self):
return str(self.__dict__)
class TC_SOAPStruct(TC.Struct):
def __init__(self, pname=None, **kw):
TC.Struct.__init__(self, SOAPStruct, [
TC.String('varString', strip=0, inline=1),
TC.Iint('varInt'),
TC.FPfloat('varFloat', format='%.18g'),
], pname, **kw)
class TC_SOAPStructStruct(TC.Struct):
def __init__(self, pname=None, **kw):
TC.Struct.__init__(self, SOAPStruct, [
TC.String('varString', strip=0),
TC.Iint('varInt'),
TC.FPfloat('varFloat', format='%.18g'),
TC_SOAPStruct('varStruct'),
], pname, **kw)
class TC_SOAPArrayStruct(TC.Struct):
def __init__(self, pname=None, **kw):
TC.Struct.__init__(self, SOAPStruct, [
TC.String('varString', strip=0),
TC.Iint('varInt'),
TC.FPfloat('varFloat', format='%.18g'),
TC.Array('xsd:string', TC.String(string=0), 'varArray'),
], pname, **kw)
class TC_ArrayOfstring(TC.Array):
def __init__(self, pname=None, **kw):
TC.Array.__init__(self, 'xsd:string', TC.String(string=0), pname, **kw)
class TC_ArrayOfint(TC.Array):
def __init__(self, pname=None, **kw):
TC.Array.__init__(self, 'xsd:int', TC.Iint(), pname, **kw)
class TC_ArrayOffloat(TC.Array):
def __init__(self, pname=None, **kw):
TC.Array.__init__(self, 'xsd:float', TC.FPfloat(format='%.18g'),
pname, **kw)
class TC_ArrayOfSOAPStruct(TC.Array):
def __init__(self, pname=None, **kw):
TC.Array.__init__(self, 'Za:SOAPStruct', TC_SOAPStruct(), pname, **kw)
#class TC_ArrayOfstring2D(TC.Array):
# def __init__(self, pname=None, **kw):
# TC.Array.__init__(self, 'xsd:string', TC.String(string=0), pname, **kw)
class RPCParameters:
def __init__(self, name):
pass
def __str__(self):
t = str(self.__dict__)
if hasattr(self, 'inputStruct'):
t += '\ninputStruct\n'
t += str(self.inputStruct)
if hasattr(self, 'inputStructArray'):
t += '\ninputStructArray\n'
t += str(self.inputStructArray)
return t
def frominput(self, arg):
self.v = s = SOAPStruct(None)
self.v.varString = arg.inputString
self.v.varInt = arg.inputInteger
self.v.varFloat = arg.inputFloat
return self
class Operation:
dispatch = {}
SOAPAction = '''"http://soapinterop.org/"'''
ns = "http://soapinterop.org/"
hdr_ns = "http://soapinterop.org/echoheader/"
def __init__(self, name, tcin, tcout, **kw):
self.name = name
if type(tcin) not in _seqtypes: tcin = tcin,
self.TCin = TC.Struct(RPCParameters, tuple(tcin), name)
if type(tcout) not in _seqtypes: tcout = tcout,
self.TCout = TC.Struct(RPCParameters, tuple(tcout), name + 'Response')
self.convert = kw.get('convert', None)
self.headers = kw.get('headers', [])
self.nsdict = kw.get('nsdict', {})
Operation.dispatch[name] = self
Operation("echoString",
TC.String('inputString', strip=0),
TC.String('inputString', oname='return', strip=0)
)
Operation("echoStringArray",
TC_ArrayOfstring('inputStringArray'),
TC_ArrayOfstring('inputStringArray', oname='return')
)
Operation("echoInteger",
TC.Iint('inputInteger'),
TC.Iint('inputInteger', oname='return'),
)
Operation("echoIntegerArray",
TC_ArrayOfint('inputIntegerArray'),
TC_ArrayOfint('inputIntegerArray', oname='return'),
)
Operation("echoFloat",
TC.FPfloat('inputFloat', format='%.18g'),
TC.FPfloat('inputFloat', format='%.18g', oname='return'),
)
Operation("echoFloatArray",
TC_ArrayOffloat('inputFloatArray'),
TC_ArrayOffloat('inputFloatArray', oname='return'),
)
Operation("echoStruct",
TC_SOAPStruct('inputStruct'),
TC_SOAPStruct('inputStruct', oname='return'),
)
Operation("echoStructArray",
TC_ArrayOfSOAPStruct('inputStructArray'),
TC_ArrayOfSOAPStruct('inputStructArray', oname='return'),
nsdict={'Za': 'http://soapinterop.org/xsd'}
)
Operation("echoVoid",
[],
[],
headers=( ( Operation.hdr_ns, 'echoMeStringRequest' ),
( Operation.hdr_ns, 'echoMeStructRequest' ) )
)
Operation("echoBase64",
TC.Base64String('inputBase64'),
TC.Base64String('inputBase64', oname='return'),
)
Operation("echoDate",
TC.gDateTime('inputDate'),
TC.gDateTime('inputDate', oname='return'),
)
Operation("echoHexBinary",
TC.HexBinaryString('inputHexBinary'),
TC.HexBinaryString('inputHexBinary', oname='return'),
)
Operation("echoDecimal",
TC.Decimal('inputDecimal'),
TC.Decimal('inputDecimal', oname='return'),
)
Operation("echoBoolean",
TC.Boolean('inputBoolean'),
TC.Boolean('inputBoolean', oname='return'),
)
Operation("echoStructAsSimpleTypes",
TC_SOAPStruct('inputStruct'),
( TC.String('outputString', strip=0), TC.Iint('outputInteger'),
TC.FPfloat('outputFloat', format='%.18g') ),
convert=lambda s: (s.v.varString, s.v.varInt, s.v.varFloat),
)
Operation("echoSimpleTypesAsStruct",
( TC.String('inputString', strip=0), TC.Iint('inputInteger'),
TC.FPfloat('inputFloat') ),
TC_SOAPStruct('v', opname='return'),
convert=lambda arg: RPCParameters(None).frominput(arg),
)
#Operation("echo2DStringArray",
# TC_ArrayOfstring2D('input2DStringArray'),
# TC_ArrayOfstring2D('return')
#),
Operation("echoNestedStruct",
TC_SOAPStructStruct('inputStruct'),
TC_SOAPStructStruct('inputStruct', oname='return'),
)
Operation("echoNestedArray",
TC_SOAPArrayStruct('inputStruct'),
TC_SOAPArrayStruct('inputStruct', oname='return'),
) | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/interop/sclasses.py | sclasses.py |
pocketsoap_struct_test = '''<SOAP-ENV:Envelope
xmlns="http://www.example.com/schemas/TEST"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:ZSI="http://www.zolera.com/schemas/ZSI/"
xmlns:ps42='http://soapinterop.org/xsd'
xmlns:xsd='http://www.w3.org/1999/XMLSchema'
xmlns:xsi='http://www.w3.org/1999/XMLSchema-instance'>
<SOAP-ENV:Header>
<ww:echoMeStringRequest xmlns:ww="http://soapinterop.org/echoheader/">
Please release <me</ww:echoMeStringRequest>
</SOAP-ENV:Header>
<SOAP-ENV:Body>
<m:echoStruct xmlns:m='http://soapinterop.org/'>
<inputStruct xsi:type='ps42:SOAPStruct'>
<varInt xsi:type='xsd:int'>1073741824</varInt>
<varFloat xsi:type='xsd:float'>-42.24</varFloat>
<varString xsi:type='xsd:string'>pocketSOAP
rocks!<g></varString>
</inputStruct>
</m:echoStruct>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>'''
phalanx_b64_test = '''<SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:m='http://soapinterop.org/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:SOAP-ENC='http://schemas.xmlsoap.org/soap/encoding/' xmlns:xsd='http://www.w3.org/2001/XMLSchema' SOAP-ENV:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'>
<SOAP-ENV:Body>
<m:echoBase64>
<inputBase64 xsi:type='xsd:base64Binary'>Ty4rY6==</inputBase64>
</m:echoBase64>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>'''
hexbin_test = '''<SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:m='http://soapinterop.org/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:SOAP-ENC='http://schemas.xmlsoap.org/soap/encoding/' xmlns:xsd='http://www.w3.org/2001/XMLSchema' SOAP-ENV:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'>
<SOAP-ENV:Body>
<m:echoHexBinary>
<inputHexBinary xsi:type='xsd:hexBinary'>656174206d792073686f72747321</inputHexBinary>
</m:echoHexBinary>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>'''
phalanx_badhref_test = '''<SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:ns1='http://soapinterop.org/xsd' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:ns='http://soapinterop.org/' xmlns:SOAP-ENC='http://schemas.xmlsoap.org/soap/encoding/' SOAP-ENV:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'>
<SOAP-ENV:Body>
<ns:echoStructArray>
<inputStructArray xsi:type='SOAP-ENC:Array' SOAP-ENC:arrayType='ns1:SOAPStruct[3]'>
<item xsi:type='ns1:SOAPStruct' href='#2'>invalid value</item>
<item xsi:type='ns1:SOAPStruct'>
<varFloat xsi:type='xsd:float'>21.02</varFloat>
<varString xsi:type='xsd:string'>c</varString>
<varInt xsi:type='xsd:int'>3</varInt>
</item>
<item xsi:type='ns1:SOAPStruct' href='#1'/>
</inputStructArray>
</ns:echoStructArray>
<mrA xsi:type='ns1:SOAPStruct' id='1'>
<varInt xsi:type='xsd:int'>-33</varInt>
<varFloat xsi:type='xsd:float'>33.33</varFloat>
<varString xsi:type='xsd:string'>test 1</varString>
</mrA>
<mrB xsi:type='ns1:SOAPStruct' id='2'>
<varFloat xsi:type='xsd:float'>11.11</varFloat>
<varString xsi:type='xsd:string'>test 2</varString>
<varInt xsi:type='xsd:int'>-11</varInt>
</mrB>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>'''
someones_b64_test = '''<S:Envelope
S:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'
xmlns:S='http://schemas.xmlsoap.org/soap/envelope/'
xmlns:E='http://schemas.xmlsoap.org/soap/encoding/'
xmlns:a='http://soapinterop.org/'
xmlns:b='http://www.w3.org/2001/XMLSchema-instance'>
<S:Body>
<a:echoBase64><inputBase64
b:type='E:base64'>AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T1</inputBase64>
</a:echoBase64>
</S:Body></S:Envelope>'''
phalanx_void_test = '''<SOAP-ENV:Envelope
xmlns="http://www.example.com/schemas/TEST"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:ZSI="http://www.zolera.com/schemas/ZSI/"
xmlns:ps42='http://soapinterop.org/xsd'
xmlns:xsd='http://www.w3.org/1999/XMLSchema'
xmlns:xsi='http://www.w3.org/1999/XMLSchema-instance'>
<SOAP-ENV:Header>
<ww:echoMeStringRequest SOAP-ENV:mustUnderstand="1" xmlns:ww="http://soapinterop.org/echoheader/">
Please release me</ww:echoMeStringRequest>
<ww:echoMeStructRequest xmlns:ww="http://soapinterop.org/echoheader/">
<varInt>111</varInt>
<varFloat>-42.24</varFloat>
<varString>Header text string.</varString>
</ww:echoMeStructRequest>
</SOAP-ENV:Header>
<SOAP-ENV:Body>
<m:echoVoid xmlns:m='http://soapinterop.org/'/>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>'''
multipart_test = '''
Ignore this
--sep
Content-Type: text/xml
<SOAP-ENV:Envelope
xmlns="http://www.example.com/schemas/TEST"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:ZSI="http://www.zolera.com/schemas/ZSI/"
xmlns:ps42='http://soapinterop.org/xsd'
xmlns:xsd='http://www.w3.org/1999/XMLSchema'
xmlns:xsi='http://www.w3.org/1999/XMLSchema-instance'>
<SOAP-ENV:Body>
<m:echoStruct xmlns:m='http://soapinterop.org/'>
<inputStruct xsi:type='ps42:SOAPStruct'>
<varInt xsi:type='xsd:int'>1073741824</varInt>
<varFloat xsi:type='xsd:float'>-42.24</varFloat>
<varString xsi:type='xsd:string' href="cid:123@456"/>
</inputStruct>
</m:echoStruct>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
--sep
Content-ID: otherwise
yehll
--sep
Content-ID: 123@456
this is a very long string
it is separated over several lines.
hwlleasdfasdf
asdfad
--sep--
'''
phalanx_badstructtype_test = '''<SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:ns1='http://soapinterop.org/xsd' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:m='http://soapinterop.org/' xmlns:SOAP-ENC='http://schemas.xmlsoap.org/soap/encoding/' SOAP-ENV:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'>
<SOAP-ENV:Body>
<m:echoStruct>
<inputStruct xsi:type='ns1:roastbeef'>
<varString xsi:type='xsd:string'>easy test</varString>
<varInt xsi:type='xsd:int'>11</varInt>
<varFloat xsi:type='xsd:float'>22.33</varFloat>
</inputStruct>
</m:echoStruct>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>'''
phalanx_int_href_test = '''<SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:m='http://soapinterop.org/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:SOAP-ENC='http://schemas.xmlsoap.org/soap/encoding/' xmlns:xsd='http://www.w3.org/2001/XMLSchema' SOAP-ENV:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'>
<SOAP-ENV:Body>
<m:echoInteger>
<inputInteger href='#a1'/>
</m:echoInteger>
<multiref xsi:type='xsd:int' id='a1'>13</multiref>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
'''
wm_simple_as_struct_test = '''<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SOAP-ENV:Body>
<m:echoSimpleTypesAsStruct xmlns:m="http://soapinterop.org/">
<inputString>White Mesa Test</inputString>
<inputInteger>42</inputInteger>
<inputFloat>0.0999</inputFloat>
</m:echoSimpleTypesAsStruct>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
'''
apache_float_test = '''<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SOAP-ENV:Body>
<ns1:echoFloat xmlns:ns1="http://soapinterop.org/">
<inputFloat xsi:type="xsd:float">3.7</inputFloat>
</ns1:echoFloat>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>'''
testlist = (
( 'struct test', pocketsoap_struct_test, None),
( 'base64 test', phalanx_b64_test, None),
( 'hexBinary', hexbin_test, None),
( 'big base64 test', someones_b64_test, None),
( 'echovoid', phalanx_void_test, None),
( 'simple2struct', wm_simple_as_struct_test, None),
( 'multipart', multipart_test,
'Content-type: multipart/related; boundary="sep"\r\n' ),
( 'int href test', phalanx_int_href_test, None),
( 'apache float', apache_float_test, None),
( 'bad href test', phalanx_badhref_test, None),
( 'bad type attr on struct', phalanx_badstructtype_test, None),
) | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/interop/cpackets.py | cpackets.py |
from ZSI import *
from ZSI import _copyright, resolvers, _child_elements, _textprotect
import sys, time, cStringIO as StringIO
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from sclasses import Operation, WSDL_DEFINITION, TC_SOAPStruct
class InteropRequestHandler(BaseHTTPRequestHandler):
server_version = 'ZSI/1.2 OS390/VM5.4 ' + BaseHTTPRequestHandler.server_version
def send_xml(self, text, code=200):
'''Send some XML.'''
self.send_response(code)
self.send_header('Content-type', 'text/xml; charset="utf-8"')
self.send_header('Content-Length', str(len(text)))
self.end_headers()
self.wfile.write(text)
self.trace(text, 'SENT')
self.wfile.flush()
def send_fault(self, f):
'''Send a fault.'''
self.send_xml(f.AsSOAP(), 500)
def trace(self, text, what):
'''Log a debug/trace message.'''
F = self.server.tracefile
if not F: return
print >>F, '=' * 60, '\n%s %s %s %s:' % \
(what, self.client_address, self.path, time.ctime(time.time()))
print >>F, text
print >>F, '=' * 60, '\n'
F.flush()
def do_QUIT(self):
'''Quit.'''
self.server.quitting = 1
self.log_message('Got QUIT command')
sys.stderr.flush()
raise SystemExit
def do_GET(self):
'''The GET command. Always returns the WSDL.'''
self.send_xml(WSDL_DEFINITION.replace('>>>URL<<<', self.server.url))
def do_POST(self):
'''The POST command.'''
try:
# SOAPAction header.
action = self.headers.get('soapaction', None)
if not action:
self.send_fault(Fault(Fault.Client,
'SOAPAction HTTP header missing.'))
return
if action != Operation.SOAPAction:
self.send_fault(Fault(Fault.Client,
'SOAPAction is "%s" not "%s"' % \
(action, Operation.SOAPAction)))
return
# Parse the message.
ct = self.headers['content-type']
if ct.startswith('multipart/'):
cid = resolvers.MIMEResolver(ct, self.rfile)
xml = cid.GetSOAPPart()
ps = ParsedSoap(xml, resolver=cid.Resolve)
else:
cl = int(self.headers['content-length'])
IN = self.rfile.read(cl)
self.trace(IN, 'RECEIVED')
ps = ParsedSoap(IN)
except ParseException, e:
self.send_fault(FaultFromZSIException(e))
return
except Exception, e:
# Faulted while processing; assume it's in the header.
self.send_fault(FaultFromException(e, 1, sys.exc_info()[2]))
return
try:
# Actors?
a = ps.WhatActorsArePresent()
if len(a):
self.send_fault(FaultFromActor(a[0]))
return
# Is the operation defined?
root = ps.body_root
if root.namespaceURI != Operation.ns:
self.send_fault(Fault(Fault.Client,
'Incorrect namespace "%s"' % root.namespaceURI))
return
n = root.localName
op = Operation.dispatch.get(n, None)
if not op:
self.send_fault(Fault(Fault.Client,
'Undefined operation "%s"' % n))
return
# Scan headers. First, see if we understand all headers with
# mustUnderstand set. Then, get the ones intended for us (ignoring
# others since step 1 insured they're not mustUnderstand).
for mu in ps.WhatMustIUnderstand():
if mu not in op.headers:
uri, localname = mu
self.send_fault(FaultFromNotUnderstood(uri, localname))
return
headers = [ e for e in ps.GetMyHeaderElements()
if (e.namespaceURI, e.localName) in op.headers ]
nsdict={ 'Z': Operation.ns }
if headers:
nsdict['E'] = Operation.hdr_ns
self.process_headers(headers, ps)
else:
self.headertext = None
try:
results = op.TCin.parse(ps.body_root, ps)
except ParseException, e:
self.send_fault(FaultFromZSIException(e))
self.trace(str(results), 'PARSED')
if op.convert:
results = op.convert(results)
if op.nsdict: nsdict.update(op.nsdict)
reply = StringIO.StringIO()
sw = SoapWriter(reply, nsdict=nsdict, header=self.headertext)
sw.serialize(results, op.TCout,
name = 'Z:' + n + 'Response', inline=1)
sw.close()
self.send_xml(reply.getvalue())
except Exception, e:
# Fault while processing; now it's in the body.
self.send_fault(FaultFromException(e, 0, sys.exc_info()[2]))
return
def process_headers(self, headers, ps):
'''Process headers, set self.headertext to be what to output.
'''
self.headertext = ''
for h in headers:
if h.localName == 'echoMeStringRequest':
s = TC.String().parse(h, ps)
self.headertext += \
'<E:echoMeStringResponse>%s</E:echoMeStringResponse>\n' % _textprotect(s)
elif h.localName == 'echoMeStructRequest':
tc = TC_SOAPStruct('echoMeStructRequest', inline=1)
data = tc.parse(h, ps)
s = StringIO.StringIO()
sw = SoapWriter(s, envelope=0)
tc.serialize(sw, data, name='E:echoMeStructResponse')
sw.close()
self.headertext += s.getvalue()
else:
raise TypeError('Unhandled header ' + h.nodeName)
pass
class InteropHTTPServer(HTTPServer):
def __init__(self, me, url, **kw):
HTTPServer.__init__(self, me, InteropRequestHandler)
self.quitting = 0
self.tracefile = kw.get('tracefile', None)
self.url = url
def handle_error(self, req, client_address):
if self.quitting: sys.exit(0)
HTTPServer.handle_error(self, req, client_address)
import getopt
try:
(opts, args) = getopt.getopt(sys.argv[1:], 'l:p:t:u:',
('log=', 'port=', 'tracefile=', 'url=') )
except getopt.GetoptError, e:
print >>sys.stderr, sys.argv[0] + ': ' + str(e)
sys.exit(1)
if args:
print >>sys.stderr, sys.argv[0] + ': Usage error.'
sys.exit(1)
portnum = 1122
tracefile = None
url = None
for opt, val in opts:
if opt in [ '-l', '--logfile' ]:
sys.stderr = open(val, 'a')
elif opt in [ '-p', '--port' ]:
portnum = int(val)
elif opt in [ '-t', '--tracefile' ]:
if val == '-':
tracefile = sys.stdout
else:
tracefile = open(val, 'a')
elif opt in [ '-u', '--url' ]:
url = val
ME = ( '', portnum )
if not url:
import socket
url = 'http://' + socket.getfqdn()
if portnum != 80: url += ':%d' % portnum
url += '/interop.wsdl'
try:
InteropHTTPServer(ME, url, tracefile=tracefile).serve_forever()
except SystemExit:
pass
sys.exit(0) | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/interop/server.py | server.py |
import getopt, socket, sys
try:
(opts, args) = getopt.getopt(sys.argv[1:],
'h:p:s',
( 'host=', 'port=',
'statusonly', 'help'))
except getopt.GetoptError, e:
print >>sys.stderr, sys.argv[0] + ': ' + str(e)
sys.exit(1)
if args:
print sys.argv[0] + ': Usage error; try --help.'
sys.exit(1)
hostname, portnum, verbose = 'localhost', 80, 1
for opt, val in opts:
if opt in [ '--help' ]:
print '''Options include:
--host HOST (-h HOST) Name of server host
--port PORT (-p PORT) Port server is listening on
--statusonly (-s) Do not output reply packets; just status code
Default is -h%s -p%d -t%s''' % \
(hostname, portnum, ','.join([str(x) for x in tests]))
sys.exit(0)
if opt in [ '-h', '--host' ]:
hostname = val
elif opt in [ '-p', '--port' ]:
portnum = int(val)
elif opt in [ '-s', '--statusonly' ]:
verbose = 0
IN = '''<SOAP-ENV:Envelope
xmlns="http://www.example.com/schemas/TEST"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<hello/>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
'''
IN = '''<SOAP-ENV:Envelope
xmlns="http://www.example.com/schemas/TEST"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<echo>
<SOAP-ENC:int>1</SOAP-ENC:int>
<SOAP-ENC:int>2</SOAP-ENC:int>
</echo>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
'''
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((hostname, portnum))
f = s.makefile('r+')
f.write('POST /cgi-bin/x HTTP/1.0\r\n')
f.write('Content-type: text/xml; charset="utf-8"\r\n')
f.write('Content-Length: %d\r\n\r\n' % len(IN))
f.write(IN)
f.flush()
status = f.readline()
print status,
while 1:
l = f.readline()
if l == '': break
if verbose: print l,
f.close() | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/test/cgicli.py | cgicli.py |
from compiler.ast import Module
import StringIO, copy, getopt
import os, sys, unittest, urlparse, signal, time, warnings, subprocess
from ConfigParser import ConfigParser, NoSectionError, NoOptionError
from ZSI.wstools.TimeoutSocket import TimeoutError
"""Global Variables:
CONFIG_FILE -- configuration file
CONFIG_PARSER -- ConfigParser instance
DOCUMENT -- test section variable, specifying document style.
LITERAL -- test section variable, specifying literal encodings.
BROKE -- test section variable, specifying broken test.
TESTS -- test section variable, whitespace separated list of modules.
SECTION_CONFIGURATION -- configuration section, turn on/off debuggging.
TRACEFILE -- file class instance.
TOPDIR -- current working directory
MODULEDIR -- stubs directory
PORT -- port of local container
HOST -- address of local container
SECTION_SERVERS -- services to be tested, values are paths to executables.
"""
CONFIG_FILE = 'config.txt'
CONFIG_PARSER = ConfigParser()
DOCUMENT = 'document'
LITERAL = 'literal'
BROKE = 'broke'
TESTS = 'tests'
SECTION_CONFIGURATION = 'configuration'
SECTION_DISPATCH = 'dispatch'
TRACEFILE = sys.stdout
TOPDIR = os.getcwd()
MODULEDIR = TOPDIR + '/stubs'
SECTION_SERVERS = 'servers'
CONFIG_PARSER.read(CONFIG_FILE)
DEBUG = CONFIG_PARSER.getboolean(SECTION_CONFIGURATION, 'debug')
SKIP = CONFIG_PARSER.getboolean(SECTION_CONFIGURATION, 'skip')
TWISTED = CONFIG_PARSER.getboolean(SECTION_CONFIGURATION, 'twisted')
LAZY = CONFIG_PARSER.getboolean(SECTION_CONFIGURATION, 'lazy')
OUTPUT = CONFIG_PARSER.get(SECTION_CONFIGURATION, 'output') or sys.stdout
if DEBUG:
from ZSI.wstools.logging import setBasicLoggerDEBUG
setBasicLoggerDEBUG()
sys.path.append('%s/%s' %(os.getcwd(), 'stubs'))
ENVIRON = copy.copy(os.environ)
ENVIRON['PYTHONPATH'] = ENVIRON.get('PYTHONPATH', '') + ':' + MODULEDIR
def _SimpleMain():
"""Gets tests to run from configuration file.
"""
unittest.TestProgram(defaultTest="all")
main = _SimpleMain
def _TwistedMain():
"""Gets tests to run from configuration file.
"""
from twisted.internet import reactor
reactor.callWhenRunning(_TwistedTestProgram, defaultTest="all")
reactor.run(installSignalHandlers=0)
if TWISTED: main = _TwistedMain
def _LaunchContainer(cmd):
'''
Parameters:
cmd -- executable, sets up a ServiceContainer or ?
'''
host = CONFIG_PARSER.get(SECTION_DISPATCH, 'host')
port = CONFIG_PARSER.get(SECTION_DISPATCH, 'port')
process = subprocess.Popen([cmd, port], env=ENVIRON)
time.sleep(1)
return process
class _TwistedTestProgram(unittest.TestProgram):
def runTests(self):
from twisted.internet import reactor
if self.testRunner is None:
self.testRunner = unittest.TextTestRunner(verbosity=self.verbosity)
result = self.testRunner.run(self.test)
reactor.stop()
return result.wasSuccessful()
class ConfigException(Exception):
"""Exception thrown when configuration settings arent correct.
"""
pass
class TestException(Exception):
"""Exception thrown when test case isn't correctly set up.
"""
pass
class ServiceTestCase(unittest.TestCase):
"""Conventions for method names:
test_net*
-- network tests
test_local*
-- local tests
test_dispatch*
-- tests that use the a spawned local container
class attributes: Edit/Override these in the inheriting class as needed
out -- file descriptor to write output to
name -- configuration item, must be set in class.
url_section -- configuration section, maps a test module
name to an URL.
client_file_name --
types_file_name --
server_file_name --
"""
out = OUTPUT
name = None
url_section = 'WSDL'
client_file_name = None
types_file_name = None
server_file_name = None
def __init__(self, methodName):
"""
parameters:
methodName --
instance variables:
client_module
types_module
server_module
processID
done
"""
self.methodName = methodName
self.url = None
self.wsdl2py_args = []
self.wsdl2dispatch_args = []
self.portkwargs = {}
self.client_module = self.types_module = self.server_module = None
self.done = False
if TWISTED:
self.wsdl2py_args.append('--twisted')
if LAZY:
self.wsdl2py_args.append('--lazy')
unittest.TestCase.__init__(self, methodName)
write = lambda self, arg: self.out.write(arg)
if sys.version_info[:2] >= (2,5):
_exc_info = unittest.TestCase._exc_info
else:
_exc_info = unittest.TestCase._TestCase__exc_info
def __call__(self, *args, **kwds):
self.run(*args, **kwds)
def run(self, result=None):
if result is None: result = self.defaultTestResult()
result.startTest(self)
testMethod = getattr(self, self.methodName)
try:
try:
self.setUp()
except KeyboardInterrupt:
raise
except:
result.addError(self, self._exc_info())
return
ok = False
try:
t1 = time.time()
pyobj = testMethod()
t2 = time.time()
ok = True
except self.failureException:
result.addFailure(self, self._exc_info())
except KeyboardInterrupt:
raise
except:
result.addError(self, self._exc_info())
try:
self.tearDown()
except KeyboardInterrupt:
raise
except:
result.addError(self, self._exc_info())
ok = False
if ok:
result.addSuccess(self)
print>>self
print>>self, "|"+"-"*60
print>>self, "| TestCase: %s" %self.methodName
print>>self, "|"+"-"*20
print>>self, "| run time: %s ms" %((t2-t1)*1000)
print>>self, "| return : %s" %pyobj
print>>self, "|"+"-"*60
finally:
result.stopTest(self)
def getPortKWArgs(self):
kw = {}
if CONFIG_PARSER.getboolean(SECTION_CONFIGURATION, 'tracefile'):
kw['tracefile'] = TRACEFILE
kw.update(self.portkwargs)
return kw
def _setUpDispatch(self):
"""Set this test up as a dispatch test.
url --
"""
host = CONFIG_PARSER.get(SECTION_DISPATCH, 'host')
port = CONFIG_PARSER.get(SECTION_DISPATCH, 'port')
path = CONFIG_PARSER.get(SECTION_DISPATCH, 'path')
scheme = 'http'
netloc = '%s:%s' %(host, port)
params = query = fragment = None
self.portkwargs['url'] = \
urlparse.urlunparse((scheme,netloc,path,params,query,fragment))
_wsdl = {}
def _generate(self):
"""call the wsdl2py and wsdl2dispatch scripts and
automatically add the "-f" or "-u" argument. Other args
can be appended via the "wsdl2py_args" and "wsdl2dispatch_args"
instance attributes.
"""
url = self.url
if SKIP:
ServiceTestCase._wsdl[url] = True
return
args = []
ServiceTestCase._wsdl[url] = False
if os.path.isfile(url):
args += ['-f', os.path.abspath(url)]
else:
args += ['-u', url]
try:
os.mkdir(MODULEDIR)
except OSError, ex:
pass
os.chdir(MODULEDIR)
if MODULEDIR not in sys.path:
sys.path.append(MODULEDIR)
try:
# Client Stubs
wsdl2py = ['wsdl2py'] + args + self.wsdl2py_args
try:
exit = subprocess.call(wsdl2py)
except OSError, ex:
warnings.warn("TODO: Not sure what is going on here?")
exit = -1
#TODO: returncode WINDOWS?
self.failUnless(os.WIFEXITED(exit),
'"%s" exited with signal#: %d' %(wsdl2py, exit))
self.failUnless(exit == 0,
'"%s" exited with exit status: %d' %(wsdl2py, exit))
# Service Stubs
if '-x' not in self.wsdl2py_args:
wsdl2dispatch = (['wsdl2dispatch'] + args +
self.wsdl2dispatch_args)
try:
exit = subprocess.call(wsdl2dispatch)
except OSError, ex:
warnings.warn("TODO: Not sure what is going on here?")
#TODO: returncode WINDOWS?
self.failUnless(os.WIFEXITED(exit),
'"%s" exited with signal#: %d' %(wsdl2dispatch, exit))
self.failUnless(exit == 0,
'"%s" exited with exit status: %d' %(wsdl2dispatch, exit))
ServiceTestCase._wsdl[url] = True
finally:
os.chdir(TOPDIR)
_process = None
_lastToDispatch = None
def setUp(self):
"""Generate types and services modules once, then make them
available thru the *_module attributes if the *_file_name
attributes were specified.
"""
section = self.url_section
name = self.name
if not section or not name:
raise TestException, 'section(%s) or name(%s) not defined' %(
section, name)
if not CONFIG_PARSER.has_section(section):
raise TestException,\
'No such section(%s) in configuration file(%s)' %(
self.url_section, CONFIG_FILE)
self.url = CONFIG_PARSER.get(section, name)
status = ServiceTestCase._wsdl.get(self.url)
if status is False:
self.fail('generation failed for "%s"' %self.url)
if status is None:
self._generate()
# Check for files
tfn = self.types_file_name
cfn = self.client_file_name
sfn = self.server_file_name
files = filter(lambda f: f is not None, [cfn, tfn,sfn])
if None is cfn is tfn is sfn:
return
for n,m in map(lambda i: (i,__import__(i.split('.py')[0])), files):
if tfn is not None and tfn == n:
self.types_module = m
elif cfn is not None and cfn == n:
self.client_module = m
elif sfn is not None and sfn == n:
self.server_module = m
else:
self.fail('Unexpected module %s' %n)
# DISPATCH PORTION OF SETUP
if not self.methodName.startswith('test_dispatch'):
return
self._setUpDispatch()
if ServiceTestCase._process is not None:
return
try:
expath = CONFIG_PARSER.get(SECTION_DISPATCH, name)
except (NoSectionError, NoOptionError), ex:
self.fail('section dispatch has no item "%s"' %name)
if ServiceTestCase._lastToDispatch == expath:
return
if ServiceTestCase._lastToDispatch is not None:
ServiceTestCase.CleanUp()
ServiceTestCase._lastToDispatch = expath
ServiceTestCase._process = _LaunchContainer(TOPDIR + '/' + expath)
def CleanUp(cls):
"""call this when dispatch server is no longer needed,
maybe another needs to be started. Assumption that
a single "Suite" uses the same server, once all the
tests are run in that suite do a cleanup.
"""
if cls._process is None:
return
os.kill(cls._process.pid, signal.SIGKILL)
cls._process = None
CleanUp = classmethod(CleanUp)
class ServiceTestSuite(unittest.TestSuite):
"""A test suite is a composite test consisting of a number of TestCases.
For use, create an instance of TestSuite, then add test case instances.
When all tests have been added, the suite can be passed to a test
runner, such as TextTestRunner. It will run the individual test cases
in the order in which they were added, aggregating the results. When
subclassing, do not forget to call the base class constructor.
"""
def __init__(self, tests=()):
unittest.TestSuite.__init__(self, tests)
def __call__(self, result):
# for python2.4
return self.run(result)
def addTest(self, test):
unittest.TestSuite.addTest(self, test)
def run(self, result):
for test in self._tests:
if result.shouldStop:
break
test(result)
ServiceTestCase.CleanUp()
return result | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/test/wsdl2py/ServiceTest.py | ServiceTest.py |
import unittest, warnings
from ServiceTest import main, CONFIG_PARSER, DOCUMENT, LITERAL, BROKE, TESTS
# General targets
def dispatch():
"""Run all dispatch tests"""
return _dispatchTestSuite(broke=False)
def local():
"""Run all local tests"""
return _localTestSuite(broke=False)
def net():
"""Run all network tests"""
return _netTestSuite(broke=False)
def all():
"""Run all tests"""
return _allTestSuite(broke=False)
# Specialized binding targets
def docLitTestSuite():
"""Run all doc/lit network tests"""
return _netTestSuite(broke=False, document=True, literal=True)
def rpcLitTestSuite():
"""Run all rpc/lit network tests"""
return _netTestSuite(broke=False, document=False, literal=True)
def rpcEncTestSuite():
"""Run all rpc/enc network tests"""
return _netTestSuite(broke=False, document=False, literal=False)
# Low level functions
def _allTestSuite(document=None, literal=None, broke=None):
return _makeTestSuite('all', document, literal, broke)
def _netTestSuite(document=None, literal=None, broke=None):
return _makeTestSuite('net', document, literal, broke)
def _localTestSuite(document=None, literal=None, broke=None):
return _makeTestSuite('local', document, literal, broke)
def _dispatchTestSuite(document=None, literal=None, broke=None):
return _makeTestSuite('dispatch', document, literal, broke)
def _makeTestSuite(test, document=None, literal=None, broke=None):
"""Return a test suite containing all test cases that satisfy
the parameters. None means don't check.
Parameters:
test -- "net" run network tests, "local" run local tests,
"dispatch" run dispatch tests, "all" run all tests.
document -- None, True, False
literal -- None, True, False
broke -- None, True, False
"""
assert test in ['net', 'local', 'dispatch', 'all'],(
'test must be net, local, dispatch, or all')
cp = CONFIG_PARSER
testSections = []
sections = [\
'rpc_encoded' , 'rpc_encoded_broke',
'rpc_literal', 'rpc_literal_broke', 'rpc_literal_broke_interop',
'doc_literal', 'doc_literal_broke', 'doc_literal_broke_interop',
]
boo = cp.getboolean
for s,d,l,b in map(\
lambda sec: \
(sec, (None,boo(sec,DOCUMENT)), (None,boo(sec,LITERAL)), (None,boo(sec,BROKE))), sections):
if document in d and literal in l and broke in b:
testSections.append(s)
suite = unittest.TestSuite()
for section in testSections:
moduleList = cp.get(section, TESTS).split()
for module in map(__import__, moduleList):
def _warn_empty():
warnings.warn('"%s" has no test "%s"' %(module, test))
return unittest.TestSuite()
s = getattr(module, test, _warn_empty)()
suite.addTest(s)
return suite
if __name__ == "__main__":
main() | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/test/wsdl2py/runTests.py | runTests.py |
from ZSI import _copyright, _children, _child_elements, \
_get_idstr, _stringtypes, _seqtypes, _Node, SoapWriter, ZSIException
from ZSI.TCcompound import Struct
from ZSI.TC import QName, URI, String, XMLString, AnyElement, UNBOUNDED
from ZSI.wstools.Namespaces import SOAP, ZSI_SCHEMA_URI
from ZSI.wstools.c14n import Canonicalize
from ZSI.TC import ElementDeclaration
import traceback, cStringIO as StringIO
class Detail:
def __init__(self, any=None):
self.any = any
Detail.typecode = Struct(Detail, [AnyElement(aname='any',minOccurs=0, maxOccurs="unbounded")], pname='detail', minOccurs=0)
class FaultType:
def __init__(self, faultcode=None, faultstring=None, faultactor=None, detail=None):
self.faultcode = faultcode
self.faultstring= faultstring
self.faultactor = faultactor
self.detail = detail
FaultType.typecode = \
Struct(FaultType,
[QName(pname='faultcode'),
String(pname='faultstring'),
URI(pname=(SOAP.ENV,'faultactor'), minOccurs=0),
Detail.typecode,
AnyElement(aname='any',minOccurs=0, maxOccurs=UNBOUNDED),
],
pname=(SOAP.ENV,'Fault'),
inline=True,
hasextras=0,
)
class ZSIHeaderDetail:
def __init__(self, detail):
self.any = detail
ZSIHeaderDetail.typecode =\
Struct(ZSIHeaderDetail,
[AnyElement(aname='any', minOccurs=0, maxOccurs=UNBOUNDED)],
pname=(ZSI_SCHEMA_URI, 'detail'))
class ZSIFaultDetailTypeCode(ElementDeclaration, Struct):
'''<ZSI:FaultDetail>
<ZSI:string>%s</ZSI:string>
<ZSI:trace>%s</ZSI:trace>
</ZSI:FaultDetail>
'''
schema = ZSI_SCHEMA_URI
literal = 'FaultDetail'
def __init__(self, **kw):
Struct.__init__(self, ZSIFaultDetail, [String(pname=(ZSI_SCHEMA_URI, 'string')),
String(pname=(ZSI_SCHEMA_URI, 'trace'),minOccurs=0),],
pname=(ZSI_SCHEMA_URI, 'FaultDetail'), **kw
)
class ZSIFaultDetail:
def __init__(self, string=None, trace=None):
self.string = string
self.trace = trace
def __str__(self):
if self.trace:
return self.string + '\n[trace: ' + self.trace + ']'
return self.string
def __repr__(self):
return "<%s.ZSIFaultDetail %s>" % (__name__, _get_idstr(self))
ZSIFaultDetail.typecode = ZSIFaultDetailTypeCode()
class URIFaultDetailTypeCode(ElementDeclaration, Struct):
'''
<ZSI:URIFaultDetail>
<ZSI:URI>uri</ZSI:URI>
<ZSI:localname>localname</ZSI:localname>
</ZSI:URIFaultDetail>
'''
schema = ZSI_SCHEMA_URI
literal = 'URIFaultDetail'
def __init__(self, **kw):
Struct.__init__(self, URIFaultDetail,
[String(pname=(ZSI_SCHEMA_URI, 'URI')), String(pname=(ZSI_SCHEMA_URI, 'localname')),],
pname=(ZSI_SCHEMA_URI, 'URIFaultDetail'), **kw
)
class URIFaultDetail:
def __init__(self, uri=None, localname=None):
self.URI = uri
self.localname = localname
URIFaultDetail.typecode = URIFaultDetailTypeCode()
class ActorFaultDetailTypeCode(ElementDeclaration, Struct):
'''
<ZSI:ActorFaultDetail>
<ZSI:URI>%s</ZSI:URI>
</ZSI:ActorFaultDetail>
'''
schema = ZSI_SCHEMA_URI
literal = 'ActorFaultDetail'
def __init__(self, **kw):
Struct.__init__(self, ActorFaultDetail, [String(pname=(ZSI_SCHEMA_URI, 'URI')),],
pname=(ZSI_SCHEMA_URI, 'ActorFaultDetail'), **kw
)
class ActorFaultDetail:
def __init__(self, uri=None):
self.URI = uri
ActorFaultDetail.typecode = ActorFaultDetailTypeCode()
class Fault(ZSIException):
'''SOAP Faults.
'''
Client = "SOAP-ENV:Client"
Server = "SOAP-ENV:Server"
MU = "SOAP-ENV:MustUnderstand"
def __init__(self, code, string,
actor=None, detail=None, headerdetail=None):
if detail is not None and type(detail) not in _seqtypes:
detail = (detail,)
if headerdetail is not None and type(headerdetail) not in _seqtypes:
headerdetail = (headerdetail,)
self.code, self.string, self.actor, self.detail, self.headerdetail = \
code, string, actor, detail, headerdetail
ZSIException.__init__(self, code, string, actor, detail, headerdetail)
def DataForSOAPHeader(self):
if not self.headerdetail: return None
# SOAP spec doesn't say how to encode header fault data.
return ZSIHeaderDetail(self.headerdetail)
def serialize(self, sw):
'''Serialize the object.'''
detail = None
if self.detail is not None:
detail = Detail()
detail.any = self.detail
pyobj = FaultType(self.code, self.string, self.actor, detail)
sw.serialize(pyobj, typed=False)
def AsSOAP(self, **kw):
header = self.DataForSOAPHeader()
sw = SoapWriter(**kw)
self.serialize(sw)
if header is not None:
sw.serialize_header(header, header.typecode, typed=False)
return str(sw)
def __str__(self):
strng = str(self.string) + "\n"
if hasattr(self, 'detail'):
if hasattr(self.detail, '__len__'):
for d in self.detail:
strng += str(d)
else:
strng += str(self.detail)
return strng
def __repr__(self):
return "<%s.Fault at %s>" % (__name__, _get_idstr(self))
AsSoap = AsSOAP
def FaultFromNotUnderstood(uri, localname, actor=None):
detail, headerdetail = None, URIFaultDetail(uri, localname)
return Fault(Fault.MU, 'SOAP mustUnderstand not understood',
actor, detail, headerdetail)
def FaultFromActor(uri, actor=None):
detail, headerdetail = None, ActorFaultDetail(uri)
return Fault(Fault.Client, 'Cannot process specified actor',
actor, detail, headerdetail)
def FaultFromZSIException(ex, actor=None):
'''Return a Fault object created from a ZSI exception object.
'''
mystr = getattr(ex, 'str', None) or str(ex)
mytrace = getattr(ex, 'trace', '')
elt = '''<ZSI:ParseFaultDetail>
<ZSI:string>%s</ZSI:string>
<ZSI:trace>%s</ZSI:trace>
</ZSI:ParseFaultDetail>
''' % (mystr, mytrace)
if getattr(ex, 'inheader', 0):
detail, headerdetail = None, elt
else:
detail, headerdetail = elt, None
return Fault(Fault.Client, 'Unparseable message',
actor, detail, headerdetail)
def FaultFromException(ex, inheader, tb=None, actor=None):
'''Return a Fault object created from a Python exception.
<SOAP-ENV:Fault>
<faultcode>SOAP-ENV:Server</faultcode>
<faultstring>Processing Failure</faultstring>
<detail>
<ZSI:FaultDetail>
<ZSI:string></ZSI:string>
<ZSI:trace></ZSI:trace>
</ZSI:FaultDetail>
</detail>
</SOAP-ENV:Fault>
'''
tracetext = None
if tb:
try:
lines = '\n'.join(['%s:%d:%s' % (name, line, func)
for name, line, func, text in traceback.extract_tb(tb)])
except:
pass
else:
tracetext = lines
exceptionName = ""
try:
exceptionName = ":".join([ex.__module__, ex.__class__.__name__])
except: pass
elt = ZSIFaultDetail(string=exceptionName + "\n" + str(ex), trace=tracetext)
if inheader:
detail, headerdetail = None, elt
else:
detail, headerdetail = elt, None
return Fault(Fault.Server, 'Processing Failure',
actor, detail, headerdetail)
def FaultFromFaultMessage(ps):
'''Parse the message as a fault.
'''
pyobj = ps.Parse(FaultType.typecode)
if pyobj.detail == None: detailany = None
else: detailany = pyobj.detail.any
return Fault(pyobj.faultcode, pyobj.faultstring,
pyobj.faultactor, detailany)
if __name__ == '__main__': print _copyright | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/ZSI/fault.py | fault.py |
from ZSI import _copyright, _children, _attrs, _child_elements, _stringtypes, \
_backtrace, EvaluateException, ParseException, _valid_encoding, \
_Node, _find_attr, _resolve_prefix
from ZSI.TC import AnyElement
import types
from ZSI.wstools.Namespaces import SOAP, XMLNS
from ZSI.wstools.Utility import SplitQName
_find_actor = lambda E: E.getAttributeNS(SOAP.ENV, "actor") or None
_find_mu = lambda E: E.getAttributeNS(SOAP.ENV, "mustUnderstand")
_find_root = lambda E: E.getAttributeNS(SOAP.ENC, "root")
_find_id = lambda E: _find_attr(E, 'id')
class ParsedSoap:
'''A Parsed SOAP object.
Convert the text to a DOM tree and parse SOAP elements.
Instance data:
reader -- the DOM reader
dom -- the DOM object
ns_cache -- dictionary (by id(node)) of namespace dictionaries
id_cache -- dictionary (by XML ID attr) of elements
envelope -- the node holding the SOAP Envelope
header -- the node holding the SOAP Header (or None)
body -- the node holding the SOAP Body
body_root -- the serialization root in the SOAP Body
data_elements -- list of non-root elements in the SOAP Body
trailer_elements -- list of elements following the SOAP body
'''
defaultReaderClass = None
def __init__(self, input, readerclass=None, keepdom=False,
trailers=False, resolver=None, envelope=True, **kw):
'''Initialize.
Keyword arguments:
trailers -- allow trailer elments (default is zero)
resolver -- function (bound method) to resolve URI's
readerclass -- factory class to create a reader
keepdom -- do not release the DOM
envelope -- look for a SOAP envelope.
'''
self.readerclass = readerclass
self.keepdom = keepdom
if not self.readerclass:
if self.defaultReaderClass != None:
self.readerclass = self.defaultReaderClass
else:
from xml.dom.ext.reader import PyExpat
self.readerclass = PyExpat.Reader
try:
self.reader = self.readerclass()
if type(input) in _stringtypes:
self.dom = self.reader.fromString(input)
else:
self.dom = self.reader.fromStream(input)
except Exception, e:
# Is this in the header? Your guess is as good as mine.
#raise ParseException("Can't parse document (" + \
# str(e.__class__) + "): " + str(e), 0)
raise
self.ns_cache = {
id(self.dom): {
'xml': XMLNS.XML,
'xmlns': XMLNS.BASE,
'': ''
}
}
self.trailers, self.resolver, self.id_cache = trailers, resolver, {}
# Exactly one child element
c = [ E for E in _children(self.dom)
if E.nodeType == _Node.ELEMENT_NODE]
if len(c) == 0:
raise ParseException("Document has no Envelope", 0)
if len(c) != 1:
raise ParseException("Document has extra child elements", 0)
if envelope is False:
self.body_root = c[0]
return
# And that one child must be the Envelope
elt = c[0]
if elt.localName != "Envelope" \
or elt.namespaceURI != SOAP.ENV:
raise ParseException('Document has "' + elt.localName + \
'" element, not Envelope', 0)
self._check_for_legal_children("Envelope", elt)
for a in _attrs(elt):
name = a.nodeName
if name.find(":") == -1 and name not in [ "xmlns", "id" ]:
raise ParseException('Unqualified attribute "' + \
name + '" in Envelope', 0)
self.envelope = elt
if not _valid_encoding(self.envelope):
raise ParseException("Envelope has invalid encoding", 0)
# Get Envelope's child elements.
c = [ E for E in _children(self.envelope)
if E.nodeType == _Node.ELEMENT_NODE ]
if len(c) == 0:
raise ParseException("Envelope is empty (no Body)", 0)
# Envelope's first child might be the header; if so, nip it off.
elt = c[0]
if elt.localName == "Header" \
and elt.namespaceURI == SOAP.ENV:
self._check_for_legal_children("Header", elt)
self._check_for_pi_nodes(_children(elt), 1)
self.header = c.pop(0)
self.header_elements = _child_elements(self.header)
else:
self.header, self.header_elements = None, []
# Now the first child must be the body
if len(c) == 0:
raise ParseException("Envelope has header but no Body", 0)
elt = c.pop(0)
if elt.localName != "Body" \
or elt.namespaceURI != SOAP.ENV:
if self.header:
raise ParseException('Header followed by "' + \
elt.localName + \
'" element, not Body', 0, elt, self.dom)
else:
raise ParseException('Document has "' + \
elt.localName + \
'" element, not Body', 0, elt, self.dom)
self._check_for_legal_children("Body", elt, 0)
self._check_for_pi_nodes(_children(elt), 0)
self.body = elt
if not _valid_encoding(self.body):
raise ParseException("Body has invalid encoding", 0)
# Trailer elements.
if not self.trailers:
if len(c):
raise ParseException("Element found after Body",
0, elt, self.dom)
# Don't set self.trailer_elements = []; if user didn't ask
# for trailers we *want* to throw an exception.
else:
self.trailer_elements = c
for elt in self.trailer_elements:
if not elt.namespaceURI:
raise ParseException('Unqualified trailer element',
0, elt, self.dom)
# Find the serialization root. Divide the Body children into
# root (root=1), no (root=0), maybe (no root attribute).
self.body_root, no, maybe = None, [], []
for elt in _child_elements(self.body):
root = _find_root(elt)
if root == "1":
if self.body_root:
raise ParseException("Multiple seralization roots found",
0, elt, self.dom)
self.body_root = elt
elif root == "0":
no.append(elt)
elif not root:
maybe.append(elt)
else:
raise ParseException('Illegal value for root attribute',
0, elt, self.dom)
# If we didn't find a root, get the first one that didn't
# say "not me", unless they all said "not me."
if self.body_root is None:
if len(maybe):
self.body_root = maybe[0]
else:
raise ParseException('No serialization root found',
0, self.body, self.dom)
if not _valid_encoding(self.body_root):
raise ParseException("Invalid encoding", 0,
elt, self.dom)
# Now get all the non-roots (in order!).
rootid = id(self.body_root)
self.data_elements = [ E for E in _child_elements(self.body)
if id(E) != rootid ]
self._check_for_pi_nodes(self.data_elements, 0)
def __del__(self):
try:
if not self.keepdom:
self.reader.releaseNode(self.dom)
except:
pass
def _check_for_legal_children(self, name, elt, mustqualify=1):
'''Check if all children of this node are elements or whitespace-only
text nodes.
'''
inheader = name == "Header"
for n in _children(elt):
t = n.nodeType
if t == _Node.COMMENT_NODE: continue
if t != _Node.ELEMENT_NODE:
if t == _Node.TEXT_NODE and n.nodeValue.strip() == "":
continue
raise ParseException("Non-element child in " + name,
inheader, elt, self.dom)
if mustqualify and not n.namespaceURI:
raise ParseException('Unqualified element "' + \
n.nodeName + '" in ' + name, inheader, elt, self.dom)
def _check_for_pi_nodes(self, list, inheader):
'''Raise an exception if any of the list descendants are PI nodes.
'''
list = list[:]
while list:
elt = list.pop()
t = elt.nodeType
if t == _Node.PROCESSING_INSTRUCTION_NODE:
raise ParseException('Found processing instruction "<?' + \
elt.nodeName + '...>"',
inheader, elt.parentNode, self.dom)
elif t == _Node.DOCUMENT_TYPE_NODE:
raise ParseException('Found DTD', inheader,
elt.parentNode, self.dom)
list += _children(elt)
def Backtrace(self, elt):
'''Return a human-readable "backtrace" from the document root to
the specified element.
'''
return _backtrace(elt, self.dom)
def FindLocalHREF(self, href, elt, headers=1):
'''Find a local HREF in the data elements.
'''
if href[0] != '#':
raise EvaluateException(
'Absolute HREF ("%s") not implemented' % href,
self.Backtrace(elt))
frag = href[1:]
# Already found?
e = self.id_cache.get(frag)
if e: return e
# Do a breadth-first search, in the data first. Most likely
# to find multi-ref targets shallow in the data area.
list = self.data_elements[:] + [self.body_root]
if headers: list.extend(self.header_elements)
while list:
e = list.pop()
if e.nodeType == _Node.ELEMENT_NODE:
nodeid = _find_id(e)
if nodeid:
self.id_cache[nodeid] = e
if nodeid == frag: return e
list += _children(e)
raise EvaluateException('''Can't find node for HREF "%s"''' % href,
self.Backtrace(elt))
def ResolveHREF(self, uri, tc, **keywords):
r = getattr(tc, 'resolver', self.resolver)
if not r:
raise EvaluateException('No resolver for "' + uri + '"')
try:
if type(uri) == types.UnicodeType: uri = str(uri)
retval = r(uri, tc, self, **keywords)
except Exception, e:
raise EvaluateException('''Can't resolve "''' + uri + '" (' + \
str(e.__class__) + "): " + str(e))
return retval
def GetMyHeaderElements(self, actorlist=None):
'''Return a list of all elements intended for these actor(s).
'''
if actorlist is None:
actorlist = [None, SOAP.ACTOR_NEXT]
else:
actorlist = list(actorlist) + [None, SOAP.ACTOR_NEXT]
return [ E for E in self.header_elements
if _find_actor(E) in actorlist ]
def GetElementNSdict(self, elt):
'''Get a dictionary of all the namespace attributes for the indicated
element. The dictionaries are cached, and we recurse up the tree
as necessary.
'''
d = self.ns_cache.get(id(elt))
if not d:
if elt != self.dom: d = self.GetElementNSdict(elt.parentNode)
for a in _attrs(elt):
if a.namespaceURI == XMLNS.BASE:
if a.localName == "xmlns":
d[''] = a.nodeValue
else:
d[a.localName] = a.nodeValue
self.ns_cache[id(elt)] = d
return d.copy()
def GetDomAndReader(self):
'''Returns a tuple containing the dom and reader objects. (dom, reader)
Unless keepdom is true, the dom and reader objects will go out of scope
when the ParsedSoap instance is deleted. If keepdom is true, the reader
object is needed to properly clean up the dom tree with
reader.releaseNode(dom).
'''
return (self.dom, self.reader)
def IsAFault(self):
'''Is this a fault message?
'''
e = self.body_root
if not e: return 0
return e.namespaceURI == SOAP.ENV and e.localName == 'Fault'
def Parse(self, how):
'''Parse the message.
'''
if type(how) == types.ClassType: how = how.typecode
return how.parse(self.body_root, self)
def WhatMustIUnderstand(self):
'''Return a list of (uri,localname) tuples for all elements in the
header that have mustUnderstand set.
'''
return [ ( E.namespaceURI, E.localName )
for E in self.header_elements if _find_mu(E) == "1" ]
def WhatActorsArePresent(self):
'''Return a list of URI's of all the actor attributes found in
the header. The special actor "next" is ignored.
'''
results = []
for E in self.header_elements:
a = _find_actor(E)
if a not in [ None, SOAP.ACTOR_NEXT ]: results.append(a)
return results
def ParseHeaderElements(self, ofwhat):
'''Returns a dictionary of pyobjs.
ofhow -- list of typecodes w/matching nspname/pname to the header_elements.
'''
d = {}
lenofwhat = len(ofwhat)
c, crange = self.header_elements[:], range(len(self.header_elements))
for i,what in [ (i, ofwhat[i]) for i in range(lenofwhat) ]:
if isinstance(what, AnyElement):
raise EvaluateException, 'not supporting <any> as child of SOAP-ENC:Header'
v = []
occurs = 0
namespaceURI,tagName = what.nspname,what.pname
for j,c_elt in [ (j, c[j]) for j in crange if c[j] ]:
prefix,name = SplitQName(c_elt.tagName)
nsuri = _resolve_prefix(c_elt, prefix)
if tagName == name and namespaceURI == nsuri:
pyobj = what.parse(c_elt, self)
else:
continue
v.append(pyobj)
c[j] = None
if what.minOccurs > len(v) > what.maxOccurs:
raise EvaluateException, 'number of occurances(%d) doesnt fit constraints (%d,%s)'\
%(len(v),what.minOccurs,what.maxOccurs)
if what.maxOccurs == 1:
if len(v) == 0: v = None
else: v = v[0]
d[(what.nspname,what.pname)] = v
return d
if __name__ == '__main__': print _copyright | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/ZSI/parse.py | parse.py |
from ZSI import _copyright, _children, _child_elements, \
_floattypes, _stringtypes, _seqtypes, _find_attr, _find_attrNS, _find_attrNodeNS, \
_find_arraytype, _find_default_namespace, _find_href, _find_encstyle, \
_resolve_prefix, _find_xsi_attr, _find_type, \
_find_xmlns_prefix, _get_element_nsuri_name, _get_idstr, \
_Node, EvaluateException, \
_valid_encoding, ParseException
from ZSI.wstools.Namespaces import SCHEMA, SOAP
from ZSI.wstools.Utility import SplitQName
from ZSI.wstools.c14n import Canonicalize
from ZSI.wstools.logging import getLogger as _GetLogger
import re, types, time, copy
from base64 import decodestring as b64decode, encodestring as b64encode
from urllib import unquote as urldecode, quote as urlencode
from binascii import unhexlify as hexdecode, hexlify as hexencode
_is_xsd_or_soap_ns = lambda ns: ns in [
SCHEMA.XSD3, SOAP.ENC, SCHEMA.XSD1, SCHEMA.XSD2, ]
_find_nil = lambda E: _find_xsi_attr(E, "null") or _find_xsi_attr(E, "nil")
def _get_xsitype(pyclass):
'''returns the xsi:type as a tuple, coupled with ZSI.schema
'''
if hasattr(pyclass,'type') and type(pyclass.type) in _seqtypes:
return pyclass.type
elif hasattr(pyclass,'type') and hasattr(pyclass, 'schema'):
return (pyclass.schema, pyclass.type)
return (None,None)
# value returned when xsi:nil="true"
Nilled = None
UNBOUNDED = 'unbounded'
class TypeCode:
'''The parent class for all parseable SOAP types.
Class data:
typechecks -- do init-time type checking if non-zero
Class data subclasses may define:
tag -- global element declaration
type -- global type definition
parselist -- list of valid SOAP types for this class, as
(uri,name) tuples, where a uri of None means "all the XML
Schema namespaces"
errorlist -- parselist in a human-readable form; will be
generated if/when needed
seriallist -- list of Python types or user-defined classes
that this typecode can serialize.
logger -- logger instance for this class.
'''
tag = None
type = (None,None)
typechecks = True
attribute_typecode_dict = None
logger = _GetLogger('ZSI.TC.TypeCode')
def __init__(self, pname=None, aname=None, minOccurs=1,
maxOccurs=1, nillable=False, typed=True, unique=True,
pyclass=None, attrs_aname='_attrs', **kw):
'''Baseclass initialization.
Instance data (and usually keyword arg)
pname -- the parameter name (localname).
nspname -- the namespace for the parameter;
None to ignore the namespace
typed -- output xsi:type attribute
unique -- data item is not aliased (no href/id needed)
minOccurs -- min occurances
maxOccurs -- max occurances
nillable -- is item nillable?
attrs_aname -- This is variable name to dictionary of attributes
encoded -- encoded namespaceURI (specify if use is encoded)
'''
if type(pname) in _seqtypes:
self.nspname, self.pname = pname
else:
self.nspname, self.pname = None, pname
if self.pname:
self.pname = str(self.pname).split(':')[-1]
self.aname = aname or self.pname
self.minOccurs = minOccurs
self.maxOccurs = maxOccurs
self.nillable = nillable
self.typed = typed
self.unique = unique
self.attrs_aname = attrs_aname
self.pyclass = pyclass
# Need this stuff for rpc/encoded.
encoded = kw.get('encoded')
if encoded is not None:
self.nspname = kw['encoded']
def parse(self, elt, ps):
'''
Parameters:
elt -- the DOM element being parsed
ps -- the ParsedSoap object.
'''
raise EvaluateException("Unimplemented evaluation", ps.Backtrace(elt))
def serialize(self, elt, sw, pyobj, name=None, orig=None, **kw):
'''
Parameters:
elt -- the current DOMWrapper element
sw -- soapWriter object
pyobj -- python object to serialize
'''
raise EvaluateException("Unimplemented evaluation", sw.Backtrace(elt))
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data.
Parameters:
text -- text content
elt -- the DOM element being parsed
ps -- the ParsedSoap object.
'''
raise EvaluateException("Unimplemented evaluation", ps.Backtrace(elt))
def serialize_as_nil(self, elt):
'''
Parameters:
elt -- the current DOMWrapper element
'''
elt.setAttributeNS(SCHEMA.XSI3, 'nil', '1')
def SimpleHREF(self, elt, ps, tag):
'''Simple HREF for non-string and non-struct and non-array.
Parameters:
elt -- the DOM element being parsed
ps -- the ParsedSoap object.
tag --
'''
if len(_children(elt)): return elt
href = _find_href(elt)
if not href:
if self.minOccurs is 0: return None
raise EvaluateException('Required' + tag + ' missing',
ps.Backtrace(elt))
return ps.FindLocalHREF(href, elt, 0)
def get_parse_and_errorlist(self):
"""Get the parselist and human-readable version, errorlist is returned,
because it is used in error messages.
"""
d = self.__class__.__dict__
parselist = d.get('parselist')
errorlist = d.get('errorlist')
if parselist and not errorlist:
errorlist = []
for t in parselist:
if t[1] not in errorlist: errorlist.append(t[1])
errorlist = ' or '.join(errorlist)
d['errorlist'] = errorlist
return (parselist, errorlist)
def checkname(self, elt, ps):
'''See if the name and type of the "elt" element is what we're
looking for. Return the element's type.
Parameters:
elt -- the DOM element being parsed
ps -- the ParsedSoap object.
'''
parselist,errorlist = self.get_parse_and_errorlist()
ns, name = _get_element_nsuri_name(elt)
if ns == SOAP.ENC:
# Element is in SOAP namespace, so the name is a type.
if parselist and \
(None, name) not in parselist and (ns, name) not in parselist:
raise EvaluateException(
'Element mismatch (got %s wanted %s) (SOAP encoding namespace)' % \
(name, errorlist), ps.Backtrace(elt))
return (ns, name)
# Not a type, check name matches.
if self.nspname and ns != self.nspname:
raise EvaluateException('Element NS mismatch (got %s wanted %s)' % \
(ns, self.nspname), ps.Backtrace(elt))
if self.pname and name != self.pname:
raise EvaluateException('Element Name mismatch (got %s wanted %s)' % \
(name, self.pname), ps.Backtrace(elt))
return self.checktype(elt, ps)
def checktype(self, elt, ps):
'''See if the type of the "elt" element is what we're looking for.
Return the element's type.
Parameters:
elt -- the DOM element being parsed
ps -- the ParsedSoap object.
'''
typeName = _find_type(elt)
if typeName is None or typeName == "":
return (None,None)
# Parse the QNAME.
prefix,typeName = SplitQName(typeName)
uri = ps.GetElementNSdict(elt).get(prefix)
if uri is None:
raise EvaluateException('Malformed type attribute (bad NS)',
ps.Backtrace(elt))
#typeName = list[1]
parselist,errorlist = self.get_parse_and_errorlist()
if not parselist or \
(uri,typeName) in parselist or \
(_is_xsd_or_soap_ns(uri) and (None,typeName) in parselist):
return (uri,typeName)
raise EvaluateException(
'Type mismatch (%s namespace) (got %s wanted %s)' % \
(uri, typeName, errorlist), ps.Backtrace(elt))
def name_match(self, elt):
'''Simple boolean test to see if we match the element name.
Parameters:
elt -- the DOM element being parsed
'''
return self.pname == elt.localName and \
self.nspname in [None, elt.namespaceURI]
def nilled(self, elt, ps):
'''Is the element NIL, and is that okay?
Parameters:
elt -- the DOM element being parsed
ps -- the ParsedSoap object.
'''
if _find_nil(elt) not in [ "true", "1"]: return False
if self.nillable is False:
raise EvaluateException('Non-nillable element is NIL',
ps.Backtrace(elt))
return True
def simple_value(self, elt, ps, mixed=False):
'''Get the value of the simple content of this element.
Parameters:
elt -- the DOM element being parsed
ps -- the ParsedSoap object.
mixed -- ignore element content, optional text node
'''
if not _valid_encoding(elt):
raise EvaluateException('Invalid encoding', ps.Backtrace(elt))
c = _children(elt)
if mixed is False:
if len(c) == 0:
raise EvaluateException('Value missing', ps.Backtrace(elt))
for c_elt in c:
if c_elt.nodeType == _Node.ELEMENT_NODE:
raise EvaluateException('Sub-elements in value',
ps.Backtrace(c_elt))
# It *seems* to be consensus that ignoring comments and
# concatenating the text nodes is the right thing to do.
return ''.join([E.nodeValue for E in c
if E.nodeType
in [ _Node.TEXT_NODE, _Node.CDATA_SECTION_NODE ]])
def parse_attributes(self, elt, ps):
'''find all attributes specified in the attribute_typecode_dict in
current element tag, if an attribute is found set it in the
self.attributes dictionary. Default to putting in String.
Parameters:
elt -- the DOM element being parsed
ps -- the ParsedSoap object.
'''
if self.attribute_typecode_dict is None:
return
attributes = {}
for attr,what in self.attribute_typecode_dict.items():
namespaceURI,localName = None,attr
if type(attr) in _seqtypes:
namespaceURI,localName = attr
value = _find_attrNodeNS(elt, namespaceURI, localName)
self.logger.debug("Parsed Attribute (%s,%s) -- %s",
namespaceURI, localName, value)
# For Now just set it w/o any type interpretation.
if value is None: continue
attributes[attr] = what.text_to_data(value, elt, ps)
return attributes
def set_attributes(self, el, pyobj):
'''Instance data attributes contains a dictionary
of keys (namespaceURI,localName) and attribute values.
These values can be self-describing (typecode), or use
attribute_typecode_dict to determine serialization.
Paramters:
el -- MessageInterface representing the element
pyobj --
'''
if not hasattr(pyobj, self.attrs_aname):
return
if not isinstance(getattr(pyobj, self.attrs_aname), dict):
raise TypeError,\
'pyobj.%s must be a dictionary of names and values'\
% self.attrs_aname
for attr, value in getattr(pyobj, self.attrs_aname).items():
namespaceURI,localName = None, attr
if type(attr) in _seqtypes:
namespaceURI, localName = attr
what = None
if getattr(self, 'attribute_typecode_dict', None) is not None:
what = self.attribute_typecode_dict.get(attr)
if what is None and namespaceURI is None:
what = self.attribute_typecode_dict.get(localName)
# allow derived type
if hasattr(value, 'typecode') and not isinstance(what, AnyType):
if what is not None and not isinstance(value.typecode, what):
raise EvaluateException, \
'self-describing attribute must subclass %s'\
%what.__class__
what = value.typecode
self.logger.debug("attribute create -- %s", value)
if isinstance(what, QName):
what.set_prefix(el, value)
#format the data
if what is None:
value = str(value)
else:
value = what.get_formatted_content(value)
el.setAttributeNS(namespaceURI, localName, value)
def set_attribute_xsi_type(self, el, **kw):
'''if typed, set the xsi:type attribute
Paramters:
el -- MessageInterface representing the element
'''
if kw.get('typed', self.typed):
namespaceURI,typeName = kw.get('type', _get_xsitype(self))
if namespaceURI and typeName:
self.logger.debug("attribute: (%s, %s)", namespaceURI, typeName)
el.setAttributeType(namespaceURI, typeName)
def set_attribute_href(self, el, objid):
'''set href attribute
Paramters:
el -- MessageInterface representing the element
objid -- ID type, unique id
'''
el.setAttributeNS(None, 'href', "#%s" %objid)
def set_attribute_id(self, el, objid):
'''set id attribute
Paramters:
el -- MessageInterface representing the element
objid -- ID type, unique id
'''
if self.unique is False:
el.setAttributeNS(None, 'id', "%s" %objid)
def get_name(self, name, objid):
'''
Paramters:
name -- element tag
objid -- ID type, unique id
'''
if type(name) is tuple:
return name
ns = self.nspname
n = name or self.pname or ('E' + objid)
return ns,n
def has_attributes(self):
'''Return True if Attributes are declared outside
the scope of SOAP ('root', 'id', 'href'), and some
attributes automatically handled (xmlns, xsi:type).
'''
if self.attribute_typecode_dict is None: return False
return len(self.attribute_typecode_dict) > 0
class SimpleType(TypeCode):
'''SimpleType -- consist exclusively of a tag, attributes, and a value
class attributes:
empty_content -- value representing an empty element.
'''
empty_content = None
logger = _GetLogger('ZSI.TC.SimpleType')
def parse(self, elt, ps):
self.checkname(elt, ps)
if len(_children(elt)) == 0:
href = _find_href(elt)
if not href:
if self.nilled(elt, ps) is False:
# No content, no HREF, not NIL: empty string
return self.text_to_data(self.empty_content, elt, ps)
# No content, no HREF, and is NIL...
if self.nillable is True:
return Nilled
raise EvaluateException('Requiredstring missing',
ps.Backtrace(elt))
if href[0] != '#':
return ps.ResolveHREF(href, self)
elt = ps.FindLocalHREF(href, elt)
self.checktype(elt, ps)
if self.nilled(elt, ps): return Nilled
if len(_children(elt)) == 0:
v = self.empty_content
else:
v = self.simple_value(elt, ps)
else:
v = self.simple_value(elt, ps)
pyobj = self.text_to_data(v, elt, ps)
# parse all attributes contained in attribute_typecode_dict
# (user-defined attributes), the values (if not None) will
# be keyed in self.attributes dictionary.
if self.attribute_typecode_dict is not None:
attributes = self.parse_attributes(elt, ps)
if attributes:
setattr(pyobj, self.attrs_aname, attributes)
return pyobj
def get_formatted_content(self, pyobj):
raise NotImplementedError, 'method get_formatted_content is not implemented'
def serialize_text_node(self, elt, sw, pyobj):
'''Serialize without an element node.
'''
textNode = None
if pyobj is not None:
text = self.get_formatted_content(pyobj)
if type(text) not in _stringtypes:
raise TypeError, 'pyobj must be a formatted string'
textNode = elt.createAppendTextNode(text)
return textNode
def serialize(self, elt, sw, pyobj, name=None, orig=None, **kw):
'''Handles the start and end tags, and attributes. callout
to get_formatted_content to get the textNode value.
Parameters:
elt -- ElementProxy/DOM element
sw -- SoapWriter instance
pyobj -- processed content
KeyWord Parameters:
name -- substitute name, (nspname,name) or name
orig --
'''
objid = _get_idstr(pyobj)
ns,n = self.get_name(name, objid)
# nillable
el = elt.createAppendElement(ns, n)
if self.nillable is True and pyobj is Nilled:
self.serialize_as_nil(el)
return None
# other attributes
self.set_attributes(el, pyobj)
# soap href attribute
unique = self.unique or kw.get('unique', False)
if unique is False and sw.Known(orig or pyobj):
self.set_attribute_href(el, objid)
return None
# xsi:type attribute
if kw.get('typed', self.typed) is True:
self.set_attribute_xsi_type(el, **kw)
# soap id attribute
if self.unique is False:
self.set_attribute_id(el, objid)
#Content, <empty tag/>c
self.serialize_text_node(el, sw, pyobj)
return el
class Any(TypeCode):
'''When the type isn't defined in the schema, but must be specified
in the incoming operation.
parsemap -- a type to class mapping (updated by descendants), for
parsing
serialmap -- same, for (outgoing) serialization
'''
logger = _GetLogger('ZSI.TC.Any')
parsemap, serialmap = {}, {}
def __init__(self, pname=None, aslist=False, minOccurs=0, **kw):
TypeCode.__init__(self, pname, minOccurs=minOccurs, **kw)
self.aslist = aslist
self.kwargs = {'aslist':aslist}
self.kwargs.update(kw)
self.unique = False
# input arg v should be a list of tuples (name, value).
def listify(self, v):
if self.aslist: return [ k for j,k in v ]
return dict(v)
def parse_into_dict_or_list(self, elt, ps):
c = _child_elements(elt)
count = len(c)
v = []
if count == 0:
href = _find_href(elt)
if not href: return v
elt = ps.FindLocalHREF(href, elt)
self.checktype(elt, ps)
c = _child_elements(elt)
count = len(c)
if count == 0: return self.listify(v)
if self.nilled(elt, ps): return Nilled
for c_elt in c:
v.append((str(c_elt.localName), self.__class__(**self.kwargs).parse(c_elt, ps)))
return self.listify(v)
def parse(self, elt, ps):
(ns,type) = self.checkname(elt, ps)
if not type and self.nilled(elt, ps): return Nilled
if len(_children(elt)) == 0:
href = _find_href(elt)
if not href:
if self.minOccurs < 1:
if _is_xsd_or_soap_ns(ns):
parser = Any.parsemap.get((None,type))
if parser: return parser.parse(elt, ps)
if ((ns,type) == (SOAP.ENC,'Array') or
(_find_arraytype(elt) or '').endswith('[0]')):
return []
return None
raise EvaluateException('Required Any missing',
ps.Backtrace(elt))
elt = ps.FindLocalHREF(href, elt)
(ns,type) = self.checktype(elt, ps)
if not type and elt.namespaceURI == SOAP.ENC:
ns,type = SOAP.ENC, elt.localName
if not type or (ns,type) == (SOAP.ENC,'Array'):
if self.aslist or _find_arraytype(elt):
return [ self.__class__(**self.kwargs).parse(e, ps)
for e in _child_elements(elt) ]
if len(_child_elements(elt)) == 0:
raise EvaluateException("Any cannot parse untyped element",
ps.Backtrace(elt))
return self.parse_into_dict_or_list(elt, ps)
parser = Any.parsemap.get((ns,type))
if not parser and _is_xsd_or_soap_ns(ns):
parser = Any.parsemap.get((None,type))
if not parser:
raise EvaluateException('''Any can't parse element''',
ps.Backtrace(elt))
return parser.parse(elt, ps)
def get_formatted_content(self, pyobj):
tc = type(pyobj)
if tc == types.InstanceType:
tc = pyobj.__class__
if hasattr(pyobj, 'typecode'):
#serializer = pyobj.typecode.serialmap.get(tc)
serializer = pyobj.typecode
else:
serializer = Any.serialmap.get(tc)
if not serializer:
tc = (types.ClassType, pyobj.__class__.__name__)
serializer = Any.serialmap.get(tc)
else:
serializer = Any.serialmap.get(tc)
if not serializer and isinstance(pyobj, time.struct_time):
from ZSI.TCtimes import gDateTime
serializer = gDateTime()
if serializer:
return serializer.get_formatted_content(pyobj)
raise EvaluateException, 'Failed to find serializer for pyobj %s' %pyobj
def serialize(self, elt, sw, pyobj, name=None, **kw):
if hasattr(pyobj, 'typecode') and pyobj.typecode is not self:
pyobj.typecode.serialize(elt, sw, pyobj, **kw)
return
objid = _get_idstr(pyobj)
ns,n = self.get_name(name, objid)
kw.setdefault('typed', self.typed)
tc = type(pyobj)
self.logger.debug('Any serialize -- %s', tc)
if tc in _seqtypes:
if self.aslist:
array = elt.createAppendElement(ns, n)
array.setAttributeType(SOAP.ENC, "Array")
array.setAttributeNS(self.nspname, 'SOAP-ENC:arrayType',
"xsd:anyType[" + str(len(pyobj)) + "]" )
for o in pyobj:
#TODO maybe this should take **self.kwargs...
serializer = getattr(o, 'typecode', self.__class__()) # also used by _AnyLax()
serializer.serialize(array, sw, o, name='element', **kw)
else:
struct = elt.createAppendElement(ns, n)
for o in pyobj:
#TODO maybe this should take **self.kwargs...
serializer = getattr(o, 'typecode', self.__class__()) # also used by _AnyLax()
serializer.serialize(struct, sw, o, **kw)
return
kw['name'] = (ns,n)
if tc == types.DictType:
el = elt.createAppendElement(ns, n)
parentNspname = self.nspname # temporarily clear nspname for dict elements
self.nspname = None
for o,m in pyobj.items():
if type(o) != types.StringType and type(o) != types.UnicodeType:
raise Exception, 'Dictionary implementation requires keys to be of type string (or unicode).' %pyobj
kw['name'] = o
kw.setdefault('typed', True)
self.serialize(el, sw, m, **kw)
# restore nspname
self.nspname = parentNspname
return
if tc == types.InstanceType:
tc = pyobj.__class__
if hasattr(pyobj, 'typecode'):
#serializer = pyobj.typecode.serialmap.get(tc)
serializer = pyobj.typecode
else:
serializer = Any.serialmap.get(tc)
if not serializer:
tc = (types.ClassType, pyobj.__class__.__name__)
serializer = Any.serialmap.get(tc)
else:
serializer = Any.serialmap.get(tc)
if not serializer and isinstance(pyobj, time.struct_time):
from ZSI.TCtimes import gDateTime
serializer = gDateTime()
if not serializer:
# Last-chance; serialize instances as dictionary
if pyobj is None:
self.serialize_as_nil(elt.createAppendElement(ns, n))
elif type(pyobj) != types.InstanceType:
raise EvaluateException('''Any can't serialize ''' + \
repr(pyobj))
else:
self.serialize(elt, sw, pyobj.__dict__, **kw)
else:
# Try to make the element name self-describing
tag = getattr(serializer, 'tag', None)
if self.pname is not None:
#serializer.nspname = self.nspname
#serializer.pname = self.pname
if "typed" not in kw:
kw['typed'] = False
elif tag:
if tag.find(':') == -1: tag = 'SOAP-ENC:' + tag
kw['name'] = tag
kw['typed'] = False
serializer.unique = self.unique
serializer.serialize(elt, sw, pyobj, **kw)
# Reset TypeCode
#serializer.nspname = None
#serializer.pname = None
class String(SimpleType):
'''A string type.
'''
empty_content = ''
parselist = [ (None,'string') ]
seriallist = [ types.StringType, types.UnicodeType ]
type = (SCHEMA.XSD3, 'string')
logger = _GetLogger('ZSI.TC.String')
def __init__(self, pname=None, strip=True, **kw):
TypeCode.__init__(self, pname, **kw)
if kw.has_key('resolver'): self.resolver = kw['resolver']
self.strip = strip
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data.
'''
if self.strip: text = text.strip()
if self.pyclass is not None:
return self.pyclass(text)
return text
def get_formatted_content(self, pyobj):
if type(pyobj) not in _stringtypes:
pyobj = str(pyobj)
if type(pyobj) == types.UnicodeType: pyobj = pyobj.encode('utf-8')
return pyobj
class URI(String):
'''A URI.
'''
parselist = [ (None,'anyURI'),(SCHEMA.XSD3, 'anyURI')]
type = (SCHEMA.XSD3, 'anyURI')
logger = _GetLogger('ZSI.TC.URI')
def text_to_data(self, text, elt, ps):
'''text --> typecode specific data.
'''
val = String.text_to_data(self, text, elt, ps)
return urldecode(val)
def get_formatted_content(self, pyobj):
'''typecode data --> text
'''
pyobj = String.get_formatted_content(self, pyobj)
return urlencode(pyobj)
class QName(String):
'''A QName type
'''
parselist = [ (None,'QName') ]
type = (SCHEMA.XSD3, 'QName')
logger = _GetLogger('ZSI.TC.QName')
def __init__(self, pname=None, strip=1, **kw):
String.__init__(self, pname, strip, **kw)
self.prefix = None
def get_formatted_content(self, pyobj):
value = pyobj
if isinstance(pyobj, tuple):
namespaceURI,localName = pyobj
if self.prefix is not None:
value = "%s:%s" %(self.prefix,localName)
return String.get_formatted_content(self, value)
def set_prefix(self, elt, pyobj):
'''use this method to set the prefix of the QName,
method looks in DOM to find prefix or set new prefix.
This method must be called before get_formatted_content.
'''
if isinstance(pyobj, tuple):
namespaceURI,localName = pyobj
self.prefix = elt.getPrefix(namespaceURI)
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data.
'''
prefix,localName = SplitQName(text)
nsdict = ps.GetElementNSdict(elt)
try:
namespaceURI = nsdict[prefix]
except KeyError, ex:
raise EvaluateException('cannot resolve prefix(%s)'%prefix,
ps.Backtrace(elt))
v = (namespaceURI,localName)
if self.pyclass is not None:
return self.pyclass(v)
return v
def serialize_text_node(self, elt, sw, pyobj):
'''Serialize without an element node.
'''
self.set_prefix(elt, pyobj)
return String.serialize_text_node(self, elt, sw, pyobj)
class Token(String):
'''an xsd:token type
'''
parselist = [ (None, 'token') ]
type = (SCHEMA.XSD3, 'token')
logger = _GetLogger('ZSI.TC.Token')
class Base64String(String):
'''A Base64 encoded string.
'''
parselist = [ (None,'base64Binary'), (SOAP.ENC, 'base64') ]
type = (SOAP.ENC, 'base64')
logger = _GetLogger('ZSI.TC.Base64String')
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data.
'''
val = b64decode(text.replace(' ', '').replace('\n','').replace('\r',''))
if self.pyclass is not None:
return self.pyclass(val)
return val
def get_formatted_content(self, pyobj):
pyobj = '\n' + b64encode(pyobj)
return String.get_formatted_content(self, pyobj)
class Base64Binary(String):
parselist = [ (None,'base64Binary'), ]
type = (SCHEMA.XSD3, 'base64Binary')
logger = _GetLogger('ZSI.TC.Base64Binary')
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data.
'''
val = b64decode(text)
if self.pyclass is not None:
return self.pyclass(val)
return val
def get_formatted_content(self, pyobj):
pyobj = b64encode(pyobj).strip()
return pyobj
class HexBinaryString(String):
'''Hex-encoded binary (yuk).
'''
parselist = [ (None,'hexBinary') ]
type = (SCHEMA.XSD3, 'hexBinary')
logger = _GetLogger('ZSI.TC.HexBinaryString')
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data.
'''
val = hexdecode(text)
if self.pyclass is not None:
return self.pyclass(val)
return val
def get_formatted_content(self, pyobj):
pyobj = hexencode(pyobj).upper()
return String.get_formatted_content(self, pyobj)
class XMLString(String):
'''A string that represents an XML document
'''
logger = _GetLogger('ZSI.TC.XMLString')
def __init__(self, pname=None, readerclass=None, **kw):
String.__init__(self, pname, **kw)
self.readerclass = readerclass
def parse(self, elt, ps):
if not self.readerclass:
from xml.dom.ext.reader import PyExpat
self.readerclass = PyExpat.Reader
v = String.parse(self, elt, ps)
return self.readerclass().fromString(v)
def get_formatted_content(self, pyobj):
pyobj = Canonicalize(pyobj)
return String.get_formatted_content(self, pyobj)
class Enumeration(String):
'''A string type, limited to a set of choices.
'''
logger = _GetLogger('ZSI.TC.Enumeration')
def __init__(self, choices, pname=None, **kw):
String.__init__(self, pname, **kw)
t = type(choices)
if t in _seqtypes:
self.choices = tuple(choices)
elif TypeCode.typechecks:
raise TypeError(
'Enumeration choices must be list or sequence, not ' + str(t))
if TypeCode.typechecks:
for c in self.choices:
if type(c) not in _stringtypes:
raise TypeError(
'Enumeration choice ' + str(c) + ' is not a string')
def parse(self, elt, ps):
val = String.parse(self, elt, ps)
if val not in self.choices:
raise EvaluateException('Value not in enumeration list',
ps.Backtrace(elt))
return val
def serialize(self, elt, sw, pyobj, name=None, orig=None, **kw):
if pyobj not in self.choices:
raise EvaluateException('Value not in enumeration list',
ps.Backtrace(elt))
String.serialize(self, elt, sw, pyobj, name=name, orig=orig, **kw)
# This is outside the Integer class purely for code esthetics.
_ignored = []
class Integer(SimpleType):
'''Common handling for all integers.
'''
ranges = {
'unsignedByte': (0, 255),
'unsignedShort': (0, 65535),
'unsignedInt': (0, 4294967295L),
'unsignedLong': (0, 18446744073709551615L),
'byte': (-128, 127),
'short': (-32768, 32767),
'int': (-2147483648L, 2147483647),
'long': (-9223372036854775808L, 9223372036854775807L),
'negativeInteger': (_ignored, -1),
'nonPositiveInteger': (_ignored, 0),
'nonNegativeInteger': (0, _ignored),
'positiveInteger': (1, _ignored),
'integer': (_ignored, _ignored)
}
parselist = [ (None,k) for k in ranges.keys() ]
seriallist = [ types.IntType, types.LongType ]
logger = _GetLogger('ZSI.TC.Integer')
def __init__(self, pname=None, format='%d', **kw):
TypeCode.__init__(self, pname, **kw)
self.format = format
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data.
'''
if self.pyclass is not None:
v = self.pyclass(text)
else:
try:
v = int(text)
except:
try:
v = long(text)
except:
raise EvaluateException('Unparseable integer',
ps.Backtrace(elt))
return v
def parse(self, elt, ps):
(ns,type) = self.checkname(elt, ps)
if self.nilled(elt, ps): return Nilled
elt = self.SimpleHREF(elt, ps, 'integer')
if not elt: return None
if type is None:
type = self.type[1]
elif self.type[1] is not None and type != self.type[1]:
raise EvaluateException('Integer type mismatch; ' \
'got %s wanted %s' % (type,self.type[1]), ps.Backtrace(elt))
v = self.simple_value(elt, ps)
v = self.text_to_data(v, elt, ps)
(rmin, rmax) = Integer.ranges.get(type, (_ignored, _ignored))
if rmin != _ignored and v < rmin:
raise EvaluateException('Underflow, less than ' + repr(rmin),
ps.Backtrace(elt))
if rmax != _ignored and v > rmax:
raise EvaluateException('Overflow, greater than ' + repr(rmax),
ps.Backtrace(elt))
return v
def get_formatted_content(self, pyobj):
return self.format %pyobj
# See credits, below.
def _make_inf():
x = 2.0
x2 = x * x
i = 0
while i < 100 and x != x2:
x = x2
x2 = x * x
i = i + 1
if x != x2:
raise ValueError("This machine's floats go on forever!")
return x
# This is outside the Decimal class purely for code esthetics.
_magicnums = { }
try:
_magicnums['INF'] = float('INF')
_magicnums['-INF'] = float('-INF')
except:
_magicnums['INF'] = _make_inf()
_magicnums['-INF'] = -_magicnums['INF']
# The following comment and code was written by Tim Peters in
# article <001401be92d2$09dcb800$5fa02299@tim> in comp.lang.python,
# also available at the following URL:
# http://groups.google.com/groups?selm=001401be92d2%2409dcb800%245fa02299%40tim
# Thanks, Tim!
# NaN-testing.
#
# The usual method (x != x) doesn't work.
# Python forces all comparisons thru a 3-outcome cmp protocol; unordered
# isn't a possible outcome. The float cmp outcome is essentially defined
# by this C expression (combining some cross-module implementation
# details, and where px and py are pointers to C double):
# px == py ? 0 : *px < *py ? -1 : *px > *py ? 1 : 0
# Comparing x to itself thus always yields 0 by the first clause, and so
# x != x is never true.
# If px and py point to distinct NaN objects, a strange thing happens:
# 1. On scrupulous 754 implementations, *px < *py returns false, and so
# does *px > *py. Python therefore returns 0, i.e. "equal"!
# 2. On Pentium HW, an unordered outcome sets an otherwise-impossible
# combination of condition codes, including both the "less than" and
# "equal to" flags. Microsoft C generates naive code that accepts
# the "less than" flag at face value, and so the *px < *py clause
# returns true, and Python returns -1, i.e. "not equal".
# So with a proper C 754 implementation Python returns the wrong result,
# and under MS's improper 754 implementation Python yields the right
# result -- both by accident. It's unclear who should be shot <wink>.
#
# Anyway, the point of all that was to convince you it's tricky getting
# the right answer in a portable way!
def isnan(x):
"""x -> true iff x is a NaN."""
# multiply by 1.0 to create a distinct object (x < x *always*
# false in Python, due to object identity forcing equality)
if x * 1.0 < x:
# it's a NaN and this is MS C on a Pentium
return 1
# Else it's non-NaN, or NaN on a non-MS+Pentium combo.
# If it's non-NaN, then x == 1.0 and x == 2.0 can't both be true,
# so we return false. If it is NaN, then assuming a good 754 C
# implementation Python maps both unordered outcomes to true.
return 1.0 == x and x == 2.0
class Decimal(SimpleType):
'''Parent class for floating-point numbers.
'''
parselist = [ (None,'decimal'), (None,'float'), (None,'double') ]
seriallist = _floattypes
type = None
ranges = {
'float': ( 7.0064923216240861E-46,
-3.4028234663852886E+38, 3.4028234663852886E+38 ),
'double': ( 2.4703282292062327E-324,
-1.7976931348623158E+308, 1.7976931348623157E+308),
}
zeropat = re.compile('[1-9]')
logger = _GetLogger('ZSI.TC.Decimal')
def __init__(self, pname=None, format='%f', **kw):
TypeCode.__init__(self, pname, **kw)
self.format = format
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data.
'''
v = text
if self.pyclass is not None:
return self.pyclass(v)
m = _magicnums.get(v)
if m: return m
try:
return float(v)
except:
raise EvaluateException('Unparseable floating point number',
ps.Backtrace(elt))
def parse(self, elt, ps):
(ns,type) = self.checkname(elt, ps)
elt = self.SimpleHREF(elt, ps, 'floating-point')
if not elt: return None
tag = getattr(self.__class__, 'type')
if tag:
if type is None:
type = tag
elif tag != (ns,type):
raise EvaluateException('Floating point type mismatch; ' \
'got (%s,%s) wanted %s' % (ns,type,tag), ps.Backtrace(elt))
# Special value?
if self.nilled(elt, ps): return Nilled
v = self.simple_value(elt, ps)
try:
fp = self.text_to_data(v, elt, ps)
except EvaluateException, ex:
ex.args.append(ps.Backtrace(elt))
raise ex
m = _magicnums.get(v)
if m:
return m
if str(fp).lower() in [ 'inf', '-inf', 'nan', '-nan' ]:
raise EvaluateException('Floating point number parsed as "' + \
str(fp) + '"', ps.Backtrace(elt))
if fp == 0 and Decimal.zeropat.search(v):
raise EvaluateException('Floating point number parsed as zero',
ps.Backtrace(elt))
(rtiny, rneg, rpos) = Decimal.ranges.get(type, (None, None, None))
if rneg and fp < 0 and fp < rneg:
raise EvaluateException('Negative underflow', ps.Backtrace(elt))
if rtiny and fp > 0 and fp < rtiny:
raise EvaluateException('Positive underflow', ps.Backtrace(elt))
if rpos and fp > 0 and fp > rpos:
raise EvaluateException('Overflow', ps.Backtrace(elt))
return fp
def get_formatted_content(self, pyobj):
if pyobj == _magicnums['INF']:
return 'INF'
elif pyobj == _magicnums['-INF']:
return '-INF'
elif isnan(pyobj):
return 'NaN'
else:
return self.format %pyobj
class Boolean(SimpleType):
'''A boolean.
'''
parselist = [ (None,'boolean') ]
seriallist = [ bool ]
type = (SCHEMA.XSD3, 'boolean')
logger = _GetLogger('ZSI.TC.Boolean')
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data.
'''
v = text
if v == 'false':
if self.pyclass is None:
return False
return self.pyclass(False)
if v == 'true':
if self.pyclass is None:
return True
return self.pyclass(True)
try:
v = int(v)
except:
try:
v = long(v)
except:
raise EvaluateException('Unparseable boolean',
ps.Backtrace(elt))
if v:
if self.pyclass is None:
return True
return self.pyclass(True)
if self.pyclass is None:
return False
return self.pyclass(False)
def parse(self, elt, ps):
self.checkname(elt, ps)
elt = self.SimpleHREF(elt, ps, 'boolean')
if not elt: return None
if self.nilled(elt, ps): return Nilled
v = self.simple_value(elt, ps).lower()
return self.text_to_data(v, elt, ps)
def get_formatted_content(self, pyobj):
if pyobj: return 'true'
return 'false'
#XXX NOT FIXED YET
class XML(TypeCode):
'''Opaque XML which shouldn't be parsed.
comments -- preserve comments
inline -- don't href/id when serializing
resolver -- object to resolve href's
wrapped -- put a wrapper element around it
'''
# Clone returned data?
copyit = 0
logger = _GetLogger('ZSI.TC.XML')
def __init__(self, pname=None, comments=0, inline=0, wrapped=True, **kw):
TypeCode.__init__(self, pname, **kw)
self.comments = comments
self.inline = inline
if kw.has_key('resolver'): self.resolver = kw['resolver']
self.wrapped = wrapped
self.copyit = kw.get('copyit', XML.copyit)
def parse(self, elt, ps):
if self.wrapped is False:
return elt
c = _child_elements(elt)
if not c:
href = _find_href(elt)
if not href:
if self.minOccurs == 0: return None
raise EvaluateException('Embedded XML document missing',
ps.Backtrace(elt))
if href[0] != '#':
return ps.ResolveHREF(href, self)
elt = ps.FindLocalHREF(href, elt)
c = _child_elements(elt)
if _find_encstyle(elt) != "":
#raise EvaluateException('Embedded XML has unknown encodingStyle',
# ps.Backtrace(elt)
pass
if len(c) != 1:
raise EvaluateException('Embedded XML has more than one child',
ps.Backtrace(elt))
if self.copyit: return c[0].cloneNode(1)
return c[0]
def serialize(self, elt, sw, pyobj, name=None, unsuppressedPrefixes=[], **kw):
if self.wrapped is False:
Canonicalize(pyobj, sw, unsuppressedPrefixes=unsuppressedPrefixes,
comments=self.comments)
return
objid = _get_idstr(pyobj)
ns,n = self.get_name(name, objid)
xmlelt = elt.createAppendElement(ns, n)
if type(pyobj) in _stringtypes:
self.set_attributes(xmlelt, pyobj)
self.set_attribute_href(xmlelt, objid)
elif kw.get('inline', self.inline):
self.cb(xmlelt, sw, pyobj, unsuppressedPrefixes)
else:
self.set_attributes(xmlelt, pyobj)
self.set_attribute_href(xmlelt, objid)
sw.AddCallback(self.cb, pyobj, unsuppressedPrefixes)
def cb(self, elt, sw, pyobj, unsuppressedPrefixes=[]):
if sw.Known(pyobj):
return
objid = _get_idstr(pyobj)
ns,n = self.get_name(name, objid)
xmlelt = elt.createAppendElement(ns, n)
self.set_attribute_id(xmlelt, objid)
xmlelt.setAttributeNS(SOAP.ENC, 'encodingStyle', '""')
Canonicalize(pyobj, sw, unsuppressedPrefixes=unsuppressedPrefixes,
comments=self.comments)
class AnyType(TypeCode):
"""XML Schema xsi:anyType type definition wildCard.
class variables:
all -- specifies use of all namespaces.
other -- specifies use of other namespaces
type --
"""
all = '#all'
other = '#other'
type = (SCHEMA.XSD3, 'anyType')
logger = _GetLogger('ZSI.TC.AnyType')
def __init__(self, pname=None, namespaces=['#all'],
minOccurs=1, maxOccurs=1, strip=1, **kw):
TypeCode.__init__(self, pname=pname, minOccurs=minOccurs,
maxOccurs=maxOccurs, **kw)
self.namespaces = namespaces
def get_formatted_content(self, pyobj):
# TODO: not sure this makes sense,
# parse side will be clueless, but oh well..
what = getattr(pyobj, 'typecode', Any())
return what.get_formatted_content(pyobj)
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data. Used only with
attributes so will not know anything about this content so
why guess?
Parameters:
text -- text content
elt -- the DOM element being parsed
ps -- the ParsedSoap object.
'''
return text
def serialize(self, elt, sw, pyobj, **kw):
nsuri,typeName = _get_xsitype(pyobj)
if self.all not in self.namespaces and nsuri not in self.namespaces:
raise EvaluateException(
'<anyType> unsupported use of namespaces "%s"' %self.namespaces)
what = getattr(pyobj, 'typecode', None)
if what is None:
# TODO: resolve this, "strict" processing but no
# concrete schema makes little sense.
#what = _AnyStrict(pname=(self.nspname,self.pname))
what = Any(pname=(self.nspname,self.pname), unique=True,
aslist=False)
kw['typed'] = True
what.serialize(elt, sw, pyobj, **kw)
return
# Namespace if element AnyType was namespaced.
what.serialize(elt, sw, pyobj,
name=(self.nspname or what.nspname, self.pname or what.pname), **kw)
def parse(self, elt, ps):
#element name must be declared ..
nspname,pname = _get_element_nsuri_name(elt)
if nspname != self.nspname or pname != self.pname:
raise EvaluateException('<anyType> instance is (%s,%s) found (%s,%s)' %(
self.nspname,self.pname,nspname,pname), ps.Backtrace(elt))
#locate xsi:type
prefix, typeName = SplitQName(_find_type(elt))
namespaceURI = _resolve_prefix(elt, prefix)
pyclass = GTD(namespaceURI, typeName)
if not pyclass:
if _is_xsd_or_soap_ns(namespaceURI):
pyclass = _AnyStrict
elif (str(namespaceURI).lower()==str(Apache.Map.type[0]).lower())\
and (str(typeName).lower() ==str(Apache.Map.type[1]).lower()):
pyclass = Apache.Map
else:
# Unknown type, so parse into a dictionary
pyobj = Any().parse_into_dict_or_list(elt, ps)
return pyobj
what = pyclass(pname=(self.nspname,self.pname))
pyobj = what.parse(elt, ps)
return pyobj
class AnyElement(AnyType):
"""XML Schema xsi:any element declaration wildCard.
class variables:
tag -- global element declaration
"""
tag = (SCHEMA.XSD3, 'any')
logger = _GetLogger('ZSI.TC.AnyElement')
def __init__(self, namespaces=['#all'],pname=None,
minOccurs=1, maxOccurs=1, strip=1, processContents='strict',
**kw):
if processContents not in ('lax', 'skip', 'strict'):
raise ValueError('processContents(%s) must be lax, skip, or strict')
self.processContents = processContents
AnyType.__init__(self, namespaces=namespaces,pname=pname,
minOccurs=minOccurs, maxOccurs=maxOccurs, strip=strip, **kw)
def serialize(self, elt, sw, pyobj, **kw):
'''Must provice typecode to AnyElement for serialization, else
try to use TC.Any to serialize instance which will serialize
based on the data type of pyobj w/o reference to XML schema
instance.
'''
if isinstance(pyobj, TypeCode):
raise TypeError, 'pyobj is a typecode instance.'
what = getattr(pyobj, 'typecode', None)
if what is not None and type(pyobj) is types.InstanceType:
tc = pyobj.__class__
what = Any.serialmap.get(tc)
if not what:
tc = (types.ClassType, pyobj.__class__.__name__)
what = Any.serialmap.get(tc)
# failed to find a registered type for class
if what is None:
#TODO: seems incomplete. what about facets.
if self.processContents == 'strict':
what = _AnyStrict(pname=(self.nspname,self.pname))
else:
what = _AnyLax(pname=(self.nspname,self.pname))
self.logger.debug('serialize with %s', what.__class__.__name__)
what.serialize(elt, sw, pyobj, **kw)
def parse(self, elt, ps):
'''
processContents -- 'lax' | 'skip' | 'strict', 'strict'
1) if 'skip' check namespaces, and return the DOM node.
2) if 'lax' look for declaration, or definition. If
not found return DOM node.
3) if 'strict' get declaration, or raise.
'''
skip = self.processContents == 'skip'
nspname,pname = _get_element_nsuri_name(elt)
what = GED(nspname, pname)
if not skip and what is not None:
pyobj = what.parse(elt, ps)
try:
pyobj.typecode = what
except AttributeError, ex:
# Assume this means builtin type.
pyobj = WrapImmutable(pyobj, what)
return pyobj
# Allow use of "<any>" element declarations w/ local
# element declarations
prefix, typeName = SplitQName(_find_type(elt))
if not skip and typeName:
namespaceURI = _resolve_prefix(elt, prefix or 'xmlns')
# First look thru user defined namespaces, if don't find
# look for 'primitives'.
pyclass = GTD(namespaceURI, typeName) or Any
what = pyclass(pname=(nspname,pname))
pyobj = what.parse(elt, ps)
try:
pyobj.typecode = what
except AttributeError, ex:
# Assume this means builtin type.
pyobj = WrapImmutable(pyobj, what)
what.typed = True
return pyobj
if skip:
what = XML(pname=(nspname,pname), wrapped=False)
elif self.processContents == 'lax':
what = _AnyLax(pname=(nspname,pname))
else:
what = _AnyStrict(pname=(nspname,pname))
try:
pyobj = what.parse(elt, ps)
except EvaluateException, ex:
self.logger.error("Give up, parse (%s,%s) as a String",
what.nspname, what.pname)
what = String(pname=(nspname,pname), typed=False)
pyobj = WrapImmutable(what.parse(elt, ps), what)
return pyobj
class Union(SimpleType):
'''simpleType Union
class variables:
memberTypes -- list [(namespace,name),] tuples, each representing a type defintion.
'''
memberTypes = None
logger = _GetLogger('ZSI.TC.Union')
def __init__(self, pname=None, minOccurs=1, maxOccurs=1, **kw):
SimpleType.__init__(self, pname=pname, minOccurs=minOccurs, maxOccurs=maxOccurs, **kw)
self.memberTypeCodes = []
def setMemberTypeCodes(self):
if len(self.memberTypeCodes) > 0:
return
if self.__class__.memberTypes is None:
raise EvaluateException, 'uninitialized class variable memberTypes [(namespace,name),]'
for nsuri,name in self.__class__.memberTypes:
tcclass = GTD(nsuri,name)
if tcclass is None:
tc = Any.parsemap.get((nsuri,name))
typecode = tc.__class__(pname=(self.nspname,self.pname))
else:
typecode = tcclass(pname=(self.nspname,self.pname))
if typecode is None:
raise EvaluateException, \
'Typecode class for Union memberType (%s,%s) is missing' %(nsuri,name)
if isinstance(typecode, Struct):
raise EvaluateException, \
'Illegal: Union memberType (%s,%s) is complexType' %(nsuri,name)
self.memberTypeCodes.append(typecode)
def parse(self, elt, ps, **kw):
'''attempt to parse sequentially. No way to know ahead of time
what this instance represents. Must be simple type so it can
not have attributes nor children, so this isn't too bad.
'''
self.setMemberTypeCodes()
(nsuri,typeName) = self.checkname(elt, ps)
#if (nsuri,typeName) not in self.memberTypes:
# raise EvaluateException(
# 'Union Type mismatch got (%s,%s) not in %s' % \
# (nsuri, typeName, self.memberTypes), ps.Backtrace(elt))
for indx in range(len(self.memberTypeCodes)):
typecode = self.memberTypeCodes[indx]
try:
pyobj = typecode.parse(elt, ps)
except ParseException, ex:
continue
except Exception, ex:
continue
if indx > 0:
self.memberTypeCodes.remove(typecode)
self.memberTypeCodes.insert(0, typecode)
break
else:
raise
return pyobj
def get_formatted_content(self, pyobj, **kw):
self.setMemberTypeCodes()
for indx in range(len(self.memberTypeCodes)):
typecode = self.memberTypeCodes[indx]
try:
content = typecode.get_formatted_content(copy.copy(pyobj))
break
except ParseException, ex:
pass
if indx > 0:
self.memberTypeCodes.remove(typecode)
self.memberTypeCodes.insert(0, typecode)
else:
raise
return content
class List(SimpleType):
'''simpleType List
Class data:
itemType -- sequence (namespaceURI,name) or a TypeCode instance
representing the type definition
'''
itemType = None
logger = _GetLogger('ZSI.TC.List')
def __init__(self, pname=None, itemType=None, **kw):
'''Currently need to require maxOccurs=1, so list
is interpreted as a single unit of data.
'''
assert kw.get('maxOccurs',1) == 1, \
'Currently only supporting SimpleType Lists with maxOccurs=1'
SimpleType.__init__(self, pname=pname, **kw)
self.itemType = itemType or self.itemType
self.itemTypeCode = self.itemType
itemTypeCode = None
if type(self.itemTypeCode) in _seqtypes:
namespaceURI,name = self.itemTypeCode
try:
itemTypeCode = GTD(*self.itemType)(None)
except:
if _is_xsd_or_soap_ns(namespaceURI) is False:
raise
for pyclass in TYPES:
if pyclass.type == self.itemTypeCode:
itemTypeCode = pyclass(None)
break
elif pyclass.type[1] == name:
itemTypeCode = pyclass(None)
if itemTypeCode is None:
raise EvaluateException('Filed to locate %s' %self.itemTypeCode)
if hasattr(itemTypeCode, 'text_to_data') is False:
raise EvaluateException('TypeCode class %s missing text_to_data method' %itemTypeCode)
self.itemTypeCode = itemTypeCode
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data. items in
list are space separated.
'''
v = []
for item in text.split(' '):
v.append(self.itemTypeCode.text_to_data(item, elt, ps))
if self.pyclass is not None:
return self.pyclass(v)
return v
def parse(self, elt, ps):
'''elt -- the DOM element being parsed
ps -- the ParsedSoap object.
'''
self.checkname(elt, ps)
if len(_children(elt)) == 0:
href = _find_href(elt)
if not href:
if self.nilled(elt, ps) is False:
# No content, no HREF, not NIL: empty string
return ""
# No content, no HREF, and is NIL...
if self.nillable is True:
return Nilled
raise EvaluateException('Required string missing',
ps.Backtrace(elt))
if href[0] != '#':
return ps.ResolveHREF(href, self)
elt = ps.FindLocalHREF(href, elt)
self.checktype(elt, ps)
if self.nilled(elt, ps): return Nilled
if len(_children(elt)) == 0: return ''
v = self.simple_value(elt, ps)
return self.text_to_data(v, elt, ps)
def serialize(self, elt, sw, pyobj, name=None, orig=None, **kw):
'''elt -- the current DOMWrapper element
sw -- soapWriter object
pyobj -- python object to serialize
'''
if type(pyobj) not in _seqtypes:
raise EvaluateException, 'expecting a list'
objid = _get_idstr(pyobj)
ns,n = self.get_name(name, objid)
el = elt.createAppendElement(ns, n)
if self.nillable is True and pyobj is None:
self.serialize_as_nil(el)
return None
tc = self.itemTypeCode
s = StringIO()
for item in pyobj:
s.write(tc.get_formatted_content(item))
s.write(' ')
el.createAppendTextNode(textNode)
class _AnyStrict(Any):
''' Handles an unspecified types when using a concrete schemas and
processContents = "strict".
'''
#WARNING: unstable
logger = _GetLogger('ZSI.TC._AnyStrict')
def __init__(self, pname=None, aslist=False, **kw):
TypeCode.__init__(self, pname=pname, **kw)
self.aslist = aslist
self.unique = True
def serialize(self, elt, sw, pyobj, name=None, **kw):
if not (type(pyobj) is dict and not self.aslist):
Any.serialize(self, elt=elt,sw=sw,pyobj=pyobj,name=name, **kw)
raise EvaluateException(
'Serializing dictionaries not implemented when processContents=\"strict\".' +
'Try as a list or use processContents=\"lax\".'
)
class _AnyLax(Any):
''' Handles unspecified types when using a concrete schemas and
processContents = "lax".
'''
logger = _GetLogger('ZSI.TC._AnyLax')
def __init__(self, pname=None, aslist=False, **kw):
TypeCode.__init__(self, pname=pname, **kw)
self.aslist = aslist
self.unique = True
def parse_into_dict_or_list(self, elt, ps):
c = _child_elements(elt)
count = len(c)
v = []
if count == 0:
href = _find_href(elt)
if not href: return {}
elt = ps.FindLocalHREF(href, elt)
self.checktype(elt, ps)
c = _child_elements(elt)
count = len(c)
if count == 0: return self.listify([])
if self.nilled(elt, ps): return Nilled
# group consecutive elements with the same name together
# We treat consecutive elements with the same name as lists.
groupedElements = [] # tuples of (name, elementList)
previousName = ""
currentElementList = None
for ce in _child_elements(elt):
name = ce.localName
if (name != previousName): # new name, so new group
if currentElementList != None: # store previous group if there is one
groupedElements.append( (previousName, currentElementList) )
currentElementList = list()
currentElementList.append(ce) # append to list
previousName = name
# add the last group if necessary
if currentElementList != None: # store previous group if there is one
groupedElements.append( (previousName, currentElementList) )
# parse the groups of names
if len(groupedElements) < 1: # should return earlier
return None
# return a list if there is one name and multiple data
elif (len(groupedElements) == 1) and (len(groupedElements[0][0]) > 1):
self.aslist = False
# else return a dictionary
for name,eltList in groupedElements:
lst = []
for elt in eltList:
#aslist = self.aslist
lst.append( self.parse(elt, ps) )
#self.aslist = aslist # restore the aslist setting
if len(lst) > 1: # consecutive elements with the same name means a list
v.append( (name, lst) )
elif len(lst) == 1:
v.append( (name, lst[0]) )
return self.listify(v)
def checkname(self, elt, ps):
'''See if the name and type of the "elt" element is what we're
looking for. Return the element's type.
Since this is _AnyLax, it's ok if names don't resolve.
'''
parselist,errorlist = self.get_parse_and_errorlist()
ns, name = _get_element_nsuri_name(elt)
if ns == SOAP.ENC:
if parselist and \
(None, name) not in parselist and (ns, name) not in parselist:
raise EvaluateException(
'Element mismatch (got %s wanted %s) (SOAP encoding namespace)' % \
(name, errorlist), ps.Backtrace(elt))
return (ns, name)
# Not a type, check name matches.
if self.nspname and ns != self.nspname:
raise EvaluateException('Element NS mismatch (got %s wanted %s)' % \
(ns, self.nspname), ps.Backtrace(elt))
return self.checktype(elt, ps)
def RegisterType(C, clobber=0, *args, **keywords):
instance = apply(C, args, keywords)
for t in C.__dict__.get('parselist', []):
prev = Any.parsemap.get(t)
if prev:
if prev.__class__ == C: continue
if not clobber:
raise TypeError(
str(C) + ' duplicating parse registration for ' + str(t))
Any.parsemap[t] = instance
for t in C.__dict__.get('seriallist', []):
ti = type(t)
if ti in [ types.TypeType, types.ClassType]:
key = t
elif ti in _stringtypes:
key = (types.ClassType, t)
else:
raise TypeError(str(t) + ' is not a class name')
prev = Any.serialmap.get(key)
if prev:
if prev.__class__ == C: continue
if not clobber:
raise TypeError(
str(C) + ' duplicating serial registration for ' + str(t))
Any.serialmap[key] = instance
from TCnumbers import *
from TCtimes import *
from schema import GTD, GED, WrapImmutable
from TCcompound import *
from TCapache import *
# aliases backwards compatiblity
_get_type_definition, _get_global_element_declaration, Wrap = GTD, GED, WrapImmutable
f = lambda x: type(x) == types.ClassType and issubclass(x, TypeCode) and getattr(x, 'type', None) is not None
TYPES = filter(f, map(lambda y:eval(y),dir()))
if __name__ == '__main__': print _copyright | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/ZSI/TC.py | TC.py |
import time, urlparse, socket
from ZSI import _seqtypes, EvaluateException, WSActionException
from TC import AnyElement, AnyType, TypeCode
from schema import GED, GTD, _has_type_definition
from ZSI.TCcompound import ComplexType
from ZSI.wstools.Namespaces import WSA_LIST
class Address(object):
'''WS-Address
Implemented is dependent on the default "wsdl2py" convention of generating aname,
so the attributes representing element declaration names should be prefixed with
an underscore.
'''
def __init__(self, addressTo=None, wsAddressURI=None, action=None):
self.wsAddressURI = wsAddressURI
self.anonymousURI = None
self._addressTo = addressTo
self._messageID = None
self._action = action
self._endPointReference = None
self._replyTo = None
self._relatesTo = None
self.setUp()
def setUp(self):
'''Look for WS-Address
'''
toplist = filter(lambda wsa: wsa.ADDRESS==self.wsAddressURI, WSA_LIST)
epr = 'EndpointReferenceType'
for WSA in toplist+WSA_LIST:
if (self.wsAddressURI is not None and self.wsAddressURI != WSA.ADDRESS) or \
_has_type_definition(WSA.ADDRESS, epr) is True:
break
else:
raise EvaluateException,\
'enabling wsAddressing requires the inclusion of that namespace'
self.wsAddressURI = WSA.ADDRESS
self.anonymousURI = WSA.ANONYMOUS
self._replyTo = WSA.ANONYMOUS
def _checkAction(self, action, value):
'''WS-Address Action
action -- Action value expecting.
value -- Action value server returned.
'''
if action is None:
raise WSActionException, 'User did not specify WSAddress Action value to expect'
if not value:
raise WSActionException, 'missing WSAddress Action, expecting %s' %action
if value != action:
raise WSActionException, 'wrong WSAddress Action(%s), expecting %s'%(value,action)
def _checkFrom(self, pyobj):
'''WS-Address From,
XXX currently not checking the hostname, not forwarding messages.
pyobj -- From server returned.
'''
if pyobj is None: return
value = pyobj._Address
if value != self._addressTo:
scheme,netloc,path,query,fragment = urlparse.urlsplit(value)
hostport = netloc.split(':')
schemeF,netlocF,pathF,queryF,fragmentF = urlparse.urlsplit(self._addressTo)
if scheme==schemeF and path==pathF and query==queryF and fragment==fragmentF:
netloc = netloc.split(':') + ['80']
netlocF = netlocF.split(':') + ['80']
if netloc[1]==netlocF[1] and \
socket.gethostbyname(netloc[0])==socket.gethostbyname(netlocF[0]):
return
raise WSActionException, 'wrong WS-Address From(%s), expecting %s'%(value,self._addressTo)
def _checkRelatesTo(self, value):
'''WS-Address From
value -- From server returned.
'''
if value != self._messageID:
raise WSActionException, 'wrong WS-Address RelatesTo(%s), expecting %s'%(value,self._messageID)
def _checkReplyTo(self, value):
'''WS-Address From
value -- From server returned in wsa:To
'''
if value != self._replyTo:
raise WSActionException, 'wrong WS-Address ReplyTo(%s), expecting %s'%(value,self._replyTo)
def setAction(self, action):
self._action = action
def getAction(self):
return self._action
def getRelatesTo(self):
return self._relatesTo
def getMessageID(self):
return self._messageID
def _getWSAddressTypeCodes(self, **kw):
'''kw -- namespaceURI keys with sequence of element names.
'''
typecodes = []
try:
for nsuri,elements in kw.items():
for el in elements:
typecode = GED(nsuri, el)
if typecode is None:
raise WSActionException, 'Missing namespace, import "%s"' %nsuri
typecodes.append(typecode)
else:
pass
except EvaluateException, ex:
raise EvaluateException, \
'To use ws-addressing register typecodes for namespace(%s)' %self.wsAddressURI
return typecodes
def checkResponse(self, ps, action):
'''
ps -- ParsedSoap
action -- ws-action for response
'''
namespaceURI = self.wsAddressURI
d = {namespaceURI:("MessageID","Action","To","From","RelatesTo")}
typecodes = self._getWSAddressTypeCodes(**d)
pyobjs = ps.ParseHeaderElements(typecodes)
got_action = pyobjs.get((namespaceURI,"Action"))
self._checkAction(got_action, action)
From = pyobjs.get((namespaceURI,"From"))
self._checkFrom(From)
RelatesTo = pyobjs.get((namespaceURI,"RelatesTo"))
self._checkRelatesTo(RelatesTo)
To = pyobjs.get((namespaceURI,"To"))
if To: self._checkReplyTo(To)
def setRequest(self, endPointReference, action):
'''Call For Request
'''
self._action = action
self.header_pyobjs = None
pyobjs = []
namespaceURI = self.wsAddressURI
addressTo = self._addressTo
messageID = self._messageID = "uuid:%s" %time.time()
# Set Message Information Headers
# MessageID
typecode = GED(namespaceURI, "MessageID")
pyobjs.append(typecode.pyclass(messageID))
# Action
typecode = GED(namespaceURI, "Action")
pyobjs.append(typecode.pyclass(action))
# To
typecode = GED(namespaceURI, "To")
pyobjs.append(typecode.pyclass(addressTo))
# From
typecode = GED(namespaceURI, "From")
mihFrom = typecode.pyclass()
mihFrom._Address = self.anonymousURI
pyobjs.append(mihFrom)
if endPointReference:
if hasattr(endPointReference, 'typecode') is False:
raise EvaluateException, 'endPointReference must have a typecode attribute'
if isinstance(endPointReference.typecode, \
GTD(namespaceURI ,'EndpointReferenceType')) is False:
raise EvaluateException, 'endPointReference must be of type %s' \
%GTD(namespaceURI ,'EndpointReferenceType')
ReferenceProperties = endPointReference._ReferenceProperties
any = ReferenceProperties._any or []
#if not (what.maxOccurs=='unbounded' and type(any) in _seqtypes):
# raise EvaluateException, 'ReferenceProperties <any> assumed maxOccurs unbounded'
for v in any:
if not hasattr(v,'typecode'):
raise EvaluateException, '<any> element, instance missing typecode attribute'
pyobjs.append(v)
#pyobjs.append(v)
self.header_pyobjs = tuple(pyobjs)
def setResponseFromWSAddress(self, address, localURL):
'''Server-side has to set these fields in response.
address -- Address instance, representing a WS-Address
'''
self.From = localURL
self.header_pyobjs = None
pyobjs = []
namespaceURI = self.wsAddressURI
for nsuri,name,value in (\
(namespaceURI, "Action", self._action),
(namespaceURI, "MessageID","uuid:%s" %time.time()),
(namespaceURI, "RelatesTo", address.getMessageID()),
(namespaceURI, "To", self.anonymousURI),):
typecode = GED(nsuri, name)
pyobjs.append(typecode.pyclass(value))
typecode = GED(nsuri, "From")
pyobj = typecode.pyclass()
pyobj._Address = self.From
pyobjs.append(pyobj)
self.header_pyobjs = tuple(pyobjs)
def serialize(self, sw, **kw):
'''
sw -- SoapWriter instance, add WS-Address header.
'''
for pyobj in self.header_pyobjs:
if hasattr(pyobj, 'typecode') is False:
raise RuntimeError, 'all header pyobjs must have a typecode attribute'
sw.serialize_header(pyobj, **kw)
def parse(self, ps, **kw):
'''
ps -- ParsedSoap instance
'''
namespaceURI = self.wsAddressURI
elements = ("MessageID","Action","To","From","RelatesTo")
d = {namespaceURI:elements}
typecodes = self._getWSAddressTypeCodes(**d)
pyobjs = ps.ParseHeaderElements(typecodes)
self._messageID = pyobjs[(namespaceURI,elements[0])]
self._action = pyobjs[(namespaceURI,elements[1])]
self._addressTo = pyobjs[(namespaceURI,elements[2])]
self._from = pyobjs[(namespaceURI,elements[3])]
self._relatesTo = pyobjs[(namespaceURI,elements[4])]
# TODO: Remove MessageContainer. Hopefully the new <any> functionality
# makes this irrelevant. But could create an Interop problem.
"""
class MessageContainer:
'''Automatically wraps all primitive types so attributes
can be specified.
'''
class IntHolder(int): pass
class StrHolder(str): pass
class UnicodeHolder(unicode): pass
class LongHolder(long): pass
class FloatHolder(float): pass
class BoolHolder(int): pass
#class TupleHolder(tuple): pass
#class ListHolder(list): pass
typecode = None
pyclass_list = [IntHolder,StrHolder,UnicodeHolder,LongHolder,
FloatHolder,BoolHolder,]
def __setattr__(self, key, value):
'''wrap all primitives with Holders if present.
'''
if type(value) in _seqtypes:
value = list(value)
for indx in range(len(value)):
try:
item = self._wrap(value[indx])
except TypeError, ex:
pass
else:
value[indx] = item
elif type(value) is bool:
value = BoolHolder(value)
else:
try:
value = self._wrap(value)
except TypeError, ex:
pass
self.__dict__[key] = value
def _wrap(self, value):
'''wrap primitive, return None
'''
if value is None:
return value
for pyclass in self.pyclass_list:
if issubclass(value.__class__, pyclass): break
else:
raise TypeError, 'MessageContainer does not know about type %s' %(type(value))
return pyclass(value)
def setUp(self, typecode=None, pyclass=None):
'''set up all attribute names (aname) in this python instance.
If what is a ComplexType or a simpleType w/attributes instantiate
a new MessageContainer, else set attribute aname to None.
'''
if typecode is None:
typecode = self.typecode
else:
self.typecode = typecode
if not isinstance(typecode, TypeCode):
raise TypeError, 'typecode must be a TypeCode class instance'
if isinstance(typecode, ComplexType):
if typecode.has_attributes() is True:
setattr(self, typecode.attrs_aname, {})
if typecode.mixed is True:
setattr(self, typecode.mixed_aname, None)
for what in typecode.ofwhat:
setattr(self, what.aname, None)
if isinstance(what, ComplexType):
setattr(self, what.aname, MessageContainer())
getattr(self, what.aname).setUp(typecode=what)
else:
raise TypeError, 'Primitive type'
"""
if __name__ == '__main__': print _copyright | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/ZSI/address.py | address.py |
'''Typecodes for numbers.
'''
import types
from ZSI import _copyright, _inttypes, _floattypes, _seqtypes, \
EvaluateException
from ZSI.TC import TypeCode, Integer, Decimal
from ZSI.wstools.Namespaces import SCHEMA
class IunsignedByte(Integer):
'''Unsigned 8bit value.
'''
type = (SCHEMA.XSD3, "unsignedByte")
parselist = [ (None, "unsignedByte") ]
seriallist = [ ]
class IunsignedShort(Integer):
'''Unsigned 16bit value.
'''
type = (SCHEMA.XSD3, "unsignedShort")
parselist = [ (None, "unsignedShort") ]
seriallist = [ ]
class IunsignedInt(Integer):
'''Unsigned 32bit value.
'''
type = (SCHEMA.XSD3, "unsignedInt")
parselist = [ (None, "unsignedInt") ]
seriallist = [ ]
class IunsignedLong(Integer):
'''Unsigned 64bit value.
'''
type = (SCHEMA.XSD3, "unsignedLong")
parselist = [ (None, "unsignedLong") ]
seriallist = [ ]
class Ibyte(Integer):
'''Signed 8bit value.
'''
type = (SCHEMA.XSD3, "byte")
parselist = [ (None, "byte") ]
seriallist = [ ]
class Ishort(Integer):
'''Signed 16bit value.
'''
type = (SCHEMA.XSD3, "short")
parselist = [ (None, "short") ]
seriallist = [ ]
class Iint(Integer):
'''Signed 32bit value.
'''
type = (SCHEMA.XSD3, "int")
parselist = [ (None, "int") ]
seriallist = [ types.IntType ]
class Ilong(Integer):
'''Signed 64bit value.
'''
type = (SCHEMA.XSD3, "long")
parselist = [(None, "long")]
seriallist = [ types.LongType ]
class InegativeInteger(Integer):
'''Value less than zero.
'''
type = (SCHEMA.XSD3, "negativeInteger")
parselist = [ (None, "negativeInteger") ]
seriallist = [ ]
class InonPositiveInteger(Integer):
'''Value less than or equal to zero.
'''
type = (SCHEMA.XSD3, "nonPositiveInteger")
parselist = [ (None, "nonPositiveInteger") ]
seriallist = [ ]
class InonNegativeInteger(Integer):
'''Value greater than or equal to zero.
'''
type = (SCHEMA.XSD3, "nonNegativeInteger")
parselist = [ (None, "nonNegativeInteger") ]
seriallist = [ ]
class IpositiveInteger(Integer):
'''Value greater than zero.
'''
type = (SCHEMA.XSD3, "positiveInteger")
parselist = [ (None, "positiveInteger") ]
seriallist = [ ]
class Iinteger(Integer):
'''Integer value.
'''
type = (SCHEMA.XSD3, "integer")
parselist = [ (None, "integer") ]
seriallist = [ ]
class IEnumeration(Integer):
'''Integer value, limited to a specified set of values.
'''
def __init__(self, choices, pname=None, **kw):
Integer.__init__(self, pname, **kw)
self.choices = choices
t = type(choices)
if t in _seqtypes:
self.choices = tuple(choices)
elif TypeCode.typechecks:
raise TypeError(
'Enumeration choices must be list or sequence, not ' + str(t))
if TypeCode.typechecks:
for c in self.choices:
if type(c) not in _inttypes:
raise TypeError('Enumeration choice "' +
str(c) + '" is not an integer')
def parse(self, elt, ps):
val = Integer.parse(self, elt, ps)
if val not in self.choices:
raise EvaluateException('Value "' + str(val) + \
'" not in enumeration list',
ps.Backtrace(elt))
return val
def serialize(self, elt, sw, pyobj, name=None, orig=None, **kw):
if pyobj not in self.choices:
raise EvaluateException('Value not in int enumeration list',
ps.Backtrace(elt))
Integer.serialize(self, elt, sw, pyobj, name=name, orig=orig, **kw)
class FPfloat(Decimal):
'''IEEE 32bit floating point value.
'''
type = (SCHEMA.XSD3, "float")
parselist = [ (None, "float") ]
seriallist = [ types.FloatType ]
class FPdouble(Decimal):
'''IEEE 64bit floating point value.
'''
type = (SCHEMA.XSD3, "double")
parselist = [ (None, "double") ]
seriallist = [ ]
class FPEnumeration(FPfloat):
'''Floating point value, limited to a specified set of values.
'''
def __init__(self, choices, pname=None, **kw):
FPfloat.__init__(self, pname, **kw)
self.choices = choices
t = type(choices)
if t in _seqtypes:
self.choices = tuple(choices)
elif TypeCode.typechecks:
raise TypeError(
'Enumeration choices must be list or sequence, not ' + str(t))
if TypeCode.typechecks:
for c in self.choices:
if type(c) not in _floattypes:
raise TypeError('Enumeration choice "' +
str(c) + '" is not floating point number')
def parse(self, elt, ps):
val = Decimal.parse(self, elt, ps)
if val not in self.choices:
raise EvaluateException('Value "' + str(val) + \
'" not in enumeration list',
ps.Backtrace(elt))
return val
def serialize(self, elt, sw, pyobj, name=None, orig=None, **kw):
if pyobj not in self.choices:
raise EvaluateException('Value not in int enumeration list',
ps.Backtrace(elt))
Decimal.serialize(self, elt, sw, pyobj, name=name, orig=orig, **kw)
if __name__ == '__main__': print _copyright | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/ZSI/TCnumbers.py | TCnumbers.py |
from md5 import md5
import random
import time
import httplib
random.seed(int(time.time()*10))
def H(val):
return md5(val).hexdigest()
def KD(secret,data):
return H('%s:%s' % (secret,data))
def A1(username,realm,passwd,nonce=None,cnonce=None):
if nonce and cnonce:
return '%s:%s:%s:%s:%s' % (username,realm,passwd,nonce,cnonce)
else:
return '%s:%s:%s' % (username,realm,passwd)
def A2(method,uri):
return '%s:%s' % (method,uri)
def dict_fetch(d,k,defval=None):
if d.has_key(k):
return d[k]
return defval
def generate_response(chaldict,uri,username,passwd,method='GET',cnonce=None):
"""
Generate an authorization response dictionary. chaldict should contain the digest
challenge in dict form. Use fetch_challenge to create a chaldict from a HTTPResponse
object like this: fetch_challenge(res.getheaders()).
returns dict (the authdict)
Note. Use build_authorization_arg() to turn an authdict into the final Authorization
header value.
"""
authdict = {}
qop = dict_fetch(chaldict,'qop')
domain = dict_fetch(chaldict,'domain')
nonce = dict_fetch(chaldict,'nonce')
stale = dict_fetch(chaldict,'stale')
algorithm = dict_fetch(chaldict,'algorithm','MD5')
realm = dict_fetch(chaldict,'realm','MD5')
opaque = dict_fetch(chaldict,'opaque')
nc = "00000001"
if not cnonce:
cnonce = H(str(random.randint(0,10000000)))[:16]
if algorithm.lower()=='md5-sess':
a1 = A1(username,realm,passwd,nonce,cnonce)
else:
a1 = A1(username,realm,passwd)
a2 = A2(method,uri)
secret = H(a1)
data = '%s:%s:%s:%s:%s' % (nonce,nc,cnonce,qop,H(a2))
authdict['username'] = '"%s"' % username
authdict['realm'] = '"%s"' % realm
authdict['nonce'] = '"%s"' % nonce
authdict['uri'] = '"%s"' % uri
authdict['response'] = '"%s"' % KD(secret,data)
authdict['qop'] = '"%s"' % qop
authdict['nc'] = nc
authdict['cnonce'] = '"%s"' % cnonce
return authdict
def fetch_challenge(http_header):
"""
Create a challenge dictionary from a HTTPResponse objects getheaders() method.
"""
chaldict = {}
vals = http_header.split(' ')
chaldict['challenge'] = vals[0]
for val in vals[1:]:
try:
a,b = val.split('=')
b=b.replace('"','')
b=b.replace("'",'')
b=b.replace(",",'')
chaldict[a.lower()] = b
except:
pass
return chaldict
def build_authorization_arg(authdict):
"""
Create an "Authorization" header value from an authdict (created by generate_response()).
"""
vallist = []
for k in authdict.keys():
vallist += ['%s=%s' % (k,authdict[k])]
return 'Digest '+', '.join(vallist)
if __name__ == '__main__': print _copyright | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/ZSI/digest_auth.py | digest_auth.py |
from ZSI import _copyright, _seqtypes, _find_type, EvaluateException
from ZSI.wstools.Namespaces import SCHEMA, SOAP
from ZSI.wstools.Utility import SplitQName
def _get_type_definition(namespaceURI, name, **kw):
return SchemaInstanceType.getTypeDefinition(namespaceURI, name, **kw)
def _get_global_element_declaration(namespaceURI, name, **kw):
return SchemaInstanceType.getElementDeclaration(namespaceURI, name, **kw)
def _get_substitute_element(elt, what):
raise NotImplementedError, 'Not implemented'
def _has_type_definition(namespaceURI, name):
return SchemaInstanceType.getTypeDefinition(namespaceURI, name) is not None
#
# functions for retrieving schema items from
# the global schema instance.
#
GED = _get_global_element_declaration
GTD = _get_type_definition
def WrapImmutable(pyobj, what):
'''Wrap immutable instance so a typecode can be
set, making it self-describing ie. serializable.
'''
return _GetPyobjWrapper.WrapImmutable(pyobj, what)
def RegisterBuiltin(arg):
'''Add a builtin to be registered, and register it
with the Any typecode.
'''
_GetPyobjWrapper.RegisterBuiltin(arg)
_GetPyobjWrapper.RegisterAnyElement()
def RegisterAnyElement():
'''register all Wrapper classes with the Any typecode.
This allows instances returned by Any to be self-describing.
ie. serializable. AnyElement falls back on Any to parse
anything it doesn't understand.
'''
return _GetPyobjWrapper.RegisterAnyElement()
class SchemaInstanceType(type):
'''Register all types/elements, when hit already defined
class dont create a new one just give back reference. Thus
import order determines which class is loaded.
class variables:
types -- dict of typecode classes definitions
representing global type definitions.
elements -- dict of typecode classes representing
global element declarations.
element_typecode_cache -- dict of typecode instances
representing global element declarations.
'''
types = {}
elements = {}
element_typecode_cache = {}
def __new__(cls,classname,bases,classdict):
'''If classdict has literal and schema register it as a
element declaration, else if has type and schema register
it as a type definition.
'''
if classname in ['ElementDeclaration', 'TypeDefinition', 'LocalElementDeclaration',]:
return type.__new__(cls,classname,bases,classdict)
if ElementDeclaration in bases:
if classdict.has_key('schema') is False or classdict.has_key('literal') is False:
raise AttributeError, 'ElementDeclaration must define schema and literal attributes'
key = (classdict['schema'],classdict['literal'])
if SchemaInstanceType.elements.has_key(key) is False:
SchemaInstanceType.elements[key] = type.__new__(cls,classname,bases,classdict)
return SchemaInstanceType.elements[key]
if TypeDefinition in bases:
if classdict.has_key('type') is None:
raise AttributeError, 'TypeDefinition must define type attribute'
key = classdict['type']
if SchemaInstanceType.types.has_key(key) is False:
SchemaInstanceType.types[key] = type.__new__(cls,classname,bases,classdict)
return SchemaInstanceType.types[key]
if LocalElementDeclaration in bases:
return type.__new__(cls,classname,bases,classdict)
raise TypeError, 'SchemaInstanceType must be an ElementDeclaration or TypeDefinition '
def getTypeDefinition(cls, namespaceURI, name, lazy=False):
'''Grab a type definition, returns a typecode class definition
because the facets (name, minOccurs, maxOccurs) must be provided.
Parameters:
namespaceURI --
name --
'''
klass = cls.types.get((namespaceURI, name), None)
if lazy and klass is not None:
return _Mirage(klass)
return klass
getTypeDefinition = classmethod(getTypeDefinition)
def getElementDeclaration(cls, namespaceURI, name, isref=False, lazy=False):
'''Grab an element declaration, returns a typecode instance
representation or a typecode class definition. An element
reference has its own facets, and is local so it will not be
cached.
Parameters:
namespaceURI --
name --
isref -- if element reference, return class definition.
'''
key = (namespaceURI, name)
if isref:
klass = cls.elements.get(key,None)
if klass is not None and lazy is True:
return _Mirage(klass)
return klass
typecode = cls.element_typecode_cache.get(key, None)
if typecode is None:
tcls = cls.elements.get(key,None)
if tcls is not None:
typecode = cls.element_typecode_cache[key] = tcls()
typecode.typed = False
return typecode
getElementDeclaration = classmethod(getElementDeclaration)
class ElementDeclaration:
'''Typecodes subclass to represent a Global Element Declaration by
setting class variables schema and literal.
schema = namespaceURI
literal = NCName
'''
__metaclass__ = SchemaInstanceType
class LocalElementDeclaration:
'''Typecodes subclass to represent a Local Element Declaration.
'''
__metaclass__ = SchemaInstanceType
class TypeDefinition:
'''Typecodes subclass to represent a Global Type Definition by
setting class variable type.
type = (namespaceURI, NCName)
'''
__metaclass__ = SchemaInstanceType
def getSubstituteType(self, elt, ps):
'''if xsi:type does not match the instance type attr,
check to see if it is a derived type substitution.
DONT Return the element's type.
Parameters:
elt -- the DOM element being parsed
ps -- the ParsedSoap object.
'''
pyclass = SchemaInstanceType.getTypeDefinition(*self.type)
if pyclass is None:
raise EvaluateException(
'No Type registed for xsi:type=(%s, %s)' %
(self.type[0], self.type[1]), ps.Backtrace(elt))
typeName = _find_type(elt)
prefix,typeName = SplitQName(typeName)
uri = ps.GetElementNSdict(elt).get(prefix)
subclass = SchemaInstanceType.getTypeDefinition(uri, typeName)
if subclass is None:
raise EvaluateException(
'No registered xsi:type=(%s, %s), substitute for xsi:type=(%s, %s)' %
(uri, typeName, self.type[0], self.type[1]), ps.Backtrace(elt))
if not issubclass(subclass, pyclass) and subclass(None) and not issubclass(subclass, pyclass):
raise TypeError(
'Substitute Type (%s, %s) is not derived from %s' %
(self.type[0], self.type[1], pyclass), ps.Backtrace(elt))
return subclass((self.nspname, self.pname))
class _Mirage:
'''Used with SchemaInstanceType for lazy evaluation, eval during serialize or
parse as needed. Mirage is callable, TypeCodes are not. When called it returns the
typecode. Tightly coupled with generated code.
NOTE: **Must Use ClassType** for intended MRO of __call__ since setting it in
an instance attribute rather than a class attribute (will not work for object).
'''
def __init__(self, klass):
self.klass = klass
self.__reveal = False
self.__cache = None
if issubclass(klass, ElementDeclaration):
self.__call__ = self._hide_element
def __str__(self):
msg = "<Mirage id=%s, Local Element %s>"
if issubclass(self.klass, ElementDeclaration):
msg = "<Mirage id=%s, GED %s>"
return msg %(id(self), self.klass)
def _hide_type(self, pname, aname, minOccurs=0, maxOccurs=1, nillable=False,
**kw):
self.__call__ = self._reveal_type
self.__reveal = True
# store all attributes, make some visable for pyclass_type
self.__kw = kw
self.minOccurs,self.maxOccurs,self.nillable = minOccurs,maxOccurs,nillable
self.nspname,self.pname,self.aname = None,pname,aname
if type(self.pname) in (tuple,list):
self.nspname,self.pname = pname
return self
def _hide_element(self, minOccurs=0, maxOccurs=1, nillable=False, **kw):
self.__call__ = self._reveal_element
self.__reveal = True
# store all attributes, make some visable for pyclass_type
self.__kw = kw
self.nspname = self.klass.schema
self.pname = self.klass.literal
#TODO: Fix hack
#self.aname = '_%s' %self.pname
self.minOccurs,self.maxOccurs,self.nillable = minOccurs,maxOccurs,nillable
return self
def _reveal_type(self):
if self.__cache is None:
self.__cache = self.klass(pname=self.pname,
aname=self.aname, minOccurs=self.minOccurs,
maxOccurs=self.maxOccurs, nillable=self.nillable,
**self.__kw)
return self.__cache
def _reveal_element(self):
if self.__cache is None:
self.__cache = self.klass(minOccurs=self.minOccurs,
maxOccurs=self.maxOccurs, nillable=self.nillable,
**self.__kw)
return self.__cache
__call__ = _hide_type
class _GetPyobjWrapper:
'''Get a python object that wraps data and typecode. Used by
<any> parse routine, so that typecode information discovered
during parsing is retained in the pyobj representation
and thus can be serialized.
'''
types_dict = {}
def RegisterBuiltin(cls, arg):
'''register a builtin, create a new wrapper.
'''
if arg in cls.types_dict:
raise RuntimeError, '%s already registered' %arg
class _Wrapper(arg):
'Wrapper for builtin %s\n%s' %(arg, cls.__doc__)
_Wrapper.__name__ = '_%sWrapper' %arg.__name__
cls.types_dict[arg] = _Wrapper
RegisterBuiltin = classmethod(RegisterBuiltin)
def RegisterAnyElement(cls):
'''If find registered TypeCode instance, add Wrapper class
to TypeCode class serialmap and Re-RegisterType. Provides
Any serialzation of any instances of the Wrapper.
'''
for k,v in cls.types_dict.items():
what = Any.serialmap.get(k)
if what is None: continue
if v in what.__class__.seriallist: continue
what.__class__.seriallist.append(v)
RegisterType(what.__class__, clobber=1, **what.__dict__)
RegisterAnyElement = classmethod(RegisterAnyElement)
def WrapImmutable(cls, pyobj, what):
'''return a wrapper for pyobj, with typecode attribute set.
Parameters:
pyobj -- instance of builtin type (immutable)
what -- typecode describing the data
'''
d = cls.types_dict
if type(pyobj) is bool:
pyclass = d[int]
elif d.has_key(type(pyobj)) is True:
pyclass = d[type(pyobj)]
else:
raise TypeError,\
'Expecting a built-in type in %s (got %s).' %(
d.keys(),type(pyobj))
newobj = pyclass(pyobj)
newobj.typecode = what
return newobj
WrapImmutable = classmethod(WrapImmutable)
from TC import Any, RegisterType
if __name__ == '__main__': print _copyright | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/ZSI/schema.py | schema.py |
from ZSI.wstools.Utility import SplitQName
from ZSI.wstools.Namespaces import WSDL
from ZSI import *
from ZSI.client import *
from ZSI.TC import Any
from ZSI.typeinterpreter import BaseTypeInterpreter
import wstools
from wstools.Utility import DOM
from urlparse import urlparse
import weakref
class ServiceProxy:
"""A ServiceProxy provides a convenient way to call a remote web
service that is described with WSDL. The proxy exposes methods
that reflect the methods of the remote web service."""
def __init__(self, wsdl, service=None, port=None, tracefile=None,
nsdict=None, transdict=None):
"""
Parameters:
wsdl -- WSDLTools.WSDL instance or URL of WSDL.
service -- service name or index
port -- port name or index
tracefile --
nsdict -- key prefix to namespace mappings for serialization
in SOAP Envelope.
transdict -- arguments to pass into HTTPConnection constructor.
"""
self._tracefile = tracefile
self._nsdict = nsdict or {}
self._transdict = transdict
self._wsdl = wsdl
if isinstance(wsdl, basestring) is True:
self._wsdl = wstools.WSDLTools.WSDLReader().loadFromURL(wsdl)
assert isinstance(self._wsdl, wstools.WSDLTools.WSDL), 'expecting a WSDL instance'
self._service = self._wsdl.services[service or 0]
self.__doc__ = self._service.documentation
self._port = self._service.ports[port or 0]
self._name = self._service.name
self._methods = {}
binding = self._port.getBinding()
portType = binding.getPortType()
for port in self._service.ports:
for item in port.getPortType().operations:
callinfo = wstools.WSDLTools.callInfoFromWSDL(port, item.name)
method = MethodProxy(self, callinfo)
setattr(self, item.name, method)
self._methods.setdefault(item.name, []).append(method)
def _call(self, name, *args, **kwargs):
"""Call the named remote web service method."""
if len(args) and len(kwargs):
raise TypeError(
'Use positional or keyword argument only.'
)
callinfo = getattr(self, name).callinfo
# go through the list of defined methods, and look for the one with
# the same number of arguments as what was passed. this is a weak
# check that should probably be improved in the future to check the
# types of the arguments to allow for polymorphism
for method in self._methods[name]:
if len(method.callinfo.inparams) == len(kwargs):
callinfo = method.callinfo
soapAction = callinfo.soapAction
url = callinfo.location
(protocol, host, uri, query, fragment, identifier) = urlparse(url)
port = None
if host.find(':') >= 0:
host, port = host.split(':')
if protocol == 'http':
transport = httplib.HTTPConnection
elif protocol == 'https':
transport = httplib.HTTPSConnection
else:
raise RuntimeError, 'Unknown protocol %s' %protocol
binding = Binding(host=host, tracefile=self._tracefile,
transport=transport,transdict=self._transdict,
port=port, url=url, nsdict=self._nsdict,
soapaction=soapAction,)
request, response = self._getTypeCodes(callinfo)
if len(kwargs): args = kwargs
if request is None:
request = Any(oname=name)
binding.Send(url=url, opname=None, obj=args,
nsdict=self._nsdict, soapaction=soapAction, requesttypecode=request)
return binding.Receive(replytype=response)
def _getTypeCodes(self, callinfo):
"""Returns typecodes representing input and output messages, if request and/or
response fails to be generated return None for either or both.
callinfo -- WSDLTools.SOAPCallInfo instance describing an operation.
"""
prefix = None
self._resetPrefixDict()
if callinfo.use == 'encoded':
prefix = self._getPrefix(callinfo.namespace)
try:
requestTC = self._getTypeCode(parameters=callinfo.getInParameters(), literal=(callinfo.use=='literal'))
except EvaluateException, ex:
print "DEBUG: Request Failed to generate --", ex
requestTC = None
self._resetPrefixDict()
try:
replyTC = self._getTypeCode(parameters=callinfo.getOutParameters(), literal=(callinfo.use=='literal'))
except EvaluateException, ex:
print "DEBUG: Response Failed to generate --", ex
replyTC = None
request = response = None
if callinfo.style == 'rpc':
if requestTC: request = TC.Struct(pyclass=None, ofwhat=requestTC, pname=callinfo.methodName)
if replyTC: response = TC.Struct(pyclass=None, ofwhat=replyTC, pname='%sResponse' %callinfo.methodName)
else:
if requestTC: request = requestTC[0]
if replyTC: response = replyTC[0]
#THIS IS FOR RPC/ENCODED, DOC/ENCODED Wrapper
if request and prefix and callinfo.use == 'encoded':
request.oname = '%(prefix)s:%(name)s xmlns:%(prefix)s="%(namespaceURI)s"' \
%{'prefix':prefix, 'name':request.aname, 'namespaceURI':callinfo.namespace}
return request, response
def _getTypeCode(self, parameters, literal=False):
"""Returns typecodes representing a parameter set
parameters -- list of WSDLTools.ParameterInfo instances representing
the parts of a WSDL Message.
"""
ofwhat = []
for part in parameters:
namespaceURI,localName = part.type
if part.element_type:
#global element
element = self._wsdl.types[namespaceURI].elements[localName]
tc = self._getElement(element, literal=literal, local=False, namespaceURI=namespaceURI)
else:
#local element
name = part.name
typeClass = self._getTypeClass(namespaceURI, localName)
if not typeClass:
tp = self._wsdl.types[namespaceURI].types[localName]
tc = self._getType(tp, name, literal, local=True, namespaceURI=namespaceURI)
else:
tc = typeClass(name)
ofwhat.append(tc)
return ofwhat
def _globalElement(self, typeCode, namespaceURI, literal):
"""namespaces typecodes representing global elements with
literal encoding.
typeCode -- typecode representing an element.
namespaceURI -- namespace
literal -- True/False
"""
if literal:
typeCode.oname = '%(prefix)s:%(name)s xmlns:%(prefix)s="%(namespaceURI)s"' \
%{'prefix':self._getPrefix(namespaceURI), 'name':typeCode.oname, 'namespaceURI':namespaceURI}
def _getPrefix(self, namespaceURI):
"""Retrieves a prefix/namespace mapping.
namespaceURI -- namespace
"""
prefixDict = self._getPrefixDict()
if prefixDict.has_key(namespaceURI):
prefix = prefixDict[namespaceURI]
else:
prefix = 'ns1'
while prefix in prefixDict.values():
prefix = 'ns%d' %int(prefix[-1]) + 1
prefixDict[namespaceURI] = prefix
return prefix
def _getPrefixDict(self):
"""Used to hide the actual prefix dictionary.
"""
if not hasattr(self, '_prefixDict'):
self.__prefixDict = {}
return self.__prefixDict
def _resetPrefixDict(self):
"""Clears the prefix dictionary, this needs to be done
before creating a new typecode for a message
(ie. before, and after creating a new message typecode)
"""
self._getPrefixDict().clear()
def _getElement(self, element, literal=False, local=False, namespaceURI=None):
"""Returns a typecode instance representing the passed in element.
element -- XMLSchema.ElementDeclaration instance
literal -- literal encoding?
local -- is locally defined?
namespaceURI -- namespace
"""
if not element.isElement():
raise TypeError, 'Expecting an ElementDeclaration'
tc = None
elementName = element.getAttribute('name')
tp = element.getTypeDefinition('type')
typeObj = None
if not (tp or element.content):
nsuriType,localName = element.getAttribute('type')
typeClass = self._getTypeClass(nsuriType,localName)
typeObj = typeClass(elementName)
elif not tp:
tp = element.content
if not typeObj:
typeObj = self._getType(tp, elementName, literal, local, namespaceURI)
minOccurs = int(element.getAttribute('minOccurs'))
typeObj.optional = not minOccurs
typeObj.minOccurs = minOccurs
maxOccurs = element.getAttribute('maxOccurs')
typeObj.repeatable = (maxOccurs == 'unbounded') or (int(maxOccurs) > 1)
return typeObj
def _getType(self, tp, name, literal, local, namespaceURI):
"""Returns a typecode instance representing the passed in type and name.
tp -- XMLSchema.TypeDefinition instance
name -- element name
literal -- literal encoding?
local -- is locally defined?
namespaceURI -- namespace
"""
ofwhat = []
if not (tp.isDefinition() and tp.isComplex()):
raise EvaluateException, 'only supporting complexType definition'
elif tp.content.isComplex():
if hasattr(tp.content, 'derivation') and tp.content.derivation.isRestriction():
derived = tp.content.derivation
typeClass = self._getTypeClass(*derived.getAttribute('base'))
if typeClass == TC.Array:
attrs = derived.attr_content[0].attributes[WSDL.BASE]
prefix, localName = SplitQName(attrs['arrayType'])
nsuri = derived.attr_content[0].getXMLNS(prefix=prefix)
localName = localName.split('[')[0]
simpleTypeClass = self._getTypeClass(namespaceURI=nsuri, localName=localName)
if simpleTypeClass:
ofwhat = simpleTypeClass()
else:
tp = self._wsdl.types[nsuri].types[localName]
ofwhat = self._getType(tp=tp, name=None, literal=literal, local=True, namespaceURI=nsuri)
else:
raise EvaluateException, 'only support soapenc:Array restrictions'
return typeClass(atype=name, ofwhat=ofwhat, pname=name, childNames='item')
else:
raise EvaluateException, 'complexContent only supported for soapenc:Array derivations'
elif tp.content.isModelGroup():
modelGroup = tp.content
for item in modelGroup.content:
ofwhat.append(self._getElement(item, literal=literal, local=True))
tc = TC.Struct(pyclass=None, ofwhat=ofwhat, pname=name)
if not local:
self._globalElement(tc, namespaceURI=namespaceURI, literal=literal)
return tc
raise EvaluateException, 'only supporting complexType w/ model group, or soapenc:Array restriction'
def _getTypeClass(self, namespaceURI, localName):
"""Returns a typecode class representing the type we are looking for.
localName -- name of the type we are looking for.
namespaceURI -- defining XMLSchema targetNamespace.
"""
bti = BaseTypeInterpreter()
simpleTypeClass = bti.get_typeclass(localName, namespaceURI)
return simpleTypeClass
class MethodProxy:
""" """
def __init__(self, parent, callinfo):
self.__name__ = callinfo.methodName
self.__doc__ = callinfo.documentation
self.callinfo = callinfo
self.parent = weakref.ref(parent)
def __call__(self, *args, **kwargs):
return self.parent()._call(self.__name__, *args, **kwargs) | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/ZSI/ServiceProxy.py | ServiceProxy.py |
from ZSI import _copyright, _child_elements, EvaluateException, TC
import multifile, mimetools, urllib
from base64 import decodestring as b64decode
import cStringIO as StringIO
def Opaque(uri, tc, ps, **keywords):
'''Resolve a URI and return its content as a string.
'''
source = urllib.urlopen(uri, **keywords)
enc = source.info().getencoding()
if enc in ['7bit', '8bit', 'binary']: return source.read()
data = StringIO.StringIO()
mimetools.decode(source, data, enc)
return data.getvalue()
def XML(uri, tc, ps, **keywords):
'''Resolve a URI and return its content as an XML DOM.
'''
source = urllib.urlopen(uri, **keywords)
enc = source.info().getencoding()
if enc in ['7bit', '8bit', 'binary']:
data = source
else:
data = StringIO.StringIO()
mimetools.decode(source, data, enc)
data.seek(0)
dom = ps.readerclass().fromStream(data)
return _child_elements(dom)[0]
class NetworkResolver:
'''A resolver that support string and XML.
'''
def __init__(self, prefix=None):
self.allowed = prefix or []
def _check_allowed(self, uri):
for a in self.allowed:
if uri.startswith(a): return
raise EvaluateException("Disallowed URI prefix")
def Opaque(self, uri, tc, ps, **keywords):
self._check_allowed(uri)
return Opaque(uri, tc, ps, **keywords)
def XML(self, uri, tc, ps, **keywords):
self._check_allowed(uri)
return XML(uri, tc, ps, **keywords)
def Resolve(self, uri, tc, ps, **keywords):
if isinstance(tc, TC.XML):
return XML(uri, tc, ps, **keywords)
return Opaque(uri, tc, ps, **keywords)
class MIMEResolver:
'''Multi-part MIME resolver -- SOAP With Attachments, mostly.
'''
def __init__(self, ct, f, next=None, uribase='thismessage:/',
seekable=0, **kw):
# Get the boundary. It's too bad I have to write this myself,
# but no way am I going to import cgi for 10 lines of code!
for param in ct.split(';'):
a = param.strip()
if a.startswith('boundary='):
if a[9] in [ '"', "'" ]:
boundary = a[10:-1]
else:
boundary = a[9:]
break
else:
raise ValueError('boundary parameter not found')
self.id_dict, self.loc_dict, self.parts = {}, {}, []
self.next = next
self.base = uribase
mf = multifile.MultiFile(f, seekable)
mf.push(boundary)
while mf.next():
head = mimetools.Message(mf)
body = StringIO.StringIO()
mimetools.decode(mf, body, head.getencoding())
body.seek(0)
part = (head, body)
self.parts.append(part)
key = head.get('content-id')
if key:
if key[0] == '<' and key[-1] == '>': key = key[1:-1]
self.id_dict[key] = part
key = head.get('content-location')
if key: self.loc_dict[key] = part
mf.pop()
def GetSOAPPart(self):
'''Get the SOAP body part.
'''
head, part = self.parts[0]
return StringIO.StringIO(part.getvalue())
def get(self, uri):
'''Get the content for the bodypart identified by the uri.
'''
if uri.startswith('cid:'):
# Content-ID, so raise exception if not found.
head, part = self.id_dict[uri[4:]]
return StringIO.StringIO(part.getvalue())
if self.loc_dict.has_key(uri):
head, part = self.loc_dict[uri]
return StringIO.StringIO(part.getvalue())
return None
def Opaque(self, uri, tc, ps, **keywords):
content = self.get(uri)
if content: return content.getvalue()
if not self.next: raise EvaluateException("Unresolvable URI " + uri)
return self.next.Opaque(uri, tc, ps, **keywords)
def XML(self, uri, tc, ps, **keywords):
content = self.get(uri)
if content:
dom = ps.readerclass().fromStream(content)
return _child_elements(dom)[0]
if not self.next: raise EvaluateException("Unresolvable URI " + uri)
return self.next.XML(uri, tc, ps, **keywords)
def Resolve(self, uri, tc, ps, **keywords):
if isinstance(tc, TC.XML):
return self.XML(uri, tc, ps, **keywords)
return self.Opaque(uri, tc, ps, **keywords)
def __getitem__(self, cid):
head, body = self.id_dict[cid]
newio = StringIO.StringIO(body.getvalue())
return newio
if __name__ == '__main__': print _copyright | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/ZSI/resolvers.py | resolvers.py |
from ZSI import _copyright, _seqtypes, ParsedSoap, SoapWriter, TC, ZSI_SCHEMA_URI,\
EvaluateException, FaultFromFaultMessage, _child_elements, _attrs, _find_arraytype,\
_find_type, _get_idstr, _get_postvalue_from_absoluteURI, FaultException, WSActionException
from ZSI.auth import AUTH
from ZSI.TC import AnyElement, AnyType, String, TypeCode, _get_global_element_declaration,\
_get_type_definition
from ZSI.TCcompound import Struct
import base64, httplib, Cookie, types, time, urlparse
from ZSI.address import Address
from ZSI.wstools.logging import getLogger as _GetLogger
_b64_encode = base64.encodestring
class _AuthHeader:
"""<BasicAuth xmlns="ZSI_SCHEMA_URI">
<Name>%s</Name><Password>%s</Password>
</BasicAuth>
"""
def __init__(self, name=None, password=None):
self.Name = name
self.Password = password
_AuthHeader.typecode = Struct(_AuthHeader, ofwhat=(String((ZSI_SCHEMA_URI,'Name'), typed=False),
String((ZSI_SCHEMA_URI,'Password'), typed=False)), pname=(ZSI_SCHEMA_URI,'BasicAuth'),
typed=False)
class _Caller:
'''Internal class used to give the user a callable object
that calls back to the Binding object to make an RPC call.
'''
def __init__(self, binding, name):
self.binding, self.name = binding, name
def __call__(self, *args):
return self.binding.RPC(None, self.name, args,
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/",
replytype=TC.Any(self.name+"Response"))
class _NamedParamCaller:
'''Similar to _Caller, expect that there are named parameters
not positional.
'''
def __init__(self, binding, name):
self.binding, self.name = binding, name
def __call__(self, **params):
# Pull out arguments that Send() uses
kw = { }
for key in [ 'auth_header', 'nsdict', 'requesttypecode' 'soapaction' ]:
if params.has_key(key):
kw[key] = params[key]
del params[key]
return self.binding.RPC(None, self.name, None,
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/",
_args=params,
replytype=TC.Any(self.name+"Response", aslist=False),
**kw)
class _Binding:
'''Object that represents a binding (connection) to a SOAP server.
Once the binding is created, various ways of sending and
receiving SOAP messages are available.
'''
defaultHttpTransport = httplib.HTTPConnection
defaultHttpsTransport = httplib.HTTPSConnection
logger = _GetLogger('ZSI.client.Binding')
def __init__(self, nsdict=None, transport=None, url=None, tracefile=None,
readerclass=None, writerclass=None, soapaction='',
wsAddressURI=None, sig_handler=None, transdict=None, **kw):
'''Initialize.
Keyword arguments include:
transport -- default use HTTPConnection.
transdict -- dict of values to pass to transport.
url -- URL of resource, POST is path
soapaction -- value of SOAPAction header
auth -- (type, name, password) triplet; default is unauth
nsdict -- namespace entries to add
tracefile -- file to dump packet traces
cert_file, key_file -- SSL data (q.v.)
readerclass -- DOM reader class
writerclass -- DOM writer class, implements MessageInterface
wsAddressURI -- namespaceURI of WS-Address to use. By default
it's not used.
sig_handler -- XML Signature handler, must sign and verify.
endPointReference -- optional Endpoint Reference.
'''
self.data = None
self.ps = None
self.user_headers = []
self.nsdict = nsdict or {}
self.transport = transport
self.transdict = transdict or {}
self.url = url
self.trace = tracefile
self.readerclass = readerclass
self.writerclass = writerclass
self.soapaction = soapaction
self.wsAddressURI = wsAddressURI
self.sig_handler = sig_handler
self.address = None
self.endPointReference = kw.get('endPointReference', None)
self.cookies = Cookie.SimpleCookie()
self.http_callbacks = {}
if kw.has_key('auth'):
self.SetAuth(*kw['auth'])
else:
self.SetAuth(AUTH.none)
def SetAuth(self, style, user=None, password=None):
'''Change auth style, return object to user.
'''
self.auth_style, self.auth_user, self.auth_pass = \
style, user, password
return self
def SetURL(self, url):
'''Set the URL we post to.
'''
self.url = url
return self
def ResetHeaders(self):
'''Empty the list of additional headers.
'''
self.user_headers = []
return self
def ResetCookies(self):
'''Empty the list of cookies.
'''
self.cookies = Cookie.SimpleCookie()
def AddHeader(self, header, value):
'''Add a header to send.
'''
self.user_headers.append((header, value))
return self
def __addcookies(self):
'''Add cookies from self.cookies to request in self.h
'''
for cname, morsel in self.cookies.items():
attrs = []
value = morsel.get('version', '')
if value != '' and value != '0':
attrs.append('$Version=%s' % value)
attrs.append('%s=%s' % (cname, morsel.coded_value))
value = morsel.get('path')
if value:
attrs.append('$Path=%s' % value)
value = morsel.get('domain')
if value:
attrs.append('$Domain=%s' % value)
self.h.putheader('Cookie', "; ".join(attrs))
def RPC(self, url, opname, obj, replytype=None, **kw):
'''Send a request, return the reply. See Send() and Recieve()
docstrings for details.
'''
self.Send(url, opname, obj, **kw)
return self.Receive(replytype, **kw)
def Send(self, url, opname, obj, nsdict={}, soapaction=None, wsaction=None,
endPointReference=None, **kw):
'''Send a message. If url is None, use the value from the
constructor (else error). obj is the object (data) to send.
Data may be described with a requesttypecode keyword, the default
is the class's typecode (if there is one), else Any.
Try to serialize as a Struct, if this is not possible serialize an Array. If
data is a sequence of built-in python data types, it will be serialized as an
Array, unless requesttypecode is specified.
arguments:
url --
opname -- struct wrapper
obj -- python instance
key word arguments:
nsdict --
soapaction --
wsaction -- WS-Address Action, goes in SOAP Header.
endPointReference -- set by calling party, must be an
EndPointReference type instance.
requesttypecode --
'''
url = url or self.url
endPointReference = endPointReference or self.endPointReference
# Serialize the object.
d = {}
d.update(self.nsdict)
d.update(nsdict)
sw = SoapWriter(nsdict=d, header=True, outputclass=self.writerclass,
encodingStyle=kw.get('encodingStyle'),)
requesttypecode = kw.get('requesttypecode')
if kw.has_key('_args'): #NamedParamBinding
tc = requesttypecode or TC.Any(pname=opname, aslist=False)
sw.serialize(kw['_args'], tc)
elif not requesttypecode:
tc = getattr(obj, 'typecode', None) or TC.Any(pname=opname, aslist=False)
try:
if type(obj) in _seqtypes:
obj = dict(map(lambda i: (i.typecode.pname,i), obj))
except AttributeError:
# can't do anything but serialize this in a SOAP:Array
tc = TC.Any(pname=opname, aslist=True)
else:
tc = TC.Any(pname=opname, aslist=False)
sw.serialize(obj, tc)
else:
sw.serialize(obj, requesttypecode)
#
# Determine the SOAP auth element. SOAP:Header element
if self.auth_style & AUTH.zsibasic:
sw.serialize_header(_AuthHeader(self.auth_user, self.auth_pass),
_AuthHeader.typecode)
#
# Serialize WS-Address
if self.wsAddressURI is not None:
if self.soapaction and wsaction.strip('\'"') != self.soapaction:
raise WSActionException, 'soapAction(%s) and WS-Action(%s) must match'\
%(self.soapaction,wsaction)
self.address = Address(url, self.wsAddressURI)
self.address.setRequest(endPointReference, wsaction)
self.address.serialize(sw)
#
# WS-Security Signature Handler
if self.sig_handler is not None:
self.sig_handler.sign(sw)
scheme,netloc,path,nil,nil,nil = urlparse.urlparse(url)
transport = self.transport
if transport is None and url is not None:
if scheme == 'https':
transport = self.defaultHttpsTransport
elif scheme == 'http':
transport = self.defaultHttpTransport
else:
raise RuntimeError, 'must specify transport or url startswith https/http'
# Send the request.
if issubclass(transport, httplib.HTTPConnection) is False:
raise TypeError, 'transport must be a HTTPConnection'
soapdata = str(sw)
self.h = transport(netloc, None, **self.transdict)
self.h.connect()
self.SendSOAPData(soapdata, url, soapaction, **kw)
def SendSOAPData(self, soapdata, url, soapaction, headers={}, **kw):
# Tracing?
if self.trace:
print >>self.trace, "_" * 33, time.ctime(time.time()), "REQUEST:"
print >>self.trace, soapdata
#scheme,netloc,path,nil,nil,nil = urlparse.urlparse(url)
path = _get_postvalue_from_absoluteURI(url)
self.h.putrequest("POST", path)
self.h.putheader("Content-length", "%d" % len(soapdata))
self.h.putheader("Content-type", 'text/xml; charset=utf-8')
self.__addcookies()
for header,value in headers.items():
self.h.putheader(header, value)
SOAPActionValue = '"%s"' % (soapaction or self.soapaction)
self.h.putheader("SOAPAction", SOAPActionValue)
if self.auth_style & AUTH.httpbasic:
val = _b64_encode(self.auth_user + ':' + self.auth_pass) \
.replace("\012", "")
self.h.putheader('Authorization', 'Basic ' + val)
elif self.auth_style == AUTH.httpdigest and not headers.has_key('Authorization') \
and not headers.has_key('Expect'):
def digest_auth_cb(response):
self.SendSOAPDataHTTPDigestAuth(response, soapdata, url, soapaction, **kw)
self.http_callbacks[401] = None
self.http_callbacks[401] = digest_auth_cb
for header,value in self.user_headers:
self.h.putheader(header, value)
self.h.endheaders()
self.h.send(soapdata)
# Clear prior receive state.
self.data, self.ps = None, None
def SendSOAPDataHTTPDigestAuth(self, response, soapdata, url, soapaction, **kw):
'''Resend the initial request w/http digest authorization headers.
The SOAP server has requested authorization. Fetch the challenge,
generate the authdict for building a response.
'''
if self.trace:
print >>self.trace, "------ Digest Auth Header"
url = url or self.url
if response.status != 401:
raise RuntimeError, 'Expecting HTTP 401 response.'
if self.auth_style != AUTH.httpdigest:
raise RuntimeError,\
'Auth style(%d) does not support requested digest authorization.' %self.auth_style
from ZSI.digest_auth import fetch_challenge,\
generate_response,\
build_authorization_arg,\
dict_fetch
chaldict = fetch_challenge( response.getheader('www-authenticate') )
if dict_fetch(chaldict,'challenge','').lower() == 'digest' and \
dict_fetch(chaldict,'nonce',None) and \
dict_fetch(chaldict,'realm',None) and \
dict_fetch(chaldict,'qop',None):
authdict = generate_response(chaldict,
url, self.auth_user, self.auth_pass, method='POST')
headers = {\
'Authorization':build_authorization_arg(authdict),
'Expect':'100-continue',
}
self.SendSOAPData(soapdata, url, soapaction, headers, **kw)
return
raise RuntimeError,\
'Client expecting digest authorization challenge.'
def ReceiveRaw(self, **kw):
'''Read a server reply, unconverted to any format and return it.
'''
if self.data: return self.data
trace = self.trace
while 1:
response = self.h.getresponse()
self.reply_code, self.reply_msg, self.reply_headers, self.data = \
response.status, response.reason, response.msg, response.read()
if trace:
print >>trace, "_" * 33, time.ctime(time.time()), "RESPONSE:"
for i in (self.reply_code, self.reply_msg,):
print >>trace, str(i)
print >>trace, "-------"
print >>trace, str(self.reply_headers)
print >>trace, self.data
saved = None
for d in response.msg.getallmatchingheaders('set-cookie'):
if d[0] in [ ' ', '\t' ]:
saved += d.strip()
else:
if saved: self.cookies.load(saved)
saved = d.strip()
if saved: self.cookies.load(saved)
if response.status == 401:
if not callable(self.http_callbacks.get(response.status,None)):
raise RuntimeError, 'HTTP Digest Authorization Failed'
self.http_callbacks[response.status](response)
continue
if response.status != 100: break
# The httplib doesn't understand the HTTP continuation header.
# Horrible internals hack to patch things up.
self.h._HTTPConnection__state = httplib._CS_REQ_SENT
self.h._HTTPConnection__response = None
return self.data
def IsSOAP(self):
if self.ps: return 1
self.ReceiveRaw()
mimetype = self.reply_headers.type
return mimetype == 'text/xml'
def ReceiveSOAP(self, readerclass=None, **kw):
'''Get back a SOAP message.
'''
if self.ps: return self.ps
if not self.IsSOAP():
raise TypeError(
'Response is "%s", not "text/xml"' % self.reply_headers.type)
if len(self.data) == 0:
raise TypeError('Received empty response')
self.ps = ParsedSoap(self.data,
readerclass=readerclass or self.readerclass,
encodingStyle=kw.get('encodingStyle'))
if self.sig_handler is not None:
self.sig_handler.verify(self.ps)
return self.ps
def IsAFault(self):
'''Get a SOAP message, see if it has a fault.
'''
self.ReceiveSOAP()
return self.ps.IsAFault()
def ReceiveFault(self, **kw):
'''Parse incoming message as a fault. Raise TypeError if no
fault found.
'''
self.ReceiveSOAP(**kw)
if not self.ps.IsAFault():
raise TypeError("Expected SOAP Fault not found")
return FaultFromFaultMessage(self.ps)
def Receive(self, replytype, **kw):
'''Parse message, create Python object.
KeyWord data:
faults -- list of WSDL operation.fault typecodes
wsaction -- If using WS-Address, must specify Action value we expect to
receive.
'''
self.ReceiveSOAP(**kw)
if self.ps.IsAFault():
msg = FaultFromFaultMessage(self.ps)
raise FaultException(msg)
tc = replytype
if hasattr(replytype, 'typecode'):
tc = replytype.typecode
reply = self.ps.Parse(tc)
if self.address is not None:
self.address.checkResponse(self.ps, kw.get('wsaction'))
return reply
def __repr__(self):
return "<%s instance %s>" % (self.__class__.__name__, _get_idstr(self))
class Binding(_Binding):
'''Object that represents a binding (connection) to a SOAP server.
Can be used in the "name overloading" style.
class attr:
gettypecode -- funcion that returns typecode from typesmodule,
can be set so can use whatever mapping you desire.
'''
gettypecode = staticmethod(lambda mod,e: getattr(mod, str(e.localName)).typecode)
logger = _GetLogger('ZSI.client.Binding')
def __init__(self, typesmodule=None, **kw):
self.typesmodule = typesmodule
_Binding.__init__(self, **kw)
def __getattr__(self, name):
'''Return a callable object that will invoke the RPC method
named by the attribute.
'''
if name[:2] == '__' and len(name) > 5 and name[-2:] == '__':
if hasattr(self, name): return getattr(self, name)
return getattr(self.__class__, name)
return _Caller(self, name)
def __parse_child(self, node):
'''for rpc-style map each message part to a class in typesmodule
'''
try:
tc = self.gettypecode(self.typesmodule, node)
except:
self.logger.debug('didnt find typecode for "%s" in typesmodule: %s',
node.localName, self.typesmodule)
tc = TC.Any(aslist=1)
return tc.parse(node, self.ps)
self.logger.debug('parse child with typecode : %s', tc)
try:
return tc.parse(node, self.ps)
except Exception:
self.logger.debug('parse failed try Any : %s', tc)
tc = TC.Any(aslist=1)
return tc.parse(node, self.ps)
def Receive(self, replytype, **kw):
'''Parse message, create Python object.
KeyWord data:
faults -- list of WSDL operation.fault typecodes
wsaction -- If using WS-Address, must specify Action value we expect to
receive.
'''
self.ReceiveSOAP(**kw)
ps = self.ps
tp = _find_type(ps.body_root)
isarray = ((type(tp) in (tuple,list) and tp[1] == 'Array') or _find_arraytype(ps.body_root))
if self.typesmodule is None or isarray:
return _Binding.Receive(self, replytype, **kw)
if ps.IsAFault():
msg = FaultFromFaultMessage(ps)
raise FaultException(msg)
tc = replytype
if hasattr(replytype, 'typecode'):
tc = replytype.typecode
#Ignore response wrapper
reply = {}
for elt in _child_elements(ps.body_root):
name = str(elt.localName)
reply[name] = self.__parse_child(elt)
if self.address is not None:
self.address.checkResponse(ps, kw.get('wsaction'))
return reply
class NamedParamBinding(Binding):
'''Like Binding, except the argument list for invocation is
named parameters.
'''
logger = _GetLogger('ZSI.client.Binding')
def __getattr__(self, name):
'''Return a callable object that will invoke the RPC method
named by the attribute.
'''
if name[:2] == '__' and len(name) > 5 and name[-2:] == '__':
if hasattr(self, name): return getattr(self, name)
return getattr(self.__class__, name)
return _NamedParamCaller(self, name)
if __name__ == '__main__': print _copyright | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/ZSI/client.py | client.py |
import urlparse, types, os, sys, cStringIO as StringIO, thread,re
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from ZSI import ParseException, FaultFromException, FaultFromZSIException, Fault
from ZSI import _copyright, _seqtypes, _get_element_nsuri_name, resolvers
from ZSI import _get_idstr
from ZSI.address import Address
from ZSI.parse import ParsedSoap
from ZSI.writer import SoapWriter
from ZSI.dispatch import _ModPythonSendXML, _ModPythonSendFault, _CGISendXML, _CGISendFault
from ZSI.dispatch import SOAPRequestHandler as BaseSOAPRequestHandler
"""
Functions:
_Dispatch
AsServer
GetSOAPContext
Classes:
SOAPContext
NoSuchService
PostNotSpecified
SOAPActionNotSpecified
ServiceSOAPBinding
SimpleWSResource
SOAPRequestHandler
ServiceContainer
"""
class NoSuchService(Exception): pass
class UnknownRequestException(Exception): pass
class PostNotSpecified(Exception): pass
class SOAPActionNotSpecified(Exception): pass
class WSActionException(Exception): pass
class WSActionNotSpecified(WSActionException): pass
class NotAuthorized(Exception): pass
class ServiceAlreadyPresent(Exception): pass
class SOAPContext:
def __init__(self, container, xmldata, ps, connection, httpheaders,
soapaction):
self.container = container
self.xmldata = xmldata
self.parsedsoap = ps
self.connection = connection
self.httpheaders= httpheaders
self.soapaction = soapaction
_contexts = dict()
def GetSOAPContext():
global _contexts
return _contexts[thread.get_ident()]
def _Dispatch(ps, server, SendResponse, SendFault, post, action, nsdict={}, **kw):
'''Send ParsedSoap instance to ServiceContainer, which dispatches to
appropriate service via post, and method via action. Response is a
self-describing pyobj, which is passed to a SoapWriter.
Call SendResponse or SendFault to send the reply back, appropriately.
server -- ServiceContainer instance
'''
localURL = 'http://%s:%d%s' %(server.server_name,server.server_port,post)
address = action
service = server.getNode(post)
isWSResource = False
if isinstance(service, SimpleWSResource):
isWSResource = True
service.setServiceURL(localURL)
address = Address()
try:
address.parse(ps)
except Exception, e:
return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)
if action and action != address.getAction():
e = WSActionException('SOAP Action("%s") must match WS-Action("%s") if specified.' \
%(action,address.getAction()))
return SendFault(FaultFromException(e, 0, None), **kw)
action = address.getAction()
if isinstance(service, ServiceInterface) is False:
e = NoSuchService('no service at POST(%s) in container: %s' %(post,server))
return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)
if not service.authorize(None, post, action):
return SendFault(Fault(Fault.Server, "Not authorized"), code=401)
#try:
# raise NotAuthorized()
#except Exception, e:
#return SendFault(FaultFromException(e, 0, None), code=401, **kw)
##return SendFault(FaultFromException(NotAuthorized(), 0, None), code=401, **kw)
try:
method = service.getOperation(ps, address)
except Exception, e:
return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)
try:
if isWSResource is True:
result = method(ps, address)
else:
result = method(ps)
except Exception, e:
return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)
# Verify if Signed
service.verify(ps)
# If No response just return.
if result is None:
return
sw = SoapWriter(nsdict=nsdict)
try:
sw.serialize(result)
except Exception, e:
return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)
if isWSResource is True:
action = service.getResponseAction(action)
addressRsp = Address(action=action)
try:
addressRsp.setResponseFromWSAddress(address, localURL)
addressRsp.serialize(sw)
except Exception, e:
return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)
# Create Signatures
service.sign(sw)
try:
soapdata = str(sw)
return SendResponse(soapdata, **kw)
except Exception, e:
return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)
def AsServer(port=80, services=()):
'''port --
services -- list of service instances
'''
address = ('', port)
sc = ServiceContainer(address, services)
#for service in services:
# path = service.getPost()
# sc.setNode(service, path)
sc.serve_forever()
class ServiceInterface:
'''Defines the interface for use with ServiceContainer Handlers.
class variables:
soapAction -- dictionary of soapAction keys, and operation name values.
These are specified in the WSDL soap bindings. There must be a
class method matching the operation name value. If WS-Action is
used the keys are WS-Action request values, according to the spec
if soapAction and WS-Action is specified they must be equal.
wsAction -- dictionary of operation name keys and WS-Action
response values. These values are specified by the portType.
root -- dictionary of root element keys, and operation name values.
'''
soapAction = {}
wsAction = {}
root = {}
def __init__(self, post):
self.post = post
def authorize(self, auth_info, post, action):
return 1
def __str__(self):
return '%s(%s) POST(%s)' %(self.__class__.__name__, _get_idstr(self), self.post)
def sign(self, sw):
return
def verify(self, ps):
return
def getPost(self):
return self.post
def getOperation(self, ps, action):
'''Returns a method of class.
action -- soapAction value
'''
opName = self.getOperationName(ps, action)
return getattr(self, opName)
def getOperationName(self, ps, action):
'''Returns operation name.
action -- soapAction value
'''
method = self.root.get(_get_element_nsuri_name(ps.body_root)) or \
self.soapAction.get(action)
if method is None:
raise UnknownRequestException, \
'failed to map request to a method: action(%s), root%s' %(action,_get_element_nsuri_name(ps.body_root))
return method
class ServiceSOAPBinding(ServiceInterface):
'''Binding defines the set of wsdl:binding operations, it takes as input a
ParsedSoap instance and parses it into a pyobj. It returns a response pyobj.
'''
def __init__(self, post):
ServiceInterface.__init__(self, post)
def __call___(self, action, ps):
return self.getOperation(ps, action)(ps)
class SimpleWSResource(ServiceSOAPBinding):
'''Simple WSRF service, performs method resolutions based
on WS-Action values rather than SOAP Action.
class variables:
encoding
wsAction -- Must override to set output Action values.
soapAction -- Must override to set input Action values.
'''
encoding = "UTF-8"
def __init__(self, post=None):
'''
post -- POST value
'''
assert isinstance(self.soapAction, dict), "soapAction must be a dict"
assert isinstance(self.wsAction, dict), "wsAction must be a dict"
ServiceSOAPBinding.__init__(self, post)
def __call___(self, action, ps, address):
return self.getOperation(ps, action)(ps, address)
def getServiceURL(self):
return self._url
def setServiceURL(self, url):
self._url = url
def getOperation(self, ps, address):
'''Returns a method of class.
address -- ws-address
'''
action = address.getAction()
opName = self.getOperationName(ps, action)
return getattr(self, opName)
def getResponseAction(self, ps, action):
'''Returns response WS-Action if available
action -- request WS-Action value.
'''
opName = self.getOperationName(ps, action)
if self.wsAction.has_key(opName) is False:
raise WSActionNotSpecified, 'wsAction dictionary missing key(%s)' %opName
return self.wsAction[opName]
def do_POST(self):
'''The POST command. This is called by HTTPServer, not twisted.
action -- SOAPAction(HTTP header) or wsa:Action(SOAP:Header)
'''
global _contexts
soapAction = self.headers.getheader('SOAPAction')
post = self.path
if not post:
raise PostNotSpecified, 'HTTP POST not specified in request'
if soapAction:
soapAction = soapAction.strip('\'"')
post = post.strip('\'"')
try:
ct = self.headers['content-type']
if ct.startswith('multipart/'):
cid = resolvers.MIMEResolver(ct, self.rfile)
xml = cid.GetSOAPPart()
ps = ParsedSoap(xml, resolver=cid.Resolve, readerclass=DomletteReader)
else:
length = int(self.headers['content-length'])
ps = ParsedSoap(self.rfile.read(length), readerclass=DomletteReader)
except ParseException, e:
self.send_fault(FaultFromZSIException(e))
except Exception, e:
# Faulted while processing; assume it's in the header.
self.send_fault(FaultFromException(e, 1, sys.exc_info()[2]))
else:
# Keep track of calls
thread_id = thread.get_ident()
_contexts[thread_id] = SOAPContext(self.server, xml, ps,
self.connection,
self.headers, soapAction)
try:
_Dispatch(ps, self.server, self.send_xml, self.send_fault,
post=post, action=soapAction)
except Exception, e:
self.send_fault(FaultFromException(e, 0, sys.exc_info()[2]))
# Clean up after the call
if _contexts.has_key(thread_id):
del _contexts[thread_id]
class SOAPRequestHandler(BaseSOAPRequestHandler):
'''SOAP handler.
'''
def do_POST(self):
'''The POST command.
action -- SOAPAction(HTTP header) or wsa:Action(SOAP:Header)
'''
soapAction = self.headers.getheader('SOAPAction')
post = self.path
if not post:
raise PostNotSpecified, 'HTTP POST not specified in request'
if soapAction:
soapAction = soapAction.strip('\'"')
post = post.strip('\'"')
try:
ct = self.headers['content-type']
if ct.startswith('multipart/'):
cid = resolvers.MIMEResolver(ct, self.rfile)
xml = cid.GetSOAPPart()
ps = ParsedSoap(xml, resolver=cid.Resolve)
else:
length = int(self.headers['content-length'])
xml = self.rfile.read(length)
ps = ParsedSoap(xml)
except ParseException, e:
self.send_fault(FaultFromZSIException(e))
except Exception, e:
# Faulted while processing; assume it's in the header.
self.send_fault(FaultFromException(e, 1, sys.exc_info()[2]))
else:
# Keep track of calls
thread_id = thread.get_ident()
_contexts[thread_id] = SOAPContext(self.server, xml, ps,
self.connection,
self.headers, soapAction)
try:
_Dispatch(ps, self.server, self.send_xml, self.send_fault,
post=post, action=soapAction)
except Exception, e:
self.send_fault(FaultFromException(e, 0, sys.exc_info()[2]))
# Clean up after the call
if _contexts.has_key(thread_id):
del _contexts[thread_id]
def do_GET(self):
'''The GET command.
'''
if self.path.lower().endswith("?wsdl"):
service_path = self.path[:-5]
service = self.server.getNode(service_path)
if hasattr(service, "_wsdl"):
wsdl = service._wsdl
# update the soap:location tag in the wsdl to the actual server
# location
# - default to 'http' as protocol, or use server-specified protocol
proto = 'http'
if hasattr(self.server,'proto'):
proto = self.server.proto
serviceUrl = '%s://%s:%d%s' % (proto,
self.server.server_name,
self.server.server_port,
service_path)
soapAddress = '<soap:address location="%s"/>' % serviceUrl
wsdlre = re.compile('\<soap:address[^\>]*>',re.IGNORECASE)
wsdl = re.sub(wsdlre,soapAddress,wsdl)
self.send_xml(wsdl)
else:
self.send_error(404, "WSDL not available for that service [%s]." % self.path)
else:
self.send_error(404, "Service not found [%s]." % self.path)
class ServiceContainer(HTTPServer):
'''HTTPServer that stores service instances according
to POST values. An action value is instance specific,
and specifies an operation (function) of an instance.
'''
class NodeTree:
'''Simple dictionary implementation of a node tree
'''
def __init__(self):
self.__dict = {}
def __str__(self):
return str(self.__dict)
def listNodes(self):
print self.__dict.keys()
def getNode(self, url):
path = urlparse.urlsplit(url)[2]
if path.startswith("/"):
path = path[1:]
if self.__dict.has_key(path):
return self.__dict[path]
else:
raise NoSuchService, 'No service(%s) in ServiceContainer' %path
def setNode(self, service, url):
path = urlparse.urlsplit(url)[2]
if path.startswith("/"):
path = path[1:]
if not isinstance(service, ServiceSOAPBinding):
raise TypeError, 'A Service must implement class ServiceSOAPBinding'
if self.__dict.has_key(path):
raise ServiceAlreadyPresent, 'Service(%s) already in ServiceContainer' % path
else:
self.__dict[path] = service
def removeNode(self, url):
path = urlparse.urlsplit(url)[2]
if path.startswith("/"):
path = path[1:]
if self.__dict.has_key(path):
node = self.__dict[path]
del self.__dict[path]
return node
else:
raise NoSuchService, 'No service(%s) in ServiceContainer' %path
def __init__(self, server_address, services=[], RequestHandlerClass=SOAPRequestHandler):
'''server_address --
RequestHandlerClass --
'''
HTTPServer.__init__(self, server_address, RequestHandlerClass)
self._nodes = self.NodeTree()
map(lambda s: self.setNode(s), services)
def __str__(self):
return '%s(%s) nodes( %s )' %(self.__class__, _get_idstr(self), str(self._nodes))
def __call__(self, ps, post, action, address=None):
'''ps -- ParsedSoap representing the request
post -- HTTP POST --> instance
action -- Soap Action header --> method
address -- Address instance representing WS-Address
'''
method = self.getCallBack(ps, post, action)
if isinstance(method.im_self, SimpleWSResource):
return method(ps, address)
return method(ps)
def setNode(self, service, url=None):
if url is None:
url = service.getPost()
self._nodes.setNode(service, url)
def getNode(self, url):
return self._nodes.getNode(url)
def removeNode(self, url):
self._nodes.removeNode(url)
class SimpleWSResource(ServiceSOAPBinding):
def getNode(self, post):
'''post -- POST HTTP value
'''
return self._nodes.getNode(post)
def setNode(self, service, post):
'''service -- service instance
post -- POST HTTP value
'''
self._nodes.setNode(service, post)
def getCallBack(self, ps, post, action):
'''post -- POST HTTP value
action -- SOAP Action value
'''
node = self.getNode(post)
if node is None:
raise NoSuchFunction
if node.authorize(None, post, action):
return node.getOperation(ps, action)
else:
raise NotAuthorized, "Authorization failed for method %s" % action
if __name__ == '__main__': print _copyright | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/ZSI/ServiceContainer.py | ServiceContainer.py |
from ZSI import _copyright, _get_idstr, ZSI_SCHEMA_URI
from ZSI import _backtrace, _stringtypes, _seqtypes
from ZSI.wstools.Utility import MessageInterface, ElementProxy
from ZSI.wstools.Namespaces import XMLNS, SOAP, SCHEMA
from ZSI.wstools.c14n import Canonicalize
import types
_standard_ns = [ ('xml', XMLNS.XML), ('xmlns', XMLNS.BASE) ]
_reserved_ns = {
'SOAP-ENV': SOAP.ENV,
'SOAP-ENC': SOAP.ENC,
'ZSI': ZSI_SCHEMA_URI,
'xsd': SCHEMA.BASE,
'xsi': SCHEMA.BASE + '-instance',
}
class SoapWriter:
'''SOAP output formatter.
Instance Data:
memo -- memory for id/href
envelope -- add Envelope?
encodingStyle --
header -- add SOAP Header?
outputclass -- ElementProxy class.
'''
def __init__(self, envelope=True, encodingStyle=None, header=True,
nsdict={}, outputclass=None, **kw):
'''Initialize.
'''
outputclass = outputclass or ElementProxy
if not issubclass(outputclass, MessageInterface):
raise TypeError, 'outputclass must subclass MessageInterface'
self.dom, self.memo, self.nsdict= \
outputclass(self), [], nsdict
self.envelope = envelope
self.encodingStyle = encodingStyle
self.header = header
self.body = None
self.callbacks = []
self.closed = False
def __str__(self):
self.close()
return str(self.dom)
def getSOAPHeader(self):
if self.header in (True, False):
return None
return self.header
def serialize_header(self, pyobj, typecode=None, **kw):
'''Serialize a Python object in SOAP-ENV:Header, make
sure everything in Header unique (no #href). Must call
serialize first to create a document.
Parameters:
pyobjs -- instances to serialize in SOAP Header
typecode -- default typecode
'''
kw['unique'] = True
soap_env = _reserved_ns['SOAP-ENV']
#header = self.dom.getElement(soap_env, 'Header')
header = self._header
if header is None:
header = self._header = self.dom.createAppendElement(soap_env,
'Header')
typecode = getattr(pyobj, 'typecode', typecode)
if typecode is None:
raise RuntimeError(
'typecode is required to serialize pyobj in header')
helt = typecode.serialize(header, self, pyobj, **kw)
def serialize(self, pyobj, typecode=None, root=None, header_pyobjs=(), **kw):
'''Serialize a Python object to the output stream.
pyobj -- python instance to serialize in body.
typecode -- typecode describing body
root -- SOAP-ENC:root
header_pyobjs -- list of pyobj for soap header inclusion, each
instance must specify the typecode attribute.
'''
self.body = None
if self.envelope:
soap_env = _reserved_ns['SOAP-ENV']
self.dom.createDocument(soap_env, 'Envelope')
for prefix, nsuri in _reserved_ns.items():
self.dom.setNamespaceAttribute(prefix, nsuri)
self.writeNSdict(self.nsdict)
if self.encodingStyle:
self.dom.setAttributeNS(soap_env, 'encodingStyle',
self.encodingStyle)
if self.header:
self._header = self.dom.createAppendElement(soap_env, 'Header')
for h in header_pyobjs:
self.serialize_header(h, **kw)
self.body = self.dom.createAppendElement(soap_env, 'Body')
else:
self.dom.createDocument(None,None)
if typecode is None: typecode = pyobj.__class__.typecode
kw = kw.copy()
if self.body is None:
elt = typecode.serialize(self.dom, self, pyobj, **kw)
else:
elt = typecode.serialize(self.body, self, pyobj, **kw)
if root is not None:
if root not in [ 0, 1 ]:
raise ValueError, "SOAP-ENC root attribute not in [0,1]"
elt.setAttributeNS(SOAP.ENC, 'root', root)
return self
def writeNSdict(self, nsdict):
'''Write a namespace dictionary, taking care to not clobber the
standard (or reserved by us) prefixes.
'''
for k,v in nsdict.items():
if (k,v) in _standard_ns: continue
rv = _reserved_ns.get(k)
if rv:
if rv != v:
raise KeyError("Reserved namespace " + str((k,v)) + " used")
continue
if k:
self.dom.setNamespaceAttribute(k, v)
else:
self.dom.setNamespaceAttribute('xmlns', v)
def ReservedNS(self, prefix, uri):
'''Is this namespace (prefix,uri) reserved by us?
'''
return _reserved_ns.get(prefix, uri) != uri
def AddCallback(self, func, *arglist):
'''Add a callback function and argument list to be invoked before
closing off the SOAP Body.
'''
self.callbacks.append((func, arglist))
def Known(self, obj):
'''Seen this object (known by its id()? Return 1 if so,
otherwise add it to our memory and return 0.
'''
obj = _get_idstr(obj)
if obj in self.memo: return 1
self.memo.append(obj)
return 0
def Forget(self, obj):
'''Forget we've seen this object.
'''
obj = _get_idstr(obj)
try:
self.memo.remove(obj)
except ValueError:
pass
def Backtrace(self, elt):
'''Return a human-readable "backtrace" from the document root to
the specified element.
'''
return _backtrace(elt._getNode(), self.dom._getNode())
def close(self):
'''Invoke all the callbacks, and close off the SOAP message.
'''
if self.closed: return
for func,arglist in self.callbacks:
apply(func, arglist)
self.closed = True
def __del__(self):
if not self.closed: self.close()
if __name__ == '__main__': print _copyright | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/ZSI/writer.py | writer.py |
import ZSI
from ZSI import TC, TCtimes, TCcompound
from ZSI.TC import TypeCode
from ZSI import _copyright, EvaluateException
from ZSI.wstools.Utility import SplitQName
from ZSI.wstools.Namespaces import SOAP, SCHEMA
###########################################################################
# Module Classes: BaseTypeInterpreter
###########################################################################
class NamespaceException(Exception): pass
class BaseTypeInterpreter:
"""Example mapping of xsd/soapenc types to zsi python types.
Checks against all available classes in ZSI.TC. Used in
wsdl2python, wsdlInterpreter, and ServiceProxy.
"""
def __init__(self):
self._type_list = [TC.Iinteger, TC.IunsignedShort, TC.gYearMonth, \
TC.InonNegativeInteger, TC.Iint, TC.String, \
TC.gDateTime, TC.IunsignedInt, TC.Duration,\
TC.IpositiveInteger, TC.FPfloat, TC.gDay, TC.gMonth, \
TC.InegativeInteger, TC.gDate, TC.URI, \
TC.HexBinaryString, TC.IunsignedByte, \
TC.gMonthDay, TC.InonPositiveInteger, \
TC.Ibyte, TC.FPdouble, TC.gTime, TC.gYear, \
TC.Ilong, TC.IunsignedLong, TC.Ishort, \
TC.Token, TC.QName]
self._tc_to_int = [
ZSI.TCnumbers.IEnumeration,
ZSI.TCnumbers.Iint,
ZSI.TCnumbers.Iinteger,
ZSI.TCnumbers.Ilong,
ZSI.TCnumbers.InegativeInteger,
ZSI.TCnumbers.InonNegativeInteger,
ZSI.TCnumbers.InonPositiveInteger,
ZSI.TC.Integer,
ZSI.TCnumbers.IpositiveInteger,
ZSI.TCnumbers.Ishort]
self._tc_to_float = [
ZSI.TC.Decimal,
ZSI.TCnumbers.FPEnumeration,
ZSI.TCnumbers.FPdouble,
ZSI.TCnumbers.FPfloat]
self._tc_to_string = [
ZSI.TC.Base64String,
ZSI.TC.Enumeration,
ZSI.TC.HexBinaryString,
ZSI.TCnumbers.Ibyte,
ZSI.TCnumbers.IunsignedByte,
ZSI.TCnumbers.IunsignedInt,
ZSI.TCnumbers.IunsignedLong,
ZSI.TCnumbers.IunsignedShort,
ZSI.TC.String,
ZSI.TC.URI,
ZSI.TC.XMLString,
ZSI.TC.Token]
self._tc_to_tuple = [
ZSI.TC.Duration,
ZSI.TC.QName,
ZSI.TCtimes.gDate,
ZSI.TCtimes.gDateTime,
ZSI.TCtimes.gDay,
ZSI.TCtimes.gMonthDay,
ZSI.TCtimes.gTime,
ZSI.TCtimes.gYear,
ZSI.TCtimes.gMonth,
ZSI.TCtimes.gYearMonth]
return
def _get_xsd_typecode(self, msg_type):
untaged_xsd_types = {'boolean':TC.Boolean,
'decimal':TC.Decimal,
'base64Binary':TC.Base64String}
if untaged_xsd_types.has_key(msg_type):
return untaged_xsd_types[msg_type]
for tc in self._type_list:
if tc.type == (SCHEMA.XSD3,msg_type):
break
else:
tc = TC.AnyType
return tc
def _get_soapenc_typecode(self, msg_type):
if msg_type == 'Array':
return TCcompound.Array
if msg_type == 'Struct':
return TCcompound.Struct
return self._get_xsd_typecode(msg_type)
def get_typeclass(self, msg_type, targetNamespace):
prefix, name = SplitQName(msg_type)
if targetNamespace in SCHEMA.XSD_LIST:
return self._get_xsd_typecode(name)
elif targetNamespace in [SOAP.ENC]:
return self._get_soapenc_typecode(name)
return None
def get_pythontype(self, msg_type, targetNamespace, typeclass=None):
if not typeclass:
tc = self.get_typeclass(msg_type, targetNamespace)
else:
tc = typeclass
if tc in self._tc_to_int:
return 'int'
elif tc in self._tc_to_float:
return 'float'
elif tc in self._tc_to_string:
return 'str'
elif tc in self._tc_to_tuple:
return 'tuple'
elif tc in [TCcompound.Array]:
return 'list'
elif tc in [TC.Boolean]:
return 'bool'
elif isinstance(tc, TypeCode):
raise EvaluateException,\
'failed to map zsi typecode to a python type'
return None | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/ZSI/typeinterpreter.py | typeinterpreter.py |
from ZSI import _copyright, _child_elements, _get_idstr
from ZSI.TC import TypeCode, Struct as _Struct, Any as _Any
class Apache:
NS = "http://xml.apache.org/xml-soap"
class _Map(TypeCode):
'''Apache's "Map" type.
'''
parselist = [ (Apache.NS, 'Map') ]
def __init__(self, pname=None, aslist=0, **kw):
TypeCode.__init__(self, pname, **kw)
self.aslist = aslist
self.tc = _Struct(None, [ _Any('key'), _Any('value') ], inline=1)
def parse(self, elt, ps):
self.checkname(elt, ps)
if self.nilled(elt, ps): return None
p = self.tc.parse
if self.aslist:
v = []
for c in _child_elements(elt):
d = p(c, ps)
v.append((d['key'], d['value']))
else:
v = {}
for c in _child_elements(elt):
d = p(c, ps)
v[d['key']] = d['value']
return v
def serialize(self, elt, sw, pyobj, name=None, **kw):
objid = _get_idstr(pyobj)
n = name or self.pname or ('E' + objid)
# nillable
el = elt.createAppendElement(self.nspname, n)
if self.nillable is True and pyobj is None:
self.serialize_as_nil(el)
return None
# other attributes
self.set_attributes(el, pyobj)
# soap href attribute
unique = self.unique or kw.get('unique', False)
if unique is False and sw.Known(orig or pyobj):
self.set_attribute_href(el, objid)
return None
# xsi:type attribute
if kw.get('typed', self.typed) is True:
self.set_attribute_xsi_type(el, **kw)
# soap id attribute
if self.unique is False:
self.set_attribute_id(el, objid)
if self.aslist:
for k,v in pyobj:
self.tc.serialize(el, sw, {'key': k, 'value': v}, name='item')
else:
for k,v in pyobj.items():
self.tc.serialize(el, sw, {'key': k, 'value': v}, name='item')
Apache.Map = _Map
if __name__ == '__main__': print _copyright | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/ZSI/TCapache.py | TCapache.py |
from ZSI import _copyright, _floattypes, _inttypes, _get_idstr, EvaluateException
from ZSI.TC import TypeCode, SimpleType
from ZSI.wstools.Namespaces import SCHEMA
import operator, re, time as _time
from time import mktime as _mktime, localtime as _localtime, gmtime as _gmtime
from datetime import tzinfo as _tzinfo, timedelta as _timedelta,\
datetime as _datetime
from math import modf as _modf
_niltime = [
0, 0, 0, # year month day
0, 0, 0, # hour minute second
0, 0, 0 # weekday, julian day, dst flag
]
#### Code added to check current timezone offset
_zero = _timedelta(0)
_dstoffset = _stdoffset = _timedelta(seconds=-_time.timezone)
if _time.daylight: _dstoffset = _timedelta(seconds=-_time.altzone)
_dstdiff = _dstoffset - _stdoffset
class _localtimezone(_tzinfo):
""" """
def dst(self, dt):
"""datetime -> DST offset in minutes east of UTC."""
tt = _localtime(_mktime((dt.year, dt.month, dt.day,
dt.hour, dt.minute, dt.second, dt.weekday(), 0, -1)))
if tt.tm_isdst > 0: return _dstdiff
return _zero
#def fromutc(...)
#datetime in UTC -> datetime in local time.
def tzname(self, dt):
"""datetime -> string name of time zone."""
tt = _localtime(_mktime((dt.year, dt.month, dt.day,
dt.hour, dt.minute, dt.second, dt.weekday(), 0, -1)))
return _time.tzname[tt.tm_isdst > 0]
def utcoffset(self, dt):
"""datetime -> minutes east of UTC (negative for west of UTC)."""
tt = _localtime(_mktime((dt.year, dt.month, dt.day,
dt.hour, dt.minute, dt.second, dt.weekday(), 0, -1)))
if tt.tm_isdst > 0: return _dstoffset
return _stdoffset
class _fixedoffset(_tzinfo):
"""Fixed offset in minutes east from UTC.
A class building tzinfo objects for fixed-offset time zones.
Note that _fixedoffset(0, "UTC") is a different way to build a
UTC tzinfo object.
"""
#def __init__(self, offset, name):
def __init__(self, offset):
self.__offset = _timedelta(minutes=offset)
#self.__name = name
def dst(self, dt):
"""datetime -> DST offset in minutes east of UTC."""
return _zero
def tzname(self, dt):
"""datetime -> string name of time zone."""
#return self.__name
return "server"
def utcoffset(self, dt):
"""datetime -> minutes east of UTC (negative for west of UTC)."""
return self.__offset
def _dict_to_tuple(d):
'''Convert a dictionary to a time tuple. Depends on key values in the
regexp pattern!
'''
retval = _niltime[:]
for k,i in ( ('Y', 0), ('M', 1), ('D', 2), ('h', 3), ('m', 4), ):
v = d.get(k)
if v: retval[i] = int(v)
v = d.get('s')
if v:
msec,sec = _modf(float(v))
retval[6],retval[5] = int(round(msec*1000)), int(sec)
v = d.get('tz')
if v and v != 'Z':
h,m = map(int, v.split(':'))
# check for time zone offset, if within the same timezone,
# ignore offset specific calculations
offset=_localtimezone().utcoffset(_datetime.now())
local_offset_hour = offset.seconds/3600
local_offset_min = (offset.seconds%3600)%60
if local_offset_hour > 12:
local_offset_hour -= 24
if local_offset_hour != h or local_offset_min != m:
if h<0:
#TODO: why is this set to server
#foff = _fixedoffset(-((abs(h)*60+m)),"server")
foff = _fixedoffset(-((abs(h)*60+m)))
else:
#TODO: why is this set to server
#foff = _fixedoffset((abs(h)*60+m),"server")
foff = _fixedoffset((abs(h)*60+m))
dt = _datetime(retval[0],retval[1],retval[2],retval[3],retval[4],
retval[5],0,foff)
# update dict with calculated timezone
localdt=dt.astimezone(_localtimezone())
retval[0] = localdt.year
retval[1] = localdt.month
retval[2] = localdt.day
retval[3] = localdt.hour
retval[4] = localdt.minute
retval[5] = localdt.second
if d.get('neg', 0):
retval[0:5] = map(operator.__neg__, retval[0:5])
return tuple(retval)
class Duration(SimpleType):
'''Time duration.
'''
parselist = [ (None,'duration') ]
lex_pattern = re.compile('^' r'(?P<neg>-?)P' \
r'((?P<Y>\d+)Y)?' r'((?P<M>\d+)M)?' r'((?P<D>\d+)D)?' \
r'(?P<T>T?)' r'((?P<h>\d+)H)?' r'((?P<m>\d+)M)?' \
r'((?P<s>\d*(\.\d+)?)S)?' '$')
type = (SCHEMA.XSD3, 'duration')
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data.
'''
if text is None:
return None
m = Duration.lex_pattern.match(text)
if m is None:
raise EvaluateException('Illegal duration', ps.Backtrace(elt))
d = m.groupdict()
if d['T'] and (d['h'] is None and d['m'] is None and d['s'] is None):
raise EvaluateException('Duration has T without time')
try:
retval = _dict_to_tuple(d)
except ValueError, e:
raise EvaluateException(str(e))
if self.pyclass is not None:
return self.pyclass(retval)
return retval
def get_formatted_content(self, pyobj):
if type(pyobj) in _floattypes or type(pyobj) in _inttypes:
pyobj = _gmtime(pyobj)
d = {}
pyobj = tuple(pyobj)
if 1 in map(lambda x: x < 0, pyobj[0:6]):
pyobj = map(abs, pyobj)
neg = '-'
else:
neg = ''
val = '%sP%dY%dM%dDT%dH%dM%dS' % \
( neg, pyobj[0], pyobj[1], pyobj[2], pyobj[3], pyobj[4], pyobj[5])
return val
class Gregorian(SimpleType):
'''Gregorian times.
'''
lex_pattern = tag = format = None
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data.
'''
if text is None:
return None
m = self.lex_pattern.match(text)
if not m:
raise EvaluateException('Bad Gregorian: %s' %text, ps.Backtrace(elt))
try:
retval = _dict_to_tuple(m.groupdict())
except ValueError, e:
#raise EvaluateException(str(e))
raise
if self.pyclass is not None:
return self.pyclass(retval)
return retval
def get_formatted_content(self, pyobj):
if type(pyobj) in _floattypes or type(pyobj) in _inttypes:
pyobj = _gmtime(pyobj)
d = {}
pyobj = tuple(pyobj)
if 1 in map(lambda x: x < 0, pyobj[0:6]):
pyobj = map(abs, pyobj)
d['neg'] = '-'
else:
d['neg'] = ''
ms = pyobj[6]
if not ms:
d = { 'Y': pyobj[0], 'M': pyobj[1], 'D': pyobj[2],
'h': pyobj[3], 'm': pyobj[4], 's': pyobj[5], }
return self.format % d
if ms > 999:
raise ValueError, 'milliseconds must be a integer between 0 and 999'
d = { 'Y': pyobj[0], 'M': pyobj[1], 'D': pyobj[2],
'h': pyobj[3], 'm': pyobj[4], 's': pyobj[5], 'ms':ms, }
return self.format_ms % d
class gDateTime(Gregorian):
'''A date and time.
'''
parselist = [ (None,'dateTime') ]
lex_pattern = re.compile('^' r'(?P<neg>-?)' \
'(?P<Y>\d{4,})-' r'(?P<M>\d\d)-' r'(?P<D>\d\d)' 'T' \
r'(?P<h>\d\d):' r'(?P<m>\d\d):' r'(?P<s>\d*(\.\d+)?)' \
r'(?P<tz>(Z|([-+]\d\d:\d\d))?)' '$')
tag, format = 'dateTime', '%(Y)04d-%(M)02d-%(D)02dT%(h)02d:%(m)02d:%(s)02dZ'
format_ms = format[:-1] + '.%(ms)03dZ'
type = (SCHEMA.XSD3, 'dateTime')
class gDate(Gregorian):
'''A date.
'''
parselist = [ (None,'date') ]
lex_pattern = re.compile('^' r'(?P<neg>-?)' \
'(?P<Y>\d{4,})-' r'(?P<M>\d\d)-' r'(?P<D>\d\d)' \
r'(?P<tz>Z|([-+]\d\d:\d\d))?' '$')
tag, format = 'date', '%(Y)04d-%(M)02d-%(D)02dZ'
type = (SCHEMA.XSD3, 'date')
class gYearMonth(Gregorian):
'''A date.
'''
parselist = [ (None,'gYearMonth') ]
lex_pattern = re.compile('^' r'(?P<neg>-?)' \
'(?P<Y>\d{4,})-' r'(?P<M>\d\d)' \
r'(?P<tz>Z|([-+]\d\d:\d\d))?' '$')
tag, format = 'gYearMonth', '%(Y)04d-%(M)02dZ'
type = (SCHEMA.XSD3, 'gYearMonth')
class gYear(Gregorian):
'''A date.
'''
parselist = [ (None,'gYear') ]
lex_pattern = re.compile('^' r'(?P<neg>-?)' \
'(?P<Y>\d{4,})' \
r'(?P<tz>Z|([-+]\d\d:\d\d))?' '$')
tag, format = 'gYear', '%(Y)04dZ'
type = (SCHEMA.XSD3, 'gYear')
class gMonthDay(Gregorian):
'''A gMonthDay.
'''
parselist = [ (None,'gMonthDay') ]
lex_pattern = re.compile('^' r'(?P<neg>-?)' \
r'--(?P<M>\d\d)-' r'(?P<D>\d\d)' \
r'(?P<tz>Z|([-+]\d\d:\d\d))?' '$')
tag, format = 'gMonthDay', '---%(M)02d-%(D)02dZ'
type = (SCHEMA.XSD3, 'gMonthDay')
class gDay(Gregorian):
'''A gDay.
'''
parselist = [ (None,'gDay') ]
lex_pattern = re.compile('^' r'(?P<neg>-?)' \
r'---(?P<D>\d\d)' \
r'(?P<tz>Z|([-+]\d\d:\d\d))?' '$')
tag, format = 'gDay', '---%(D)02dZ'
type = (SCHEMA.XSD3, 'gDay')
class gMonth(Gregorian):
'''A gMonth.
'''
parselist = [ (None,'gMonth') ]
lex_pattern = re.compile('^' r'(?P<neg>-?)' \
r'---(?P<M>\d\d)' \
r'(?P<tz>Z|([-+]\d\d:\d\d))?' '$')
tag, format = 'gMonth', '---%(M)02dZ'
type = (SCHEMA.XSD3, 'gMonth')
class gTime(Gregorian):
'''A time.
'''
parselist = [ (None,'time') ]
lex_pattern = re.compile('^' r'(?P<neg>-?)' \
r'(?P<h>\d\d):' r'(?P<m>\d\d):' r'(?P<s>\d*(\.\d+)?)' \
r'(?P<tz>Z|([-+]\d\d:\d\d))?' '$')
tag, format = 'time', '%(h)02d:%(m)02d:%(s)02dZ'
format_ms = format[:-1] + '.%(ms)03dZ'
type = (SCHEMA.XSD3, 'time')
if __name__ == '__main__': print _copyright | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/ZSI/TCtimes.py | TCtimes.py |
_copyright = """ZSI: Zolera Soap Infrastructure.
Copyright 2001, Zolera Systems, Inc. All Rights Reserved.
Copyright 2002-2003, Rich Salz. All Rights Reserved.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, and/or
sell copies of the Software, and to permit persons to whom the Software
is furnished to do so, provided that the above copyright notice(s) and
this permission notice appear in all copies of the Software and that
both the above copyright notice(s) and this permission notice appear in
supporting documentation.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS
INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT
OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
OR PERFORMANCE OF THIS SOFTWARE.
Except as contained in this notice, the name of a copyright holder
shall not be used in advertising or otherwise to promote the sale, use
or other dealings in this Software without prior written authorization
of the copyright holder.
Portions are also:
Copyright (c) 2003, The Regents of the University of California,
through Lawrence Berkeley National Laboratory (subject to receipt of
any required approvals from the U.S. Dept. of Energy). All rights
reserved. Redistribution and use in source and binary forms, with or
without modification, are permitted provided that the following
conditions are met:
(1) Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
(2) Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
(3) Neither the name of the University of California, Lawrence Berkeley
National Laboratory, U.S. Dept. of Energy nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
You are under no obligation whatsoever to provide any bug fixes,
patches, or upgrades to the features, functionality or performance of
the source code ("Enhancements") to anyone; however, if you choose to
make your Enhancements available either publicly, or directly to
Lawrence Berkeley National Laboratory, without imposing a separate
written license agreement for such Enhancements, then you hereby grant
the following license: a non-exclusive, royalty-free perpetual license
to install, use, modify, prepare derivative works, incorporate into
other computer software, distribute, and sublicense such Enhancements
or derivative works thereof, in binary and source code form.
For wstools also:
Zope Public License (ZPL) Version 2.0
-----------------------------------------------
This software is Copyright (c) Zope Corporation (tm) and
Contributors. All rights reserved.
This license has been certified as open source. It has also
been designated as GPL compatible by the Free Software
Foundation (FSF).
Redistribution and use in source and binary forms, with or
without modification, are permitted provided that the
following conditions are met:
1. Redistributions in source code must retain the above
copyright notice, this list of conditions, and the following
disclaimer.
2. Redistributions in binary form must reproduce the above
copyright notice, this list of conditions, and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
3. The name Zope Corporation (tm) must not be used to
endorse or promote products derived from this software
without prior written permission from Zope Corporation.
4. The right to distribute this software or to use it for
any purpose does not give you the right to use Servicemarks
(sm) or Trademarks (tm) of Zope Corporation. Use of them is
covered in a separate agreement (see
http://www.zope.com/Marks).
5. If any files are modified, you must cause the modified
files to carry prominent notices stating that you changed
the files and the date of any change.
Disclaimer
THIS SOFTWARE IS PROVIDED BY ZOPE CORPORATION ``AS IS''
AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
NO EVENT SHALL ZOPE CORPORATION OR ITS CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
This software consists of contributions made by Zope
Corporation and many individuals on behalf of Zope
Corporation. Specific attributions are listed in the
accompanying credits file.
"""
##
## Stuff imported from elsewhere.
from xml.dom import Node as _Node
import types as _types
##
## Public constants.
from ZSI.wstools.Namespaces import ZSI_SCHEMA_URI
##
## Not public constants.
_inttypes = [ _types.IntType, _types.LongType ]
_floattypes = [ _types.FloatType ]
_seqtypes = [ _types.TupleType, _types.ListType ]
_stringtypes = [ _types.StringType, _types.UnicodeType ]
##
## Low-level DOM oriented utilities; useful for typecode implementors.
_attrs = lambda E: (E.attributes and E.attributes.values()) or []
_children = lambda E: E.childNodes or []
_child_elements = lambda E: [ n for n in (E.childNodes or [])
if n.nodeType == _Node.ELEMENT_NODE ]
##
## Stuff imported from elsewhere.
from ZSI.wstools.Namespaces import SOAP as _SOAP, SCHEMA as _SCHEMA, XMLNS as _XMLNS
##
## Low-level DOM oriented utilities; useful for typecode implementors.
_find_arraytype = lambda E: E.getAttributeNS(_SOAP.ENC, "arrayType")
_find_encstyle = lambda E: E.getAttributeNS(_SOAP.ENV, "encodingStyle")
try:
from xml.dom import EMPTY_NAMESPACE
_empty_nsuri_list = [ EMPTY_NAMESPACE ]
#if '' not in _empty_nsuri_list: __empty_nsuri_list.append('')
#if None not in _empty_nsuri_list: __empty_nsuri_list.append(None)
except:
_empty_nsuri_list = [ None, '' ]
def _find_attr(E, attr):
for nsuri in _empty_nsuri_list:
try:
v = E.getAttributeNS(nsuri, attr)
if v: return v
except: pass
return None
def _find_attrNS(E, namespaceURI, localName):
'''namespaceURI
localName
'''
try:
v = E.getAttributeNS(namespaceURI, localName)
if v: return v
except: pass
return None
def _find_attrNodeNS(E, namespaceURI, localName):
'''Must grab the attribute Node to distinquish between
an unspecified attribute(None) and one set to empty string("").
namespaceURI
localName
'''
attr = E.getAttributeNodeNS(namespaceURI, localName)
if attr is None: return None
try:
return attr.value
except: pass
return E.getAttributeNS(namespaceURI, localName)
_find_href = lambda E: _find_attr(E, "href")
_find_xsi_attr = lambda E, attr: \
E.getAttributeNS(_SCHEMA.XSI3, attr) \
or E.getAttributeNS(_SCHEMA.XSI1, attr) \
or E.getAttributeNS(_SCHEMA.XSI2, attr)
_find_type = lambda E: _find_xsi_attr(E, "type")
_find_xmlns_prefix = lambda E, attr: E.getAttributeNS(_XMLNS.BASE, attr)
_find_default_namespace = lambda E: E.getAttributeNS(_XMLNS.BASE, None)
#_textprotect = lambda s: s.replace('&', '&').replace('<', '<')
_get_element_nsuri_name = lambda E: (E.namespaceURI, E.localName)
_is_element = lambda E: E.nodeType == _Node.ELEMENT_NODE
def _resolve_prefix(celt, prefix):
'''resolve prefix to a namespaceURI. If None or
empty str, return default namespace or None.
Parameters:
celt -- element node
prefix -- xmlns:prefix, or empty str or None
'''
namespace = None
while _is_element(celt):
if prefix:
namespaceURI = _find_xmlns_prefix(celt, prefix)
else:
namespaceURI = _find_default_namespace(celt)
if namespaceURI: break
celt = celt.parentNode
else:
if prefix:
raise EvaluateException, 'cant resolve xmlns:%s' %prefix
return namespaceURI
def _valid_encoding(elt):
'''Does this node have a valid encoding?
'''
enc = _find_encstyle(elt)
if not enc or enc == _SOAP.ENC: return 1
for e in enc.split():
if e.startswith(_SOAP.ENC):
# XXX Is this correct? Once we find a Sec5 compatible
# XXX encoding, should we check that all the rest are from
# XXX that same base? Perhaps. But since the if test above
# XXX will surely get 99% of the cases, leave it for now.
return 1
return 0
def _backtrace(elt, dom):
'''Return a "backtrace" from the given element to the DOM root,
in XPath syntax.
'''
s = ''
while elt != dom:
name, parent = elt.nodeName, elt.parentNode
if parent is None: break
matches = [ c for c in _child_elements(parent)
if c.nodeName == name ]
if len(matches) == 1:
s = '/' + name + s
else:
i = matches.index(elt) + 1
s = ('/%s[%d]' % (name, i)) + s
elt = parent
return s
def _get_idstr(pyobj):
'''Python 2.3.x generates a FutureWarning for negative IDs, so
we use a different prefix character to ensure uniqueness, and
call abs() to avoid the warning.'''
x = id(pyobj)
if x < 0:
return 'x%x' % abs(x)
return 'o%x' % x
def _get_postvalue_from_absoluteURI(url):
"""Bug [ 1513000 ] POST Request-URI not limited to "abs_path"
Request-URI = "*" | absoluteURI | abs_path | authority
Not a complete solution, but it seems to work with all known
implementations. ValueError thrown if bad uri.
"""
cache = _get_postvalue_from_absoluteURI.cache
path = cache.get(url, '')
if not path:
scheme,authpath = url.split('://')
s = authpath.split('/', 1)
if len(s) == 2: path = '/%s' %s[1]
if len(cache) > _get_postvalue_from_absoluteURI.MAXLEN:cache.clear()
cache[url] = path
return path
_get_postvalue_from_absoluteURI.cache = {}
_get_postvalue_from_absoluteURI.MAXLEN = 20
##
## Exception classes.
class ZSIException(Exception):
'''Base class for all ZSI exceptions.
'''
pass
class ParseException(ZSIException):
'''Exception raised during parsing.
'''
def __init__(self, str, inheader, elt=None, dom=None):
Exception.__init__(self)
self.str, self.inheader, self.trace = str, inheader, None
if elt and dom:
self.trace = _backtrace(elt, dom)
def __str__(self):
if self.trace:
return self.str + '\n[Element trace: ' + self.trace + ']'
return self.str
def __repr__(self):
return "<%s.ParseException %s>" % (__name__, _get_idstr(self))
class EvaluateException(ZSIException):
'''Exception raised during data evaluation (serialization).
'''
def __init__(self, str, trace=None):
Exception.__init__(self)
self.str, self.trace = str, trace
def __str__(self):
if self.trace:
return self.str + '\n[Element trace: ' + self.trace + ']'
return self.str
def __repr__(self):
return "<%s.EvaluateException %s>" % (__name__, _get_idstr(self))
class FaultException(ZSIException):
'''Exception raised when a fault is received.
'''
def __init__(self, fault):
self.fault = fault
def __str__(self):
return str(self.fault)
def __repr__(self):
return "<%s.FaultException %s>" % (__name__, _get_idstr(self))
class WSActionException(ZSIException):
'''Exception raised when WS-Address Action Header is incorrectly
specified when received by client or server.
'''
pass
##
## Importing the rest of ZSI.
import version
def Version():
return version.Version
from writer import SoapWriter
from parse import ParsedSoap
from fault import Fault, \
FaultFromActor, FaultFromException, FaultFromFaultMessage, \
FaultFromNotUnderstood, FaultFromZSIException
import TC
TC.RegisterType(TC.String, minOccurs=0, nillable=False)
TC.RegisterType(TC.URI, minOccurs=0, nillable=False)
TC.RegisterType(TC.Base64String, minOccurs=0, nillable=False)
TC.RegisterType(TC.HexBinaryString, minOccurs=0, nillable=False)
#TC.RegisterType(TC.Integer)
#TC.RegisterType(TC.Decimal)
for pyclass in (TC.IunsignedByte, TC.IunsignedShort, TC.IunsignedInt, TC.IunsignedLong,
TC.Ibyte, TC.Ishort, TC.Iint, TC.Ilong, TC.InegativeInteger,
TC.InonPositiveInteger, TC.InonNegativeInteger, TC.IpositiveInteger,
TC.Iinteger, TC.FPfloat, TC.FPdouble, ):
TC.RegisterType(pyclass, minOccurs=0, nillable=False)
TC.RegisterType(TC.Boolean, minOccurs=0, nillable=False)
TC.RegisterType(TC.Duration, minOccurs=0, nillable=False)
TC.RegisterType(TC.gDateTime, minOccurs=0, nillable=False)
TC.RegisterType(TC.gDate, minOccurs=0, nillable=False)
TC.RegisterType(TC.gYearMonth, minOccurs=0, nillable=False)
TC.RegisterType(TC.gYear, minOccurs=0, nillable=False)
TC.RegisterType(TC.gMonthDay, minOccurs=0, nillable=False)
TC.RegisterType(TC.gDay, minOccurs=0, nillable=False)
TC.RegisterType(TC.gTime, minOccurs=0, nillable=False)
TC.RegisterType(TC.Apache.Map, minOccurs=0, nillable=False)
##
## Register Wrappers for builtin types.
## TC.AnyElement wraps builtins so element name information can be saved
##
import schema
for i in [int,float,str,tuple,list,unicode]:
schema._GetPyobjWrapper.RegisterBuiltin(i)
## Load up Wrappers for builtin types
schema.RegisterAnyElement()
#try:
# from ServiceProxy import *
#except:
# pass
if __name__ == '__main__': print _copyright | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/ZSI/__init__.py | __init__.py |
import types, os, sys
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from ZSI import *
from ZSI import _child_elements, _copyright, _seqtypes, _find_arraytype, _find_type, resolvers
from ZSI.auth import _auth_tc, AUTH, ClientBinding
# Client binding information is stored in a global. We provide an accessor
# in case later on it's not.
_client_binding = None
def GetClientBinding():
'''Return the client binding object.
'''
return _client_binding
gettypecode = lambda mod,e: getattr(mod, str(e.localName)).typecode
def _Dispatch(ps, modules, SendResponse, SendFault, nsdict={}, typesmodule=None,
gettypecode=gettypecode, rpc=False, docstyle=False, **kw):
'''Find a handler for the SOAP request in ps; search modules.
Call SendResponse or SendFault to send the reply back, appropriately.
Behaviors:
default -- Call "handler" method with pyobj representation of body root, and return
a self-describing request (w/typecode). Parsing done via a typecode from
typesmodule, or Any.
docstyle -- Call "handler" method with ParsedSoap instance and parse result with an
XML typecode (DOM). Behavior, wrap result in a body_root "Response" appended message.
rpc -- Specify RPC wrapper of result. Behavior, ignore body root (RPC Wrapper)
of request, parse all "parts" of message via individual typecodes. Expect
the handler to return the parts of the message, whether it is a dict, single instance,
or a list try to serialize it as a Struct but if this is not possible put it in an Array.
Parsing done via a typecode from typesmodule, or Any.
'''
global _client_binding
try:
what = str(ps.body_root.localName)
# See what modules have the element name.
if modules is None:
modules = ( sys.modules['__main__'], )
handlers = [ getattr(m, what) for m in modules if hasattr(m, what) ]
if len(handlers) == 0:
raise TypeError("Unknown method " + what)
# Of those modules, see who's callable.
handlers = [ h for h in handlers if callable(h) ]
if len(handlers) == 0:
raise TypeError("Unimplemented method " + what)
if len(handlers) > 1:
raise TypeError("Multiple implementations found: " + `handlers`)
handler = handlers[0]
_client_binding = ClientBinding(ps)
if docstyle:
result = handler(ps.body_root)
tc = TC.XML(aslist=1, pname=what+'Response')
elif not rpc:
try:
tc = gettypecode(typesmodule, ps.body_root)
except Exception:
tc = TC.Any()
try:
arg = tc.parse(ps.body_root, ps)
except EvaluateException, ex:
SendFault(FaultFromZSIException(ex), **kw)
return
try:
result = handler(*arg)
except Exception,ex:
SendFault(FaultFromZSIException(ex), **kw)
try:
tc = result.typecode
except AttributeError,ex:
SendFault(FaultFromZSIException(ex), **kw)
elif typesmodule is not None:
kwargs = {}
for e in _child_elements(ps.body_root):
try:
tc = gettypecode(typesmodule, e)
except Exception:
tc = TC.Any()
try:
kwargs[str(e.localName)] = tc.parse(e, ps)
except EvaluateException, ex:
SendFault(FaultFromZSIException(ex), **kw)
return
result = handler(**kwargs)
aslist = False
# make sure data is wrapped, try to make this a Struct
if type(result) in _seqtypes:
for o in result:
aslist = hasattr(result, 'typecode')
if aslist: break
elif type(result) is not dict:
aslist = not hasattr(result, 'typecode')
result = (result,)
tc = TC.Any(pname=what+'Response', aslist=aslist)
else:
# if this is an Array, call handler with list
# if this is an Struct, call handler with dict
tp = _find_type(ps.body_root)
isarray = ((type(tp) in (tuple,list) and tp[1] == 'Array') or _find_arraytype(ps.body_root))
data = _child_elements(ps.body_root)
tc = TC.Any()
if isarray and len(data) == 0:
result = handler()
elif isarray:
try: arg = [ tc.parse(e, ps) for e in data ]
except EvaluateException, e:
#SendFault(FaultFromZSIException(e), **kw)
SendFault(RuntimeError("THIS IS AN ARRAY: %s" %isarray))
return
result = handler(*arg)
else:
try: kwarg = dict([ (str(e.localName),tc.parse(e, ps)) for e in data ])
except EvaluateException, e:
SendFault(FaultFromZSIException(e), **kw)
return
result = handler(**kwarg)
# reponse typecode
#tc = getattr(result, 'typecode', TC.Any(pname=what+'Response'))
tc = TC.Any(pname=what+'Response')
sw = SoapWriter(nsdict=nsdict)
sw.serialize(result, tc)
return SendResponse(str(sw), **kw)
except Fault, e:
return SendFault(e, **kw)
except Exception, e:
# Something went wrong, send a fault.
return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)
def _ModPythonSendXML(text, code=200, **kw):
req = kw['request']
req.content_type = 'text/xml'
req.content_length = len(text)
req.send_http_header()
req.write(text)
def _ModPythonSendFault(f, **kw):
_ModPythonSendXML(f.AsSOAP(), 500, **kw)
def _JonPySendFault(f, **kw):
_JonPySendXML(f.AsSOAP(), 500, **kw)
def _JonPySendXML(text, code=200, **kw):
req = kw['request']
req.set_header("Content-Type", 'text/xml; charset="utf-8"')
req.set_header("Content-Length", str(len(text)))
req.write(text)
def _CGISendXML(text, code=200, **kw):
print 'Status: %d' % code
print 'Content-Type: text/xml; charset="utf-8"'
print 'Content-Length: %d' % len(text)
print ''
print text
def _CGISendFault(f, **kw):
_CGISendXML(f.AsSOAP(), 500, **kw)
class SOAPRequestHandler(BaseHTTPRequestHandler):
'''SOAP handler.
'''
server_version = 'ZSI/1.1 ' + BaseHTTPRequestHandler.server_version
def send_xml(self, text, code=200):
'''Send some XML.
'''
self.send_response(code)
self.send_header('Content-type', 'text/xml; charset="utf-8"')
self.send_header('Content-Length', str(len(text)))
self.end_headers()
self.wfile.write(text)
self.wfile.flush()
def send_fault(self, f, code=500):
'''Send a fault.
'''
self.send_xml(f.AsSOAP(), code)
def do_POST(self):
'''The POST command.
'''
try:
ct = self.headers['content-type']
if ct.startswith('multipart/'):
cid = resolvers.MIMEResolver(ct, self.rfile)
xml = cid.GetSOAPPart()
ps = ParsedSoap(xml, resolver=cid.Resolve)
else:
length = int(self.headers['content-length'])
ps = ParsedSoap(self.rfile.read(length))
except ParseException, e:
self.send_fault(FaultFromZSIException(e))
return
except Exception, e:
# Faulted while processing; assume it's in the header.
self.send_fault(FaultFromException(e, 1, sys.exc_info()[2]))
return
_Dispatch(ps, self.server.modules, self.send_xml, self.send_fault,
docstyle=self.server.docstyle, nsdict=self.server.nsdict,
typesmodule=self.server.typesmodule, rpc=self.server.rpc)
def AsServer(port=80, modules=None, docstyle=False, nsdict={}, typesmodule=None,
rpc=False, addr=''):
address = (addr, port)
httpd = HTTPServer(address, SOAPRequestHandler)
httpd.modules = modules
httpd.docstyle = docstyle
httpd.nsdict = nsdict
httpd.typesmodule = typesmodule
httpd.rpc = rpc
httpd.serve_forever()
def AsCGI(nsdict={}, typesmodule=None, rpc=False, modules=None):
'''Dispatch within a CGI script.
'''
if os.environ.get('REQUEST_METHOD') != 'POST':
_CGISendFault(Fault(Fault.Client, 'Must use POST'))
return
ct = os.environ['CONTENT_TYPE']
try:
if ct.startswith('multipart/'):
cid = resolvers.MIMEResolver(ct, sys.stdin)
xml = cid.GetSOAPPart()
ps = ParsedSoap(xml, resolver=cid.Resolve)
else:
length = int(os.environ['CONTENT_LENGTH'])
ps = ParsedSoap(sys.stdin.read(length))
except ParseException, e:
_CGISendFault(FaultFromZSIException(e))
return
_Dispatch(ps, modules, _CGISendXML, _CGISendFault, nsdict=nsdict,
typesmodule=typesmodule, rpc=rpc)
def AsHandler(request=None, modules=None, **kw):
'''Dispatch from within ModPython.'''
ps = ParsedSoap(request)
kw['request'] = request
_Dispatch(ps, modules, _ModPythonSendXML, _ModPythonSendFault, **kw)
def AsJonPy(request=None, modules=None, **kw):
'''Dispatch within a jonpy CGI/FastCGI script.
'''
kw['request'] = request
if request.environ.get('REQUEST_METHOD') != 'POST':
_JonPySendFault(Fault(Fault.Client, 'Must use POST'), **kw)
return
ct = request.environ['CONTENT_TYPE']
try:
if ct.startswith('multipart/'):
cid = resolvers.MIMEResolver(ct, request.stdin)
xml = cid.GetSOAPPart()
ps = ParsedSoap(xml, resolver=cid.Resolve)
else:
length = int(request.environ['CONTENT_LENGTH'])
ps = ParsedSoap(request.stdin.read(length))
except ParseException, e:
_JonPySendFault(FaultFromZSIException(e), **kw)
return
_Dispatch(ps, modules, _JonPySendXML, _JonPySendFault, **kw)
if __name__ == '__main__': print _copyright | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/ZSI/dispatch.py | dispatch.py |
from ZSI import _copyright, _children, _child_elements, \
_inttypes, _stringtypes, _seqtypes, _find_arraytype, _find_href, \
_find_type, _find_xmlns_prefix, _get_idstr, EvaluateException, \
ParseException
from TC import _get_element_nsuri_name, \
_get_xsitype, TypeCode, Any, AnyElement, AnyType, \
Nilled, UNBOUNDED
from schema import ElementDeclaration, TypeDefinition, \
_get_substitute_element, _get_type_definition
from ZSI.wstools.Namespaces import SCHEMA, SOAP
from ZSI.wstools.Utility import SplitQName
from ZSI.wstools.logging import getLogger as _GetLogger
import re, types
_find_arrayoffset = lambda E: E.getAttributeNS(SOAP.ENC, "offset")
_find_arrayposition = lambda E: E.getAttributeNS(SOAP.ENC, "position")
_offset_pat = re.compile(r'\[[0-9]+\]')
_position_pat = _offset_pat
def _check_typecode_list(ofwhat, tcname):
'''Check a list of typecodes for compliance with Struct
requirements.'''
for o in ofwhat:
if callable(o): #skip if _Mirage
continue
if not isinstance(o, TypeCode):
raise TypeError(
tcname + ' ofwhat outside the TypeCode hierarchy, ' +
str(o.__class__))
if o.pname is None and not isinstance(o, AnyElement):
raise TypeError(tcname + ' element ' + str(o) + ' has no name')
def _get_type_or_substitute(typecode, pyobj, sw, elt):
'''return typecode or substitute type for wildcard or
derived type. For serialization only.
'''
sub = getattr(pyobj, 'typecode', typecode)
if sub is typecode or sub is None:
return typecode
# Element WildCard
if isinstance(typecode, AnyElement):
return sub
# Global Element Declaration
if isinstance(sub, ElementDeclaration):
if (typecode.nspname,typecode.pname) == (sub.nspname,sub.pname):
raise TypeError(\
'bad usage, failed to serialize element reference (%s, %s), in: %s' %
(typecode.nspname, typecode.pname, sw.Backtrace(elt),))
raise TypeError(\
'failed to serialize (%s, %s) illegal sub GED (%s,%s): %s' %
(typecode.nspname, typecode.pname, sub.nspname, sub.pname,
sw.Backtrace(elt),))
# Local Element
if not isinstance(typecode, AnyType) and not isinstance(sub, typecode.__class__):
raise TypeError(\
'failed to serialize substitute %s for %s, not derivation: %s' %
(sub, typecode, sw.Backtrace(elt),))
sub.nspname = typecode.nspname
sub.pname = typecode.pname
sub.aname = typecode.aname
sub.minOccurs = 1
sub.maxOccurs = 1
return sub
def _get_any_instances(ofwhat, d):
'''Run thru list ofwhat.anames and find unmatched keys in value
dictionary d. Assume these are element wildcard instances.
'''
any_keys = []
anames = map(lambda what: what.aname, ofwhat)
for aname,pyobj in d.items():
if isinstance(pyobj, AnyType) or aname in anames or pyobj is None:
continue
any_keys.append(aname)
return any_keys
class ComplexType(TypeCode):
'''Represents an element of complexType, potentially containing other
elements.
'''
logger = _GetLogger('ZSI.TCcompound.ComplexType')
def __init__(self, pyclass, ofwhat, pname=None, inorder=False, inline=False,
mutable=True, mixed=False, mixed_aname='_text', **kw):
'''pyclass -- the Python class to hold the fields
ofwhat -- a list of fields to be in the complexType
inorder -- fields must be in exact order or not
inline -- don't href/id when serializing
mutable -- object could change between multiple serializations
type -- the (URI,localname) of the datatype
mixed -- mixed content model? True/False
mixed_aname -- if mixed is True, specify text content here. Default _text
'''
TypeCode.__init__(self, pname, pyclass=pyclass, **kw)
self.inorder = inorder
self.inline = inline
self.mutable = mutable
self.mixed = mixed
self.mixed_aname = None
if mixed is True:
self.mixed_aname = mixed_aname
if self.mutable is True: self.inline = True
self.type = kw.get('type') or _get_xsitype(self)
t = type(ofwhat)
if t not in _seqtypes:
raise TypeError(
'Struct ofwhat must be list or sequence, not ' + str(t))
self.ofwhat = tuple(ofwhat)
if TypeCode.typechecks:
# XXX Not sure how to determine if new-style class..
if self.pyclass is not None and \
type(self.pyclass) is not types.ClassType and not isinstance(self.pyclass, object):
raise TypeError('pyclass must be None or an old-style/new-style class, not ' +
str(type(self.pyclass)))
_check_typecode_list(self.ofwhat, 'ComplexType')
def parse(self, elt, ps):
debug = self.logger.debugOn()
debug and self.logger.debug('parse')
xtype = self.checkname(elt, ps)
if self.type and xtype not in [ self.type, (None,None) ]:
if not isinstance(self, TypeDefinition):
raise EvaluateException(\
'ComplexType for %s has wrong type(%s), looking for %s' %
(self.pname, self.checktype(elt,ps), self.type),
ps.Backtrace(elt))
else:
#TODO: mabye change MRO to handle this
debug and self.logger.debug('delegate to substitute type')
what = TypeDefinition.getSubstituteType(self, elt, ps)
return what.parse(elt, ps)
href = _find_href(elt)
if href:
if _children(elt):
raise EvaluateException('Struct has content and HREF',
ps.Backtrace(elt))
elt = ps.FindLocalHREF(href, elt)
c = _child_elements(elt)
count = len(c)
if self.nilled(elt, ps): return Nilled
# Create the object.
v = {}
# parse all attributes contained in attribute_typecode_dict (user-defined attributes),
# the values (if not None) will be keyed in self.attributes dictionary.
attributes = self.parse_attributes(elt, ps)
if attributes:
v[self.attrs_aname] = attributes
#MIXED
if self.mixed is True:
v[self.mixed_aname] = self.simple_value(elt,ps, mixed=True)
# Clone list of kids (we null it out as we process)
c, crange = c[:], range(len(c))
# Loop over all items we're expecting
if debug:
self.logger.debug("ofwhat: %s",str(self.ofwhat))
any = None
for i,what in [ (i, self.ofwhat[i]) for i in range(len(self.ofwhat)) ]:
# retrieve typecode if it is hidden
if callable(what): what = what()
# Loop over all available kids
if debug:
self.logger.debug("what: (%s,%s)", what.nspname, what.pname)
for j,c_elt in [ (j, c[j]) for j in crange if c[j] ]:
if debug:
self.logger.debug("child node: (%s,%s)", c_elt.namespaceURI,
c_elt.tagName)
if what.name_match(c_elt):
# Parse value, and mark this one done.
try:
value = what.parse(c_elt, ps)
except EvaluateException, e:
#what = _get_substitute_element(c_elt, what)
#value = what.parse(c_elt, ps)
raise
if what.maxOccurs > 1:
if v.has_key(what.aname):
v[what.aname].append(value)
else:
v[what.aname] = [value]
c[j] = None
continue
else:
v[what.aname] = value
c[j] = None
break
else:
if debug:
self.logger.debug("no element (%s,%s)",
what.nspname, what.pname)
# No match; if it was supposed to be here, that's an error.
if self.inorder is True and i == j:
raise EvaluateException('Out of order complexType',
ps.Backtrace(c_elt))
else:
# only supporting 1 <any> declaration in content.
if isinstance(what,AnyElement):
any = what
elif hasattr(what, 'default'):
v[what.aname] = what.default
elif what.minOccurs > 0 and not v.has_key(what.aname):
raise EvaluateException('Element "' + what.aname + \
'" missing from complexType', ps.Backtrace(elt))
# Look for wildcards and unprocessed children
# XXX Stick all this stuff in "any", hope for no collisions
if any is not None:
occurs = 0
v[any.aname] = []
for j,c_elt in [ (j, c[j]) for j in crange if c[j] ]:
value = any.parse(c_elt, ps)
if any.maxOccurs == UNBOUNDED or any.maxOccurs > 1:
v[any.aname].append(value)
else:
v[any.aname] = value
occurs += 1
# No such thing as nillable <any>
if any.maxOccurs == 1 and occurs == 0:
v[any.aname] = None
elif occurs < any.minOccurs or (any.maxOccurs!=UNBOUNDED and any.maxOccurs<occurs):
raise EvaluateException('occurances of <any> elements(#%d) bound by (%d,%s)' %(
occurs, any.minOccurs,str(any.maxOccurs)), ps.Backtrace(elt))
if not self.pyclass:
return v
# type definition must be informed of element tag (nspname,pname),
# element declaration is initialized with a tag.
try:
pyobj = self.pyclass()
except Exception, e:
raise TypeError("Constructing element (%s,%s) with pyclass(%s), %s" \
%(self.nspname, self.pname, self.pyclass.__name__, str(e)))
for key in v.keys():
setattr(pyobj, key, v[key])
return pyobj
def serialize(self, elt, sw, pyobj, inline=False, name=None, **kw):
if inline or self.inline:
self.cb(elt, sw, pyobj, name=name, **kw)
else:
objid = _get_idstr(pyobj)
ns,n = self.get_name(name, objid)
el = elt.createAppendElement(ns, n)
el.setAttributeNS(None, 'href', "#%s" %objid)
sw.AddCallback(self.cb, elt, sw, pyobj)
def cb(self, elt, sw, pyobj, name=None, **kw):
debug = self.logger.debugOn()
if debug:
self.logger.debug("cb: %s" %str(self.ofwhat))
objid = _get_idstr(pyobj)
ns,n = self.get_name(name, objid)
if pyobj is None:
if self.nillable is True:
elem = elt.createAppendElement(ns, n)
self.serialize_as_nil(elem)
return
raise EvaluateException, 'element(%s,%s) is not nillable(%s)' %(
self.nspname,self.pname,self.nillable)
if self.mutable is False and sw.Known(pyobj):
return
if debug:
self.logger.debug("element: (%s, %s)", str(ns), n)
if n is not None:
elem = elt.createAppendElement(ns, n)
self.set_attributes(elem, pyobj)
if kw.get('typed', self.typed) is True:
self.set_attribute_xsi_type(elem)
#MIXED For now just stick it in front.
if self.mixed is True and self.mixed_aname is not None:
if hasattr(pyobj, self.mixed_aname):
textContent = getattr(pyobj, self.mixed_aname)
if hasattr(textContent, 'typecode'):
textContent.typecode.serialize_text_node(elem, sw, textContent)
elif type(textContent) in _stringtypes:
if debug:
self.logger.debug("mixed text content:\n\t%s",
textContent)
elem.createAppendTextNode(textContent)
else:
raise EvaluateException('mixed test content in element (%s,%s) must be a string type' %(
self.nspname,self.pname), sw.Backtrace(elt))
else:
if debug:
self.logger.debug("mixed NO text content in %s",
self.mixed_aname)
else:
#For information items w/o tagNames
# ie. model groups,SOAP-ENC:Header
elem = elt
if self.inline:
pass
elif not self.inline and self.unique:
raise EvaluateException('Not inline, but unique makes no sense. No href/id.',
sw.Backtrace(elt))
elif n is not None:
self.set_attribute_id(elem, objid)
if self.pyclass and type(self.pyclass) is type:
f = lambda attr: getattr(pyobj, attr, None)
elif self.pyclass:
d = pyobj.__dict__
f = lambda attr: d.get(attr)
else:
d = pyobj
f = lambda attr: pyobj.get(attr)
if TypeCode.typechecks and type(d) != types.DictType:
raise TypeError("Classless struct didn't get dictionary")
indx, lenofwhat = 0, len(self.ofwhat)
if debug:
self.logger.debug('element declaration (%s,%s)', self.nspname,
self.pname)
if self.type:
self.logger.debug('xsi:type definition (%s,%s)', self.type[0],
self.type[1])
else:
self.logger.warning('NO xsi:type')
while indx < lenofwhat:
occurs = 0
what = self.ofwhat[indx]
# retrieve typecode if hidden
if callable(what): what = what()
if debug:
self.logger.debug('serialize what -- %s',
what.__class__.__name__)
# No way to order <any> instances, so just grab any unmatched
# anames and serialize them. Only support one <any> in all content.
# Must be self-describing instances
# Regular handling of declared elements
aname = what.aname
v = f(aname)
indx += 1
if what.minOccurs == 0 and v is None:
continue
# Default to typecode, if self-describing instance, and check
# to make sure it is derived from what.
whatTC = what
if whatTC.maxOccurs > 1 and v is not None:
if type(v) not in _seqtypes:
raise EvaluateException('pyobj (%s,%s), aname "%s": maxOccurs %s, expecting a %s' %(
self.nspname,self.pname,what.aname,whatTC.maxOccurs,_seqtypes),
sw.Backtrace(elt))
for v2 in v:
occurs += 1
if occurs > whatTC.maxOccurs:
raise EvaluateException('occurances (%d) exceeded maxOccurs(%d) for <%s>' %(
occurs, whatTC.maxOccurs, what.pname),
sw.Backtrace(elt))
what = _get_type_or_substitute(whatTC, v2, sw, elt)
if debug and what is not whatTC:
self.logger.debug('substitute derived type: %s' %
what.__class__)
what.serialize(elem, sw, v2, **kw)
# try:
# what.serialize(elem, sw, v2, **kw)
# except Exception, e:
# raise EvaluateException('Serializing %s.%s, %s %s' %
# (n, whatTC.aname or '?', e.__class__.__name__, str(e)))
if occurs < whatTC.minOccurs:
raise EvaluateException(\
'occurances(%d) less than minOccurs(%d) for <%s>' %
(occurs, whatTC.minOccurs, what.pname), sw.Backtrace(elt))
continue
if v is not None or what.nillable is True:
what = _get_type_or_substitute(whatTC, v, sw, elt)
if debug and what is not whatTC:
self.logger.debug('substitute derived type: %s' %
what.__class__)
what.serialize(elem, sw, v, **kw)
# try:
# what.serialize(elem, sw, v, **kw)
# except (ParseException, EvaluateException), e:
# raise
# except Exception, e:
# raise EvaluateException('Serializing %s.%s, %s %s' %
# (n, whatTC.aname or '?', e.__class__.__name__, str(e)),
# sw.Backtrace(elt))
continue
raise EvaluateException('Got None for nillable(%s), minOccurs(%d) element (%s,%s), %s' %
(what.nillable, what.minOccurs, what.nspname, what.pname, elem),
sw.Backtrace(elt))
def setDerivedTypeContents(self, extensions=None, restrictions=None):
"""For derived types set appropriate parameter and
"""
if extensions:
ofwhat = list(self.ofwhat)
if type(extensions) in _seqtypes:
ofwhat += list(extensions)
else:
ofwhat.append(extensions)
elif restrictions:
if type(restrictions) in _seqtypes:
ofwhat = restrictions
else:
ofwhat = (restrictions,)
else:
return
self.ofwhat = tuple(ofwhat)
self.lenofwhat = len(self.ofwhat)
class Struct(ComplexType):
'''Struct is a complex type for accessors identified by name.
Constraint: No element may have the same name as any other,
nor may any element have a maxOccurs > 1.
<xs:group name="Struct" >
<xs:sequence>
<xs:any namespace="##any" minOccurs="0" maxOccurs="unbounded" processContents="lax" />
</xs:sequence>
</xs:group>
<xs:complexType name="Struct" >
<xs:group ref="tns:Struct" minOccurs="0" />
<xs:attributeGroup ref="tns:commonAttributes"/>
</xs:complexType>
'''
logger = _GetLogger('ZSI.TCcompound.Struct')
def __init__(self, pyclass, ofwhat, pname=None, inorder=False, inline=False,
mutable=True, **kw):
'''pyclass -- the Python class to hold the fields
ofwhat -- a list of fields to be in the struct
inorder -- fields must be in exact order or not
inline -- don't href/id when serializing
mutable -- object could change between multiple serializations
'''
ComplexType.__init__(self, pyclass, ofwhat, pname=pname,
inorder=inorder, inline=inline, mutable=mutable,
**kw
)
# Check Constraints
whats = map(lambda what: (what.nspname,what.pname), self.ofwhat)
for idx in range(len(self.ofwhat)):
what = self.ofwhat[idx]
key = (what.nspname,what.pname)
if not isinstance(what, AnyElement) and what.maxOccurs > 1:
raise TypeError,\
'Constraint: no element can have a maxOccurs>1'
if key in whats[idx+1:]:
raise TypeError,\
'Constraint: No element may have the same name as any other'
class Array(TypeCode):
'''An array.
atype -- arrayType, (namespace,ncname)
mutable -- object could change between multiple serializations
undeclared -- do not serialize/parse arrayType attribute.
'''
logger = _GetLogger('ZSI.TCcompound.Array')
def __init__(self, atype, ofwhat, pname=None, dimensions=1, fill=None,
sparse=False, mutable=False, size=None, nooffset=0, undeclared=False,
childnames=None, **kw):
TypeCode.__init__(self, pname, **kw)
self.dimensions = dimensions
self.atype = atype
if undeclared is False and self.atype[1].endswith(']') is False:
self.atype = (self.atype[0], '%s[]' %self.atype[1])
# Support multiple dimensions
if self.dimensions != 1:
raise TypeError("Only single-dimensioned arrays supported")
self.fill = fill
self.sparse = sparse
#if self.sparse: ofwhat.minOccurs = 0
self.mutable = mutable
self.size = size
self.nooffset = nooffset
self.undeclared = undeclared
self.childnames = childnames
if self.size:
t = type(self.size)
if t in _inttypes:
self.size = (self.size,)
elif t in _seqtypes:
self.size = tuple(self.size)
elif TypeCode.typechecks:
raise TypeError('Size must be integer or list, not ' + str(t))
if TypeCode.typechecks:
if self.undeclared is False and type(atype) not in _seqtypes and len(atype) == 2:
raise TypeError("Array type must be a sequence of len 2.")
t = type(ofwhat)
if not isinstance(ofwhat, TypeCode):
raise TypeError(
'Array ofwhat outside the TypeCode hierarchy, ' +
str(ofwhat.__class__))
if self.size:
if len(self.size) != self.dimensions:
raise TypeError('Array dimension/size mismatch')
for s in self.size:
if type(s) not in _inttypes:
raise TypeError('Array size "' + str(s) +
'" is not an integer.')
self.ofwhat = ofwhat
def parse_offset(self, elt, ps):
o = _find_arrayoffset(elt)
if not o: return 0
if not _offset_pat.match(o):
raise EvaluateException('Bad offset "' + o + '"',
ps.Backtrace(elt))
return int(o[1:-1])
def parse_position(self, elt, ps):
o = _find_arrayposition(elt)
if not o: return None
if o.find(','):
raise EvaluateException('Sorry, no multi-dimensional arrays',
ps.Backtrace(elt))
if not _position_pat.match(o):
raise EvaluateException('Bad array position "' + o + '"',
ps.Backtrace(elt))
return int(o[-1:1])
def parse(self, elt, ps):
href = _find_href(elt)
if href:
if _children(elt):
raise EvaluateException('Array has content and HREF',
ps.Backtrace(elt))
elt = ps.FindLocalHREF(href, elt)
if self.nilled(elt, ps): return Nilled
if not _find_arraytype(elt) and self.undeclared is False:
raise EvaluateException('Array expected', ps.Backtrace(elt))
t = _find_type(elt)
if t:
pass # XXX should check the type, but parsing that is hairy.
offset = self.parse_offset(elt, ps)
v, vlen = [], 0
if offset and not self.sparse:
while vlen < offset:
vlen += 1
v.append(self.fill)
for c in _child_elements(elt):
item = self.ofwhat.parse(c, ps)
position = self.parse_position(c, ps) or offset
if self.sparse:
v.append((position, item))
else:
while offset < position:
offset += 1
v.append(self.fill)
v.append(item)
offset += 1
return v
def serialize(self, elt, sw, pyobj, name=None, childnames=None, **kw):
debug = self.logger.debugOn()
if debug:
self.logger.debug("serialize: %r" %pyobj)
if self.mutable is False and sw.Known(pyobj): return
objid = _get_idstr(pyobj)
ns,n = self.get_name(name, objid)
el = elt.createAppendElement(ns, n)
# nillable
if self.nillable is True and pyobj is None:
self.serialize_as_nil(el)
return None
# other attributes
self.set_attributes(el, pyobj)
# soap href attribute
unique = self.unique or kw.get('unique', False)
if unique is False and sw.Known(pyobj):
self.set_attribute_href(el, objid)
return None
# xsi:type attribute
if kw.get('typed', self.typed) is True:
self.set_attribute_xsi_type(el, **kw)
# soap id attribute
if self.unique is False:
self.set_attribute_id(el, objid)
offset = 0
if self.sparse is False and self.nooffset is False:
offset, end = 0, len(pyobj)
while offset < end and pyobj[offset] == self.fill:
offset += 1
if offset:
el.setAttributeNS(SOAP.ENC, 'offset', '[%d]' %offset)
if self.undeclared is False:
el.setAttributeNS(SOAP.ENC, 'arrayType',
'%s:%s' %(el.getPrefix(self.atype[0]), self.atype[1])
)
if debug:
self.logger.debug("ofwhat: %r" %self.ofwhat)
d = {}
kn = childnames or self.childnames
if kn:
d['name'] = kn
elif not self.ofwhat.aname:
d['name'] = 'element'
if self.sparse is False:
for e in pyobj[offset:]: self.ofwhat.serialize(el, sw, e, **d)
else:
position = 0
for pos, v in pyobj:
if pos != position:
el.setAttributeNS(SOAP.ENC, 'position', '[%d]' %pos)
position = pos
self.ofwhat.serialize(el, sw, v, **d)
position += 1
if __name__ == '__main__': print _copyright | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/ZSI/TCcompound.py | TCcompound.py |
# contains text container classes for new generation generator
# $Id: containers.py 1276 2006-10-23 23:18:07Z boverhof $
import types
from utility import StringWriter, TextProtect, TextProtectAttributeName,\
GetPartsSubNames
from utility import NamespaceAliasDict as NAD, NCName_to_ClassName as NC_to_CN
import ZSI
from ZSI.TC import _is_xsd_or_soap_ns
from ZSI.wstools import XMLSchema, WSDLTools
from ZSI.wstools.Namespaces import SCHEMA, SOAP, WSDL
from ZSI.wstools.logging import getLogger as _GetLogger
from ZSI.typeinterpreter import BaseTypeInterpreter
from ZSI.generate import WSISpec, WSInteropError, Wsdl2PythonError,\
WsdlGeneratorError, WSDLFormatError
ID1 = ' '
ID2 = 2*ID1
ID3 = 3*ID1
ID4 = 4*ID1
ID5 = 5*ID1
ID6 = 6*ID1
KW = {'ID1':ID1, 'ID2':ID2, 'ID3':ID3,'ID4':ID4, 'ID5':ID5, 'ID6':ID6,}
DEC = '_Dec'
DEF = '_Def'
"""
type_class_name -- function to return the name formatted as a type class.
element_class_name -- function to return the name formatted as an element class.
"""
type_class_name = lambda n: '%s%s' %(NC_to_CN(n), DEF)
element_class_name = lambda n: '%s%s' %(NC_to_CN(n), DEC)
def IsRPC(item):
"""item -- OperationBinding instance.
"""
if not isinstance(item, WSDLTools.OperationBinding):
raise TypeError, 'IsRPC takes 1 argument of type WSDLTools.OperationBinding'
soapbinding = item.getBinding().findBinding(WSDLTools.SoapBinding)
sob = item.findBinding(WSDLTools.SoapOperationBinding)
style = soapbinding.style
if sob is not None:
style = sob.style or soapbinding.style
return style == 'rpc'
def IsLiteral(item):
"""item -- MessageRoleBinding instance.
"""
if not isinstance(item, WSDLTools.MessageRoleBinding):
raise TypeError, 'IsLiteral takes 1 argument of type WSDLTools.MessageRoleBinding'
sbb = None
if item.type == 'input' or item.type == 'output':
sbb = item.findBinding(WSDLTools.SoapBodyBinding)
if sbb is None:
raise ValueError, 'Missing soap:body binding.'
return sbb.use == 'literal'
def SetTypeNameFunc(func):
global type_class_name
type_class_name = func
def SetElementNameFunc(func):
global element_class_name
element_class_name = func
def GetClassNameFromSchemaItem(item,do_extended=False):
'''
'''
assert isinstance(item, XMLSchema.XMLSchemaComponent), 'must be a schema item.'
alias = NAD.getAlias(item.getTargetNamespace())
if item.isDefinition() is True:
return '%s.%s' %(alias, NC_to_CN('%s' %type_class_name(item.getAttributeName())))
return None
def FromMessageGetSimpleElementDeclaration(message):
'''If message consists of one part with an element attribute,
and this element is a simpleType return a string representing
the python type, else return None.
'''
assert isinstance(message, WSDLTools.Message), 'expecting WSDLTools.Message'
if len(message.parts) == 1 and message.parts[0].element is not None:
part = message.parts[0]
nsuri,name = part.element
wsdl = message.getWSDL()
types = wsdl.types
if types.has_key(nsuri) and types[nsuri].elements.has_key(name):
e = types[nsuri].elements[name]
if isinstance(e, XMLSchema.ElementDeclaration) is True and e.getAttribute('type'):
typ = e.getAttribute('type')
bt = BaseTypeInterpreter()
ptype = bt.get_pythontype(typ[1], typ[0])
return ptype
return None
class AttributeMixIn:
'''for containers that can declare attributes.
Class Attributes:
attribute_typecode -- typecode attribute name typecode dict
built_in_refs -- attribute references that point to built-in
types. Skip resolving them into attribute declarations.
'''
attribute_typecode = 'self.attribute_typecode_dict'
built_in_refs = [(SOAP.ENC, 'arrayType'),]
def _setAttributes(self, attributes):
'''parameters
attributes -- a flat list of all attributes,
from this list all items in attribute_typecode_dict will
be generated into attrComponents.
returns a list of strings representing the attribute_typecode_dict.
'''
atd = self.attribute_typecode
atd_list = formatted_attribute_list = []
if not attributes:
return formatted_attribute_list
atd_list.append('# attribute handling code')
for a in attributes:
if a.isWildCard() and a.isDeclaration():
atd_list.append(\
'%s[("%s","anyAttribute")] = ZSI.TC.AnyElement()'\
% (atd, SCHEMA.XSD3)
)
elif a.isDeclaration():
tdef = a.getTypeDefinition('type')
if tdef is not None:
tc = '%s.%s(None)' %(NAD.getAlias(tdef.getTargetNamespace()),
self.mangle(type_class_name(tdef.getAttributeName()))
)
else:
# built-in
t = a.getAttribute('type')
try:
tc = BTI.get_typeclass(t[1], t[0])
except:
# hand back a string by default.
tc = ZSI.TC.String
if tc is not None:
tc = '%s()' %tc
key = None
if a.getAttribute('form') == 'qualified':
key = '("%s","%s")' % ( a.getTargetNamespace(),
a.getAttribute('name') )
elif a.getAttribute('form') == 'unqualified':
key = '"%s"' % a.getAttribute('name')
else:
raise ContainerError, \
'attribute form must be un/qualified %s' \
% a.getAttribute('form')
atd_list.append(\
'%s[%s] = %s' % (atd, key, tc)
)
elif a.isReference() and a.isAttributeGroup():
# flatten 'em out....
for ga in a.getAttributeGroup().getAttributeContent():
if not ga.isAttributeGroup():
attributes += (ga,)
continue
elif a.isReference():
try:
ga = a.getAttributeDeclaration()
except XMLSchema.SchemaError:
key = a.getAttribute('ref')
self.logger.debug('No schema item for attribute ref (%s, %s)' %key)
if key in self.built_in_refs: continue
raise
tp = None
if ga is not None:
tp = ga.getTypeDefinition('type')
key = '("%s","%s")' %(ga.getTargetNamespace(),
ga.getAttribute('name'))
if ga is None:
# TODO: probably SOAPENC:arrayType
key = '("%s","%s")' %(
a.getAttribute('ref').getTargetNamespace(),
a.getAttribute('ref').getName())
atd_list.append(\
'%s[%s] = ZSI.TC.String()' %(atd, key)
)
elif tp is None:
# built in simple type
try:
namespace,typeName = ga.getAttribute('type')
except TypeError, ex:
# TODO: attribute declaration could be anonymous type
# hack in something to work
atd_list.append(\
'%s[%s] = ZSI.TC.String()' %(atd, key)
)
else:
atd_list.append(\
'%s[%s] = %s()' %(atd, key,
BTI.get_typeclass(typeName, namespace))
)
else:
typeName = tp.getAttribute('name')
namespace = tp.getTargetNamespace()
alias = NAD.getAlias(namespace)
key = '("%s","%s")' \
% (ga.getTargetNamespace(),ga.getAttribute('name'))
atd_list.append(\
'%s[%s] = %s.%s(None)' \
% (atd, key, alias, type_class_name(typeName))
)
else:
raise TypeError, 'expecting an attribute: %s' %a.getItemTrace()
return formatted_attribute_list
class ContainerError(Exception):
pass
class ContainerBase:
'''Base class for all Containers.
func_aname -- function that takes name, and returns aname.
'''
func_aname = TextProtectAttributeName
func_aname = staticmethod(func_aname)
logger = _GetLogger("ContainerBase")
def __init__(self):
self.content = StringWriter('\n')
self.__setup = False
self.ns = None
def __str__(self):
return self.getvalue()
# - string content methods
def mangle(self, s):
'''class/variable name illegalities
'''
return TextProtect(s)
def write(self, s):
self.content.write(s)
def writeArray(self, a):
self.content.write('\n'.join(a))
def _setContent(self):
'''override in subclasses. formats the content in the desired way.
'''
raise NotImplementedError, 'abstract method not implemented'
def getvalue(self):
if not self.__setup:
self._setContent()
self.__setup = True
return self.content.getvalue()
# - namespace utility methods
def getNSAlias(self):
if self.ns:
return NAD.getAlias(self.ns)
raise ContainerError, 'no self.ns attr defined in %s' % self.__class__
def getNSModuleName(self):
if self.ns:
return NAD.getModuleName(self.ns)
raise ContainerError, 'no self.ns attr defined in %s' % self.__class__
def getAttributeName(self, name):
'''represents the aname
'''
if self.func_aname is None:
return name
assert callable(self.func_aname), \
'expecting callable method for attribute func_aname, not %s' %type(self.func_aname)
f = self.func_aname
return f(name)
# -- containers for services file components
class ServiceContainerBase(ContainerBase):
clientClassSuffix = "SOAP"
logger = _GetLogger("ServiceContainerBase")
class ServiceHeaderContainer(ServiceContainerBase):
imports = ['\nimport urlparse, types',
'from ZSI.TCcompound import ComplexType, Struct',
'from ZSI import client',
'import ZSI'
]
logger = _GetLogger("ServiceHeaderContainer")
def __init__(self, do_extended=False):
ServiceContainerBase.__init__(self)
self.basic = self.imports[:]
self.types = None
self.messages = None
self.extras = []
self.do_extended = do_extended
def setTypesModuleName(self, module):
self.types = module
def setMessagesModuleName(self, module):
self.messages = module
def appendImport(self, statement):
'''append additional import statement(s).
import_stament -- tuple or list or str
'''
if type(statement) in (list,tuple):
self.extras += statement
else:
self.extras.append(statement)
def _setContent(self):
if self.messages:
self.write('from %s import *' % self.messages)
if self.types:
self.write('from %s import *' % self.types)
imports = self.basic[:]
imports += self.extras
self.writeArray(imports)
class ServiceLocatorContainer(ServiceContainerBase):
logger = _GetLogger("ServiceLocatorContainer")
def __init__(self):
ServiceContainerBase.__init__(self)
self.serviceName = None
self.portInfo = []
self.locatorName = None
self.portMethods = []
def setUp(self, service):
assert isinstance(service, WSDLTools.Service), \
'expecting WDSLTools.Service instance.'
self.serviceName = service.name
for p in service.ports:
try:
ab = p.getAddressBinding()
except WSDLTools.WSDLError, ex:
self.logger.warning('Skip port(%s), missing address binding' %p.name)
continue
if isinstance(ab, WSDLTools.SoapAddressBinding) is False:
self.logger.warning('Skip port(%s), not a SOAP-1.1 address binding' %p.name)
continue
info = (p.getBinding().getPortType().name, p.getBinding().name, ab.location)
self.portInfo.append(info)
def getLocatorName(self):
'''return class name of generated locator.
'''
return self.locatorName
def getPortMethods(self):
'''list of get port accessor methods of generated locator class.
'''
return self.portMethods
def _setContent(self):
if not self.serviceName:
raise ContainerError, 'no service name defined!'
self.serviceName = self.mangle(self.serviceName)
self.locatorName = '%sLocator' %self.serviceName
locator = ['# Locator', 'class %s:' %self.locatorName, ]
self.portMethods = []
for p in self.portInfo:
ptName = NC_to_CN(p[0])
bName = NC_to_CN(p[1])
sAdd = p[2]
method = 'get%s' %ptName
pI = [
'%s%s_address = "%s"' % (ID1, ptName, sAdd),
'%sdef get%sAddress(self):' % (ID1, ptName),
'%sreturn %sLocator.%s_address' % (ID2,
self.serviceName,ptName),
'%sdef %s(self, url=None, **kw):' %(ID1, method),
'%sreturn %s%s(url or %sLocator.%s_address, **kw)' \
% (ID2, bName, self.clientClassSuffix, self.serviceName, ptName),
]
self.portMethods.append(method)
locator += pI
self.writeArray(locator)
class ServiceOperationContainer(ServiceContainerBase):
logger = _GetLogger("ServiceOperationContainer")
def __init__(self, useWSA=False, do_extended=False):
'''Parameters:
useWSA -- boolean, enable ws-addressing
do_extended -- boolean
'''
ServiceContainerBase.__init__(self)
self.useWSA = useWSA
self.do_extended = do_extended
def hasInput(self):
return self.inputName is not None
def hasOutput(self):
return self.outputName is not None
def isRPC(self):
return IsRPC(self.binding_operation)
def isLiteral(self, input=True):
msgrole = self.binding_operation.input
if input is False:
msgrole = self.binding_operation.output
return IsLiteral(msgrole)
def isSimpleType(self, input=True):
if input is False:
return self.outputSimpleType
return self.inputSimpleType
def getOperation(self):
return self.port.operations.get(self.name)
def getBOperation(self):
return self.port.get(self.name)
def getOperationName(self):
return self.name
def setUp(self, item):
'''
Parameters:
item -- WSDLTools BindingOperation instance.
'''
if not isinstance(item, WSDLTools.OperationBinding):
raise TypeError, 'Expecting WSDLTools Operation instance'
if not item.input:
raise WSDLFormatError('No <input/> in <binding name="%s"><operation name="%s">' %(
item.getBinding().name, item.name))
self.name = None
self.port = None
self.soapaction = None
self.inputName = None
self.outputName = None
self.inputSimpleType = None
self.outputSimpleType = None
self.inputAction = None
self.outputAction = None
self.port = port = item.getBinding().getPortType()
self._wsdl = item.getWSDL()
self.name = name = item.name
self.binding_operation = bop = item
op = port.operations.get(name)
if op is None:
raise WSDLFormatError(
'<portType name="%s"/> no match for <binding name="%s"><operation name="%s">' %(
port.name, item.getBinding().name, item.name))
soap_bop = bop.findBinding(WSDLTools.SoapOperationBinding)
if soap_bop is None:
raise SOAPBindingError, 'expecting SOAP Bindings'
self.soapaction = soap_bop.soapAction
sbody = bop.input.findBinding(WSDLTools.SoapBodyBinding)
if not sbody:
raise SOAPBindingError('Missing <binding name="%s"><operation name="%s"><input><soap:body>' %(
port.binding.name, bop.name))
self.encodingStyle = None
if sbody.use == 'encoded':
assert sbody.encodingStyle == SOAP.ENC,\
'Supporting encodingStyle=%s, not %s'%(SOAP.ENC, sbody.encodingStyle)
self.encodingStyle = sbody.encodingStyle
self.inputName = op.getInputMessage().name
self.inputSimpleType = \
FromMessageGetSimpleElementDeclaration(op.getInputMessage())
self.inputAction = op.getInputAction()
if bop.output is not None:
sbody = bop.output.findBinding(WSDLTools.SoapBodyBinding)
if not item.output:
raise WSDLFormatError, "Operation %s, no match for output binding" %name
self.outputName = op.getOutputMessage().name
self.outputSimpleType = \
FromMessageGetSimpleElementDeclaration(op.getOutputMessage())
self.outputAction = op.getOutputAction()
def _setContent(self):
'''create string representation of operation.
'''
kwstring = 'kw = {}'
tCheck = 'if isinstance(request, %s) is False:' % self.inputName
bindArgs = ''
if self.encodingStyle is not None:
bindArgs = 'encodingStyle="%s", ' %self.encodingStyle
if self.useWSA:
wsactionIn = 'wsaction = "%s"' % self.inputAction
wsactionOut = 'wsaction = "%s"' % self.outputAction
bindArgs += 'wsaction=wsaction, endPointReference=self.endPointReference, '
responseArgs = ', wsaction=wsaction'
else:
wsactionIn = '# no input wsaction'
wsactionOut = '# no output wsaction'
responseArgs = ''
bindArgs += '**kw)'
if self.do_extended:
inputName = self.getOperation().getInputMessage().name
wrap_str = ""
partsList = self.getOperation().getInputMessage().parts.values()
try:
subNames = GetPartsSubNames(partsList, self._wsdl)
except TypeError, ex:
raise Wsdl2PythonError,\
"Extended generation failure: only supports doc/lit, "\
+"and all element attributes (<message><part element="\
+"\"my:GED\"></message>) must refer to single global "\
+"element declaration with complexType content. "\
+"\n\n**** TRY WITHOUT EXTENDED ****\n"
args = []
for pa in subNames:
args += pa
for arg in args:
wrap_str += "%srequest.%s = %s\n" % (ID2,
self.getAttributeName(arg),
self.mangle(arg))
#args = [pa.name for pa in self.getOperation().getInputMessage().parts.values()]
argsStr = ",".join(args)
if len(argsStr) > 1: # add inital comma if args exist
argsStr = ", " + argsStr
method = [
'%s# op: %s' % (ID1, self.getOperation().getInputMessage()),
'%sdef %s(self%s):' % (ID1, self.name, argsStr),
'\n%srequest = %s()' % (ID2, self.inputName),
'%s' % (wrap_str),
'%s%s' % (ID2, kwstring),
'%s%s' % (ID2, wsactionIn),
'%sself.binding.Send(None, None, request, soapaction="%s", %s'\
%(ID2, self.soapaction, bindArgs),
]
else:
method = [
'%s# op: %s' % (ID1, self.name),
'%sdef %s(self, request):' % (ID1, self.name),
'%s%s' % (ID2, tCheck),
'%sraise TypeError, "%%s incorrect request type" %% (%s)' %(ID3, 'request.__class__'),
'%s%s' % (ID2, kwstring),
'%s%s' % (ID2, wsactionIn),
'%sself.binding.Send(None, None, request, soapaction="%s", %s'\
%(ID2, self.soapaction, bindArgs),
]
#
# BP 1.0: rpc/literal
# WSDL 1.1 Section 3.5 could be interpreted to mean the RPC response
# wrapper element must be named identical to the name of the
# wsdl:operation.
# R2729
#
# SOAP-1.1 Note: rpc/encoded
# Each parameter accessor has a name corresponding to the name of the
# parameter and type corresponding to the type of the parameter. The name of
# the return value accessor is not significant. Likewise, the name of the struct is
# not significant. However, a convention is to name it after the method name
# with the string "Response" appended.
#
if self.outputName:
response = ['%s%s' % (ID2, wsactionOut),]
if self.isRPC() and not self.isLiteral():
# rpc/encoded Replace wrapper name with None
response.append(\
'%stypecode = Struct(pname=None, ofwhat=%s.typecode.ofwhat, pyclass=%s.typecode.pyclass)' %(
ID2, self.outputName, self.outputName)
)
response.append(\
'%sresponse = self.binding.Receive(typecode%s)' %(
ID2, responseArgs)
)
else:
response.append(\
'%sresponse = self.binding.Receive(%s.typecode%s)' %(
ID2, self.outputName, responseArgs)
)
if self.outputSimpleType:
response.append('%sreturn %s(response)' %(ID2, self.outputName))
else:
if self.do_extended:
partsList = self.getOperation().getOutputMessage().parts.values()
subNames = GetPartsSubNames(partsList, self._wsdl)
args = []
for pa in subNames:
args += pa
for arg in args:
response.append('%s%s = response.%s' % (ID2, self.mangle(arg), self.getAttributeName(arg)) )
margs = ",".join(args)
response.append("%sreturn %s" % (ID2, margs) )
else:
response.append('%sreturn response' %ID2)
method += response
self.writeArray(method)
class ServiceOperationsClassContainer(ServiceContainerBase):
'''
class variables:
readerclass --
writerclass --
operationclass -- representation of each operation.
'''
readerclass = None
writerclass = None
operationclass = ServiceOperationContainer
logger = _GetLogger("ServiceOperationsClassContainer")
def __init__(self, useWSA=False, do_extended=False, wsdl=None):
'''Parameters:
name -- binding name
property -- resource properties
useWSA -- boolean, enable ws-addressing
name -- binding name
'''
ServiceContainerBase.__init__(self)
self.useWSA = useWSA
self.rProp = None
self.bName = None
self.operations = None
self.do_extended = do_extended
self._wsdl = wsdl # None unless do_extended == True
def setReaderClass(cls, className):
'''specify a reader class name, this must be imported
in service module.
'''
cls.readerclass = className
setReaderClass = classmethod(setReaderClass)
def setWriterClass(cls, className):
'''specify a writer class name, this must be imported
in service module.
'''
cls.writerclass = className
setWriterClass = classmethod(setWriterClass)
def setOperationClass(cls, className):
'''specify an operation container class name.
'''
cls.operationclass = className
setOperationClass = classmethod(setOperationClass)
def setUp(self, port):
'''This method finds all SOAP Binding Operations, it will skip
all bindings that are not SOAP.
port -- WSDL.Port instance
'''
assert isinstance(port, WSDLTools.Port), 'expecting WSDLTools Port instance'
self.operations = []
self.bName = port.getBinding().name
self.rProp = port.getBinding().getPortType().getResourceProperties()
soap_binding = port.getBinding().findBinding(WSDLTools.SoapBinding)
if soap_binding is None:
raise Wsdl2PythonError,\
'port(%s) missing WSDLTools.SoapBinding' %port.name
for bop in port.getBinding().operations:
soap_bop = bop.findBinding(WSDLTools.SoapOperationBinding)
if soap_bop is None:
self.logger.warning(\
'Skip port(%s) operation(%s) no SOAP Binding Operation'\
%(port.name, bop.name),
)
continue
#soapAction = soap_bop.soapAction
if bop.input is not None:
soapBodyBind = bop.input.findBinding(WSDLTools.SoapBodyBinding)
if soapBodyBind is None:
self.logger.warning(\
'Skip port(%s) operation(%s) Bindings(%s) not supported'\
%(port.name, bop.name, bop.extensions)
)
continue
op = port.getBinding().getPortType().operations.get(bop.name)
if op is None:
raise Wsdl2PythonError,\
'no matching portType/Binding operation(%s)' % bop.name
c = self.operationclass(useWSA=self.useWSA,
do_extended=self.do_extended)
c.setUp(bop)
self.operations.append(c)
def _setContent(self):
if self.useWSA is True:
ctorArgs = 'endPointReference=None, **kw'
epr = 'self.endPointReference = endPointReference'
else:
ctorArgs = '**kw'
epr = '# no ws-addressing'
if self.rProp:
rprop = 'kw.setdefault("ResourceProperties", ("%s","%s"))'\
%(self.rProp[0], self.rProp[1])
else:
rprop = '# no resource properties'
methods = [
'# Methods',
'class %s%s:' % (NC_to_CN(self.bName), self.clientClassSuffix),
'%sdef __init__(self, url, %s):' % (ID1, ctorArgs),
'%skw.setdefault("readerclass", %s)' % (ID2, self.readerclass),
'%skw.setdefault("writerclass", %s)' % (ID2, self.writerclass),
'%s%s' % (ID2, rprop),
'%sself.binding = client.Binding(url=url, **kw)' %ID2,
'%s%s' % (ID2,epr),
]
for op in self.operations:
methods += [ op.getvalue() ]
self.writeArray(methods)
class MessageContainerInterface:
logger = _GetLogger("MessageContainerInterface")
def setUp(self, port, soc, input):
'''sets the attribute _simple which represents a
primitive type message represents, or None if not primitive.
soc -- WSDLTools.ServiceOperationContainer instance
port -- WSDLTools.Port instance
input-- boolean, input messasge or output message of operation.
'''
raise NotImplementedError, 'Message container must implemented setUp.'
class ServiceDocumentLiteralMessageContainer(ServiceContainerBase, MessageContainerInterface):
logger = _GetLogger("ServiceDocumentLiteralMessageContainer")
def __init__(self, do_extended=False):
ServiceContainerBase.__init__(self)
self.do_extended=do_extended
def setUp(self, port, soc, input):
content = self.content
# TODO: check soapbody for part name
simple = self._simple = soc.isSimpleType(soc.getOperationName())
name = soc.getOperationName()
# Document/literal
operation = port.getBinding().getPortType().operations.get(name)
bop = port.getBinding().operations.get(name)
soapBodyBind = None
if input is True:
soapBodyBind = bop.input.findBinding(WSDLTools.SoapBodyBinding)
message = operation.getInputMessage()
else:
soapBodyBind = bop.output.findBinding(WSDLTools.SoapBodyBinding)
message = operation.getOutputMessage()
# using underlying data structure to avoid phantom problem.
# parts = message.parts.data.values()
# if len(parts) > 1:
# raise Wsdl2PythonError, 'not suporting multi part doc/lit msgs'
if len(message.parts) == 0:
raise Wsdl2PythonError, 'must specify part for doc/lit msg'
p = None
if soapBodyBind.parts is not None:
if len(soapBodyBind.parts) > 1:
raise Wsdl2PythonError,\
'not supporting multiple parts in soap body'
if len(soapBodyBind.parts) == 0:
return
p = message.parts.get(soapBodyBind.parts[0])
# XXX: Allow for some slop
p = p or message.parts[0]
if p.type:
raise Wsdl2PythonError, 'no doc/lit suport for <part type>'
if not p.element:
return
content.ns = p.element[0]
content.pName = p.element[1]
content.mName = message.name
def _setContent(self):
'''create string representation of doc/lit message container. If
message element is simple(primitive), use python type as base class.
'''
try:
simple = self._simple
except AttributeError:
raise RuntimeError, 'call setUp first'
# TODO: Hidden contract. Must set self.ns before getNSAlias...
# File "/usr/local/python/lib/python2.4/site-packages/ZSI/generate/containers.py", line 625, in _setContent
# kw['message'],kw['prefix'],kw['typecode'] = \
# File "/usr/local/python/lib/python2.4/site-packages/ZSI/generate/containers.py", line 128, in getNSAlias
# raise ContainerError, 'no self.ns attr defined in %s' % self.__class__
# ZSI.generate.containers.ContainerError: no self.ns attr defined in ZSI.generate.containers.ServiceDocumentLiteralMessageContainer
#
self.ns = self.content.ns
kw = KW.copy()
kw['message'],kw['prefix'],kw['typecode'] = \
self.content.mName, self.getNSAlias(), element_class_name(self.content.pName)
# These messsages are just global element declarations
self.writeArray(['%(message)s = %(prefix)s.%(typecode)s().pyclass' %kw])
class ServiceRPCEncodedMessageContainer(ServiceContainerBase, MessageContainerInterface):
logger = _GetLogger("ServiceRPCEncodedMessageContainer")
def setUp(self, port, soc, input):
'''
Instance Data:
op -- WSDLTools Operation instance
bop -- WSDLTools BindingOperation instance
input -- boolean input/output
'''
name = soc.getOperationName()
bop = port.getBinding().operations.get(name)
op = port.getBinding().getPortType().operations.get(name)
assert op is not None, 'port has no operation %s' %name
assert bop is not None, 'port has no binding operation %s' %name
self.input = input
self.op = op
self.bop = bop
def _setContent(self):
try:
self.op
except AttributeError:
raise RuntimeError, 'call setUp first'
pname = self.op.name
msgRole = self.op.input
msgRoleB = self.bop.input
if self.input is False:
pname = '%sResponse' %self.op.name
msgRole = self.op.output
msgRoleB = self.bop.output
sbody = msgRoleB.findBinding(WSDLTools.SoapBodyBinding)
if not sbody or not sbody.namespace:
raise WSInteropError, WSISpec.R2717
assert sbody.use == 'encoded', 'Expecting use=="encoded"'
encodingStyle = sbody.encodingStyle
assert encodingStyle == SOAP.ENC,\
'Supporting encodingStyle=%s, not %s' %(SOAP.ENC, encodingStyle)
namespace = sbody.namespace
tcb = MessageTypecodeContainer(\
tuple(msgRole.getMessage().parts.list),
)
ofwhat = '[%s]' %tcb.getTypecodeList()
pyclass = msgRole.getMessage().name
fdict = KW.copy()
fdict['nspname'] = sbody.namespace
fdict['pname'] = pname
fdict['pyclass'] = None
fdict['ofwhat'] = ofwhat
fdict['encoded'] = namespace
#if self.input is False:
# fdict['typecode'] = \
# 'Struct(pname=None, ofwhat=%(ofwhat)s, pyclass=%(pyclass)s, encoded="%(encoded)s")'
#else:
fdict['typecode'] = \
'Struct(pname=("%(nspname)s","%(pname)s"), ofwhat=%(ofwhat)s, pyclass=%(pyclass)s, encoded="%(encoded)s")'
message = ['class %(pyclass)s:',
'%(ID1)sdef __init__(self):']
for aname in tcb.getAttributeNames():
message.append('%(ID2)sself.' + aname +' = None')
message.append('%(ID2)sreturn')
# TODO: This isn't a TypecodeContainerBase instance but it
# certaintly generates a pyclass and typecode.
#if self.metaclass is None:
if TypecodeContainerBase.metaclass is None:
fdict['pyclass'] = pyclass
fdict['typecode'] = fdict['typecode'] %fdict
message.append('%(pyclass)s.typecode = %(typecode)s')
else:
# Need typecode to be available when class is constructed.
fdict['typecode'] = fdict['typecode'] %fdict
fdict['pyclass'] = pyclass
fdict['metaclass'] = TypecodeContainerBase.metaclass
message.insert(0, '_%(pyclass)sTypecode = %(typecode)s')
message.insert(2, '%(ID1)stypecode = _%(pyclass)sTypecode')
message.insert(3, '%(ID1)s__metaclass__ = %(metaclass)s')
message.append('%(pyclass)s.typecode.pyclass = %(pyclass)s')
self.writeArray(map(lambda l: l %fdict, message))
class ServiceRPCLiteralMessageContainer(ServiceContainerBase, MessageContainerInterface):
logger = _GetLogger("ServiceRPCLiteralMessageContainer")
def setUp(self, port, soc, input):
'''
Instance Data:
op -- WSDLTools Operation instance
bop -- WSDLTools BindingOperation instance
input -- boolean input/output
'''
name = soc.getOperationName()
bop = port.getBinding().operations.get(name)
op = port.getBinding().getPortType().operations.get(name)
assert op is not None, 'port has no operation %s' %name
assert bop is not None, 'port has no binding operation %s' %name
self.op = op
self.bop = bop
self.input = input
def _setContent(self):
try:
self.op
except AttributeError:
raise RuntimeError, 'call setUp first'
operation = self.op
input = self.input
pname = operation.name
msgRole = operation.input
msgRoleB = self.bop.input
if input is False:
pname = '%sResponse' %operation.name
msgRole = operation.output
msgRoleB = self.bop.output
sbody = msgRoleB.findBinding(WSDLTools.SoapBodyBinding)
if not sbody or not sbody.namespace:
raise WSInteropError, WSISpec.R2717
namespace = sbody.namespace
tcb = MessageTypecodeContainer(\
tuple(msgRole.getMessage().parts.list),
)
ofwhat = '[%s]' %tcb.getTypecodeList()
pyclass = msgRole.getMessage().name
fdict = KW.copy()
fdict['nspname'] = sbody.namespace
fdict['pname'] = pname
fdict['pyclass'] = None
fdict['ofwhat'] = ofwhat
fdict['encoded'] = namespace
fdict['typecode'] = \
'Struct(pname=("%(nspname)s","%(pname)s"), ofwhat=%(ofwhat)s, pyclass=%(pyclass)s, encoded="%(encoded)s")'
message = ['class %(pyclass)s:',
'%(ID1)sdef __init__(self):']
for aname in tcb.getAttributeNames():
message.append('%(ID2)sself.' + aname +' = None')
message.append('%(ID2)sreturn')
# TODO: This isn't a TypecodeContainerBase instance but it
# certaintly generates a pyclass and typecode.
#if self.metaclass is None:
if TypecodeContainerBase.metaclass is None:
fdict['pyclass'] = pyclass
fdict['typecode'] = fdict['typecode'] %fdict
message.append('%(pyclass)s.typecode = %(typecode)s')
else:
# Need typecode to be available when class is constructed.
fdict['typecode'] = fdict['typecode'] %fdict
fdict['pyclass'] = pyclass
fdict['metaclass'] = TypecodeContainerBase.metaclass
message.insert(0, '_%(pyclass)sTypecode = %(typecode)s')
message.insert(2, '%(ID1)stypecode = _%(pyclass)sTypecode')
message.insert(3, '%(ID1)s__metaclass__ = %(metaclass)s')
message.append('%(pyclass)s.typecode.pyclass = %(pyclass)s')
self.writeArray(map(lambda l: l %fdict, message))
TypesContainerBase = ContainerBase
class TypesHeaderContainer(TypesContainerBase):
'''imports for all generated types modules.
'''
imports = [
'import ZSI',
'import ZSI.TCcompound',
'from ZSI.schema import LocalElementDeclaration, ElementDeclaration, TypeDefinition, GTD, GED',
]
logger = _GetLogger("TypesHeaderContainer")
def _setContent(self):
self.writeArray(TypesHeaderContainer.imports)
NamespaceClassContainerBase = TypesContainerBase
class NamespaceClassHeaderContainer(NamespaceClassContainerBase):
logger = _GetLogger("NamespaceClassHeaderContainer")
def _setContent(self):
head = [
'#' * 30,
'# targetNamespace',
'# %s' % self.ns,
'#' * 30 + '\n',
'class %s:' % self.getNSAlias(),
'%stargetNamespace = "%s"' % (ID1, self.ns)
]
self.writeArray(head)
class NamespaceClassFooterContainer(NamespaceClassContainerBase):
logger = _GetLogger("NamespaceClassFooterContainer")
def _setContent(self):
foot = [
'# end class %s (tns: %s)' % (self.getNSAlias(), self.ns),
]
self.writeArray(foot)
BTI = BaseTypeInterpreter()
class TypecodeContainerBase(TypesContainerBase):
'''Base class for all classes representing anything
with element content.
class variables:
mixed_content_aname -- text content will be placed in this attribute.
attributes_aname -- attributes will be placed in this attribute.
metaclass -- set this attribute to specify a pyclass __metaclass__
'''
mixed_content_aname = 'text'
attributes_aname = 'attrs'
metaclass = None
lazy = False
logger = _GetLogger("TypecodeContainerBase")
def __init__(self, do_extended=False, extPyClasses=None):
TypesContainerBase.__init__(self)
self.name = None
# attrs for model groups and others with elements, tclists, etc...
self.allOptional = False
self.mgContent = None
self.contentFlattened = False
self.elementAttrs = []
self.tcListElements = []
self.tcListSet = False
self.localTypes = []
# used when processing nested anonymous types
self.parentClass = None
# used when processing attribute content
self.mixed = False
self.extraFlags = ''
self.attrComponents = None
# --> EXTENDED
# Used if an external pyclass was specified for this type.
self.do_extended = do_extended
if extPyClasses is None:
self.extPyClasses = {}
else:
self.extPyClasses = extPyClasses
# <--
def getvalue(self):
out = ContainerBase.getvalue(self)
for item in self.localTypes:
content = None
assert True is item.isElement() is item.isLocal(), 'expecting local elements only'
etp = item.content
qName = item.getAttribute('type')
if not qName:
etp = item.content
local = True
else:
etp = item.getTypeDefinition('type')
if etp is None:
if local is True:
content = ElementLocalComplexTypeContainer(do_extended=self.do_extended)
else:
content = ElementSimpleTypeContainer()
elif etp.isLocal() is False:
content = ElementGlobalDefContainer()
elif etp.isSimple() is True:
content = ElementLocalSimpleTypeContainer()
elif etp.isComplex():
content = ElementLocalComplexTypeContainer(do_extended=self.do_extended)
else:
raise Wsdl2PythonError, "Unknown element declaration: %s" %item.getItemTrace()
content.setUp(item)
out += '\n\n'
if self.parentClass:
content.parentClass = \
'%s.%s' %(self.parentClass, self.getClassName())
else:
content.parentClass = '%s.%s' %(self.getNSAlias(), self.getClassName())
for l in content.getvalue().split('\n'):
if l: out += '%s%s\n' % (ID1, l)
else: out += '\n'
out += '\n\n'
return out
def getAttributeName(self, name):
'''represents the aname
'''
if self.func_aname is None:
return name
assert callable(self.func_aname), \
'expecting callable method for attribute func_aname, not %s' %type(self.func_aname)
f = self.func_aname
return f(name)
def getMixedTextAName(self):
'''returns an aname representing mixed text content.
'''
return self.getAttributeName(self.mixed_content_aname)
def getClassName(self):
if not self.name:
raise ContainerError, 'self.name not defined!'
if not hasattr(self.__class__, 'type'):
raise ContainerError, 'container type not defined!'
#suffix = self.__class__.type
if self.__class__.type == DEF:
classname = type_class_name(self.name)
elif self.__class__.type == DEC:
classname = element_class_name(self.name)
return self.mangle( classname )
# --> EXTENDED
def hasExtPyClass(self):
if self.name in self.extPyClasses:
return True
else:
return False
# <--
def getPyClass(self):
'''Name of generated inner class that will be specified as pyclass.
'''
# --> EXTENDED
if self.hasExtPyClass():
classInfo = self.extPyClasses[self.name]
return ".".join(classInfo)
# <--
return 'Holder'
def getPyClassDefinition(self):
'''Return a list containing pyclass definition.
'''
kw = KW.copy()
# --> EXTENDED
if self.hasExtPyClass():
classInfo = self.extPyClasses[self.name]
kw['classInfo'] = classInfo[0]
return ["%(ID3)simport %(classInfo)s" %kw ]
# <--
kw['pyclass'] = self.getPyClass()
definition = []
definition.append('%(ID3)sclass %(pyclass)s:' %kw)
if self.metaclass is not None:
kw['type'] = self.metaclass
definition.append('%(ID4)s__metaclass__ = %(type)s' %kw)
definition.append('%(ID4)stypecode = self' %kw)
#TODO: Remove pyclass holder __init__ -->
definition.append('%(ID4)sdef __init__(self):' %kw)
definition.append('%(ID5)s# pyclass' %kw)
# JRB HACK need to call _setElements via getElements
self._setUpElements()
# JRB HACK need to indent additional one level
for el in self.elementAttrs:
kw['element'] = el
definition.append('%(ID2)s%(element)s' %kw)
definition.append('%(ID5)sreturn' %kw)
# <--
# pyclass descriptive name
if self.name is not None:
kw['name'] = self.name
definition.append(\
'%(ID3)s%(pyclass)s.__name__ = "%(name)s_Holder"' %kw
)
return definition
def nsuriLogic(self):
'''set a variable "ns" that represents the targetNamespace in
which this item is defined. Used for namespacing local elements.
'''
if self.parentClass:
return 'ns = %s.%s.schema' %(self.parentClass, self.getClassName())
return 'ns = %s.%s.schema' %(self.getNSAlias(), self.getClassName())
def schemaTag(self):
if self.ns is not None:
return 'schema = "%s"' % self.ns
raise ContainerError, 'failed to set schema targetNamespace(%s)' %(self.__class__)
def typeTag(self):
if self.name is not None:
return 'type = (schema, "%s")' % self.name
raise ContainerError, 'failed to set type name(%s)' %(self.__class__)
def literalTag(self):
if self.name is not None:
return 'literal = "%s"' % self.name
raise ContainerError, 'failed to set element name(%s)' %(self.__class__)
def getExtraFlags(self):
if self.mixed:
self.extraFlags += 'mixed=True, mixed_aname="%s", ' %self.getMixedTextAName()
return self.extraFlags
def simpleConstructor(self, superclass=None):
if superclass:
return '%s.__init__(self, **kw)' % superclass
else:
return 'def __init__(self, **kw):'
def pnameConstructor(self, superclass=None):
if superclass:
return '%s.__init__(self, pname, **kw)' % superclass
else:
return 'def __init__(self, pname, **kw):'
def _setUpElements(self):
"""TODO: Remove this method
This method ONLY sets up the instance attributes.
Dependency instance attribute:
mgContent -- expected to be either a complex definition
with model group content, a model group, or model group
content. TODO: should only support the first two.
"""
self.logger.debug("_setUpElements: %s" %self._item.getItemTrace())
if hasattr(self, '_done'):
#return '\n'.join(self.elementAttrs)
return
self._done = True
flat = []
content = self.mgContent
if type(self.mgContent) is not tuple:
mg = self.mgContent
if not mg.isModelGroup():
mg = mg.content
content = mg.content
if mg.isAll():
flat = content
content = []
elif mg.isModelGroup() and mg.isDefinition():
mg = mg.content
content = mg.content
idx = 0
content = list(content)
while idx < len(content):
c = orig = content[idx]
if c.isElement():
flat.append(c)
idx += 1
continue
if c.isReference() and c.isModelGroup():
c = c.getModelGroupReference()
if c.isDefinition() and c.isModelGroup():
c = c.content
if c.isSequence() or c.isChoice():
begIdx = idx
endIdx = begIdx + len(c.content)
for i in range(begIdx, endIdx):
content.insert(i, c.content[i-begIdx])
content.remove(orig)
continue
raise ContainerError, 'unexpected schema item: %s' %c.getItemTrace()
for c in flat:
if c.isDeclaration() and c.isElement():
defaultValue = "None"
parent = c
defs = []
# stop recursion via global ModelGroupDefinition
while defs.count(parent) <= 1:
maxOccurs = parent.getAttribute('maxOccurs')
if maxOccurs == 'unbounded' or int(maxOccurs) > 1:
defaultValue = "[]"
break
parent = parent._parent()
if not parent.isModelGroup():
break
if parent.isReference():
parent = parent.getModelGroupReference()
if parent.isDefinition():
parent = parent.content
defs.append(parent)
if None == c.getAttribute('name') and c.isWildCard():
e = '%sself.%s = %s' %(ID3,
self.getAttributeName('any'), defaultValue)
else:
e = '%sself.%s = %s' %(ID3,
self.getAttributeName(c.getAttribute('name')), defaultValue)
self.elementAttrs.append(e)
continue
# TODO: This seems wrong
if c.isReference():
e = '%sself._%s = None' %(ID3,
self.mangle(c.getAttribute('ref')[1]))
self.elementAttrs.append(e)
continue
raise ContainerError, 'unexpected item: %s' % c.getItemTrace()
#return '\n'.join(self.elementAttrs)
return
def _setTypecodeList(self):
"""generates ofwhat content, minOccurs/maxOccurs facet generation.
Dependency instance attribute:
mgContent -- expected to be either a complex definition
with model group content, a model group, or model group
content. TODO: should only support the first two.
localTypes -- produce local class definitions later
tcListElements -- elements, local/global
"""
self.logger.debug("_setTypecodeList(%r): %s" %
(self.mgContent, self._item.getItemTrace()))
flat = []
content = self.mgContent
#TODO: too much slop permitted here, impossible
# to tell what is going on.
if type(content) is not tuple:
mg = content
if not mg.isModelGroup():
raise Wsdl2PythonErr("Expecting ModelGroup: %s" %
mg.getItemTrace())
self.logger.debug("ModelGroup(%r) contents(%r): %s" %
(mg, mg.content, mg.getItemTrace()))
#<group ref>
if mg.isReference():
raise RuntimeError("Unexpected modelGroup reference: %s" %
mg.getItemTrace())
#<group name>
if mg.isDefinition():
mg = mg.content
if mg.isAll():
flat = mg.content
content = []
elif mg.isSequence():
content = mg.content
elif mg.isChoice():
content = mg.content
else:
raise RuntimeError("Unknown schema item")
idx = 0
content = list(content)
self.logger.debug("content: %r" %content)
while idx < len(content):
c = orig = content[idx]
if c.isElement():
flat.append(c)
idx += 1
continue
if c.isReference() and c.isModelGroup():
c = c.getModelGroupReference()
if c.isDefinition() and c.isModelGroup():
c = c.content
if c.isSequence() or c.isChoice():
begIdx = idx
endIdx = begIdx + len(c.content)
for i in range(begIdx, endIdx):
content.insert(i, c.content[i-begIdx])
content.remove(orig)
continue
raise ContainerError, 'unexpected schema item: %s' %c.getItemTrace()
# TODO: Need to store "parents" in a dict[id] = list(),
# because cannot follow references, but not currently
# a big concern.
self.logger.debug("flat: %r" %list(flat))
for c in flat:
tc = TcListComponentContainer()
# TODO: Remove _getOccurs
min,max,nil = self._getOccurs(c)
min = max = None
maxOccurs = 1
parent = c
defs = []
# stop recursion via global ModelGroupDefinition
while defs.count(parent) <= 1:
max = parent.getAttribute('maxOccurs')
if max == 'unbounded':
maxOccurs = '"%s"' %max
break
maxOccurs = int(max) * maxOccurs
parent = parent._parent()
if not parent.isModelGroup():
break
if parent.isReference():
parent = parent.getModelGroupReference()
if parent.isDefinition():
parent = parent.content
defs.append(parent)
del defs
parent = c
while 1:
minOccurs = int(parent.getAttribute('minOccurs'))
if minOccurs == 0 or parent.isChoice():
minOccurs = 0
break
parent = parent._parent()
if not parent.isModelGroup():
minOccurs = int(c.getAttribute('minOccurs'))
break
if parent.isReference():
parent = parent.getModelGroupReference()
if parent.isDefinition():
parent = parent.content
tc.setOccurs(minOccurs, maxOccurs, nil)
processContents = self._getProcessContents(c)
tc.setProcessContents(processContents)
if c.isDeclaration() and c.isElement():
global_type = c.getAttribute('type')
content = getattr(c, 'content', None)
if c.isLocal() and c.isQualified() is False:
tc.unQualified()
if c.isWildCard():
tc.setStyleAnyElement()
elif global_type is not None:
tc.name = c.getAttribute('name')
ns = global_type[0]
if ns in SCHEMA.XSD_LIST:
tpc = BTI.get_typeclass(global_type[1],global_type[0])
tc.klass = tpc
# elif (self.ns,self.name) == global_type:
# # elif self._isRecursiveElement(c)
# # TODO: Remove this, it only works for 1 level.
# tc.setStyleRecursion()
else:
tc.setGlobalType(*global_type)
# tc.klass = '%s.%s' % (NAD.getAlias(ns),
# type_class_name(global_type[1]))
del ns
elif content is not None and content.isLocal() and content.isComplex():
tc.name = c.getAttribute('name')
tc.klass = 'self.__class__.%s' % (element_class_name(tc.name))
#TODO: Not an element reference, confusing nomenclature
tc.setStyleElementReference()
self.localTypes.append(c)
elif content is not None and content.isLocal() and content.isSimple():
# Local Simple Type
tc.name = c.getAttribute('name')
tc.klass = 'self.__class__.%s' % (element_class_name(tc.name))
#TODO: Not an element reference, confusing nomenclature
tc.setStyleElementReference()
self.localTypes.append(c)
else:
raise ContainerError, 'unexpected item: %s' % c.getItemTrace()
elif c.isReference():
# element references
ref = c.getAttribute('ref')
# tc.klass = '%s.%s' % (NAD.getAlias(ref[0]),
# element_class_name(ref[1]) )
tc.setStyleElementReference()
tc.setGlobalType(*ref)
else:
raise ContainerError, 'unexpected item: %s' % c.getItemTrace()
self.tcListElements.append(tc)
def getTypecodeList(self):
if not self.tcListSet:
# self._flattenContent()
self._setTypecodeList()
self.tcListSet = True
list = []
for e in self.tcListElements:
list.append(str(e))
return ', '.join(list)
# the following _methods() are utility methods used during
# TCList generation, et al.
def _getOccurs(self, e):
nillable = e.getAttribute('nillable')
if nillable == 'true':
nillable = True
else:
nillable = False
maxOccurs = e.getAttribute('maxOccurs')
if maxOccurs == 'unbounded':
maxOccurs = '"%s"' %maxOccurs
minOccurs = e.getAttribute('minOccurs')
if self.allOptional is True:
#JRB Hack
minOccurs = '0'
maxOccurs = '"unbounded"'
return minOccurs,maxOccurs,nillable
def _getProcessContents(self, e):
processContents = e.getAttribute('processContents')
return processContents
def getBasesLogic(self, indent):
try:
prefix = NAD.getAlias(self.sKlassNS)
except WsdlGeneratorError, ex:
# XSD or SOAP
raise
bases = []
bases.append(\
'if %s.%s not in %s.%s.__bases__:'\
%(NAD.getAlias(self.sKlassNS), type_class_name(self.sKlass), self.getNSAlias(), self.getClassName()),
)
bases.append(\
'%sbases = list(%s.%s.__bases__)'\
%(ID1,self.getNSAlias(),self.getClassName()),
)
bases.append(\
'%sbases.insert(0, %s.%s)'\
%(ID1,NAD.getAlias(self.sKlassNS), type_class_name(self.sKlass) ),
)
bases.append(\
'%s%s.%s.__bases__ = tuple(bases)'\
%(ID1, self.getNSAlias(), self.getClassName())
)
s = ''
for b in bases:
s += '%s%s\n' % (indent, b)
return s
class MessageTypecodeContainer(TypecodeContainerBase):
'''Used for RPC style messages, where we have
serveral parts serialized within a rpc wrapper name.
'''
logger = _GetLogger("MessageTypecodeContainer")
def __init__(self, parts=None):
TypecodeContainerBase.__init__(self)
self.mgContent = parts
def _getOccurs(self, e):
'''return a 3 item tuple
'''
minOccurs = maxOccurs = '1'
nillable = True
return minOccurs,maxOccurs,nillable
def _setTypecodeList(self):
self.logger.debug("_setTypecodeList: %s" %
str(self.mgContent))
assert type(self.mgContent) is tuple,\
'expecting tuple for mgContent not: %s' %type(self.mgContent)
for p in self.mgContent:
# JRB
# not sure what needs to be set for tc, this should be
# the job of the constructor or a setUp method.
min,max,nil = self._getOccurs(p)
if p.element:
raise WSInteropError, WSISpec.R2203
elif p.type:
nsuri,name = p.type
tc = RPCMessageTcListComponentContainer(qualified=False)
tc.setOccurs(min, max, nil)
tc.name = p.name
if nsuri in SCHEMA.XSD_LIST:
tpc = BTI.get_typeclass(name, nsuri)
tc.klass = tpc
else:
tc.klass = '%s.%s' % (NAD.getAlias(nsuri), type_class_name(name) )
else:
raise ContainerError, 'part must define an element or type attribute'
self.tcListElements.append(tc)
def getTypecodeList(self):
if not self.tcListSet:
self._setTypecodeList()
self.tcListSet = True
list = []
for e in self.tcListElements:
list.append(str(e))
return ', '.join(list)
def getAttributeNames(self):
'''returns a list of anames representing the parts
of the message.
'''
return map(lambda e: self.getAttributeName(e.name), self.tcListElements)
def setParts(self, parts):
self.mgContent = parts
class TcListComponentContainer(ContainerBase):
'''Encapsulates a single value in the TClist list.
it inherits TypecodeContainerBase only to get the mangle() method,
it does not call the baseclass ctor.
TODO: Change this inheritance scheme.
'''
logger = _GetLogger("TcListComponentContainer")
def __init__(self, qualified=True):
'''
qualified -- qualify element. All GEDs should be qualified,
but local element declarations qualified if form attribute
is qualified, else they are unqualified. Only relevant for
standard style.
'''
#TypecodeContainerBase.__init__(self)
ContainerBase.__init__(self)
self.qualified = qualified
self.name = None
self.klass = None
self.global_type = None
self.min = None
self.max = None
self.nil = None
self.style = None
self.setStyleElementDeclaration()
def setOccurs(self, min, max, nil):
self.min = min
self.max = max
self.nil = nil
def setProcessContents(self, processContents):
self.processContents = processContents
def setGlobalType(self, namespace, name):
self.global_type = (namespace, name)
def setStyleElementDeclaration(self):
'''set the element style.
standard -- GED or local element
'''
self.style = 'standard'
def setStyleElementReference(self):
'''set the element style.
ref -- element reference
'''
self.style = 'ref'
def setStyleAnyElement(self):
'''set the element style.
anyElement -- <any> element wildcard
'''
self.name = 'any'
self.style = 'anyElement'
# def setStyleRecursion(self):
# '''TODO: Remove. good for 1 level
# '''
# self.style = 'recursion'
def unQualified(self):
'''Do not qualify element.
'''
self.qualified = False
def _getOccurs(self):
return 'minOccurs=%s, maxOccurs=%s, nillable=%s' \
% (self.min, self.max, self.nil)
def _getProcessContents(self):
return 'processContents="%s"' \
% (self.processContents)
def _getvalue(self):
kw = {'occurs':self._getOccurs(),
'aname':self.getAttributeName(self.name),
'klass':self.klass,
'lazy':TypecodeContainerBase.lazy,
'typed':'typed=False',
'encoded':'encoded=kw.get("encoded")'}
gt = self.global_type
if gt is not None:
kw['nsuri'],kw['type'] = gt
if self.style == 'standard':
kw['pname'] = '"%s"' %self.name
if self.qualified is True:
kw['pname'] = '(ns,"%s")' %self.name
if gt is None:
return '%(klass)s(pname=%(pname)s, aname="%(aname)s", %(occurs)s, %(typed)s, %(encoded)s)' %kw
return 'GTD("%(nsuri)s","%(type)s",lazy=%(lazy)s)(pname=%(pname)s, aname="%(aname)s", %(occurs)s, %(typed)s, %(encoded)s)' %kw
if self.style == 'ref':
if gt is None:
return '%(klass)s(%(occurs)s, %(encoded)s)' %kw
return 'GED("%(nsuri)s","%(type)s",lazy=%(lazy)s, isref=True)(%(occurs)s, %(encoded)s)' %kw
kw['process'] = self._getProcessContents()
if self.style == 'anyElement':
return 'ZSI.TC.AnyElement(aname="%(aname)s", %(occurs)s, %(process)s)' %kw
# if self.style == 'recursion':
# return 'ZSI.TC.AnyElement(aname="%(aname)s", %(occurs)s, %(process)s)' %kw
raise RuntimeError, 'Must set style for typecode list generation'
def __str__(self):
return self._getvalue()
class RPCMessageTcListComponentContainer(TcListComponentContainer):
'''Container for rpc/literal rpc/encoded message typecode.
'''
logger = _GetLogger("RPCMessageTcListComponentContainer")
def __init__(self, qualified=True, encoded=None):
'''
encoded -- encoded namespaceURI, if None treat as rpc/literal.
'''
TcListComponentContainer.__init__(self, qualified=qualified)
self._encoded = encoded
def _getvalue(self):
encoded = self._encoded
if encoded is not None:
encoded = '"%s"' %self._encoded
if self.style == 'standard':
pname = '"%s"' %self.name
if self.qualified is True:
pname = '(ns,"%s")' %self.name
return '%s(pname=%s, aname="%s", typed=False, encoded=%s, %s)' \
%(self.klass, pname, self.getAttributeName(self.name),
encoded, self._getOccurs())
elif self.style == 'ref':
return '%s(encoded=%s, %s)' % (self.klass, encoded, self._getOccurs())
elif self.style == 'anyElement':
return 'ZSI.TC.AnyElement(aname="%s", %s, %s)' \
%(self.getAttributeName(self.name), self._getOccurs(), self._getProcessContents())
# elif self.style == 'recursion':
# return 'ZSI.TC.AnyElement(aname="%s", %s, %s)' \
# % (self.getAttributeName(self.name), self._getOccurs(), self._getProcessContents())
raise RuntimeError('Must set style(%s) for typecode list generation' %
self.style)
class ElementSimpleTypeContainer(TypecodeContainerBase):
type = DEC
logger = _GetLogger("ElementSimpleTypeContainer")
def _setContent(self):
aname = self.getAttributeName(self.name)
pyclass = self.pyclass
# bool cannot be subclassed
if pyclass == 'bool': pyclass = 'int'
kw = KW.copy()
kw.update(dict(aname=aname, ns=self.ns, name=self.name,
subclass=self.sKlass,literal=self.literalTag(),
schema=self.schemaTag(), init=self.simpleConstructor(),
klass=self.getClassName(), element="ElementDeclaration"))
if self.local:
kw['element'] = 'LocalElementDeclaration'
element = map(lambda i: i %kw, [
'%(ID1)sclass %(klass)s(%(subclass)s, %(element)s):',
'%(ID2)s%(literal)s',
'%(ID2)s%(schema)s',
'%(ID2)s%(init)s',
'%(ID3)skw["pname"] = ("%(ns)s","%(name)s")',
'%(ID3)skw["aname"] = "%(aname)s"',
]
)
# TODO: What about getPyClass and getPyClassDefinition?
# I want to add pyclass metaclass here but this needs to be
# corrected first.
#
# anyType (?others) has no pyclass.
app = element.append
if pyclass is not None:
app('%sclass IHolder(%s): typecode=self' % (ID3, pyclass),)
app('%skw["pyclass"] = IHolder' %(ID3),)
app('%sIHolder.__name__ = "%s_immutable_holder"' %(ID3, aname),)
app('%s%s' % (ID3, self.simpleConstructor(self.sKlass)),)
self.writeArray(element)
def setUp(self, tp):
self._item = tp
self.local = tp.isLocal()
try:
self.name = tp.getAttribute('name')
self.ns = tp.getTargetNamespace()
qName = tp.getAttribute('type')
except Exception, ex:
raise Wsdl2PythonError('Error occured processing element: %s' %(
tp.getItemTrace()), *ex.args)
if qName is None:
raise Wsdl2PythonError('Missing QName for element type attribute: %s' %tp.getItemTrace())
tns,local = qName.getTargetNamespace(),qName.getName()
self.sKlass = BTI.get_typeclass(local, tns)
if self.sKlass is None:
raise Wsdl2PythonError('No built-in typecode for type definition("%s","%s"): %s' %(tns,local,tp.getItemTrace()))
try:
self.pyclass = BTI.get_pythontype(None, None, typeclass=self.sKlass)
except Exception, ex:
raise Wsdl2PythonError('Error occured processing element: %s' %(
tp.getItemTrace()), *ex.args)
class ElementLocalSimpleTypeContainer(TypecodeContainerBase):
'''local simpleType container
'''
type = DEC
logger = _GetLogger("ElementLocalSimpleTypeContainer")
def _setContent(self):
kw = KW.copy()
kw.update(dict(aname=self.getAttributeName(self.name), ns=self.ns, name=self.name,
subclass=self.sKlass,literal=self.literalTag(),
schema=self.schemaTag(), init=self.simpleConstructor(),
klass=self.getClassName(), element="ElementDeclaration",
baseinit=self.simpleConstructor(self.sKlass)))
if self.local:
kw['element'] = 'LocalElementDeclaration'
element = map(lambda i: i %kw, [
'%(ID1)sclass %(klass)s(%(subclass)s, %(element)s):',
'%(ID2)s%(literal)s',
'%(ID2)s%(schema)s',
'%(ID2)s%(init)s',
'%(ID3)skw["pname"] = ("%(ns)s","%(name)s")',
'%(ID3)skw["aname"] = "%(aname)s"',
'%(ID3)s%(baseinit)s',
]
)
self.writeArray(element)
def setUp(self, tp):
self._item = tp
assert tp.isElement() is True and tp.content is not None and \
tp.content.isLocal() is True and tp.content.isSimple() is True ,\
'expecting local simple type: %s' %tp.getItemTrace()
self.local = tp.isLocal()
self.name = tp.getAttribute('name')
self.ns = tp.getTargetNamespace()
content = tp.content.content
if content.isRestriction():
try:
base = content.getTypeDefinition()
except XMLSchema.SchemaError, ex:
base = None
qName = content.getAttributeBase()
if base is None:
self.sKlass = BTI.get_typeclass(qName[1], qName[0])
return
raise Wsdl2PythonError, 'unsupported local simpleType restriction: %s' \
%tp.content.getItemTrace()
if content.isList():
try:
base = content.getTypeDefinition()
except XMLSchema.SchemaError, ex:
base = None
if base is None:
qName = content.getItemType()
self.sKlass = BTI.get_typeclass(qName[1], qName[0])
return
raise Wsdl2PythonError, 'unsupported local simpleType List: %s' \
%tp.content.getItemTrace()
if content.isUnion():
raise Wsdl2PythonError, 'unsupported local simpleType Union: %s' \
%tp.content.getItemTrace()
raise Wsdl2PythonError, 'unexpected schema item: %s' \
%tp.content.getItemTrace()
class ElementLocalComplexTypeContainer(TypecodeContainerBase, AttributeMixIn):
type = DEC
logger = _GetLogger("ElementLocalComplexTypeContainer")
def _setContent(self):
kw = KW.copy()
try:
kw.update(dict(klass=self.getClassName(),
subclass='ZSI.TCcompound.ComplexType',
element='ElementDeclaration',
literal=self.literalTag(),
schema=self.schemaTag(),
init=self.simpleConstructor(),
ns=self.ns, name=self.name,
aname=self.getAttributeName(self.name),
nsurilogic=self.nsuriLogic(),
ofwhat=self.getTypecodeList(),
atypecode=self.attribute_typecode,
pyclass=self.getPyClass(),
))
except Exception, ex:
args = ['Failure processing an element w/local complexType: %s' %(
self._item.getItemTrace())]
args += ex.args
ex.args = tuple(args)
raise
if self.local:
kw['element'] = 'LocalElementDeclaration'
element = [
'%(ID1)sclass %(klass)s(%(subclass)s, %(element)s):',
'%(ID2)s%(literal)s',
'%(ID2)s%(schema)s',
'%(ID2)s%(init)s',
'%(ID3)s%(nsurilogic)s',
'%(ID3)sTClist = [%(ofwhat)s]',
'%(ID3)skw["pname"] = ("%(ns)s","%(name)s")',
'%(ID3)skw["aname"] = "%(aname)s"',
'%(ID3)s%(atypecode)s = {}',
'%(ID3)sZSI.TCcompound.ComplexType.__init__(self,None,TClist,inorder=0,**kw)',
]
for l in self.attrComponents: element.append('%(ID3)s'+str(l))
element += self.getPyClassDefinition()
element.append('%(ID3)sself.pyclass = %(pyclass)s' %kw)
self.writeArray(map(lambda l: l %kw, element))
def setUp(self, tp):
'''
{'xsd':['annotation', 'simpleContent', 'complexContent',\
'group', 'all', 'choice', 'sequence', 'attribute', 'attributeGroup',\
'anyAttribute', 'any']}
'''
#
# TODO: Need a Recursive solution, this is incomplete will ignore many
# extensions, restrictions, etc.
#
self._item = tp
# JRB HACK SUPPORTING element/no content.
assert tp.isElement() is True and \
(tp.content is None or (tp.content.isComplex() is True and tp.content.isLocal() is True)),\
'expecting element w/local complexType not: %s' %tp.content.getItemTrace()
self.name = tp.getAttribute('name')
self.ns = tp.getTargetNamespace()
self.local = tp.isLocal()
complex = tp.content
# JRB HACK SUPPORTING element/no content.
if complex is None:
self.mgContent = ()
return
#attributeContent = complex.getAttributeContent()
#self.mgContent = None
if complex.content is None:
self.mgContent = ()
self.attrComponents = self._setAttributes(complex.getAttributeContent())
return
is_simple = complex.content.isSimple()
if is_simple and complex.content.content.isExtension():
# TODO: Not really supported just passing thru
self.mgContent = ()
self.attrComponents = self._setAttributes(complex.getAttributeContent())
return
if is_simple and complex.content.content.isRestriction():
# TODO: Not really supported just passing thru
self.mgContent = ()
self.attrComponents = self._setAttributes(complex.getAttributeContent())
return
if is_simple:
raise ContainerError, 'not implemented local complexType/simpleContent: %s'\
%tp.getItemTrace()
is_complex = complex.content.isComplex()
if is_complex and complex.content.content is None:
# TODO: Recursion...
self.mgContent = ()
self.attrComponents = self._setAttributes(complex.getAttributeContent())
return
if (is_complex and complex.content.content.isExtension() and
complex.content.content.content is not None and
complex.content.content.content.isModelGroup()):
self.mgContent = complex.content.content.content.content
self.attrComponents = self._setAttributes(
complex.content.content.getAttributeContent()
)
return
if (is_complex and complex.content.content.isRestriction() and
complex.content.content.content is not None and
complex.content.content.content.isModelGroup()):
self.mgContent = complex.content.content.content.content
self.attrComponents = self._setAttributes(
complex.content.content.getAttributeContent()
)
return
if is_complex:
self.mgContent = ()
self.attrComponents = self._setAttributes(complex.getAttributeContent())
return
if complex.content.isModelGroup():
self.mgContent = complex.content.content
self.attrComponents = self._setAttributes(complex.getAttributeContent())
return
# TODO: Scary Fallthru
self.mgContent = ()
self.attrComponents = self._setAttributes(complex.getAttributeContent())
class ElementGlobalDefContainer(TypecodeContainerBase):
type = DEC
logger = _GetLogger("ElementGlobalDefContainer")
def _setContent(self):
'''GED defines element name, so also define typecode aname
'''
kw = KW.copy()
try:
kw.update(dict(klass=self.getClassName(),
element='ElementDeclaration',
literal=self.literalTag(),
schema=self.schemaTag(),
init=self.simpleConstructor(),
ns=self.ns, name=self.name,
aname=self.getAttributeName(self.name),
baseslogic=self.getBasesLogic(ID3),
#ofwhat=self.getTypecodeList(),
#atypecode=self.attribute_typecode,
#pyclass=self.getPyClass(),
alias=NAD.getAlias(self.sKlassNS),
subclass=type_class_name(self.sKlass),
))
except Exception, ex:
args = ['Failure processing an element w/local complexType: %s' %(
self._item.getItemTrace())]
args += ex.args
ex.args = tuple(args)
raise
if self.local:
kw['element'] = 'LocalElementDeclaration'
element = [
'%(ID1)sclass %(klass)s(%(element)s):',
'%(ID2)s%(literal)s',
'%(ID2)s%(schema)s',
'%(ID2)s%(init)s',
'%(ID3)skw["pname"] = ("%(ns)s","%(name)s")',
'%(ID3)skw["aname"] = "%(aname)s"',
'%(baseslogic)s',
'%(ID3)s%(alias)s.%(subclass)s.__init__(self, **kw)',
'%(ID3)sif self.pyclass is not None: self.pyclass.__name__ = "%(klass)s_Holder"',
]
self.writeArray(map(lambda l: l %kw, element))
def setUp(self, element):
# Save for debugging
self._item = element
self.local = element.isLocal()
self.name = element.getAttribute('name')
self.ns = element.getTargetNamespace()
tp = element.getTypeDefinition('type')
self.sKlass = tp.getAttribute('name')
self.sKlassNS = tp.getTargetNamespace()
class ComplexTypeComplexContentContainer(TypecodeContainerBase, AttributeMixIn):
'''Represents ComplexType with ComplexContent.
'''
type = DEF
logger = _GetLogger("ComplexTypeComplexContentContainer")
def __init__(self, do_extended=False):
TypecodeContainerBase.__init__(self, do_extended=do_extended)
def setUp(self, tp):
'''complexContent/[extension,restriction]
restriction
extension
extType -- used in figuring attrs for extensions
'''
self._item = tp
assert tp.content.isComplex() is True and \
(tp.content.content.isRestriction() or tp.content.content.isExtension() is True),\
'expecting complexContent/[extension,restriction]'
self.extType = None
self.restriction = False
self.extension = False
self._kw_array = None
self._is_array = False
self.name = tp.getAttribute('name')
self.ns = tp.getTargetNamespace()
# xxx: what is this for?
#self.attribute_typecode = 'attributes'
derivation = tp.content.content
# Defined in Schema instance?
try:
base = derivation.getTypeDefinition('base')
except XMLSchema.SchemaError, ex:
base = None
# anyType, arrayType, etc...
if base is None:
base = derivation.getAttributeQName('base')
if base is None:
raise ContainerError, 'Unsupported derivation: %s'\
%derivation.getItemTrace()
if base != (SOAP.ENC,'Array') and base != (SCHEMA.XSD3,'anyType'):
raise ContainerError, 'Unsupported base(%s): %s' %(
base, derivation.getItemTrace()
)
if base == (SOAP.ENC,'Array'):
# SOAP-ENC:Array expecting arrayType attribute reference
self.logger.debug("Derivation of soapenc:Array")
self._is_array = True
self._kw_array = {'atype':None, 'id3':ID3, 'ofwhat':None}
self.sKlass = BTI.get_typeclass(base[1], base[0])
self.sKlassNS = base[0]
attr = None
for a in derivation.getAttributeContent():
assert a.isAttribute() is True,\
'only attribute content expected: %s' %a.getItemTrace()
if a.isReference() is True:
if a.getAttribute('ref') == (SOAP.ENC,'arrayType'):
self._kw_array['atype'] = a.getAttributeQName((WSDL.BASE, 'arrayType'))
attr = a
break
qname = self._kw_array.get('atype')
if attr is not None:
qname = self._kw_array.get('atype')
ncname = qname[1].strip('[]')
namespace = qname[0]
try:
ofwhat = attr.getSchemaItem(XMLSchema.TYPES, namespace, ncname)
except XMLSchema.SchemaError, ex:
ofwhat = None
if ofwhat is None:
self._kw_array['ofwhat'] = BTI.get_typeclass(ncname, namespace)
else:
self._kw_array['ofwhat'] = GetClassNameFromSchemaItem(ofwhat, do_extended=self.do_extended)
if self._kw_array['ofwhat'] is None:
raise ContainerError, 'For Array could not resolve ofwhat typecode(%s,%s): %s'\
%(namespace, ncname, derivation.getItemTrace())
self.logger.debug('Attribute soapenc:arrayType="%s"' %
str(self._kw_array['ofwhat']))
elif isinstance(base, XMLSchema.XMLSchemaComponent):
self.sKlass = base.getAttribute('name')
self.sKlassNS = base.getTargetNamespace()
else:
# TypeDescriptionComponent
self.sKlass = base.getName()
self.sKlassNS = base.getTargetNamespace()
attrs = []
if derivation.isRestriction():
self.restriction = True
self.extension = False
# derivation.getAttributeContent subset of tp.getAttributeContent
attrs += derivation.getAttributeContent() or ()
else:
self.restriction = False
self.extension = True
attrs += tp.getAttributeContent() or ()
if isinstance(derivation, XMLSchema.XMLSchemaComponent):
attrs += derivation.getAttributeContent() or ()
# XXX: not sure what this is doing
if attrs:
self.extType = derivation
if derivation.content is not None \
and derivation.content.isModelGroup():
group = derivation.content
if group.isReference():
group = group.getModelGroupReference()
self.mgContent = group.content
elif derivation.content:
raise Wsdl2PythonError, \
'expecting model group, not: %s' %derivation.content.getItemTrace()
else:
self.mgContent = ()
self.attrComponents = self._setAttributes(tuple(attrs))
def _setContent(self):
'''JRB What is the difference between instance data
ns, name, -- type definition?
sKlass, sKlassNS? -- element declaration?
'''
kw = KW.copy()
definition = []
if self._is_array:
# SOAP-ENC:Array
if _is_xsd_or_soap_ns(self.sKlassNS) is False and self.sKlass == 'Array':
raise ContainerError, 'unknown type: (%s,%s)'\
%(self.sKlass, self.sKlassNS)
# No need to xsi:type array items since specify with
# SOAP-ENC:arrayType attribute.
definition += [\
'%sclass %s(ZSI.TC.Array, TypeDefinition):' % (ID1, self.getClassName()),
'%s#complexType/complexContent base="SOAP-ENC:Array"' %(ID2),
'%s%s' % (ID2, self.schemaTag()),
'%s%s' % (ID2, self.typeTag()),
'%s%s' % (ID2, self.pnameConstructor()),
'%(id3)sofwhat = %(ofwhat)s(None, typed=False)' %self._kw_array,
'%(id3)satype = %(atype)s' %self._kw_array,
'%s%s.__init__(self, atype, ofwhat, pname=pname, childnames=\'item\', **kw)'
%(ID3, self.sKlass),
]
self.writeArray(definition)
return
definition += [\
'%sclass %s(TypeDefinition):' % (ID1, self.getClassName()),
'%s%s' % (ID2, self.schemaTag()),
'%s%s' % (ID2, self.typeTag()),
'%s%s' % (ID2, self.pnameConstructor()),
'%s%s' % (ID3, self.nsuriLogic()),
'%sTClist = [%s]' % (ID3, self.getTypecodeList()),
]
definition.append(
'%(ID3)sattributes = %(atc)s = attributes or {}' %{
'ID3':ID3, 'atc':self.attribute_typecode}
)
#
# Special case: anyType restriction
isAnyType = (self.sKlassNS, self.sKlass) == (SCHEMA.XSD3, 'anyType')
if isAnyType:
del definition[0]
definition.insert(0,
'%sclass %s(ZSI.TC.ComplexType, TypeDefinition):' % (
ID1, self.getClassName())
)
definition.insert(1,
'%s#complexType/complexContent restrict anyType' %(
ID2)
)
# derived type support
definition.append('%sif extend: TClist += ofwhat'%(ID3))
definition.append('%sif restrict: TClist = ofwhat' %(ID3))
if len(self.attrComponents) > 0:
definition.append('%selse:' %(ID3))
for l in self.attrComponents:
definition.append('%s%s'%(ID4, l))
if isAnyType:
definition.append(\
'%sZSI.TC.ComplexType.__init__(self, None, TClist, pname=pname, **kw)' %(
ID3),
)
# pyclass class definition
definition += self.getPyClassDefinition()
kw['pyclass'] = self.getPyClass()
definition.append('%(ID3)sself.pyclass = %(pyclass)s' %kw)
self.writeArray(definition)
return
for l in self.attrComponents:
definition.append('%s%s'%(ID3, l))
definition.append('%s' % self.getBasesLogic(ID3))
prefix = NAD.getAlias(self.sKlassNS)
typeClassName = type_class_name(self.sKlass)
if self.restriction:
definition.append(\
'%s%s.%s.__init__(self, pname, ofwhat=TClist, restrict=True, **kw)' %(
ID3, prefix, typeClassName),
)
definition.insert(1, '%s#complexType/complexContent restriction' %ID2)
self.writeArray(definition)
return
if self.extension:
definition.append(\
'%s%s.%s.__init__(self, pname, ofwhat=TClist, extend=True, attributes=attributes, **kw)'%(
ID3, prefix, typeClassName),
)
definition.insert(1, '%s#complexType/complexContent extension' %(ID2))
self.writeArray(definition)
return
raise Wsdl2PythonError,\
'ComplexContent must be a restriction or extension'
def pnameConstructor(self, superclass=None):
if superclass:
return '%s.__init__(self, pname, ofwhat=(), extend=False, restrict=False, attributes=None, **kw)' % superclass
return 'def __init__(self, pname, ofwhat=(), extend=False, restrict=False, attributes=None, **kw):'
class ComplexTypeContainer(TypecodeContainerBase, AttributeMixIn):
'''Represents a global complexType definition.
'''
type = DEF
logger = _GetLogger("ComplexTypeContainer")
def setUp(self, tp, empty=False):
'''Problematic, loose all model group information.
<all>, <choice>, <sequence> ..
tp -- type definition
empty -- no model group, just use as a dummy holder.
'''
self._item = tp
self.name = tp.getAttribute('name')
self.ns = tp.getTargetNamespace()
self.mixed = tp.isMixed()
self.mgContent = ()
self.attrComponents = self._setAttributes(tp.getAttributeContent())
# Save reference to type for debugging
self._item = tp
if empty:
return
model = tp.content
if model.isReference():
model = model.getModelGroupReference()
if model is None:
return
if model.content is None:
return
# sequence, all or choice
#self.mgContent = model.content
self.mgContent = model
def _setContent(self):
try:
definition = [
'%sclass %s(ZSI.TCcompound.ComplexType, TypeDefinition):'
% (ID1, self.getClassName()),
'%s%s' % (ID2, self.schemaTag()),
'%s%s' % (ID2, self.typeTag()),
'%s%s' % (ID2, self.pnameConstructor()),
#'%s' % self.getElements(),
'%s%s' % (ID3, self.nsuriLogic()),
'%sTClist = [%s]' % (ID3, self.getTypecodeList()),
]
except Exception, ex:
args = ["Failure processing %s" %self._item.getItemTrace()]
args += ex.args
ex.args = tuple(args)
raise
definition.append('%s%s = attributes or {}' %(ID3,
self.attribute_typecode))
# IF EXTEND
definition.append('%sif extend: TClist += ofwhat'%(ID3))
# IF RESTRICT
definition.append('%sif restrict: TClist = ofwhat' %(ID3))
# ELSE
if len(self.attrComponents) > 0:
definition.append('%selse:' %(ID3))
for l in self.attrComponents: definition.append('%s%s'%(ID4, l))
definition.append(\
'%sZSI.TCcompound.ComplexType.__init__(self, None, TClist, pname=pname, inorder=0, %s**kw)' \
%(ID3, self.getExtraFlags())
)
# pyclass class definition
definition += self.getPyClassDefinition()
# set pyclass
kw = KW.copy()
kw['pyclass'] = self.getPyClass()
definition.append('%(ID3)sself.pyclass = %(pyclass)s' %kw)
self.writeArray(definition)
def pnameConstructor(self, superclass=None):
''' TODO: Logic is a little tricky. If superclass is ComplexType this is not used.
'''
if superclass:
return '%s.__init__(self, pname, ofwhat=(), attributes=None, extend=False, restrict=False, **kw)' % superclass
return 'def __init__(self, pname, ofwhat=(), attributes=None, extend=False, restrict=False, **kw):'
class SimpleTypeContainer(TypecodeContainerBase):
type = DEF
logger = _GetLogger("SimpleTypeContainer")
def __init__(self):
'''
Instance Data From TypecodeContainerBase NOT USED...
mgContent
'''
TypecodeContainerBase.__init__(self)
def setUp(self, tp):
raise NotImplementedError, 'abstract method not implemented'
def _setContent(self, tp):
raise NotImplementedError, 'abstract method not implemented'
def getPythonType(self):
pyclass = eval(str(self.sKlass))
if issubclass(pyclass, ZSI.TC.String):
return 'str'
if issubclass(pyclass, ZSI.TC.Ilong) or issubclass(pyclass, ZSI.TC.IunsignedLong):
return 'long'
if issubclass(pyclass, ZSI.TC.Boolean) or issubclass(pyclass, ZSI.TC.Integer):
return 'int'
if issubclass(pyclass, ZSI.TC.Decimal):
return 'float'
if issubclass(pyclass, ZSI.TC.Gregorian) or issubclass(pyclass, ZSI.TC.Duration):
return 'tuple'
return None
def getPyClassDefinition(self):
definition = []
pt = self.getPythonType()
if pt is not None:
definition.append('%sclass %s(%s):' %(ID3,self.getPyClass(),pt))
definition.append('%stypecode = self' %ID4)
return definition
class RestrictionContainer(SimpleTypeContainer):
'''
simpleType/restriction
'''
logger = _GetLogger("RestrictionContainer")
def setUp(self, tp):
self._item = tp
assert tp.isSimple() is True and tp.isDefinition() is True and \
tp.content.isRestriction() is True,\
'expecting simpleType restriction, not: %s' %tp.getItemTrace()
if tp.content is None:
raise Wsdl2PythonError, \
'empty simpleType defintion: %s' %tp.getItemTrace()
self.name = tp.getAttribute('name')
self.ns = tp.getTargetNamespace()
self.sKlass = None
base = tp.content.getAttribute('base')
if base is not None:
try:
item = tp.content.getTypeDefinition('base')
except XMLSchema.SchemaError, ex:
pass
if item is None:
self.sKlass = BTI.get_typeclass(base.getName(), base.getTargetNamespace())
if self.sKlass is not None:
return
raise Wsdl2PythonError('no built-in type nor schema instance type for base attribute("%s","%s"): %s' %(
base.getTargetNamespace(), base.getName(), tp.getItemTrace()))
raise Wsdl2PythonError, \
'Not Supporting simpleType/Restriction w/User-Defined Base: %s %s' %(tp.getItemTrace(),item.getItemTrace())
sc = tp.content.getSimpleTypeContent()
if sc is not None and True is sc.isSimple() is sc.isLocal() is sc.isDefinition():
base = None
if sc.content.isRestriction() is True:
try:
item = tp.content.getTypeDefinition('base')
except XMLSchema.SchemaError, ex:
pass
if item is None:
base = sc.content.getAttribute('base')
if base is not None:
self.sKlass = BTI.get_typeclass(base.getTargetNamespace(), base.getName())
return
raise Wsdl2PythonError, \
'Not Supporting simpleType/Restriction w/User-Defined Base: '\
%item.getItemTrace()
raise Wsdl2PythonError, \
'Not Supporting simpleType/Restriction w/User-Defined Base: '\
%item.getItemTrace()
if sc.content.isList() is True:
raise Wsdl2PythonError, \
'iction base in subtypes: %s'\
%sc.getItemTrace()
if sc.content.isUnion() is True:
raise Wsdl2PythonError, \
'could not get restriction base in subtypes: %s'\
%sc.getItemTrace()
return
raise Wsdl2PythonError, 'No Restriction @base/simpleType: %s' %tp.getItemTrace()
def _setContent(self):
definition = [
'%sclass %s(%s, TypeDefinition):' %(ID1, self.getClassName(),
self.sKlass),
'%s%s' % (ID2, self.schemaTag()),
'%s%s' % (ID2, self.typeTag()),
'%s%s' % (ID2, self.pnameConstructor()),
]
if self.getPythonType() is None:
definition.append('%s%s.__init__(self, pname, **kw)' %(ID3,
self.sKlass))
else:
definition.append('%s%s.__init__(self, pname, pyclass=None, **kw)' \
%(ID3, self.sKlass,))
# pyclass class definition
definition += self.getPyClassDefinition()
# set pyclass
kw = KW.copy()
kw['pyclass'] = self.getPyClass()
definition.append('%(ID3)sself.pyclass = %(pyclass)s' %kw)
self.writeArray(definition)
class ComplexTypeSimpleContentContainer(SimpleTypeContainer, AttributeMixIn):
'''Represents a ComplexType with simpleContent.
'''
type = DEF
logger = _GetLogger("ComplexTypeSimpleContentContainer")
def setUp(self, tp):
'''tp -- complexType/simpleContent/[Exention,Restriction]
'''
self._item = tp
assert tp.isComplex() is True and tp.content.isSimple() is True,\
'expecting complexType/simpleContent not: %s' %tp.content.getItemTrace()
simple = tp.content
dv = simple.content
assert dv.isExtension() is True or dv.isRestriction() is True,\
'expecting complexType/simpleContent/[Extension,Restriction] not: %s' \
%tp.content.getItemTrace()
self.name = tp.getAttribute('name')
self.ns = tp.getTargetNamespace()
# TODO: Why is this being set?
self.content.attributeContent = dv.getAttributeContent()
base = dv.getAttribute('base')
if base is not None:
self.sKlass = BTI.get_typeclass( base[1], base[0] )
if not self.sKlass:
self.sKlass,self.sKlassNS = base[1], base[0]
self.attrComponents = self._setAttributes(
self.content.attributeContent
)
return
raise Wsdl2PythonError,\
'simple content derivation bad base attribute: ' %tp.getItemTrace()
def _setContent(self):
# TODO: Add derivation logic to constructors.
if type(self.sKlass) in (types.ClassType, type):
definition = [
'%sclass %s(%s, TypeDefinition):' \
% (ID1, self.getClassName(), self.sKlass),
'%s# ComplexType/SimpleContent derivation of built-in type' %ID2,
'%s%s' % (ID2, self.schemaTag()),
'%s%s' % (ID2, self.typeTag()),
'%s%s' % (ID2, self.pnameConstructor()),
'%sif getattr(self, "attribute_typecode_dict", None) is None: %s = {}' %(
ID3, self.attribute_typecode),
]
for l in self.attrComponents:
definition.append('%s%s'%(ID3, l))
definition.append('%s%s.__init__(self, pname, **kw)' %(ID3, self.sKlass))
if self.getPythonType() is not None:
definition += self.getPyClassDefinition()
kw = KW.copy()
kw['pyclass'] = self.getPyClass()
definition.append('%(ID3)sself.pyclass = %(pyclass)s' %kw)
self.writeArray(definition)
return
definition = [
'%sclass %s(TypeDefinition):' % (ID1, self.getClassName()),
'%s# ComplexType/SimpleContent derivation of user-defined type' %ID2,
'%s%s' % (ID2, self.schemaTag()),
'%s%s' % (ID2, self.typeTag()),
'%s%s' % (ID2, self.pnameConstructor()),
'%s%s' % (ID3, self.nsuriLogic()),
'%s' % self.getBasesLogic(ID3),
'%sif getattr(self, "attribute_typecode_dict", None) is None: %s = {}' %(
ID3, self.attribute_typecode),
]
for l in self.attrComponents:
definition.append('%s%s'%(ID3, l))
definition.append('%s%s.%s.__init__(self, pname, **kw)' %(
ID3, NAD.getAlias(self.sKlassNS), type_class_name(self.sKlass)))
self.writeArray(definition)
def getPyClassDefinition(self):
definition = []
pt = self.getPythonType()
if pt is not None:
definition.append('%sclass %s(%s):' %(ID3,self.getPyClass(),pt))
if self.metaclass is not None:
definition.append('%s__metaclass__ = %s' %(ID4, self.metaclass))
definition.append('%stypecode = self' %ID4)
return definition
class UnionContainer(SimpleTypeContainer):
'''SimpleType Union
'''
type = DEF
logger = _GetLogger("UnionContainer")
def __init__(self):
SimpleTypeContainer.__init__(self)
self.memberTypes = None
def setUp(self, tp):
self._item = tp
if tp.content.isUnion() is False:
raise ContainerError, 'content must be a Union: %s' %tp.getItemTrace()
self.name = tp.getAttribute('name')
self.ns = tp.getTargetNamespace()
self.sKlass = 'ZSI.TC.Union'
self.memberTypes = tp.content.getAttribute('memberTypes')
def _setContent(self):
definition = [
'%sclass %s(%s, TypeDefinition):' \
% (ID1, self.getClassName(), self.sKlass),
'%smemberTypes = %s' % (ID2, self.memberTypes),
'%s%s' % (ID2, self.schemaTag()),
'%s%s' % (ID2, self.typeTag()),
'%s%s' % (ID2, self.pnameConstructor()),
'%s%s' % (ID3, self.pnameConstructor(self.sKlass)),
]
# TODO: Union pyclass is None
self.writeArray(definition)
class ListContainer(SimpleTypeContainer):
'''SimpleType List
'''
type = DEF
logger = _GetLogger("ListContainer")
def setUp(self, tp):
self._item = tp
if tp.content.isList() is False:
raise ContainerError, 'content must be a List: %s' %tp.getItemTrace()
self.name = tp.getAttribute('name')
self.ns = tp.getTargetNamespace()
self.sKlass = 'ZSI.TC.List'
self.itemType = tp.content.getAttribute('itemType')
def _setContent(self):
definition = [
'%sclass %s(%s, TypeDefinition):' \
% (ID1, self.getClassName(), self.sKlass),
'%sitemType = %s' % (ID2, self.itemType),
'%s%s' % (ID2, self.schemaTag()),
'%s%s' % (ID2, self.typeTag()),
'%s%s' % (ID2, self.pnameConstructor()),
'%s%s' % (ID3, self.pnameConstructor(self.sKlass)),
]
self.writeArray(definition) | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/ZSI/generate/containers.py | containers.py |
import pydoc, sys, warnings
from ZSI import TC
# If function.__name__ is read-only, fail
def _x(): return
try:
_x.func_name = '_y'
except:
raise RuntimeError,\
'use python-2.4 or later, cannot set function names in python "%s"'\
%sys.version
del _x
#def GetNil(typecode=None):
# """returns the nilled element, use to set an element
# as nilled for immutable instance.
# """
#
# nil = TC.Nilled()
# if typecode is not None: nil.typecode = typecode
# return nil
#
#
#def GetNilAsSelf(cls, typecode=None):
# """returns the nilled element with typecode specified,
# use returned instance to set this element as nilled.
#
# Key Word Parameters:
# typecode -- use to specify a derived type or wildcard as nilled.
# """
# if typecode is not None and not isinstance(typecode, TC.TypeCode):
# raise TypeError, "Expecting a TypeCode instance"
#
# nil = TC.Nilled()
# nil.typecode = typecode or cls.typecode
# return nil
class pyclass_type(type):
"""Stability: Unstable
type for pyclasses used with typecodes. expects the typecode to
be available in the classdict. creates python properties for accessing
and setting the elements specified in the ofwhat list, and factory methods
for constructing the elements.
Known Limitations:
1)Uses XML Schema element names directly to create method names,
using characters in this set will cause Syntax Errors:
(NCNAME)-(letter U digit U "_")
"""
def __new__(cls, classname, bases, classdict):
"""
"""
#import new
typecode = classdict.get('typecode')
assert typecode is not None, 'MUST HAVE A TYPECODE.'
# Assume this means immutable type. ie. str
if len(bases) > 0:
#classdict['new_Nill'] = classmethod(GetNilAsSelf)
pass
# Assume this means mutable type. ie. ofwhat.
else:
assert hasattr(typecode, 'ofwhat'), 'typecode has no ofwhat list??'
assert hasattr(typecode, 'attribute_typecode_dict'),\
'typecode has no attribute_typecode_dict??'
#classdict['new_Nill'] = staticmethod(GetNil)
if typecode.mixed:
get,set = cls.__create_text_functions_from_what(typecode)
if classdict.has_key(get.__name__):
raise AttributeError,\
'attribute %s previously defined.' %get.__name__
if classdict.has_key(set.__name__):
raise AttributeError,\
'attribute %s previously defined.' %set.__name__
classdict[get.__name__] = get
classdict[set.__name__] = set
for what in typecode.ofwhat:
get,set,new_func = cls.__create_functions_from_what(what)
if classdict.has_key(get.__name__):
raise AttributeError,\
'attribute %s previously defined.' %get.__name__
classdict[get.__name__] = get
if classdict.has_key(set.__name__):
raise AttributeError,\
'attribute %s previously defined.' %set.__name__
classdict[set.__name__] = set
if new_func is not None:
if classdict.has_key(new_func.__name__):
raise AttributeError,\
'attribute %s previously defined.' %new_func.__name__
classdict[new_func.__name__] = new_func
assert not classdict.has_key(what.pname),\
'collision with pname="%s", bail..' %what.pname
pname = what.pname
if pname is None and isinstance(what, TC.AnyElement): pname = 'any'
assert pname is not None, 'Element with no name: %s' %what
# TODO: for pname if keyword just uppercase first letter.
#if pydoc.Helper.keywords.has_key(pname):
pname = pname[0].upper() + pname[1:]
assert not pydoc.Helper.keywords.has_key(pname), 'unexpected keyword: %s' %pname
classdict[pname] =\
property(get, set, None,
'property for element (%s,%s), minOccurs="%s" maxOccurs="%s" nillable="%s"'\
%(what.nspname,what.pname,what.minOccurs,what.maxOccurs,what.nillable)
)
#
# mutable type <complexType> complexContent | modelGroup
# or immutable type <complexType> simpleContent (float, str, etc)
#
if hasattr(typecode, 'attribute_typecode_dict'):
attribute_typecode_dict = typecode.attribute_typecode_dict or {}
for key,what in attribute_typecode_dict.items():
get,set = cls.__create_attr_functions_from_what(key, what)
if classdict.has_key(get.__name__):
raise AttributeError,\
'attribute %s previously defined.' %get.__name__
if classdict.has_key(set.__name__):
raise AttributeError,\
'attribute %s previously defined.' %set.__name__
classdict[get.__name__] = get
classdict[set.__name__] = set
return type.__new__(cls,classname,bases,classdict)
def __create_functions_from_what(what):
if not callable(what):
def get(self):
return getattr(self, what.aname)
if what.maxOccurs > 1:
def set(self, value):
if not (value is None or hasattr(value, '__iter__')):
raise TypeError, 'expecting an iterable instance'
setattr(self, what.aname, value)
else:
def set(self, value):
setattr(self, what.aname, value)
else:
def get(self):
return getattr(self, what().aname)
if what.maxOccurs > 1:
def set(self, value):
if not (value is None or hasattr(value, '__iter__')):
raise TypeError, 'expecting an iterable instance'
setattr(self, what().aname, value)
else:
def set(self, value):
setattr(self, what().aname, value)
#
# new factory function
# if pyclass is None, skip
#
if not callable(what) and getattr(what, 'pyclass', None) is None:
new_func = None
elif (isinstance(what, TC.ComplexType) or
isinstance(what, TC.Array)):
def new_func(self):
'''returns a mutable type
'''
return what.pyclass()
elif not callable(what):
def new_func(self, value):
'''value -- initialize value
returns an immutable type
'''
return what.pyclass(value)
elif (issubclass(what.klass, TC.ComplexType) or
issubclass(what.klass, TC.Array)):
def new_func(self):
'''returns a mutable type or None (if no pyclass).
'''
p = what().pyclass
if p is None: return
return p()
else:
def new_func(self, value=None):
'''if simpleType provide initialization value, else
if complexType value should be left as None.
Parameters:
value -- initialize value or None
returns a mutable instance (value is None)
or an immutable instance or None (if no pyclass)
'''
p = what().pyclass
if p is None: return
if value is None: return p()
return p(value)
#TODO: sub all illegal characters in set
# (NCNAME)-(letter U digit U "_")
if new_func is not None:
new_func.__name__ = 'new_%s' %what.pname
get.func_name = 'get_element_%s' %what.pname
set.func_name = 'set_element_%s' %what.pname
return get,set,new_func
__create_functions_from_what = staticmethod(__create_functions_from_what)
def __create_attr_functions_from_what(key, what):
def get(self):
'''returns attribute value for attribute %s, else None.
''' %str(key)
return getattr(self, what.attrs_aname, {}).get(key, None)
def set(self, value):
'''set value for attribute %s.
value -- initialize value, immutable type
''' %str(key)
if not hasattr(self, what.attrs_aname):
setattr(self, what.attrs_aname, {})
getattr(self, what.attrs_aname)[key] = value
#TODO: sub all illegal characters in set
# (NCNAME)-(letter U digit U "_")
if type(key) in (tuple, list):
get.__name__ = 'get_attribute_%s' %key[1]
set.__name__ = 'set_attribute_%s' %key[1]
else:
get.__name__ = 'get_attribute_%s' %key
set.__name__ = 'set_attribute_%s' %key
return get,set
__create_attr_functions_from_what = \
staticmethod(__create_attr_functions_from_what)
def __create_text_functions_from_what(what):
def get(self):
'''returns text content, else None.
'''
return getattr(self, what.mixed_aname, None)
get.im_func = 'get_text'
def set(self, value):
'''set text content.
value -- initialize value, immutable type
'''
setattr(self, what.mixed_aname, value)
get.im_func = 'set_text'
return get,set
__create_text_functions_from_what = \
staticmethod(__create_text_functions_from_what) | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/ZSI/generate/pyclass.py | pyclass.py |
import exceptions, sys, optparse, os, warnings
from operator import xor
import ZSI
from ConfigParser import ConfigParser
from ZSI.generate.wsdl2python import WriteServiceModule, ServiceDescription
from ZSI.wstools import WSDLTools, XMLSchema
from ZSI.wstools.logging import setBasicLoggerDEBUG
from ZSI.generate import containers, utility
from ZSI.generate.utility import NCName_to_ClassName as NC_to_CN, TextProtect
from ZSI.generate.wsdl2dispatch import ServiceModuleWriter as ServiceDescription
from ZSI.generate.wsdl2dispatch import DelAuthServiceModuleWriter as DelAuthServiceDescription
from ZSI.generate.wsdl2dispatch import WSAServiceModuleWriter as ServiceDescriptionWSA
from ZSI.generate.wsdl2dispatch import DelAuthWSAServiceModuleWriter as DelAuthServiceDescriptionWSA
warnings.filterwarnings('ignore', '', exceptions.UserWarning)
def SetDebugCallback(option, opt, value, parser, *args, **kwargs):
setBasicLoggerDEBUG()
warnings.resetwarnings()
def SetPyclassMetaclass(option, opt, value, parser, *args, **kwargs):
"""set up pyclass metaclass for complexTypes"""
from ZSI.generate.containers import ServiceHeaderContainer, TypecodeContainerBase, TypesHeaderContainer
TypecodeContainerBase.metaclass = kwargs['metaclass']
TypesHeaderContainer.imports.append(\
'from %(module)s import %(metaclass)s' %kwargs
)
ServiceHeaderContainer.imports.append(\
'from %(module)s import %(metaclass)s' %kwargs
)
def SetUpTwistedClient(option, opt, value, parser, *args, **kwargs):
from ZSI.generate.containers import ServiceHeaderContainer
ServiceHeaderContainer.imports.remove('from ZSI import client')
ServiceHeaderContainer.imports.append('from ZSI.twisted import client')
def SetUpLazyEvaluation(option, opt, value, parser, *args, **kwargs):
from ZSI.generate.containers import TypecodeContainerBase
TypecodeContainerBase.lazy = True
def formatSchemaObject(fname, schemaObj):
""" In the case of a 'schema only' generation (-s) this creates
a fake wsdl object that will function w/in the adapters
and allow the generator to do what it needs to do.
"""
class fake:
pass
f = fake()
if fname.rfind('/'):
tmp = fname[fname.rfind('/') + 1 :].split('.')
else:
tmp = fname.split('.')
f.name = tmp[0] + '_' + tmp[1]
f.types = { schemaObj.targetNamespace : schemaObj }
return f
def wsdl2py(args=None):
"""
A utility for automatically generating client interface code from a wsdl
definition, and a set of classes representing element declarations and
type definitions. This will produce two files in the current working
directory named after the wsdl definition name.
eg. <definition name='SampleService'>
SampleService.py
SampleService_types.py
"""
op = optparse.OptionParser(usage="usage: %prog [options]",
description=wsdl2py.__doc__)
# Basic options
op.add_option("-f", "--file",
action="store", dest="file", default=None, type="string",
help="FILE to load wsdl from")
op.add_option("-u", "--url",
action="store", dest="url", default=None, type="string",
help="URL to load wsdl from")
op.add_option("-x", "--schema",
action="store_true", dest="schema", default=False,
help="process just the schema from an xsd file [no services]")
op.add_option("-d", "--debug",
action="callback", callback=SetDebugCallback,
help="debug output")
# WS Options
op.add_option("-a", "--address",
action="store_true", dest="address", default=False,
help="ws-addressing support, must include WS-Addressing schema.")
# pyclass Metaclass
op.add_option("-b", "--complexType",
action="callback", callback=SetPyclassMetaclass,
callback_kwargs={'module':'ZSI.generate.pyclass',
'metaclass':'pyclass_type'},
help="add convenience functions for complexTypes, including Getters, Setters, factory methods, and properties (via metaclass). *** DONT USE WITH --simple-naming ***")
# Lazy Evaluation of Typecodes (done at serialization/parsing when needed).
op.add_option("-l", "--lazy",
action="callback", callback=SetUpLazyEvaluation,
callback_kwargs={},
help="EXPERIMENTAL: recursion error solution, lazy evalution of typecodes")
# Use Twisted
op.add_option("-w", "--twisted",
action="callback", callback=SetUpTwistedClient,
callback_kwargs={'module':'ZSI.generate.pyclass',
'metaclass':'pyclass_type'},
help="generate a twisted.web client, dependencies python>=2.4, Twisted>=2.0.0, TwistedWeb>=0.5.0")
# Extended generation options
op.add_option("-e", "--extended",
action="store_true", dest="extended", default=False,
help="Do Extended code generation.")
op.add_option("-z", "--aname",
action="store", dest="aname", default=None, type="string",
help="pass in a function for attribute name creation")
op.add_option("-t", "--types",
action="store", dest="types", default=None, type="string",
help="file to load types from")
op.add_option("-o", "--output-dir",
action="store", dest="output_dir", default=".", type="string",
help="Write generated files to OUTPUT_DIR")
op.add_option("-s", "--simple-naming",
action="store_true", dest="simple_naming", default=False,
help="Simplify generated naming.")
op.add_option("-c", "--clientClassSuffix",
action="store", dest="clientClassSuffix", default=None, type="string",
help="Suffix to use for service client class (default \"SOAP\")")
op.add_option("-m", "--pyclassMapModule",
action="store", dest="pyclassMapModule", default=None, type="string",
help="Python file that maps external python classes to a schema type. The classes are used as the \"pyclass\" for that type. The module should contain a dict() called mapping in the format: mapping = {schemaTypeName:(moduleName.py,className) }")
if args is None:
(options, args) = op.parse_args()
else:
(options, args) = op.parse_args(args)
if not xor(options.file is None, options.url is None):
print 'Must specify either --file or --url option'
sys.exit(os.EX_USAGE)
location = options.file
if options.url is not None:
location = options.url
if options.schema is True:
reader = XMLSchema.SchemaReader(base_url=location)
else:
reader = WSDLTools.WSDLReader()
load = reader.loadFromFile
if options.url is not None:
load = reader.loadFromURL
wsdl = None
try:
wsdl = load(location)
except Exception, e:
print "Error loading %s: \n\t%s" % (location, e)
# exit code UNIX specific, Windows?
sys.exit(os.EX_NOINPUT)
if options.simple_naming:
# Use a different client suffix
WriteServiceModule.client_module_suffix = "_client"
# Write messages definitions to a separate file.
ServiceDescription.separate_messages = True
# Use more simple type and element class names
containers.SetTypeNameFunc( lambda n: '%s_' %(NC_to_CN(n)) )
containers.SetElementNameFunc( lambda n: '%s' %(NC_to_CN(n)) )
# Don't add "_" to the attribute name (remove when --aname works well)
containers.ContainerBase.func_aname = lambda instnc,n: TextProtect(str(n))
# write out the modules with their names rather than their number.
utility.namespace_name = lambda cls, ns: utility.Namespace2ModuleName(ns)
if options.clientClassSuffix:
from ZSI.generate.containers import ServiceContainerBase
ServiceContainerBase.clientClassSuffix = options.clientClassSuffix
if options.schema is True:
wsdl = formatSchemaObject(location, wsdl)
if options.aname is not None:
args = options.aname.rsplit('.',1)
assert len(args) == 2, 'expecting module.function'
# The following exec causes a syntax error.
#exec('from %s import %s as FUNC' %(args[0],args[1]))
assert callable(FUNC),\
'%s must be a callable method with one string parameter' %options.aname
from ZSI.generate.containers import TypecodeContainerBase
TypecodeContainerBase.func_aname = staticmethod(FUNC)
if options.pyclassMapModule != None:
mod = __import__(options.pyclassMapModule)
components = options.pyclassMapModule.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
extPyClasses = mod.mapping
else:
extPyClasses = None
wsm = WriteServiceModule(wsdl, addressing=options.address, do_extended=options.extended, extPyClasses=extPyClasses)
if options.types != None:
wsm.setTypesModuleName(options.types)
if options.schema is False:
fd = open(os.path.join(options.output_dir, '%s.py' %wsm.getClientModuleName()), 'w+')
# simple naming writes the messages to a separate file
if not options.simple_naming:
wsm.writeClient(fd)
else: # provide a separate file to store messages to.
msg_fd = open(os.path.join(options.output_dir, '%s.py' %wsm.getMessagesModuleName()), 'w+')
wsm.writeClient(fd, msg_fd=msg_fd)
msg_fd.close()
fd.close()
fd = open( os.path.join(options.output_dir, '%s.py' %wsm.getTypesModuleName()), 'w+')
wsm.writeTypes(fd)
fd.close()
def wsdl2dispatch(args=None):
"""
wsdl2dispatch
A utility for automatically generating service skeleton code from a wsdl
definition.
"""
op = optparse.OptionParser()
op.add_option("-f", "--file",
action="store", dest="file", default=None, type="string",
help="file to load wsdl from")
op.add_option("-u", "--url",
action="store", dest="url", default=None, type="string",
help="URL to load wsdl from")
op.add_option("-a", "--address",
action="store_true", dest="address", default=False,
help="ws-addressing support, must include WS-Addressing schema.")
op.add_option("-e", "--extended",
action="store_true", dest="extended", default=False,
help="Extended code generation.")
op.add_option("-d", "--debug",
action="callback", callback=SetDebugCallback,
help="debug output")
op.add_option("-t", "--types",
action="store", dest="types", default=None, type="string",
help="Write generated files to OUTPUT_DIR")
op.add_option("-o", "--output-dir",
action="store", dest="output_dir", default=".", type="string",
help="file to load types from")
op.add_option("-s", "--simple-naming",
action="store_true", dest="simple_naming", default=False,
help="Simplify generated naming.")
if args is None:
(options, args) = op.parse_args()
else:
(options, args) = op.parse_args(args)
if options.simple_naming:
ServiceDescription.server_module_suffix = '_interface'
ServiceDescription.func_aname = lambda instnc,n: TextProtect(n)
ServiceDescription.separate_messages = True
# use module names rather than their number.
utility.namespace_name = lambda cls, ns: utility.Namespace2ModuleName(ns)
reader = WSDLTools.WSDLReader()
wsdl = None
if options.file is not None:
wsdl = reader.loadFromFile(options.file)
elif options.url is not None:
wsdl = reader.loadFromURL(options.url)
assert wsdl is not None, 'Must specify WSDL either with --file or --url'
ss = None
if options.address is True:
if options.extended:
ss = DelAuthServiceDescriptionWSA(do_extended=options.extended)
else:
ss = ServiceDescriptionWSA(do_extended=options.extended)
else:
if options.extended:
ss = DelAuthServiceDescription(do_extended=options.extended)
else:
ss = ServiceDescription(do_extended=options.extended)
ss.fromWSDL(wsdl)
fd = open( os.path.join(options.output_dir, ss.getServiceModuleName()+'.py'), 'w+')
ss.write(fd)
fd.close() | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/ZSI/generate/commands.py | commands.py |
# main generator engine for new generation generator
# $Id: wsdl2python.py 1203 2006-05-03 00:13:20Z boverhof $
import os
from ZSI import _get_idstr
from ZSI.wstools.logging import getLogger as _GetLogger
from ZSI.wstools import WSDLTools
from ZSI.wstools.WSDLTools import SoapAddressBinding,\
SoapBodyBinding, SoapBinding,MimeContentBinding,\
HttpUrlEncodedBinding
from ZSI.wstools.XMLSchema import SchemaReader, ElementDeclaration, SchemaError
from ZSI.typeinterpreter import BaseTypeInterpreter
from ZSI.generate import WsdlGeneratorError, Wsdl2PythonError
from containers import *
from ZSI.generate import utility
from ZSI.generate.utility import NamespaceAliasDict as NAD
from ZSI.generate.utility import GetModuleBaseNameFromWSDL
"""
classes:
WriteServiceModule
-- composes/writes out client stubs and types module.
ServiceDescription
-- represents a single WSDL service.
MessageWriter
-- represents a single WSDL Message and associated bindings
of the port/binding.
SchemaDescription
-- generates classes for defs and decs in the schema instance.
TypeWriter
-- represents a type definition.
ElementWriter
-- represents a element declaration.
"""
class WriteServiceModule:
"""top level driver class invoked by wsd2py
class variables:
client_module_suffix -- suffix of client module.
types_module_suffix -- suffix of types module.
"""
client_module_suffix = '_services'
messages_module_suffix = '_messages'
types_module_suffix = '_services_types'
logger = _GetLogger("WriteServiceModule")
def __init__(self, wsdl, addressing=False, notification=False,
do_extended=False, extPyClasses=None, configParser = None):
self._wsdl = wsdl
self._addressing = addressing
self._notification = notification
self._configParser = configParser
self.usedNamespaces = None
self.services = []
self.client_module_path = None
self.types_module_name = None
self.types_module_path = None
self.messages_module_path = None # used in extended generation
self.do_extended = do_extended
self.extPyClasses = extPyClasses
def getClientModuleName(self):
"""client module name.
"""
name = GetModuleBaseNameFromWSDL(self._wsdl)
if not name:
raise WsdlGeneratorError, 'could not determine a service name'
if self.client_module_suffix is None:
return name
return '%s%s' %(name, self.client_module_suffix)
def getMessagesModuleName(self):
name = GetModuleBaseNameFromWSDL(self._wsdl)
if not name:
raise WsdlGeneratorError, 'could not determine a service name'
if self.messages_module_suffix is None:
return name
if len(self.messages_module_suffix) == 0:
return self.getClientModuleName()
return '%s%s' %(name, self.messages_module_suffix)
def setTypesModuleName(self, name):
self.types_module_name = name
def getTypesModuleName(self):
"""types module name.
"""
if self.types_module_name is not None:
return self.types_module_name
name = GetModuleBaseNameFromWSDL(self._wsdl)
if not name:
raise WsdlGeneratorError, 'could not determine a service name'
if self.types_module_suffix is None:
return name
return '%s%s' %(name, self.types_module_suffix)
def setClientModulePath(self, path):
"""setup module path to where client module before calling fromWsdl.
module path to types module eg. MyApp.client
"""
self.client_module_path = path
def getTypesModulePath(self):
"""module path to types module eg. MyApp.types
"""
return self.types_module_path
def getMessagesModulePath(self):
'''module path to messages module
same as types path
'''
return self.messages_module_path
def setTypesModulePath(self, path):
"""setup module path to where service module before calling fromWsdl.
module path to types module eg. MyApp.types
"""
self.types_module_path = path
def setMessagesModulePath(self, path):
"""setup module path to where message module before calling fromWsdl.
module path to types module eg. MyApp.types
"""
self.messages_module_path = path
def gatherNamespaces(self):
'''This method must execute once.. Grab all schemas
representing each targetNamespace.
'''
if self.usedNamespaces is not None:
return
self.logger.debug('gatherNamespaces')
self.usedNamespaces = {}
# Add all schemas defined in wsdl
# to used namespace and to the Alias dict
for schema in self._wsdl.types.values():
tns = schema.getTargetNamespace()
self.logger.debug('Register schema(%s) -- TNS(%s)'\
%(_get_idstr(schema), tns),)
if self.usedNamespaces.has_key(tns) is False:
self.usedNamespaces[tns] = []
self.usedNamespaces[tns].append(schema)
NAD.add(tns)
# Add all xsd:import schema instances
# to used namespace and to the Alias dict
for k,v in SchemaReader.namespaceToSchema.items():
self.logger.debug('Register schema(%s) -- TNS(%s)'\
%(_get_idstr(v), k),)
if self.usedNamespaces.has_key(k) is False:
self.usedNamespaces[k] = []
self.usedNamespaces[k].append(v)
NAD.add(k)
def writeClient(self, fd, sdClass=None, msg_fd=None, **kw):
"""write out client module to file descriptor.
Parameters and Keywords arguments:
fd -- file descriptor
msg_fd -- optional messsages module file descriptor
sdClass -- service description class name
imports -- list of imports
readerclass -- class name of ParsedSoap reader
writerclass -- class name of SoapWriter writer
"""
sdClass = sdClass or ServiceDescription
assert issubclass(sdClass, ServiceDescription), \
'parameter sdClass must subclass ServiceDescription'
header = '%s \n# %s.py \n# generated by %s\n%s\n\n'\
%('#'*50, self.getClientModuleName(), self.__module__, '#'*50)
fd.write(header)
if msg_fd is not None:
# TODO: Why is this not getMessagesModuleName?
msg_filename = str(self.getClientModuleName()).replace("client", "messages")
if self.getMessagesModulePath() is not None:
msg_filename = os.path.join(self.getMessagesModulePath(), msg_filename)
messages_header = header.replace("client", "messages")
msg_fd.write(messages_header)
self.services = []
for service in self._wsdl.services:
sd = sdClass(self._addressing, do_extended=self.do_extended, wsdl=self._wsdl)
if len(self._wsdl.types) > 0:
sd.setTypesModuleName(self.getTypesModuleName(), self.getTypesModulePath())
sd.setMessagesModuleName(self.getMessagesModuleName(), self.getMessagesModulePath())
self.gatherNamespaces()
sd.fromWsdl(service, **kw)
sd.write(fd,msg_fd)
self.services.append(sd)
def writeTypes(self, fd):
"""write out types module to file descriptor.
"""
header = '%s \n# %s.py \n# generated by %s\n%s\n\n'\
%('#'*50, self.getTypesModuleName(), self.__module__, '#'*50)
fd.write(header)
print >>fd, TypesHeaderContainer()
self.gatherNamespaces()
for l in self.usedNamespaces.values():
sd = SchemaDescription(do_extended=self.do_extended, extPyClasses=self.extPyClasses)
for schema in l:
sd.fromSchema(schema)
sd.write(fd)
class ServiceDescription:
"""client interface - locator, port, etc classes"""
separate_messages = False
logger = _GetLogger("ServiceDescription")
def __init__(self, addressing=False, do_extended=False, wsdl=None):
self.typesModuleName = None
self.messagesModuleName = None
self.wsAddressing = addressing
self.imports = ServiceHeaderContainer()
self.messagesImports = ServiceHeaderContainer()
self.locator = ServiceLocatorContainer()
self.methods = []
self.messages = []
self.do_extended=do_extended
self._wsdl = wsdl # None unless do_extended == True
def setTypesModuleName(self, name, modulePath=None):
"""The types module to be imported.
Parameters
name -- name of types module
modulePath -- optional path where module is located.
"""
self.typesModuleName = '%s' %name
if modulePath is not None:
self.typesModuleName = '%s.%s' %(modulePath,name)
def setMessagesModuleName(self, name, modulePath=None):
'''The types module to be imported.
Parameters
name -- name of types module
modulePath -- optional path where module is located.
'''
self.messagesModuleName = '%s' %name
if modulePath is not None:
self.messagesModuleName = '%s.%s' %(modulePath,name)
def fromWsdl(self, service, **kw):
self.imports.setTypesModuleName(self.typesModuleName)
if self.separate_messages:
self.messagesImports.setMessagesModuleName(self.messagesModuleName)
self.imports.appendImport(kw.get('imports', []))
self.locator.setUp(service)
for port in service.ports:
sop_container = ServiceOperationsClassContainer(useWSA=self.wsAddressing, do_extended=self.do_extended, wsdl=self._wsdl)
try:
sop_container.setUp(port)
except Wsdl2PythonError, ex:
self.logger.warning('Skipping port(%s)' %port.name)
if len(ex.args):
self.logger.warning(ex.args[0])
else:
sop_container.setReaderClass(kw.get('readerclass'))
sop_container.setWriterClass(kw.get('writerclass'))
for soc in sop_container.operations:
if soc.hasInput() is True:
mw = MessageWriter(do_extended=self.do_extended)
mw.setUp(soc, port, input=True)
self.messages.append(mw)
if soc.hasOutput() is True:
mw = MessageWriter(do_extended=self.do_extended)
mw.setUp(soc, port, input=False)
self.messages.append(mw)
self.methods.append(sop_container)
def write(self, fd, msg_fd=None):
"""write out module to file descriptor.
fd -- file descriptor to write out service description.
msg_fd -- optional file descriptor for messages module.
"""
if msg_fd != None:
print >>fd, self.messagesImports
print >>msg_fd, self.imports
else:
print >>fd, self.imports
print >>fd, self.locator
for m in self.methods:
print >>fd, m
if msg_fd != None:
for m in self.messages:
print >>msg_fd, m
else:
for m in self.messages:
print >>fd, m
class MessageWriter:
logger = _GetLogger("MessageWriter")
def __init__(self, do_extended=False):
"""Representation of a WSDL Message and associated WSDL Binding.
operation --
boperation --
input --
rpc --
literal --
simple --
"""
self.content = None
self.do_extended = do_extended
def __str__(self):
if not self.content:
raise Wsdl2PythonError, 'Must call setUp.'
return self.content.getvalue()
def setUp(self, soc, port, input=False):
assert isinstance(soc, ServiceOperationContainer),\
'expecting a ServiceOperationContainer instance'
assert isinstance(port, WSDLTools.Port),\
'expecting a WSDL.Port instance'
rpc,literal = soc.isRPC(), soc.isLiteral(input)
kw,klass = {}, None
if rpc and literal:
klass = ServiceRPCLiteralMessageContainer
elif not rpc and literal:
kw['do_extended'] = self.do_extended
klass = ServiceDocumentLiteralMessageContainer
elif rpc and not literal:
klass = ServiceRPCEncodedMessageContainer
else:
raise WsdlGeneratorError, 'doc/enc not supported.'
self.content = klass(**kw)
self.content.setUp(port, soc, input)
class SchemaDescription:
"""generates classes for defs and decs in the schema instance.
"""
logger = _GetLogger("SchemaDescription")
def __init__(self, do_extended=False, extPyClasses=None):
self.classHead = NamespaceClassHeaderContainer()
self.classFoot = NamespaceClassFooterContainer()
self.items = []
self.__types = []
self.__elements = []
self.targetNamespace = None
self.do_extended=do_extended
self.extPyClasses = extPyClasses
def fromSchema(self, schema):
''' Can be called multiple times, but will not redefine a
previously defined type definition or element declaration.
'''
ns = schema.getTargetNamespace()
assert self.targetNamespace is None or self.targetNamespace == ns,\
'SchemaDescription instance represents %s, not %s'\
%(self.targetNamespace, ns)
if self.targetNamespace is None:
self.targetNamespace = ns
self.classHead.ns = self.classFoot.ns = ns
for item in [t for t in schema.types if t.getAttributeName() not in self.__types]:
self.__types.append(item.getAttributeName())
self.items.append(TypeWriter(do_extended=self.do_extended, extPyClasses=self.extPyClasses))
self.items[-1].fromSchemaItem(item)
for item in [e for e in schema.elements if e.getAttributeName() not in self.__elements]:
self.__elements.append(item.getAttributeName())
self.items.append(ElementWriter(do_extended=self.do_extended))
self.items[-1].fromSchemaItem(item)
def getTypes(self):
return self.__types
def getElements(self):
return self.__elements
def write(self, fd):
"""write out to file descriptor.
"""
print >>fd, self.classHead
for t in self.items:
print >>fd, t
print >>fd, self.classFoot
class SchemaItemWriter:
"""contains/generates a single declaration"""
logger = _GetLogger("SchemaItemWriter")
def __init__(self, do_extended=False, extPyClasses=None):
self.content = None
self.do_extended=do_extended
self.extPyClasses=extPyClasses
def __str__(self):
'''this appears to set up whatever is in self.content.localElements,
local elements simpleType|complexType.
'''
assert self.content is not None, 'Must call fromSchemaItem to setup.'
return str(self.content)
def fromSchemaItem(self, item):
raise NotImplementedError, ''
class ElementWriter(SchemaItemWriter):
"""contains/generates a single declaration"""
logger = _GetLogger("ElementWriter")
def fromSchemaItem(self, item):
"""set up global elements.
"""
if item.isElement() is False or item.isLocal() is True:
raise TypeError, 'expecting global element declaration: %s' %item.getItemTrace()
local = False
qName = item.getAttribute('type')
if not qName:
etp = item.content
local = True
else:
etp = item.getTypeDefinition('type')
if etp is None:
if local is True:
self.content = ElementLocalComplexTypeContainer(do_extended=self.do_extended)
else:
self.content = ElementSimpleTypeContainer()
elif etp.isLocal() is False:
self.content = ElementGlobalDefContainer()
elif etp.isSimple() is True:
self.content = ElementLocalSimpleTypeContainer()
elif etp.isComplex():
self.content = ElementLocalComplexTypeContainer(do_extended=self.do_extended)
else:
raise Wsdl2PythonError, "Unknown element declaration: %s" %item.getItemTrace()
self.logger.debug('ElementWriter setUp container "%r", Schema Item "%s"' %(
self.content, item.getItemTrace()))
self.content.setUp(item)
class TypeWriter(SchemaItemWriter):
"""contains/generates a single definition"""
logger = _GetLogger("TypeWriter")
def fromSchemaItem(self, item):
if item.isDefinition() is False or item.isLocal() is True:
raise TypeError, \
'expecting global type definition not: %s' %item.getItemTrace()
self.content = None
if item.isSimple():
if item.content.isRestriction():
self.content = RestrictionContainer()
elif item.content.isUnion():
self.content = UnionContainer()
elif item.content.isList():
self.content = ListContainer()
else:
raise Wsdl2PythonError,\
'unknown simple type definition: %s' %item.getItemTrace()
self.content.setUp(item)
return
if item.isComplex():
kw = {}
if item.content is None or item.content.isModelGroup():
self.content = \
ComplexTypeContainer(\
do_extended=self.do_extended,
extPyClasses=self.extPyClasses
)
kw['empty'] = item.content is None
elif item.content.isSimple():
self.content = ComplexTypeSimpleContentContainer()
elif item.content.isComplex():
self.content = \
ComplexTypeComplexContentContainer(\
do_extended=self.do_extended
)
else:
raise Wsdl2PythonError,\
'unknown complex type definition: %s' %item.getItemTrace()
self.logger.debug('TypeWriter setUp container "%r", Schema Item "%s"' %(
self.content, item.getItemTrace()))
try:
self.content.setUp(item, **kw)
except Exception, ex:
args = ['Failure in setUp: %s' %item.getItemTrace()]
args += ex.args
ex.args = tuple(args)
raise
return
raise TypeError,\
'expecting SimpleType or ComplexType: %s' %item.getItemTrace() | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/ZSI/generate/wsdl2python.py | wsdl2python.py |
from cStringIO import StringIO
import ZSI, string, sys, getopt, urlparse, types, warnings
from ZSI.wstools import WSDLTools
from ZSI.generate.wsdl2python import WriteServiceModule, MessageTypecodeContainer
from ZSI.ServiceContainer import ServiceSOAPBinding, SimpleWSResource
from ZSI.generate.utility import TextProtect, GetModuleBaseNameFromWSDL, NCName_to_ClassName, GetPartsSubNames, TextProtectAttributeName
from ZSI.generate import WsdlGeneratorError, Wsdl2PythonError
from ZSI.generate.wsdl2python import SchemaDescription
# Split last token
rsplit = lambda x,sep,: (x[:x.rfind(sep)], x[x.rfind(sep)+1:],)
if sys.version_info[0:2] == (2, 4, 0, 'final', 0)[0:2]:
rsplit = lambda x,sep,: x.rsplit(sep, 1)
class SOAPService:
def __init__(self, service):
self.classdef = StringIO()
self.initdef = StringIO()
self.location = ''
self.methods = []
def newMethod(self):
'''name -- operation name
'''
self.methods.append(StringIO())
return self.methods[-1]
class ServiceModuleWriter:
'''Creates a skeleton for a SOAP service instance.
'''
indent = ' '*4
server_module_suffix = '_services_server'
func_aname = TextProtectAttributeName
func_aname = staticmethod(func_aname)
separate_messages = False # Whether to write message definitions into a separate file.
def __init__(self, base=ServiceSOAPBinding, prefix='soap', service_class=SOAPService, do_extended=False):
'''
parameters:
base -- either a class definition, or a str representing a qualified class name.
prefix -- method prefix.
'''
self.wsdl = None
self.base_class = base
self.method_prefix = prefix
self._service_class = SOAPService
self.header = None
self.imports = None
self._services = None
self.client_module_path = None
self.client_module_name = None
self.messages_module_name = None
self.do_extended = do_extended
def reset(self):
self.header = StringIO()
self.imports = StringIO()
self._services = {}
def _getBaseClassName(self):
'''return base class name, do not override.
'''
if type(self.base_class) is types.ClassType:
return self.base_class.__name__
return rsplit(self.base_class, '.')[-1]
def _getBaseClassModule(self):
'''return base class module, do not override.
'''
if type(self.base_class) is types.ClassType:
return self.base_class.__module__
if self.base_class.find('.') >= 0:
return rsplit(self.base_class, '.')[0]
return None
def getIndent(self, level=1):
'''return indent.
'''
assert 0 < level < 10, 'bad indent level %d' %level
return self.indent*level
def getMethodName(self, method):
'''return method name.
'''
return '%s_%s' %(self.method_prefix, TextProtect(method))
def getClassName(self, name):
'''return class name.
'''
return NCName_to_ClassName(name)
def setClientModuleName(self, name):
self.client_module_name = name
def getClientModuleName(self):
'''return module name.
'''
assert self.wsdl is not None, 'initialize, call fromWSDL'
if self.client_module_name is not None:
return self.client_module_name
wsm = WriteServiceModule(self.wsdl, do_extended=self.do_extended)
return wsm.getClientModuleName()
def getMessagesModuleName(self):
'''return module name.
'''
assert self.wsdl is not None, 'initialize, call fromWSDL'
if self.messages_module_name is not None:
return self.messages_module_name
wsm = WriteServiceModule(self.wsdl, do_extended=self.do_extended)
return wsm.getMessagesModuleName()
def getServiceModuleName(self):
'''return module name.
'''
name = GetModuleBaseNameFromWSDL(self.wsdl)
if not name:
raise WsdlGeneratorError, 'could not determine a service name'
if self.server_module_suffix is None:
return name
return '%s%s' %(name, self.server_module_suffix)
def getClientModulePath(self):
return self.client_module_path
def setClientModulePath(self, path):
'''setup module path to where client module before calling fromWSDL.
'''
self.client_module_path = path
def setUpClassDef(self, service):
'''set class definition and class variables.
service -- ServiceDescription instance
'''
assert isinstance(service, WSDLTools.Service) is True,\
'expecting WSDLTools.Service instance.'
s = self._services[service.name].classdef
print >>s, 'class %s(%s):' %(self.getClassName(service.name), self._getBaseClassName())
print >>s, '%ssoapAction = {}' % self.getIndent(level=1)
print >>s, '%sroot = {}' % self.getIndent(level=1)
print >>s, "%s_wsdl = \"\"\"%s\"\"\"" % (self.getIndent(level=1), self.raw_wsdl)
def setUpImports(self):
'''set import statements
'''
path = self.getClientModulePath()
i = self.imports
if path is None:
if self.separate_messages:
print >>i, 'from %s import *' %self.getMessagesModuleName()
else:
print >>i, 'from %s import *' %self.getClientModuleName()
else:
if self.separate_messages:
print >>i, 'from %s.%s import *' %(path, self.getMessagesModuleName())
else:
print >>i, 'from %s.%s import *' %(path, self.getClientModuleName())
mod = self._getBaseClassModule()
name = self._getBaseClassName()
if mod is None:
print >>i, 'import %s' %name
else:
print >>i, 'from %s import %s' %(mod, name)
def setUpInitDef(self, service):
'''set __init__ function
'''
assert isinstance(service, WSDLTools.Service), 'expecting WSDLTools.Service instance.'
sd = self._services[service.name]
d = sd.initdef
if sd.location is not None:
scheme,netloc,path,params,query,fragment = urlparse.urlparse(sd.location)
print >>d, '%sdef __init__(self, post=\'%s\', **kw):' %(self.getIndent(level=1), path)
else:
print >>d, '%sdef __init__(self, post, **kw):' %self.getIndent(level=1)
print >>d, '%s%s.__init__(self, post)' %(self.getIndent(level=2),self._getBaseClassName())
def mangle(self, name):
return TextProtect(name)
def getAttributeName(self, name):
return self.func_aname(name)
def setUpMethods(self, port):
'''set up all methods representing the port operations.
Parameters:
port -- Port that defines the operations.
'''
assert isinstance(port, WSDLTools.Port), \
'expecting WSDLTools.Port not: ' %type(port)
sd = self._services.get(port.getService().name)
assert sd is not None, 'failed to initialize.'
binding = port.getBinding()
portType = port.getPortType()
action_in = ''
for bop in binding.operations:
try:
op = portType.operations[bop.name]
except KeyError, ex:
raise WsdlGeneratorError,\
'Port(%s) PortType(%s) missing operation(%s) defined in Binding(%s)' \
%(port.name,portType.name,bop.name,binding.name)
for ext in bop.extensions:
if isinstance(ext, WSDLTools.SoapOperationBinding):
action_in = ext.soapAction
break
else:
warnings.warn('Port(%s) operation(%s) defined in Binding(%s) missing soapAction' \
%(port.name,op.name,binding.name)
)
msgin = op.getInputMessage()
msgin_name = TextProtect(msgin.name)
method_name = self.getMethodName(op.name)
m = sd.newMethod()
print >>m, '%sdef %s(self, ps):' %(self.getIndent(level=1), method_name)
if msgin is not None:
print >>m, '%sself.request = ps.Parse(%s.typecode)' %(self.getIndent(level=2), msgin_name)
else:
print >>m, '%s# NO input' %self.getIndent(level=2)
msgout = op.getOutputMessage()
if self.do_extended:
input_args = msgin.parts.values()
iargs = ["%s" % x.name for x in input_args]
if msgout is not None:
output_args = msgout.parts.values()
else:
output_args = []
oargs = ["%s" % x.name for x in output_args]
if output_args:
if len(output_args) > 1:
print "Message has more than one return value (Bad Design)."
output_args = "(%s)" % output_args
else:
output_args = ""
# Get arg list
iSubNames = GetPartsSubNames(msgin.parts.values(), self.wsdl)
for i in range( len(iargs) ): # should only be one part to messages here anyway
argSubNames = iSubNames[i]
if len(argSubNames) > 0:
subNamesStr = "self.request." + ", self.request.".join(map(self.getAttributeName, argSubNames))
if len(argSubNames) > 1:
subNamesStr = "(" + subNamesStr + ")"
print >>m, "%s%s = %s" % (self.getIndent(level=2), iargs[i], subNamesStr)
print >>m, "\n%s# If we have an implementation object use it" % (self.getIndent(level=2))
print >>m, "%sif hasattr(self,'impl'):" % (self.getIndent(level=2))
iargsStrList = []
for arg in iargs:
argSubNames = iSubNames[i]
if len(argSubNames) > 0:
if len(argSubNames) > 1:
for i in range(len(argSubNames)):
iargsStrList.append( arg + "[%i]" % i )
else:
iargsStrList.append( arg )
iargsStr = ",".join(iargsStrList)
oargsStr = ", ".join(oargs)
if len(oargsStr) > 0:
oargsStr += " = "
print >>m, "%s%sself.impl.%s(%s)" % (self.getIndent(level=3), oargsStr, op.name, iargsStr)
if msgout is not None:
msgout_name = TextProtect(msgout.name)
if self.do_extended:
print >>m, '\n%sresult = %s()' %(self.getIndent(level=2), msgout_name)
oSubNames = GetPartsSubNames(msgout.parts.values(), self.wsdl)
if (len(oSubNames) > 0) and (len(oSubNames[0]) > 0):
print >>m, "%s# If we have an implementation object, copy the result " % (self.getIndent(level=2))
print >>m, "%sif hasattr(self,'impl'):" % (self.getIndent(level=2))
# copy result's members
for i in range( len(oargs) ): # should only be one part messages here anyway
oargSubNames = oSubNames[i]
if len(oargSubNames) > 1:
print >>m, '%s# Should have a tuple of %i args' %(self.getIndent(level=3), len(oargSubNames))
for j in range(len(oargSubNames)):
oargSubName = oargSubNames[j]
print >>m, '%sresult.%s = %s[%i]' %(self.getIndent(level=3), self.getAttributeName(oargSubName), oargs[i], j)
elif len(oargSubNames) == 1:
oargSubName = oargSubNames[0]
print >>m, '%sresult.%s = %s' %(self.getIndent(level=3), self.getAttributeName(oargSubName), oargs[i])
else:
raise Exception("The subnames within message " + msgout_name + "'s part were not found. Message is the output of operation " + op.name)
print >>m, '%sreturn result' %(self.getIndent(level=2))
else:
print >>m, '%sreturn %s()' %(self.getIndent(level=2), msgout_name)
else:
print >>m, '%s# NO output' % self.getIndent(level=2)
print >>m, '%sreturn None' % self.getIndent(level=2)
print >>m, ''
print >>m, '%ssoapAction[\'%s\'] = \'%s\'' %(self.getIndent(level=1), action_in, method_name)
print >>m, '%sroot[(%s.typecode.nspname,%s.typecode.pname)] = \'%s\'' \
%(self.getIndent(level=1), msgin_name, msgin_name, method_name)
return
def setUpHeader(self):
print >>self.header, '##################################################'
print >>self.header, '# %s.py' %self.getServiceModuleName()
print >>self.header, '# Generated by %s' %(self.__class__)
print >>self.header, '#'
print >>self.header, '##################################################'
def write(self, fd=sys.stdout):
'''write out to file descriptor,
should not need to override.
'''
print >>fd, self.header.getvalue()
print >>fd, self.imports.getvalue()
for k,v in self._services.items():
print >>fd, v.classdef.getvalue()
print >>fd, v.initdef.getvalue()
for s in v.methods:
print >>fd, s.getvalue()
def fromWSDL(self, wsdl):
'''setup the service description from WSDL,
should not need to override.
'''
assert isinstance(wsdl, WSDLTools.WSDL), 'expecting WSDL instance'
if len(wsdl.services) == 0:
raise WsdlGeneratorError, 'No service defined'
self.reset()
self.wsdl = wsdl
self.raw_wsdl = wsdl.document.toxml().replace("\"", "\\\"")
self.setUpHeader()
self.setUpImports()
for service in wsdl.services:
sd = self._service_class(service.name)
self._services[service.name] = sd
for port in service.ports:
for e in port.extensions:
if isinstance(e, WSDLTools.SoapAddressBinding):
sd.location = e.location
self.setUpMethods(port)
self.setUpClassDef(service)
self.setUpInitDef(service)
class WSAServiceModuleWriter(ServiceModuleWriter):
'''Creates a skeleton for a WS-Address service instance.
'''
def __init__(self, base=SimpleWSResource, prefix='wsa', service_class=SOAPService, strict=True):
'''
Parameters:
strict -- check that soapAction and input ws-action do not collide.
'''
ServiceModuleWriter.__init__(self, base, prefix, service_class)
self.strict = strict
def createMethodBody(msgInName, msgOutName, **kw):
'''return a tuple of strings containing the body of a method.
msgInName -- None or a str
msgOutName -- None or a str
'''
body = []
if msgInName is not None:
body.append('self.request = ps.Parse(%s.typecode)' %msgInName)
if msgOutName is not None:
body.append('return %s()' %msgOutName)
else:
body.append('return None')
return tuple(body)
createMethodBody = staticmethod(createMethodBody)
def setUpClassDef(self, service):
'''use soapAction dict for WS-Action input, setup wsAction
dict for grabbing WS-Action output values.
'''
assert isinstance(service, WSDLTools.Service), 'expecting WSDLTools.Service instance'
s = self._services[service.name].classdef
print >>s, 'class %s(%s):' %(self.getClassName(service.name), self._getBaseClassName())
print >>s, '%ssoapAction = {}' % self.getIndent(level=1)
print >>s, '%swsAction = {}' % self.getIndent(level=1)
print >>s, '%sroot = {}' % self.getIndent(level=1)
def setUpMethods(self, port):
'''set up all methods representing the port operations.
Parameters:
port -- Port that defines the operations.
'''
assert isinstance(port, WSDLTools.Port), \
'expecting WSDLTools.Port not: ' %type(port)
binding = port.getBinding()
portType = port.getPortType()
service = port.getService()
s = self._services[service.name]
for bop in binding.operations:
try:
op = portType.operations[bop.name]
except KeyError, ex:
raise WsdlGeneratorError,\
'Port(%s) PortType(%s) missing operation(%s) defined in Binding(%s)' \
%(port.name, portType.name, op.name, binding.name)
soap_action = wsaction_in = wsaction_out = None
if op.input is not None:
wsaction_in = op.getInputAction()
if op.output is not None:
wsaction_out = op.getOutputAction()
for ext in bop.extensions:
if isinstance(ext, WSDLTools.SoapOperationBinding) is False: continue
soap_action = ext.soapAction
if wsaction_in is None: break
if wsaction_in == soap_action: break
if self.strict is False:
warnings.warn(\
'Port(%s) operation(%s) in Binding(%s) soapAction(%s) != WS-Action(%s)' \
%(port.name, op.name, binding.name, soap_action, wsaction_in),
)
break
raise WsdlGeneratorError,\
'Port(%s) operation(%s) in Binding(%s) soapAction(%s) MUST match WS-Action(%s)' \
%(port.name, op.name, binding.name, soap_action, wsaction_in)
method_name = self.getMethodName(op.name)
m = s.newMethod()
print >>m, '%sdef %s(self, ps, address):' %(self.getIndent(level=1), method_name)
msgin_name = msgout_name = None
msgin,msgout = op.getInputMessage(),op.getOutputMessage()
if msgin is not None:
msgin_name = TextProtect(msgin.name)
if msgout is not None:
msgout_name = TextProtect(msgout.name)
indent = self.getIndent(level=2)
for l in self.createMethodBody(msgin_name, msgout_name):
print >>m, indent + l
print >>m, ''
print >>m, '%ssoapAction[\'%s\'] = \'%s\'' %(self.getIndent(level=1), wsaction_in, method_name)
print >>m, '%swsAction[\'%s\'] = \'%s\'' %(self.getIndent(level=1), method_name, wsaction_out)
print >>m, '%sroot[(%s.typecode.nspname,%s.typecode.pname)] = \'%s\'' \
%(self.getIndent(level=1), msgin_name, msgin_name, method_name)
class DelAuthServiceModuleWriter(ServiceModuleWriter):
''' Includes the generation of lines to call an authorization method on the server side
if an authorization function has been defined.
'''
def __init__(self, base=ServiceSOAPBinding, prefix='soap', service_class=SOAPService, do_extended=False):
ServiceModuleWriter.__init__(self, base=base, prefix=prefix, service_class=service_class, do_extended=do_extended)
def fromWSDL(self, wsdl):
ServiceModuleWriter.fromWSDL(self, wsdl)
for service in wsdl.services:
self.setUpAuthDef(service)
def setUpInitDef(self, service):
ServiceModuleWriter.setUpInitDef(self, service)
sd = self._services[service.name]
d = sd.initdef
print >>d, '%sif kw.has_key(\'impl\'):' % self.getIndent(level=2)
print >>d, '%sself.impl = kw[\'impl\']' % self.getIndent(level=3)
print >>d, '%sself.auth_method_name = None' % self.getIndent(level=2)
print >>d, '%sif kw.has_key(\'auth_method_name\'):' % self.getIndent(level=2)
print >>d, '%sself.auth_method_name = kw[\'auth_method_name\']' % self.getIndent(level=3)
def setUpAuthDef(self, service):
'''set __auth__ function
'''
sd = self._services[service.name]
e = sd.initdef
print >>e, "%sdef authorize(self, auth_info, post, action):" % self.getIndent(level=1)
print >>e, "%sif self.auth_method_name and hasattr(self.impl, self.auth_method_name):" % self.getIndent(level=2)
print >>e, "%sreturn getattr(self.impl, self.auth_method_name)(auth_info, post, action)" % self.getIndent(level=3)
print >>e, "%selse:" % self.getIndent(level=2)
print >>e, "%sreturn 1" % self.getIndent(level=3)
class DelAuthWSAServiceModuleWriter(WSAServiceModuleWriter):
def __init__(self, base=SimpleWSResource, prefix='wsa', service_class=SOAPService, strict=True):
WSAServiceModuleWriter.__init__(self, base=base, prefix=prefix, service_class=service_class, strict=strict)
def fromWSDL(self, wsdl):
WSAServiceModuleWriter.fromWSDL(self, wsdl)
for service in wsdl.services:
self.setUpAuthDef(service)
def setUpInitDef(self, service):
WSAServiceModuleWriter.setUpInitDef(self, service)
sd = self._services[service.name]
d = sd.initdef
print >>d, '%sif kw.has_key(\'impl\'):' % self.getIndent(level=2)
print >>d, '%sself.impl = kw[\'impl\']' % self.getIndent(level=3)
print >>d, '%sif kw.has_key(\'auth_method_name\'):' % self.getIndent(level=2)
print >>d, '%sself.auth_method_name = kw[\'auth_method_name\']' % self.getIndent(level=3)
def setUpAuthDef(self, service):
'''set __auth__ function
'''
sd = self._services[service.name]
e = sd.initdef
print >>e, "%sdef authorize(self, auth_info, post, action):" % self.getIndent(level=1)
print >>e, "%sif self.auth_method_name and hasattr(self.impl, self.auth_method_name):" % self.getIndent(level=2)
print >>e, "%sreturn getattr(self.impl, self.auth_method_name)(auth_info, post, action)" % self.getIndent(level=3)
print >>e, "%selse:" % self.getIndent(level=2)
print >>e, "%sreturn 1" % self.getIndent(level=3) | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/ZSI/generate/wsdl2dispatch.py | wsdl2dispatch.py |
#XXX tuple instances (in Python 2.2) contain also:
# __class__, __delattr__, __getattribute__, __hash__, __new__,
# __reduce__, __setattr__, __str__
# What about these?
class UserTuple:
def __init__(self, inittuple=None):
self.data = ()
if inittuple is not None:
# XXX should this accept an arbitrary sequence?
if type(inittuple) == type(self.data):
self.data = inittuple
elif isinstance(inittuple, UserTuple):
# this results in
# self.data is inittuple.data
# but that's ok for tuples because they are
# immutable. (Builtin tuples behave the same.)
self.data = inittuple.data[:]
else:
# the same applies here; (t is tuple(t)) == 1
self.data = tuple(inittuple)
def __repr__(self): return repr(self.data)
def __lt__(self, other): return self.data < self.__cast(other)
def __le__(self, other): return self.data <= self.__cast(other)
def __eq__(self, other): return self.data == self.__cast(other)
def __ne__(self, other): return self.data != self.__cast(other)
def __gt__(self, other): return self.data > self.__cast(other)
def __ge__(self, other): return self.data >= self.__cast(other)
def __cast(self, other):
if isinstance(other, UserTuple): return other.data
else: return other
def __cmp__(self, other):
return cmp(self.data, self.__cast(other))
def __contains__(self, item): return item in self.data
def __len__(self): return len(self.data)
def __getitem__(self, i): return self.data[i]
def __getslice__(self, i, j):
i = max(i, 0); j = max(j, 0)
return self.__class__(self.data[i:j])
def __add__(self, other):
if isinstance(other, UserTuple):
return self.__class__(self.data + other.data)
elif isinstance(other, type(self.data)):
return self.__class__(self.data + other)
else:
return self.__class__(self.data + tuple(other))
# dir( () ) contains no __radd__ (at least in Python 2.2)
def __mul__(self, n):
return self.__class__(self.data*n)
__rmul__ = __mul__ | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/ZSI/wstools/UserTuple.py | UserTuple.py |
"""Logging"""
ident = "$Id: logging.py 1204 2006-05-03 00:13:47Z boverhof $"
import sys
WARN = 1
DEBUG = 2
class ILogger:
'''Logger interface, by default this class
will be used and logging calls are no-ops.
'''
level = 0
def __init__(self, msg):
return
def warning(self, *args):
return
def debug(self, *args):
return
def error(self, *args):
return
def setLevel(cls, level):
cls.level = level
setLevel = classmethod(setLevel)
debugOn = lambda self: self.level >= DEBUG
warnOn = lambda self: self.level >= WARN
class BasicLogger(ILogger):
last = ''
def __init__(self, msg, out=sys.stdout):
self.msg, self.out = msg, out
def warning(self, msg, *args):
if self.warnOn() is False: return
if BasicLogger.last != self.msg:
BasicLogger.last = self.msg
print >>self, "---- ", self.msg, " ----"
print >>self, " %s " %BasicLogger.WARN,
print >>self, msg %args
WARN = '[WARN]'
def debug(self, msg, *args):
if self.debugOn() is False: return
if BasicLogger.last != self.msg:
BasicLogger.last = self.msg
print >>self, "---- ", self.msg, " ----"
print >>self, " %s " %BasicLogger.DEBUG,
print >>self, msg %args
DEBUG = '[DEBUG]'
def error(self, msg, *args):
if BasicLogger.last != self.msg:
BasicLogger.last = self.msg
print >>self, "---- ", self.msg, " ----"
print >>self, " %s " %BasicLogger.ERROR,
print >>self, msg %args
ERROR = '[ERROR]'
def write(self, *args):
'''Write convenience function; writes strings.
'''
for s in args: self.out.write(s)
_LoggerClass = BasicLogger
def setBasicLogger():
'''Use Basic Logger.
'''
setLoggerClass(BasicLogger)
BasicLogger.setLevel(0)
def setBasicLoggerWARN():
'''Use Basic Logger.
'''
setLoggerClass(BasicLogger)
BasicLogger.setLevel(WARN)
def setBasicLoggerDEBUG():
'''Use Basic Logger.
'''
setLoggerClass(BasicLogger)
BasicLogger.setLevel(DEBUG)
def setLoggerClass(loggingClass):
'''Set Logging Class.
'''
assert issubclass(loggingClass, ILogger), 'loggingClass must subclass ILogger'
global _LoggerClass
_LoggerClass = loggingClass
def setLevel(level=0):
'''Set Global Logging Level.
'''
ILogger.level = level
def getLevel():
return ILogger.level
def getLogger(msg):
'''Return instance of Logging class.
'''
return _LoggerClass(msg) | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/ZSI/wstools/logging.py | logging.py |
ident = "$Id: TimeoutSocket.py 237 2003-05-20 21:10:14Z warnes $"
import string, socket, select, errno
WSAEINVAL = getattr(errno, 'WSAEINVAL', 10022)
class TimeoutSocket:
"""A socket imposter that supports timeout limits."""
def __init__(self, timeout=20, sock=None):
self.timeout = float(timeout)
self.inbuf = ''
if sock is None:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock = sock
self.sock.setblocking(0)
self._rbuf = ''
self._wbuf = ''
def __getattr__(self, name):
# Delegate to real socket attributes.
return getattr(self.sock, name)
def connect(self, *addr):
timeout = self.timeout
sock = self.sock
try:
# Non-blocking mode
sock.setblocking(0)
apply(sock.connect, addr)
sock.setblocking(timeout != 0)
return 1
except socket.error,why:
if not timeout:
raise
sock.setblocking(1)
if len(why.args) == 1:
code = 0
else:
code, why = why
if code not in (
errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK
):
raise
r,w,e = select.select([],[sock],[],timeout)
if w:
try:
apply(sock.connect, addr)
return 1
except socket.error,why:
if len(why.args) == 1:
code = 0
else:
code, why = why
if code in (errno.EISCONN, WSAEINVAL):
return 1
raise
raise TimeoutError('socket connect() timeout.')
def send(self, data, flags=0):
total = len(data)
next = 0
while 1:
r, w, e = select.select([],[self.sock], [], self.timeout)
if w:
buff = data[next:next + 8192]
sent = self.sock.send(buff, flags)
next = next + sent
if next == total:
return total
continue
raise TimeoutError('socket send() timeout.')
def recv(self, amt, flags=0):
if select.select([self.sock], [], [], self.timeout)[0]:
return self.sock.recv(amt, flags)
raise TimeoutError('socket recv() timeout.')
buffsize = 4096
handles = 1
def makefile(self, mode="r", buffsize=-1):
self.handles = self.handles + 1
self.mode = mode
return self
def close(self):
self.handles = self.handles - 1
if self.handles == 0 and self.sock.fileno() >= 0:
self.sock.close()
def read(self, n=-1):
if not isinstance(n, type(1)):
n = -1
if n >= 0:
k = len(self._rbuf)
if n <= k:
data = self._rbuf[:n]
self._rbuf = self._rbuf[n:]
return data
n = n - k
L = [self._rbuf]
self._rbuf = ""
while n > 0:
new = self.recv(max(n, self.buffsize))
if not new: break
k = len(new)
if k > n:
L.append(new[:n])
self._rbuf = new[n:]
break
L.append(new)
n = n - k
return "".join(L)
k = max(4096, self.buffsize)
L = [self._rbuf]
self._rbuf = ""
while 1:
new = self.recv(k)
if not new: break
L.append(new)
k = min(k*2, 1024**2)
return "".join(L)
def readline(self, limit=-1):
data = ""
i = self._rbuf.find('\n')
while i < 0 and not (0 < limit <= len(self._rbuf)):
new = self.recv(self.buffsize)
if not new: break
i = new.find('\n')
if i >= 0: i = i + len(self._rbuf)
self._rbuf = self._rbuf + new
if i < 0: i = len(self._rbuf)
else: i = i+1
if 0 <= limit < len(self._rbuf): i = limit
data, self._rbuf = self._rbuf[:i], self._rbuf[i:]
return data
def readlines(self, sizehint = 0):
total = 0
list = []
while 1:
line = self.readline()
if not line: break
list.append(line)
total += len(line)
if sizehint and total >= sizehint:
break
return list
def writelines(self, list):
self.send(''.join(list))
def write(self, data):
self.send(data)
def flush(self):
pass
class TimeoutError(Exception):
pass | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/ZSI/wstools/TimeoutSocket.py | TimeoutSocket.py |
ident = "$Id: XMLname.py 954 2005-02-16 14:45:37Z warnes $"
from re import *
def _NCNameChar(x):
return x.isalpha() or x.isdigit() or x=="." or x=='-' or x=="_"
def _NCNameStartChar(x):
return x.isalpha() or x=="_"
def _toUnicodeHex(x):
hexval = hex(ord(x[0]))[2:]
hexlen = len(hexval)
# Make hexval have either 4 or 8 digits by prepending 0's
if (hexlen==1): hexval = "000" + hexval
elif (hexlen==2): hexval = "00" + hexval
elif (hexlen==3): hexval = "0" + hexval
elif (hexlen==4): hexval = "" + hexval
elif (hexlen==5): hexval = "000" + hexval
elif (hexlen==6): hexval = "00" + hexval
elif (hexlen==7): hexval = "0" + hexval
elif (hexlen==8): hexval = "" + hexval
else: raise Exception, "Illegal Value returned from hex(ord(x))"
return "_x"+ hexval + "_"
def _fromUnicodeHex(x):
return eval( r'u"\u'+x[2:-1]+'"' )
def toXMLname(string):
"""Convert string to a XML name."""
if string.find(':') != -1 :
(prefix, localname) = string.split(':',1)
else:
prefix = None
localname = string
T = unicode(localname)
N = len(localname)
X = [];
for i in range(N) :
if i< N-1 and T[i]==u'_' and T[i+1]==u'x':
X.append(u'_x005F_')
elif i==0 and N >= 3 and \
( T[0]==u'x' or T[0]==u'X' ) and \
( T[1]==u'm' or T[1]==u'M' ) and \
( T[2]==u'l' or T[2]==u'L' ):
X.append(u'_xFFFF_' + T[0])
elif (not _NCNameChar(T[i])) or (i==0 and not _NCNameStartChar(T[i])):
X.append(_toUnicodeHex(T[i]))
else:
X.append(T[i])
if prefix:
return "%s:%s" % (prefix, u''.join(X))
return u''.join(X)
def fromXMLname(string):
"""Convert XML name to unicode string."""
retval = sub(r'_xFFFF_','', string )
def fun( matchobj ):
return _fromUnicodeHex( matchobj.group(0) )
retval = sub(r'_x[0-9A-Za-z]+_', fun, retval )
return retval | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/ZSI/wstools/XMLname.py | XMLname.py |
ident = "$Id: Namespaces.py 1160 2006-03-17 19:28:11Z boverhof $"
try:
from xml.ns import SOAP, SCHEMA, WSDL, XMLNS, DSIG, ENCRYPTION
DSIG.C14N = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"
except:
class SOAP:
ENV = "http://schemas.xmlsoap.org/soap/envelope/"
ENC = "http://schemas.xmlsoap.org/soap/encoding/"
ACTOR_NEXT = "http://schemas.xmlsoap.org/soap/actor/next"
class SCHEMA:
XSD1 = "http://www.w3.org/1999/XMLSchema"
XSD2 = "http://www.w3.org/2000/10/XMLSchema"
XSD3 = "http://www.w3.org/2001/XMLSchema"
XSD_LIST = [ XSD1, XSD2, XSD3 ]
XSI1 = "http://www.w3.org/1999/XMLSchema-instance"
XSI2 = "http://www.w3.org/2000/10/XMLSchema-instance"
XSI3 = "http://www.w3.org/2001/XMLSchema-instance"
XSI_LIST = [ XSI1, XSI2, XSI3 ]
BASE = XSD3
class WSDL:
BASE = "http://schemas.xmlsoap.org/wsdl/"
BIND_HTTP = "http://schemas.xmlsoap.org/wsdl/http/"
BIND_MIME = "http://schemas.xmlsoap.org/wsdl/mime/"
BIND_SOAP = "http://schemas.xmlsoap.org/wsdl/soap/"
BIND_SOAP12 = "http://schemas.xmlsoap.org/wsdl/soap12/"
class XMLNS:
BASE = "http://www.w3.org/2000/xmlns/"
XML = "http://www.w3.org/XML/1998/namespace"
HTML = "http://www.w3.org/TR/REC-html40"
class DSIG:
BASE = "http://www.w3.org/2000/09/xmldsig#"
C14N = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"
C14N_COMM = "http://www.w3.org/TR/2000/CR-xml-c14n-20010315#WithComments"
C14N_EXCL = "http://www.w3.org/2001/10/xml-exc-c14n#"
DIGEST_MD2 = "http://www.w3.org/2000/09/xmldsig#md2"
DIGEST_MD5 = "http://www.w3.org/2000/09/xmldsig#md5"
DIGEST_SHA1 = "http://www.w3.org/2000/09/xmldsig#sha1"
ENC_BASE64 = "http://www.w3.org/2000/09/xmldsig#base64"
ENVELOPED = "http://www.w3.org/2000/09/xmldsig#enveloped-signature"
HMAC_SHA1 = "http://www.w3.org/2000/09/xmldsig#hmac-sha1"
SIG_DSA_SHA1 = "http://www.w3.org/2000/09/xmldsig#dsa-sha1"
SIG_RSA_SHA1 = "http://www.w3.org/2000/09/xmldsig#rsa-sha1"
XPATH = "http://www.w3.org/TR/1999/REC-xpath-19991116"
XSLT = "http://www.w3.org/TR/1999/REC-xslt-19991116"
class ENCRYPTION:
BASE = "http://www.w3.org/2001/04/xmlenc#"
BLOCK_3DES = "http://www.w3.org/2001/04/xmlenc#des-cbc"
BLOCK_AES128 = "http://www.w3.org/2001/04/xmlenc#aes128-cbc"
BLOCK_AES192 = "http://www.w3.org/2001/04/xmlenc#aes192-cbc"
BLOCK_AES256 = "http://www.w3.org/2001/04/xmlenc#aes256-cbc"
DIGEST_RIPEMD160 = "http://www.w3.org/2001/04/xmlenc#ripemd160"
DIGEST_SHA256 = "http://www.w3.org/2001/04/xmlenc#sha256"
DIGEST_SHA512 = "http://www.w3.org/2001/04/xmlenc#sha512"
KA_DH = "http://www.w3.org/2001/04/xmlenc#dh"
KT_RSA_1_5 = "http://www.w3.org/2001/04/xmlenc#rsa-1_5"
KT_RSA_OAEP = "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"
STREAM_ARCFOUR = "http://www.w3.org/2001/04/xmlenc#arcfour"
WRAP_3DES = "http://www.w3.org/2001/04/xmlenc#kw-3des"
WRAP_AES128 = "http://www.w3.org/2001/04/xmlenc#kw-aes128"
WRAP_AES192 = "http://www.w3.org/2001/04/xmlenc#kw-aes192"
WRAP_AES256 = "http://www.w3.org/2001/04/xmlenc#kw-aes256"
class WSRF_V1_2:
'''OASIS WSRF Specifications Version 1.2
'''
class LIFETIME:
XSD_DRAFT1 = "http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-ResourceLifetime-1.2-draft-01.xsd"
XSD_DRAFT4 = "http://docs.oasis-open.org/wsrf/2004/11/wsrf-WS-ResourceLifetime-1.2-draft-04.xsd"
WSDL_DRAFT1 = "http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-ResourceLifetime-1.2-draft-01.wsdl"
WSDL_DRAFT4 = "http://docs.oasis-open.org/wsrf/2004/11/wsrf-WS-ResourceLifetime-1.2-draft-04.wsdl"
LATEST = WSDL_DRAFT4
WSDL_LIST = (WSDL_DRAFT1, WSDL_DRAFT4)
XSD_LIST = (XSD_DRAFT1, XSD_DRAFT4)
class PROPERTIES:
XSD_DRAFT1 = "http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-ResourceProperties-1.2-draft-01.xsd"
XSD_DRAFT5 = "http://docs.oasis-open.org/wsrf/2004/11/wsrf-WS-ResourceProperties-1.2-draft-05.xsd"
WSDL_DRAFT1 = "http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-ResourceProperties-1.2-draft-01.wsdl"
WSDL_DRAFT5 = "http://docs.oasis-open.org/wsrf/2004/11/wsrf-WS-ResourceProperties-1.2-draft-05.wsdl"
LATEST = WSDL_DRAFT5
WSDL_LIST = (WSDL_DRAFT1, WSDL_DRAFT5)
XSD_LIST = (XSD_DRAFT1, XSD_DRAFT5)
class BASENOTIFICATION:
XSD_DRAFT1 = "http://docs.oasis-open.org/wsn/2004/06/wsn-WS-BaseNotification-1.2-draft-01.xsd"
WSDL_DRAFT1 = "http://docs.oasis-open.org/wsn/2004/06/wsn-WS-BaseNotification-1.2-draft-01.wsdl"
LATEST = WSDL_DRAFT1
WSDL_LIST = (WSDL_DRAFT1,)
XSD_LIST = (XSD_DRAFT1,)
class BASEFAULTS:
XSD_DRAFT1 = "http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-BaseFaults-1.2-draft-01.xsd"
XSD_DRAFT3 = "http://docs.oasis-open.org/wsrf/2004/11/wsrf-WS-BaseFaults-1.2-draft-03.xsd"
#LATEST = DRAFT3
#WSDL_LIST = (WSDL_DRAFT1, WSDL_DRAFT3)
XSD_LIST = (XSD_DRAFT1, XSD_DRAFT3)
WSRF = WSRF_V1_2
WSRFLIST = (WSRF_V1_2,)
class OASIS:
'''URLs for Oasis specifications
'''
WSSE = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
UTILITY = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
class X509TOKEN:
Base64Binary = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary"
STRTransform = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0"
PKCS7 = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#PKCS7"
X509 = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509"
X509PKIPathv1 = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509PKIPathv1"
X509v3SubjectKeyIdentifier = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3SubjectKeyIdentifier"
LIFETIME = WSRF_V1_2.LIFETIME.XSD_DRAFT1
PROPERTIES = WSRF_V1_2.PROPERTIES.XSD_DRAFT1
BASENOTIFICATION = WSRF_V1_2.BASENOTIFICATION.XSD_DRAFT1
BASEFAULTS = WSRF_V1_2.BASEFAULTS.XSD_DRAFT1
class WSTRUST:
BASE = "http://schemas.xmlsoap.org/ws/2004/04/trust"
ISSUE = "http://schemas.xmlsoap.org/ws/2004/04/trust/Issue"
class WSSE:
BASE = "http://schemas.xmlsoap.org/ws/2002/04/secext"
TRUST = WSTRUST.BASE
class WSU:
BASE = "http://schemas.xmlsoap.org/ws/2002/04/utility"
UTILITY = "http://schemas.xmlsoap.org/ws/2002/07/utility"
class WSR:
PROPERTIES = "http://www.ibm.com/xmlns/stdwip/web-services/WS-ResourceProperties"
LIFETIME = "http://www.ibm.com/xmlns/stdwip/web-services/WS-ResourceLifetime"
class WSA200408:
ADDRESS = "http://schemas.xmlsoap.org/ws/2004/08/addressing"
ANONYMOUS = "%s/role/anonymous" %ADDRESS
FAULT = "%s/fault" %ADDRESS
class WSA200403:
ADDRESS = "http://schemas.xmlsoap.org/ws/2004/03/addressing"
ANONYMOUS = "%s/role/anonymous" %ADDRESS
FAULT = "%s/fault" %ADDRESS
class WSA200303:
ADDRESS = "http://schemas.xmlsoap.org/ws/2003/03/addressing"
ANONYMOUS = "%s/role/anonymous" %ADDRESS
FAULT = None
WSA = WSA200408
WSA_LIST = (WSA200408, WSA200403, WSA200303)
class WSP:
POLICY = "http://schemas.xmlsoap.org/ws/2002/12/policy"
class BEA:
SECCONV = "http://schemas.xmlsoap.org/ws/2004/04/sc"
SCTOKEN = "http://schemas.xmlsoap.org/ws/2004/04/security/sc/sct"
class GLOBUS:
SECCONV = "http://wsrf.globus.org/core/2004/07/security/secconv"
CORE = "http://www.globus.org/namespaces/2004/06/core"
SIG = "http://www.globus.org/2002/04/xmlenc#gssapi-sign"
TOKEN = "http://www.globus.org/ws/2004/09/security/sc#GSSAPI_GSI_TOKEN"
ZSI_SCHEMA_URI = 'http://www.zolera.com/schemas/ZSI/' | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/ZSI/wstools/Namespaces.py | Namespaces.py |
ident = "$Id: XMLSchema.py 1207 2006-05-04 18:34:01Z boverhof $"
import types, weakref, sys, warnings
from Namespaces import SCHEMA, XMLNS
from Utility import DOM, DOMException, Collection, SplitQName, basejoin
from StringIO import StringIO
# If we have no threading, this should be a no-op
try:
from threading import RLock
except ImportError:
class RLock:
def acquire():
pass
def release():
pass
#
# Collections in XMLSchema class
#
TYPES = 'types'
ATTRIBUTE_GROUPS = 'attr_groups'
ATTRIBUTES = 'attr_decl'
ELEMENTS = 'elements'
MODEL_GROUPS = 'model_groups'
def GetSchema(component):
"""convience function for finding the parent XMLSchema instance.
"""
parent = component
while not isinstance(parent, XMLSchema):
parent = parent._parent()
return parent
class SchemaReader:
"""A SchemaReader creates XMLSchema objects from urls and xml data.
"""
namespaceToSchema = {}
def __init__(self, domReader=None, base_url=None):
"""domReader -- class must implement DOMAdapterInterface
base_url -- base url string
"""
self.__base_url = base_url
self.__readerClass = domReader
if not self.__readerClass:
self.__readerClass = DOMAdapter
self._includes = {}
self._imports = {}
def __setImports(self, schema):
"""Add dictionary of imports to schema instance.
schema -- XMLSchema instance
"""
for ns,val in schema.imports.items():
if self._imports.has_key(ns):
schema.addImportSchema(self._imports[ns])
def __setIncludes(self, schema):
"""Add dictionary of includes to schema instance.
schema -- XMLSchema instance
"""
for schemaLocation, val in schema.includes.items():
if self._includes.has_key(schemaLocation):
schema.addIncludeSchema(self._imports[schemaLocation])
def addSchemaByLocation(self, location, schema):
"""provide reader with schema document for a location.
"""
self._includes[location] = schema
def addSchemaByNamespace(self, schema):
"""provide reader with schema document for a targetNamespace.
"""
self._imports[schema.targetNamespace] = schema
def loadFromNode(self, parent, element):
"""element -- DOM node or document
parent -- WSDLAdapter instance
"""
reader = self.__readerClass(element)
schema = XMLSchema(parent)
#HACK to keep a reference
schema.wsdl = parent
schema.setBaseUrl(self.__base_url)
schema.load(reader)
return schema
def loadFromStream(self, file, url=None):
"""Return an XMLSchema instance loaded from a file object.
file -- file object
url -- base location for resolving imports/includes.
"""
reader = self.__readerClass()
reader.loadDocument(file)
schema = XMLSchema()
if url is not None:
schema.setBaseUrl(url)
schema.load(reader)
self.__setIncludes(schema)
self.__setImports(schema)
return schema
def loadFromString(self, data):
"""Return an XMLSchema instance loaded from an XML string.
data -- XML string
"""
return self.loadFromStream(StringIO(data))
def loadFromURL(self, url, schema=None):
"""Return an XMLSchema instance loaded from the given url.
url -- URL to dereference
schema -- Optional XMLSchema instance.
"""
reader = self.__readerClass()
if self.__base_url:
url = basejoin(self.__base_url,url)
reader.loadFromURL(url)
schema = schema or XMLSchema()
schema.setBaseUrl(url)
schema.load(reader)
self.__setIncludes(schema)
self.__setImports(schema)
return schema
def loadFromFile(self, filename):
"""Return an XMLSchema instance loaded from the given file.
filename -- name of file to open
"""
if self.__base_url:
filename = basejoin(self.__base_url,filename)
file = open(filename, 'rb')
try:
schema = self.loadFromStream(file, filename)
finally:
file.close()
return schema
class SchemaError(Exception):
pass
###########################
# DOM Utility Adapters
##########################
class DOMAdapterInterface:
def hasattr(self, attr, ns=None):
"""return true if node has attribute
attr -- attribute to check for
ns -- namespace of attribute, by default None
"""
raise NotImplementedError, 'adapter method not implemented'
def getContentList(self, *contents):
"""returns an ordered list of child nodes
*contents -- list of node names to return
"""
raise NotImplementedError, 'adapter method not implemented'
def setAttributeDictionary(self, attributes):
"""set attribute dictionary
"""
raise NotImplementedError, 'adapter method not implemented'
def getAttributeDictionary(self):
"""returns a dict of node's attributes
"""
raise NotImplementedError, 'adapter method not implemented'
def getNamespace(self, prefix):
"""returns namespace referenced by prefix.
"""
raise NotImplementedError, 'adapter method not implemented'
def getTagName(self):
"""returns tagName of node
"""
raise NotImplementedError, 'adapter method not implemented'
def getParentNode(self):
"""returns parent element in DOMAdapter or None
"""
raise NotImplementedError, 'adapter method not implemented'
def loadDocument(self, file):
"""load a Document from a file object
file --
"""
raise NotImplementedError, 'adapter method not implemented'
def loadFromURL(self, url):
"""load a Document from an url
url -- URL to dereference
"""
raise NotImplementedError, 'adapter method not implemented'
class DOMAdapter(DOMAdapterInterface):
"""Adapter for ZSI.Utility.DOM
"""
def __init__(self, node=None):
"""Reset all instance variables.
element -- DOM document, node, or None
"""
if hasattr(node, 'documentElement'):
self.__node = node.documentElement
else:
self.__node = node
self.__attributes = None
def getNode(self):
return self.__node
def hasattr(self, attr, ns=None):
"""attr -- attribute
ns -- optional namespace, None means unprefixed attribute.
"""
if not self.__attributes:
self.setAttributeDictionary()
if ns:
return self.__attributes.get(ns,{}).has_key(attr)
return self.__attributes.has_key(attr)
def getContentList(self, *contents):
nodes = []
ELEMENT_NODE = self.__node.ELEMENT_NODE
for child in DOM.getElements(self.__node, None):
if child.nodeType == ELEMENT_NODE and\
SplitQName(child.tagName)[1] in contents:
nodes.append(child)
return map(self.__class__, nodes)
def setAttributeDictionary(self):
self.__attributes = {}
for v in self.__node._attrs.values():
self.__attributes[v.nodeName] = v.nodeValue
def getAttributeDictionary(self):
if not self.__attributes:
self.setAttributeDictionary()
return self.__attributes
def getTagName(self):
return self.__node.tagName
def getParentNode(self):
if self.__node.parentNode.nodeType == self.__node.ELEMENT_NODE:
return DOMAdapter(self.__node.parentNode)
return None
def getNamespace(self, prefix):
"""prefix -- deference namespace prefix in node's context.
Ascends parent nodes until found.
"""
namespace = None
if prefix == 'xmlns':
namespace = DOM.findDefaultNS(prefix, self.__node)
else:
try:
namespace = DOM.findNamespaceURI(prefix, self.__node)
except DOMException, ex:
if prefix != 'xml':
raise SchemaError, '%s namespace not declared for %s'\
%(prefix, self.__node._get_tagName())
namespace = XMLNS.XML
return namespace
def loadDocument(self, file):
self.__node = DOM.loadDocument(file)
if hasattr(self.__node, 'documentElement'):
self.__node = self.__node.documentElement
def loadFromURL(self, url):
self.__node = DOM.loadFromURL(url)
if hasattr(self.__node, 'documentElement'):
self.__node = self.__node.documentElement
class XMLBase:
""" These class variables are for string indentation.
"""
tag = None
__indent = 0
__rlock = RLock()
def __str__(self):
XMLBase.__rlock.acquire()
XMLBase.__indent += 1
tmp = "<" + str(self.__class__) + '>\n'
for k,v in self.__dict__.items():
tmp += "%s* %s = %s\n" %(XMLBase.__indent*' ', k, v)
XMLBase.__indent -= 1
XMLBase.__rlock.release()
return tmp
"""Marker Interface: can determine something about an instances properties by using
the provided convenience functions.
"""
class DefinitionMarker:
"""marker for definitions
"""
pass
class DeclarationMarker:
"""marker for declarations
"""
pass
class AttributeMarker:
"""marker for attributes
"""
pass
class AttributeGroupMarker:
"""marker for attribute groups
"""
pass
class WildCardMarker:
"""marker for wildcards
"""
pass
class ElementMarker:
"""marker for wildcards
"""
pass
class ReferenceMarker:
"""marker for references
"""
pass
class ModelGroupMarker:
"""marker for model groups
"""
pass
class AllMarker(ModelGroupMarker):
"""marker for all model group
"""
pass
class ChoiceMarker(ModelGroupMarker):
"""marker for choice model group
"""
pass
class SequenceMarker(ModelGroupMarker):
"""marker for sequence model group
"""
pass
class ExtensionMarker:
"""marker for extensions
"""
pass
class RestrictionMarker:
"""marker for restrictions
"""
facets = ['enumeration', 'length', 'maxExclusive', 'maxInclusive',\
'maxLength', 'minExclusive', 'minInclusive', 'minLength',\
'pattern', 'fractionDigits', 'totalDigits', 'whiteSpace']
class SimpleMarker:
"""marker for simple type information
"""
pass
class ListMarker:
"""marker for simple type list
"""
pass
class UnionMarker:
"""marker for simple type Union
"""
pass
class ComplexMarker:
"""marker for complex type information
"""
pass
class LocalMarker:
"""marker for complex type information
"""
pass
class MarkerInterface:
def isDefinition(self):
return isinstance(self, DefinitionMarker)
def isDeclaration(self):
return isinstance(self, DeclarationMarker)
def isAttribute(self):
return isinstance(self, AttributeMarker)
def isAttributeGroup(self):
return isinstance(self, AttributeGroupMarker)
def isElement(self):
return isinstance(self, ElementMarker)
def isReference(self):
return isinstance(self, ReferenceMarker)
def isWildCard(self):
return isinstance(self, WildCardMarker)
def isModelGroup(self):
return isinstance(self, ModelGroupMarker)
def isAll(self):
return isinstance(self, AllMarker)
def isChoice(self):
return isinstance(self, ChoiceMarker)
def isSequence(self):
return isinstance(self, SequenceMarker)
def isExtension(self):
return isinstance(self, ExtensionMarker)
def isRestriction(self):
return isinstance(self, RestrictionMarker)
def isSimple(self):
return isinstance(self, SimpleMarker)
def isComplex(self):
return isinstance(self, ComplexMarker)
def isLocal(self):
return isinstance(self, LocalMarker)
def isList(self):
return isinstance(self, ListMarker)
def isUnion(self):
return isinstance(self, UnionMarker)
##########################################################
# Schema Components
#########################################################
class XMLSchemaComponent(XMLBase, MarkerInterface):
"""
class variables:
required -- list of required attributes
attributes -- dict of default attribute values, including None.
Value can be a function for runtime dependencies.
contents -- dict of namespace keyed content lists.
'xsd' content of xsd namespace.
xmlns_key -- key for declared xmlns namespace.
xmlns -- xmlns is special prefix for namespace dictionary
xml -- special xml prefix for xml namespace.
"""
required = []
attributes = {}
contents = {}
xmlns_key = ''
xmlns = 'xmlns'
xml = 'xml'
def __init__(self, parent=None):
"""parent -- parent instance
instance variables:
attributes -- dictionary of node's attributes
"""
self.attributes = None
self._parent = parent
if self._parent:
self._parent = weakref.ref(parent)
if not self.__class__ == XMLSchemaComponent\
and not (type(self.__class__.required) == type(XMLSchemaComponent.required)\
and type(self.__class__.attributes) == type(XMLSchemaComponent.attributes)\
and type(self.__class__.contents) == type(XMLSchemaComponent.contents)):
raise RuntimeError, 'Bad type for a class variable in %s' %self.__class__
def getItemTrace(self):
"""Returns a node trace up to the <schema> item.
"""
item, path, name, ref = self, [], 'name', 'ref'
while not isinstance(item,XMLSchema) and not isinstance(item,WSDLToolsAdapter):
attr = item.getAttribute(name)
if attr is None:
attr = item.getAttribute(ref)
if attr is None: path.append('<%s>' %(item.tag))
else: path.append('<%s ref="%s">' %(item.tag, attr))
else:
path.append('<%s name="%s">' %(item.tag,attr))
item = item._parent()
try:
tns = item.getTargetNamespace()
except:
tns = ''
path.append('<%s targetNamespace="%s">' %(item.tag, tns))
path.reverse()
return ''.join(path)
def getTargetNamespace(self):
"""return targetNamespace
"""
parent = self
targetNamespace = 'targetNamespace'
tns = self.attributes.get(targetNamespace)
while not tns:
parent = parent._parent()
tns = parent.attributes.get(targetNamespace)
return tns
def getAttributeDeclaration(self, attribute):
"""attribute -- attribute with a QName value (eg. type).
collection -- check types collection in parent Schema instance
"""
return self.getQNameAttribute(ATTRIBUTES, attribute)
def getAttributeGroup(self, attribute):
"""attribute -- attribute with a QName value (eg. type).
collection -- check types collection in parent Schema instance
"""
return self.getQNameAttribute(ATTRIBUTE_GROUPS, attribute)
def getTypeDefinition(self, attribute):
"""attribute -- attribute with a QName value (eg. type).
collection -- check types collection in parent Schema instance
"""
return self.getQNameAttribute(TYPES, attribute)
def getElementDeclaration(self, attribute):
"""attribute -- attribute with a QName value (eg. element).
collection -- check elements collection in parent Schema instance.
"""
return self.getQNameAttribute(ELEMENTS, attribute)
def getModelGroup(self, attribute):
"""attribute -- attribute with a QName value (eg. ref).
collection -- check model_group collection in parent Schema instance.
"""
return self.getQNameAttribute(MODEL_GROUPS, attribute)
def getQNameAttribute(self, collection, attribute):
"""returns object instance representing QName --> (namespace,name),
or if does not exist return None.
attribute -- an information item attribute, with a QName value.
collection -- collection in parent Schema instance to search.
"""
obj = None
tdc = self.getAttributeQName(attribute)
if tdc:
obj = self.getSchemaItem(collection, tdc.getTargetNamespace(), tdc.getName())
return obj
def getSchemaItem(self, collection, namespace, name):
"""returns object instance representing namespace, name,
or if does not exist return None.
namespace -- namespace item defined in.
name -- name of item.
collection -- collection in parent Schema instance to search.
"""
parent = GetSchema(self)
if parent.targetNamespace == namespace:
try:
obj = getattr(parent, collection)[name]
except KeyError, ex:
raise KeyError, 'targetNamespace(%s) collection(%s) has no item(%s)'\
%(namespace, collection, name)
return obj
if not parent.imports.has_key(namespace):
return None
# Lazy Eval
schema = parent.imports[namespace]
if not isinstance(schema, XMLSchema):
schema = schema.getSchema()
if schema is not None:
parent.imports[namespace] = schema
if schema is None:
raise SchemaError, 'no schema instance for imported namespace (%s).'\
%(namespace)
if not isinstance(schema, XMLSchema):
raise TypeError, 'expecting XMLSchema instance not "%r"' %schema
try:
obj = getattr(schema, collection)[name]
except KeyError, ex:
raise KeyError, 'targetNamespace(%s) collection(%s) has no item(%s)'\
%(namespace, collection, name)
return obj
def getXMLNS(self, prefix=None):
"""deference prefix or by default xmlns, returns namespace.
"""
if prefix == XMLSchemaComponent.xml:
return XMLNS.XML
parent = self
ns = self.attributes[XMLSchemaComponent.xmlns].get(prefix or\
XMLSchemaComponent.xmlns_key)
while not ns:
parent = parent._parent()
ns = parent.attributes[XMLSchemaComponent.xmlns].get(prefix or\
XMLSchemaComponent.xmlns_key)
if not ns and isinstance(parent, WSDLToolsAdapter):
if prefix is None:
return ''
raise SchemaError, 'unknown prefix %s' %prefix
return ns
def getAttribute(self, attribute):
"""return requested attribute value or None
"""
if type(attribute) in (list, tuple):
if len(attribute) != 2:
raise LookupError, 'To access attributes must use name or (namespace,name)'
return self.attributes.get(attribute[0]).get(attribute[1])
return self.attributes.get(attribute)
def getAttributeQName(self, attribute):
"""return requested attribute value as (namespace,name) or None
"""
qname = self.getAttribute(attribute)
if isinstance(qname, TypeDescriptionComponent) is True:
return qname
if qname is None:
return None
prefix,ncname = SplitQName(qname)
namespace = self.getXMLNS(prefix)
return TypeDescriptionComponent((namespace,ncname))
def getAttributeName(self):
"""return attribute name or None
"""
return self.getAttribute('name')
def setAttributes(self, node):
"""Sets up attribute dictionary, checks for required attributes and
sets default attribute values. attr is for default attribute values
determined at runtime.
structure of attributes dictionary
['xmlns'][xmlns_key] -- xmlns namespace
['xmlns'][prefix] -- declared namespace prefix
[namespace][prefix] -- attributes declared in a namespace
[attribute] -- attributes w/o prefix, default namespaces do
not directly apply to attributes, ie Name can't collide
with QName.
"""
self.attributes = {XMLSchemaComponent.xmlns:{}}
for k,v in node.getAttributeDictionary().items():
prefix,value = SplitQName(k)
if value == XMLSchemaComponent.xmlns:
self.attributes[value][prefix or XMLSchemaComponent.xmlns_key] = v
elif prefix:
ns = node.getNamespace(prefix)
if not ns:
raise SchemaError, 'no namespace for attribute prefix %s'\
%prefix
if not self.attributes.has_key(ns):
self.attributes[ns] = {}
elif self.attributes[ns].has_key(value):
raise SchemaError, 'attribute %s declared multiple times in %s'\
%(value, ns)
self.attributes[ns][value] = v
elif not self.attributes.has_key(value):
self.attributes[value] = v
else:
raise SchemaError, 'attribute %s declared multiple times' %value
if not isinstance(self, WSDLToolsAdapter):
self.__checkAttributes()
self.__setAttributeDefaults()
#set QNames
for k in ['type', 'element', 'base', 'ref', 'substitutionGroup', 'itemType']:
if self.attributes.has_key(k):
prefix, value = SplitQName(self.attributes.get(k))
self.attributes[k] = \
TypeDescriptionComponent((self.getXMLNS(prefix), value))
#Union, memberTypes is a whitespace separated list of QNames
for k in ['memberTypes']:
if self.attributes.has_key(k):
qnames = self.attributes[k]
self.attributes[k] = []
for qname in qnames.split():
prefix, value = SplitQName(qname)
self.attributes['memberTypes'].append(\
TypeDescriptionComponent(\
(self.getXMLNS(prefix), value)))
def getContents(self, node):
"""retrieve xsd contents
"""
return node.getContentList(*self.__class__.contents['xsd'])
def __setAttributeDefaults(self):
"""Looks for default values for unset attributes. If
class variable representing attribute is None, then
it must be defined as an instance variable.
"""
for k,v in self.__class__.attributes.items():
if v is not None and self.attributes.has_key(k) is False:
if isinstance(v, types.FunctionType):
self.attributes[k] = v(self)
else:
self.attributes[k] = v
def __checkAttributes(self):
"""Checks that required attributes have been defined,
attributes w/default cannot be required. Checks
all defined attributes are legal, attribute
references are not subject to this test.
"""
for a in self.__class__.required:
if not self.attributes.has_key(a):
raise SchemaError,\
'class instance %s, missing required attribute %s'\
%(self.__class__, a)
for a,v in self.attributes.items():
# attribute #other, ie. not in empty namespace
if type(v) is dict:
continue
# predefined prefixes xmlns, xml
if a in (XMLSchemaComponent.xmlns, XMLNS.XML):
continue
if (a not in self.__class__.attributes.keys()) and not\
(self.isAttribute() and self.isReference()):
raise SchemaError, '%s, unknown attribute(%s,%s)' \
%(self.getItemTrace(), a, self.attributes[a])
class WSDLToolsAdapter(XMLSchemaComponent):
"""WSDL Adapter to grab the attributes from the wsdl document node.
"""
attributes = {'name':None, 'targetNamespace':None}
tag = 'definitions'
def __init__(self, wsdl):
XMLSchemaComponent.__init__(self, parent=wsdl)
self.setAttributes(DOMAdapter(wsdl.document))
def getImportSchemas(self):
"""returns WSDLTools.WSDL types Collection
"""
return self._parent().types
class Notation(XMLSchemaComponent):
"""<notation>
parent:
schema
attributes:
id -- ID
name -- NCName, Required
public -- token, Required
system -- anyURI
contents:
annotation?
"""
required = ['name', 'public']
attributes = {'id':None, 'name':None, 'public':None, 'system':None}
contents = {'xsd':('annotation')}
tag = 'notation'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
for i in contents:
component = SplitQName(i.getTagName())[1]
if component == 'annotation' and not self.annotation:
self.annotation = Annotation(self)
self.annotation.fromDom(i)
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
class Annotation(XMLSchemaComponent):
"""<annotation>
parent:
all,any,anyAttribute,attribute,attributeGroup,choice,complexContent,
complexType,element,extension,field,group,import,include,key,keyref,
list,notation,redefine,restriction,schema,selector,simpleContent,
simpleType,union,unique
attributes:
id -- ID
contents:
(documentation | appinfo)*
"""
attributes = {'id':None}
contents = {'xsd':('documentation', 'appinfo')}
tag = 'annotation'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.content = None
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
content = []
for i in contents:
component = SplitQName(i.getTagName())[1]
if component == 'documentation':
#print_debug('class %s, documentation skipped' %self.__class__, 5)
continue
elif component == 'appinfo':
#print_debug('class %s, appinfo skipped' %self.__class__, 5)
continue
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
self.content = tuple(content)
class Documentation(XMLSchemaComponent):
"""<documentation>
parent:
annotation
attributes:
source, anyURI
xml:lang, language
contents:
mixed, any
"""
attributes = {'source':None, 'xml:lang':None}
contents = {'xsd':('mixed', 'any')}
tag = 'documentation'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.content = None
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
content = []
for i in contents:
component = SplitQName(i.getTagName())[1]
if component == 'mixed':
#print_debug('class %s, mixed skipped' %self.__class__, 5)
continue
elif component == 'any':
#print_debug('class %s, any skipped' %self.__class__, 5)
continue
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
self.content = tuple(content)
class Appinfo(XMLSchemaComponent):
"""<appinfo>
parent:
annotation
attributes:
source, anyURI
contents:
mixed, any
"""
attributes = {'source':None, 'anyURI':None}
contents = {'xsd':('mixed', 'any')}
tag = 'appinfo'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.content = None
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
content = []
for i in contents:
component = SplitQName(i.getTagName())[1]
if component == 'mixed':
#print_debug('class %s, mixed skipped' %self.__class__, 5)
continue
elif component == 'any':
#print_debug('class %s, any skipped' %self.__class__, 5)
continue
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
self.content = tuple(content)
class XMLSchemaFake:
# This is temporary, for the benefit of WSDL until the real thing works.
def __init__(self, element):
self.targetNamespace = DOM.getAttr(element, 'targetNamespace')
self.element = element
class XMLSchema(XMLSchemaComponent):
"""A schema is a collection of schema components derived from one
or more schema documents, that is, one or more <schema> element
information items. It represents the abstract notion of a schema
rather than a single schema document (or other representation).
<schema>
parent:
ROOT
attributes:
id -- ID
version -- token
xml:lang -- language
targetNamespace -- anyURI
attributeFormDefault -- 'qualified' | 'unqualified', 'unqualified'
elementFormDefault -- 'qualified' | 'unqualified', 'unqualified'
blockDefault -- '#all' | list of
('substitution | 'extension' | 'restriction')
finalDefault -- '#all' | list of
('extension' | 'restriction' | 'list' | 'union')
contents:
((include | import | redefine | annotation)*,
(attribute, attributeGroup, complexType, element, group,
notation, simpleType)*, annotation*)*
attributes -- schema attributes
imports -- import statements
includes -- include statements
redefines --
types -- global simpleType, complexType definitions
elements -- global element declarations
attr_decl -- global attribute declarations
attr_groups -- attribute Groups
model_groups -- model Groups
notations -- global notations
"""
attributes = {'id':None,
'version':None,
'xml:lang':None,
'targetNamespace':None,
'attributeFormDefault':'unqualified',
'elementFormDefault':'unqualified',
'blockDefault':None,
'finalDefault':None}
contents = {'xsd':('include', 'import', 'redefine', 'annotation',
'attribute', 'attributeGroup', 'complexType',
'element', 'group', 'notation', 'simpleType',
'annotation')}
empty_namespace = ''
tag = 'schema'
def __init__(self, parent=None):
"""parent --
instance variables:
targetNamespace -- schema's declared targetNamespace, or empty string.
_imported_schemas -- namespace keyed dict of schema dependencies, if
a schema is provided instance will not resolve import statement.
_included_schemas -- schemaLocation keyed dict of component schemas,
if schema is provided instance will not resolve include statement.
_base_url -- needed for relative URLs support, only works with URLs
relative to initial document.
includes -- collection of include statements
imports -- collection of import statements
elements -- collection of global element declarations
types -- collection of global type definitions
attr_decl -- collection of global attribute declarations
attr_groups -- collection of global attribute group definitions
model_groups -- collection of model group definitions
notations -- collection of notations
"""
self.__node = None
self.targetNamespace = None
XMLSchemaComponent.__init__(self, parent)
f = lambda k: k.attributes['name']
ns = lambda k: k.attributes['namespace']
sl = lambda k: k.attributes['schemaLocation']
self.includes = Collection(self, key=sl)
self.imports = Collection(self, key=ns)
self.elements = Collection(self, key=f)
self.types = Collection(self, key=f)
self.attr_decl = Collection(self, key=f)
self.attr_groups = Collection(self, key=f)
self.model_groups = Collection(self, key=f)
self.notations = Collection(self, key=f)
self._imported_schemas = {}
self._included_schemas = {}
self._base_url = None
def getNode(self):
"""
Interacting with the underlying DOM tree.
"""
return self.__node
def addImportSchema(self, schema):
"""for resolving import statements in Schema instance
schema -- schema instance
_imported_schemas
"""
if not isinstance(schema, XMLSchema):
raise TypeError, 'expecting a Schema instance'
if schema.targetNamespace != self.targetNamespace:
self._imported_schemas[schema.targetNamespace] = schema
else:
raise SchemaError, 'import schema bad targetNamespace'
def addIncludeSchema(self, schemaLocation, schema):
"""for resolving include statements in Schema instance
schemaLocation -- schema location
schema -- schema instance
_included_schemas
"""
if not isinstance(schema, XMLSchema):
raise TypeError, 'expecting a Schema instance'
if not schema.targetNamespace or\
schema.targetNamespace == self.targetNamespace:
self._included_schemas[schemaLocation] = schema
else:
raise SchemaError, 'include schema bad targetNamespace'
def setImportSchemas(self, schema_dict):
"""set the import schema dictionary, which is used to
reference depedent schemas.
"""
self._imported_schemas = schema_dict
def getImportSchemas(self):
"""get the import schema dictionary, which is used to
reference depedent schemas.
"""
return self._imported_schemas
def getSchemaNamespacesToImport(self):
"""returns tuple of namespaces the schema instance has declared
itself to be depedent upon.
"""
return tuple(self.includes.keys())
def setIncludeSchemas(self, schema_dict):
"""set the include schema dictionary, which is keyed with
schemaLocation (uri).
This is a means of providing
schemas to the current schema for content inclusion.
"""
self._included_schemas = schema_dict
def getIncludeSchemas(self):
"""get the include schema dictionary, which is keyed with
schemaLocation (uri).
"""
return self._included_schemas
def getBaseUrl(self):
"""get base url, used for normalizing all relative uri's
"""
return self._base_url
def setBaseUrl(self, url):
"""set base url, used for normalizing all relative uri's
"""
self._base_url = url
def getElementFormDefault(self):
"""return elementFormDefault attribute
"""
return self.attributes.get('elementFormDefault')
def isElementFormDefaultQualified(self):
return self.attributes.get('elementFormDefault') == 'qualified'
def getAttributeFormDefault(self):
"""return attributeFormDefault attribute
"""
return self.attributes.get('attributeFormDefault')
def getBlockDefault(self):
"""return blockDefault attribute
"""
return self.attributes.get('blockDefault')
def getFinalDefault(self):
"""return finalDefault attribute
"""
return self.attributes.get('finalDefault')
def load(self, node, location=None):
self.__node = node
pnode = node.getParentNode()
if pnode:
pname = SplitQName(pnode.getTagName())[1]
if pname == 'types':
attributes = {}
self.setAttributes(pnode)
attributes.update(self.attributes)
self.setAttributes(node)
for k,v in attributes['xmlns'].items():
if not self.attributes['xmlns'].has_key(k):
self.attributes['xmlns'][k] = v
else:
self.setAttributes(node)
else:
self.setAttributes(node)
self.targetNamespace = self.getTargetNamespace()
for childNode in self.getContents(node):
component = SplitQName(childNode.getTagName())[1]
if component == 'include':
tp = self.__class__.Include(self)
tp.fromDom(childNode)
sl = tp.attributes['schemaLocation']
schema = tp.getSchema()
if not self.getIncludeSchemas().has_key(sl):
self.addIncludeSchema(sl, schema)
self.includes[sl] = tp
pn = childNode.getParentNode().getNode()
pn.removeChild(childNode.getNode())
for child in schema.getNode().getNode().childNodes:
pn.appendChild(child.cloneNode(1))
for collection in ['imports','elements','types',
'attr_decl','attr_groups','model_groups',
'notations']:
for k,v in getattr(schema,collection).items():
if not getattr(self,collection).has_key(k):
v._parent = weakref.ref(self)
getattr(self,collection)[k] = v
else:
warnings.warn("Not keeping schema component.")
elif component == 'import':
slocd = SchemaReader.namespaceToSchema
tp = self.__class__.Import(self)
tp.fromDom(childNode)
import_ns = tp.getAttribute('namespace') or\
self.__class__.empty_namespace
schema = slocd.get(import_ns)
if schema is None:
schema = XMLSchema()
slocd[import_ns] = schema
try:
tp.loadSchema(schema)
except SchemaError:
# Dependency declaration, hopefully implementation
# is aware of this namespace (eg. SOAP,WSDL,?)
#warnings.warn(\
# '<import namespace="%s" schemaLocation=?>, %s'\
# %(import_ns, 'failed to load schema instance')
#)
del slocd[import_ns]
class LazyEval(str):
'''Lazy evaluation of import, replace entry in self.imports.'''
def getSchema(namespace):
schema = slocd.get(namespace)
if schema is None:
parent = self._parent()
wstypes = parent
if isinstance(parent, WSDLToolsAdapter):
wstypes = parent.getImportSchemas()
schema = wstypes.get(namespace)
if isinstance(schema, XMLSchema):
self.imports[namespace] = schema
return schema
return None
self.imports[import_ns] = LazyEval(import_ns)
continue
else:
tp._schema = schema
if self.getImportSchemas().has_key(import_ns):
warnings.warn(\
'Detected multiple imports of the namespace "%s" '\
%import_ns)
self.addImportSchema(schema)
# spec says can have multiple imports of same namespace
# but purpose of import is just dependency declaration.
self.imports[import_ns] = tp
elif component == 'redefine':
warnings.warn('redefine is ignored')
elif component == 'annotation':
warnings.warn('annotation is ignored')
elif component == 'attribute':
tp = AttributeDeclaration(self)
tp.fromDom(childNode)
self.attr_decl[tp.getAttribute('name')] = tp
elif component == 'attributeGroup':
tp = AttributeGroupDefinition(self)
tp.fromDom(childNode)
self.attr_groups[tp.getAttribute('name')] = tp
elif component == 'element':
tp = ElementDeclaration(self)
tp.fromDom(childNode)
self.elements[tp.getAttribute('name')] = tp
elif component == 'group':
tp = ModelGroupDefinition(self)
tp.fromDom(childNode)
self.model_groups[tp.getAttribute('name')] = tp
elif component == 'notation':
tp = Notation(self)
tp.fromDom(childNode)
self.notations[tp.getAttribute('name')] = tp
elif component == 'complexType':
tp = ComplexType(self)
tp.fromDom(childNode)
self.types[tp.getAttribute('name')] = tp
elif component == 'simpleType':
tp = SimpleType(self)
tp.fromDom(childNode)
self.types[tp.getAttribute('name')] = tp
else:
break
class Import(XMLSchemaComponent):
"""<import>
parent:
schema
attributes:
id -- ID
namespace -- anyURI
schemaLocation -- anyURI
contents:
annotation?
"""
attributes = {'id':None,
'namespace':None,
'schemaLocation':None}
contents = {'xsd':['annotation']}
tag = 'import'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
self._schema = None
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
if self.attributes['namespace'] == self.getTargetNamespace():
raise SchemaError, 'namespace of schema and import match'
for i in contents:
component = SplitQName(i.getTagName())[1]
if component == 'annotation' and not self.annotation:
self.annotation = Annotation(self)
self.annotation.fromDom(i)
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
def getSchema(self):
"""if schema is not defined, first look for a Schema class instance
in parent Schema. Else if not defined resolve schemaLocation
and create a new Schema class instance, and keep a hard reference.
"""
if not self._schema:
ns = self.attributes['namespace']
schema = self._parent().getImportSchemas().get(ns)
if not schema and self._parent()._parent:
schema = self._parent()._parent().getImportSchemas().get(ns)
if not schema:
url = self.attributes.get('schemaLocation')
if not url:
raise SchemaError, 'namespace(%s) is unknown' %ns
base_url = self._parent().getBaseUrl()
reader = SchemaReader(base_url=base_url)
reader._imports = self._parent().getImportSchemas()
reader._includes = self._parent().getIncludeSchemas()
self._schema = reader.loadFromURL(url)
return self._schema or schema
def loadSchema(self, schema):
"""
"""
base_url = self._parent().getBaseUrl()
reader = SchemaReader(base_url=base_url)
reader._imports = self._parent().getImportSchemas()
reader._includes = self._parent().getIncludeSchemas()
self._schema = schema
if not self.attributes.has_key('schemaLocation'):
raise SchemaError, 'no schemaLocation'
reader.loadFromURL(self.attributes.get('schemaLocation'), schema)
class Include(XMLSchemaComponent):
"""<include schemaLocation>
parent:
schema
attributes:
id -- ID
schemaLocation -- anyURI, required
contents:
annotation?
"""
required = ['schemaLocation']
attributes = {'id':None,
'schemaLocation':None}
contents = {'xsd':['annotation']}
tag = 'include'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
self._schema = None
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
for i in contents:
component = SplitQName(i.getTagName())[1]
if component == 'annotation' and not self.annotation:
self.annotation = Annotation(self)
self.annotation.fromDom(i)
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
def getSchema(self):
"""if schema is not defined, first look for a Schema class instance
in parent Schema. Else if not defined resolve schemaLocation
and create a new Schema class instance.
"""
if not self._schema:
schema = self._parent()
self._schema = schema.getIncludeSchemas().get(\
self.attributes['schemaLocation']
)
if not self._schema:
url = self.attributes['schemaLocation']
reader = SchemaReader(base_url=schema.getBaseUrl())
reader._imports = schema.getImportSchemas()
reader._includes = schema.getIncludeSchemas()
# create schema before loading so chameleon include
# will evalute targetNamespace correctly.
self._schema = XMLSchema(schema)
reader.loadFromURL(url, self._schema)
return self._schema
class AttributeDeclaration(XMLSchemaComponent,\
AttributeMarker,\
DeclarationMarker):
"""<attribute name>
parent:
schema
attributes:
id -- ID
name -- NCName, required
type -- QName
default -- string
fixed -- string
contents:
annotation?, simpleType?
"""
required = ['name']
attributes = {'id':None,
'name':None,
'type':None,
'default':None,
'fixed':None}
contents = {'xsd':['annotation','simpleType']}
tag = 'attribute'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
self.content = None
def fromDom(self, node):
""" No list or union support
"""
self.setAttributes(node)
contents = self.getContents(node)
for i in contents:
component = SplitQName(i.getTagName())[1]
if component == 'annotation' and not self.annotation:
self.annotation = Annotation(self)
self.annotation.fromDom(i)
elif component == 'simpleType':
self.content = AnonymousSimpleType(self)
self.content.fromDom(i)
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
class LocalAttributeDeclaration(AttributeDeclaration,\
AttributeMarker,\
LocalMarker,\
DeclarationMarker):
"""<attribute name>
parent:
complexType, restriction, extension, attributeGroup
attributes:
id -- ID
name -- NCName, required
type -- QName
form -- ('qualified' | 'unqualified'), schema.attributeFormDefault
use -- ('optional' | 'prohibited' | 'required'), optional
default -- string
fixed -- string
contents:
annotation?, simpleType?
"""
required = ['name']
attributes = {'id':None,
'name':None,
'type':None,
'form':lambda self: GetSchema(self).getAttributeFormDefault(),
'use':'optional',
'default':None,
'fixed':None}
contents = {'xsd':['annotation','simpleType']}
def __init__(self, parent):
AttributeDeclaration.__init__(self, parent)
self.annotation = None
self.content = None
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
for i in contents:
component = SplitQName(i.getTagName())[1]
if component == 'annotation' and not self.annotation:
self.annotation = Annotation(self)
self.annotation.fromDom(i)
elif component == 'simpleType':
self.content = AnonymousSimpleType(self)
self.content.fromDom(i)
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
class AttributeWildCard(XMLSchemaComponent,\
AttributeMarker,\
DeclarationMarker,\
WildCardMarker):
"""<anyAttribute>
parents:
complexType, restriction, extension, attributeGroup
attributes:
id -- ID
namespace -- '##any' | '##other' |
(anyURI* | '##targetNamespace' | '##local'), ##any
processContents -- 'lax' | 'skip' | 'strict', strict
contents:
annotation?
"""
attributes = {'id':None,
'namespace':'##any',
'processContents':'strict'}
contents = {'xsd':['annotation']}
tag = 'anyAttribute'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
for i in contents:
component = SplitQName(i.getTagName())[1]
if component == 'annotation' and not self.annotation:
self.annotation = Annotation(self)
self.annotation.fromDom(i)
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
class AttributeReference(XMLSchemaComponent,\
AttributeMarker,\
ReferenceMarker):
"""<attribute ref>
parents:
complexType, restriction, extension, attributeGroup
attributes:
id -- ID
ref -- QName, required
use -- ('optional' | 'prohibited' | 'required'), optional
default -- string
fixed -- string
contents:
annotation?
"""
required = ['ref']
attributes = {'id':None,
'ref':None,
'use':'optional',
'default':None,
'fixed':None}
contents = {'xsd':['annotation']}
tag = 'attribute'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
def getAttributeDeclaration(self, attribute='ref'):
return XMLSchemaComponent.getAttributeDeclaration(self, attribute)
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
for i in contents:
component = SplitQName(i.getTagName())[1]
if component == 'annotation' and not self.annotation:
self.annotation = Annotation(self)
self.annotation.fromDom(i)
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
class AttributeGroupDefinition(XMLSchemaComponent,\
AttributeGroupMarker,\
DefinitionMarker):
"""<attributeGroup name>
parents:
schema, redefine
attributes:
id -- ID
name -- NCName, required
contents:
annotation?, (attribute | attributeGroup)*, anyAttribute?
"""
required = ['name']
attributes = {'id':None,
'name':None}
contents = {'xsd':['annotation', 'attribute', 'attributeGroup', 'anyAttribute']}
tag = 'attributeGroup'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
self.attr_content = None
def getAttributeContent(self):
return self.attr_content
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
content = []
for indx in range(len(contents)):
component = SplitQName(contents[indx].getTagName())[1]
if (component == 'annotation') and (not indx):
self.annotation = Annotation(self)
self.annotation.fromDom(contents[indx])
elif component == 'attribute':
if contents[indx].hasattr('name'):
content.append(LocalAttributeDeclaration(self))
elif contents[indx].hasattr('ref'):
content.append(AttributeReference(self))
else:
raise SchemaError, 'Unknown attribute type'
content[-1].fromDom(contents[indx])
elif component == 'attributeGroup':
content.append(AttributeGroupReference(self))
content[-1].fromDom(contents[indx])
elif component == 'anyAttribute':
if len(contents) != indx+1:
raise SchemaError, 'anyAttribute is out of order in %s' %self.getItemTrace()
content.append(AttributeWildCard(self))
content[-1].fromDom(contents[indx])
else:
raise SchemaError, 'Unknown component (%s)' %(contents[indx].getTagName())
self.attr_content = tuple(content)
class AttributeGroupReference(XMLSchemaComponent,\
AttributeGroupMarker,\
ReferenceMarker):
"""<attributeGroup ref>
parents:
complexType, restriction, extension, attributeGroup
attributes:
id -- ID
ref -- QName, required
contents:
annotation?
"""
required = ['ref']
attributes = {'id':None,
'ref':None}
contents = {'xsd':['annotation']}
tag = 'attributeGroup'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
def getAttributeGroup(self, attribute='ref'):
"""attribute -- attribute with a QName value (eg. type).
collection -- check types collection in parent Schema instance
"""
return XMLSchemaComponent.getAttributeGroup(self, attribute)
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
for i in contents:
component = SplitQName(i.getTagName())[1]
if component == 'annotation' and not self.annotation:
self.annotation = Annotation(self)
self.annotation.fromDom(i)
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
######################################################
# Elements
#####################################################
class IdentityConstrants(XMLSchemaComponent):
"""Allow one to uniquely identify nodes in a document and ensure the
integrity of references between them.
attributes -- dictionary of attributes
selector -- XPath to selected nodes
fields -- list of XPath to key field
"""
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.selector = None
self.fields = None
self.annotation = None
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
fields = []
for i in contents:
component = SplitQName(i.getTagName())[1]
if component in self.__class__.contents['xsd']:
if component == 'annotation' and not self.annotation:
self.annotation = Annotation(self)
self.annotation.fromDom(i)
elif component == 'selector':
self.selector = self.Selector(self)
self.selector.fromDom(i)
continue
elif component == 'field':
fields.append(self.Field(self))
fields[-1].fromDom(i)
continue
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
self.fields = tuple(fields)
class Constraint(XMLSchemaComponent):
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
for i in contents:
component = SplitQName(i.getTagName())[1]
if component in self.__class__.contents['xsd']:
if component == 'annotation' and not self.annotation:
self.annotation = Annotation(self)
self.annotation.fromDom(i)
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
class Selector(Constraint):
"""<selector xpath>
parent:
unique, key, keyref
attributes:
id -- ID
xpath -- XPath subset, required
contents:
annotation?
"""
required = ['xpath']
attributes = {'id':None,
'xpath':None}
contents = {'xsd':['annotation']}
tag = 'selector'
class Field(Constraint):
"""<field xpath>
parent:
unique, key, keyref
attributes:
id -- ID
xpath -- XPath subset, required
contents:
annotation?
"""
required = ['xpath']
attributes = {'id':None,
'xpath':None}
contents = {'xsd':['annotation']}
tag = 'field'
class Unique(IdentityConstrants):
"""<unique name> Enforce fields are unique w/i a specified scope.
parent:
element
attributes:
id -- ID
name -- NCName, required
contents:
annotation?, selector, field+
"""
required = ['name']
attributes = {'id':None,
'name':None}
contents = {'xsd':['annotation', 'selector', 'field']}
tag = 'unique'
class Key(IdentityConstrants):
"""<key name> Enforce fields are unique w/i a specified scope, and all
field values are present w/i document. Fields cannot
be nillable.
parent:
element
attributes:
id -- ID
name -- NCName, required
contents:
annotation?, selector, field+
"""
required = ['name']
attributes = {'id':None,
'name':None}
contents = {'xsd':['annotation', 'selector', 'field']}
tag = 'key'
class KeyRef(IdentityConstrants):
"""<keyref name refer> Ensure a match between two sets of values in an
instance.
parent:
element
attributes:
id -- ID
name -- NCName, required
refer -- QName, required
contents:
annotation?, selector, field+
"""
required = ['name', 'refer']
attributes = {'id':None,
'name':None,
'refer':None}
contents = {'xsd':['annotation', 'selector', 'field']}
tag = 'keyref'
class ElementDeclaration(XMLSchemaComponent,\
ElementMarker,\
DeclarationMarker):
"""<element name>
parents:
schema
attributes:
id -- ID
name -- NCName, required
type -- QName
default -- string
fixed -- string
nillable -- boolean, false
abstract -- boolean, false
substitutionGroup -- QName
block -- ('#all' | ('substition' | 'extension' | 'restriction')*),
schema.blockDefault
final -- ('#all' | ('extension' | 'restriction')*),
schema.finalDefault
contents:
annotation?, (simpleType,complexType)?, (key | keyref | unique)*
"""
required = ['name']
attributes = {'id':None,
'name':None,
'type':None,
'default':None,
'fixed':None,
'nillable':0,
'abstract':0,
'substitutionGroup':None,
'block':lambda self: self._parent().getBlockDefault(),
'final':lambda self: self._parent().getFinalDefault()}
contents = {'xsd':['annotation', 'simpleType', 'complexType', 'key',\
'keyref', 'unique']}
tag = 'element'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
self.content = None
self.constraints = ()
def isQualified(self):
"""Global elements are always qualified.
"""
return True
def getAttribute(self, attribute):
"""return attribute.
If attribute is type and it's None, and no simple or complex content,
return the default type "xsd:anyType"
"""
value = XMLSchemaComponent.getAttribute(self, attribute)
if attribute != 'type' or value is not None:
return value
if self.content is not None:
return None
parent = self
while 1:
nsdict = parent.attributes[XMLSchemaComponent.xmlns]
for k,v in nsdict.items():
if v not in SCHEMA.XSD_LIST: continue
return TypeDescriptionComponent((v, 'anyType'))
if isinstance(parent, WSDLToolsAdapter)\
or not hasattr(parent, '_parent'):
break
parent = parent._parent()
raise SchemaError, 'failed to locate the XSD namespace'
def getElementDeclaration(self, attribute):
raise Warning, 'invalid operation for <%s>' %self.tag
def getTypeDefinition(self, attribute=None):
"""If attribute is None, "type" is assumed, return the corresponding
representation of the global type definition (TypeDefinition),
or the local definition if don't find "type". To maintain backwards
compat, if attribute is provided call base class method.
"""
if attribute:
return XMLSchemaComponent.getTypeDefinition(self, attribute)
gt = XMLSchemaComponent.getTypeDefinition(self, 'type')
if gt:
return gt
return self.content
def getConstraints(self):
return self._constraints
def setConstraints(self, constraints):
self._constraints = tuple(constraints)
constraints = property(getConstraints, setConstraints, None, "tuple of key, keyref, unique constraints")
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
constraints = []
for i in contents:
component = SplitQName(i.getTagName())[1]
if component in self.__class__.contents['xsd']:
if component == 'annotation' and not self.annotation:
self.annotation = Annotation(self)
self.annotation.fromDom(i)
elif component == 'simpleType' and not self.content:
self.content = AnonymousSimpleType(self)
self.content.fromDom(i)
elif component == 'complexType' and not self.content:
self.content = LocalComplexType(self)
self.content.fromDom(i)
elif component == 'key':
constraints.append(Key(self))
constraints[-1].fromDom(i)
elif component == 'keyref':
constraints.append(KeyRef(self))
constraints[-1].fromDom(i)
elif component == 'unique':
constraints.append(Unique(self))
constraints[-1].fromDom(i)
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
self.constraints = constraints
class LocalElementDeclaration(ElementDeclaration,\
LocalMarker):
"""<element>
parents:
all, choice, sequence
attributes:
id -- ID
name -- NCName, required
form -- ('qualified' | 'unqualified'), schema.elementFormDefault
type -- QName
minOccurs -- Whole Number, 1
maxOccurs -- (Whole Number | 'unbounded'), 1
default -- string
fixed -- string
nillable -- boolean, false
block -- ('#all' | ('extension' | 'restriction')*), schema.blockDefault
contents:
annotation?, (simpleType,complexType)?, (key | keyref | unique)*
"""
required = ['name']
attributes = {'id':None,
'name':None,
'form':lambda self: GetSchema(self).getElementFormDefault(),
'type':None,
'minOccurs':'1',
'maxOccurs':'1',
'default':None,
'fixed':None,
'nillable':0,
'abstract':0,
'block':lambda self: GetSchema(self).getBlockDefault()}
contents = {'xsd':['annotation', 'simpleType', 'complexType', 'key',\
'keyref', 'unique']}
def isQualified(self):
"""
Local elements can be qualified or unqualifed according
to the attribute form, or the elementFormDefault. By default
local elements are unqualified.
"""
form = self.getAttribute('form')
if form == 'qualified':
return True
if form == 'unqualified':
return False
raise SchemaError, 'Bad form (%s) for element: %s' %(form, self.getItemTrace())
class ElementReference(XMLSchemaComponent,\
ElementMarker,\
ReferenceMarker):
"""<element ref>
parents:
all, choice, sequence
attributes:
id -- ID
ref -- QName, required
minOccurs -- Whole Number, 1
maxOccurs -- (Whole Number | 'unbounded'), 1
contents:
annotation?
"""
required = ['ref']
attributes = {'id':None,
'ref':None,
'minOccurs':'1',
'maxOccurs':'1'}
contents = {'xsd':['annotation']}
tag = 'element'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
def getElementDeclaration(self, attribute=None):
"""If attribute is None, "ref" is assumed, return the corresponding
representation of the global element declaration (ElementDeclaration),
To maintain backwards compat, if attribute is provided call base class method.
"""
if attribute:
return XMLSchemaComponent.getElementDeclaration(self, attribute)
return XMLSchemaComponent.getElementDeclaration(self, 'ref')
def fromDom(self, node):
self.annotation = None
self.setAttributes(node)
for i in self.getContents(node):
component = SplitQName(i.getTagName())[1]
if component in self.__class__.contents['xsd']:
if component == 'annotation' and not self.annotation:
self.annotation = Annotation(self)
self.annotation.fromDom(i)
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
class ElementWildCard(LocalElementDeclaration, WildCardMarker):
"""<any>
parents:
choice, sequence
attributes:
id -- ID
minOccurs -- Whole Number, 1
maxOccurs -- (Whole Number | 'unbounded'), 1
namespace -- '##any' | '##other' |
(anyURI* | '##targetNamespace' | '##local'), ##any
processContents -- 'lax' | 'skip' | 'strict', strict
contents:
annotation?
"""
required = []
attributes = {'id':None,
'minOccurs':'1',
'maxOccurs':'1',
'namespace':'##any',
'processContents':'strict'}
contents = {'xsd':['annotation']}
tag = 'any'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
def isQualified(self):
"""
Global elements are always qualified, but if processContents
are not strict could have dynamically generated local elements.
"""
return GetSchema(self).isElementFormDefaultQualified()
def getAttribute(self, attribute):
"""return attribute.
"""
return XMLSchemaComponent.getAttribute(self, attribute)
def getTypeDefinition(self, attribute):
raise Warning, 'invalid operation for <%s>' % self.tag
def fromDom(self, node):
self.annotation = None
self.setAttributes(node)
for i in self.getContents(node):
component = SplitQName(i.getTagName())[1]
if component in self.__class__.contents['xsd']:
if component == 'annotation' and not self.annotation:
self.annotation = Annotation(self)
self.annotation.fromDom(i)
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
######################################################
# Model Groups
#####################################################
class Sequence(XMLSchemaComponent,\
SequenceMarker):
"""<sequence>
parents:
complexType, extension, restriction, group, choice, sequence
attributes:
id -- ID
minOccurs -- Whole Number, 1
maxOccurs -- (Whole Number | 'unbounded'), 1
contents:
annotation?, (element | group | choice | sequence | any)*
"""
attributes = {'id':None,
'minOccurs':'1',
'maxOccurs':'1'}
contents = {'xsd':['annotation', 'element', 'group', 'choice', 'sequence',\
'any']}
tag = 'sequence'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
self.content = None
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
content = []
for i in contents:
component = SplitQName(i.getTagName())[1]
if component in self.__class__.contents['xsd']:
if component == 'annotation' and not self.annotation:
self.annotation = Annotation(self)
self.annotation.fromDom(i)
continue
elif component == 'element':
if i.hasattr('ref'):
content.append(ElementReference(self))
else:
content.append(LocalElementDeclaration(self))
elif component == 'group':
content.append(ModelGroupReference(self))
elif component == 'choice':
content.append(Choice(self))
elif component == 'sequence':
content.append(Sequence(self))
elif component == 'any':
content.append(ElementWildCard(self))
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
content[-1].fromDom(i)
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
self.content = tuple(content)
class All(XMLSchemaComponent,\
AllMarker):
"""<all>
parents:
complexType, extension, restriction, group
attributes:
id -- ID
minOccurs -- '0' | '1', 1
maxOccurs -- '1', 1
contents:
annotation?, element*
"""
attributes = {'id':None,
'minOccurs':'1',
'maxOccurs':'1'}
contents = {'xsd':['annotation', 'element']}
tag = 'all'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
self.content = None
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
content = []
for i in contents:
component = SplitQName(i.getTagName())[1]
if component in self.__class__.contents['xsd']:
if component == 'annotation' and not self.annotation:
self.annotation = Annotation(self)
self.annotation.fromDom(i)
continue
elif component == 'element':
if i.hasattr('ref'):
content.append(ElementReference(self))
else:
content.append(LocalElementDeclaration(self))
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
content[-1].fromDom(i)
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
self.content = tuple(content)
class Choice(XMLSchemaComponent,\
ChoiceMarker):
"""<choice>
parents:
complexType, extension, restriction, group, choice, sequence
attributes:
id -- ID
minOccurs -- Whole Number, 1
maxOccurs -- (Whole Number | 'unbounded'), 1
contents:
annotation?, (element | group | choice | sequence | any)*
"""
attributes = {'id':None,
'minOccurs':'1',
'maxOccurs':'1'}
contents = {'xsd':['annotation', 'element', 'group', 'choice', 'sequence',\
'any']}
tag = 'choice'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
self.content = None
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
content = []
for i in contents:
component = SplitQName(i.getTagName())[1]
if component in self.__class__.contents['xsd']:
if component == 'annotation' and not self.annotation:
self.annotation = Annotation(self)
self.annotation.fromDom(i)
continue
elif component == 'element':
if i.hasattr('ref'):
content.append(ElementReference(self))
else:
content.append(LocalElementDeclaration(self))
elif component == 'group':
content.append(ModelGroupReference(self))
elif component == 'choice':
content.append(Choice(self))
elif component == 'sequence':
content.append(Sequence(self))
elif component == 'any':
content.append(ElementWildCard(self))
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
content[-1].fromDom(i)
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
self.content = tuple(content)
class ModelGroupDefinition(XMLSchemaComponent,\
ModelGroupMarker,\
DefinitionMarker):
"""<group name>
parents:
redefine, schema
attributes:
id -- ID
name -- NCName, required
contents:
annotation?, (all | choice | sequence)?
"""
required = ['name']
attributes = {'id':None,
'name':None}
contents = {'xsd':['annotation', 'all', 'choice', 'sequence']}
tag = 'group'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
self.content = None
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
for i in contents:
component = SplitQName(i.getTagName())[1]
if component in self.__class__.contents['xsd']:
if component == 'annotation' and not self.annotation:
self.annotation = Annotation(self)
self.annotation.fromDom(i)
continue
elif component == 'all' and not self.content:
self.content = All(self)
elif component == 'choice' and not self.content:
self.content = Choice(self)
elif component == 'sequence' and not self.content:
self.content = Sequence(self)
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
self.content.fromDom(i)
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
class ModelGroupReference(XMLSchemaComponent,\
ModelGroupMarker,\
ReferenceMarker):
"""<group ref>
parents:
choice, complexType, extension, restriction, sequence
attributes:
id -- ID
ref -- NCName, required
minOccurs -- Whole Number, 1
maxOccurs -- (Whole Number | 'unbounded'), 1
contents:
annotation?
"""
required = ['ref']
attributes = {'id':None,
'ref':None,
'minOccurs':'1',
'maxOccurs':'1'}
contents = {'xsd':['annotation']}
tag = 'group'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
def getModelGroupReference(self):
return self.getModelGroup('ref')
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
for i in contents:
component = SplitQName(i.getTagName())[1]
if component in self.__class__.contents['xsd']:
if component == 'annotation' and not self.annotation:
self.annotation = Annotation(self)
self.annotation.fromDom(i)
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
class ComplexType(XMLSchemaComponent,\
DefinitionMarker,\
ComplexMarker):
"""<complexType name>
parents:
redefine, schema
attributes:
id -- ID
name -- NCName, required
mixed -- boolean, false
abstract -- boolean, false
block -- ('#all' | ('extension' | 'restriction')*), schema.blockDefault
final -- ('#all' | ('extension' | 'restriction')*), schema.finalDefault
contents:
annotation?, (simpleContent | complexContent |
((group | all | choice | sequence)?, (attribute | attributeGroup)*, anyAttribute?))
"""
required = ['name']
attributes = {'id':None,
'name':None,
'mixed':0,
'abstract':0,
'block':lambda self: self._parent().getBlockDefault(),
'final':lambda self: self._parent().getFinalDefault()}
contents = {'xsd':['annotation', 'simpleContent', 'complexContent',\
'group', 'all', 'choice', 'sequence', 'attribute', 'attributeGroup',\
'anyAttribute', 'any']}
tag = 'complexType'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
self.content = None
self.attr_content = None
def isMixed(self):
m = self.getAttribute('mixed')
if m == 0 or m == False:
return False
if isinstance(m, basestring) is True:
if m in ('false', '0'):
return False
if m in ('true', '1'):
return True
raise SchemaError, 'invalid value for attribute mixed(%s): %s'\
%(m, self.getItemTrace())
def getAttributeContent(self):
return self.attr_content
def getElementDeclaration(self, attribute):
raise Warning, 'invalid operation for <%s>' %self.tag
def getTypeDefinition(self, attribute):
raise Warning, 'invalid operation for <%s>' %self.tag
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
indx = 0
num = len(contents)
if not num:
return
component = SplitQName(contents[indx].getTagName())[1]
if component == 'annotation':
self.annotation = Annotation(self)
self.annotation.fromDom(contents[indx])
indx += 1
component = SplitQName(contents[indx].getTagName())[1]
self.content = None
if component == 'simpleContent':
self.content = self.__class__.SimpleContent(self)
self.content.fromDom(contents[indx])
elif component == 'complexContent':
self.content = self.__class__.ComplexContent(self)
self.content.fromDom(contents[indx])
else:
if component == 'all':
self.content = All(self)
elif component == 'choice':
self.content = Choice(self)
elif component == 'sequence':
self.content = Sequence(self)
elif component == 'group':
self.content = ModelGroupReference(self)
if self.content:
self.content.fromDom(contents[indx])
indx += 1
self.attr_content = []
while indx < num:
component = SplitQName(contents[indx].getTagName())[1]
if component == 'attribute':
if contents[indx].hasattr('ref'):
self.attr_content.append(AttributeReference(self))
else:
self.attr_content.append(LocalAttributeDeclaration(self))
elif component == 'attributeGroup':
self.attr_content.append(AttributeGroupReference(self))
elif component == 'anyAttribute':
self.attr_content.append(AttributeWildCard(self))
else:
raise SchemaError, 'Unknown component (%s): %s' \
%(contents[indx].getTagName(),self.getItemTrace())
self.attr_content[-1].fromDom(contents[indx])
indx += 1
class _DerivedType(XMLSchemaComponent):
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
# XXX remove attribute derivation, inconsistent
self.derivation = None
self.content = None
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
for i in contents:
component = SplitQName(i.getTagName())[1]
if component in self.__class__.contents['xsd']:
if component == 'annotation' and not self.annotation:
self.annotation = Annotation(self)
self.annotation.fromDom(i)
continue
elif component == 'restriction' and not self.derivation:
self.derivation = self.__class__.Restriction(self)
elif component == 'extension' and not self.derivation:
self.derivation = self.__class__.Extension(self)
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
self.derivation.fromDom(i)
self.content = self.derivation
class ComplexContent(_DerivedType,\
ComplexMarker):
"""<complexContent>
parents:
complexType
attributes:
id -- ID
mixed -- boolean, false
contents:
annotation?, (restriction | extension)
"""
attributes = {'id':None,
'mixed':0}
contents = {'xsd':['annotation', 'restriction', 'extension']}
tag = 'complexContent'
def isMixed(self):
m = self.getAttribute('mixed')
if m == 0 or m == False:
return False
if isinstance(m, basestring) is True:
if m in ('false', '0'):
return False
if m in ('true', '1'):
return True
raise SchemaError, 'invalid value for attribute mixed(%s): %s'\
%(m, self.getItemTrace())
class _DerivationBase(XMLSchemaComponent):
"""<extension>,<restriction>
parents:
complexContent
attributes:
id -- ID
base -- QName, required
contents:
annotation?, (group | all | choice | sequence)?,
(attribute | attributeGroup)*, anyAttribute?
"""
required = ['base']
attributes = {'id':None,
'base':None }
contents = {'xsd':['annotation', 'group', 'all', 'choice',\
'sequence', 'attribute', 'attributeGroup', 'anyAttribute']}
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
self.content = None
self.attr_content = None
def getAttributeContent(self):
return self.attr_content
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
indx = 0
num = len(contents)
#XXX ugly
if not num:
return
component = SplitQName(contents[indx].getTagName())[1]
if component == 'annotation':
self.annotation = Annotation(self)
self.annotation.fromDom(contents[indx])
indx += 1
component = SplitQName(contents[indx].getTagName())[1]
if component == 'all':
self.content = All(self)
self.content.fromDom(contents[indx])
indx += 1
elif component == 'choice':
self.content = Choice(self)
self.content.fromDom(contents[indx])
indx += 1
elif component == 'sequence':
self.content = Sequence(self)
self.content.fromDom(contents[indx])
indx += 1
elif component == 'group':
self.content = ModelGroupReference(self)
self.content.fromDom(contents[indx])
indx += 1
else:
self.content = None
self.attr_content = []
while indx < num:
component = SplitQName(contents[indx].getTagName())[1]
if component == 'attribute':
if contents[indx].hasattr('ref'):
self.attr_content.append(AttributeReference(self))
else:
self.attr_content.append(LocalAttributeDeclaration(self))
elif component == 'attributeGroup':
if contents[indx].hasattr('ref'):
self.attr_content.append(AttributeGroupReference(self))
else:
self.attr_content.append(AttributeGroupDefinition(self))
elif component == 'anyAttribute':
self.attr_content.append(AttributeWildCard(self))
else:
raise SchemaError, 'Unknown component (%s)' %(contents[indx].getTagName())
self.attr_content[-1].fromDom(contents[indx])
indx += 1
class Extension(_DerivationBase,
ExtensionMarker):
"""<extension base>
parents:
complexContent
attributes:
id -- ID
base -- QName, required
contents:
annotation?, (group | all | choice | sequence)?,
(attribute | attributeGroup)*, anyAttribute?
"""
tag = 'extension'
class Restriction(_DerivationBase,\
RestrictionMarker):
"""<restriction base>
parents:
complexContent
attributes:
id -- ID
base -- QName, required
contents:
annotation?, (group | all | choice | sequence)?,
(attribute | attributeGroup)*, anyAttribute?
"""
tag = 'restriction'
class SimpleContent(_DerivedType,\
SimpleMarker):
"""<simpleContent>
parents:
complexType
attributes:
id -- ID
contents:
annotation?, (restriction | extension)
"""
attributes = {'id':None}
contents = {'xsd':['annotation', 'restriction', 'extension']}
tag = 'simpleContent'
class Extension(XMLSchemaComponent,\
ExtensionMarker):
"""<extension base>
parents:
simpleContent
attributes:
id -- ID
base -- QName, required
contents:
annotation?, (attribute | attributeGroup)*, anyAttribute?
"""
required = ['base']
attributes = {'id':None,
'base':None }
contents = {'xsd':['annotation', 'attribute', 'attributeGroup',
'anyAttribute']}
tag = 'extension'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
self.attr_content = None
def getAttributeContent(self):
return self.attr_content
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
indx = 0
num = len(contents)
if num:
component = SplitQName(contents[indx].getTagName())[1]
if component == 'annotation':
self.annotation = Annotation(self)
self.annotation.fromDom(contents[indx])
indx += 1
component = SplitQName(contents[indx].getTagName())[1]
content = []
while indx < num:
component = SplitQName(contents[indx].getTagName())[1]
if component == 'attribute':
if contents[indx].hasattr('ref'):
content.append(AttributeReference(self))
else:
content.append(LocalAttributeDeclaration(self))
elif component == 'attributeGroup':
content.append(AttributeGroupReference(self))
elif component == 'anyAttribute':
content.append(AttributeWildCard(self))
else:
raise SchemaError, 'Unknown component (%s)'\
%(contents[indx].getTagName())
content[-1].fromDom(contents[indx])
indx += 1
self.attr_content = tuple(content)
class Restriction(XMLSchemaComponent,\
RestrictionMarker):
"""<restriction base>
parents:
simpleContent
attributes:
id -- ID
base -- QName, required
contents:
annotation?, simpleType?, (enumeration | length |
maxExclusive | maxInclusive | maxLength | minExclusive |
minInclusive | minLength | pattern | fractionDigits |
totalDigits | whiteSpace)*, (attribute | attributeGroup)*,
anyAttribute?
"""
required = ['base']
attributes = {'id':None,
'base':None }
contents = {'xsd':['annotation', 'simpleType', 'attribute',\
'attributeGroup', 'anyAttribute'] + RestrictionMarker.facets}
tag = 'restriction'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
self.content = None
self.attr_content = None
def getAttributeContent(self):
return self.attr_content
def fromDom(self, node):
self.content = []
self.setAttributes(node)
contents = self.getContents(node)
indx = 0
num = len(contents)
component = SplitQName(contents[indx].getTagName())[1]
if component == 'annotation':
self.annotation = Annotation(self)
self.annotation.fromDom(contents[indx])
indx += 1
component = SplitQName(contents[indx].getTagName())[1]
content = []
while indx < num:
component = SplitQName(contents[indx].getTagName())[1]
if component == 'attribute':
if contents[indx].hasattr('ref'):
content.append(AttributeReference(self))
else:
content.append(LocalAttributeDeclaration(self))
elif component == 'attributeGroup':
content.append(AttributeGroupReference(self))
elif component == 'anyAttribute':
content.append(AttributeWildCard(self))
elif component == 'simpleType':
self.content.append(AnonymousSimpleType(self))
self.content[-1].fromDom(contents[indx])
else:
raise SchemaError, 'Unknown component (%s)'\
%(contents[indx].getTagName())
content[-1].fromDom(contents[indx])
indx += 1
self.attr_content = tuple(content)
class LocalComplexType(ComplexType,\
LocalMarker):
"""<complexType>
parents:
element
attributes:
id -- ID
mixed -- boolean, false
contents:
annotation?, (simpleContent | complexContent |
((group | all | choice | sequence)?, (attribute | attributeGroup)*, anyAttribute?))
"""
required = []
attributes = {'id':None,
'mixed':0}
tag = 'complexType'
class SimpleType(XMLSchemaComponent,\
DefinitionMarker,\
SimpleMarker):
"""<simpleType name>
parents:
redefine, schema
attributes:
id -- ID
name -- NCName, required
final -- ('#all' | ('extension' | 'restriction' | 'list' | 'union')*),
schema.finalDefault
contents:
annotation?, (restriction | list | union)
"""
required = ['name']
attributes = {'id':None,
'name':None,
'final':lambda self: self._parent().getFinalDefault()}
contents = {'xsd':['annotation', 'restriction', 'list', 'union']}
tag = 'simpleType'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
self.content = None
def getElementDeclaration(self, attribute):
raise Warning, 'invalid operation for <%s>' %self.tag
def getTypeDefinition(self, attribute):
raise Warning, 'invalid operation for <%s>' %self.tag
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
for child in contents:
component = SplitQName(child.getTagName())[1]
if component == 'annotation':
self.annotation = Annotation(self)
self.annotation.fromDom(child)
continue
break
else:
return
if component == 'restriction':
self.content = self.__class__.Restriction(self)
elif component == 'list':
self.content = self.__class__.List(self)
elif component == 'union':
self.content = self.__class__.Union(self)
else:
raise SchemaError, 'Unknown component (%s)' %(component)
self.content.fromDom(child)
class Restriction(XMLSchemaComponent,\
RestrictionMarker):
"""<restriction base>
parents:
simpleType
attributes:
id -- ID
base -- QName, required or simpleType child
contents:
annotation?, simpleType?, (enumeration | length |
maxExclusive | maxInclusive | maxLength | minExclusive |
minInclusive | minLength | pattern | fractionDigits |
totalDigits | whiteSpace)*
"""
attributes = {'id':None,
'base':None }
contents = {'xsd':['annotation', 'simpleType']+RestrictionMarker.facets}
tag = 'restriction'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
self.content = None
self.facets = None
def getAttributeBase(self):
return XMLSchemaComponent.getAttribute(self, 'base')
def getTypeDefinition(self, attribute='base'):
return XMLSchemaComponent.getTypeDefinition(self, attribute)
def getSimpleTypeContent(self):
for el in self.content:
if el.isSimple(): return el
return None
def fromDom(self, node):
self.facets = []
self.setAttributes(node)
contents = self.getContents(node)
content = []
for indx in range(len(contents)):
component = SplitQName(contents[indx].getTagName())[1]
if (component == 'annotation') and (not indx):
self.annotation = Annotation(self)
self.annotation.fromDom(contents[indx])
continue
elif (component == 'simpleType') and (not indx or indx == 1):
content.append(AnonymousSimpleType(self))
content[-1].fromDom(contents[indx])
elif component in RestrictionMarker.facets:
self.facets.append(contents[indx])
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
self.content = tuple(content)
class Union(XMLSchemaComponent,
UnionMarker):
"""<union>
parents:
simpleType
attributes:
id -- ID
memberTypes -- list of QNames, required or simpleType child.
contents:
annotation?, simpleType*
"""
attributes = {'id':None,
'memberTypes':None }
contents = {'xsd':['annotation', 'simpleType']}
tag = 'union'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
self.content = None
def fromDom(self, node):
self.setAttributes(node)
contents = self.getContents(node)
content = []
for indx in range(len(contents)):
component = SplitQName(contents[indx].getTagName())[1]
if (component == 'annotation') and (not indx):
self.annotation = Annotation(self)
self.annotation.fromDom(contents[indx])
elif (component == 'simpleType'):
content.append(AnonymousSimpleType(self))
content[-1].fromDom(contents[indx])
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
self.content = tuple(content)
class List(XMLSchemaComponent,
ListMarker):
"""<list>
parents:
simpleType
attributes:
id -- ID
itemType -- QName, required or simpleType child.
contents:
annotation?, simpleType?
"""
attributes = {'id':None,
'itemType':None }
contents = {'xsd':['annotation', 'simpleType']}
tag = 'list'
def __init__(self, parent):
XMLSchemaComponent.__init__(self, parent)
self.annotation = None
self.content = None
def getItemType(self):
return self.attributes.get('itemType')
def getTypeDefinition(self, attribute='itemType'):
"""
return the type refered to by itemType attribute or
the simpleType content. If returns None, then the
type refered to by itemType is primitive.
"""
tp = XMLSchemaComponent.getTypeDefinition(self, attribute)
return tp or self.content
def fromDom(self, node):
self.annotation = None
self.content = None
self.setAttributes(node)
contents = self.getContents(node)
for indx in range(len(contents)):
component = SplitQName(contents[indx].getTagName())[1]
if (component == 'annotation') and (not indx):
self.annotation = Annotation(self)
self.annotation.fromDom(contents[indx])
elif (component == 'simpleType'):
self.content = AnonymousSimpleType(self)
self.content.fromDom(contents[indx])
break
else:
raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
class AnonymousSimpleType(SimpleType,\
SimpleMarker,\
LocalMarker):
"""<simpleType>
parents:
attribute, element, list, restriction, union
attributes:
id -- ID
contents:
annotation?, (restriction | list | union)
"""
required = []
attributes = {'id':None}
tag = 'simpleType'
class Redefine:
"""<redefine>
parents:
attributes:
contents:
"""
tag = 'redefine'
###########################
###########################
if sys.version_info[:2] >= (2, 2):
tupleClass = tuple
else:
import UserTuple
tupleClass = UserTuple.UserTuple
class TypeDescriptionComponent(tupleClass):
"""Tuple of length 2, consisting of
a namespace and unprefixed name.
"""
def __init__(self, args):
"""args -- (namespace, name)
Remove the name's prefix, irrelevant.
"""
if len(args) != 2:
raise TypeError, 'expecting tuple (namespace, name), got %s' %args
elif args[1].find(':') >= 0:
args = (args[0], SplitQName(args[1])[1])
tuple.__init__(self, args)
return
def getTargetNamespace(self):
return self[0]
def getName(self):
return self[1] | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/ZSI/wstools/XMLSchema.py | XMLSchema.py |
ident = "$Id: Utility.py 1116 2006-01-24 20:51:57Z boverhof $"
import sys, types, httplib, smtplib, urllib, socket, weakref
from os.path import isfile
from string import join, strip, split
from UserDict import UserDict
from cStringIO import StringIO
from TimeoutSocket import TimeoutSocket, TimeoutError
from urlparse import urlparse
from httplib import HTTPConnection, HTTPSConnection
from exceptions import Exception
try:
from ZSI import _get_idstr
except:
def _get_idstr(pyobj):
'''Python 2.3.x generates a FutureWarning for negative IDs, so
we use a different prefix character to ensure uniqueness, and
call abs() to avoid the warning.'''
x = id(pyobj)
if x < 0:
return 'x%x' % abs(x)
return 'o%x' % x
import xml.dom.minidom
from xml.dom import Node
import logging
from c14n import Canonicalize
from Namespaces import SCHEMA, SOAP, XMLNS, ZSI_SCHEMA_URI
try:
from xml.dom.ext import SplitQName
except:
def SplitQName(qname):
'''SplitQName(qname) -> (string, string)
Split Qualified Name into a tuple of len 2, consisting
of the prefix and the local name.
(prefix, localName)
Special Cases:
xmlns -- (localName, 'xmlns')
None -- (None, localName)
'''
l = qname.split(':')
if len(l) == 1:
l.insert(0, None)
elif len(l) == 2:
if l[0] == 'xmlns':
l.reverse()
else:
return
return tuple(l)
#
# python2.3 urllib.basejoin does not remove current directory ./
# from path and this causes problems on subsequent basejoins.
#
basejoin = urllib.basejoin
if sys.version_info[0:2] < (2, 4, 0, 'final', 0)[0:2]:
#basejoin = lambda base,url: urllib.basejoin(base,url.lstrip('./'))
token = './'
def basejoin(base, url):
if url.startswith(token) is True:
return urllib.basejoin(base,url[2:])
return urllib.basejoin(base,url)
class NamespaceError(Exception):
"""Used to indicate a Namespace Error."""
class RecursionError(Exception):
"""Used to indicate a HTTP redirect recursion."""
class ParseError(Exception):
"""Used to indicate a XML parsing error."""
class DOMException(Exception):
"""Used to indicate a problem processing DOM."""
class Base:
"""Base class for instance level Logging"""
def __init__(self, module=__name__):
self.logger = logging.getLogger('%s-%s(%s)' %(module, self.__class__, _get_idstr(self)))
class HTTPResponse:
"""Captures the information in an HTTP response message."""
def __init__(self, response):
self.status = response.status
self.reason = response.reason
self.headers = response.msg
self.body = response.read() or None
response.close()
class TimeoutHTTP(HTTPConnection):
"""A custom http connection object that supports socket timeout."""
def __init__(self, host, port=None, timeout=20):
HTTPConnection.__init__(self, host, port)
self.timeout = timeout
def connect(self):
self.sock = TimeoutSocket(self.timeout)
self.sock.connect((self.host, self.port))
class TimeoutHTTPS(HTTPSConnection):
"""A custom https object that supports socket timeout. Note that this
is not really complete. The builtin SSL support in the Python socket
module requires a real socket (type) to be passed in to be hooked to
SSL. That means our fake socket won't work and our timeout hacks are
bypassed for send and recv calls. Since our hack _is_ in place at
connect() time, it should at least provide some timeout protection."""
def __init__(self, host, port=None, timeout=20, **kwargs):
HTTPSConnection.__init__(self, str(host), port, **kwargs)
self.timeout = timeout
def connect(self):
sock = TimeoutSocket(self.timeout)
sock.connect((self.host, self.port))
realsock = getattr(sock.sock, '_sock', sock.sock)
ssl = socket.ssl(realsock, self.key_file, self.cert_file)
self.sock = httplib.FakeSocket(sock, ssl)
def urlopen(url, timeout=20, redirects=None):
"""A minimal urlopen replacement hack that supports timeouts for http.
Note that this supports GET only."""
scheme, host, path, params, query, frag = urlparse(url)
if not scheme in ('http', 'https'):
return urllib.urlopen(url)
if params: path = '%s;%s' % (path, params)
if query: path = '%s?%s' % (path, query)
if frag: path = '%s#%s' % (path, frag)
if scheme == 'https':
# If ssl is not compiled into Python, you will not get an exception
# until a conn.endheaders() call. We need to know sooner, so use
# getattr.
if hasattr(socket, 'ssl'):
conn = TimeoutHTTPS(host, None, timeout)
else:
import M2Crypto
ctx = M2Crypto.SSL.Context()
ctx.set_session_timeout(timeout)
conn = M2Crypto.httpslib.HTTPSConnection(host, ssl_context=ctx)
#conn.set_debuglevel(1)
else:
conn = TimeoutHTTP(host, None, timeout)
conn.putrequest('GET', path)
conn.putheader('Connection', 'close')
conn.endheaders()
response = None
while 1:
response = conn.getresponse()
if response.status != 100:
break
conn._HTTPConnection__state = httplib._CS_REQ_SENT
conn._HTTPConnection__response = None
status = response.status
# If we get an HTTP redirect, we will follow it automatically.
if status >= 300 and status < 400:
location = response.msg.getheader('location')
if location is not None:
response.close()
if redirects is not None and redirects.has_key(location):
raise RecursionError(
'Circular HTTP redirection detected.'
)
if redirects is None:
redirects = {}
redirects[location] = 1
return urlopen(location, timeout, redirects)
raise HTTPResponse(response)
if not (status >= 200 and status < 300):
raise HTTPResponse(response)
body = StringIO(response.read())
response.close()
return body
class DOM:
"""The DOM singleton defines a number of XML related constants and
provides a number of utility methods for DOM related tasks. It
also provides some basic abstractions so that the rest of the
package need not care about actual DOM implementation in use."""
# Namespace stuff related to the SOAP specification.
NS_SOAP_ENV_1_1 = 'http://schemas.xmlsoap.org/soap/envelope/'
NS_SOAP_ENC_1_1 = 'http://schemas.xmlsoap.org/soap/encoding/'
NS_SOAP_ENV_1_2 = 'http://www.w3.org/2001/06/soap-envelope'
NS_SOAP_ENC_1_2 = 'http://www.w3.org/2001/06/soap-encoding'
NS_SOAP_ENV_ALL = (NS_SOAP_ENV_1_1, NS_SOAP_ENV_1_2)
NS_SOAP_ENC_ALL = (NS_SOAP_ENC_1_1, NS_SOAP_ENC_1_2)
NS_SOAP_ENV = NS_SOAP_ENV_1_1
NS_SOAP_ENC = NS_SOAP_ENC_1_1
_soap_uri_mapping = {
NS_SOAP_ENV_1_1 : '1.1',
NS_SOAP_ENV_1_2 : '1.2',
}
SOAP_ACTOR_NEXT_1_1 = 'http://schemas.xmlsoap.org/soap/actor/next'
SOAP_ACTOR_NEXT_1_2 = 'http://www.w3.org/2001/06/soap-envelope/actor/next'
SOAP_ACTOR_NEXT_ALL = (SOAP_ACTOR_NEXT_1_1, SOAP_ACTOR_NEXT_1_2)
def SOAPUriToVersion(self, uri):
"""Return the SOAP version related to an envelope uri."""
value = self._soap_uri_mapping.get(uri)
if value is not None:
return value
raise ValueError(
'Unsupported SOAP envelope uri: %s' % uri
)
def GetSOAPEnvUri(self, version):
"""Return the appropriate SOAP envelope uri for a given
human-friendly SOAP version string (e.g. '1.1')."""
attrname = 'NS_SOAP_ENV_%s' % join(split(version, '.'), '_')
value = getattr(self, attrname, None)
if value is not None:
return value
raise ValueError(
'Unsupported SOAP version: %s' % version
)
def GetSOAPEncUri(self, version):
"""Return the appropriate SOAP encoding uri for a given
human-friendly SOAP version string (e.g. '1.1')."""
attrname = 'NS_SOAP_ENC_%s' % join(split(version, '.'), '_')
value = getattr(self, attrname, None)
if value is not None:
return value
raise ValueError(
'Unsupported SOAP version: %s' % version
)
def GetSOAPActorNextUri(self, version):
"""Return the right special next-actor uri for a given
human-friendly SOAP version string (e.g. '1.1')."""
attrname = 'SOAP_ACTOR_NEXT_%s' % join(split(version, '.'), '_')
value = getattr(self, attrname, None)
if value is not None:
return value
raise ValueError(
'Unsupported SOAP version: %s' % version
)
# Namespace stuff related to XML Schema.
NS_XSD_99 = 'http://www.w3.org/1999/XMLSchema'
NS_XSI_99 = 'http://www.w3.org/1999/XMLSchema-instance'
NS_XSD_00 = 'http://www.w3.org/2000/10/XMLSchema'
NS_XSI_00 = 'http://www.w3.org/2000/10/XMLSchema-instance'
NS_XSD_01 = 'http://www.w3.org/2001/XMLSchema'
NS_XSI_01 = 'http://www.w3.org/2001/XMLSchema-instance'
NS_XSD_ALL = (NS_XSD_99, NS_XSD_00, NS_XSD_01)
NS_XSI_ALL = (NS_XSI_99, NS_XSI_00, NS_XSI_01)
NS_XSD = NS_XSD_01
NS_XSI = NS_XSI_01
_xsd_uri_mapping = {
NS_XSD_99 : NS_XSI_99,
NS_XSD_00 : NS_XSI_00,
NS_XSD_01 : NS_XSI_01,
}
for key, value in _xsd_uri_mapping.items():
_xsd_uri_mapping[value] = key
def InstanceUriForSchemaUri(self, uri):
"""Return the appropriate matching XML Schema instance uri for
the given XML Schema namespace uri."""
return self._xsd_uri_mapping.get(uri)
def SchemaUriForInstanceUri(self, uri):
"""Return the appropriate matching XML Schema namespace uri for
the given XML Schema instance namespace uri."""
return self._xsd_uri_mapping.get(uri)
# Namespace stuff related to WSDL.
NS_WSDL_1_1 = 'http://schemas.xmlsoap.org/wsdl/'
NS_WSDL_ALL = (NS_WSDL_1_1,)
NS_WSDL = NS_WSDL_1_1
NS_SOAP_BINDING_1_1 = 'http://schemas.xmlsoap.org/wsdl/soap/'
NS_HTTP_BINDING_1_1 = 'http://schemas.xmlsoap.org/wsdl/http/'
NS_MIME_BINDING_1_1 = 'http://schemas.xmlsoap.org/wsdl/mime/'
NS_SOAP_BINDING_ALL = (NS_SOAP_BINDING_1_1,)
NS_HTTP_BINDING_ALL = (NS_HTTP_BINDING_1_1,)
NS_MIME_BINDING_ALL = (NS_MIME_BINDING_1_1,)
NS_SOAP_BINDING = NS_SOAP_BINDING_1_1
NS_HTTP_BINDING = NS_HTTP_BINDING_1_1
NS_MIME_BINDING = NS_MIME_BINDING_1_1
NS_SOAP_HTTP_1_1 = 'http://schemas.xmlsoap.org/soap/http'
NS_SOAP_HTTP_ALL = (NS_SOAP_HTTP_1_1,)
NS_SOAP_HTTP = NS_SOAP_HTTP_1_1
_wsdl_uri_mapping = {
NS_WSDL_1_1 : '1.1',
}
def WSDLUriToVersion(self, uri):
"""Return the WSDL version related to a WSDL namespace uri."""
value = self._wsdl_uri_mapping.get(uri)
if value is not None:
return value
raise ValueError(
'Unsupported SOAP envelope uri: %s' % uri
)
def GetWSDLUri(self, version):
attr = 'NS_WSDL_%s' % join(split(version, '.'), '_')
value = getattr(self, attr, None)
if value is not None:
return value
raise ValueError(
'Unsupported WSDL version: %s' % version
)
def GetWSDLSoapBindingUri(self, version):
attr = 'NS_SOAP_BINDING_%s' % join(split(version, '.'), '_')
value = getattr(self, attr, None)
if value is not None:
return value
raise ValueError(
'Unsupported WSDL version: %s' % version
)
def GetWSDLHttpBindingUri(self, version):
attr = 'NS_HTTP_BINDING_%s' % join(split(version, '.'), '_')
value = getattr(self, attr, None)
if value is not None:
return value
raise ValueError(
'Unsupported WSDL version: %s' % version
)
def GetWSDLMimeBindingUri(self, version):
attr = 'NS_MIME_BINDING_%s' % join(split(version, '.'), '_')
value = getattr(self, attr, None)
if value is not None:
return value
raise ValueError(
'Unsupported WSDL version: %s' % version
)
def GetWSDLHttpTransportUri(self, version):
attr = 'NS_SOAP_HTTP_%s' % join(split(version, '.'), '_')
value = getattr(self, attr, None)
if value is not None:
return value
raise ValueError(
'Unsupported WSDL version: %s' % version
)
# Other xml namespace constants.
NS_XMLNS = 'http://www.w3.org/2000/xmlns/'
def isElement(self, node, name, nsuri=None):
"""Return true if the given node is an element with the given
name and optional namespace uri."""
if node.nodeType != node.ELEMENT_NODE:
return 0
return node.localName == name and \
(nsuri is None or self.nsUriMatch(node.namespaceURI, nsuri))
def getElement(self, node, name, nsuri=None, default=join):
"""Return the first child of node with a matching name and
namespace uri, or the default if one is provided."""
nsmatch = self.nsUriMatch
ELEMENT_NODE = node.ELEMENT_NODE
for child in node.childNodes:
if child.nodeType == ELEMENT_NODE:
if ((child.localName == name or name is None) and
(nsuri is None or nsmatch(child.namespaceURI, nsuri))
):
return child
if default is not join:
return default
raise KeyError, name
def getElementById(self, node, id, default=join):
"""Return the first child of node matching an id reference."""
attrget = self.getAttr
ELEMENT_NODE = node.ELEMENT_NODE
for child in node.childNodes:
if child.nodeType == ELEMENT_NODE:
if attrget(child, 'id') == id:
return child
if default is not join:
return default
raise KeyError, name
def getMappingById(self, document, depth=None, element=None,
mapping=None, level=1):
"""Create an id -> element mapping of those elements within a
document that define an id attribute. The depth of the search
may be controlled by using the (1-based) depth argument."""
if document is not None:
element = document.documentElement
mapping = {}
attr = element._attrs.get('id', None)
if attr is not None:
mapping[attr.value] = element
if depth is None or depth > level:
level = level + 1
ELEMENT_NODE = element.ELEMENT_NODE
for child in element.childNodes:
if child.nodeType == ELEMENT_NODE:
self.getMappingById(None, depth, child, mapping, level)
return mapping
def getElements(self, node, name, nsuri=None):
"""Return a sequence of the child elements of the given node that
match the given name and optional namespace uri."""
nsmatch = self.nsUriMatch
result = []
ELEMENT_NODE = node.ELEMENT_NODE
for child in node.childNodes:
if child.nodeType == ELEMENT_NODE:
if ((child.localName == name or name is None) and (
(nsuri is None) or nsmatch(child.namespaceURI, nsuri))):
result.append(child)
return result
def hasAttr(self, node, name, nsuri=None):
"""Return true if element has attribute with the given name and
optional nsuri. If nsuri is not specified, returns true if an
attribute exists with the given name with any namespace."""
if nsuri is None:
if node.hasAttribute(name):
return True
return False
return node.hasAttributeNS(nsuri, name)
def getAttr(self, node, name, nsuri=None, default=join):
"""Return the value of the attribute named 'name' with the
optional nsuri, or the default if one is specified. If
nsuri is not specified, an attribute that matches the
given name will be returned regardless of namespace."""
if nsuri is None:
result = node._attrs.get(name, None)
if result is None:
for item in node._attrsNS.keys():
if item[1] == name:
result = node._attrsNS[item]
break
else:
result = node._attrsNS.get((nsuri, name), None)
if result is not None:
return result.value
if default is not join:
return default
return ''
def getAttrs(self, node):
"""Return a Collection of all attributes
"""
attrs = {}
for k,v in node._attrs.items():
attrs[k] = v.value
return attrs
def getElementText(self, node, preserve_ws=None):
"""Return the text value of an xml element node. Leading and trailing
whitespace is stripped from the value unless the preserve_ws flag
is passed with a true value."""
result = []
for child in node.childNodes:
nodetype = child.nodeType
if nodetype == child.TEXT_NODE or \
nodetype == child.CDATA_SECTION_NODE:
result.append(child.nodeValue)
value = join(result, '')
if preserve_ws is None:
value = strip(value)
return value
def findNamespaceURI(self, prefix, node):
"""Find a namespace uri given a prefix and a context node."""
attrkey = (self.NS_XMLNS, prefix)
DOCUMENT_NODE = node.DOCUMENT_NODE
ELEMENT_NODE = node.ELEMENT_NODE
while 1:
if node is None:
raise DOMException('Value for prefix %s not found.' % prefix)
if node.nodeType != ELEMENT_NODE:
node = node.parentNode
continue
result = node._attrsNS.get(attrkey, None)
if result is not None:
return result.value
if hasattr(node, '__imported__'):
raise DOMException('Value for prefix %s not found.' % prefix)
node = node.parentNode
if node.nodeType == DOCUMENT_NODE:
raise DOMException('Value for prefix %s not found.' % prefix)
def findDefaultNS(self, node):
"""Return the current default namespace uri for the given node."""
attrkey = (self.NS_XMLNS, 'xmlns')
DOCUMENT_NODE = node.DOCUMENT_NODE
ELEMENT_NODE = node.ELEMENT_NODE
while 1:
if node.nodeType != ELEMENT_NODE:
node = node.parentNode
continue
result = node._attrsNS.get(attrkey, None)
if result is not None:
return result.value
if hasattr(node, '__imported__'):
raise DOMException('Cannot determine default namespace.')
node = node.parentNode
if node.nodeType == DOCUMENT_NODE:
raise DOMException('Cannot determine default namespace.')
def findTargetNS(self, node):
"""Return the defined target namespace uri for the given node."""
attrget = self.getAttr
attrkey = (self.NS_XMLNS, 'xmlns')
DOCUMENT_NODE = node.DOCUMENT_NODE
ELEMENT_NODE = node.ELEMENT_NODE
while 1:
if node.nodeType != ELEMENT_NODE:
node = node.parentNode
continue
result = attrget(node, 'targetNamespace', default=None)
if result is not None:
return result
node = node.parentNode
if node.nodeType == DOCUMENT_NODE:
raise DOMException('Cannot determine target namespace.')
def getTypeRef(self, element):
"""Return (namespaceURI, name) for a type attribue of the given
element, or None if the element does not have a type attribute."""
typeattr = self.getAttr(element, 'type', default=None)
if typeattr is None:
return None
parts = typeattr.split(':', 1)
if len(parts) == 2:
nsuri = self.findNamespaceURI(parts[0], element)
else:
nsuri = self.findDefaultNS(element)
return (nsuri, parts[1])
def importNode(self, document, node, deep=0):
"""Implements (well enough for our purposes) DOM node import."""
nodetype = node.nodeType
if nodetype in (node.DOCUMENT_NODE, node.DOCUMENT_TYPE_NODE):
raise DOMException('Illegal node type for importNode')
if nodetype == node.ENTITY_REFERENCE_NODE:
deep = 0
clone = node.cloneNode(deep)
self._setOwnerDoc(document, clone)
clone.__imported__ = 1
return clone
def _setOwnerDoc(self, document, node):
node.ownerDocument = document
for child in node.childNodes:
self._setOwnerDoc(document, child)
def nsUriMatch(self, value, wanted, strict=0, tt=type(())):
"""Return a true value if two namespace uri values match."""
if value == wanted or (type(wanted) is tt) and value in wanted:
return 1
if not strict and value is not None:
wanted = type(wanted) is tt and wanted or (wanted,)
value = value[-1:] != '/' and value or value[:-1]
for item in wanted:
if item == value or item[:-1] == value:
return 1
return 0
def createDocument(self, nsuri, qname, doctype=None):
"""Create a new writable DOM document object."""
impl = xml.dom.minidom.getDOMImplementation()
return impl.createDocument(nsuri, qname, doctype)
def loadDocument(self, data):
"""Load an xml file from a file-like object and return a DOM
document instance."""
return xml.dom.minidom.parse(data)
def loadFromURL(self, url):
"""Load an xml file from a URL and return a DOM document."""
if isfile(url) is True:
file = open(url, 'r')
else:
file = urlopen(url)
try:
result = self.loadDocument(file)
except Exception, ex:
file.close()
raise ParseError(('Failed to load document %s' %url,) + ex.args)
else:
file.close()
return result
DOM = DOM()
class MessageInterface:
'''Higher Level Interface, delegates to DOM singleton, must
be subclassed and implement all methods that throw NotImplementedError.
'''
def __init__(self, sw):
'''Constructor, May be extended, do not override.
sw -- soapWriter instance
'''
self.sw = None
if type(sw) != weakref.ReferenceType and sw is not None:
self.sw = weakref.ref(sw)
else:
self.sw = sw
def AddCallback(self, func, *arglist):
self.sw().AddCallback(func, *arglist)
def Known(self, obj):
return self.sw().Known(obj)
def Forget(self, obj):
return self.sw().Forget(obj)
def canonicalize(self):
'''canonicalize the underlying DOM, and return as string.
'''
raise NotImplementedError, ''
def createDocument(self, namespaceURI=SOAP.ENV, localName='Envelope'):
'''create Document
'''
raise NotImplementedError, ''
def createAppendElement(self, namespaceURI, localName):
'''create and append element(namespaceURI,localName), and return
the node.
'''
raise NotImplementedError, ''
def findNamespaceURI(self, qualifiedName):
raise NotImplementedError, ''
def resolvePrefix(self, prefix):
raise NotImplementedError, ''
def setAttributeNS(self, namespaceURI, localName, value):
'''set attribute (namespaceURI, localName)=value
'''
raise NotImplementedError, ''
def setAttributeType(self, namespaceURI, localName):
'''set attribute xsi:type=(namespaceURI, localName)
'''
raise NotImplementedError, ''
def setNamespaceAttribute(self, namespaceURI, prefix):
'''set namespace attribute xmlns:prefix=namespaceURI
'''
raise NotImplementedError, ''
class ElementProxy(Base, MessageInterface):
'''
'''
_soap_env_prefix = 'SOAP-ENV'
_soap_enc_prefix = 'SOAP-ENC'
_zsi_prefix = 'ZSI'
_xsd_prefix = 'xsd'
_xsi_prefix = 'xsi'
_xml_prefix = 'xml'
_xmlns_prefix = 'xmlns'
_soap_env_nsuri = SOAP.ENV
_soap_enc_nsuri = SOAP.ENC
_zsi_nsuri = ZSI_SCHEMA_URI
_xsd_nsuri = SCHEMA.XSD3
_xsi_nsuri = SCHEMA.XSI3
_xml_nsuri = XMLNS.XML
_xmlns_nsuri = XMLNS.BASE
standard_ns = {\
_xml_prefix:_xml_nsuri,
_xmlns_prefix:_xmlns_nsuri
}
reserved_ns = {\
_soap_env_prefix:_soap_env_nsuri,
_soap_enc_prefix:_soap_enc_nsuri,
_zsi_prefix:_zsi_nsuri,
_xsd_prefix:_xsd_nsuri,
_xsi_prefix:_xsi_nsuri,
}
name = None
namespaceURI = None
def __init__(self, sw, message=None):
'''Initialize.
sw -- SoapWriter
'''
self._indx = 0
MessageInterface.__init__(self, sw)
Base.__init__(self)
self._dom = DOM
self.node = None
if type(message) in (types.StringType,types.UnicodeType):
self.loadFromString(message)
elif isinstance(message, ElementProxy):
self.node = message._getNode()
else:
self.node = message
self.processorNss = self.standard_ns.copy()
self.processorNss.update(self.reserved_ns)
def __str__(self):
return self.toString()
def evaluate(self, expression, processorNss=None):
'''expression -- XPath compiled expression
'''
from Ft.Xml import XPath
if not processorNss:
context = XPath.Context.Context(self.node, processorNss=self.processorNss)
else:
context = XPath.Context.Context(self.node, processorNss=processorNss)
nodes = expression.evaluate(context)
return map(lambda node: ElementProxy(self.sw,node), nodes)
#############################################
# Methods for checking/setting the
# classes (namespaceURI,name) node.
#############################################
def checkNode(self, namespaceURI=None, localName=None):
'''
namespaceURI -- namespace of element
localName -- local name of element
'''
namespaceURI = namespaceURI or self.namespaceURI
localName = localName or self.name
check = False
if localName and self.node:
check = self._dom.isElement(self.node, localName, namespaceURI)
if not check:
raise NamespaceError, 'unexpected node type %s, expecting %s' %(self.node, localName)
def setNode(self, node=None):
if node:
if isinstance(node, ElementProxy):
self.node = node._getNode()
else:
self.node = node
elif self.node:
node = self._dom.getElement(self.node, self.name, self.namespaceURI, default=None)
if not node:
raise NamespaceError, 'cant find element (%s,%s)' %(self.namespaceURI,self.name)
self.node = node
else:
#self.node = self._dom.create(self.node, self.name, self.namespaceURI, default=None)
self.createDocument(self.namespaceURI, localName=self.name, doctype=None)
self.checkNode()
#############################################
# Wrapper Methods for direct DOM Element Node access
#############################################
def _getNode(self):
return self.node
def _getElements(self):
return self._dom.getElements(self.node, name=None)
def _getOwnerDocument(self):
return self.node.ownerDocument or self.node
def _getUniquePrefix(self):
'''I guess we need to resolve all potential prefixes
because when the current node is attached it copies the
namespaces into the parent node.
'''
while 1:
self._indx += 1
prefix = 'ns%d' %self._indx
try:
self._dom.findNamespaceURI(prefix, self._getNode())
except DOMException, ex:
break
return prefix
def _getPrefix(self, node, nsuri):
'''
Keyword arguments:
node -- DOM Element Node
nsuri -- namespace of attribute value
'''
try:
if node and (node.nodeType == node.ELEMENT_NODE) and \
(nsuri == self._dom.findDefaultNS(node)):
return None
except DOMException, ex:
pass
if nsuri == XMLNS.XML:
return self._xml_prefix
if node.nodeType == Node.ELEMENT_NODE:
for attr in node.attributes.values():
if attr.namespaceURI == XMLNS.BASE \
and nsuri == attr.value:
return attr.localName
else:
if node.parentNode:
return self._getPrefix(node.parentNode, nsuri)
raise NamespaceError, 'namespaceURI "%s" is not defined' %nsuri
def _appendChild(self, node):
'''
Keyword arguments:
node -- DOM Element Node
'''
if node is None:
raise TypeError, 'node is None'
self.node.appendChild(node)
def _insertBefore(self, newChild, refChild):
'''
Keyword arguments:
child -- DOM Element Node to insert
refChild -- DOM Element Node
'''
self.node.insertBefore(newChild, refChild)
def _setAttributeNS(self, namespaceURI, qualifiedName, value):
'''
Keyword arguments:
namespaceURI -- namespace of attribute
qualifiedName -- qualified name of new attribute value
value -- value of attribute
'''
self.node.setAttributeNS(namespaceURI, qualifiedName, value)
#############################################
#General Methods
#############################################
def isFault(self):
'''check to see if this is a soap:fault message.
'''
return False
def getPrefix(self, namespaceURI):
try:
prefix = self._getPrefix(node=self.node, nsuri=namespaceURI)
except NamespaceError, ex:
prefix = self._getUniquePrefix()
self.setNamespaceAttribute(prefix, namespaceURI)
return prefix
def getDocument(self):
return self._getOwnerDocument()
def setDocument(self, document):
self.node = document
def importFromString(self, xmlString):
doc = self._dom.loadDocument(StringIO(xmlString))
node = self._dom.getElement(doc, name=None)
clone = self.importNode(node)
self._appendChild(clone)
def importNode(self, node):
if isinstance(node, ElementProxy):
node = node._getNode()
return self._dom.importNode(self._getOwnerDocument(), node, deep=1)
def loadFromString(self, data):
self.node = self._dom.loadDocument(StringIO(data))
def canonicalize(self):
return Canonicalize(self.node)
def toString(self):
return self.canonicalize()
def createDocument(self, namespaceURI, localName, doctype=None):
'''If specified must be a SOAP envelope, else may contruct an empty document.
'''
prefix = self._soap_env_prefix
if namespaceURI == self.reserved_ns[prefix]:
qualifiedName = '%s:%s' %(prefix,localName)
elif namespaceURI is localName is None:
self.node = self._dom.createDocument(None,None,None)
return
else:
raise KeyError, 'only support creation of document in %s' %self.reserved_ns[prefix]
document = self._dom.createDocument(nsuri=namespaceURI, qname=qualifiedName, doctype=doctype)
self.node = document.childNodes[0]
#set up reserved namespace attributes
for prefix,nsuri in self.reserved_ns.items():
self._setAttributeNS(namespaceURI=self._xmlns_nsuri,
qualifiedName='%s:%s' %(self._xmlns_prefix,prefix),
value=nsuri)
#############################################
#Methods for attributes
#############################################
def hasAttribute(self, namespaceURI, localName):
return self._dom.hasAttr(self._getNode(), name=localName, nsuri=namespaceURI)
def setAttributeType(self, namespaceURI, localName):
'''set xsi:type
Keyword arguments:
namespaceURI -- namespace of attribute value
localName -- name of new attribute value
'''
self.logger.debug('setAttributeType: (%s,%s)', namespaceURI, localName)
value = localName
if namespaceURI:
value = '%s:%s' %(self.getPrefix(namespaceURI),localName)
xsi_prefix = self.getPrefix(self._xsi_nsuri)
self._setAttributeNS(self._xsi_nsuri, '%s:type' %xsi_prefix, value)
def createAttributeNS(self, namespace, name, value):
document = self._getOwnerDocument()
attrNode = document.createAttributeNS(namespace, name, value)
def setAttributeNS(self, namespaceURI, localName, value):
'''
Keyword arguments:
namespaceURI -- namespace of attribute to create, None is for
attributes in no namespace.
localName -- local name of new attribute
value -- value of new attribute
'''
prefix = None
if namespaceURI:
try:
prefix = self.getPrefix(namespaceURI)
except KeyError, ex:
prefix = 'ns2'
self.setNamespaceAttribute(prefix, namespaceURI)
qualifiedName = localName
if prefix:
qualifiedName = '%s:%s' %(prefix, localName)
self._setAttributeNS(namespaceURI, qualifiedName, value)
def setNamespaceAttribute(self, prefix, namespaceURI):
'''
Keyword arguments:
prefix -- xmlns prefix
namespaceURI -- value of prefix
'''
self._setAttributeNS(XMLNS.BASE, 'xmlns:%s' %prefix, namespaceURI)
#############################################
#Methods for elements
#############################################
def createElementNS(self, namespace, qname):
'''
Keyword arguments:
namespace -- namespace of element to create
qname -- qualified name of new element
'''
document = self._getOwnerDocument()
node = document.createElementNS(namespace, qname)
return ElementProxy(self.sw, node)
def createAppendSetElement(self, namespaceURI, localName, prefix=None):
'''Create a new element (namespaceURI,name), append it
to current node, then set it to be the current node.
Keyword arguments:
namespaceURI -- namespace of element to create
localName -- local name of new element
prefix -- if namespaceURI is not defined, declare prefix. defaults
to 'ns1' if left unspecified.
'''
node = self.createAppendElement(namespaceURI, localName, prefix=None)
node=node._getNode()
self._setNode(node._getNode())
def createAppendElement(self, namespaceURI, localName, prefix=None):
'''Create a new element (namespaceURI,name), append it
to current node, and return the newly created node.
Keyword arguments:
namespaceURI -- namespace of element to create
localName -- local name of new element
prefix -- if namespaceURI is not defined, declare prefix. defaults
to 'ns1' if left unspecified.
'''
declare = False
qualifiedName = localName
if namespaceURI:
try:
prefix = self.getPrefix(namespaceURI)
except:
declare = True
prefix = prefix or self._getUniquePrefix()
if prefix:
qualifiedName = '%s:%s' %(prefix, localName)
node = self.createElementNS(namespaceURI, qualifiedName)
if declare:
node._setAttributeNS(XMLNS.BASE, 'xmlns:%s' %prefix, namespaceURI)
self._appendChild(node=node._getNode())
return node
def createInsertBefore(self, namespaceURI, localName, refChild):
qualifiedName = localName
prefix = self.getPrefix(namespaceURI)
if prefix:
qualifiedName = '%s:%s' %(prefix, localName)
node = self.createElementNS(namespaceURI, qualifiedName)
self._insertBefore(newChild=node._getNode(), refChild=refChild._getNode())
return node
def getElement(self, namespaceURI, localName):
'''
Keyword arguments:
namespaceURI -- namespace of element
localName -- local name of element
'''
node = self._dom.getElement(self.node, localName, namespaceURI, default=None)
if node:
return ElementProxy(self.sw, node)
return None
def getAttributeValue(self, namespaceURI, localName):
'''
Keyword arguments:
namespaceURI -- namespace of attribute
localName -- local name of attribute
'''
if self.hasAttribute(namespaceURI, localName):
attr = self.node.getAttributeNodeNS(namespaceURI,localName)
return attr.value
return None
def getValue(self):
return self._dom.getElementText(self.node, preserve_ws=True)
#############################################
#Methods for text nodes
#############################################
def createAppendTextNode(self, pyobj):
node = self.createTextNode(pyobj)
self._appendChild(node=node._getNode())
return node
def createTextNode(self, pyobj):
document = self._getOwnerDocument()
node = document.createTextNode(pyobj)
return ElementProxy(self.sw, node)
#############################################
#Methods for retrieving namespaceURI's
#############################################
def findNamespaceURI(self, qualifiedName):
parts = SplitQName(qualifiedName)
element = self._getNode()
if len(parts) == 1:
return (self._dom.findTargetNS(element), value)
return self._dom.findNamespaceURI(parts[0], element)
def resolvePrefix(self, prefix):
element = self._getNode()
return self._dom.findNamespaceURI(prefix, element)
def getSOAPEnvURI(self):
return self._soap_env_nsuri
def isEmpty(self):
return not self.node
class Collection(UserDict):
"""Helper class for maintaining ordered named collections."""
default = lambda self,k: k.name
def __init__(self, parent, key=None):
UserDict.__init__(self)
self.parent = weakref.ref(parent)
self.list = []
self._func = key or self.default
def __getitem__(self, key):
if type(key) is type(1):
return self.list[key]
return self.data[key]
def __setitem__(self, key, item):
item.parent = weakref.ref(self)
self.list.append(item)
self.data[key] = item
def keys(self):
return map(lambda i: self._func(i), self.list)
def items(self):
return map(lambda i: (self._func(i), i), self.list)
def values(self):
return self.list
class CollectionNS(UserDict):
"""Helper class for maintaining ordered named collections."""
default = lambda self,k: k.name
def __init__(self, parent, key=None):
UserDict.__init__(self)
self.parent = weakref.ref(parent)
self.targetNamespace = None
self.list = []
self._func = key or self.default
def __getitem__(self, key):
self.targetNamespace = self.parent().targetNamespace
if type(key) is types.IntType:
return self.list[key]
elif self.__isSequence(key):
nsuri,name = key
return self.data[nsuri][name]
return self.data[self.parent().targetNamespace][key]
def __setitem__(self, key, item):
item.parent = weakref.ref(self)
self.list.append(item)
targetNamespace = getattr(item, 'targetNamespace', self.parent().targetNamespace)
if not self.data.has_key(targetNamespace):
self.data[targetNamespace] = {}
self.data[targetNamespace][key] = item
def __isSequence(self, key):
return (type(key) in (types.TupleType,types.ListType) and len(key) == 2)
def keys(self):
keys = []
for tns in self.data.keys():
keys.append(map(lambda i: (tns,self._func(i)), self.data[tns].values()))
return keys
def items(self):
return map(lambda i: (self._func(i), i), self.list)
def values(self):
return self.list
# This is a runtime guerilla patch for pulldom (used by minidom) so
# that xml namespace declaration attributes are not lost in parsing.
# We need them to do correct QName linking for XML Schema and WSDL.
# The patch has been submitted to SF for the next Python version.
from xml.dom.pulldom import PullDOM, START_ELEMENT
if 1:
def startPrefixMapping(self, prefix, uri):
if not hasattr(self, '_xmlns_attrs'):
self._xmlns_attrs = []
self._xmlns_attrs.append((prefix or 'xmlns', uri))
self._ns_contexts.append(self._current_context.copy())
self._current_context[uri] = prefix or ''
PullDOM.startPrefixMapping = startPrefixMapping
def startElementNS(self, name, tagName , attrs):
# Retrieve xml namespace declaration attributes.
xmlns_uri = 'http://www.w3.org/2000/xmlns/'
xmlns_attrs = getattr(self, '_xmlns_attrs', None)
if xmlns_attrs is not None:
for aname, value in xmlns_attrs:
attrs._attrs[(xmlns_uri, aname)] = value
self._xmlns_attrs = []
uri, localname = name
if uri:
# When using namespaces, the reader may or may not
# provide us with the original name. If not, create
# *a* valid tagName from the current context.
if tagName is None:
prefix = self._current_context[uri]
if prefix:
tagName = prefix + ":" + localname
else:
tagName = localname
if self.document:
node = self.document.createElementNS(uri, tagName)
else:
node = self.buildDocument(uri, tagName)
else:
# When the tagname is not prefixed, it just appears as
# localname
if self.document:
node = self.document.createElement(localname)
else:
node = self.buildDocument(None, localname)
for aname,value in attrs.items():
a_uri, a_localname = aname
if a_uri == xmlns_uri:
if a_localname == 'xmlns':
qname = a_localname
else:
qname = 'xmlns:' + a_localname
attr = self.document.createAttributeNS(a_uri, qname)
node.setAttributeNodeNS(attr)
elif a_uri:
prefix = self._current_context[a_uri]
if prefix:
qname = prefix + ":" + a_localname
else:
qname = a_localname
attr = self.document.createAttributeNS(a_uri, qname)
node.setAttributeNodeNS(attr)
else:
attr = self.document.createAttribute(a_localname)
node.setAttributeNode(attr)
attr.value = value
self.lastEvent[1] = [(START_ELEMENT, node), None]
self.lastEvent = self.lastEvent[1]
self.push(node)
PullDOM.startElementNS = startElementNS
#
# This is a runtime guerilla patch for minidom so
# that xmlns prefixed attributes dont raise AttributeErrors
# during cloning.
#
# Namespace declarations can appear in any start-tag, must look for xmlns
# prefixed attribute names during cloning.
#
# key (attr.namespaceURI, tag)
# ('http://www.w3.org/2000/xmlns/', u'xsd') <xml.dom.minidom.Attr instance at 0x82227c4>
# ('http://www.w3.org/2000/xmlns/', 'xmlns') <xml.dom.minidom.Attr instance at 0x8414b3c>
#
# xml.dom.minidom.Attr.nodeName = xmlns:xsd
# xml.dom.minidom.Attr.value = = http://www.w3.org/2001/XMLSchema
if 1:
def _clone_node(node, deep, newOwnerDocument):
"""
Clone a node and give it the new owner document.
Called by Node.cloneNode and Document.importNode
"""
if node.ownerDocument.isSameNode(newOwnerDocument):
operation = xml.dom.UserDataHandler.NODE_CLONED
else:
operation = xml.dom.UserDataHandler.NODE_IMPORTED
if node.nodeType == xml.dom.minidom.Node.ELEMENT_NODE:
clone = newOwnerDocument.createElementNS(node.namespaceURI,
node.nodeName)
for attr in node.attributes.values():
clone.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.value)
prefix, tag = xml.dom.minidom._nssplit(attr.nodeName)
if prefix == 'xmlns':
a = clone.getAttributeNodeNS(attr.namespaceURI, tag)
elif prefix:
a = clone.getAttributeNodeNS(attr.namespaceURI, tag)
else:
a = clone.getAttributeNodeNS(attr.namespaceURI, attr.nodeName)
a.specified = attr.specified
if deep:
for child in node.childNodes:
c = xml.dom.minidom._clone_node(child, deep, newOwnerDocument)
clone.appendChild(c)
elif node.nodeType == xml.dom.minidom.Node.DOCUMENT_FRAGMENT_NODE:
clone = newOwnerDocument.createDocumentFragment()
if deep:
for child in node.childNodes:
c = xml.dom.minidom._clone_node(child, deep, newOwnerDocument)
clone.appendChild(c)
elif node.nodeType == xml.dom.minidom.Node.TEXT_NODE:
clone = newOwnerDocument.createTextNode(node.data)
elif node.nodeType == xml.dom.minidom.Node.CDATA_SECTION_NODE:
clone = newOwnerDocument.createCDATASection(node.data)
elif node.nodeType == xml.dom.minidom.Node.PROCESSING_INSTRUCTION_NODE:
clone = newOwnerDocument.createProcessingInstruction(node.target,
node.data)
elif node.nodeType == xml.dom.minidom.Node.COMMENT_NODE:
clone = newOwnerDocument.createComment(node.data)
elif node.nodeType == xml.dom.minidom.Node.ATTRIBUTE_NODE:
clone = newOwnerDocument.createAttributeNS(node.namespaceURI,
node.nodeName)
clone.specified = True
clone.value = node.value
elif node.nodeType == xml.dom.minidom.Node.DOCUMENT_TYPE_NODE:
assert node.ownerDocument is not newOwnerDocument
operation = xml.dom.UserDataHandler.NODE_IMPORTED
clone = newOwnerDocument.implementation.createDocumentType(
node.name, node.publicId, node.systemId)
clone.ownerDocument = newOwnerDocument
if deep:
clone.entities._seq = []
clone.notations._seq = []
for n in node.notations._seq:
notation = xml.dom.minidom.Notation(n.nodeName, n.publicId, n.systemId)
notation.ownerDocument = newOwnerDocument
clone.notations._seq.append(notation)
if hasattr(n, '_call_user_data_handler'):
n._call_user_data_handler(operation, n, notation)
for e in node.entities._seq:
entity = xml.dom.minidom.Entity(e.nodeName, e.publicId, e.systemId,
e.notationName)
entity.actualEncoding = e.actualEncoding
entity.encoding = e.encoding
entity.version = e.version
entity.ownerDocument = newOwnerDocument
clone.entities._seq.append(entity)
if hasattr(e, '_call_user_data_handler'):
e._call_user_data_handler(operation, n, entity)
else:
# Note the cloning of Document and DocumentType nodes is
# implemenetation specific. minidom handles those cases
# directly in the cloneNode() methods.
raise xml.dom.NotSupportedErr("Cannot clone node %s" % repr(node))
# Check for _call_user_data_handler() since this could conceivably
# used with other DOM implementations (one of the FourThought
# DOMs, perhaps?).
if hasattr(node, '_call_user_data_handler'):
node._call_user_data_handler(operation, node, clone)
return clone
xml.dom.minidom._clone_node = _clone_node | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/ZSI/wstools/Utility.py | Utility.py |
_copyright = '''Copyright 2001, Zolera Systems Inc. All Rights Reserved.
Copyright 2001, MIT. All Rights Reserved.
Distributed under the terms of:
Python 2.0 License or later.
http://www.python.org/2.0.1/license.html
or
W3C Software License
http://www.w3.org/Consortium/Legal/copyright-software-19980720
'''
import string
from xml.dom import Node
try:
from xml.ns import XMLNS
except:
class XMLNS:
BASE = "http://www.w3.org/2000/xmlns/"
XML = "http://www.w3.org/XML/1998/namespace"
try:
import cStringIO
StringIO = cStringIO
except ImportError:
import StringIO
_attrs = lambda E: (E.attributes and E.attributes.values()) or []
_children = lambda E: E.childNodes or []
_IN_XML_NS = lambda n: n.name.startswith("xmlns")
_inclusive = lambda n: n.unsuppressedPrefixes == None
# Does a document/PI has lesser/greater document order than the
# first element?
_LesserElement, _Element, _GreaterElement = range(3)
def _sorter(n1,n2):
'''_sorter(n1,n2) -> int
Sorting predicate for non-NS attributes.'''
i = cmp(n1.namespaceURI, n2.namespaceURI)
if i: return i
return cmp(n1.localName, n2.localName)
def _sorter_ns(n1,n2):
'''_sorter_ns((n,v),(n,v)) -> int
"(an empty namespace URI is lexicographically least)."'''
if n1[0] == 'xmlns': return -1
if n2[0] == 'xmlns': return 1
return cmp(n1[0], n2[0])
def _utilized(n, node, other_attrs, unsuppressedPrefixes):
'''_utilized(n, node, other_attrs, unsuppressedPrefixes) -> boolean
Return true if that nodespace is utilized within the node'''
if n.startswith('xmlns:'):
n = n[6:]
elif n.startswith('xmlns'):
n = n[5:]
if (n=="" and node.prefix in ["#default", None]) or \
n == node.prefix or n in unsuppressedPrefixes:
return 1
for attr in other_attrs:
if n == attr.prefix: return 1
# For exclusive need to look at attributes
if unsuppressedPrefixes is not None:
for attr in _attrs(node):
if n == attr.prefix: return 1
return 0
def _inclusiveNamespacePrefixes(node, context, unsuppressedPrefixes):
'''http://www.w3.org/TR/xml-exc-c14n/
InclusiveNamespaces PrefixList parameter, which lists namespace prefixes that
are handled in the manner described by the Canonical XML Recommendation'''
inclusive = []
if node.prefix:
usedPrefixes = ['xmlns:%s' %node.prefix]
else:
usedPrefixes = ['xmlns']
for a in _attrs(node):
if a.nodeName.startswith('xmlns') or not a.prefix: continue
usedPrefixes.append('xmlns:%s' %a.prefix)
unused_namespace_dict = {}
for attr in context:
n = attr.nodeName
if n in unsuppressedPrefixes:
inclusive.append(attr)
elif n.startswith('xmlns:') and n[6:] in unsuppressedPrefixes:
inclusive.append(attr)
elif n.startswith('xmlns') and n[5:] in unsuppressedPrefixes:
inclusive.append(attr)
elif attr.nodeName in usedPrefixes:
inclusive.append(attr)
elif n.startswith('xmlns:'):
unused_namespace_dict[n] = attr.value
return inclusive, unused_namespace_dict
#_in_subset = lambda subset, node: not subset or node in subset
_in_subset = lambda subset, node: subset is None or node in subset # rich's tweak
class _implementation:
'''Implementation class for C14N. This accompanies a node during it's
processing and includes the parameters and processing state.'''
# Handler for each node type; populated during module instantiation.
handlers = {}
def __init__(self, node, write, **kw):
'''Create and run the implementation.'''
self.write = write
self.subset = kw.get('subset')
self.comments = kw.get('comments', 0)
self.unsuppressedPrefixes = kw.get('unsuppressedPrefixes')
nsdict = kw.get('nsdict', { 'xml': XMLNS.XML, 'xmlns': XMLNS.BASE })
# Processing state.
self.state = (nsdict, {'xml':''}, {}, {}) #0422
if node.nodeType == Node.DOCUMENT_NODE:
self._do_document(node)
elif node.nodeType == Node.ELEMENT_NODE:
self.documentOrder = _Element # At document element
if not _inclusive(self):
inherited,unused = _inclusiveNamespacePrefixes(node, self._inherit_context(node),
self.unsuppressedPrefixes)
self._do_element(node, inherited, unused=unused)
else:
inherited = self._inherit_context(node)
self._do_element(node, inherited)
elif node.nodeType == Node.DOCUMENT_TYPE_NODE:
pass
else:
raise TypeError, str(node)
def _inherit_context(self, node):
'''_inherit_context(self, node) -> list
Scan ancestors of attribute and namespace context. Used only
for single element node canonicalization, not for subset
canonicalization.'''
# Collect the initial list of xml:foo attributes.
xmlattrs = filter(_IN_XML_NS, _attrs(node))
# Walk up and get all xml:XXX attributes we inherit.
inherited, parent = [], node.parentNode
while parent and parent.nodeType == Node.ELEMENT_NODE:
for a in filter(_IN_XML_NS, _attrs(parent)):
n = a.localName
if n not in xmlattrs:
xmlattrs.append(n)
inherited.append(a)
parent = parent.parentNode
return inherited
def _do_document(self, node):
'''_do_document(self, node) -> None
Process a document node. documentOrder holds whether the document
element has been encountered such that PIs/comments can be written
as specified.'''
self.documentOrder = _LesserElement
for child in node.childNodes:
if child.nodeType == Node.ELEMENT_NODE:
self.documentOrder = _Element # At document element
self._do_element(child)
self.documentOrder = _GreaterElement # After document element
elif child.nodeType == Node.PROCESSING_INSTRUCTION_NODE:
self._do_pi(child)
elif child.nodeType == Node.COMMENT_NODE:
self._do_comment(child)
elif child.nodeType == Node.DOCUMENT_TYPE_NODE:
pass
else:
raise TypeError, str(child)
handlers[Node.DOCUMENT_NODE] = _do_document
def _do_text(self, node):
'''_do_text(self, node) -> None
Process a text or CDATA node. Render various special characters
as their C14N entity representations.'''
if not _in_subset(self.subset, node): return
s = string.replace(node.data, "&", "&")
s = string.replace(s, "<", "<")
s = string.replace(s, ">", ">")
s = string.replace(s, "\015", "
")
if s: self.write(s)
handlers[Node.TEXT_NODE] = _do_text
handlers[Node.CDATA_SECTION_NODE] = _do_text
def _do_pi(self, node):
'''_do_pi(self, node) -> None
Process a PI node. Render a leading or trailing #xA if the
document order of the PI is greater or lesser (respectively)
than the document element.
'''
if not _in_subset(self.subset, node): return
W = self.write
if self.documentOrder == _GreaterElement: W('\n')
W('<?')
W(node.nodeName)
s = node.data
if s:
W(' ')
W(s)
W('?>')
if self.documentOrder == _LesserElement: W('\n')
handlers[Node.PROCESSING_INSTRUCTION_NODE] = _do_pi
def _do_comment(self, node):
'''_do_comment(self, node) -> None
Process a comment node. Render a leading or trailing #xA if the
document order of the comment is greater or lesser (respectively)
than the document element.
'''
if not _in_subset(self.subset, node): return
if self.comments:
W = self.write
if self.documentOrder == _GreaterElement: W('\n')
W('<!--')
W(node.data)
W('-->')
if self.documentOrder == _LesserElement: W('\n')
handlers[Node.COMMENT_NODE] = _do_comment
def _do_attr(self, n, value):
''''_do_attr(self, node) -> None
Process an attribute.'''
W = self.write
W(' ')
W(n)
W('="')
s = string.replace(value, "&", "&")
s = string.replace(s, "<", "<")
s = string.replace(s, '"', '"')
s = string.replace(s, '\011', '	')
s = string.replace(s, '\012', '
')
s = string.replace(s, '\015', '
')
W(s)
W('"')
def _do_element(self, node, initial_other_attrs = [], unused = None):
'''_do_element(self, node, initial_other_attrs = [], unused = {}) -> None
Process an element (and its children).'''
# Get state (from the stack) make local copies.
# ns_parent -- NS declarations in parent
# ns_rendered -- NS nodes rendered by ancestors
# ns_local -- NS declarations relevant to this element
# xml_attrs -- Attributes in XML namespace from parent
# xml_attrs_local -- Local attributes in XML namespace.
# ns_unused_inherited -- not rendered namespaces, used for exclusive
ns_parent, ns_rendered, xml_attrs = \
self.state[0], self.state[1].copy(), self.state[2].copy() #0422
ns_unused_inherited = unused
if unused is None:
ns_unused_inherited = self.state[3].copy()
ns_local = ns_parent.copy()
inclusive = _inclusive(self)
xml_attrs_local = {}
# Divide attributes into NS, XML, and others.
other_attrs = []
in_subset = _in_subset(self.subset, node)
for a in initial_other_attrs + _attrs(node):
if a.namespaceURI == XMLNS.BASE:
n = a.nodeName
if n == "xmlns:": n = "xmlns" # DOM bug workaround
ns_local[n] = a.nodeValue
elif a.namespaceURI == XMLNS.XML:
if inclusive or (in_subset and _in_subset(self.subset, a)): #020925 Test to see if attribute node in subset
xml_attrs_local[a.nodeName] = a #0426
else:
if _in_subset(self.subset, a): #020925 Test to see if attribute node in subset
other_attrs.append(a)
# # TODO: exclusive, might need to define xmlns:prefix here
# if not inclusive and a.prefix is not None and not ns_rendered.has_key('xmlns:%s' %a.prefix):
# ns_local['xmlns:%s' %a.prefix] = ??
#add local xml:foo attributes to ancestor's xml:foo attributes
xml_attrs.update(xml_attrs_local)
# Render the node
W, name = self.write, None
if in_subset:
name = node.nodeName
if not inclusive:
if node.prefix is not None:
prefix = 'xmlns:%s' %node.prefix
else:
prefix = 'xmlns'
if not ns_rendered.has_key(prefix) and not ns_local.has_key(prefix):
if not ns_unused_inherited.has_key(prefix):
raise RuntimeError,\
'For exclusive c14n, unable to map prefix "%s" in %s' %(
prefix, node)
ns_local[prefix] = ns_unused_inherited[prefix]
del ns_unused_inherited[prefix]
W('<')
W(name)
# Create list of NS attributes to render.
ns_to_render = []
for n,v in ns_local.items():
# If default namespace is XMLNS.BASE or empty,
# and if an ancestor was the same
if n == "xmlns" and v in [ XMLNS.BASE, '' ] \
and ns_rendered.get('xmlns') in [ XMLNS.BASE, '', None ]:
continue
# "omit namespace node with local name xml, which defines
# the xml prefix, if its string value is
# http://www.w3.org/XML/1998/namespace."
if n in ["xmlns:xml", "xml"] \
and v in [ 'http://www.w3.org/XML/1998/namespace' ]:
continue
# If not previously rendered
# and it's inclusive or utilized
if (n,v) not in ns_rendered.items():
if inclusive or _utilized(n, node, other_attrs, self.unsuppressedPrefixes):
ns_to_render.append((n, v))
elif not inclusive:
ns_unused_inherited[n] = v
# Sort and render the ns, marking what was rendered.
ns_to_render.sort(_sorter_ns)
for n,v in ns_to_render:
self._do_attr(n, v)
ns_rendered[n]=v #0417
# If exclusive or the parent is in the subset, add the local xml attributes
# Else, add all local and ancestor xml attributes
# Sort and render the attributes.
if not inclusive or _in_subset(self.subset,node.parentNode): #0426
other_attrs.extend(xml_attrs_local.values())
else:
other_attrs.extend(xml_attrs.values())
other_attrs.sort(_sorter)
for a in other_attrs:
self._do_attr(a.nodeName, a.value)
W('>')
# Push state, recurse, pop state.
state, self.state = self.state, (ns_local, ns_rendered, xml_attrs, ns_unused_inherited)
for c in _children(node):
_implementation.handlers[c.nodeType](self, c)
self.state = state
if name: W('</%s>' % name)
handlers[Node.ELEMENT_NODE] = _do_element
def Canonicalize(node, output=None, **kw):
'''Canonicalize(node, output=None, **kw) -> UTF-8
Canonicalize a DOM document/element node and all descendents.
Return the text; if output is specified then output.write will
be called to output the text and None will be returned
Keyword parameters:
nsdict: a dictionary of prefix:uri namespace entries
assumed to exist in the surrounding context
comments: keep comments if non-zero (default is 0)
subset: Canonical XML subsetting resulting from XPath
(default is [])
unsuppressedPrefixes: do exclusive C14N, and this specifies the
prefixes that should be inherited.
'''
if output:
apply(_implementation, (node, output.write), kw)
else:
s = StringIO.StringIO()
apply(_implementation, (node, s.write), kw)
return s.getvalue() | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/ZSI/wstools/c14n.py | c14n.py |
ident = "$Id: WSDLTools.py 1122 2006-02-04 01:24:50Z boverhof $"
import weakref
from cStringIO import StringIO
from Namespaces import OASIS, XMLNS, WSA, WSA_LIST, WSRF_V1_2, WSRF
from Utility import Collection, CollectionNS, DOM, ElementProxy, basejoin
from XMLSchema import XMLSchema, SchemaReader, WSDLToolsAdapter
class WSDLReader:
"""A WSDLReader creates WSDL instances from urls and xml data."""
# Custom subclasses of WSDLReader may wish to implement a caching
# strategy or other optimizations. Because application needs vary
# so widely, we don't try to provide any caching by default.
def loadFromStream(self, stream, name=None):
"""Return a WSDL instance loaded from a stream object."""
document = DOM.loadDocument(stream)
wsdl = WSDL()
if name:
wsdl.location = name
elif hasattr(stream, 'name'):
wsdl.location = stream.name
wsdl.load(document)
return wsdl
def loadFromURL(self, url):
"""Return a WSDL instance loaded from the given url."""
document = DOM.loadFromURL(url)
wsdl = WSDL()
wsdl.location = url
wsdl.load(document)
return wsdl
def loadFromString(self, data):
"""Return a WSDL instance loaded from an xml string."""
return self.loadFromStream(StringIO(data))
def loadFromFile(self, filename):
"""Return a WSDL instance loaded from the given file."""
file = open(filename, 'rb')
try:
wsdl = self.loadFromStream(file)
finally:
file.close()
return wsdl
class WSDL:
"""A WSDL object models a WSDL service description. WSDL objects
may be created manually or loaded from an xml representation
using a WSDLReader instance."""
def __init__(self, targetNamespace=None, strict=1):
self.targetNamespace = targetNamespace or 'urn:this-document.wsdl'
self.documentation = ''
self.location = None
self.document = None
self.name = None
self.services = CollectionNS(self)
self.messages = CollectionNS(self)
self.portTypes = CollectionNS(self)
self.bindings = CollectionNS(self)
self.imports = Collection(self)
self.types = Types(self)
self.extensions = []
self.strict = strict
def __del__(self):
if self.document is not None:
self.document.unlink()
version = '1.1'
def addService(self, name, documentation='', targetNamespace=None):
if self.services.has_key(name):
raise WSDLError(
'Duplicate service element: %s' % name
)
item = Service(name, documentation)
if targetNamespace:
item.targetNamespace = targetNamespace
self.services[name] = item
return item
def addMessage(self, name, documentation='', targetNamespace=None):
if self.messages.has_key(name):
raise WSDLError(
'Duplicate message element: %s.' % name
)
item = Message(name, documentation)
if targetNamespace:
item.targetNamespace = targetNamespace
self.messages[name] = item
return item
def addPortType(self, name, documentation='', targetNamespace=None):
if self.portTypes.has_key(name):
raise WSDLError(
'Duplicate portType element: name'
)
item = PortType(name, documentation)
if targetNamespace:
item.targetNamespace = targetNamespace
self.portTypes[name] = item
return item
def addBinding(self, name, type, documentation='', targetNamespace=None):
if self.bindings.has_key(name):
raise WSDLError(
'Duplicate binding element: %s' % name
)
item = Binding(name, type, documentation)
if targetNamespace:
item.targetNamespace = targetNamespace
self.bindings[name] = item
return item
def addImport(self, namespace, location):
item = ImportElement(namespace, location)
self.imports[namespace] = item
return item
def toDom(self):
""" Generate a DOM representation of the WSDL instance.
Not dealing with generating XML Schema, thus the targetNamespace
of all XML Schema elements or types used by WSDL message parts
needs to be specified via import information items.
"""
namespaceURI = DOM.GetWSDLUri(self.version)
self.document = DOM.createDocument(namespaceURI ,'wsdl:definitions')
# Set up a couple prefixes for easy reading.
child = DOM.getElement(self.document, None)
child.setAttributeNS(None, 'targetNamespace', self.targetNamespace)
child.setAttributeNS(XMLNS.BASE, 'xmlns:wsdl', namespaceURI)
child.setAttributeNS(XMLNS.BASE, 'xmlns:xsd', 'http://www.w3.org/1999/XMLSchema')
child.setAttributeNS(XMLNS.BASE, 'xmlns:soap', 'http://schemas.xmlsoap.org/wsdl/soap/')
child.setAttributeNS(XMLNS.BASE, 'xmlns:tns', self.targetNamespace)
if self.name:
child.setAttributeNS(None, 'name', self.name)
# wsdl:import
for item in self.imports:
item.toDom()
# wsdl:message
for item in self.messages:
item.toDom()
# wsdl:portType
for item in self.portTypes:
item.toDom()
# wsdl:binding
for item in self.bindings:
item.toDom()
# wsdl:service
for item in self.services:
item.toDom()
def load(self, document):
# We save a reference to the DOM document to ensure that elements
# saved as "extensions" will continue to have a meaningful context
# for things like namespace references. The lifetime of the DOM
# document is bound to the lifetime of the WSDL instance.
self.document = document
definitions = DOM.getElement(document, 'definitions', None, None)
if definitions is None:
raise WSDLError(
'Missing <definitions> element.'
)
self.version = DOM.WSDLUriToVersion(definitions.namespaceURI)
NS_WSDL = DOM.GetWSDLUri(self.version)
self.targetNamespace = DOM.getAttr(definitions, 'targetNamespace',
None, None)
self.name = DOM.getAttr(definitions, 'name', None, None)
self.documentation = GetDocumentation(definitions)
#
# Retrieve all <wsdl:import>'s, append all children of imported
# document to main document. First iteration grab all original
# <wsdl:import>'s from document, second iteration grab all
# "imported" <wsdl:imports> from document, etc break out when
# no more <wsdl:import>'s.
#
imported = []
base_location = self.location
do_it = True
while do_it:
do_it = False
for element in DOM.getElements(definitions, 'import', NS_WSDL):
location = DOM.getAttr(element, 'location')
if base_location is not None:
location = basejoin(base_location, location)
if location not in imported:
do_it = True
self._import(document, element, base_location)
imported.append(location)
else:
definitions.removeChild(element)
base_location = None
#
# No more <wsdl:import>'s, now load up all other
# WSDL information items.
#
for element in DOM.getElements(definitions, None, None):
targetNamespace = DOM.getAttr(element, 'targetNamespace')
localName = element.localName
if not DOM.nsUriMatch(element.namespaceURI, NS_WSDL):
if localName == 'schema':
tns = DOM.getAttr(element, 'targetNamespace')
reader = SchemaReader(base_url=self.imports[tns].location)
schema = reader.loadFromNode(WSDLToolsAdapter(self),
element)
# schema.setBaseUrl(self.location)
self.types.addSchema(schema)
else:
self.extensions.append(element)
continue
elif localName == 'message':
name = DOM.getAttr(element, 'name')
docs = GetDocumentation(element)
message = self.addMessage(name, docs, targetNamespace)
parts = DOM.getElements(element, 'part', NS_WSDL)
message.load(parts)
continue
elif localName == 'portType':
name = DOM.getAttr(element, 'name')
docs = GetDocumentation(element)
ptype = self.addPortType(name, docs, targetNamespace)
#operations = DOM.getElements(element, 'operation', NS_WSDL)
#ptype.load(operations)
ptype.load(element)
continue
elif localName == 'binding':
name = DOM.getAttr(element, 'name')
type = DOM.getAttr(element, 'type', default=None)
if type is None:
raise WSDLError(
'Missing type attribute for binding %s.' % name
)
type = ParseQName(type, element)
docs = GetDocumentation(element)
binding = self.addBinding(name, type, docs, targetNamespace)
operations = DOM.getElements(element, 'operation', NS_WSDL)
binding.load(operations)
binding.load_ex(GetExtensions(element))
continue
elif localName == 'service':
name = DOM.getAttr(element, 'name')
docs = GetDocumentation(element)
service = self.addService(name, docs, targetNamespace)
ports = DOM.getElements(element, 'port', NS_WSDL)
service.load(ports)
service.load_ex(GetExtensions(element))
continue
elif localName == 'types':
self.types.documentation = GetDocumentation(element)
base_location = DOM.getAttr(element, 'base-location')
if base_location:
element.removeAttribute('base-location')
base_location = base_location or self.location
reader = SchemaReader(base_url=base_location)
for item in DOM.getElements(element, None, None):
if item.localName == 'schema':
schema = reader.loadFromNode(WSDLToolsAdapter(self), item)
# XXX <types> could have been imported
#schema.setBaseUrl(self.location)
schema.setBaseUrl(base_location)
self.types.addSchema(schema)
else:
self.types.addExtension(item)
# XXX remove the attribute
# element.removeAttribute('base-location')
continue
def _import(self, document, element, base_location=None):
'''Algo take <import> element's children, clone them,
and add them to the main document. Support for relative
locations is a bit complicated. The orig document context
is lost, so we need to store base location in DOM elements
representing <types>, by creating a special temporary
"base-location" attribute, and <import>, by resolving
the relative "location" and storing it as "location".
document -- document we are loading
element -- DOM Element representing <import>
base_location -- location of document from which this
<import> was gleaned.
'''
namespace = DOM.getAttr(element, 'namespace', default=None)
location = DOM.getAttr(element, 'location', default=None)
if namespace is None or location is None:
raise WSDLError(
'Invalid import element (missing namespace or location).'
)
if base_location:
location = basejoin(base_location, location)
element.setAttributeNS(None, 'location', location)
obimport = self.addImport(namespace, location)
obimport._loaded = 1
importdoc = DOM.loadFromURL(location)
try:
if location.find('#') > -1:
idref = location.split('#')[-1]
imported = DOM.getElementById(importdoc, idref)
else:
imported = importdoc.documentElement
if imported is None:
raise WSDLError(
'Import target element not found for: %s' % location
)
imported_tns = DOM.findTargetNS(imported)
if imported_tns != namespace:
return
if imported.localName == 'definitions':
imported_nodes = imported.childNodes
else:
imported_nodes = [imported]
parent = element.parentNode
parent.removeChild(element)
for node in imported_nodes:
if node.nodeType != node.ELEMENT_NODE:
continue
child = DOM.importNode(document, node, 1)
parent.appendChild(child)
child.setAttribute('targetNamespace', namespace)
attrsNS = imported._attrsNS
for attrkey in attrsNS.keys():
if attrkey[0] == DOM.NS_XMLNS:
attr = attrsNS[attrkey].cloneNode(1)
child.setAttributeNode(attr)
#XXX Quick Hack, should be in WSDL Namespace.
if child.localName == 'import':
rlocation = child.getAttributeNS(None, 'location')
alocation = basejoin(location, rlocation)
child.setAttribute('location', alocation)
elif child.localName == 'types':
child.setAttribute('base-location', location)
finally:
importdoc.unlink()
return location
class Element:
"""A class that provides common functions for WSDL element classes."""
def __init__(self, name=None, documentation=''):
self.name = name
self.documentation = documentation
self.extensions = []
def addExtension(self, item):
item.parent = weakref.ref(self)
self.extensions.append(item)
def getWSDL(self):
"""Return the WSDL object that contains this information item."""
parent = self
while 1:
# skip any collections
if isinstance(parent, WSDL):
return parent
try: parent = parent.parent()
except: break
return None
class ImportElement(Element):
def __init__(self, namespace, location):
self.namespace = namespace
self.location = location
# def getWSDL(self):
# """Return the WSDL object that contains this Message Part."""
# return self.parent().parent()
def toDom(self):
wsdl = self.getWSDL()
ep = ElementProxy(None, DOM.getElement(wsdl.document, None))
epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), 'import')
epc.setAttributeNS(None, 'namespace', self.namespace)
epc.setAttributeNS(None, 'location', self.location)
_loaded = None
class Types(Collection):
default = lambda self,k: k.targetNamespace
def __init__(self, parent):
Collection.__init__(self, parent)
self.documentation = ''
self.extensions = []
def addSchema(self, schema):
name = schema.targetNamespace
self[name] = schema
return schema
def addExtension(self, item):
self.extensions.append(item)
class Message(Element):
def __init__(self, name, documentation=''):
Element.__init__(self, name, documentation)
self.parts = Collection(self)
def addPart(self, name, type=None, element=None):
if self.parts.has_key(name):
raise WSDLError(
'Duplicate message part element: %s' % name
)
if type is None and element is None:
raise WSDLError(
'Missing type or element attribute for part: %s' % name
)
item = MessagePart(name)
item.element = element
item.type = type
self.parts[name] = item
return item
def load(self, elements):
for element in elements:
name = DOM.getAttr(element, 'name')
part = MessagePart(name)
self.parts[name] = part
elemref = DOM.getAttr(element, 'element', default=None)
typeref = DOM.getAttr(element, 'type', default=None)
if typeref is None and elemref is None:
raise WSDLError(
'No type or element attribute for part: %s' % name
)
if typeref is not None:
part.type = ParseTypeRef(typeref, element)
if elemref is not None:
part.element = ParseTypeRef(elemref, element)
# def getElementDeclaration(self):
# """Return the XMLSchema.ElementDeclaration instance or None"""
# element = None
# if self.element:
# nsuri,name = self.element
# wsdl = self.getWSDL()
# if wsdl.types.has_key(nsuri) and wsdl.types[nsuri].elements.has_key(name):
# element = wsdl.types[nsuri].elements[name]
# return element
#
# def getTypeDefinition(self):
# """Return the XMLSchema.TypeDefinition instance or None"""
# type = None
# if self.type:
# nsuri,name = self.type
# wsdl = self.getWSDL()
# if wsdl.types.has_key(nsuri) and wsdl.types[nsuri].types.has_key(name):
# type = wsdl.types[nsuri].types[name]
# return type
# def getWSDL(self):
# """Return the WSDL object that contains this Message Part."""
# return self.parent().parent()
def toDom(self):
wsdl = self.getWSDL()
ep = ElementProxy(None, DOM.getElement(wsdl.document, None))
epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), 'message')
epc.setAttributeNS(None, 'name', self.name)
for part in self.parts:
part.toDom(epc._getNode())
class MessagePart(Element):
def __init__(self, name):
Element.__init__(self, name, '')
self.element = None
self.type = None
# def getWSDL(self):
# """Return the WSDL object that contains this Message Part."""
# return self.parent().parent().parent().parent()
def getTypeDefinition(self):
wsdl = self.getWSDL()
nsuri,name = self.type
schema = wsdl.types.get(nsuri, {})
return schema.get(name)
def getElementDeclaration(self):
wsdl = self.getWSDL()
nsuri,name = self.element
schema = wsdl.types.get(nsuri, {})
return schema.get(name)
def toDom(self, node):
"""node -- node representing message"""
wsdl = self.getWSDL()
ep = ElementProxy(None, node)
epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), 'part')
epc.setAttributeNS(None, 'name', self.name)
if self.element is not None:
ns,name = self.element
prefix = epc.getPrefix(ns)
epc.setAttributeNS(None, 'element', '%s:%s'%(prefix,name))
elif self.type is not None:
ns,name = self.type
prefix = epc.getPrefix(ns)
epc.setAttributeNS(None, 'type', '%s:%s'%(prefix,name))
class PortType(Element):
'''PortType has a anyAttribute, thus must provide for an extensible
mechanism for supporting such attributes. ResourceProperties is
specified in WS-ResourceProperties. wsa:Action is specified in
WS-Address.
Instance Data:
name -- name attribute
resourceProperties -- optional. wsr:ResourceProperties attribute,
value is a QName this is Parsed into a (namespaceURI, name)
that represents a Global Element Declaration.
operations
'''
def __init__(self, name, documentation=''):
Element.__init__(self, name, documentation)
self.operations = Collection(self)
self.resourceProperties = None
# def getWSDL(self):
# return self.parent().parent()
def getTargetNamespace(self):
return self.targetNamespace or self.getWSDL().targetNamespace
def getResourceProperties(self):
return self.resourceProperties
def addOperation(self, name, documentation='', parameterOrder=None):
item = Operation(name, documentation, parameterOrder)
self.operations[name] = item
return item
def load(self, element):
self.name = DOM.getAttr(element, 'name')
self.documentation = GetDocumentation(element)
self.targetNamespace = DOM.getAttr(element, 'targetNamespace')
for nsuri in WSRF_V1_2.PROPERTIES.XSD_LIST:
if DOM.hasAttr(element, 'ResourceProperties', nsuri):
rpref = DOM.getAttr(element, 'ResourceProperties', nsuri)
self.resourceProperties = ParseQName(rpref, element)
NS_WSDL = DOM.GetWSDLUri(self.getWSDL().version)
elements = DOM.getElements(element, 'operation', NS_WSDL)
for element in elements:
name = DOM.getAttr(element, 'name')
docs = GetDocumentation(element)
param_order = DOM.getAttr(element, 'parameterOrder', default=None)
if param_order is not None:
param_order = param_order.split(' ')
operation = self.addOperation(name, docs, param_order)
item = DOM.getElement(element, 'input', None, None)
if item is not None:
name = DOM.getAttr(item, 'name')
docs = GetDocumentation(item)
msgref = DOM.getAttr(item, 'message')
message = ParseQName(msgref, item)
for WSA in WSA_LIST:
action = DOM.getAttr(item, 'Action', WSA.ADDRESS, None)
if action: break
operation.setInput(message, name, docs, action)
item = DOM.getElement(element, 'output', None, None)
if item is not None:
name = DOM.getAttr(item, 'name')
docs = GetDocumentation(item)
msgref = DOM.getAttr(item, 'message')
message = ParseQName(msgref, item)
for WSA in WSA_LIST:
action = DOM.getAttr(item, 'Action', WSA.ADDRESS, None)
if action: break
operation.setOutput(message, name, docs, action)
for item in DOM.getElements(element, 'fault', None):
name = DOM.getAttr(item, 'name')
docs = GetDocumentation(item)
msgref = DOM.getAttr(item, 'message')
message = ParseQName(msgref, item)
for WSA in WSA_LIST:
action = DOM.getAttr(item, 'Action', WSA.ADDRESS, None)
if action: break
operation.addFault(message, name, docs, action)
def toDom(self):
wsdl = self.getWSDL()
ep = ElementProxy(None, DOM.getElement(wsdl.document, None))
epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), 'portType')
epc.setAttributeNS(None, 'name', self.name)
if self.resourceProperties:
ns,name = self.resourceProperties
prefix = epc.getPrefix(ns)
epc.setAttributeNS(WSRF.PROPERTIES.LATEST, 'ResourceProperties',
'%s:%s'%(prefix,name))
for op in self.operations:
op.toDom(epc._getNode())
class Operation(Element):
def __init__(self, name, documentation='', parameterOrder=None):
Element.__init__(self, name, documentation)
self.parameterOrder = parameterOrder
self.faults = Collection(self)
self.input = None
self.output = None
def getWSDL(self):
"""Return the WSDL object that contains this Operation."""
return self.parent().parent().parent().parent()
def getPortType(self):
return self.parent().parent()
def getInputAction(self):
"""wsa:Action attribute"""
return GetWSAActionInput(self)
def getInputMessage(self):
if self.input is None:
return None
wsdl = self.getPortType().getWSDL()
return wsdl.messages[self.input.message]
def getOutputAction(self):
"""wsa:Action attribute"""
return GetWSAActionOutput(self)
def getOutputMessage(self):
if self.output is None:
return None
wsdl = self.getPortType().getWSDL()
return wsdl.messages[self.output.message]
def getFaultAction(self, name):
"""wsa:Action attribute"""
return GetWSAActionFault(self, name)
def getFaultMessage(self, name):
wsdl = self.getPortType().getWSDL()
return wsdl.messages[self.faults[name].message]
def addFault(self, message, name, documentation='', action=None):
if self.faults.has_key(name):
raise WSDLError(
'Duplicate fault element: %s' % name
)
item = MessageRole('fault', message, name, documentation, action)
self.faults[name] = item
return item
def setInput(self, message, name='', documentation='', action=None):
self.input = MessageRole('input', message, name, documentation, action)
self.input.parent = weakref.ref(self)
return self.input
def setOutput(self, message, name='', documentation='', action=None):
self.output = MessageRole('output', message, name, documentation, action)
self.output.parent = weakref.ref(self)
return self.output
def toDom(self, node):
wsdl = self.getWSDL()
ep = ElementProxy(None, node)
epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), 'operation')
epc.setAttributeNS(None, 'name', self.name)
node = epc._getNode()
if self.input:
self.input.toDom(node)
if self.output:
self.output.toDom(node)
for fault in self.faults:
fault.toDom(node)
class MessageRole(Element):
def __init__(self, type, message, name='', documentation='', action=None):
Element.__init__(self, name, documentation)
self.message = message
self.type = type
self.action = action
def getWSDL(self):
"""Return the WSDL object that contains this information item."""
parent = self
while 1:
# skip any collections
if isinstance(parent, WSDL):
return parent
try: parent = parent.parent()
except: break
return None
def getMessage(self):
"""Return the WSDL object that represents the attribute message
(namespaceURI, name) tuple
"""
wsdl = self.getWSDL()
return wsdl.messages[self.message]
def toDom(self, node):
wsdl = self.getWSDL()
ep = ElementProxy(None, node)
epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), self.type)
if not isinstance(self.message, basestring) and len(self.message) == 2:
ns,name = self.message
prefix = epc.getPrefix(ns)
epc.setAttributeNS(None, 'message', '%s:%s' %(prefix,name))
else:
epc.setAttributeNS(None, 'message', self.message)
if self.action:
epc.setAttributeNS(WSA.ADDRESS, 'Action', self.action)
if self.name:
epc.setAttributeNS(None, 'name', self.name)
class Binding(Element):
def __init__(self, name, type, documentation=''):
Element.__init__(self, name, documentation)
self.operations = Collection(self)
self.type = type
# def getWSDL(self):
# """Return the WSDL object that contains this binding."""
# return self.parent().parent()
def getPortType(self):
"""Return the PortType object associated with this binding."""
return self.getWSDL().portTypes[self.type]
def findBinding(self, kind):
for item in self.extensions:
if isinstance(item, kind):
return item
return None
def findBindings(self, kind):
return [ item for item in self.extensions if isinstance(item, kind) ]
def addOperationBinding(self, name, documentation=''):
item = OperationBinding(name, documentation)
self.operations[name] = item
return item
def load(self, elements):
for element in elements:
name = DOM.getAttr(element, 'name')
docs = GetDocumentation(element)
opbinding = self.addOperationBinding(name, docs)
opbinding.load_ex(GetExtensions(element))
item = DOM.getElement(element, 'input', None, None)
if item is not None:
#TODO: addInputBinding?
mbinding = MessageRoleBinding('input')
mbinding.documentation = GetDocumentation(item)
opbinding.input = mbinding
mbinding.load_ex(GetExtensions(item))
mbinding.parent = weakref.ref(opbinding)
item = DOM.getElement(element, 'output', None, None)
if item is not None:
mbinding = MessageRoleBinding('output')
mbinding.documentation = GetDocumentation(item)
opbinding.output = mbinding
mbinding.load_ex(GetExtensions(item))
mbinding.parent = weakref.ref(opbinding)
for item in DOM.getElements(element, 'fault', None):
name = DOM.getAttr(item, 'name')
mbinding = MessageRoleBinding('fault', name)
mbinding.documentation = GetDocumentation(item)
opbinding.faults[name] = mbinding
mbinding.load_ex(GetExtensions(item))
mbinding.parent = weakref.ref(opbinding)
def load_ex(self, elements):
for e in elements:
ns, name = e.namespaceURI, e.localName
if ns in DOM.NS_SOAP_BINDING_ALL and name == 'binding':
transport = DOM.getAttr(e, 'transport', default=None)
style = DOM.getAttr(e, 'style', default='document')
ob = SoapBinding(transport, style)
self.addExtension(ob)
continue
elif ns in DOM.NS_HTTP_BINDING_ALL and name == 'binding':
verb = DOM.getAttr(e, 'verb')
ob = HttpBinding(verb)
self.addExtension(ob)
continue
else:
self.addExtension(e)
def toDom(self):
wsdl = self.getWSDL()
ep = ElementProxy(None, DOM.getElement(wsdl.document, None))
epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), 'binding')
epc.setAttributeNS(None, 'name', self.name)
ns,name = self.type
prefix = epc.getPrefix(ns)
epc.setAttributeNS(None, 'type', '%s:%s' %(prefix,name))
node = epc._getNode()
for ext in self.extensions:
ext.toDom(node)
for op_binding in self.operations:
op_binding.toDom(node)
class OperationBinding(Element):
def __init__(self, name, documentation=''):
Element.__init__(self, name, documentation)
self.input = None
self.output = None
self.faults = Collection(self)
# def getWSDL(self):
# """Return the WSDL object that contains this binding."""
# return self.parent().parent().parent().parent()
def getBinding(self):
"""Return the parent Binding object of the operation binding."""
return self.parent().parent()
def getOperation(self):
"""Return the abstract Operation associated with this binding."""
return self.getBinding().getPortType().operations[self.name]
def findBinding(self, kind):
for item in self.extensions:
if isinstance(item, kind):
return item
return None
def findBindings(self, kind):
return [ item for item in self.extensions if isinstance(item, kind) ]
def addInputBinding(self, binding):
if self.input is None:
self.input = MessageRoleBinding('input')
self.input.parent = weakref.ref(self)
self.input.addExtension(binding)
return binding
def addOutputBinding(self, binding):
if self.output is None:
self.output = MessageRoleBinding('output')
self.output.parent = weakref.ref(self)
self.output.addExtension(binding)
return binding
def addFaultBinding(self, name, binding):
fault = self.get(name, None)
if fault is None:
fault = MessageRoleBinding('fault', name)
fault.addExtension(binding)
return binding
def load_ex(self, elements):
for e in elements:
ns, name = e.namespaceURI, e.localName
if ns in DOM.NS_SOAP_BINDING_ALL and name == 'operation':
soapaction = DOM.getAttr(e, 'soapAction', default=None)
style = DOM.getAttr(e, 'style', default=None)
ob = SoapOperationBinding(soapaction, style)
self.addExtension(ob)
continue
elif ns in DOM.NS_HTTP_BINDING_ALL and name == 'operation':
location = DOM.getAttr(e, 'location')
ob = HttpOperationBinding(location)
self.addExtension(ob)
continue
else:
self.addExtension(e)
def toDom(self, node):
wsdl = self.getWSDL()
ep = ElementProxy(None, node)
epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), 'operation')
epc.setAttributeNS(None, 'name', self.name)
node = epc._getNode()
for ext in self.extensions:
ext.toDom(node)
if self.input:
self.input.toDom(node)
if self.output:
self.output.toDom(node)
for fault in self.faults:
fault.toDom(node)
class MessageRoleBinding(Element):
def __init__(self, type, name='', documentation=''):
Element.__init__(self, name, documentation)
self.type = type
def findBinding(self, kind):
for item in self.extensions:
if isinstance(item, kind):
return item
return None
def findBindings(self, kind):
return [ item for item in self.extensions if isinstance(item, kind) ]
def load_ex(self, elements):
for e in elements:
ns, name = e.namespaceURI, e.localName
if ns in DOM.NS_SOAP_BINDING_ALL and name == 'body':
encstyle = DOM.getAttr(e, 'encodingStyle', default=None)
namespace = DOM.getAttr(e, 'namespace', default=None)
parts = DOM.getAttr(e, 'parts', default=None)
use = DOM.getAttr(e, 'use', default=None)
if use is None:
raise WSDLError(
'Invalid soap:body binding element.'
)
ob = SoapBodyBinding(use, namespace, encstyle, parts)
self.addExtension(ob)
continue
elif ns in DOM.NS_SOAP_BINDING_ALL and name == 'fault':
encstyle = DOM.getAttr(e, 'encodingStyle', default=None)
namespace = DOM.getAttr(e, 'namespace', default=None)
name = DOM.getAttr(e, 'name', default=None)
use = DOM.getAttr(e, 'use', default=None)
if use is None or name is None:
raise WSDLError(
'Invalid soap:fault binding element.'
)
ob = SoapFaultBinding(name, use, namespace, encstyle)
self.addExtension(ob)
continue
elif ns in DOM.NS_SOAP_BINDING_ALL and name in (
'header', 'headerfault'
):
encstyle = DOM.getAttr(e, 'encodingStyle', default=None)
namespace = DOM.getAttr(e, 'namespace', default=None)
message = DOM.getAttr(e, 'message')
part = DOM.getAttr(e, 'part')
use = DOM.getAttr(e, 'use')
if name == 'header':
_class = SoapHeaderBinding
else:
_class = SoapHeaderFaultBinding
message = ParseQName(message, e)
ob = _class(message, part, use, namespace, encstyle)
self.addExtension(ob)
continue
elif ns in DOM.NS_HTTP_BINDING_ALL and name == 'urlReplacement':
ob = HttpUrlReplacementBinding()
self.addExtension(ob)
continue
elif ns in DOM.NS_HTTP_BINDING_ALL and name == 'urlEncoded':
ob = HttpUrlEncodedBinding()
self.addExtension(ob)
continue
elif ns in DOM.NS_MIME_BINDING_ALL and name == 'multipartRelated':
ob = MimeMultipartRelatedBinding()
self.addExtension(ob)
ob.load_ex(GetExtensions(e))
continue
elif ns in DOM.NS_MIME_BINDING_ALL and name == 'content':
part = DOM.getAttr(e, 'part', default=None)
type = DOM.getAttr(e, 'type', default=None)
ob = MimeContentBinding(part, type)
self.addExtension(ob)
continue
elif ns in DOM.NS_MIME_BINDING_ALL and name == 'mimeXml':
part = DOM.getAttr(e, 'part', default=None)
ob = MimeXmlBinding(part)
self.addExtension(ob)
continue
else:
self.addExtension(e)
def toDom(self, node):
wsdl = self.getWSDL()
ep = ElementProxy(None, node)
epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), self.type)
node = epc._getNode()
for item in self.extensions:
if item: item.toDom(node)
class Service(Element):
def __init__(self, name, documentation=''):
Element.__init__(self, name, documentation)
self.ports = Collection(self)
def getWSDL(self):
return self.parent().parent()
def addPort(self, name, binding, documentation=''):
item = Port(name, binding, documentation)
self.ports[name] = item
return item
def load(self, elements):
for element in elements:
name = DOM.getAttr(element, 'name', default=None)
docs = GetDocumentation(element)
binding = DOM.getAttr(element, 'binding', default=None)
if name is None or binding is None:
raise WSDLError(
'Invalid port element.'
)
binding = ParseQName(binding, element)
port = self.addPort(name, binding, docs)
port.load_ex(GetExtensions(element))
def load_ex(self, elements):
for e in elements:
self.addExtension(e)
def toDom(self):
wsdl = self.getWSDL()
ep = ElementProxy(None, DOM.getElement(wsdl.document, None))
epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), "service")
epc.setAttributeNS(None, "name", self.name)
node = epc._getNode()
for port in self.ports:
port.toDom(node)
class Port(Element):
def __init__(self, name, binding, documentation=''):
Element.__init__(self, name, documentation)
self.binding = binding
# def getWSDL(self):
# return self.parent().parent().getWSDL()
def getService(self):
"""Return the Service object associated with this port."""
return self.parent().parent()
def getBinding(self):
"""Return the Binding object that is referenced by this port."""
wsdl = self.getService().getWSDL()
return wsdl.bindings[self.binding]
def getPortType(self):
"""Return the PortType object that is referenced by this port."""
wsdl = self.getService().getWSDL()
binding = wsdl.bindings[self.binding]
return wsdl.portTypes[binding.type]
def getAddressBinding(self):
"""A convenience method to obtain the extension element used
as the address binding for the port."""
for item in self.extensions:
if isinstance(item, SoapAddressBinding) or \
isinstance(item, HttpAddressBinding):
return item
raise WSDLError(
'No address binding found in port.'
)
def load_ex(self, elements):
for e in elements:
ns, name = e.namespaceURI, e.localName
if ns in DOM.NS_SOAP_BINDING_ALL and name == 'address':
location = DOM.getAttr(e, 'location', default=None)
ob = SoapAddressBinding(location)
self.addExtension(ob)
continue
elif ns in DOM.NS_HTTP_BINDING_ALL and name == 'address':
location = DOM.getAttr(e, 'location', default=None)
ob = HttpAddressBinding(location)
self.addExtension(ob)
continue
else:
self.addExtension(e)
def toDom(self, node):
wsdl = self.getWSDL()
ep = ElementProxy(None, node)
epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), "port")
epc.setAttributeNS(None, "name", self.name)
ns,name = self.binding
prefix = epc.getPrefix(ns)
epc.setAttributeNS(None, "binding", "%s:%s" %(prefix,name))
node = epc._getNode()
for ext in self.extensions:
ext.toDom(node)
class SoapBinding:
def __init__(self, transport, style='rpc'):
self.transport = transport
self.style = style
def getWSDL(self):
return self.parent().getWSDL()
def toDom(self, node):
wsdl = self.getWSDL()
ep = ElementProxy(None, node)
epc = ep.createAppendElement(DOM.GetWSDLSoapBindingUri(wsdl.version), 'binding')
if self.transport:
epc.setAttributeNS(None, "transport", self.transport)
if self.style:
epc.setAttributeNS(None, "style", self.style)
class SoapAddressBinding:
def __init__(self, location):
self.location = location
def getWSDL(self):
return self.parent().getWSDL()
def toDom(self, node):
wsdl = self.getWSDL()
ep = ElementProxy(None, node)
epc = ep.createAppendElement(DOM.GetWSDLSoapBindingUri(wsdl.version), 'address')
epc.setAttributeNS(None, "location", self.location)
class SoapOperationBinding:
def __init__(self, soapAction=None, style=None):
self.soapAction = soapAction
self.style = style
def getWSDL(self):
return self.parent().getWSDL()
def toDom(self, node):
wsdl = self.getWSDL()
ep = ElementProxy(None, node)
epc = ep.createAppendElement(DOM.GetWSDLSoapBindingUri(wsdl.version), 'operation')
if self.soapAction:
epc.setAttributeNS(None, 'soapAction', self.soapAction)
if self.style:
epc.setAttributeNS(None, 'style', self.style)
class SoapBodyBinding:
def __init__(self, use, namespace=None, encodingStyle=None, parts=None):
if not use in ('literal', 'encoded'):
raise WSDLError(
'Invalid use attribute value: %s' % use
)
self.encodingStyle = encodingStyle
self.namespace = namespace
if type(parts) in (type(''), type(u'')):
parts = parts.split()
self.parts = parts
self.use = use
def getWSDL(self):
return self.parent().getWSDL()
def toDom(self, node):
wsdl = self.getWSDL()
ep = ElementProxy(None, node)
epc = ep.createAppendElement(DOM.GetWSDLSoapBindingUri(wsdl.version), 'body')
epc.setAttributeNS(None, "use", self.use)
epc.setAttributeNS(None, "namespace", self.namespace)
class SoapFaultBinding:
def __init__(self, name, use, namespace=None, encodingStyle=None):
if not use in ('literal', 'encoded'):
raise WSDLError(
'Invalid use attribute value: %s' % use
)
self.encodingStyle = encodingStyle
self.namespace = namespace
self.name = name
self.use = use
def getWSDL(self):
return self.parent().getWSDL()
def toDom(self, node):
wsdl = self.getWSDL()
ep = ElementProxy(None, node)
epc = ep.createAppendElement(DOM.GetWSDLSoapBindingUri(wsdl.version), 'body')
epc.setAttributeNS(None, "use", self.use)
epc.setAttributeNS(None, "name", self.name)
if self.namespace is not None:
epc.setAttributeNS(None, "namespace", self.namespace)
if self.encodingStyle is not None:
epc.setAttributeNS(None, "encodingStyle", self.encodingStyle)
class SoapHeaderBinding:
def __init__(self, message, part, use, namespace=None, encodingStyle=None):
if not use in ('literal', 'encoded'):
raise WSDLError(
'Invalid use attribute value: %s' % use
)
self.encodingStyle = encodingStyle
self.namespace = namespace
self.message = message
self.part = part
self.use = use
tagname = 'header'
class SoapHeaderFaultBinding(SoapHeaderBinding):
tagname = 'headerfault'
class HttpBinding:
def __init__(self, verb):
self.verb = verb
class HttpAddressBinding:
def __init__(self, location):
self.location = location
class HttpOperationBinding:
def __init__(self, location):
self.location = location
class HttpUrlReplacementBinding:
pass
class HttpUrlEncodedBinding:
pass
class MimeContentBinding:
def __init__(self, part=None, type=None):
self.part = part
self.type = type
class MimeXmlBinding:
def __init__(self, part=None):
self.part = part
class MimeMultipartRelatedBinding:
def __init__(self):
self.parts = []
def load_ex(self, elements):
for e in elements:
ns, name = e.namespaceURI, e.localName
if ns in DOM.NS_MIME_BINDING_ALL and name == 'part':
self.parts.append(MimePartBinding())
continue
class MimePartBinding:
def __init__(self):
self.items = []
def load_ex(self, elements):
for e in elements:
ns, name = e.namespaceURI, e.localName
if ns in DOM.NS_MIME_BINDING_ALL and name == 'content':
part = DOM.getAttr(e, 'part', default=None)
type = DOM.getAttr(e, 'type', default=None)
ob = MimeContentBinding(part, type)
self.items.append(ob)
continue
elif ns in DOM.NS_MIME_BINDING_ALL and name == 'mimeXml':
part = DOM.getAttr(e, 'part', default=None)
ob = MimeXmlBinding(part)
self.items.append(ob)
continue
elif ns in DOM.NS_SOAP_BINDING_ALL and name == 'body':
encstyle = DOM.getAttr(e, 'encodingStyle', default=None)
namespace = DOM.getAttr(e, 'namespace', default=None)
parts = DOM.getAttr(e, 'parts', default=None)
use = DOM.getAttr(e, 'use', default=None)
if use is None:
raise WSDLError(
'Invalid soap:body binding element.'
)
ob = SoapBodyBinding(use, namespace, encstyle, parts)
self.items.append(ob)
continue
class WSDLError(Exception):
pass
def DeclareNSPrefix(writer, prefix, nsuri):
if writer.hasNSPrefix(nsuri):
return
writer.declareNSPrefix(prefix, nsuri)
def ParseTypeRef(value, element):
parts = value.split(':', 1)
if len(parts) == 1:
return (DOM.findTargetNS(element), value)
nsuri = DOM.findNamespaceURI(parts[0], element)
return (nsuri, parts[1])
def ParseQName(value, element):
nameref = value.split(':', 1)
if len(nameref) == 2:
nsuri = DOM.findNamespaceURI(nameref[0], element)
name = nameref[-1]
else:
nsuri = DOM.findTargetNS(element)
name = nameref[-1]
return nsuri, name
def GetDocumentation(element):
docnode = DOM.getElement(element, 'documentation', None, None)
if docnode is not None:
return DOM.getElementText(docnode)
return ''
def GetExtensions(element):
return [ item for item in DOM.getElements(element, None, None)
if item.namespaceURI != DOM.NS_WSDL ]
def GetWSAActionFault(operation, name):
"""Find wsa:Action attribute, and return value or WSA.FAULT
for the default.
"""
attr = operation.faults[name].action
if attr is not None:
return attr
return WSA.FAULT
def GetWSAActionInput(operation):
"""Find wsa:Action attribute, and return value or the default."""
attr = operation.input.action
if attr is not None:
return attr
portType = operation.getPortType()
targetNamespace = portType.getTargetNamespace()
ptName = portType.name
msgName = operation.input.name
if not msgName:
msgName = operation.name + 'Request'
if targetNamespace.endswith('/'):
return '%s%s/%s' %(targetNamespace, ptName, msgName)
return '%s/%s/%s' %(targetNamespace, ptName, msgName)
def GetWSAActionOutput(operation):
"""Find wsa:Action attribute, and return value or the default."""
attr = operation.output.action
if attr is not None:
return attr
targetNamespace = operation.getPortType().getTargetNamespace()
ptName = operation.getPortType().name
msgName = operation.output.name
if not msgName:
msgName = operation.name + 'Response'
if targetNamespace.endswith('/'):
return '%s%s/%s' %(targetNamespace, ptName, msgName)
return '%s/%s/%s' %(targetNamespace, ptName, msgName)
def FindExtensions(object, kind, t_type=type(())):
if isinstance(kind, t_type):
result = []
namespaceURI, name = kind
return [ item for item in object.extensions
if hasattr(item, 'nodeType') \
and DOM.nsUriMatch(namespaceURI, item.namespaceURI) \
and item.name == name ]
return [ item for item in object.extensions if isinstance(item, kind) ]
def FindExtension(object, kind, t_type=type(())):
if isinstance(kind, t_type):
namespaceURI, name = kind
for item in object.extensions:
if hasattr(item, 'nodeType') \
and DOM.nsUriMatch(namespaceURI, item.namespaceURI) \
and item.name == name:
return item
else:
for item in object.extensions:
if isinstance(item, kind):
return item
return None
class SOAPCallInfo:
"""SOAPCallInfo captures the important binding information about a
SOAP operation, in a structure that is easier to work with than
raw WSDL structures."""
def __init__(self, methodName):
self.methodName = methodName
self.inheaders = []
self.outheaders = []
self.inparams = []
self.outparams = []
self.retval = None
encodingStyle = DOM.NS_SOAP_ENC
documentation = ''
soapAction = None
transport = None
namespace = None
location = None
use = 'encoded'
style = 'rpc'
def addInParameter(self, name, type, namespace=None, element_type=0):
"""Add an input parameter description to the call info."""
parameter = ParameterInfo(name, type, namespace, element_type)
self.inparams.append(parameter)
return parameter
def addOutParameter(self, name, type, namespace=None, element_type=0):
"""Add an output parameter description to the call info."""
parameter = ParameterInfo(name, type, namespace, element_type)
self.outparams.append(parameter)
return parameter
def setReturnParameter(self, name, type, namespace=None, element_type=0):
"""Set the return parameter description for the call info."""
parameter = ParameterInfo(name, type, namespace, element_type)
self.retval = parameter
return parameter
def addInHeaderInfo(self, name, type, namespace, element_type=0,
mustUnderstand=0):
"""Add an input SOAP header description to the call info."""
headerinfo = HeaderInfo(name, type, namespace, element_type)
if mustUnderstand:
headerinfo.mustUnderstand = 1
self.inheaders.append(headerinfo)
return headerinfo
def addOutHeaderInfo(self, name, type, namespace, element_type=0,
mustUnderstand=0):
"""Add an output SOAP header description to the call info."""
headerinfo = HeaderInfo(name, type, namespace, element_type)
if mustUnderstand:
headerinfo.mustUnderstand = 1
self.outheaders.append(headerinfo)
return headerinfo
def getInParameters(self):
"""Return a sequence of the in parameters of the method."""
return self.inparams
def getOutParameters(self):
"""Return a sequence of the out parameters of the method."""
return self.outparams
def getReturnParameter(self):
"""Return param info about the return value of the method."""
return self.retval
def getInHeaders(self):
"""Return a sequence of the in headers of the method."""
return self.inheaders
def getOutHeaders(self):
"""Return a sequence of the out headers of the method."""
return self.outheaders
class ParameterInfo:
"""A ParameterInfo object captures parameter binding information."""
def __init__(self, name, type, namespace=None, element_type=0):
if element_type:
self.element_type = 1
if namespace is not None:
self.namespace = namespace
self.name = name
self.type = type
element_type = 0
namespace = None
default = None
class HeaderInfo(ParameterInfo):
"""A HeaderInfo object captures SOAP header binding information."""
def __init__(self, name, type, namespace, element_type=None):
ParameterInfo.__init__(self, name, type, namespace, element_type)
mustUnderstand = 0
actor = None
def callInfoFromWSDL(port, name):
"""Return a SOAPCallInfo given a WSDL port and operation name."""
wsdl = port.getService().getWSDL()
binding = port.getBinding()
portType = binding.getPortType()
operation = portType.operations[name]
opbinding = binding.operations[name]
messages = wsdl.messages
callinfo = SOAPCallInfo(name)
addrbinding = port.getAddressBinding()
if not isinstance(addrbinding, SoapAddressBinding):
raise ValueError, 'Unsupported binding type.'
callinfo.location = addrbinding.location
soapbinding = binding.findBinding(SoapBinding)
if soapbinding is None:
raise ValueError, 'Missing soap:binding element.'
callinfo.transport = soapbinding.transport
callinfo.style = soapbinding.style or 'document'
soap_op_binding = opbinding.findBinding(SoapOperationBinding)
if soap_op_binding is not None:
callinfo.soapAction = soap_op_binding.soapAction
callinfo.style = soap_op_binding.style or callinfo.style
parameterOrder = operation.parameterOrder
if operation.input is not None:
message = messages[operation.input.message]
msgrole = opbinding.input
mime = msgrole.findBinding(MimeMultipartRelatedBinding)
if mime is not None:
raise ValueError, 'Mime bindings are not supported.'
else:
for item in msgrole.findBindings(SoapHeaderBinding):
part = messages[item.message].parts[item.part]
header = callinfo.addInHeaderInfo(
part.name,
part.element or part.type,
item.namespace,
element_type = part.element and 1 or 0
)
header.encodingStyle = item.encodingStyle
body = msgrole.findBinding(SoapBodyBinding)
if body is None:
raise ValueError, 'Missing soap:body binding.'
callinfo.encodingStyle = body.encodingStyle
callinfo.namespace = body.namespace
callinfo.use = body.use
if body.parts is not None:
parts = []
for name in body.parts:
parts.append(message.parts[name])
else:
parts = message.parts.values()
for part in parts:
callinfo.addInParameter(
part.name,
part.element or part.type,
element_type = part.element and 1 or 0
)
if operation.output is not None:
try:
message = messages[operation.output.message]
except KeyError:
if self.strict:
raise RuntimeError(
"Recieved message not defined in the WSDL schema: %s" %
operation.output.message)
else:
message = wsdl.addMessage(operation.output.message)
print "Warning:", \
"Recieved message not defined in the WSDL schema.", \
"Adding it."
print "Message:", operation.output.message
msgrole = opbinding.output
mime = msgrole.findBinding(MimeMultipartRelatedBinding)
if mime is not None:
raise ValueError, 'Mime bindings are not supported.'
else:
for item in msgrole.findBindings(SoapHeaderBinding):
part = messages[item.message].parts[item.part]
header = callinfo.addOutHeaderInfo(
part.name,
part.element or part.type,
item.namespace,
element_type = part.element and 1 or 0
)
header.encodingStyle = item.encodingStyle
body = msgrole.findBinding(SoapBodyBinding)
if body is None:
raise ValueError, 'Missing soap:body binding.'
callinfo.encodingStyle = body.encodingStyle
callinfo.namespace = body.namespace
callinfo.use = body.use
if body.parts is not None:
parts = []
for name in body.parts:
parts.append(message.parts[name])
else:
parts = message.parts.values()
if parts:
for part in parts:
callinfo.addOutParameter(
part.name,
part.element or part.type,
element_type = part.element and 1 or 0
)
return callinfo | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/ZSI/wstools/WSDLTools.py | WSDLTools.py |
import time
# twisted & related imports
from zope.interface import classProvides, implements, Interface
from twisted.web import client
from twisted.internet import defer
from twisted.internet import reactor
from twisted.python import log
from twisted.python.failure import Failure
from ZSI.parse import ParsedSoap
from ZSI.writer import SoapWriter
from ZSI.fault import FaultFromFaultMessage
from ZSI.wstools.Namespaces import WSA
from WSresource import HandlerChainInterface, CheckInputArgs
#
# Stability: Unstable
#
class HTTPPageGetter(client.HTTPPageGetter):
def handleStatus_500(self):
"""potentially a SOAP:Fault.
"""
log.err('HTTP Error 500')
def handleStatus_404(self):
"""client error, not found
"""
log.err('HTTP Error 404')
client.HTTPClientFactory.protocol = HTTPPageGetter
def getPage(url, contextFactory=None, *args, **kwargs):
"""Download a web page as a string.
Download a page. Return a deferred, which will callback with a
page (as a string) or errback with a description of the error.
See HTTPClientFactory to see what extra args can be passed.
"""
scheme, host, port, path = client._parse(url)
factory = client.HTTPClientFactory(url, *args, **kwargs)
if scheme == 'https':
if contextFactory is None:
raise RuntimeError, 'must provide a contextFactory'
conn = reactor.connectSSL(host, port, factory, contextFactory)
else:
conn = reactor.connectTCP(host, port, factory)
return factory
class ClientDataHandler:
"""
class variables:
readerClass -- factory class to create reader for ParsedSoap instances.
writerClass -- ElementProxy implementation to use for SoapWriter
instances.
"""
classProvides(HandlerChainInterface)
readerClass = None
writerClass = None
@classmethod
def processResponse(cls, soapdata, **kw):
"""called by deferred, returns pyobj representing reply.
Parameters and Key Words:
soapdata -- SOAP Data
replytype -- reply type of response
"""
if len(soapdata) == 0:
raise TypeError('Received empty response')
# log.msg("_" * 33, time.ctime(time.time()),
# "RESPONSE: \n%s" %soapdata, debug=True)
ps = ParsedSoap(soapdata, readerclass=cls.readerClass)
if ps.IsAFault() is True:
log.msg('Received SOAP:Fault', debug=True)
raise FaultFromFaultMessage(ps)
return ps
@classmethod
def processRequest(cls, obj, nsdict={}, header=True,
**kw):
tc = None
if kw.has_key('requesttypecode'):
tc = kw['requesttypecode']
elif kw.has_key('requestclass'):
tc = kw['requestclass'].typecode
else:
tc = getattr(obj.__class__, 'typecode', None)
sw = SoapWriter(nsdict=nsdict, header=header,
outputclass=cls.writerClass)
sw.serialize(obj, tc)
return sw
class WSAddressHandler:
"""Minimal WS-Address handler. Most of the logic is in
the ZSI.address.Address class.
class variables:
uri -- default WSA Addressing URI
"""
implements(HandlerChainInterface)
uri = WSA.ADDRESS
def processResponse(self, ps, wsaction=None, soapaction=None, **kw):
addr = self.address
addr.parse(ps)
action = addr.getAction()
if not action:
raise WSActionException('No WS-Action specified in Request')
if not soapaction:
return ps
soapaction = soapaction.strip('\'"')
if soapaction and soapaction != wsaction:
raise WSActionException(\
'SOAP Action("%s") must match WS-Action("%s") if specified.'%(
soapaction, wsaction)
)
return ps
def processRequest(self, sw, wsaction=None, url=None, endPointReference=None, **kw):
from ZSI.address import Address
if sw is None:
self.address = None
return
if not sw.header:
raise RuntimeError, 'expecting SOAP:Header'
self.address = addr = Address(url, wsAddressURI=self.uri)
addr.setRequest(endPointReference, wsaction)
addr.serialize(sw, typed=False)
return sw
class DefaultClientHandlerChain:
@CheckInputArgs(HandlerChainInterface)
def __init__(self, *handlers):
self.handlers = handlers
self.debug = len(log.theLogPublisher.observers) > 0
self.flow = None
@staticmethod
def parseResponse(ps, replytype):
return ps.Parse(replytype)
def processResponse(self, arg, replytype, **kw):
"""
Parameters:
arg -- deferred
replytype -- typecode
"""
if self.debug:
log.msg('--->PROCESS REQUEST\n%s' %arg, debug=1)
for h in self.handlers:
arg.addCallback(h.processResponse, **kw)
arg.addCallback(self.parseResponse, replytype)
def processRequest(self, arg, **kw):
"""
Parameters:
arg -- XML Soap data string
"""
if self.debug:
log.msg('===>PROCESS RESPONSE: %s' %str(arg), debug=1)
if arg is None:
return
for h in self.handlers:
arg = h.processRequest(arg, **kw)
s = str(arg)
if self.debug:
log.msg(s, debug=1)
return s
class DefaultClientHandlerChainFactory:
protocol = DefaultClientHandlerChain
@classmethod
def newInstance(cls):
return cls.protocol(ClientDataHandler)
class WSAddressClientHandlerChainFactory:
protocol = DefaultClientHandlerChain
@classmethod
def newInstance(cls):
return cls.protocol(ClientDataHandler,
WSAddressHandler())
class Binding:
"""Object that represents a binding (connection) to a SOAP server.
"""
agent='ZSI.twisted client'
factory = DefaultClientHandlerChainFactory
defer = False
def __init__(self, url=None, nsdict=None, contextFactory=None,
tracefile=None, **kw):
"""Initialize.
Keyword arguments include:
url -- URL of resource, POST is path
nsdict -- namespace entries to add
contextFactory -- security contexts
tracefile -- file to dump packet traces
"""
self.url = url
self.nsdict = nsdict or {}
self.contextFactory = contextFactory
self.http_headers = {'content-type': 'text/xml',}
self.trace = tracefile
def addHTTPHeader(self, key, value):
self.http_headers[key] = value
def getHTTPHeaders(self):
return self.http_headers
def Send(self, url, opname, pyobj, nsdict={}, soapaction=None, chain=None,
**kw):
"""Returns a ProcessingChain which needs to be passed to Receive if
Send is being called consecutively.
"""
url = url or self.url
cookies = None
if chain is not None:
cookies = chain.flow.cookies
d = {}
d.update(self.nsdict)
d.update(nsdict)
if soapaction is not None:
self.addHTTPHeader('SOAPAction', soapaction)
chain = self.factory.newInstance()
soapdata = chain.processRequest(pyobj, nsdict=nsdict,
soapaction=soapaction, **kw)
if self.trace:
print >>self.trace, "_" * 33, time.ctime(time.time()), "REQUEST:"
print >>self.trace, soapdata
f = getPage(str(url), contextFactory=self.contextFactory,
postdata=soapdata, agent=self.agent,
method='POST', headers=self.getHTTPHeaders(),
cookies=cookies)
if isinstance(f, Failure):
return f
chain.flow = f
self.chain = chain
return chain
def Receive(self, replytype, chain=None, **kw):
"""This method allows code to act in a synchronous manner, it waits to
return until the deferred fires but it doesn't prevent other queued
calls from being executed. Send must be called first, which sets up
the chain/factory.
WARNING: If defer is set to True, must either call Receive
immediately after Send (ie. no intervening Sends) or pass
chain in as a paramter.
Parameters:
replytype -- TypeCode
KeyWord Parameters:
chain -- processing chain, optional
"""
chain = chain or self.chain
d = chain.flow.deferred
if self.trace:
def trace(soapdata):
print >>self.trace, "_" * 33, time.ctime(time.time()), "RESPONSE:"
print >>self.trace, soapdata
return soapdata
d.addCallback(trace)
chain.processResponse(d, replytype, **kw)
if self.defer:
return d
failure = []
append = failure.append
def errback(result):
"""Used with Response method to suppress 'Unhandled error in
Deferred' messages by adding an errback.
"""
append(result)
return None
d.addErrback(errback)
# spin reactor
while not d.called:
reactor.runUntilCurrent()
t2 = reactor.timeout()
t = reactor.running and t2
reactor.doIteration(t)
pyobj = d.result
if len(failure):
failure[0].raiseException()
return pyobj
def trace():
if trace:
print >>trace, "_" * 33, time.ctime(time.time()), "RESPONSE:"
for i in (self.reply_code, self.reply_msg,):
print >>trace, str(i)
print >>trace, "-------"
print >>trace, str(self.reply_headers)
print >>trace, self.data | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/ZSI/twisted/client.py | client.py |
import sys, time, warnings
import sha, base64
# twisted & related imports
from zope.interface import classProvides, implements, Interface
from twisted.python import log, failure
from twisted.web.error import NoResource
from twisted.web.server import NOT_DONE_YET
from twisted.internet import reactor
import twisted.web.http
import twisted.web.resource
# ZSI imports
from ZSI import _get_element_nsuri_name, EvaluateException, ParseException
from ZSI.parse import ParsedSoap
from ZSI.writer import SoapWriter
from ZSI.TC import _get_global_element_declaration as GED
from ZSI import fault
from ZSI.wstools.Namespaces import OASIS, DSIG
from WSresource import DefaultHandlerChain, HandlerChainInterface,\
WSAddressCallbackHandler, DataHandler, WSAddressHandler
#
# Global Element Declarations
#
UsernameTokenDec = GED(OASIS.WSSE, "UsernameToken")
SecurityDec = GED(OASIS.WSSE, "Security")
SignatureDec = GED(DSIG.BASE, "Signature")
PasswordDec = GED(OASIS.WSSE, "Password")
NonceDec = GED(OASIS.WSSE, "Nonce")
CreatedDec = GED(OASIS.UTILITY, "Created")
if None in [UsernameTokenDec,SecurityDec,SignatureDec,PasswordDec,NonceDec,CreatedDec]:
raise ImportError, 'required global element(s) unavailable: %s ' %({
(OASIS.WSSE, "UsernameToken"):UsernameTokenDec,
(OASIS.WSSE, "Security"):SecurityDec,
(DSIG.BASE, "Signature"):SignatureDec,
(OASIS.WSSE, "Password"):PasswordDec,
(OASIS.WSSE, "Nonce"):NonceDec,
(OASIS.UTILITY, "Created"):CreatedDec,
})
#
# Stability: Unstable, Untested, Not Finished.
#
class WSSecurityHandler:
"""Web Services Security: SOAP Message Security 1.0
Class Variables:
debug -- If True provide more detailed SOAP:Fault information to clients.
"""
classProvides(HandlerChainInterface)
debug = True
@classmethod
def processRequest(cls, ps, **kw):
if type(ps) is not ParsedSoap:
raise TypeError,'Expecting ParsedSoap instance'
security = ps.ParseHeaderElements([cls.securityDec])
# Assume all security headers are supposed to be processed here.
for pyobj in security or []:
for any in pyobj.Any or []:
if any.typecode is UsernameTokenDec:
try:
ps = cls.UsernameTokenProfileHandler.processRequest(ps, any)
except Exception, ex:
if cls.debug: raise
raise RuntimeError, 'Unauthorized Username/passphrase combination'
continue
if any.typecode is SignatureDec:
try:
ps = cls.SignatureHandler.processRequest(ps, any)
except Exception, ex:
if cls.debug: raise
raise RuntimeError, 'Invalid Security Header'
continue
raise RuntimeError, 'WS-Security, Unsupported token %s' %str(any)
return ps
@classmethod
def processResponse(cls, output, **kw):
return output
class UsernameTokenProfileHandler:
"""Web Services Security UsernameToken Profile 1.0
Class Variables:
targetNamespace --
"""
classProvides(HandlerChainInterface)
# Class Variables
targetNamespace = OASIS.WSSE
sweepInterval = 60*5
nonces = None
# Set to None to disable
PasswordText = targetNamespace + "#PasswordText"
PasswordDigest = targetNamespace + "#PasswordDigest"
# Override passwordCallback
passwordCallback = lambda cls,username: None
@classmethod
def sweep(cls, index):
"""remove nonces every sweepInterval.
Parameters:
index -- remove all nonces up to this index.
"""
if cls.nonces is None:
cls.nonces = []
seconds = cls.sweepInterval
cls.nonces = cls.nonces[index:]
reactor.callLater(seconds, cls.sweep, len(cls.nonces))
@classmethod
def processRequest(cls, ps, token, **kw):
"""
Parameters:
ps -- ParsedSoap instance
token -- UsernameToken pyclass instance
"""
if token.typecode is not UsernameTokenDec:
raise TypeError, 'expecting GED (%s,%s) representation.' %(
UsernameTokenDec.nspname, UsernameTokenDec.pname)
username = token.Username
# expecting only one password
# may have a nonce and a created
password = nonce = timestamp = None
for any in token.Any or []:
if any.typecode is PasswordDec:
password = any
continue
if any.typecode is NonceTypeDec:
nonce = any
continue
if any.typecode is CreatedTypeDec:
timestamp = any
continue
raise TypeError, 'UsernameTokenProfileHander unexpected %s' %str(any)
if password is None:
raise RuntimeError, 'Unauthorized, no password'
# TODO: not yet supporting complexType simpleContent in pyclass_type
attrs = getattr(password, password.typecode.attrs_aname, {})
pwtype = attrs.get('Type', cls.PasswordText)
# Clear Text Passwords
if cls.PasswordText is not None and pwtype == cls.PasswordText:
if password == cls.passwordCallback(username):
return ps
raise RuntimeError, 'Unauthorized, clear text password failed'
if cls.nonces is None: cls.sweep(0)
if nonce is not None:
if nonce in cls.nonces:
raise RuntimeError, 'Invalid Nonce'
# created was 10 seconds ago or sooner
if created is not None and created < time.gmtime(time.time()-10):
raise RuntimeError, 'UsernameToken created is expired'
cls.nonces.append(nonce)
# PasswordDigest, recommended that implemenations
# require a Nonce and Created
if cls.PasswordDigest is not None and pwtype == cls.PasswordDigest:
digest = sha.sha()
for i in (nonce, created, cls.passwordCallback(username)):
if i is None: continue
digest.update(i)
if password == base64.encodestring(digest.digest()).strip():
return ps
raise RuntimeError, 'Unauthorized, digest failed'
raise RuntimeError, 'Unauthorized, contents of UsernameToken unknown'
@classmethod
def processResponse(cls, output, **kw):
return output
@staticmethod
def hmac_sha1(xml):
return
class SignatureHandler:
"""Web Services Security UsernameToken Profile 1.0
"""
digestMethods = {
DSIG.BASE+"#sha1":sha.sha,
}
signingMethods = {
DSIG.BASE+"#hmac-sha1":hmac_sha1,
}
canonicalizationMethods = {
DSIG.C14N_EXCL:lambda node: Canonicalize(node, unsuppressedPrefixes=[]),
DSIG.C14N:lambda node: Canonicalize(node),
}
@classmethod
def processRequest(cls, ps, signature, **kw):
"""
Parameters:
ps -- ParsedSoap instance
signature -- Signature pyclass instance
"""
if token.typecode is not SignatureDec:
raise TypeError, 'expecting GED (%s,%s) representation.' %(
SignatureDec.nspname, SignatureDec.pname)
si = signature.SignedInfo
si.CanonicalizationMethod
calgo = si.CanonicalizationMethod.get_attribute_Algorithm()
for any in si.CanonicalizationMethod.Any:
pass
# Check Digest
si.Reference
context = XPath.Context.Context(ps.dom, processContents={'wsu':OASIS.UTILITY})
exp = XPath.Compile('//*[@wsu:Id="%s"]' %si.Reference.get_attribute_URI())
nodes = exp.evaluate(context)
if len(nodes) != 1:
raise RuntimeError, 'A SignedInfo Reference must refer to one node %s.' %(
si.Reference.get_attribute_URI())
try:
xml = cls.canonicalizeMethods[calgo](nodes[0])
except IndexError:
raise RuntimeError, 'Unsupported canonicalization algorithm'
try:
digest = cls.digestMethods[salgo]
except IndexError:
raise RuntimeError, 'unknown digestMethods Algorithm'
digestValue = base64.encodestring(digest(xml).digest()).strip()
if si.Reference.DigestValue != digestValue:
raise RuntimeError, 'digest does not match'
if si.Reference.Transforms:
pass
signature.KeyInfo
signature.KeyInfo.KeyName
signature.KeyInfo.KeyValue
signature.KeyInfo.RetrievalMethod
signature.KeyInfo.X509Data
signature.KeyInfo.PGPData
signature.KeyInfo.SPKIData
signature.KeyInfo.MgmtData
signature.KeyInfo.Any
signature.Object
# TODO: Check Signature
signature.SignatureValue
si.SignatureMethod
salgo = si.SignatureMethod.get_attribute_Algorithm()
if si.SignatureMethod.HMACOutputLength:
pass
for any in si.SignatureMethod.Any:
pass
# <SignedInfo><Reference URI="">
exp = XPath.Compile('//child::*[attribute::URI = "%s"]/..' %(
si.Reference.get_attribute_URI()))
nodes = exp.evaluate(context)
if len(nodes) != 1:
raise RuntimeError, 'A SignedInfo Reference must refer to one node %s.' %(
si.Reference.get_attribute_URI())
try:
xml = cls.canonicalizeMethods[calgo](nodes[0])
except IndexError:
raise RuntimeError, 'Unsupported canonicalization algorithm'
# TODO: Check SignatureValue
@classmethod
def processResponse(cls, output, **kw):
return output
class X509TokenProfileHandler:
"""Web Services Security UsernameToken Profile 1.0
"""
targetNamespace = DSIG.BASE
# Token Types
singleCertificate = targetNamespace + "#X509v3"
certificatePath = targetNamespace + "#X509PKIPathv1"
setCerticatesCRLs = targetNamespace + "#PKCS7"
@classmethod
def processRequest(cls, ps, signature, **kw):
return ps
"""
<element name="KeyInfo" type="ds:KeyInfoType"/>
<complexType name="KeyInfoType" mixed="true">
<choice maxOccurs="unbounded">
<element ref="ds:KeyName"/>
<element ref="ds:KeyValue"/>
<element ref="ds:RetrievalMethod"/>
<element ref="ds:X509Data"/>
<element ref="ds:PGPData"/>
<element ref="ds:SPKIData"/>
<element ref="ds:MgmtData"/>
<any processContents="lax" namespace="##other"/>
<!-- (1,1) elements from (0,unbounded) namespaces -->
</choice>
<attribute name="Id" type="ID" use="optional"/>
</complexType>
<element name="Signature" type="ds:SignatureType"/>
<complexType name="SignatureType">
<sequence>
<element ref="ds:SignedInfo"/>
<element ref="ds:SignatureValue"/>
<element ref="ds:KeyInfo" minOccurs="0"/>
<element ref="ds:Object" minOccurs="0" maxOccurs="unbounded"/>
</sequence>
<attribute name="Id" type="ID" use="optional"/>
</complexType>
<element name="SignatureValue" type="ds:SignatureValueType"/>
<complexType name="SignatureValueType">
<simpleContent>
<extension base="base64Binary">
<attribute name="Id" type="ID" use="optional"/>
</extension>
</simpleContent>
</complexType>
<!-- Start SignedInfo -->
<element name="SignedInfo" type="ds:SignedInfoType"/>
<complexType name="SignedInfoType">
<sequence>
<element ref="ds:CanonicalizationMethod"/>
<element ref="ds:SignatureMethod"/>
<element ref="ds:Reference" maxOccurs="unbounded"/>
</sequence>
<attribute name="Id" type="ID" use="optional"/>
</complexType>
"""
class WSSecurityHandlerChainFactory:
protocol = DefaultHandlerChain
@classmethod
def newInstance(cls):
return cls.protocol(WSAddressCallbackHandler, DataHandler,
WSSecurityHandler, WSAddressHandler()) | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/ZSI/twisted/WSsecurity.py | WSsecurity.py |
import sys, warnings
# twisted & related imports
from zope.interface import classProvides, implements, Interface
from twisted.python import log, failure
from twisted.web.error import NoResource
from twisted.web.server import NOT_DONE_YET
import twisted.web.http
import twisted.web.resource
# ZSI imports
from ZSI import _get_element_nsuri_name, EvaluateException, ParseException
from ZSI.parse import ParsedSoap
from ZSI.writer import SoapWriter
from ZSI import fault
# WS-Address related imports
from ZSI.address import Address
from ZSI.ServiceContainer import WSActionException
#
# Stability: Unstable
#
class HandlerChainInterface(Interface):
def processRequest(self, input, **kw):
"""returns a representation of the request, the
last link in the chain must return a response
pyobj with a typecode attribute.
Parameters:
input --
Keyword Parameters:
request -- HTTPRequest instance
resource -- Resource instance
"""
def processResponse(self, output, **kw):
"""returns a string representing the soap response.
Parameters
output --
Keyword Parameters:
request -- HTTPRequest instance
resource -- Resource instance
"""
class CallbackChainInterface(Interface):
def processRequest(self, input, **kw):
"""returns a response pyobj with a typecode
attribute.
Parameters:
input --
Keyword Parameters:
request -- HTTPRequest instance
resource -- Resource instance
"""
class DataHandler:
"""
class variables:
readerClass -- factory class to create reader for ParsedSoap instances.
writerClass -- ElementProxy implementation to use for SoapWriter instances.
"""
classProvides(HandlerChainInterface)
readerClass = None
writerClass = None
@classmethod
def processRequest(cls, input, **kw):
return ParsedSoap(input, readerclass=cls.readerClass)
@classmethod
def processResponse(cls, output, **kw):
sw = SoapWriter(outputclass=cls.writerClass)
sw.serialize(output)
return sw
class DefaultCallbackHandler:
classProvides(CallbackChainInterface)
@classmethod
def processRequest(cls, ps, **kw):
"""invokes callback that should return a (request,response) tuple.
representing the SOAP request and response respectively.
ps -- ParsedSoap instance representing HTTP Body.
request -- twisted.web.server.Request
"""
resource = kw['resource']
request = kw['request']
method = getattr(resource, 'soap_%s' %
_get_element_nsuri_name(ps.body_root)[-1])
try:
req_pyobj,rsp_pyobj = method(ps, request=request)
except TypeError, ex:
log.err(
'ERROR: service %s is broken, method MUST return request, response'\
% cls.__name__
)
raise
except Exception, ex:
log.err('failure when calling bound method')
raise
return rsp_pyobj
class WSAddressHandler:
"""General WS-Address handler. This implementation depends on a
'wsAction' dictionary in the service stub which contains keys to
WS-Action values.
Implementation saves state on request response flow, so using this
handle is not reliable if execution is deferred between proceesRequest
and processResponse.
TODO: sink this up with wsdl2dispatch
TODO: reduce coupling with WSAddressCallbackHandler.
"""
implements(HandlerChainInterface)
def processRequest(self, ps, **kw):
# TODO: Clean this up
resource = kw['resource']
d = getattr(resource, 'root', None)
key = _get_element_nsuri_name(ps.body_root)
if d is None or d.has_key(key) is False:
raise RuntimeError,\
'Error looking for key(%s) in root dictionary(%s)' %(key, str(d))
self.op_name = d[key]
self.address = address = Address()
address.parse(ps)
action = address.getAction()
if not action:
raise WSActionException('No WS-Action specified in Request')
request = kw['request']
http_headers = request.getAllHeaders()
soap_action = http_headers.get('soapaction')
if soap_action and soap_action.strip('\'"') != action:
raise WSActionException(\
'SOAP Action("%s") must match WS-Action("%s") if specified.'\
%(soap_action,action)
)
# Save WS-Address in ParsedSoap instance.
ps.address = address
return ps
def processResponse(self, sw, **kw):
if sw is None:
self.address = None
return
request, resource = kw['request'], kw['resource']
if isinstance(request, twisted.web.http.Request) is False:
raise TypeError, '%s instance expected' %http.Request
d = getattr(resource, 'wsAction', None)
key = self.op_name
if d is None or d.has_key(key) is False:
raise WSActionNotSpecified,\
'Error looking for key(%s) in wsAction dictionary(%s)' %(key, str(d))
addressRsp = Address(action=d[key])
if request.transport.TLS == 0:
addressRsp.setResponseFromWSAddress(\
self.address, 'http://%s:%d%s' %(
request.host.host, request.host.port, request.path)
)
else:
addressRsp.setResponseFromWSAddress(\
self.address, 'https://%s:%d%s' %(
request.host.host, request.host.port, request.path)
)
addressRsp.serialize(sw, typed=False)
self.address = None
return sw
class WSAddressCallbackHandler:
classProvides(CallbackChainInterface)
@classmethod
def processRequest(cls, ps, **kw):
"""invokes callback that should return a (request,response) tuple.
representing the SOAP request and response respectively.
ps -- ParsedSoap instance representing HTTP Body.
request -- twisted.web.server.Request
"""
resource = kw['resource']
request = kw['request']
method = getattr(resource, 'wsa_%s' %
_get_element_nsuri_name(ps.body_root)[-1])
# TODO: grab ps.address, clean this up.
try:
req_pyobj,rsp_pyobj = method(ps, ps.address, request=request)
except TypeError, ex:
log.err(
'ERROR: service %s is broken, method MUST return request, response'\
%self.__class__.__name__
)
raise
except Exception, ex:
log.err('failure when calling bound method')
raise
return rsp_pyobj
def CheckInputArgs(*interfaces):
"""Must provide at least one interface, the last one may be repeated.
"""
l = len(interfaces)
def wrapper(func):
def check_args(self, *args, **kw):
for i in range(len(args)):
if (l > i and interfaces[i].providedBy(args[i])) or interfaces[-1].providedBy(args[i]):
continue
if l > i: raise TypeError, 'arg %s does not implement %s' %(args[i], interfaces[i])
raise TypeError, 'arg %s does not implement %s' %(args[i], interfaces[-1])
func(self, *args, **kw)
return check_args
return wrapper
class DefaultHandlerChain:
@CheckInputArgs(CallbackChainInterface, HandlerChainInterface)
def __init__(self, cb, *handlers):
self.handlercb = cb
self.handlers = handlers
self.debug = len(log.theLogPublisher.observers) > 0
def processRequest(self, arg, **kw):
if self.debug:
log.msg('--->PROCESS REQUEST\n%s' %arg, debug=1)
for h in self.handlers:
arg = h.processRequest(arg, **kw)
return self.handlercb.processRequest(arg, **kw)
def processResponse(self, arg, **kw):
if self.debug:
log.msg('===>PROCESS RESPONSE: %s' %str(arg), debug=1)
if arg is None:
return
for h in self.handlers:
arg = h.processResponse(arg, **kw)
s = str(arg)
if self.debug:
log.msg(s, debug=1)
return s
class DefaultHandlerChainFactory:
protocol = DefaultHandlerChain
@classmethod
def newInstance(cls):
return cls.protocol(DefaultCallbackHandler, DataHandler)
class WSAddressHandlerChainFactory:
protocol = DefaultHandlerChain
@classmethod
def newInstance(cls):
return cls.protocol(WSAddressCallbackHandler, DataHandler,
WSAddressHandler())
class WSResource(twisted.web.resource.Resource, object):
"""
class variables:
encoding --
factory -- hander chain, which has a factory method "newInstance"
that returns a
"""
encoding = "UTF-8"
factory = DefaultHandlerChainFactory
def __init__(self):
"""
"""
twisted.web.resource.Resource.__init__(self)
def _writeResponse(self, request, response, status=200):
"""
request -- request message
response --- response message
status -- HTTP Status
"""
request.setResponseCode(status)
if self.encoding is not None:
mimeType = 'text/xml; charset="%s"' % self.encoding
else:
mimeType = "text/xml"
request.setHeader("Content-type", mimeType)
request.setHeader("Content-length", str(len(response)))
request.write(response)
request.finish()
return NOT_DONE_YET
def _writeFault(self, request, ex):
"""
request -- request message
ex -- Exception
"""
response = None
response = fault.FaultFromException(ex, False, sys.exc_info()[2]).AsSOAP()
log.err('SOAP FAULT: %s' % response)
return self._writeResponse(request, response, status=500)
def render_POST(self, request):
"""Dispatch Method called by twisted render, creates a
request/response handler chain.
request -- twisted.web.server.Request
"""
chain = self.factory.newInstance()
data = request.content.read()
try:
pyobj = chain.processRequest(data, request=request, resource=self)
except Exception, ex:
return self._writeFault(request, ex)
try:
soap = chain.processResponse(pyobj, request=request, resource=self)
except Exception, ex:
return self._writeFault(request, ex)
if soap is not None:
return self._writeResponse(request, soap)
request.finish()
return NOT_DONE_YET | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/ZSI/twisted/WSresource.py | WSresource.py |
from ZSI import *
"""Polymorphic containers using TC.Choice
Based on code and text from Dan Gunter <[email protected]>.
The TC.Choice typecode can be used to create a polymorphic type for
a specified set of object types. Here's how:
1. Define all your data classes (D1, D2, ...). If they derive from
a common base class (Base), some feel you get "cleaner" code.
2. Create a typecode class (TC_D1, TC_D2, ...) for each data class.
3. Create a "base" typecode that uses TC.Choice to do the actual
parsing and serializing. Two versions are shown, below.
Then you can instantiate, e.g., an Array that can handle multiple
datatypes with:
TC.Array("base-class-name", TC_Base(), "MyArray")
"""
class Base: pass
class D1(Base): pass
class D2(Base): pass
class TC_D1(TC.TypeCode): pass
class TC_D2(TC.TypeCode): pass
D1.typecode = TC_D1()
D2.typecode = TC_D2()
# A simple version of TC_Base that is "hardwired" with the types of
# objects it can handle. We defer setting the choice attribute because
# with nested containers you could get too much recursion.
class TC_Base(TC.TypeCode):
def parse(self, elt, ps):
return self.choice.parse(elt, ps)[1]
def serialize(self, sw, pyobj, **kw):
if not isinstance(pyobj, Base):
raise TypeError(str(pyobj.__class__) + " not in type hierarchy")
if isinstance(pyobj, D1):
self.choice.serialize(sw, ('D1', pyobj), **kw)
elif isinstance(pyobj, D2):
self.choice.serialize(sw, ('D2', pyobj), **kw)
else:
raise TypeError(str(pyobj.__class__) + " unknown type")
return
def __getattr__(self, attr):
if attr == 'choice':
choice = TC.Choice((D1.typecode, D2.typecode), 'Item')
self.__dict__['choice'] = choice
return choice
raise AttributeError(attr)
## Another version that takes a dictionary that maps element names to
## the python class.
class TC_Polymorphic(TC.TypeCode):
def __init__(self, name2class, pname=None, **kw):
TC.TypeCode.__init__(self, pname, **kw)
self.name2class = name2class
def parse(self, elt, ps):
return self.choice.parse(elt, ps)[1]
def serialize(self, sw, pyobj, **kw):
self.choice.serialize(sw,
(self.class2name[pyobj.__class__], pyobj), **kw)
def __getattr__(self, attr):
if attr == 'choice':
choice = TC.Choice(
[getattr(v, 'typecode') for k,v in self.name2class.items()],
'Item')
self.__dict__['choice'] = choice
return choice
if attr == 'class2name':
class2name = {}
for k,v in self.name2class.items(): class2name[v] = k
self.__dict__['class2name'] = class2name
return class2name
raise AttributeError(attr)
class P1: pass
class P2: pass
P1.typecode = TC.String('s')
P2.typecode = TC.Integer('i')
myTC = TC.Array("Base", TC_Polymorphic({'i': P2, 's': P1}))
test = '''<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body xmlns='test-uri'>
<array SOAP-ENC:arrayType="Base">
<i>34</i>
<s>hello</s>
<s>34</s>
<i>12</i>
<s>goodbye</s>
</array>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>'''
ps = ParsedSoap(test)
a = myTC.parse(ps.body_root, ps)
print a
if 0:
# XXX. Does not work. :(
b = [ P1(), P1(), P2(), P1() ]
b[0].s = 'string'
b[1].s = '34'
b[2].i = 34
b[3].s = 'adios'
import sys
sw = SoapWriter(sys.stdout)
myTC.serialize(sw, b) | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/ZSI/zsi/samples/poly.py | poly.py |
from ZSI import *
"""Polymorphic containers using TC.Choice
Based on code and text from Dan Gunter <[email protected]>.
The TC.Choice typecode can be used to create a polymorphic type for
a specified set of object types. Here's how:
1. Define all your data classes (D1, D2, ...). If they derive from
a common base class (Base), some feel you get "cleaner" code.
2. Create a typecode class (TC_D1, TC_D2, ...) for each data class.
3. Create a "base" typecode that uses TC.Choice to do the actual
parsing and serializing. Two versions are shown, below.
Then you can instantiate, e.g., an Array that can handle multiple
datatypes with:
TC.Array("base-class-name", TC_Base(), "MyArray")
"""
class Base: pass
class D1(Base): pass
class D2(Base): pass
class TC_D1(TC.TypeCode): pass
class TC_D2(TC.TypeCode): pass
D1.typecode = TC_D1()
D2.typecode = TC_D2()
# A simple version of TC_Base that is "hardwired" with the types of
# objects it can handle. We defer setting the choice attribute because
# with nested containers you could get too much recursion.
class TC_Base(TC.TypeCode):
def parse(self, elt, ps):
return self.choice.parse(elt, ps)[1]
def serialize(self, sw, pyobj, **kw):
if not isinstance(pyobj, Base):
raise TypeError(str(pyobj.__class__) + " not in type hierarchy")
if isinstance(pyobj, D1):
self.choice.serialize(sw, ('D1', pyobj), **kw)
elif isinstance(pyobj, D2):
self.choice.serialize(sw, ('D2', pyobj), **kw)
else:
raise TypeError(str(pyobj.__class__) + " unknown type")
return
def __getattr__(self, attr):
if attr == 'choice':
choice = TC.Choice((D1.typecode, D2.typecode), 'Item')
self.__dict__['choice'] = choice
return choice
raise AttributeError(attr)
## Another version that takes a dictionary that maps element names to
## the python class.
class TC_Polymorphic(TC.TypeCode):
def __init__(self, name2class, pname=None, **kw):
TC.TypeCode.__init__(self, pname, **kw)
self.name2class = name2class
def parse(self, elt, ps):
return self.choice.parse(elt, ps)[1]
def serialize(self, sw, pyobj, **kw):
self.choice.serialize(sw,
(self.class2name[pyobj.__class__], pyobj), **kw)
def __getattr__(self, attr):
if attr == 'choice':
choice = TC.Choice(
[getattr(v, 'typecode') for k,v in self.name2class.items()],
'Item')
self.__dict__['choice'] = choice
return choice
if attr == 'class2name':
class2name = {}
for k,v in self.name2class.items(): class2name[v] = k
self.__dict__['class2name'] = class2name
return class2name
raise AttributeError(attr)
class P1: pass
class P2: pass
P1.typecode = TC.String('s')
P2.typecode = TC.Integer('i')
myTC = TC.Array("Base", TC_Polymorphic({'i': P2, 's': P1}))
test = '''<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body xmlns='test-uri'>
<array SOAP-ENC:arrayType="Base">
<i>34</i>
<s>hello</s>
<s>34</s>
<i>12</i>
<s>goodbye</s>
</array>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>'''
ps = ParsedSoap(test)
a = myTC.parse(ps.body_root, ps)
print a
if 0:
# XXX. Does not work. :(
b = [ P1(), P1(), P2(), P1() ]
b[0].s = 'string'
b[1].s = '34'
b[2].i = 34
b[3].s = 'adios'
import sys
sw = SoapWriter(sys.stdout)
myTC.serialize(sw, b) | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/samples/poly.py | poly.py |
BACKGROUND
==========
This is a simple example of the new additions I've been adding to
ZSI. Among these modifications are:
1) Extended code generation facilities for server and client
2) Authorization callbacks
3) ServiceContainer enhancements for implementations to use
Extended Code Generation for Server and Client
----------------------------------------------
These extensions are illustrated by the Echo.wsdl, EchoServer.py and
EchoClient.py that implement an Echo service. The EchoServer.py file
has two classes defined that implement the Echo functionality, the
difference in the two is that one inherits from the generated
EchoServer_interface class (generated by wsdl2dispatch), and one can
be passed to the EchoServer_interface constructor with the keyword
argument impl=<obj>.
These two solutions follow the classic TIE and Derive patterns from
previous systems like CORBA.
The EchoClient.py implements a simple client for each service and
invokes the method to do the work. The second call is programmed to
result in an authorization error.
Authorization Callbacks
-----------------------
This functionality lets you define a method on your implementation
object that can be invoked to authorize calls to it from the
underlying SOAP interface.
ServiceContainer Enhancements
-----------------------------
I've added the ability to get a CallContext via a ServiceContainer
module level function GetSOAPContext(). This returns a context object
for the current request. I've make this thread-safe by keeping a
global dictionary of contexts indexed by thread id. The requesthandler
object cleanly creates and destroys these for each incoming request.
The SOAPContext contains:
- a reference to the connection object
- a reference to the Service Container
- the HTTP headers
- the raw xml of the request
- the Parsed SOAP object
- the SOAP Action
This should provide all the information a developer could need.
BUILDING
========
You should (with a fresh checkout from cvs that's been installed) be able to run:
>wsdl2py -e -f Echo.wsdl --simple-naming
>wsdl2dispatch -e -f Echo.wsdl --simple-naming
Then in separate terminal windows:
Terminal 1:
>python EchoServer.py
Terminal 2:
>python EchoClient.py
Expected SERVER Output:
C:\xfer\Echo-extended>EchoServer.py
Authorizing TIE Echo
['__doc__', '__init__', '__module__', 'connection', 'container', 'httpheaders',
'parsedsoap', 'soapaction', 'xmldata']
Container: <socket._socketobject object at 0x00C03030>
Parsed SOAP: <ZSI.parse.ParsedSoap instance at 0x00C00878>
Container: <ZSI.ServiceContainer.ServiceContainer instance at 0x00BEB710>
HTTP Headers:
Host: localhost:9999
Accept-Encoding: identity
Content-length: 551
Content-type: text/xml; charset=utf-8
SOAPAction: "Echo"
----
XML Data:
<?xml version="1.0" encoding="utf-8"?>
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:ZSI="http://www.zolera.com/schemas/ZSI/"
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" >
<SOAP-ENV:Body>
<None xmlns="">
<in_str id="8fbb88" xsi:type="xsd:string">Test TIE String</in_str>
</None >
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
localhost - - [02/Feb/2005 21:35:00] "POST /EchoServer HTTP/1.1" 200 -
NOT Authorizing INHERIT Echo
['__doc__', '__init__', '__module__', 'connection', 'container', 'httpheaders',
'parsedsoap', 'soapaction', 'xmldata']
Container: <socket._socketobject object at 0x00C03030>
Parsed SOAP: <ZSI.parse.ParsedSoap instance at 0x00C5EEB8>
Container: <ZSI.ServiceContainer.ServiceContainer instance at 0x00BEB710>
HTTP Headers:
Host: localhost:9999
Accept-Encoding: identity
Content-length: 555
Content-type: text/xml; charset=utf-8
SOAPAction: "Echo"
----
XML Data:
<?xml version="1.0" encoding="utf-8"?>
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:ZSI="http://www.zolera.com/schemas/ZSI/"
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" >
<SOAP-ENV:Body>
<None xmlns="">
<in_str id="8f4cb0" xsi:type="xsd:string">Test INHERIT String</in_str>
</None >
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
localhost - - [02/Feb/2005 21:35:00] "POST /EchoServIn HTTP/1.1" 401 -
Expected CLIENT Output:
C:\xfer\Echo-extended>EchoClient.py
Test TIE StringTest TIE StringTest TIE String
Failed to echo (Inherited): Not authorized | zsi-lxml | /zsi-lxml-2.0-rc3.tar.gz/ZSI-2.0-rc3/samples/Echo/README | README |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.