code
stringlengths 501
5.19M
| package
stringlengths 2
81
| path
stringlengths 9
304
| filename
stringlengths 4
145
|
---|---|---|---|
import os
import os.path
import sys
import pkg_resources
import zc.buildout.easy_install
import zc.recipe.egg
class TestRunner:
def __init__(self, buildout, name, options):
self.buildout = buildout
self.name = name
self.options = options
options['script'] = os.path.join(buildout['buildout']['bin-directory'],
options.get('script', self.name),
)
if not options.get('working-directory', ''):
options['location'] = os.path.join(
buildout['buildout']['parts-directory'], name)
self.egg = zc.recipe.egg.Egg(buildout, name, options)
def install(self):
options = self.options
dest = []
eggs, ws = self.egg.working_set(('zope.testrunner', ))
test_paths = [ws.find(pkg_resources.Requirement.parse(spec)).location
for spec in eggs]
defaults = options.get('defaults', '').strip()
if defaults:
defaults = '(%s) + ' % defaults
wd = options.get('working-directory', '')
if not wd:
wd = options['location']
if os.path.exists(wd):
assert os.path.isdir(wd)
else:
os.mkdir(wd)
dest.append(wd)
wd = os.path.abspath(wd)
if self.egg._relative_paths:
wd = _relativize(self.egg._relative_paths, wd)
test_paths = [_relativize(self.egg._relative_paths, p)
for p in test_paths]
else:
wd = repr(wd)
test_paths = map(repr, test_paths)
initialization = initialization_template % wd
env_section = options.get('environment', '').strip()
if env_section:
env = self.buildout[env_section]
for key, value in env.items():
initialization += env_template % (key, value)
initialization_section = options.get('initialization', '').strip()
if initialization_section:
initialization += initialization_section
dest.extend(zc.buildout.easy_install.scripts(
[(options['script'], 'zope.testrunner', 'run')],
ws, options['executable'],
self.buildout['buildout']['bin-directory'],
extra_paths=self.egg.extra_paths,
arguments=defaults + (
'[\n' +
''.join((" '--test-path', %s,\n" % p)
for p in test_paths)
+ ' ]'),
initialization=initialization,
relative_paths=self.egg._relative_paths,
))
return dest
update = install
arg_template = """\
['--test-path', %(TESTPATH)s,]
"""
initialization_template = """\
import os
sys.argv[0] = os.path.abspath(sys.argv[0])
os.chdir(%s)
"""
env_template = """\
os.environ['%s'] = %r
"""
def _relativize(base, path):
base += os.path.sep
if sys.platform == 'win32':
# windoze paths are case insensitive, but startswith is not
base = base.lower()
path = path.lower()
if path.startswith(base):
path = 'join(base, %r)' % path[len(base):]
else:
path = repr(path)
return path | zc.recipe.testrunner | /zc.recipe.testrunner-3.0-py3-none-any.whl/zc/recipe/testrunner/__init__.py | __init__.py |
import pwd
import pprint
import os
import os.path
import sys
TEMPLATE = """#!%(interpreter)s
import os
import sys
env = {}
env.update(os.environ)
newenv = %(env)s
env.update(newenv)
target = '%(target)s'
base = os.path.dirname(os.path.abspath(os.path.realpath(__file__)))
base = os.path.dirname(base)
path = os.path.join(
*([os.sep,] + base.split(os.sep) + target.split(os.sep)))
args = [sys.executable] + [path] + sys.argv[1:]
os.execve(sys.executable, args, env)"""
def get_platform():
# Monkeypatch me for tests.
return sys.platform
class Wrapper(object):
def __init__(self, buildout, name, options):
self.buildout = buildout
self.name = name
self.options = options
self.supported_os = self.options.get('if-os', '').split() or ['ANY']
def install(self):
if set(['ANY'] + [get_platform()]) & set(self.supported_os):
options = {}
options.update(self.options)
options['deployment'] = self.options.get('deployment', '')
options['if-os'] = self.options.get('if-os', 'ANY')
options['name'] = self.options.get('name', self.name)
if 'deployment' in self.options:
deployment = self.buildout[self.options['deployment']]
path = deployment['rc-directory']
user = deployment['user']
else:
path = self.buildout['buildout']['directory']
user = pwd.getpwuid(os.geteuid()).pw_name
options['path'] = os.path.join(
os.sep, path, 'bin', options['name'])
self.options.update(options)
parameters = dict(
env = pprint.pformat(
self.buildout[self.options['environment']]),
interpreter = self.buildout['buildout']['executable'],
target = self.options['target'],)
wrapper = open(self.options['path'], 'w')
wrapper.write(TEMPLATE % parameters)
wrapper.close()
os.chmod(options['path'], 0755)
os.chown(options['path'], *(pwd.getpwnam(user)[2:4]))
return ()
update = install
def uninstall(self):
if set(['ANY'] + [get_platform()]) & set(self.supported_os):
os.remove(self.options['path']) | zc.recipe.wrapper | /zc.recipe.wrapper-1.1.0.tar.gz/zc.recipe.wrapper-1.1.0/src/zc/recipe/wrapper/__init__.py | __init__.py |
=======
Changes
=======
2.0 (2023-04-05)
================
- Drop support for Python 2.7, 3.5, 3.6.
[ale-rt]
- Fix the dependency on the ZODB, we just need to depend on the BTrees package.
Refs. #11.
[ale-rt]
1.2 (2023-03-28)
================
- Adapt code for PEP-479 (Change StopIteration handling inside generators).
See: https://peps.python.org/pep-0479.
Fixes #11.
[ale-rt]
1.1.post2 (2018-06-18)
======================
- Another attempt to fix PyPI page by using correct expected metadata syntax.
1.1.post1 (2018-06-18)
======================
- Fix PyPI page by using correct ReST syntax.
1.1 (2018-06-15)
================
- Add support for Python 3.5 and 3.6.
1.0 (2008-04-23)
================
This is the initial release of the zc.relation package. However, it
represents a refactoring of another package, zc.relationship. This
package contains only a modified version of the relation(ship) index,
now called a catalog. The refactored version of zc.relationship index
relies on (subclasses) this catalog. zc.relationship also maintains a
backwards-compatible subclass.
This package only relies on the ZODB, zope.interface, and zope.testing
software, and can be used inside or outside of a standard ZODB database.
The software does have to be there, though (the package relies heavily
on the ZODB BTrees package).
If you would like to switch a legacy zc.relationship index to a
zc.relation catalog, try this trick in your generations script.
Assuming the old index is ``old``, the following line should create
a new zc.relation catalog with your legacy data:
>>> new = old.copy(zc.relation.Catalog)
Why is the same basic data structure called a catalog now? Because we
exposed the ability to mutate the data structure, and what you are really
adding and removing are indexes. It didn't make sense to put an index in
an index, but it does make sense to put an index in a catalog. Thus, a
name change was born.
The catalog in this package has several incompatibilities from the earlier
zc.relationship index, and many new features. The zc.relationship package
maintains a backwards-compatible subclass. The following discussion
compares the zc.relation catalog with the zc.relationship 1.x index.
Incompatibilities with zc.relationship 1.x index
------------------------------------------------
The two big changes are that method names now refer to ``Relation`` rather
than ``Relationship``; and the catalog is instantiated slightly differently
from the index. A few other changes are worth your attention. The
following list attempts to highlight all incompatibilities.
:Big incompatibilities:
- ``findRelationshipTokenSet`` and ``findValueTokenSet`` are renamed, with
some slightly different semantics, as ``getRelationTokens`` and
``getValueTokens``. The exact same result as
``findRelationTokenSet(query)`` can be obtained with
``findRelationTokens(query, 1)`` (where 1 is maxDepth). The same
result as ``findValueTokenSet(reltoken, name)`` can be obtained with
``findValueTokens(name, {zc.relation.RELATION: reltoken}, 1)``.
- ``findRelations`` replaces ``findRelatonships``. The new method will use
the defaultTransitiveQueriesFactory if it is set and maxDepth is not 1.
It shares the call signature of ``findRelationChains``.
- ``isLinked`` is now ``canFind``.
- The catalog instantiation arguments have changed from the old index.
* ``load`` and ``dump`` (formerly ``loadRel`` and ``dumpRel``,
respectively) are now required arguments for instantiation.
* The only other optional arguments are ``btree`` (was ``relFamily``) and
``family``. You now specify what elements to index with
``addValueIndex``
* Note also that ``addValueIndex`` defaults to no load and dump function,
unlike the old instantiation options.
- query factories are different. See ``IQueryFactory`` in the interfaces.
* they first get (query, catalog, cache) and then return a getQueries
callable that gets relchains and yields queries; OR None if they
don't match.
* They must also handle an empty relchain. Typically this should
return the original query, but may also be used to mutate the
original query.
* They are no longer thought of as transitive query factories, but as
general query mutators.
:Medium:
- The catalog no longer inherits from
zope.app.container.contained.Contained.
- The index requires ZODB 3.8 or higher.
:Small:
- ``deactivateSets`` is no longer an instantiation option (it was broken
because of a ZODB bug anyway, as had been described in the
documentation).
Changes and new features
------------------------
- The catalog now offers the ability to index certain
searches. The indexes must be explicitly instantiated and registered
you want to optimize. This can be used when searching for values, when
searching for relations, or when determining if two objects are
linked. It cannot be used for relation chains. Requesting an index
has the usual trade-offs of greater storage space and slower write
speed for faster search speed. Registering a search index is done
after instantiation time; you can iteratate over the current settings
used, and remove them. (The code path expects to support legacy
zc.relationship index instances for all of these APIs.)
- You can now specify new values after the catalog has been created, iterate
over the settings used, and remove values.
- The catalog has a copy method, to quickly make new copies without actually
having to reindex the relations.
- query arguments can now specify multiple values for a given name by
using zc.relation.catalog.any(1, 2, 3, 4) or
zc.relation.catalog.Any((1, 2, 3, 4)).
- The catalog supports specifying indexed values by passing callables rather
than interface elements (which are also still supported).
- ``findRelations`` and new method ``findRelationTokens`` can find
relations transitively and intransitively. ``findRelationTokens``
when used intransitively repeats the legacy zc.relationship index
behavior of ``findRelationTokenSet``.
(``findRelationTokenSet`` remains in the API, not deprecated, a companion
to ``findValueTokenSet``.)
- in findValues and findValueTokens, ``query`` argument is now optional. If
the query evaluates to False in a boolean context, all values, or value
tokens, are returned. Value tokens are explicitly returned using the
underlying BTree storage. This can then be used directly for other BTree
operations.
- Completely new docs. Unfortunately, still really not good enough.
- The package has drastically reduced direct dependecies from zc.relationship:
it is now more clearly a ZODB tool, with no other Zope dependencies than
zope.testing and zope.interface.
- Listeners allow objects to listen to messages from the catalog (which can
be used directly or, for instance, to fire off events).
- You can search for relations, using a key of zc.relation.RELATION...which is
really an alias for None. Sorry. But hey, use the constant! I think it is
more readable.
- tokenizeQuery (and resolveQuery) now accept keyword arguments as an
alternative to a normal dict query. This can make constructing the query
a bit more attractive (i.e., ``query = catalog.tokenizeQuery;
res = catalog.findValues('object', query(subject=joe, predicate=OWNS))``).
| zc.relation | /zc.relation-2.0.tar.gz/zc.relation-2.0/CHANGES.rst | CHANGES.rst |
To develop this package from source:
- check out the software from the repository
- ``cd`` to the checkout
- Ideally with a clean, non-system python, run
``python bootstrap.py``
- run ``./bin/buildout``
To run tests, run *both* of the following:
- ``./bin/test``: this tests zc.relation alone
- ``./bin/testall``: this tests zc.relation and zc.relationship, to make sure
that zc.relation changes do not break zc.relationship tests.
Changes should be documented in CHANGES.rst *in the package*.
Before making a release that registers the software to PyPI, run the
`longtest` command of the ``zest.releaser`` package to check for errors
in the ``long_description``.
Once this works, go ahead and ``./bin/py setup.py sdist upload``.
| zc.relation | /zc.relation-2.0.tar.gz/zc.relation-2.0/DEVELOP.rst | DEVELOP.rst |
================
Relation Catalog
================
.. contents::
Overview
========
The relation catalog can be used to optimize intransitive and transitive
searches for N-ary relations of finite, preset dimensions.
For example, you can index simple two-way relations, like employee to
supervisor; RDF-style triples of subject-predicate-object; and more complex
relations such as subject-predicate-object with context and state. These
can be searched with variable definitions of transitive behavior.
The catalog can be used in the ZODB or standalone. It is a generic, relatively
policy-free tool.
It is expected to be used usually as an engine for more specialized and
constrained tools and APIs. Three such tools are zc.relationship containers,
plone.relations containers, and zc.vault. The documents in the package,
including this one, describe other possible uses.
History
=======
This is a refactoring of the ZODB-only parts of the zc.relationship package.
Specifically, the zc.relation catalog is largely equivalent to the
zc.relationship index. The index in the zc.relationship 2.x line is an
almost-completely backwards-compatible wrapper of the zc.relation catalog.
zc.relationship will continue to be maintained, though active development is
expected to go into zc.relation.
Many of the ideas come from discussions with and code from Casey Duncan, Tres
Seaver, Ken Manheimer, and more.
Setting Up a Relation Catalog
=============================
In this section, we will be introducing the following ideas.
- Relations are objects with indexed values.
- You add value indexes to relation catalogs to be able to search. Values
can be identified to the catalog with callables or interface elements. The
indexed value must be specified to the catalog as a single value or a
collection.
- Relations and their values are stored in the catalog as tokens: unique
identifiers that you can resolve back to the original value. Integers are the
most efficient tokens, but others can work fine too.
- Token type determines the BTree module needed.
- You must define your own functions for tokenizing and resolving tokens. These
functions are registered with the catalog for the relations and for each of
their value indexes.
- Relations are indexed with ``index``.
We will use a simple two way relation as our example here. A brief introduction
to a more complex RDF-style subject-predicate-object set up can be found later
in the document.
Creating the Catalog
--------------------
Imagine a two way relation from one value to another. Let's say that we
are modeling a relation of people to their supervisors: an employee may
have a single supervisor. For this first example, the relation between
employee and supervisor will be intrinsic: the employee has a pointer to
the supervisor, and the employee object itself represents the relation.
Let's say further, for simplicity, that employee names are unique and
can be used to represent employees. We can use names as our "tokens".
Tokens are similar to the primary key in a relational database. A token is a
way to identify an object. It must sort reliably and you must be able to write
a callable that reliably resolves to the object given the right context. In
Zope 3, intids (zope.app.intid) and keyreferences (zope.app.keyreference) are
good examples of reasonable tokens.
As we'll see below, you provide a way to convert objects to tokens, and resolve
tokens to objects, for the relations, and for each value index individually.
They can be the all the same functions or completely different, depending on
your needs.
For speed, integers make the best tokens; followed by other
immutables like strings; followed by non-persistent objects; followed by
persistent objects. The choice also determines a choice of BTree module, as
we'll see below.
Here is our toy ``Employee`` example class. Again, we will use the employee
name as the tokens.
>>> employees = {} # we'll use this to resolve the "name" tokens
>>> from functools import total_ordering
>>> @total_ordering
... class Employee(object):
... def __init__(self, name, supervisor=None):
... if name in employees:
... raise ValueError('employee with same name already exists')
... self.name = name # expect this to be readonly
... self.supervisor = supervisor
... employees[name] = self
... # the next parts just make the tests prettier
... def __repr__(self):
... return '<Employee instance "' + self.name + '">'
... def __lt__(self, other):
... return self.name < other.name
... def __eq__(self, other):
... return self is other
... def __hash__(self):
... ''' Dummy method needed because we defined __eq__
... '''
... return 1
...
So, we need to define how to turn employees into their tokens. We call the
tokenization a "dump" function. Conversely, the function to resolve tokens into
objects is called a "load".
Functions to dump relations and values get several arguments. The first
argument is the object to be tokenized. Next, because it helps sometimes to
provide context, is the catalog. The last argument is a dictionary that will be
shared for a given search. The dictionary can be ignored, or used as a cache
for optimizations (for instance, to stash a utility that you looked up).
For this example, our function is trivial: we said the token would be
the employee's name.
>>> def dumpEmployees(emp, catalog, cache):
... return emp.name
...
If you store the relation catalog persistently (e.g., in the ZODB) be aware
that the callables you provide must be picklable--a module-level function,
for instance.
We also need a way to turn tokens into employees, or "load".
The "load" functions get the token to be resolved; the catalog, for
context; and a dict cache, for optimizations of subsequent calls.
You might have noticed in our ``Employee.__init__`` that we keep a mapping
of name to object in the ``employees`` global dict (defined right above
the class definition). We'll use that for resolving the tokens.
>>> def loadEmployees(token, catalog, cache):
... return employees[token]
...
Now we know enough to get started with a catalog. We'll instantiate it
by specifying how to tokenize relations, and what kind of BTree modules
should be used to hold the tokens.
How do you pick BTree modules?
- If the tokens are 32-bit ints, choose ``BTrees.family32.II``,
``BTrees.family32.IF`` or ``BTrees.family32.IO``.
- If the tokens are 64 bit ints, choose ``BTrees.family64.II``,
``BTrees.family64.IF`` or ``BTrees.family64.IO``.
- If they are anything else, choose ``BTrees.family32.OI``,
``BTrees.family64.OI``, or ``BTrees.family32.OO`` (or
``BTrees.family64.OO``--they are the same).
Within these rules, the choice is somewhat arbitrary unless you plan to merge
these results with that of another source that is using a particular BTree
module. BTree set operations only work within the same module, so you must
match module to module. The catalog defaults to IF trees, because that's what
standard zope catalogs use. That's as reasonable a choice as any, and will
potentially come in handy if your tokens are in fact the same as those used by
the zope catalog and you want to do some set operations.
In this example, our tokens are strings, so we want OO or an OI variant. We'll
choose BTrees.family32.OI, arbitrarily.
>>> import zc.relation.catalog
>>> import BTrees
>>> catalog = zc.relation.catalog.Catalog(dumpEmployees, loadEmployees,
... btree=BTrees.family32.OI)
[#verifyObjectICatalog]_
.. [#verifyObjectICatalog] The catalog provides ICatalog.
>>> from zope.interface.verify import verifyObject
>>> import zc.relation.interfaces
>>> verifyObject(zc.relation.interfaces.ICatalog, catalog)
True
[#legacy]_
.. [#legacy] Old instances of zc.relationship indexes, which in the newest
version subclass a zc.relation Catalog, used to have a dict in an
internal data structure. We specify that here so that the code that
converts the dict to an OOBTree can have a chance to run.
>>> catalog._attrs = dict(catalog._attrs)
Look! A relation catalog! We can't do very
much searching with it so far though, because the catalog doesn't have any
indexes.
In this example, the relation itself represents the employee, so we won't need
to index that separately.
But we do need a way to tell the catalog how to find the other end of the
relation, the supervisor. You can specify this to the catalog with an attribute
or method specified from ``zope.interface Interface``, or with a callable.
We'll use a callable for now. The callable will receive the indexed relation
and the catalog for context.
>>> def supervisor(emp, catalog):
... return emp.supervisor # None or another employee
...
We'll also need to specify how to tokenize (dump and load) those values. In
this case, we're able to use the same functions as the relations themselves.
However, do note that we can specify a completely different way to dump and
load for each "value index," or relation element.
We could also specify the name to call the index, but it will default to the
``__name__`` of the function (or interface element), which will work just fine
for us now.
Now we can add the "supervisor" value index.
>>> catalog.addValueIndex(supervisor, dumpEmployees, loadEmployees,
... btree=BTrees.family32.OI)
Now we have an index [#addValueIndexExceptions]_.
.. [#addValueIndexExceptions] Adding a value index can generate several
exceptions.
You must supply both of dump and load or neither.
>>> catalog.addValueIndex(supervisor, dumpEmployees, None,
... btree=BTrees.family32.OI, name='supervisor2')
Traceback (most recent call last):
...
ValueError: either both of 'dump' and 'load' must be None, or neither
In this example, even if we fix it, we'll get an error, because we have
already indexed the supervisor function.
>>> catalog.addValueIndex(supervisor, dumpEmployees, loadEmployees,
... btree=BTrees.family32.OI, name='supervisor2')
... # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: ('element already indexed', <function supervisor at ...>)
You also can't add a different function under the same name.
>>> def supervisor2(emp, catalog):
... return emp.supervisor # None or another employee
...
>>> catalog.addValueIndex(supervisor2, dumpEmployees, loadEmployees,
... btree=BTrees.family32.OI, name='supervisor')
... # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: ('name already used', 'supervisor')
Finally, if your function does not have a ``__name__`` and you do not
provide one, you may not add an index.
>>> class Supervisor3(object):
... __name__ = None
... def __call__(klass, emp, catalog):
... return emp.supervisor
...
>>> supervisor3 = Supervisor3()
>>> supervisor3.__name__
>>> catalog.addValueIndex(supervisor3, dumpEmployees, loadEmployees,
... btree=BTrees.family32.OI)
... # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: no name specified
>>> [info['name'] for info in catalog.iterValueIndexInfo()]
['supervisor']
Adding Relations
----------------
Now let's create a few employees. All but one will have supervisors.
If you recall our toy ``Employee`` class, the first argument to the
constructor is the employee name (and therefore the token), and the
optional second argument is the supervisor.
>>> a = Employee('Alice')
>>> b = Employee('Betty', a)
>>> c = Employee('Chuck', a)
>>> d = Employee('Diane', b)
>>> e = Employee('Edgar', b)
>>> f = Employee('Frank', c)
>>> g = Employee('Galyn', c)
>>> h = Employee('Howie', d)
Here is a diagram of the hierarchy.
::
Alice
__/ \__
Betty Chuck
/ \ / \
Diane Edgar Frank Galyn
|
Howie
Let's tell the catalog about the relations, using the ``index`` method.
>>> for emp in (a,b,c,d,e,f,g,h):
... catalog.index(emp)
...
We've now created the relation catalog and added relations to it. We're ready
to search!
Searching
=========
In this section, we will introduce the following ideas.
- Queries to the relation catalog are formed with dicts.
- Query keys are the names of the indexes you want to search, or, for the
special case of precise relations, the ``zc.relation.RELATION`` constant.
- Query values are the tokens of the results you want to match; or ``None``,
indicating relations that have ``None`` as a value (or an empty collection,
if it is a multiple). Search values can use
``zc.relation.catalog.any(args)`` or ``zc.relation.catalog.Any(args)`` to
specify multiple (non-``None``) results to match for a given key.
- The index has a variety of methods to help you work with tokens.
``tokenizeQuery`` is typically the most used, though others are available.
- To find relations that match a query, use ``findRelations`` or
``findRelationTokens``.
- To find values that match a query, use ``findValues`` or ``findValueTokens``.
- You search transitively by using a query factory. The
``zc.relation.queryfactory.TransposingTransitive`` is a good common case
factory that lets you walk up and down a hierarchy. A query factory can be
passed in as an argument to search methods as a ``queryFactory``, or
installed as a default behavior using ``addDefaultQueryFactory``.
- To find how a query is related, use ``findRelationChains`` or
``findRelationTokenChains``.
- To find out if a query is related, use ``canFind``.
- Circular transitive relations are handled to prevent infinite loops. They
are identified in ``findRelationChains`` and ``findRelationTokenChains`` with
a ``zc.relation.interfaces.ICircularRelationPath`` marker interface.
- search methods share the following arguments:
* ``maxDepth``, limiting the transitive depth for searches;
* ``filter``, allowing code to filter transitive paths;
* ``targetQuery``, allowing a query to filter transitive paths on the basis
of the endpoint;
* ``targetFilter``, allowing code to filter transitive paths on the basis of
the endpoint; and
* ``queryFactory``, mentioned above.
- You can set up search indexes to speed up specific transitive searches.
Queries, ``findRelations``, and special query values
----------------------------------------------------
So who works for Alice? That means we want to get the relations--the
employees--with a ``supervisor`` of Alice.
The heart of a question to the catalog is a query. A query is spelled
as a dictionary. The main idea is simply that keys in a dictionary
specify index names, and the values specify the constraints.
The values in a query are always expressed with tokens. The catalog has
several helpers to make this less onerous, but for now let's take
advantage of the fact that our tokens are easily comprehensible.
>>> sorted(catalog.findRelations({'supervisor': 'Alice'}))
[<Employee instance "Betty">, <Employee instance "Chuck">]
Alice is the direct (intransitive) boss of Betty and Chuck.
What if you want to ask "who doesn't report to anyone?" Then you want to
ask for a relation in which the supervisor is None.
>>> list(catalog.findRelations({'supervisor': None}))
[<Employee instance "Alice">]
Alice is the only employee who doesn't report to anyone.
What if you want to ask "who reports to Diane or Chuck?" Then you use the
zc.relation ``Any`` class or ``any`` function to pass the multiple values.
>>> sorted(catalog.findRelations(
... {'supervisor': zc.relation.catalog.any('Diane', 'Chuck')}))
... # doctest: +NORMALIZE_WHITESPACE
[<Employee instance "Frank">, <Employee instance "Galyn">,
<Employee instance "Howie">]
Frank, Galyn, and Howie each report to either Diane or Chuck. [#any]_
.. [#any] ``Any`` can be compared.
>>> zc.relation.catalog.any('foo', 'bar', 'baz')
<zc.relation.catalog.Any instance ('bar', 'baz', 'foo')>
>>> (zc.relation.catalog.any('foo', 'bar', 'baz') ==
... zc.relation.catalog.any('bar', 'foo', 'baz'))
True
>>> (zc.relation.catalog.any('foo', 'bar', 'baz') !=
... zc.relation.catalog.any('bar', 'foo', 'baz'))
False
>>> (zc.relation.catalog.any('foo', 'bar', 'baz') ==
... zc.relation.catalog.any('foo', 'baz'))
False
>>> (zc.relation.catalog.any('foo', 'bar', 'baz') !=
... zc.relation.catalog.any('foo', 'baz'))
True
``findValues`` and the ``RELATION`` query key
---------------------------------------------
So how do we find who an employee's supervisor is? Well, in this case,
look at the attribute on the employee! If you can use an attribute that
will usually be a win in the ZODB.
>>> h.supervisor
<Employee instance "Diane">
Again, as we mentioned at the start of this first example, the knowledge
of a supervisor is "intrinsic" to the employee instance. It is
possible, and even easy, to ask the catalog this kind of question, but
the catalog syntax is more geared to "extrinsic" relations, such as the
one from the supervisor to the employee: the connection between a
supervisor object and its employees is extrinsic to the supervisor, so
you actually might want a catalog to find it!
However, we will explore the syntax very briefly, because it introduces an
important pair of search methods, and because it is a stepping stone
to our first transitive search.
So, o relation catalog, who is Howie's supervisor?
To ask this question we want to get the indexed values off of the relations:
``findValues``. In its simplest form, the arguments are the index name of the
values you want, and a query to find the relations that have the desired
values.
What about the query? Above, we noted that the keys in a query are the names of
the indexes to search. However, in this case, we don't want to search one or
more indexes for matching relations, as usual, but actually specify a relation:
Howie.
We do not have a value index name: we are looking for a relation. The query
key, then, should be the constant ``zc.relation.RELATION``. For our current
example, that would mean the query is ``{zc.relation.RELATION: 'Howie'}``.
>>> import zc.relation
>>> list(catalog.findValues(
... 'supervisor', {zc.relation.RELATION: 'Howie'}))[0]
<Employee instance "Diane">
Congratulations, you just found an obfuscated and comparitively
inefficient way to write ``howie.supervisor``! [#intrinsic_search]_
.. [#intrinsic_search] Here's the same with token results.
>>> list(catalog.findValueTokens('supervisor',
... {zc.relation.RELATION: 'Howie'}))
['Diane']
While we're down here in the footnotes, I'll mention that you can
search for relations that haven't been indexed.
>>> list(catalog.findRelationTokens({zc.relation.RELATION: 'Ygritte'}))
[]
>>> list(catalog.findRelations({zc.relation.RELATION: 'Ygritte'}))
[]
[#findValuesExceptions]_
.. [#findValuesExceptions] If you use ``findValues`` or ``findValueTokens`` and
try to specify a value name that is not indexed, you get a ValueError.
>>> catalog.findValues('foo')
Traceback (most recent call last):
...
ValueError: ('name not indexed', 'foo')
Slightly more usefully, you can use other query keys along with
zc.relation.RELATION. This asks, "Of Betty, Alice, and Frank, who are
supervised by Alice?"
>>> sorted(catalog.findRelations(
... {zc.relation.RELATION: zc.relation.catalog.any(
... 'Betty', 'Alice', 'Frank'),
... 'supervisor': 'Alice'}))
[<Employee instance "Betty">]
Only Betty is.
Tokens
------
As mentioned above, the catalog provides several helpers to work with tokens.
The most frequently used is ``tokenizeQuery``, which takes a query with object
values and converts them to tokens using the "dump" functions registered for
the relations and indexed values. Here are alternate spellings of some of the
queries we've encountered above.
>>> catalog.tokenizeQuery({'supervisor': a})
{'supervisor': 'Alice'}
>>> catalog.tokenizeQuery({'supervisor': None})
{'supervisor': None}
>>> import pprint
>>> result = catalog.tokenizeQuery(
... {zc.relation.RELATION: zc.relation.catalog.any(a, b, f),
... 'supervisor': a}) # doctest: +NORMALIZE_WHITESPACE
>>> pprint.pprint(result)
{None: <zc.relation.catalog.Any instance ('Alice', 'Betty', 'Frank')>,
'supervisor': 'Alice'}
(If you are wondering about that ``None`` in the last result, yes,
``zc.relation.RELATION`` is just readability sugar for ``None``.)
So, here's a real search using ``tokenizeQuery``. We'll make an alias for
``catalog.tokenizeQuery`` just to shorten things up a bit.
>>> query = catalog.tokenizeQuery
>>> sorted(catalog.findRelations(query(
... {zc.relation.RELATION: zc.relation.catalog.any(a, b, f),
... 'supervisor': a})))
[<Employee instance "Betty">]
The catalog always has parallel search methods, one for finding objects, as
seen above, and one for finding tokens (the only exception is ``canFind``,
described below). Finding tokens can be much more efficient, especially if the
result from the relation catalog is just one step along the path of finding
your desired result. But finding objects is simpler for some common cases.
Here's a quick example of some queries above, getting tokens rather than
objects.
You can also spell a query in ``tokenizeQuery`` with keyword arguments. This
won't work if your key is ``zc.relation.RELATION``, but otherwise it can
improve readability. We'll see some examples of this below as well.
>>> sorted(catalog.findRelationTokens(query(supervisor=a)))
['Betty', 'Chuck']
>>> sorted(catalog.findRelationTokens({'supervisor': None}))
['Alice']
>>> sorted(catalog.findRelationTokens(
... query(supervisor=zc.relation.catalog.any(c, d))))
['Frank', 'Galyn', 'Howie']
>>> sorted(catalog.findRelationTokens(
... query({zc.relation.RELATION: zc.relation.catalog.any(a, b, f),
... 'supervisor': a})))
['Betty']
The catalog provides several other methods just for working with tokens.
- ``resolveQuery``: the inverse of ``tokenizeQuery``, converting a
tokenizedquery to a query with objects.
- ``tokenizeValues``: returns an iterable of tokens for the values of the given
index name.
- ``resolveValueTokens``: returns an iterable of values for the tokens of the
given index name.
- ``tokenizeRelation``: returns a token for the given relation.
- ``resolveRelationToken``: returns a relation for the given token.
- ``tokenizeRelations``: returns an iterable of tokens for the relations given.
- ``resolveRelationTokens``: returns an iterable of relations for the tokens
given.
These methods are lesser used, and described in more technical documents in
this package.
Transitive Searching, Query Factories, and ``maxDepth``
-------------------------------------------------------
So, we've seen a lot of one-level, intransitive searching. What about
transitive searching? Well, you need to tell the catalog how to walk the tree.
In simple (and very common) cases like this, the
``zc.relation.queryfactory.TransposingTransitive`` will do the trick.
A transitive query factory is just a callable that the catalog uses to
ask "I got this query, and here are the results I found. I'm supposed to
walk another step transitively, so what query should I search for next?"
Writing a factory is more complex than we want to talk about right now,
but using the ``TransposingTransitiveQueryFactory`` is easy. You just tell
it the two query names it should transpose for walking in either
direction.
For instance, here we just want to tell the factory to transpose the two keys
we've used, ``zc.relation.RELATION`` and 'supervisor'. Let's make a factory,
use it in a query for a couple of transitive searches, and then, if you want,
you can read through a footnote to talk through what is happening.
Here's the factory.
>>> import zc.relation.queryfactory
>>> factory = zc.relation.queryfactory.TransposingTransitive(
... zc.relation.RELATION, 'supervisor')
Now ``factory`` is just a callable. Let's let it help answer a couple of
questions.
Who are all of Howie's supervisors transitively (this looks up in the
diagram)?
>>> list(catalog.findValues('supervisor', {zc.relation.RELATION: 'Howie'},
... queryFactory=factory))
... # doctest: +NORMALIZE_WHITESPACE
[<Employee instance "Diane">, <Employee instance "Betty">,
<Employee instance "Alice">]
Who are all of the people Betty supervises transitively, breadth first (this
looks down in the diagram)?
>>> people = list(catalog.findRelations(
... {'supervisor': 'Betty'}, queryFactory=factory))
>>> sorted(people[:2])
[<Employee instance "Diane">, <Employee instance "Edgar">]
>>> people[2]
<Employee instance "Howie">
Yup, that looks right. So how did that work? If you care, read this
footnote. [#I_care]_
This transitive factory is really the only transitive factory you would
want for this particular catalog, so it probably is safe to wire it in
as a default. You can add multiple query factories to match different
queries using ``addDefaultQueryFactory``.
>>> catalog.addDefaultQueryFactory(factory)
Now all searches are transitive by default.
>>> list(catalog.findValues('supervisor', {zc.relation.RELATION: 'Howie'}))
... # doctest: +NORMALIZE_WHITESPACE
[<Employee instance "Diane">, <Employee instance "Betty">,
<Employee instance "Alice">]
>>> people = list(catalog.findRelations({'supervisor': 'Betty'}))
>>> sorted(people[:2])
[<Employee instance "Diane">, <Employee instance "Edgar">]
>>> people[2]
<Employee instance "Howie">
We can force a non-transitive search, or a specific search depth, with
``maxDepth`` [#needs_a_transitive_queries_factory]_.
.. [#needs_a_transitive_queries_factory] A search with a ``maxDepth`` > 1 but
no ``queryFactory`` raises an error.
>>> catalog.removeDefaultQueryFactory(factory)
>>> catalog.findRelationTokens({'supervisor': 'Diane'}, maxDepth=3)
Traceback (most recent call last):
...
ValueError: if maxDepth not in (None, 1), queryFactory must be available
>>> catalog.addDefaultQueryFactory(factory)
>>> list(catalog.findValues(
... 'supervisor', {zc.relation.RELATION: 'Howie'}, maxDepth=1))
[<Employee instance "Diane">]
>>> sorted(catalog.findRelations({'supervisor': 'Betty'}, maxDepth=1))
[<Employee instance "Diane">, <Employee instance "Edgar">]
[#maxDepthExceptions]_
.. [#maxDepthExceptions] ``maxDepth`` must be None or a positive integer, or
else you'll get a value error.
>>> catalog.findRelations({'supervisor': 'Betty'}, maxDepth=0)
Traceback (most recent call last):
...
ValueError: maxDepth must be None or a positive integer
>>> catalog.findRelations({'supervisor': 'Betty'}, maxDepth=-1)
Traceback (most recent call last):
...
ValueError: maxDepth must be None or a positive integer
We'll introduce some other available search
arguments later in this document and in other documents. It's important
to note that *all search methods share the same arguments as
``findRelations``*. ``findValues`` and ``findValueTokens`` only add the
initial argument of specifying the desired value.
We've looked at two search methods so far: the ``findValues`` and
``findRelations`` methods help you ask what is related. But what if you
want to know *how* things are transitively related?
``findRelationChains`` and ``targetQuery``
------------------------------------------
Another search method, ``findRelationChains``, helps you discover how
things are transitively related.
The method name says "find relation chains". But what is a "relation
chain"? In this API, it is a transitive path of relations. For
instance, what's the chain of command above Howie? ``findRelationChains``
will return each unique path.
>>> list(catalog.findRelationChains({zc.relation.RELATION: 'Howie'}))
... # doctest: +NORMALIZE_WHITESPACE
[(<Employee instance "Howie">,),
(<Employee instance "Howie">, <Employee instance "Diane">),
(<Employee instance "Howie">, <Employee instance "Diane">,
<Employee instance "Betty">),
(<Employee instance "Howie">, <Employee instance "Diane">,
<Employee instance "Betty">, <Employee instance "Alice">)]
Look at that result carefully. Notice that the result is an iterable of
tuples. Each tuple is a unique chain, which may be a part of a
subsequent chain. In this case, the last chain is the longest and the
most comprehensive.
What if we wanted to see all the paths from Alice? That will be one
chain for each supervised employee, because it shows all possible paths.
>>> sorted(catalog.findRelationChains(
... {'supervisor': 'Alice'}))
... # doctest: +NORMALIZE_WHITESPACE
[(<Employee instance "Betty">,),
(<Employee instance "Betty">, <Employee instance "Diane">),
(<Employee instance "Betty">, <Employee instance "Diane">,
<Employee instance "Howie">),
(<Employee instance "Betty">, <Employee instance "Edgar">),
(<Employee instance "Chuck">,),
(<Employee instance "Chuck">, <Employee instance "Frank">),
(<Employee instance "Chuck">, <Employee instance "Galyn">)]
That's all the paths--all the chains--from Alice. We sorted the results,
but normally they would be breadth first.
But what if we wanted to just find the paths from one query result to
another query result--say, we wanted to know the chain of command from Alice
down to Howie? Then we can specify a ``targetQuery`` that specifies the
characteristics of our desired end point (or points).
>>> list(catalog.findRelationChains(
... {'supervisor': 'Alice'},
... targetQuery={zc.relation.RELATION: 'Howie'}))
... # doctest: +NORMALIZE_WHITESPACE
[(<Employee instance "Betty">, <Employee instance "Diane">,
<Employee instance "Howie">)]
So, Betty supervises Diane, who supervises Howie.
Note that ``targetQuery`` now joins ``maxDepth`` in our collection of shared
search arguments that we have introduced.
``filter`` and ``targetFilter``
-------------------------------
We can take a quick look now at the last of the two shared search arguments:
``filter`` and ``targetFilter``. These two are similar in that they both are
callables that can approve or reject given relations in a search based on
whatever logic you can code. They differ in that ``filter`` stops any further
transitive searches from the relation, while ``targetFilter`` merely omits the
given result but allows further search from it. Like ``targetQuery``, then,
``targetFilter`` is good when you want to specify the other end of a path.
As an example, let's say we only want to return female employees.
>>> female_employees = ('Alice', 'Betty', 'Diane', 'Galyn')
>>> def female_filter(relchain, query, catalog, cache):
... return relchain[-1] in female_employees
...
Here are all the female employees supervised by Alice transitively, using
``targetFilter``.
>>> list(catalog.findRelations({'supervisor': 'Alice'},
... targetFilter=female_filter))
... # doctest: +NORMALIZE_WHITESPACE
[<Employee instance "Betty">, <Employee instance "Diane">,
<Employee instance "Galyn">]
Here are all the female employees supervised by Chuck.
>>> list(catalog.findRelations({'supervisor': 'Chuck'},
... targetFilter=female_filter))
[<Employee instance "Galyn">]
The same method used as a filter will only return females directly
supervised by other females--not Galyn, in this case.
>>> list(catalog.findRelations({'supervisor': 'Alice'},
... filter=female_filter))
[<Employee instance "Betty">, <Employee instance "Diane">]
These can be combined with one another, and with the other search
arguments [#filter]_.
.. [#filter] For instance:
>>> list(catalog.findRelationTokens(
... {'supervisor': 'Alice'}, targetFilter=female_filter,
... targetQuery={zc.relation.RELATION: 'Galyn'}))
['Galyn']
>>> list(catalog.findRelationTokens(
... {'supervisor': 'Alice'}, targetFilter=female_filter,
... targetQuery={zc.relation.RELATION: 'Not known'}))
[]
>>> arbitrary = ['Alice', 'Chuck', 'Betty', 'Galyn']
>>> def arbitrary_filter(relchain, query, catalog, cache):
... return relchain[-1] in arbitrary
>>> list(catalog.findRelationTokens({'supervisor': 'Alice'},
... filter=arbitrary_filter,
... targetFilter=female_filter))
['Betty', 'Galyn']
Search indexes
--------------
Without setting up any additional indexes, the transitive behavior of
the ``findRelations`` and ``findValues`` methods essentially relies on the
brute force searches of ``findRelationChains``. Results are iterables
that are gradually computed. For instance, let's repeat the question
"Whom does Betty supervise?". Notice that ``res`` first populates a list
with three members, but then does not populate a second list. The
iterator has been exhausted.
>>> res = catalog.findRelationTokens({'supervisor': 'Betty'})
>>> unindexed = sorted(res)
>>> len(unindexed)
3
>>> len(list(res)) # iterator is exhausted
0
The brute force of this approach can be sufficient in many cases, but
sometimes speed for these searches is critical. In these cases, you can
add a "search index". A search index speeds up the result of one or
more precise searches by indexing the results. Search indexes can
affect the results of searches with a ``queryFactory`` in ``findRelations``,
``findValues``, and the soon-to-be-introduced ``canFind``, but they do not
affect ``findRelationChains``.
The zc.relation package currently includes two kinds of search indexes, one for
indexing transitive membership searches in a hierarchy and one for intransitive
searches explored in tokens.rst in this package, which can optimize frequent
searches on complex queries or can effectively change the meaning of an
intransitive search. Other search index implementations and approaches may be
added in the future.
Here's a very brief example of adding a search index for the transitive
searches seen above that specify a 'supervisor'.
>>> import zc.relation.searchindex
>>> catalog.addSearchIndex(
... zc.relation.searchindex.TransposingTransitiveMembership(
... 'supervisor', zc.relation.RELATION))
The ``zc.relation.RELATION`` describes how to walk back up the chain. Search
indexes are explained in reasonable detail in searchindex.rst.
Now that we have added the index, we can search again. The result this
time is already computed, so, at least when you ask for tokens, it
is repeatable.
>>> res = catalog.findRelationTokens({'supervisor': 'Betty'})
>>> len(list(res))
3
>>> len(list(res))
3
>>> sorted(res) == unindexed
True
Note that the breadth-first sorting is lost when an index is used [#updates]_.
.. [#updates] The scenario we are looking at in this document shows a case
in which special logic in the search index needs to address updates.
For example, if we move Howie from Diane
::
Alice
__/ \__
Betty Chuck
/ \ / \
Diane Edgar Frank Galyn
|
Howie
to Galyn
::
Alice
__/ \__
Betty Chuck
/ \ / \
Diane Edgar Frank Galyn
|
Howie
then the search index is correct both for the new location and the old.
>>> h.supervisor = g
>>> catalog.index(h)
>>> list(catalog.findRelationTokens({'supervisor': 'Diane'}))
[]
>>> list(catalog.findRelationTokens({'supervisor': 'Betty'}))
['Diane', 'Edgar']
>>> list(catalog.findRelationTokens({'supervisor': 'Chuck'}))
['Frank', 'Galyn', 'Howie']
>>> list(catalog.findRelationTokens({'supervisor': 'Galyn'}))
['Howie']
>>> h.supervisor = d
>>> catalog.index(h) # move him back
>>> list(catalog.findRelationTokens({'supervisor': 'Galyn'}))
[]
>>> list(catalog.findRelationTokens({'supervisor': 'Diane'}))
['Howie']
Transitive cycles (and updating and removing relations)
-------------------------------------------------------
The transitive searches and the provided search indexes can handle
cycles. Cycles are less likely in the current example than some others,
but we can stretch the case a bit: imagine a "king in disguise", in
which someone at the top works lower in the hierarchy. Perhaps Alice
works for Zane, who works for Betty, who works for Alice. Artificial,
but easy enough to draw::
______
/ \
/ Zane
/ |
/ Alice
/ __/ \__
/ Betty__ Chuck
\-/ / \ / \
Diane Edgar Frank Galyn
|
Howie
Easy to create too.
>>> z = Employee('Zane', b)
>>> a.supervisor = z
Now we have a cycle. Of course, we have not yet told the catalog about it.
``index`` can be used both to reindex Alice and index Zane.
>>> catalog.index(a)
>>> catalog.index(z)
Now, if we ask who works for Betty, we get the entire tree. (We'll ask
for tokens, just so that the result is smaller to look at.) [#same_set]_
.. [#same_set] The result of the query for Betty, Alice, and Zane are all the
same.
>>> res1 = catalog.findRelationTokens({'supervisor': 'Betty'})
>>> res2 = catalog.findRelationTokens({'supervisor': 'Alice'})
>>> res3 = catalog.findRelationTokens({'supervisor': 'Zane'})
>>> list(res1) == list(res2) == list(res3)
True
The cycle doesn't pollute the index outside of the cycle.
>>> res = catalog.findRelationTokens({'supervisor': 'Diane'})
>>> list(res)
['Howie']
>>> list(res) # it isn't lazy, it is precalculated
['Howie']
>>> sorted(catalog.findRelationTokens({'supervisor': 'Betty'}))
... # doctest: +NORMALIZE_WHITESPACE
['Alice', 'Betty', 'Chuck', 'Diane', 'Edgar', 'Frank', 'Galyn', 'Howie',
'Zane']
If we ask for the supervisors of Frank, it will include Betty.
>>> list(catalog.findValueTokens(
... 'supervisor', {zc.relation.RELATION: 'Frank'}))
['Chuck', 'Alice', 'Zane', 'Betty']
Paths returned by ``findRelationChains`` are marked with special interfaces,
and special metadata, to show the chain.
>>> res = list(catalog.findRelationChains({zc.relation.RELATION: 'Frank'}))
>>> len(res)
5
>>> import zc.relation.interfaces
>>> [zc.relation.interfaces.ICircularRelationPath.providedBy(r)
... for r in res]
[False, False, False, False, True]
Here's the last chain:
>>> res[-1] # doctest: +NORMALIZE_WHITESPACE
cycle(<Employee instance "Frank">, <Employee instance "Chuck">,
<Employee instance "Alice">, <Employee instance "Zane">,
<Employee instance "Betty">)
The chain's 'cycled' attribute has a list of queries that create a cycle.
If you run the query, or queries, you see where the cycle would
restart--where the path would have started to overlap. Sometimes the query
results will include multiple cycles, and some paths that are not cycles.
In this case, there's only a single cycled query, which results in a single
cycled relation.
>>> len(res[4].cycled)
1
>>> list(catalog.findRelations(res[4].cycled[0], maxDepth=1))
[<Employee instance "Alice">]
To remove this craziness [#reverse_lookup]_, we can unindex Zane, and change
and reindex Alice.
.. [#reverse_lookup] If you want to, look what happens when you go the
other way:
>>> res = list(catalog.findRelationChains({'supervisor': 'Zane'}))
>>> def sortEqualLenByName(one):
... return len(one), one
...
>>> res.sort(key=sortEqualLenByName) # normalizes for test stability
>>> from __future__ import print_function
>>> print(res) # doctest: +NORMALIZE_WHITESPACE
[(<Employee instance "Alice">,),
(<Employee instance "Alice">, <Employee instance "Betty">),
(<Employee instance "Alice">, <Employee instance "Chuck">),
(<Employee instance "Alice">, <Employee instance "Betty">,
<Employee instance "Diane">),
(<Employee instance "Alice">, <Employee instance "Betty">,
<Employee instance "Edgar">),
cycle(<Employee instance "Alice">, <Employee instance "Betty">,
<Employee instance "Zane">),
(<Employee instance "Alice">, <Employee instance "Chuck">,
<Employee instance "Frank">),
(<Employee instance "Alice">, <Employee instance "Chuck">,
<Employee instance "Galyn">),
(<Employee instance "Alice">, <Employee instance "Betty">,
<Employee instance "Diane">, <Employee instance "Howie">)]
>>> [zc.relation.interfaces.ICircularRelationPath.providedBy(r)
... for r in res]
[False, False, False, False, False, True, False, False, False]
>>> len(res[5].cycled)
1
>>> list(catalog.findRelations(res[5].cycled[0], maxDepth=1))
[<Employee instance "Alice">]
>>> a.supervisor = None
>>> catalog.index(a)
>>> list(catalog.findValueTokens(
... 'supervisor', {zc.relation.RELATION: 'Frank'}))
['Chuck', 'Alice']
>>> catalog.unindex(z)
>>> sorted(catalog.findRelationTokens({'supervisor': 'Betty'}))
['Diane', 'Edgar', 'Howie']
``canFind``
-----------
We're to the last search method: ``canFind``. We've gotten values and
relations, but what if you simply want to know if there is any
connection at all? For instance, is Alice a supervisor of Howie? Is
Chuck? To answer these questions, you can use the ``canFind`` method
combined with the ``targetQuery`` search argument.
The ``canFind`` method takes the same arguments as findRelations. However,
it simply returns a boolean about whether the search has any results. This
is a convenience that also allows some extra optimizations.
Does Betty supervise anyone?
>>> catalog.canFind({'supervisor': 'Betty'})
True
What about Howie?
>>> catalog.canFind({'supervisor': 'Howie'})
False
What about...Zane (no longer an employee)?
>>> catalog.canFind({'supervisor': 'Zane'})
False
If we want to know if Alice or Chuck supervise Howie, then we want to specify
characteristics of two points on a path. To ask a question about the other
end of a path, use ``targetQuery``.
Is Alice a supervisor of Howie?
>>> catalog.canFind({'supervisor': 'Alice'},
... targetQuery={zc.relation.RELATION: 'Howie'})
True
Is Chuck a supervisor of Howie?
>>> catalog.canFind({'supervisor': 'Chuck'},
... targetQuery={zc.relation.RELATION: 'Howie'})
False
Is Howie Alice's employee?
>>> catalog.canFind({zc.relation.RELATION: 'Howie'},
... targetQuery={'supervisor': 'Alice'})
True
Is Howie Chuck's employee?
>>> catalog.canFind({zc.relation.RELATION: 'Howie'},
... targetQuery={'supervisor': 'Chuck'})
False
(Note that, if your relations describe a hierarchy, searching up a hierarchy is
usually more efficient than searching down, so the second pair of questions is
generally preferable to the first in that case.)
Working with More Complex Relations
===================================
So far, our examples have used a simple relation, in which the indexed object
is one end of the relation, and the indexed value on the object is the other.
This example has let us look at all of the basic zc.relation catalog
functionality.
As mentioned in the introduction, though, the catalog supports, and was
designed for, more complex relations. This section will quickly examine a
few examples of other uses.
In this section, we will see several examples of ideas mentioned above but not
yet demonstrated.
- We can use interface attributes (values or callables) to define value
indexes.
- Using interface attributes will cause an attempt to adapt the relation if it
does not already provide the interface.
- We can use the ``multiple`` argument when defining a value index to indicate
that the indexed value is a collection.
- We can use the ``name`` argument when defining a value index to specify the
name to be used in queries, rather than relying on the name of the interface
attribute or callable.
- The ``family`` argument in instantiating the catalog lets you change the
default btree family for relations and value indexes from
``BTrees.family32.IF`` to ``BTrees.family64.IF``.
Extrinsic Two-Way Relations
---------------------------
A simple variation of our current story is this: what if the indexed relation
were between two other objects--that is, what if the relation were extrinsic to
both participants?
Let's imagine we have relations that show biological parentage. We'll want a
"Person" and a "Parentage" relation. We'll define an interface for
``IParentage`` so we can see how using an interface to define a value index
works.
>>> class Person(object):
... def __init__(self, name):
... self.name = name
... def __repr__(self):
... return '<Person %r>' % (self.name,)
...
>>> import zope.interface
>>> class IParentage(zope.interface.Interface):
... child = zope.interface.Attribute('the child')
... parents = zope.interface.Attribute('the parents')
...
>>> @zope.interface.implementer(IParentage)
... class Parentage(object):
...
... def __init__(self, child, parent1, parent2):
... self.child = child
... self.parents = (parent1, parent2)
...
Now we'll define the dumpers and loaders and then the catalog. Notice that
we are relying on a pattern: the dump must be called before the load.
>>> _people = {}
>>> _relations = {}
>>> def dumpPeople(obj, catalog, cache):
... if _people.setdefault(obj.name, obj) is not obj:
... raise ValueError('we are assuming names are unique')
... return obj.name
...
>>> def loadPeople(token, catalog, cache):
... return _people[token]
...
>>> def dumpRelations(obj, catalog, cache):
... if _relations.setdefault(id(obj), obj) is not obj:
... raise ValueError('huh?')
... return id(obj)
...
>>> def loadRelations(token, catalog, cache):
... return _relations[token]
...
>>> catalog = zc.relation.catalog.Catalog(dumpRelations, loadRelations, family=BTrees.family64)
>>> catalog.addValueIndex(IParentage['child'], dumpPeople, loadPeople,
... btree=BTrees.family32.OO)
>>> catalog.addValueIndex(IParentage['parents'], dumpPeople, loadPeople,
... btree=BTrees.family32.OO, multiple=True,
... name='parent')
>>> catalog.addDefaultQueryFactory(
... zc.relation.queryfactory.TransposingTransitive(
... 'child', 'parent'))
Now we have a catalog fully set up. Let's add some relations.
>>> a = Person('Alice')
>>> b = Person('Betty')
>>> c = Person('Charles')
>>> d = Person('Donald')
>>> e = Person('Eugenia')
>>> f = Person('Fred')
>>> g = Person('Gertrude')
>>> h = Person('Harry')
>>> i = Person('Iphigenia')
>>> j = Person('Jacob')
>>> k = Person('Karyn')
>>> l = Person('Lee')
>>> r1 = Parentage(child=j, parent1=k, parent2=l)
>>> r2 = Parentage(child=g, parent1=i, parent2=j)
>>> r3 = Parentage(child=f, parent1=g, parent2=h)
>>> r4 = Parentage(child=e, parent1=g, parent2=h)
>>> r5 = Parentage(child=b, parent1=e, parent2=d)
>>> r6 = Parentage(child=a, parent1=e, parent2=c)
Here's that in one of our hierarchy diagrams.
::
Karyn Lee
\ /
Jacob Iphigenia
\ /
Gertrude Harry
\ /
/-------\
Fred Eugenia
Donald / \ Charles
\ / \ /
Betty Alice
Now we can index the relations, and ask some questions.
>>> for r in (r1, r2, r3, r4, r5, r6):
... catalog.index(r)
>>> query = catalog.tokenizeQuery
>>> sorted(catalog.findValueTokens(
... 'parent', query(child=a), maxDepth=1))
['Charles', 'Eugenia']
>>> sorted(catalog.findValueTokens('parent', query(child=g)))
['Iphigenia', 'Jacob', 'Karyn', 'Lee']
>>> sorted(catalog.findValueTokens(
... 'child', query(parent=h), maxDepth=1))
['Eugenia', 'Fred']
>>> sorted(catalog.findValueTokens('child', query(parent=h)))
['Alice', 'Betty', 'Eugenia', 'Fred']
>>> catalog.canFind(query(parent=h), targetQuery=query(child=d))
False
>>> catalog.canFind(query(parent=l), targetQuery=query(child=b))
True
Multi-Way Relations
-------------------
The previous example quickly showed how to set the catalog up for a completely
extrinsic two-way relation. The same pattern can be extended for N-way
relations. For example, consider a four way relation in the form of
SUBJECTS PREDICATE OBJECTS [in CONTEXT]. For instance, we might
want to say "(joe,) SELLS (doughnuts, coffee) in corner_store", where "(joe,)"
is the collection of subjects, "SELLS" is the predicate, "(doughnuts, coffee)"
is the collection of objects, and "corner_store" is the optional context.
For this last example, we'll integrate two components we haven't seen examples
of here before: the ZODB and adaptation.
Our example ZODB approach uses OIDs as the tokens. this might be OK in some
cases, if you will never support multiple databases and you don't need an
abstraction layer so that a different object can have the same identifier.
>>> import persistent
>>> import struct
>>> class Demo(persistent.Persistent):
... def __init__(self, name):
... self.name = name
... def __repr__(self):
... return '<Demo instance %r>' % (self.name,)
...
>>> class IRelation(zope.interface.Interface):
... subjects = zope.interface.Attribute('subjects')
... predicate = zope.interface.Attribute('predicate')
... objects = zope.interface.Attribute('objects')
...
>>> class IContextual(zope.interface.Interface):
... def getContext():
... 'return context'
... def setContext(value):
... 'set context'
...
>>> @zope.interface.implementer(IContextual)
... class Contextual(object):
...
... _context = None
... def getContext(self):
... return self._context
... def setContext(self, value):
... self._context = value
...
>>> @zope.interface.implementer(IRelation)
... class Relation(persistent.Persistent):
...
... def __init__(self, subjects, predicate, objects):
... self.subjects = subjects
... self.predicate = predicate
... self.objects = objects
... self._contextual = Contextual()
...
... def __conform__(self, iface):
... if iface is IContextual:
... return self._contextual
...
(When using zope.component, the ``__conform__`` would normally be unnecessary;
however, this package does not depend on zope.component.)
>>> def dumpPersistent(obj, catalog, cache):
... if obj._p_jar is None:
... catalog._p_jar.add(obj) # assumes something else places it
... return struct.unpack('<q', obj._p_oid)[0]
...
>>> def loadPersistent(token, catalog, cache):
... return catalog._p_jar.get(struct.pack('<q', token))
...
>>> from ZODB.tests.util import DB
>>> db = DB()
>>> conn = db.open()
>>> root = conn.root()
>>> catalog = root['catalog'] = zc.relation.catalog.Catalog(
... dumpPersistent, loadPersistent, family=BTrees.family64)
>>> catalog.addValueIndex(IRelation['subjects'],
... dumpPersistent, loadPersistent, multiple=True, name='subject')
>>> catalog.addValueIndex(IRelation['objects'],
... dumpPersistent, loadPersistent, multiple=True, name='object')
>>> catalog.addValueIndex(IRelation['predicate'], btree=BTrees.family32.OO)
>>> catalog.addValueIndex(IContextual['getContext'],
... dumpPersistent, loadPersistent, name='context')
>>> import transaction
>>> transaction.commit()
The ``dumpPersistent`` and ``loadPersistent`` is a bit of a toy, as warned
above. Also, while our predicate will be stored as a string, some programmers
may prefer to have a dump in such a case verify that the string has been
explicitly registered in some way, to prevent typos. Obviously, we are not
bothering with this for our example.
We make some objects, and then we make some relations with those objects and
index them.
>>> joe = root['joe'] = Demo('joe')
>>> sara = root['sara'] = Demo('sara')
>>> jack = root['jack'] = Demo('jack')
>>> ann = root['ann'] = Demo('ann')
>>> doughnuts = root['doughnuts'] = Demo('doughnuts')
>>> coffee = root['coffee'] = Demo('coffee')
>>> muffins = root['muffins'] = Demo('muffins')
>>> cookies = root['cookies'] = Demo('cookies')
>>> newspaper = root['newspaper'] = Demo('newspaper')
>>> corner_store = root['corner_store'] = Demo('corner_store')
>>> bistro = root['bistro'] = Demo('bistro')
>>> bakery = root['bakery'] = Demo('bakery')
>>> SELLS = 'SELLS'
>>> BUYS = 'BUYS'
>>> OBSERVES = 'OBSERVES'
>>> rel1 = root['rel1'] = Relation((joe,), SELLS, (doughnuts, coffee))
>>> IContextual(rel1).setContext(corner_store)
>>> rel2 = root['rel2'] = Relation((sara, jack), SELLS,
... (muffins, doughnuts, cookies))
>>> IContextual(rel2).setContext(bakery)
>>> rel3 = root['rel3'] = Relation((ann,), BUYS, (doughnuts,))
>>> rel4 = root['rel4'] = Relation((sara,), BUYS, (bistro,))
>>> for r in (rel1, rel2, rel3, rel4):
... catalog.index(r)
...
Now we can ask a simple question. Where do they sell doughnuts?
>>> query = catalog.tokenizeQuery
>>> sorted(catalog.findValues(
... 'context',
... (query(predicate=SELLS, object=doughnuts))),
... key=lambda ob: ob.name)
[<Demo instance 'bakery'>, <Demo instance 'corner_store'>]
Hopefully these examples give you further ideas on how you can use this tool.
Additional Functionality
========================
This section introduces peripheral functionality. We will learn the following.
- Listeners can be registered in the catalog. They are alerted when a relation
is added, modified, or removed; and when the catalog is cleared and copied
(see below).
- The ``clear`` method clears the relations in the catalog.
- The ``copy`` method makes a copy of the current catalog by copying internal
data structures, rather than reindexing the relations, which can be a
significant optimization opportunity. This copies value indexes and search
indexes; and gives listeners an opportunity to specify what, if anything,
should be included in the new copy.
- The ``ignoreSearchIndex`` argument to the five pertinent search methods
causes the search to ignore search indexes, even if there is an appropriate
one.
- ``findRelationTokens()`` (without arguments) returns the BTree set of all
relation tokens in the catalog.
- ``findValueTokens(INDEX_NAME)`` (where "INDEX_NAME" should be replaced with
an index name) returns the BTree set of all value tokens in the catalog for
the given index name.
Listeners
---------
A variety of potential clients may want to be alerted when the catalog changes.
zc.relation does not depend on zope.event, so listeners may be registered for
various changes. Let's make a quick demo listener. The ``additions`` and
``removals`` arguments are dictionaries of {value name: iterable of added or
removed value tokens}.
>>> def pchange(d):
... pprint.pprint(dict(
... (k, v is not None and sorted(set(v)) or v) for k, v in d.items()))
>>> @zope.interface.implementer(zc.relation.interfaces.IListener)
... class DemoListener(persistent.Persistent):
...
... def relationAdded(self, token, catalog, additions):
... print('a relation (token %r) was added to %r '
... 'with these values:' % (token, catalog))
... pchange(additions)
... def relationModified(self, token, catalog, additions, removals):
... print('a relation (token %r) in %r was modified '
... 'with these additions:' % (token, catalog))
... pchange(additions)
... print('and these removals:')
... pchange(removals)
... def relationRemoved(self, token, catalog, removals):
... print('a relation (token %r) was removed from %r '
... 'with these values:' % (token, catalog))
... pchange(removals)
... def sourceCleared(self, catalog):
... print('catalog %r had all relations unindexed' % (catalog,))
... def sourceAdded(self, catalog):
... print('now listening to catalog %r' % (catalog,))
... def sourceRemoved(self, catalog):
... print('no longer listening to catalog %r' % (catalog,))
... def sourceCopied(self, original, copy):
... print('catalog %r made a copy %r' % (catalog, copy))
... copy.addListener(self)
...
Listeners can be installed multiple times.
Listeners can be added as persistent weak references, so that, if they are
deleted elsewhere, a ZODB pack will not consider the reference in the catalog
to be something preventing garbage collection.
We'll install one of these demo listeners into our new catalog as a
normal reference, the default behavior. Then we'll show some example messages
sent to the demo listener.
>>> listener = DemoListener()
>>> catalog.addListener(listener) # doctest: +ELLIPSIS
now listening to catalog <zc.relation.catalog.Catalog object at ...>
>>> rel5 = root['rel5'] = Relation((ann,), OBSERVES, (newspaper,))
>>> catalog.index(rel5) # doctest: +ELLIPSIS
a relation (token ...) was added to <...Catalog...> with these values:
{'context': None,
'object': [...],
'predicate': ['OBSERVES'],
'subject': [...]}
>>> rel5.subjects = (jack,)
>>> IContextual(rel5).setContext(bistro)
>>> catalog.index(rel5) # doctest: +ELLIPSIS
a relation (token ...) in ...Catalog... was modified with these additions:
{'context': [...], 'subject': [...]}
and these removals:
{'subject': [...]}
>>> catalog.unindex(rel5) # doctest: +ELLIPSIS
a relation (token ...) was removed from <...Catalog...> with these values:
{'context': [...],
'object': [...],
'predicate': ['OBSERVES'],
'subject': [...]}
>>> catalog.removeListener(listener) # doctest: +ELLIPSIS
no longer listening to catalog <...Catalog...>
>>> catalog.index(rel5) # doctest: +ELLIPSIS
The only two methods not shown by those examples are ``sourceCleared`` and
``sourceCopied``. We'll get to those very soon below.
The ``clear`` Method
--------------------
The ``clear`` method simply indexes all relations from a catalog. Installed
listeners have ``sourceCleared`` called.
>>> len(catalog)
5
>>> catalog.addListener(listener) # doctest: +ELLIPSIS
now listening to catalog <zc.relation.catalog.Catalog object at ...>
>>> catalog.clear() # doctest: +ELLIPSIS
catalog <...Catalog...> had all relations unindexed
>>> len(catalog)
0
>>> sorted(catalog.findValues(
... 'context',
... (query(predicate=SELLS, object=doughnuts))),
... key=lambda ob: ob.name)
[]
The ``copy`` Method
-------------------
Sometimes you may want to copy a relation catalog. One way of doing this is
to create a new catalog, set it up like the current one, and then reindex
all the same relations. This is unnecessarily slow for programmer and
computer. The ``copy`` method makes a new catalog with the same corpus of
indexed relations by copying internal data structures.
Search indexes are requested to make new copies of themselves for the new
catalog; and listeners are given an opportunity to react as desired to the new
copy, including installing themselves, and/or another object of their choosing
as a listener.
Let's make a copy of a populated index with a search index and a listener.
Notice in our listener that ``sourceCopied`` adds itself as a listener to the
new copy. This is done at the very end of the ``copy`` process.
>>> for r in (rel1, rel2, rel3, rel4, rel5):
... catalog.index(r)
... # doctest: +ELLIPSIS
a relation ... was added...
a relation ... was added...
a relation ... was added...
a relation ... was added...
a relation ... was added...
>>> BEGAT = 'BEGAT'
>>> rel6 = root['rel6'] = Relation((jack, ann), BEGAT, (sara,))
>>> henry = root['henry'] = Demo('henry')
>>> rel7 = root['rel7'] = Relation((sara, joe), BEGAT, (henry,))
>>> catalog.index(rel6) # doctest: +ELLIPSIS
a relation (token ...) was added to <...Catalog...> with these values:
{'context': None,
'object': [...],
'predicate': ['BEGAT'],
'subject': [..., ...]}
>>> catalog.index(rel7) # doctest: +ELLIPSIS
a relation (token ...) was added to <...Catalog...> with these values:
{'context': None,
'object': [...],
'predicate': ['BEGAT'],
'subject': [..., ...]}
>>> catalog.addDefaultQueryFactory(
... zc.relation.queryfactory.TransposingTransitive(
... 'subject', 'object', {'predicate': BEGAT}))
...
>>> list(catalog.findValues(
... 'object', query(subject=jack, predicate=BEGAT)))
[<Demo instance 'sara'>, <Demo instance 'henry'>]
>>> catalog.addSearchIndex(
... zc.relation.searchindex.TransposingTransitiveMembership(
... 'subject', 'object', static={'predicate': BEGAT}))
>>> sorted(
... catalog.findValues(
... 'object', query(subject=jack, predicate=BEGAT)),
... key=lambda o: o.name)
[<Demo instance 'henry'>, <Demo instance 'sara'>]
>>> newcat = root['newcat'] = catalog.copy() # doctest: +ELLIPSIS
catalog <...Catalog...> made a copy <...Catalog...>
now listening to catalog <...Catalog...>
>>> transaction.commit()
Now the copy has its own copies of internal data structures and of the
searchindex. For example, let's modify the relations and add a new one to the
copy.
>>> mary = root['mary'] = Demo('mary')
>>> buffy = root['buffy'] = Demo('buffy')
>>> zack = root['zack'] = Demo('zack')
>>> rel7.objects += (mary,)
>>> rel8 = root['rel8'] = Relation((henry, buffy), BEGAT, (zack,))
>>> newcat.index(rel7) # doctest: +ELLIPSIS
a relation (token ...) in ...Catalog... was modified with these additions:
{'object': [...]}
and these removals:
{}
>>> newcat.index(rel8) # doctest: +ELLIPSIS
a relation (token ...) was added to ...Catalog... with these values:
{'context': None,
'object': [...],
'predicate': ['BEGAT'],
'subject': [..., ...]}
>>> len(newcat)
8
>>> sorted(
... newcat.findValues(
... 'object', query(subject=jack, predicate=BEGAT)),
... key=lambda o: o.name) # doctest: +NORMALIZE_WHITESPACE
[<Demo instance 'henry'>, <Demo instance 'mary'>, <Demo instance 'sara'>,
<Demo instance 'zack'>]
>>> sorted(
... newcat.findValues(
... 'object', query(subject=sara)),
... key=lambda o: o.name) # doctest: +NORMALIZE_WHITESPACE
[<Demo instance 'bistro'>, <Demo instance 'cookies'>,
<Demo instance 'doughnuts'>, <Demo instance 'henry'>,
<Demo instance 'mary'>, <Demo instance 'muffins'>]
The original catalog is not modified.
>>> len(catalog)
7
>>> sorted(
... catalog.findValues(
... 'object', query(subject=jack, predicate=BEGAT)),
... key=lambda o: o.name)
[<Demo instance 'henry'>, <Demo instance 'sara'>]
>>> sorted(
... catalog.findValues(
... 'object', query(subject=sara)),
... key=lambda o: o.name) # doctest: +NORMALIZE_WHITESPACE
[<Demo instance 'bistro'>, <Demo instance 'cookies'>,
<Demo instance 'doughnuts'>, <Demo instance 'henry'>,
<Demo instance 'muffins'>]
The ``ignoreSearchIndex`` argument
----------------------------------
The five methods that can use search indexes, ``findValues``,
``findValueTokens``, ``findRelations``, ``findRelationTokens``, and
``canFind``, can be explicitly requested to ignore any pertinent search index
using the ``ignoreSearchIndex`` argument.
We can see this easily with the token-related methods: the search index result
will be a BTree set, while without the search index the result will be a
generator.
>>> res1 = newcat.findValueTokens(
... 'object', query(subject=jack, predicate=BEGAT))
>>> res1 # doctest: +ELLIPSIS
LFSet([..., ..., ..., ...])
>>> res2 = newcat.findValueTokens(
... 'object', query(subject=jack, predicate=BEGAT),
... ignoreSearchIndex=True)
>>> res2 # doctest: +ELLIPSIS
<generator object ... at 0x...>
>>> sorted(res2) == list(res1)
True
>>> res1 = newcat.findRelationTokens(
... query(subject=jack, predicate=BEGAT))
>>> res1 # doctest: +ELLIPSIS
LFSet([..., ..., ...])
>>> res2 = newcat.findRelationTokens(
... query(subject=jack, predicate=BEGAT), ignoreSearchIndex=True)
>>> res2 # doctest: +ELLIPSIS
<generator object ... at 0x...>
>>> sorted(res2) == list(res1)
True
We can see that the other methods take the argument, but the results look the
same as usual.
>>> res = newcat.findValues(
... 'object', query(subject=jack, predicate=BEGAT),
... ignoreSearchIndex=True)
>>> res # doctest: +ELLIPSIS
<generator object ... at 0x...>
>>> list(res) == list(newcat.resolveValueTokens(newcat.findValueTokens(
... 'object', query(subject=jack, predicate=BEGAT),
... ignoreSearchIndex=True), 'object'))
True
>>> res = newcat.findRelations(
... query(subject=jack, predicate=BEGAT),
... ignoreSearchIndex=True)
>>> res # doctest: +ELLIPSIS
<generator object ... at 0x...>
>>> list(res) == list(newcat.resolveRelationTokens(
... newcat.findRelationTokens(
... query(subject=jack, predicate=BEGAT),
... ignoreSearchIndex=True)))
True
>>> newcat.canFind(
... query(subject=jack, predicate=BEGAT), ignoreSearchIndex=True)
True
``findRelationTokens()``
------------------------
If you call ``findRelationTokens`` without any arguments, you will get the
BTree set of all relation tokens in the catalog. This can be handy for tests
and for advanced uses of the catalog.
>>> newcat.findRelationTokens() # doctest: +ELLIPSIS
<BTrees.LFBTree.LFTreeSet object at ...>
>>> len(newcat.findRelationTokens())
8
>>> set(newcat.resolveRelationTokens(newcat.findRelationTokens())) == set(
... (rel1, rel2, rel3, rel4, rel5, rel6, rel7, rel8))
True
``findValueTokens(INDEX_NAME)``
-------------------------------
If you call ``findValueTokens`` with only an index name, you will get the BTree
structure of all tokens for that value in the index. This can be handy for
tests and for advanced uses of the catalog.
>>> newcat.findValueTokens('predicate') # doctest: +ELLIPSIS
<BTrees.OOBTree.OOBTree object at ...>
>>> list(newcat.findValueTokens('predicate'))
['BEGAT', 'BUYS', 'OBSERVES', 'SELLS']
Conclusion
==========
Review
------
That brings us to the end of our introductory examples. Let's review, and
then look at where you can go from here.
* Relations are objects with indexed values.
* The relation catalog indexes relations. The relations can be one-way,
two-way, three-way, or N-way, as long as you tell the catalog to index the
different values.
* Creating a catalog:
- Relations and their values are stored in the catalog as tokens: unique
identifiers that you can resolve back to the original value. Integers are
the most efficient tokens, but others can work fine too.
- Token type determines the BTree module needed.
- If the tokens are 32-bit ints, choose ``BTrees.family32.II``,
``BTrees.family32.IF`` or ``BTrees.family32.IO``.
- If the tokens are 64 bit ints, choose ``BTrees.family64.II``,
``BTrees.family64.IF`` or ``BTrees.family64.IO``.
- If they are anything else, choose ``BTrees.family32.OI``,
``BTrees.family64.OI``, or ``BTrees.family32.OO`` (or
BTrees.family64.OO--they are the same).
Within these rules, the choice is somewhat arbitrary unless you plan to
merge these results with that of another source that is using a
particular BTree module. BTree set operations only work within the same
module, so you must match module to module.
- The ``family`` argument in instantiating the catalog lets you change the
default btree family for relations and value indexes from
``BTrees.family32.IF`` to ``BTrees.family64.IF``.
- You must define your own functions for tokenizing and resolving tokens.
These functions are registered with the catalog for the relations and for
each of their value indexes.
- You add value indexes to relation catalogs to be able to search. Values
can be identified to the catalog with callables or interface elements.
- Using interface attributes will cause an attempt to adapt the
relation if it does not already provide the interface.
- We can use the ``multiple`` argument when defining a value index to
indicate that the indexed value is a collection. This defaults to
False.
- We can use the ``name`` argument when defining a value index to
specify the name to be used in queries, rather than relying on the
name of the interface attribute or callable.
- You can set up search indexes to speed up specific searches, usually
transitive.
- Listeners can be registered in the catalog. They are alerted when a
relation is added, modified, or removed; and when the catalog is cleared
and copied.
* Catalog Management:
- Relations are indexed with ``index(relation)``, and removed from the
catalog with ``unindex(relation)``. ``index_doc(relation_token,
relation)`` and ``unindex_doc(relation_token)`` also work.
- The ``clear`` method clears the relations in the catalog.
- The ``copy`` method makes a copy of the current catalog by copying
internal data structures, rather than reindexing the relations, which can
be a significant optimization opportunity. This copies value indexes and
search indexes; and gives listeners an opportunity to specify what, if
anything, should be included in the new copy.
* Searching a catalog:
- Queries to the relation catalog are formed with dicts.
- Query keys are the names of the indexes you want to search, or, for the
special case of precise relations, the ``zc.relation.RELATION`` constant.
- Query values are the tokens of the results you want to match; or
``None``, indicating relations that have ``None`` as a value (or an empty
collection, if it is a multiple). Search values can use
``zc.relation.catalog.any(args)`` or ``zc.relation.catalog.Any(args)`` to
specify multiple (non-``None``) results to match for a given key.
- The index has a variety of methods to help you work with tokens.
``tokenizeQuery`` is typically the most used, though others are
available.
- To find relations that match a query, use ``findRelations`` or
``findRelationTokens``. Calling ``findRelationTokens`` without any
arguments returns the BTree set of all relation tokens in the catalog.
- To find values that match a query, use ``findValues`` or
``findValueTokens``. Calling ``findValueTokens`` with only the name
of a value index returns the BTree set of all tokens in the catalog for
that value index.
- You search transitively by using a query factory. The
``zc.relation.queryfactory.TransposingTransitive`` is a good common case
factory that lets you walk up and down a hierarchy. A query factory can
be passed in as an argument to search methods as a ``queryFactory``, or
installed as a default behavior using ``addDefaultQueryFactory``.
- To find how a query is related, use ``findRelationChains`` or
``findRelationTokenChains``.
- To find out if a query is related, use ``canFind``.
- Circular transitive relations are handled to prevent infinite loops. They
are identified in ``findRelationChains`` and ``findRelationTokenChains``
with a ``zc.relation.interfaces.ICircularRelationPath`` marker interface.
- search methods share the following arguments:
* ``maxDepth``, limiting the transitive depth for searches;
* ``filter``, allowing code to filter transitive paths;
* ``targetQuery``, allowing a query to filter transitive paths on the
basis of the endpoint;
* ``targetFilter``, allowing code to filter transitive paths on the basis
of the endpoint; and
* ``queryFactory``, mentioned above.
In addition, the ``ignoreSearchIndex`` argument to ``findRelations``,
``findRelationTokens``, ``findValues``, ``findValueTokens``, and
``canFind`` causes the search to ignore search indexes, even if there is
an appropriate one.
Next Steps
----------
If you want to read more, next steps depend on how you like to learn. Here
are some of the other documents in the zc.relation package.
:optimization.rst:
Best practices for optimizing your use of the relation catalog.
:searchindex.rst:
Queries factories and search indexes: from basics to nitty gritty details.
:tokens.rst:
This document explores the details of tokens. All God's chillun
love tokens, at least if God's chillun are writing non-toy apps
using zc.relation. It includes discussion of the token helpers that
the catalog provides, how to use zope.app.intid-like registries with
zc.relation, how to use tokens to "join" query results reasonably
efficiently, and how to index joins. It also is unnecessarily
mind-blowing because of the examples used.
:interfaces.py:
The contract, for nuts and bolts.
Finally, the truly die-hard might also be interested in the timeit
directory, which holds scripts used to test assumptions and learn.
.. ......... ..
.. FOOTNOTES ..
.. ......... ..
.. [#I_care] OK, you care about how that query factory worked, so
we will look into it a bit. Let's talk through two steps of the
transitive search in the second question. The catalog initially
performs the initial intransitive search requested: find relations
for which Betty is the supervisor. That's Diane and Edgar.
Now, for each of the results, the catalog asks the query factory for
next steps. Let's take Diane. The catalog says to the factory,
"Given this query for relations where Betty is supervisor, I got
this result of Diane. Do you have any other queries I should try to
look further?". The factory also gets the catalog instance so it
can use it to answer the question if it needs to.
OK, the next part is where your brain hurts. Hang on.
In our case, the factory sees that the query was for supervisor. Its
other key, the one it transposes with, is ``zc.relation.RELATION``. *The
factory gets the transposing key's result for the current token.* So, for
us, a key of ``zc.relation.RELATION`` is actually a no-op: the result *is*
the current token, Diane. Then, the factory has its answer: replace the old
value of supervisor in the query, Betty, with the result, Diane. The next
transitive query should be {'supervisor', 'Diane'}. Ta-da.
| zc.relation | /zc.relation-2.0.tar.gz/zc.relation-2.0/src/zc/relation/README.rst | README.rst |
Optimizing Relation Catalog Use
===============================
There are several best practices and optimization opportunities in regards to
the catalog.
- Use integer-keyed BTree sets when possible. They can use the BTrees'
`multiunion` for a speed boost. Integers' __cmp__ is reliable, and in C.
- Never use persistent objects as keys. They will cause a database load every
time you need to look at them, they take up memory and object caches, and
they (as of this writing) disable conflict resolution. Intids (or similar)
are your best bet for representing objects, and some other immutable such as
strings are the next-best bet, and zope.app.keyreferences (or similar) are
after that.
- Use multiple-token values in your queries when possible, especially in your
transitive query factories.
- Use the cache when you are loading and dumping tokens, and in your
transitive query factories.
- When possible, don't load or dump tokens (the values themselves may be used
as tokens). This is especially important when you have multiple tokens:
store them in a BTree structure in the same module as the zc.relation module
for the value.
For some operations, particularly with hundreds or thousands of members in a
single relation value, some of these optimizations can speed up some
common-case reindexing work by around 100 times.
The easiest (and perhaps least useful) optimization is that all dump
calls and all load calls generated by a single operation share a cache
dictionary per call type (dump/load), per indexed relation value.
Therefore, for instance, we could stash an intids utility, so that we
only had to do a utility lookup once, and thereafter it was only a
single dictionary lookup. This is what the default `generateToken` and
`resolveToken` functions in zc.relationship's index.py do: look at them
for an example.
A further optimization is to not load or dump tokens at all, but use values
that may be tokens. This will be particularly useful if the tokens have
__cmp__ (or equivalent) in C, such as built-in types like ints. To specify
this behavior, you create an index with the 'load' and 'dump' values for the
indexed attribute descriptions explicitly set to None.
>>> import zope.interface
>>> class IRelation(zope.interface.Interface):
... subjects = zope.interface.Attribute(
... 'The sources of the relation; the subject of the sentence')
... relationtype = zope.interface.Attribute(
... '''unicode: the single relation type of this relation;
... usually contains the verb of the sentence.''')
... objects = zope.interface.Attribute(
... '''the targets of the relation; usually a direct or
... indirect object in the sentence''')
...
>>> import BTrees
>>> relations = BTrees.family32.IO.BTree()
>>> relations[99] = None # just to give us a start
>>> @zope.interface.implementer(IRelation)
... class Relation(object):
...
... def __init__(self, subjects, relationtype, objects):
... self.subjects = subjects
... assert relationtype in relTypes
... self.relationtype = relationtype
... self.objects = objects
... self.id = relations.maxKey() + 1
... relations[self.id] = self
... def __repr__(self):
... return '<%r %s %r>' % (
... self.subjects, self.relationtype, self.objects)
>>> def token(rel, self):
... return rel.token
...
>>> def children(rel, self):
... return rel.children
...
>>> def dumpRelation(obj, index, cache):
... return obj.id
...
>>> def loadRelation(token, index, cache):
... return relations[token]
...
>>> relTypes = ['has the role of']
>>> def relTypeDump(obj, index, cache):
... assert obj in relTypes, 'unknown relationtype'
... return obj
...
>>> def relTypeLoad(token, index, cache):
... assert token in relTypes, 'unknown relationtype'
... return token
...
>>> import zc.relation.catalog
>>> catalog = zc.relation.catalog.Catalog(
... dumpRelation, loadRelation)
>>> catalog.addValueIndex(IRelation['subjects'], multiple=True)
>>> catalog.addValueIndex(
... IRelation['relationtype'], relTypeDump, relTypeLoad,
... BTrees.family32.OI, name='reltype')
>>> catalog.addValueIndex(IRelation['objects'], multiple=True)
>>> import zc.relation.queryfactory
>>> factory = zc.relation.queryfactory.TransposingTransitive(
... 'subjects', 'objects')
>>> catalog.addDefaultQueryFactory(factory)
>>> rel = Relation((1,), 'has the role of', (2,))
>>> catalog.index(rel)
>>> list(catalog.findValueTokens('objects', {'subjects': 1}))
[2]
If you have single relations that relate hundreds or thousands of
objects, it can be a huge win if the value is a 'multiple' of the same
type as the stored BTree for the given attribute. The default BTree
family for attributes is IFBTree; IOBTree is also a good choice, and may
be preferrable for some applications.
>>> catalog.unindex(rel)
>>> rel = Relation(
... BTrees.family32.IF.TreeSet((1,)), 'has the role of',
... BTrees.family32.IF.TreeSet())
>>> catalog.index(rel)
>>> list(catalog.findValueTokens('objects', {'subjects': 1}))
[]
>>> list(catalog.findValueTokens('subjects', {'objects': None}))
[1]
Reindexing is where some of the big improvements can happen. The following
gyrations exercise the optimization code.
>>> rel.objects.insert(2)
1
>>> catalog.index(rel)
>>> list(catalog.findValueTokens('objects', {'subjects': 1}))
[2]
>>> rel.subjects = BTrees.family32.IF.TreeSet((3,4,5))
>>> catalog.index(rel)
>>> list(catalog.findValueTokens('objects', {'subjects': 3}))
[2]
>>> rel.subjects.insert(6)
1
>>> catalog.index(rel)
>>> list(catalog.findValueTokens('objects', {'subjects': 6}))
[2]
>>> rel.subjects.update(range(100, 200))
100
>>> catalog.index(rel)
>>> list(catalog.findValueTokens('objects', {'subjects': 100}))
[2]
>>> rel.subjects = BTrees.family32.IF.TreeSet((3,4,5,6))
>>> catalog.index(rel)
>>> list(catalog.findValueTokens('objects', {'subjects': 3}))
[2]
>>> rel.subjects = BTrees.family32.IF.TreeSet(())
>>> catalog.index(rel)
>>> list(catalog.findValueTokens('objects', {'subjects': 3}))
[]
>>> rel.subjects = BTrees.family32.IF.TreeSet((3,4,5))
>>> catalog.index(rel)
>>> list(catalog.findValueTokens('objects', {'subjects': 3}))
[2]
tokenizeValues and resolveValueTokens work correctly without loaders and
dumpers--that is, they do nothing.
>>> catalog.tokenizeValues((3,4,5), 'subjects')
(3, 4, 5)
>>> catalog.resolveValueTokens((3,4,5), 'subjects')
(3, 4, 5)
| zc.relation | /zc.relation-2.0.tar.gz/zc.relation-2.0/src/zc/relation/optimization.rst | optimization.rst |
"""interfaces
"""
import zope.interface
class ICircularRelationPath(zope.interface.Interface):
"""A tuple that has a circular relation in the very final element of
the path."""
cycled = zope.interface.Attribute(
"""a list of the searches needed to continue the cycle""")
class IQueryFactory(zope.interface.Interface):
def __call__(query, catalog, cache):
"""if query matches, return `getQueries` callable; else return None.
A getQueries callable receives a relchain. The last relation token in
relchain is the most recent, and if you are using search indexes may be
the only reliable one. Return an iterable of queries to search
further from given relchain.
IMPORTANT: the getQueries is first called with an empty tuple. This
shou normally yield the original query, but can yield one or more
arbitrary queries as desired.
"""
class IFilter(zope.interface.Interface):
def __call__(relchain, query, index, cache):
"""return boolean: whether to accept the given relchain.
last relation token in relchain is the most recent.
query is original query that started the search.
Used for the filter and targetFilter arguments of the IIndex query
methods. Cache is a dictionary that will be used throughout a given
search."""
class IMessageListener(zope.interface.Interface):
def relationAdded(token, catalog, additions):
"""message: relation token has been added to catalog.
additions is a dictionary of {value name : iterable of added value
tokens}.
"""
def relationModified(token, catalog, additions, removals):
"""message: relation token has been updated in catalog.
additions is a dictionary of {value name : iterable of added value
tokens}.
removals is a dictionary of {value name : iterable of removed value
tokens}.
"""
def relationRemoved(token, catalog, removals):
"""message: relation token has been removed from catalog.
removals is a dictionary of {value name : iterable of removed value
tokens}.
"""
def sourceCleared(catalog):
"""message: the catalog has been cleared."""
class IListener(IMessageListener):
def sourceAdded(catalog):
"""message: you've been added as a listener to the given catalog."""
def sourceRemoved(catalog):
"""message: you've been removed as a listener from the given catalog.
"""
def sourceCopied(original, copy):
"""message: the given original is making a copy.
Can install listeners in the copy, if desired.
"""
class ISearchIndex(IMessageListener):
def copy(catalog):
"""return a copy of this index, bound to provided catalog."""
def setCatalog(catalog):
"""set the search index to be using the given catalog, return matches.
Should immediately being index up-to-date if catalog has content.
if index already has a catalog, raise an error.
If provided catalog is None, clear catalog and indexes.
Returned matches should be iterable of tuples of (search name or None,
query names, static values, maxDepth, filter, queryFactory). Only
searches matching one of these tuples will be sent to the search
index.
"""
def getResults(name, query, maxDepth, filter, queryFactory):
"""return results for search if available, and None if not
Returning a non-None value means that this search index claims the
search. No other search indexes will be consulted, and the given
results are believed to be accurate.
"""
class ICatalog(zope.interface.Interface):
family = zope.interface.Attribute(
"""BTrees.family32 or BTrees.family64. Influences defaults.""")
def index(relation):
"""obtains the token for the relation and indexes"""
def index_doc(token, relation):
"""indexes relation as given token"""
def unindex(relation):
"""obtains the token for the relation and unindexes"""
def unindex_doc(relation):
"""unindexes relation for given token"""
def __contains__(relation):
"""returns whether the relation is in the index"""
def __len__():
"""returns number of relations in catalog."""
def __iter__():
"""return iterator of relations in catalog"""
def clear():
"""clean catalog to index no relations"""
def copy(klass=None):
"""return a copy of index, using klass (__new__) if given."""
def addValueIndex(element, dump=None, load=None, btree=None,
multiple=False, name=None):
"""add a value index for given element.
element may be interface element or callable. Here are the other
arguments.
- `dump`, the tokenizer is a callable taking (obj, index, cache)
and returning a token. If it is None, that means that the value
is already a sufficient token.
- `load` is the token resolver, a callable taking (token, index, cache)
to return the object which the token represents. If it is None,
that means that the token is the value. If you specify None
for `dump` or `load`, you must also specify None for the other.
- `btree` is the btree module to use to store and process the tokens,
such as BTrees.OOBTree. Defaults to catalog.family.IFBTree.
- `multiple` is a boolean indicating whether the value is a
collection.
- `name` is the name of the index in the catalog. If this is not
supplied, the element's `__name__` is used.
"""
def iterValueIndexInfo():
"""return iterable of dicts, each with data for added value indexes.
See arguments to addValueIndex for keys in dicts."""
def removeValueIndex(name):
"""remove value index of given name"""
def addListener(listener):
"""add a listener.
Listener is expected to fulfil IListener.
If listener is Persistent, make a weak reference to it."""
def iterListeners():
"""return iterator of all available listeners"""
def removeListener(listener):
"""remove listener"""
def addDefaultQueryFactory(factory):
"""add a default query factory."""
def iterDefaultQueryFactories():
"""return iterator of all available factories"""
def removeDefaultQueryFactory(factory):
"""remove factory"""
def addSearchIndex(ix):
"""add a search index"""
def iterSearchIndexes():
"""return iterator of all search indexes"""
def removeSearchIndex(ix):
"""remove search index"""
def getRelationModuleTools():
"""return dict with useful BTree tools.
keys will include 'BTree', 'Bucket', 'Set', 'TreeSet', 'difference',
'dump', 'intersection', 'load', and 'union'. may also include
'multiunion'.
"""
def getValueModuleTools(name):
"""return dict with useful BTree tools for named value index.
keys will include 'BTree', 'Bucket', 'Set', 'TreeSet', 'difference',
'dump', 'intersection', 'load', and 'union'. may also include
'multiunion' and other keys for internal use.
"""
def getRelationTokens(query=None):
"""return tokens for given intransitive query, or all relation tokens.
Returns a None if no Tokens for query.
This also happens to be equivalent to `findRelationTokens` with
a maxDepth of 1, and no other arguments other than the optional
query, except that if there are no matches, `findRelationTokens`
returns an empty set (so it *always* returns an iterable). """
def getValueTokens(name, reltoken=None):
"""return value tokens for name, limited to relation token if given.
returns a none if no tokens.
This is identical to `findValueTokens`except that if there are
no matches, `findValueTokens` returns an empty set (so it
*always* returns an iterable) """
def yieldRelationTokenChains(query, relData, maxDepth, checkFilter,
checkTargetFilter, getQueries,
findCycles=True):
"""a search workhorse for searches that use a query factory
TODO: explain. :-/"""
def findValueTokens(
name, query=None, maxDepth=None, filter=None, targetQuery=None,
targetFilter=None, queryFactory=None, ignoreSearchIndex=False):
"""find token results for searchTerms.
- name is the index name wanted for results.
- if query is None (or evaluates to boolean False), returns the
underlying btree data structure; which is an iterable result but
can also be used with BTree operations
Otherwise, same arguments as findRelationChains.
"""
def findValues(
name, query=None, maxDepth=None, filter=None, targetQuery=None,
targetFilter=None, queryFactory=None, ignoreSearchIndex=False):
"""Like findValueTokens, but resolves value tokens"""
def findRelations(
query=(), maxDepth=None, filter=None, targetQuery=None,
targetFilter=None, queryFactory=None, ignoreSearchIndex=False):
"""Given a single dictionary of {indexName: token}, return an iterable
of relations that match the query"""
def findRelationTokens(
query=(), maxDepth=None, filter=None, targetQuery=None,
targetFilter=None, queryFactory=None, ignoreSearchIndex=False):
"""Given a single dictionary of {indexName: token}, return an iterable
of relation tokens that match the query"""
def findRelationTokenChains(
query, maxDepth=None, filter=None, targetQuery=None,
targetFilter=None, queryFactory=None):
"""find tuples of relation tokens for searchTerms.
- query is a dictionary of {indexName: token}
- maxDepth is None or a positive integer that specifies maximum depth
for transitive results. None means that the transitiveMap will be
followed until a cycle is detected. It is a ValueError to provide a
non-None depth if queryFactory is None and
index.defaultTransitiveQueriesFactory is None.
- filter is a an optional callable providing IFilter that determines
whether relations will be traversed at all.
- targetQuery is an optional query that specifies that only paths with
final relations that match the targetQuery should be returned.
It represents a useful subset of the jobs that can be done with the
targetFilter.
- targetFilter is an optional callable providing IFilter that
determines whether a given path will be included in results (it will
still be traversed)
- optional queryFactory takes the place of the index's
matching registered queryFactory, if any.
"""
def findRelationChains(
query, maxDepth=None, filter=None, targetQuery=None,
targetFilter=None, queryFactory=None):
"Like findRelationTokenChains, but resolves relation tokens"
def canFind(query, maxDepth=None, filter=None, targetQuery=None,
targetFilter=None, queryFactory=None, ignoreSearchIndex=False):
"""boolean if there is any result for the given search.
Same arguments as findRelationChains.
The general algorithm for using the arguments is this:
try to yield a single chain from findRelationTokenChains with the
given arguments. If one can be found, return True, else False."""
def tokenizeQuery(query):
'''Given a dictionary of {indexName: value} returns a dictionary of
{indexname: token} appropriate for the search methods'''
def resolveQuery(query):
'''Given a dictionary of {indexName: token} returns a dictionary of
{indexname: value}'''
def tokenizeValues(values, name):
"""Returns an iterable of tokens for the values of the given index
name"""
def resolveValueTokens(tokens, name):
"""Returns an iterable of values for the tokens of the given index
name"""
def tokenizeRelation(rel):
"""Returns a token for the given relation"""
def resolveRelationToken(token):
"""Returns a relation for the given token"""
def tokenizeRelations(rels):
"""Returns an iterable of tokens for the relations given"""
def resolveRelationTokens(tokens):
"""Returns an iterable of relations for the tokens given""" | zc.relation | /zc.relation-2.0.tar.gz/zc.relation-2.0/src/zc/relation/interfaces.py | interfaces.py |
import copy
import BTrees
import persistent
import zope.interface
import zc.relation.catalog
import zc.relation.interfaces
import zc.relation.queryfactory
import zc.relation.searchindex
##############################################################################
# common case search indexes
_marker = object()
@zope.interface.implementer(zc.relation.interfaces.ISearchIndex)
class TransposingTransitiveMembership(persistent.Persistent):
"""for searches using zc.relation.queryfactory.TransposingTransitive.
Only indexes one direction. Only indexes with maxDepth=None.
Does not support filters.
This search index's algorithm is intended for transposing transitive
searches that look *downward* in a top-down hierarchy. It could be
described as indexing transitive membership in a hierarchy--indexing the
children of a given node.
This index can significantly speed transitive membership tests,
demonstrating a factor-of-ten speed increase even in a small example. See
timeit/transitive_search_index.py for nitty-gritty details.
Using it to index the parents in a hierarchy (looking upward) would
technically work, but it would result in many writes when a top-level node
changed, and would probably not provide enough read advantage to account
for the write cost.
This approach could be used for other query factories that only look
at the final element in the relchain. If that were desired, I'd abstract
some of this code.
while target filters are currently supported, perhaps they shouldn't be:
the target filter can look at the last element in the relchain, but not
at the true relchain itself. That is: the relchain lies, except for the
last element.
The basic index is for relations. By providing ``names`` to the
initialization, the named value indexes will also be included in the
transitive search index.
"""
name = index = catalog = None
def __init__(self, forward, reverse, names=(), static=()):
# normalize
self.names = BTrees.family32.OO.Bucket([(nm, None) for nm in names])
self.forward = forward
self.reverse = reverse
self.update = frozenset((forward, reverse))
self.factory = zc.relation.queryfactory.TransposingTransitive(
forward, reverse, static)
for k, v in self.factory.static:
if isinstance(v, zc.relation.catalog.Any):
raise NotImplementedError(
'``Any`` static values are not supported at this time')
def copy(self, catalog):
new = self.__class__.__new__(self.__class__)
new.names = BTrees.family32.OO.Bucket()
for nm, val in self.names.items():
if val is not None:
new_val = zc.relation.catalog.getMapping(
self.catalog.getValueModuleTools(nm))()
for k, v in val.items():
new_val[k] = copy.copy(v)
val = new_val
new.names[nm] = val
new.forward = self.forward
new.reverse = self.reverse
new.update = self.update
new.factory = self.factory
if self.index is not None:
new.catalog = catalog
new.index = zc.relation.catalog.getMapping(
self.catalog.getRelationModuleTools())()
for k, v in self.index.items():
new.index[k] = copy.copy(v)
new.factory = self.factory
return new
def setCatalog(self, catalog):
if catalog is None:
self.index = self.catalog = None
return
elif self.catalog is not None:
raise ValueError('catalog already set')
self.catalog = catalog
self.index = zc.relation.catalog.getMapping(
self.catalog.getRelationModuleTools())()
for nm in self.names.keys():
self.names[nm] = zc.relation.catalog.getMapping(
self.catalog.getValueModuleTools(nm))()
for token in catalog.getRelationTokens():
if token not in self.index:
self._index(token)
# name, query_names, static_values, maxDepth, filter, queryFactory
res = [(None, (self.forward,), self.factory.static, None, None,
self.factory)]
for nm in self.names:
res.append(
(nm, (self.forward,), self.factory.static, None, None,
self.factory))
return res
def _index(self, token, removals=None, remove=False):
starts = {token}
if removals and self.forward in removals:
starts.update(t for t in removals[self.forward] if t is not None)
tokens = set()
reverseQuery = BTrees.family32.OO.Bucket(
((self.reverse, None),) + self.factory.static)
for token in starts:
getQueries = self.factory(dict(reverseQuery), self.catalog)
tokens.update(chain[-1] for chain in
self.catalog.yieldRelationTokenChains(
reverseQuery, ((token,),), None, None, None,
getQueries))
if remove:
tokens.remove(token)
self.index.pop(token, None)
for ix in self.names.values():
ix.pop(token, None)
# because of the possibility of cycles involving this token in the
# previous state, we first clean out all of the items "above"
for token in tokens:
self.index.pop(token, None)
# now we go back and try to fill them back in again. If there had
# been a cycle, we can see now that we have to work down.
relTools = self.catalog.getRelationModuleTools()
query = BTrees.family32.OO.Bucket(
((self.forward, None),) + self.factory.static)
getQueries = self.factory(query, self.catalog)
for token in tokens:
if token in self.index: # must have filled it in during a cycle
continue
stack = [[token, None, set(), [], {token}, False]]
while stack:
token, child, sets, empty, traversed_tokens, cycled = stack[-1]
if not sets:
rels = zc.relation.catalog.multiunion(
(self.catalog.getRelationTokens(q) for q in
getQueries([token])), relTools)
for rel in rels:
if rel == token:
# cycles on itself.
sets.add(relTools['Set']((token,)))
continue
indexed = self.index.get(rel)
if indexed is None:
iterator = reversed(stack)
traversed = [next(iterator)]
for info in iterator:
if rel == info[0]:
sets = info[2]
traversed_tokens = info[4]
cycled = True
for trav in traversed:
sets.update(trav[2])
trav[2] = sets
traversed_tokens.update(trav[4])
trav[4] = traversed_tokens
trav[5] = True
break
traversed.append(info)
else:
empty.append(rel)
else:
sets.add(indexed)
sets.add(rels)
if child is not None:
sets.add(child)
# clear it out
child = stack[-1][1] = None
if empty:
# We have one of two classes of situations. Either this
# *is* currently a cycle, and the result for this and all
# children will be the same set; or this *may* be
# a cycle, because this is an initial indexing.
# Walk down, passing token.
_next = empty.pop()
stack.append(
[_next, None, set(), [], {_next}, False])
else:
stack.pop()
assert stack or not cycled, (
'top level should never consider itself cycled')
if not cycled:
rels = zc.relation.catalog.multiunion(
sets, relTools)
rels.insert(token)
names = {}
for nm in self.names.keys():
names[nm] = zc.relation.catalog.multiunion(
(self.catalog.getValueTokens(nm, rel)
for rel in rels),
self.catalog.getValueModuleTools(nm))
for token in traversed_tokens:
self.index[token] = rels
for nm, ix in self.names.items():
ix[token] = names[nm]
if stack:
stack[-1][1] = rels
# listener interface
def relationAdded(self, token, catalog, additions):
if token in self.index and not self.update.intersection(additions):
return # no changes; don't do work
self._index(token)
def relationModified(self, token, catalog, additions, removals):
if (token in self.index and not self.update.intersection(additions) and
not self.update.intersection(removals)):
return # no changes; don't do work
self._index(token, removals)
def relationRemoved(self, token, catalog, removals):
self._index(token, removals, remove=True)
def sourceCleared(self, catalog):
if self.catalog is catalog:
self.setCatalog(None)
self.setCatalog(catalog)
# end listener interface
def getResults(self, name, query, maxDepth, filter, queryFactory):
rels = self.catalog.getRelationTokens(query)
if name is None:
tools = self.catalog.getRelationModuleTools()
ix = self.index
else:
tools = self.catalog.getValueModuleTools(name)
ix = self.names[name]
if rels is None:
return tools['Set']()
elif not rels:
return rels
return zc.relation.catalog.multiunion(
(ix.get(rel) for rel in rels), tools)
@zope.interface.implementer(
zc.relation.interfaces.ISearchIndex,
zc.relation.interfaces.IListener,
)
class Intransitive(persistent.Persistent):
"""saves results for precise search.
Could be used for transitive searches, but writes would be much more
expensive than the TransposingTransitive approach.
see tokens.rst for an example.
"""
# XXX Rename to Direct?
index = catalog = name = queryFactory = None
update = frozenset()
def __init__(self, names, name=None,
queryFactory=None, getValueTokens=None, update=None,
unlimitedDepth=False):
self.names = tuple(sorted(names))
self.name = name
self.queryFactory = queryFactory
if update is None:
update = names
if name is not None:
update += (name,)
self.update = frozenset(update)
self.getValueTokens = getValueTokens
if unlimitedDepth:
depths = (1, None)
else:
depths = (1,)
self.depths = tuple(depths)
def copy(self, catalog):
res = self.__class__.__new__(self.__class__)
if self.index is not None:
res.catalog = catalog
res.index = BTrees.family32.OO.BTree()
for k, v in self.index.items():
res.index[k] = copy.copy(v)
res.names = self.names
res.name = self.name
res.queryFactory = self.queryFactory
res.update = self.update
res.getValueTokens = self.getValueTokens
res.depths = self.depths
return res
def setCatalog(self, catalog):
if catalog is None:
self.index = self.catalog = None
return
elif self.catalog is not None:
raise ValueError('catalog already set')
self.catalog = catalog
self.index = BTrees.family32.OO.BTree()
self.sourceAdded(catalog)
# name, query_names, static_values, maxDepth, filter, queryFactory
return [(self.name, self.names, (), depth, None, self.queryFactory)
for depth in self.depths]
def relationAdded(self, token, catalog, additions):
self._index(token, catalog, additions)
def relationModified(self, token, catalog, additions, removals):
self._index(token, catalog, additions, removals)
def relationRemoved(self, token, catalog, removals):
self._index(token, catalog, removals=removals, removed=True)
def _index(self, token, catalog, additions=None, removals=None,
removed=False):
if ((not additions or not self.update.intersection(additions)) and
(not removals or not self.update.intersection(removals))):
return
if additions is None:
additions = {}
if removals is None:
removals = {}
for query in self.getQueries(token, catalog, additions, removals,
removed):
self._indexQuery(tuple(query.items()))
def _indexQuery(self, query):
dquery = dict(query)
if self.queryFactory is not None:
getQueries = self.queryFactory(dquery, self.catalog)
else:
def getQueries(empty):
return (query,)
res = zc.relation.catalog.multiunion(
(self.catalog.getRelationTokens(q) for q in getQueries(())),
self.catalog.getRelationModuleTools())
if not res:
self.index.pop(query, None)
else:
if self.name is not None:
res = zc.relation.catalog.multiunion(
(self.catalog.getValueTokens(self.name, r)
for r in res),
self.catalog.getValueModuleTools(self.name))
self.index[query] = res
def sourceAdded(self, catalog):
queries = set()
for token in catalog.getRelationTokens():
additions = {
info['name']: catalog.getValueTokens(info['name'], token)
for info in catalog.iterValueIndexInfo()}
queries.update(
tuple(q.items()) for q in
self.getQueries(token, catalog, additions, {}, False))
for q in queries:
self._indexQuery(q)
def sourceRemoved(self, catalog):
# this only really makes sense if the getQueries/getValueTokens was
# changed
queries = set()
for token in catalog.getRelationTokens():
removals = {
info['name']: catalog.getValueTokens(info['name'], token)
for info in catalog.iterValueIndexInfo()}
queries.update(
tuple(q.items()) for q in
self.getQueries(token, catalog, {}, removals, True))
for q in queries:
self._indexQuery(q)
def sourceCleared(self, catalog):
if self.catalog is catalog:
self.setCatalog(None)
self.setCatalog(catalog)
def sourceCopied(self, original, copy):
pass
def getQueries(self, token, catalog, additions, removals, removed):
source = {}
for name in self.names:
values = set()
for changes in (additions, removals):
value = changes.get(name, _marker)
if value is None:
values.add(value)
elif value is not _marker:
values.update(value)
if values:
if not removed and source:
source.clear()
break
source[name] = values
if removed and not source:
return
for name in self.names:
res = None
if self.getValueTokens is not None:
res = self.getValueTokens(self, name, token, catalog, source,
additions, removals, removed)
if res is None:
if name in source:
continue
res = {None}
current = self.catalog.getValueTokens(name, token)
if current:
res.update(current)
source[name] = res
vals = []
for name in self.names:
src = source[name]
iterator = iter(src)
value = next(iterator, _marker) # should always have at least one
if value is _marker:
return
vals.append([name, value, iterator, src])
while 1:
yield BTrees.family32.OO.Bucket(
[(name, value) for name, value, iterator, src in vals])
for s in vals:
name, value, iterator, src = s
_ = next(iterator, _marker)
if _ is _marker:
iterator = s[2] = iter(src)
_ = next(iterator, _marker)
if _ is _marker:
return
s[1] = _
else:
s[1] = _
break
else:
break
def getResults(self, name, query, maxDepth, filter, queryFactory):
query = tuple(query.items())
for nm, v in query:
if isinstance(v, zc.relation.catalog.Any):
return None # TODO open up
res = self.index.get(query)
if res is None:
if self.name is None:
res = self.catalog.getRelationModuleTools()['Set']()
else:
res = self.catalog.getValueModuleTools(self.name)['Set']()
return res | zc.relation | /zc.relation-2.0.tar.gz/zc.relation-2.0/src/zc/relation/searchindex.py | searchindex.py |
=================================================================
Working with Search Indexes: zc.relation Catalog Extended Example
=================================================================
Introduction
============
This document assumes you have read the README.rst document, and want to learn
a bit more by example. In it, we will explore a set of relations that
demonstrates most of the aspects of working with search indexes and listeners.
It will not explain the topics that the other documents already addressed. It
also describes an advanced use case.
As we have seen in the other documents, the relation catalog supports
search indexes. These can return the results of any search, as desired.
Of course, the intent is that you supply an index that optimizes the
particular searches it claims.
The searchindex module supplies a few search indexes, optimizing
specified transitive and intransitive searches. We have seen them working
in other documents. We will examine them more in depth in this document.
Search indexes update themselves by receiving messages via a "listener"
interface. We will also look at how this works.
The example described in this file examines a use case similar to that in
the zc.revision or zc.vault packages: a relation describes a graph of
other objects. Therefore, this is our first concrete example of purely
extrinsic relations.
Let's build the example story a bit. Imagine we have a graph, often a
hierarchy, of tokens--integers. Relations specify that a given integer
token relates to other integer tokens, with a containment denotation or
other meaning.
The integers may also have relations that specify that they represent an
object or objects.
This allows us to have a graph of objects in which changing one part of the
graph does not require changing the rest. zc.revision and zc.vault thus
are able to model graphs that can have multiple revisions efficiently and
with quite a bit of metadata to support merges.
Let's imagine a simple hierarchy. The relation has a `token` attribute
and a `children` attribute; children point to tokens. Relations will
identify themselves with ids.
>>> import BTrees
>>> relations = BTrees.family64.IO.BTree()
>>> relations[99] = None # just to give us a start
>>> class Relation(object):
... def __init__(self, token, children=()):
... self.token = token
... self.children = BTrees.family64.IF.TreeSet(children)
... self.id = relations.maxKey() + 1
... relations[self.id] = self
...
>>> def token(rel, self):
... return rel.token
...
>>> def children(rel, self):
... return rel.children
...
>>> def dumpRelation(obj, index, cache):
... return obj.id
...
>>> def loadRelation(token, index, cache):
... return relations[token]
...
The standard TransposingTransitiveQueriesFactory will be able to handle this
quite well, so we'll use that for our index.
>>> import zc.relation.queryfactory
>>> factory = zc.relation.queryfactory.TransposingTransitive(
... 'token', 'children')
>>> import zc.relation.catalog
>>> catalog = zc.relation.catalog.Catalog(
... dumpRelation, loadRelation, BTrees.family64.IO, BTrees.family64)
>>> catalog.addValueIndex(token)
>>> catalog.addValueIndex(children, multiple=True)
>>> catalog.addDefaultQueryFactory(factory)
Now let's quickly create a hierarchy and index it.
>>> for token, children in (
... (0, (1, 2)), (1, (3, 4)), (2, (10, 11, 12)), (3, (5, 6)),
... (4, (13, 14)), (5, (7, 8, 9)), (6, (15, 16)), (7, (17, 18, 19)),
... (8, (20, 21, 22)), (9, (23, 24)), (10, (25, 26)),
... (11, (27, 28, 29, 30, 31, 32))):
... catalog.index(Relation(token, children))
...
[#queryFactory]_ That hierarchy is arbitrary. Here's what we have, in terms of tokens
pointing to children::
_____________0_____________
/ \
________1_______ ______2____________
/ \ / | \
______3_____ _4_ 10 ____11_____ 12
/ \ / \ / \ / / | \ \ \
_______5_______ 6 13 14 25 26 27 28 29 30 31 32
/ | \ / \
_7_ _8_ 9 15 16
/ | \ / | \ / \
17 18 19 20 21 22 23 24
Twelve relations, with tokens 0 through 11, and a total of 33 tokens,
including children. The ids for the 12 relations are 100 through 111,
corresponding with the tokens of 0 through 11.
Without a transitive search index, we can get all transitive results.
The results are iterators.
>>> res = catalog.findRelationTokens({'token': 0})
>>> getattr(res, '__next__') is None
False
>>> getattr(res, '__len__', None) is None
True
>>> sorted(res)
[100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111]
>>> list(res)
[]
>>> res = catalog.findValueTokens('children', {'token': 0})
>>> sorted(res) == list(range(1, 33))
True
>>> list(res)
[]
[#findValuesUnindexed]_ `canFind` also can work transitively, and will
use transitive search indexes, as we'll see below.
>>> catalog.canFind({'token': 1}, targetQuery={'children': 23})
True
>>> catalog.canFind({'token': 2}, targetQuery={'children': 23})
False
>>> catalog.canFind({'children': 23}, targetQuery={'token': 1})
True
>>> catalog.canFind({'children': 23}, targetQuery={'token': 2})
False
`findRelationTokenChains` won't change, but we'll include it in the
discussion and examples to show that.
>>> res = catalog.findRelationTokenChains({'token': 2})
>>> chains = list(res)
>>> len(chains)
3
>>> len(list(res))
0
Transitive Search Indexes
=========================
Now we can add a couple of transitive search index. We'll talk about
them a bit first.
There is currently one variety of transitive index, which indexes
relation and value searches for the transposing transitive query
factory.
The index can only be used under certain conditions.
- The search is not a request for a relation chain.
- It does not specify a maximum depth.
- Filters are not used.
If it is a value search, then specific value indexes cannot be used if a
target filter or target query are used, but the basic relation index can
still be used in that case.
The usage of the search indexes is largely transparent: set them up, and
the relation catalog will use them for the same API calls that used more
brute force previously. The only difference from external uses is that
results that use an index will usually be a BTree structure, rather than
an iterator.
When you add a transitive index for a relation, you must specify the
transitive name (or names) of the query, and the same for the reverse.
That's all we'll do now.
>>> import zc.relation.searchindex
>>> catalog.addSearchIndex(
... zc.relation.searchindex.TransposingTransitiveMembership(
... 'token', 'children', names=('children',)))
Now we should have a search index installed.
Notice that we went from parent (token) to child: this index is primarily
designed for helping transitive membership searches in a hierarchy. Using it to
index parents would incur a lot of write expense for not much win.
There's just a bit more you can specify here: static fields for a query
to do a bit of filtering. We don't need any of that for this example.
Now how does the catalog use this index for searches? Three basic ways,
depending on the kind of search, relations, values, or `canFind`.
Before we start looking into the internals, let's verify that we're getting
what we expect: correct answers, and not iterators, but BTree structures.
>>> res = catalog.findRelationTokens({'token': 0})
>>> list(res)
[100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111]
>>> list(res)
[100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111]
>>> res = catalog.findValueTokens('children', {'token': 0})
>>> list(res) == list(range(1, 33))
True
>>> list(res) == list(range(1, 33))
True
>>> catalog.canFind({'token': 1}, targetQuery={'children': 23})
True
>>> catalog.canFind({'token': 2}, targetQuery={'children': 23})
False
[#findValuesIndexed]_ Note that the last two `canFind` examples from
when we went through these examples without an index do not use the
index, so we don't show them here: they look the wrong direction for
this index.
So how do these results happen?
The first, `findRelationTokens`, and the last, `canFind`, are the most
straightforward. The index finds all relations that match the given
query, intransitively. Then for each relation, it looks up the indexed
transitive results for that token. The end result is the union of all
indexed results found from the intransitive search. `canFind` simply
casts the result into a boolean.
`findValueTokens` is the same story as above with only one more step. After
the union of relations is calculated, the method returns the union of the
sets of the requested value for all found relations.
It will maintain itself when relations are reindexed.
>>> rel = list(catalog.findRelations({'token': 11}))[0]
>>> for t in (27, 28, 29, 30, 31):
... rel.children.remove(t)
...
>>> catalog.index(rel)
>>> catalog.findValueTokens('children', {'token': 0})
... # doctest: +NORMALIZE_WHITESPACE
LFSet([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 32])
>>> catalog.findValueTokens('children', {'token': 2})
LFSet([10, 11, 12, 25, 26, 32])
>>> catalog.findValueTokens('children', {'token': 11})
LFSet([32])
>>> rel.children.remove(32)
>>> catalog.index(rel)
>>> catalog.findValueTokens('children', {'token': 0})
... # doctest: +NORMALIZE_WHITESPACE
LFSet([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26])
>>> catalog.findValueTokens('children', {'token': 2})
LFSet([10, 11, 12, 25, 26])
>>> catalog.findValueTokens('children', {'token': 11})
LFSet([])
>>> rel.children.insert(27)
1
>>> catalog.index(rel)
>>> catalog.findValueTokens('children', {'token': 0})
... # doctest: +NORMALIZE_WHITESPACE
LFSet([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27])
>>> catalog.findValueTokens('children', {'token': 2})
LFSet([10, 11, 12, 25, 26, 27])
>>> catalog.findValueTokens('children', {'token': 11})
LFSet([27])
When the index is copied, the search index is copied.
>>> new = catalog.copy()
>>> res = list(new.iterSearchIndexes())
>>> len(res)
1
>>> new_index = res[0]
>>> res = list(catalog.iterSearchIndexes())
>>> len(res)
1
>>> old_index = res[0]
>>> new_index is old_index
False
>>> old_index.index is new_index.index
False
>>> list(old_index.index.keys()) == list(new_index.index.keys())
True
>>> from __future__ import print_function
>>> for key, value in old_index.index.items():
... v = new_index.index[key]
... if v is value or list(v) != list(value):
... print('oops', key, value, v)
... break
... else:
... print('good')
...
good
>>> old_index.names is not new_index.names
True
>>> list(old_index.names) == list(new_index.names)
True
>>> for name, old_ix in old_index.names.items():
... new_ix = new_index.names[name]
... if new_ix is old_ix or list(new_ix.keys()) != list(old_ix.keys()):
... print('oops')
... break
... for key, value in old_ix.items():
... v = new_ix[key]
... if v is value or list(v) != list(value):
... print('oops', name, key, value, v)
... break
... else:
... continue
... break
... else:
... print('good')
...
good
Helpers
=======
When writing search indexes and query factories, you often want complete
access to relation catalog data. We've seen a number of these tools already:
- `getRelationModuleTools` gets a dictionary of the BTree tools needed to
work with relations.
>>> sorted(catalog.getRelationModuleTools().keys())
... # doctest: +NORMALIZE_WHITESPACE
['BTree', 'Bucket', 'Set', 'TreeSet', 'difference', 'dump',
'intersection', 'load', 'multiunion', 'union']
'multiunion' is only there if the BTree is an I* or L* module.
Use the zc.relation.catalog.multiunion helper function to do the
best union you can for a given set of tools.
- `getValueModuleTools` does the same for indexed values.
>>> tools = set(('BTree', 'Bucket', 'Set', 'TreeSet', 'difference',
... 'dump', 'intersection', 'load', 'multiunion', 'union'))
>>> tools.difference(catalog.getValueModuleTools('children').keys()) == set()
True
>>> tools.difference(catalog.getValueModuleTools('token').keys()) == set()
True
- `getRelationTokens` can return all of the tokens in the catalog.
>>> len(catalog.getRelationTokens()) == len(catalog)
True
This also happens to be equivalent to `findRelationTokens` with an empty
query.
>>> catalog.getRelationTokens() is catalog.findRelationTokens({})
True
It also can return all the tokens that match a given query, or None if
there are no matches.
>>> catalog.getRelationTokens({'token': 0}) # doctest: +ELLIPSIS
<BTrees.LOBTree.LOTreeSet object at ...>
>>> list(catalog.getRelationTokens({'token': 0}))
[100]
This also happens to be equivalent to `findRelationTokens` with a query,
a maxDepth of 1, and no other arguments.
>>> catalog.findRelationTokens({'token': 0}, maxDepth=1) is (
... catalog.getRelationTokens({'token': 0}))
True
Except that if there are no matches, `findRelationTokens` returns an empty
set (so it *always* returns an iterable).
>>> catalog.findRelationTokens({'token': 50}, maxDepth=1)
LOSet([])
>>> print(catalog.getRelationTokens({'token': 50}))
None
- `getValueTokens` can return all of the tokens for a given value name in
the catalog.
>>> list(catalog.getValueTokens('token')) == list(range(12))
True
This is identical to catalog.findValueTokens with a name only (or with
an empty query, and a maxDepth of 1).
>>> list(catalog.findValueTokens('token')) == list(range(12))
True
>>> catalog.findValueTokens('token') is catalog.getValueTokens('token')
True
It can also return the values for a given token.
>>> list(catalog.getValueTokens('children', 100))
[1, 2]
This is identical to catalog.findValueTokens with a name and a query of
{None: token}.
>>> list(catalog.findValueTokens('children', {None: 100}))
[1, 2]
>>> catalog.getValueTokens('children', 100) is (
... catalog.findValueTokens('children', {None: 100}))
True
Except that if there are no matches, `findValueTokens` returns an empty
set (so it *always* returns an iterable); while getValueTokens will
return None if the relation has no values (or the relation is unknown).
>>> catalog.findValueTokens('children', {None: 50}, maxDepth=1)
LFSet([])
>>> print(catalog.getValueTokens('children', 50))
None
>>> rel.children.remove(27)
>>> catalog.index(rel)
>>> catalog.findValueTokens('children', {None: rel.id}, maxDepth=1)
LFSet([])
>>> print(catalog.getValueTokens('children', rel.id))
None
- `yieldRelationTokenChains` is a search workhorse for searches that use a
query factory. TODO: describe.
.. ......... ..
.. Footnotes ..
.. ......... ..
.. [#queryFactory] The query factory knows when it is not needed--not only
when neither of its names are used, but also when both of its names are
used.
>>> list(catalog.findRelationTokens({'token': 0, 'children': 1}))
[100]
.. [#findValuesUnindexed] When values are the same as their tokens,
`findValues` returns the same result as `findValueTokens`. Here
we see this without indexes.
>>> list(catalog.findValueTokens('children', {'token': 0})) == list(
... catalog.findValues('children', {'token': 0}))
True
.. [#findValuesIndexed] Again, when values are the same as their tokens,
`findValues` returns the same result as `findValueTokens`. Here
we see this with indexes.
>>> list(catalog.findValueTokens('children', {'token': 0})) == list(
... catalog.findValues('children', {'token': 0}))
True
| zc.relation | /zc.relation-2.0.tar.gz/zc.relation-2.0/src/zc/relation/searchindex.rst | searchindex.rst |
import copy
import sys
import BTrees
import BTrees.check
import BTrees.Length
import persistent
import persistent.list
import persistent.wref
import zope.interface
import zope.interface.interfaces
from zc.relation import interfaces
##############################################################################
# constants
#
RELATION = None
# uh, yeah. None. The story is, zc.relation.RELATION is more readable as
# a search key, so I want a constant; but by the time I came to this decision,
# ``None`` had already been advertised as the way to spell this. So, yeah...
# hysterical raisins.
##############################################################################
# helpers
#
_marker = object()
def multiunion(sets, data):
sets = tuple(s for s in sets if s) # bool is appropriate here
if not sets:
res = data['Set']()
elif data['multiunion'] is not None:
res = data['multiunion'](sets)
else:
res = sets[0]
for s in sets[1:]:
res = data['union'](res, s)
return res
def getModuleTools(module):
return {
nm: getattr(module, nm, None) for nm in
('BTree', 'TreeSet', 'Bucket', 'Set',
'intersection', 'multiunion', 'union', 'difference')}
def getMapping(tools):
if tools['TreeSet'].__name__[0] == 'I':
Mapping = BTrees.family32.IO.BTree
elif tools['TreeSet'].__name__[0] == 'L':
Mapping = BTrees.family64.IO.BTree
else:
assert tools['TreeSet'].__name__.startswith('O')
Mapping = BTrees.family32.OO.BTree
return Mapping
class Ref(persistent.Persistent):
def __init__(self, ob):
self.ob = ob
def __call__(self):
return self.ob
def createRef(ob):
if isinstance(ob, persistent.Persistent):
return persistent.wref.WeakRef(ob)
else:
return Ref(ob)
##############################################################################
# Any and any
#
class Any:
def __init__(self, source):
self.source = frozenset(source)
def __iter__(self):
return iter(self.source)
def __eq__(self, other):
return (isinstance(other, self.__class__) and
self.source == other.source)
def __ne__(self, other):
return not self.__eq__(other)
def __repr__(self):
return '<{}.{} instance {!r}>'.format(
self.__class__.__module__, self.__class__.__name__,
tuple(sorted(self.source)))
def any(*args):
return Any(args)
##############################################################################
# the marker that shows that a path is circular
#
@zope.interface.implementer(interfaces.ICircularRelationPath)
class CircularRelationPath(tuple):
def __new__(cls, elements, cycled):
res = super().__new__(cls, elements)
res.cycled = cycled
return res
def __repr__(self):
return 'cycle%s' % super().__repr__()
##############################################################################
# the relation catalog
@zope.interface.implementer(interfaces.ICatalog)
class Catalog(persistent.Persistent):
family = BTrees.family32
_listeners = _queryFactories = _searchIndexes = ()
_searchIndexMatches = None
def __init__(self, dump, load, btree=None, family=None):
# instantiate with instructions on how to dump and load relations,
# and optionally the btree module for relations. ``family`` should
# either be BTrees.family32 or BTrees.family64, and will be ignored
# if ``btree`` is always specified. (Otherwise, it will make btree
# default to family.IF for relations and value indexes.)
if family is not None:
self.family = family
else:
family = self.family
self._name_TO_mapping = family.OO.BTree()
# held mappings are objtoken to (relcount, relset)
self._EMPTY_name_TO_relcount_relset = family.OO.BTree()
self._reltoken_name_TO_objtokenset = family.OO.BTree()
if btree is None:
btree = family.IF
self._relTools = getModuleTools(btree)
self._relTools['load'] = load
self._relTools['dump'] = dump
self._relLength = BTrees.Length.Length()
self._relTokens = self._relTools['TreeSet']()
# private; only mutate via indexValue and unindexValue
self._attrs = self.family.OO.Bucket() # _attrs name is legacy
# The code is divided into the following sections by ReST-like headers:
#
# Administration and Introspection
# General
# Value Indexes
# Listeners
# DefaultQueryFactories
# Search Indexes
# Indexing
# Top-Level
# Indexing Values
# Tokenization
# Searching
# Administration and Introspection
# ================================
# General
# -------
def __contains__(self, rel):
return self.tokenizeRelation(rel) in self._relTokens
def __len__(self):
return self._relLength.value
def __iter__(self):
cache = {}
for token in self._relTokens:
yield self._relTools['load'](token, self, cache)
def clear(self):
for v in self._name_TO_mapping.values():
v.clear()
self._EMPTY_name_TO_relcount_relset.clear()
self._reltoken_name_TO_objtokenset.clear()
self._relTokens.clear()
self._relLength.set(0)
for listener in self._iterListeners():
listener.sourceCleared(self)
def copy(self, klass=None):
if klass is None:
klass = self.__class__
res = klass.__new__(klass)
res._relTokens = self._relTools['TreeSet']()
res._relTokens.update(self._relTokens)
res.family = self.family
res._name_TO_mapping = self.family.OO.BTree()
for name, mapping in self._name_TO_mapping.items():
new = mapping.__class__()
for k, (l, s) in mapping.items():
new[k] = (copy.copy(l), copy.copy(s))
res._name_TO_mapping[name] = new
res._EMPTY_name_TO_relcount_relset = self.family.OO.BTree()
for k, (l, s) in self._EMPTY_name_TO_relcount_relset.items():
res._EMPTY_name_TO_relcount_relset[k] = (
copy.copy(l), copy.copy(s))
res._reltoken_name_TO_objtokenset = self.family.OO.BTree()
for k, s in self._reltoken_name_TO_objtokenset.items():
res._reltoken_name_TO_objtokenset[k] = copy.copy(s)
res._attrs = self.family.OO.Bucket(
[(k, self.family.OO.Bucket(v)) for k, v in self._attrs.items()])
res._relTools = dict(self._relTools)
res._queryFactories = self._queryFactories # it's a tuple
res._relLength = BTrees.Length.Length()
res._relLength.set(self._relLength.value)
if self._searchIndexMatches is not None:
indexes = []
res._searchIndexMatches = self.family.OO.Bucket()
for ix, keys in self._searchIndexes:
cix = ix.copy(res)
indexes.append((cix, keys))
for key in keys:
dest = res._searchIndexMatches.get(key)
if dest is None:
dest = res._searchIndexMatches[key] = (
persistent.list.PersistentList())
for info in self._searchIndexMatches[key]:
if info[3] is ix:
dest.append(info[:3] + (cix,))
res._searchIndexes = tuple(indexes)
for listener in self._listeners:
listener.sourceCopied(self, res)
return res
# Value Indexes
# -------------
def _fixLegacyAttrs(self):
if isinstance(self._attrs, dict): # legacy
# because _attrs used to be a normal dict
self._attrs = self.family.OO.Bucket(self._attrs)
def addValueIndex(self, element, dump=None, load=None, btree=None,
multiple=False, name=None):
if btree is None:
btree = self.family.IF
value_index_info = self.family.OO.Bucket(getModuleTools(btree))
value_index_info['dump'] = dump
value_index_info['load'] = load
value_index_info['multiple'] = multiple
if (value_index_info['dump'] is None) \
^ (value_index_info['load'] is None):
raise ValueError(
"either both of 'dump' and 'load' must be None, or "
"neither")
# when both load and dump are None, this is a small
# optimization that can be a large optimization if the returned
# value is one of the main four options of the selected btree
# family (BTree, TreeSet, Set, Bucket).
if zope.interface.interfaces.IElement.providedBy(element):
key = 'element'
value_index_info['attrname'] = defaultname = element.__name__
value_index_info['interface'] = element.interface
value_index_info['call'] = \
zope.interface.interfaces.IMethod.providedBy(element)
else:
key = 'callable'
defaultname = getattr(element, '__name__', None)
if [d for d in self._attrs.values() if d.get(key) == element]:
raise ValueError('element already indexed', element)
value_index_info[key] = element
if name is None:
if defaultname is None:
raise ValueError('no name specified')
name = defaultname
if name in self._attrs:
raise ValueError('name already used', name)
value_index_info['name'] = name
self._name_TO_mapping[name] = getMapping(value_index_info)()
# these are objtoken to (relcount, relset)
self._attrs[name] = value_index_info
load = self._relTools['load']
cache = {}
for token in self._relTokens:
additions = {}
additions[name] = (None, self._indexNew(
token, load(token, self, cache), value_index_info))
for listener in self._iterListeners():
listener.relationModified(token, self, additions, {})
self._fixLegacyAttrs()
def iterValueIndexInfo(self):
for d in self._attrs.values():
res = {}
res['name'] = d['name']
res['element'] = d.get('element', d.get('callable'))
res['multiple'] = d['multiple']
res['dump'] = d['dump']
res['load'] = d['load']
res['btree'] = sys.modules[d['TreeSet'].__module__]
yield res
def removeValueIndex(self, name):
del self._attrs[name]
self._fixLegacyAttrs()
del self._name_TO_mapping[name]
if name in self._EMPTY_name_TO_relcount_relset:
del self._EMPTY_name_TO_relcount_relset[name]
# Listeners
# -----------
def addListener(self, listener, weakref=False):
res = []
for item in self._listeners:
if isinstance(item, persistent.wref.WeakRef):
if item() is not None:
res.append(item)
else:
res.append(item)
if isinstance(listener, persistent.Persistent):
if weakref:
res.append(persistent.wref.WeakRef(listener))
else:
res.append(listener)
else:
if weakref:
raise ValueError('cannot use weakref on non-persistent object')
# make a persistent object so tuple itself is smaller
res.append(Ref(listener))
self._listeners = tuple(res)
listener.sourceAdded(self)
def iterListeners(self):
for item in self._listeners:
if isinstance(item, (persistent.wref.WeakRef, Ref)):
item = item()
if item is None:
continue
yield item
def removeListener(self, listener):
if listener is None:
raise LookupError('listener not found', listener)
res = []
found = False
for item in reversed(self._listeners):
if isinstance(item, (persistent.wref.WeakRef, Ref)):
val = item()
if val is None:
continue
else:
val = item
if val is listener and not found:
found = True
continue
res.append(item)
if not found:
raise LookupError('listener not found', listener)
res.reverse()
self._listeners = tuple(res)
listener.sourceRemoved(self)
# DefaultQueryFactories
# -----------------------
def addDefaultQueryFactory(self, factory):
if factory in self._queryFactories:
raise ValueError('factory already registered')
self._queryFactories += (factory,)
def iterDefaultQueryFactories(self):
return iter(self._queryFactories)
def removeDefaultQueryFactory(self, factory):
res = list(self._queryFactories)
try:
res.remove(factory)
except ValueError:
raise LookupError('factory not found', factory)
self._queryFactories = tuple(res)
# Search Indexes
# --------------
def addSearchIndex(self, ix):
matches = tuple(ix.setCatalog(self))
if self._searchIndexMatches is None:
self._searchIndexMatches = self.family.OO.Bucket()
keys = set()
for (name,
query_names,
static_values,
maxDepth,
filter,
queryFactory) in matches:
if name is None:
name = ''
rel_bool = True
else:
rel_bool = False
query_names_res = BTrees.family32.OO.Set() # sorts
relation_query = False
for nm in query_names:
if nm is RELATION:
relation_query = True
else:
query_names_res.insert(nm)
if getattr(static_values, 'items', None) is not None:
static_values = static_values.items()
for k, v in static_values:
if k is RELATION:
raise ValueError(
'may not register static value for RELATION (None)')
query_names_res.insert(k)
if maxDepth is None:
maxDepth = 0
k = (rel_bool, name, relation_query,
tuple(query_names_res), maxDepth)
a = self._searchIndexMatches.get(k)
if a is None:
self._searchIndexMatches[
k] = a = persistent.list.PersistentList()
a.append((filter, queryFactory, tuple(static_values), ix))
keys.add(k)
keys = frozenset(keys)
self._searchIndexes += ((ix, keys),)
def iterSearchIndexes(self):
return (data[0] for data in self._searchIndexes)
def removeSearchIndex(self, ix):
res = []
keys = None
for data in self._searchIndexes:
if data[0] is ix:
assert keys is None, 'internal data structure error'
keys = data[1]
else:
res.append(data)
if keys is None:
raise LookupError('index not found', ix)
self._searchIndexes = tuple(res)
ix.setCatalog(None)
if not res:
self._searchIndexMatches = None
else:
for key in keys:
a = self._searchIndexMatches[key]
res = persistent.list.PersistentList(
info for info in a if info[3] is not ix)
if not res:
del self._searchIndexMatches[key]
else:
self._searchIndexMatches[key] = res
# Indexing
# ========
# Top-Level
# ---------
def _indexNew(self, token, rel, value_index_info):
assert self._reltoken_name_TO_objtokenset.get(
(token, value_index_info['name']), self) is self
values, tokens, optimization = self._getValuesAndTokens(
rel, value_index_info)
if optimization and tokens is not None:
tokens = value_index_info['TreeSet'](tokens)
self._add(token, tokens, value_index_info['name'], tokens)
return tokens
def index(self, rel):
self.index_doc(self._relTools['dump'](rel, self, {}), rel)
def index_doc(self, relToken, rel):
additions = {}
removals = {}
if relToken in self._relTokens:
# reindex
for data in self._attrs.values():
values, newTokens, optimization = self._getValuesAndTokens(
rel, data)
oldTokens = self._reltoken_name_TO_objtokenset[
(relToken, data['name'])]
if newTokens != oldTokens:
if newTokens is not None and oldTokens is not None:
added = data['difference'](newTokens, oldTokens)
removed = data['difference'](oldTokens, newTokens)
if optimization:
# the goal of this optimization is to not have to
# recreate a TreeSet (which can be large and
# relatively timeconsuming) when only small changes
# have been made. We ballpark this by saying
# "if there are only a few removals, do them, and
# then do an update: it's almost certainly a win
# over essentially generating a new TreeSet and
# updating it with *all* values. On the other
# hand, if there are a lot of removals, it's
# probably quicker just to make a new one." See
# timeit/set_creation_vs_removal.py for details.
# A len is pretty cheap--`removed` is a single
# bucket, and `oldTokens` should have all of its
# buckets in memory already, and adding up bucket
# lens in C is pretty fast.
len_removed = len(removed)
if len_removed < 5:
recycle = True
else:
len_old = len(oldTokens)
ratio = float(len_old) / len_removed
recycle = (ratio <= 0.1 or len_old > 500
and ratio < 0.2)
if recycle:
for t in removed:
oldTokens.remove(t)
oldTokens.update(added)
newTokens = oldTokens
else:
newTokens = data['TreeSet'](newTokens)
else:
if optimization and newTokens is not None:
newTokens = data['TreeSet'](newTokens)
removed = oldTokens
added = newTokens
self._remove(relToken, removed, data['name'])
if removed:
removals[data['name']] = removed
self._add(relToken, added, data['name'], newTokens)
if added:
additions[data['name']] = added
for listener in self._iterListeners():
listener.relationModified(relToken, self, additions, removals)
else:
# new token
for value_index_info in self._attrs.values():
additions[value_index_info['name']] = self._indexNew(
relToken, rel, value_index_info)
self._relTokens.insert(relToken)
self._relLength.change(1)
for listener in self._iterListeners():
listener.relationAdded(relToken, self, additions)
def unindex(self, rel):
self.unindex_doc(self._relTools['dump'](rel, self, {}))
def unindex_doc(self, relToken):
removals = {}
if relToken in self._relTokens:
for value_index_info in self._attrs.values():
tokens = self._reltoken_name_TO_objtokenset.pop(
(relToken, value_index_info['name']))
if tokens:
removals[value_index_info['name']] = tokens
self._remove(relToken, tokens, value_index_info['name'])
self._relTokens.remove(relToken)
self._relLength.change(-1)
for listener in self._iterListeners():
listener.relationRemoved(relToken, self, removals)
# Indexing Values
# ---------------
def _getValuesAndTokens(self, rel, data):
values = None
if 'interface' in data:
valueSource = data['interface'](rel, None)
if valueSource is not None:
values = getattr(valueSource, data['attrname'])
if data['call']:
values = values()
else:
values = data['callable'](rel, self)
if not data['multiple'] and values is not None:
# None is a marker for no value
values = (values,)
optimization = data['dump'] is None and (
values is None or
isinstance(values, (
data['TreeSet'], data['BTree'], data['Bucket'], data['Set'])))
if not values:
return None, None, optimization
elif optimization:
# this is the optimization story (see _add)
return values, values, optimization
else:
cache = {}
if data['dump'] is None:
tokens = data['TreeSet'](values)
else:
tokens = data['TreeSet'](
data['dump'](o, self, cache) for o in values)
return values, tokens, False
def _add(self, relToken, tokens, name, fullTokens):
self._reltoken_name_TO_objtokenset[(relToken, name)] = fullTokens
if tokens is None:
dataset = self._EMPTY_name_TO_relcount_relset
keys = (name,)
else:
dataset = self._name_TO_mapping[name]
keys = tokens
for key in keys:
data = dataset.get(key)
if data is None:
data = dataset[key] = (
BTrees.Length.Length(), self._relTools['TreeSet']())
res = data[1].insert(relToken)
assert res, 'Internal error: relToken existed in data'
data[0].change(1)
def _remove(self, relToken, tokens, name):
"""
relToken: The token to remove
tokens: the tokens that match for the value index of `name`
name: the name of the value index
"""
if tokens is None:
dataset = self._EMPTY_name_TO_relcount_relset
keys = (name,)
else:
dataset = self._name_TO_mapping[name]
keys = tokens
for key in keys:
try:
data = dataset[key]
except KeyError:
BTrees.check.check(dataset)
raise
data[1].remove(relToken)
data[0].change(-1)
if not data[0].value:
del dataset[key]
else:
assert data[0].value > 0
# Tokenization
# ============
def tokenizeQuery(self, *args, **kwargs):
if args:
if kwargs or len(args) > 1:
raise TypeError(
'supply a query dictionary or keyword arguments, not both')
query = args[0]
else:
query = kwargs
res = {}
for k, v in query.items():
if k is RELATION:
tools = self._relTools
else:
tools = self._attrs[k]
if isinstance(v, Any):
if tools['dump'] is not None:
cache = {}
v = Any(tools['dump'](val, self, cache) for val in v)
else:
if v is not None and tools['dump'] is not None:
v = tools['dump'](v, self, {})
res[k] = v
return res
def resolveQuery(self, *args, **kwargs):
if args:
if kwargs or len(args) > 1:
raise TypeError(
'supply a query dictionary or keyword arguments, not both')
query = args[0]
else:
query = kwargs
res = {}
for k, v in query.items():
if k is RELATION:
tools = self._relTools
else:
tools = self._attrs[k]
if isinstance(v, Any):
if tools['load'] is not None:
cache = {}
v = Any(tools['load'](val, self, cache) for val in v)
else:
if v is not None and tools['load'] is not None:
v = tools['load'](v, self, {})
res[k] = v
return res
def tokenizeValues(self, values, name):
dump = self._attrs[name]['dump']
if dump is None:
return values
cache = {}
return (dump(v, self, cache) for v in values)
def resolveValueTokens(self, tokens, name):
load = self._attrs[name]['load']
if load is None:
return tokens
cache = {}
return (load(t, self, cache) for t in tokens)
def tokenizeRelation(self, rel):
return self._relTools['dump'](rel, self, {})
def resolveRelationToken(self, token):
return self._relTools['load'](token, self, {})
def tokenizeRelations(self, rels):
cache = {}
return (self._relTools['dump'](r, self, cache) for r in rels)
def resolveRelationTokens(self, tokens):
cache = {}
return (self._relTools['load'](t, self, cache) for t in tokens)
# Searching
# =========
# Internal Helpers
# ----------------
def _relData(self, query):
# query must be BTrees.family32.OO.Bucket. The key may be
# a value index name or RELATION, indicating one or more relations. The
# val may be token, None, or iterator (object with a `next` method) of
# tokens (may not include None).
if not query:
return self._relTokens
data = []
tools = self._relTools
explicit_relations = False
for name, value in query.items():
if name is RELATION:
explicit_relations = True
if not isinstance(value, Any):
value = (value,)
rels = tools['Set'](value)
length = len(rels)
else:
if isinstance(value, Any):
get = self._name_TO_mapping[name].get
rels = multiunion(
(get(token, (None, None))[1] for token in value),
self._relTools)
length = len(rels)
else:
if value is None:
relData = self._EMPTY_name_TO_relcount_relset.get(name)
else:
relData = self._name_TO_mapping[name].get(value)
if relData is None:
return None
length = relData[0].value
rels = relData[1]
if not length:
return None
data.append((length, rels))
# we don't want to sort on the set values!! just the lengths.
data.sort(key=lambda i: i[0])
if explicit_relations and len(data) == 1:
# we'll need to intersect with our set of relations to make
# sure the relations are actually members. This set should
# be the biggest possible set, so we put it at the end after
# sorting.
data.append((self._relLength.value, self._relTokens))
# we know we have at least one result now. intersect all. Work
# from smallest to largest, until we're done or we don't have any
# more results.
res = data.pop(0)[1]
while res and data:
res = self._relTools['intersection'](res, data.pop(0)[1])
return res
def _getSearchIndexResults(self, key, query, maxDepth, filter,
targetQuery, targetFilter, queryFactory):
# only call for relations
for (c_filter, c_queryFactory,
c_static_values, ix) in self._searchIndexMatches.get(key, ()):
if (c_filter != filter or
c_queryFactory != queryFactory):
continue
for k, v in c_static_values:
if query[k] != v: # we want a precise match here
continue
res = ix.getResults(
None, query, maxDepth, filter, queryFactory)
if res is not None:
if res:
if targetQuery:
targetData = self._relData(targetQuery)
if not targetData:
return self._relTools['Set']()
res = self._relTools['intersection'](
res, targetData)
if targetFilter is not None:
targetCache = {}
res = (rel
for rel in res
if targetFilter(
[rel], query, self, targetCache))
return res
def _iterListeners(self):
# fix up ourself first
for ix, keys in self._searchIndexes:
yield ix
# then tell others
yield from self.iterListeners()
def _getQueryFactory(self, query, queryFactory):
res = None
if queryFactory is not None:
res = queryFactory(query, self)
else:
for queryFactory in self.iterDefaultQueryFactories():
res = queryFactory(query, self)
if res is not None:
break
if res is None:
queryFactory = None
return queryFactory, res
def _parse(self, query, maxDepth, filter, targetQuery, targetFilter,
getQueries):
assert (isinstance(query, BTrees.family32.OO.Bucket) and
isinstance(targetQuery, BTrees.family32.OO.Bucket)), (
'internal error: parse expects query and targetQuery '
'to already be normalized (to OO.Bucket.')
if maxDepth is not None and (
not isinstance(maxDepth, int) or maxDepth < 1):
raise ValueError('maxDepth must be None or a positive integer')
if getQueries is not None:
queries = getQueries(())
else:
queries = (query,)
if getQueries is None and maxDepth is not None:
raise ValueError(
'if maxDepth not in (None, 1), queryFactory must be available')
relData = (r for r in (self._relData(q) for q in queries) if r)
if filter is not None:
filterCache = {}
def checkFilter(relchain, query):
return filter(relchain, query, self, filterCache)
else:
checkFilter = None
targetCache = {}
checkTargetFilter = None
if targetQuery:
targetData = self._relData(targetQuery)
if not targetData:
relData = () # shortcut
else:
if targetFilter is not None:
def checkTargetFilter(relchain, query):
return relchain[-1] in targetData and targetFilter(
relchain, query, self, targetCache)
else:
def checkTargetFilter(relchain, query):
return relchain[-1] in targetData
elif targetFilter is not None:
def checkTargetFilter(relchain, query):
return targetFilter(relchain, query, self, targetCache)
return (query, relData, maxDepth, checkFilter, checkTargetFilter,
getQueries)
# API to help plugin writers
# --------------------------
def getRelationModuleTools(self):
return self._relTools
def getValueModuleTools(self, name):
return self._attrs[name]
def getRelationTokens(self, query=None):
if query is None:
return self._relTokens
else:
if not isinstance(query, BTrees.family32.OO.Bucket):
query = BTrees.family32.OO.Bucket(query)
return self._relData(query)
def getValueTokens(self, name, reltoken=None):
if reltoken is None:
return self._name_TO_mapping[name]
else:
return self._reltoken_name_TO_objtokenset.get(
(reltoken, name))
def yieldRelationTokenChains(self, query, relData, maxDepth, checkFilter,
checkTargetFilter, getQueries,
findCycles=True):
stack = []
for d in relData:
stack.append(((), iter(d)))
while stack:
tokenChain, relDataIter = stack[0]
relToken = next(relDataIter, _marker)
if relToken is _marker:
stack.pop(0)
else:
tokenChain += (relToken,)
if checkFilter is not None and not checkFilter(
tokenChain, query):
continue
walkFurther = maxDepth is None or len(tokenChain) < maxDepth
if getQueries is not None and (walkFurther or findCycles):
oldInputs = frozenset(tokenChain)
_next = set()
cycled = []
for q in getQueries(tokenChain):
relData = self._relData(q)
if relData:
intersection = oldInputs.intersection(relData)
if intersection:
# it's a cycle
cycled.append(q)
elif walkFurther:
_next.update(relData)
if walkFurther and _next:
stack.append((tokenChain, iter(_next)))
if cycled:
tokenChain = CircularRelationPath(
tokenChain, cycled)
if (checkTargetFilter is None or
checkTargetFilter(tokenChain, query)):
yield tokenChain
# Main search API
# ---------------
def findValueTokens(self, name, query=(), maxDepth=None,
filter=None, targetQuery=(), targetFilter=None,
queryFactory=None, ignoreSearchIndex=False):
data = self._attrs.get(name)
if data is None:
raise ValueError('name not indexed', name)
query = BTrees.family32.OO.Bucket(query) # sorts on key
getQueries = None
if queryFactory is None:
queryFactory, getQueries = self._getQueryFactory(
query, queryFactory)
targetQuery = BTrees.family32.OO.Bucket(targetQuery)
if (((maxDepth is None and queryFactory is None)
or maxDepth == 1) and filter is None and targetFilter is None):
# return a set
if not query and not targetQuery:
return self._name_TO_mapping[name]
rels = self._relData(query)
if targetQuery and rels:
# well, it's kind of odd to have specified query and
# targetQuery without a transitive search, but hey, this
# should be the result.
rels = self._relTools['intersection'](
rels, self._relData(targetQuery))
if not rels:
return data['Set']()
elif len(rels) == 1:
res = self._reltoken_name_TO_objtokenset.get(
(rels.maxKey(), name))
if res is None:
res = self._attrs[name]['Set']()
return res
else:
return multiunion(
(self._reltoken_name_TO_objtokenset.get((r, name))
for r in rels), data)
if not ignoreSearchIndex and self._searchIndexMatches is not None:
if RELATION in query:
relation_query = True
query_names = tuple(nm for nm in query if nm is not RELATION)
else:
relation_query = False
query_names = tuple(query)
if not targetQuery and targetFilter is None:
key = (False, name, relation_query, query_names, maxDepth or 0)
for (c_filter,
c_queryFactory,
c_static_values,
ix) in self._searchIndexMatches.get(key, ()):
if (c_filter != filter or
c_queryFactory != queryFactory):
continue
for k, v in c_static_values:
if query[k] != v:
continue
res = ix.getResults(
name, query, maxDepth, filter, queryFactory)
if res is not None:
return res
key = (True, '', relation_query, query_names, maxDepth or 0)
res = self._getSearchIndexResults(
key, query, maxDepth, filter, targetQuery, targetFilter,
queryFactory)
if res is not None:
return multiunion(
(self._reltoken_name_TO_objtokenset.get((r, name))
for r in res),
self._attrs[name])
if getQueries is None:
queryFactory, getQueries = self._getQueryFactory(
query, queryFactory)
return self._yieldValueTokens(
name, *self._parse( # query and targetQuery normalized above
query, maxDepth, filter, targetQuery, targetFilter,
getQueries))
def findValues(self, name, query=(), maxDepth=None, filter=None,
targetQuery=(), targetFilter=None,
queryFactory=None, ignoreSearchIndex=False):
res = self.findValueTokens(name, query, maxDepth, filter,
targetQuery, targetFilter,
queryFactory, ignoreSearchIndex)
resolve = self._attrs[name]['load']
if resolve is None:
return res
else:
cache = {}
return (resolve(t, self, cache) for t in res)
def _yieldValueTokens(
self, name, query, relData, maxDepth, checkFilter,
checkTargetFilter, getQueries, yieldSets=False):
# this is really an internal bit of findValueTokens, and is only
# used there.
relSeen = set()
objSeen = set()
for path in self.yieldRelationTokenChains(
query, relData, maxDepth, checkFilter, checkTargetFilter,
getQueries, findCycles=False):
relToken = path[-1]
if relToken not in relSeen:
relSeen.add(relToken)
outputSet = self._reltoken_name_TO_objtokenset.get(
(relToken, name))
if outputSet:
if yieldSets: # this is needed for zc.relationship!!!
yield outputSet
else:
for token in outputSet:
if token not in objSeen:
yield token
objSeen.add(token)
def findRelationTokens(self, query=(), maxDepth=None, filter=None,
targetQuery=(), targetFilter=None,
queryFactory=None, ignoreSearchIndex=False):
query = BTrees.family32.OO.Bucket(query) # sorts on key
getQueries = None
if queryFactory is None:
queryFactory, getQueries = self._getQueryFactory(
query, queryFactory)
targetQuery = BTrees.family32.OO.Bucket(targetQuery)
if (((maxDepth is None and queryFactory is None)
or maxDepth == 1)
and filter is None
and not targetQuery
and targetFilter is None):
res = self._relData(query)
if res is None:
res = self._relTools['Set']()
return res
if not ignoreSearchIndex and self._searchIndexMatches is not None:
if RELATION in query:
relation_query = True
query_names = tuple(nm for nm in query if nm is not None)
else:
relation_query = False
query_names = tuple(query)
key = (True, '', relation_query, query_names, maxDepth or 0)
res = self._getSearchIndexResults(
key, query, maxDepth, filter, targetQuery, targetFilter,
queryFactory)
if res is not None:
return res
if getQueries is None:
queryFactory, getQueries = self._getQueryFactory(
query, queryFactory)
seen = self._relTools['Set']()
return (res[-1]
for res in self.yieldRelationTokenChains(
*self._parse(
query, maxDepth, filter, targetQuery,
targetFilter, getQueries) +
(False,))
if seen.insert(res[-1]))
def findRelations(self, query=(), maxDepth=None, filter=None,
targetQuery=(), targetFilter=None,
queryFactory=None, ignoreSearchIndex=False):
return self.resolveRelationTokens(
self.findRelationTokens(
query, maxDepth, filter, targetQuery, targetFilter,
queryFactory, ignoreSearchIndex))
def findRelationChains(self, query, maxDepth=None, filter=None,
targetQuery=(), targetFilter=None,
queryFactory=None):
query = BTrees.family32.OO.Bucket(query) # sorts on key
queryFactory, getQueries = self._getQueryFactory(
query, queryFactory)
return self._yieldRelationChains(*self._parse(
query, maxDepth, filter, BTrees.family32.OO.Bucket(targetQuery),
targetFilter, getQueries))
def _yieldRelationChains(self, query, relData, maxDepth, checkFilter,
checkTargetFilter, getQueries, findCycles=True):
# this is really an internal bit of findRelationChains, and is only
# used there.
resolve = self._relTools['load']
cache = {}
for p in self.yieldRelationTokenChains(
query, relData, maxDepth, checkFilter, checkTargetFilter,
getQueries, findCycles):
t = (resolve(t, self, cache) for t in p)
if interfaces.ICircularRelationPath.providedBy(p):
res = CircularRelationPath(t, p.cycled)
else:
res = tuple(t)
yield res
def findRelationTokenChains(self, query, maxDepth=None, filter=None,
targetQuery=(), targetFilter=None,
queryFactory=None):
query = BTrees.family32.OO.Bucket(query) # sorts on key
queryFactory, getQueries = self._getQueryFactory(
query, queryFactory)
return self.yieldRelationTokenChains(*self._parse(
query, maxDepth, filter, BTrees.family32.OO.Bucket(targetQuery),
targetFilter, getQueries))
def canFind(self, query, maxDepth=None, filter=None,
targetQuery=(), targetFilter=None,
queryFactory=None, ignoreSearchIndex=False):
query = BTrees.family32.OO.Bucket(query) # sorts on key
getQueries = None
if queryFactory is None:
queryFactory, getQueries = self._getQueryFactory(
query, queryFactory)
targetQuery = BTrees.family32.OO.Bucket(targetQuery)
if not ignoreSearchIndex and self._searchIndexMatches is not None:
if RELATION in query:
relation_query = True
query_names = tuple(nm for nm in query if nm is not None)
else:
relation_query = False
query_names = tuple(query)
key = (True, '', relation_query, query_names, maxDepth or 0)
res = self._getSearchIndexResults(
key, query, maxDepth, filter, targetQuery, targetFilter,
queryFactory)
if res is not None:
return bool(res)
if getQueries is None:
queryFactory, getQueries = self._getQueryFactory(
query, queryFactory)
_ = next(self.yieldRelationTokenChains(
*self._parse(
query, maxDepth, filter, targetQuery,
targetFilter, getQueries) +
(False,)), _marker)
if _ is _marker:
return False
else:
return True | zc.relation | /zc.relation-2.0.tar.gz/zc.relation-2.0/src/zc/relation/catalog.py | catalog.py |
import BTrees
import persistent
import zope.interface
import zc.relation.catalog
import zc.relation.interfaces
##############################################################################
# a common case transitive queries factory
_marker = object()
@zope.interface.implementer(zc.relation.interfaces.IQueryFactory)
class TransposingTransitive(persistent.Persistent):
def __init__(self, name1, name2, static=()):
self.names = [name1, name2] # a list so we can use index
if getattr(static, 'items', None) is not None:
static = static.items()
self.static = tuple(sorted(static))
def __call__(self, query, catalog):
# check static values, if any. we want to be permissive here. (as
# opposed to finding searchindexes in the catalog's
# _getSearchIndexResults method)
for k, v in self.static:
if k in query:
if isinstance(v, zc.relation.catalog.Any):
if isinstance(query[k], zc.relation.catalog.Any):
if query[k].source.issubset(v.source):
continue
elif query[k] in v:
continue
elif v == query[k]:
continue
return None
static = []
name = other = _marker
for nm, val in query.items():
try:
ix = self.names.index(nm)
except ValueError:
static.append((nm, val))
else:
if name is not _marker:
# both were specified: no transitive search known.
return None
else:
name = nm
other = self.names[not ix]
if name is not _marker:
def getQueries(relchain):
if not relchain:
yield query
return
if other is None:
rels = relchain[-1]
else:
tokens = catalog.getValueTokens(other, relchain[-1])
if not tokens:
return
rels = zc.relation.catalog.Any(tokens)
res = BTrees.family32.OO.Bucket(static)
res[name] = rels
yield res
return getQueries
def __eq__(self, other):
return (isinstance(other, self.__class__) and
set(self.names) == set(other.names)
and self.static == other.static)
def __ne__(self, other):
return not self.__eq__(other) | zc.relation | /zc.relation-2.0.tar.gz/zc.relation-2.0/src/zc/relation/queryfactory.py | queryfactory.py |
======================================================
Tokens and Joins: zc.relation Catalog Extended Example
======================================================
Introduction and Set Up
=======================
This document assumes you have read the introductory README.rst and want
to learn a bit more by example. In it, we will explore a more
complicated set of relations that demonstrates most of the aspects of
working with tokens. In particular, we will look at joins, which will
also give us a chance to look more in depth at query factories and
search indexes, and introduce the idea of listeners. It will not explain
the basics that the README already addressed.
Imagine we are indexing security assertions in a system. In this
system, users may have roles within an organization. Each organization
may have multiple child organizations and may have a single parent
organization. A user with a role in a parent organization will have the
same role in all transitively connected child relations.
We have two kinds of relations, then. One kind of relation will model
the hierarchy of organizations. We'll do it with an intrinsic relation
of organizations to their children: that reflects the fact that parent
organizations choose and are comprised of their children; children do
not choose their parents.
The other relation will model the (multiple) roles a (single) user has
in a (single) organization. This relation will be entirely extrinsic.
We could create two catalogs, one for each type. Or we could put them
both in the same catalog. Initially, we'll go with the single-catalog
approach for our examples. This single catalog, then, will be indexing
a heterogeneous collection of relations.
Let's define the two relations with interfaces. We'll include one
accessor, getOrganization, largely to show how to handle methods.
>>> import zope.interface
>>> class IOrganization(zope.interface.Interface):
... title = zope.interface.Attribute('the title')
... parts = zope.interface.Attribute(
... 'the organizations that make up this one')
...
>>> class IRoles(zope.interface.Interface):
... def getOrganization():
... 'return the organization in which this relation operates'
... principal_id = zope.interface.Attribute(
... 'the pricipal id whose roles this relation lists')
... role_ids = zope.interface.Attribute(
... 'the role ids that the principal explicitly has in the '
... 'organization. The principal may have other roles via '
... 'roles in parent organizations.')
...
Now we can create some classes. In the README example, the setup was a bit
of a toy. This time we will be just a bit more practical. We'll also expect
to be operating within the ZODB, with a root and transactions. [#ZODB]_
.. [#ZODB] Here we will set up a ZODB instance for us to use.
>>> from ZODB.tests.util import DB
>>> db = DB()
>>> conn = db.open()
>>> root = conn.root()
Here's how we will dump and load our relations: use a "registry"
object, similar to an intid utility. [#faux_intid]_
.. [#faux_intid] Here's a simple persistent keyreference. Notice that it is
not persistent itself: this is important for conflict resolution to be
able to work (which we don't show here, but we're trying to lean more
towards real usage for this example).
>>> from functools import total_ordering
>>> @total_ordering
... class Reference(object): # see zope.app.keyreference
... def __init__(self, obj):
... self.object = obj
... def _get_sorting_key(self):
... # this doesn't work during conflict resolution. See
... # zope.app.keyreference.persistent, 3.5 release, for current
... # best practice.
... if self.object._p_jar is None:
... raise ValueError(
... 'can only compare when both objects have connections')
... return self.object._p_oid or ''
... def __lt__(self, other):
... # this doesn't work during conflict resolution. See
... # zope.app.keyreference.persistent, 3.5 release, for current
... # best practice.
... if not isinstance(other, Reference):
... raise ValueError('can only compare with Reference objects')
... return self._get_sorting_key() < other._get_sorting_key()
... def __eq__(self, other):
... # this doesn't work during conflict resolution. See
... # zope.app.keyreference.persistent, 3.5 release, for current
... # best practice.
... if not isinstance(other, Reference):
... raise ValueError('can only compare with Reference objects')
... return self._get_sorting_key() == other._get_sorting_key()
Here's a simple integer identifier tool.
>>> import persistent
>>> import BTrees
>>> class Registry(persistent.Persistent): # see zope.app.intid
... def __init__(self, family=BTrees.family32):
... self.family = family
... self.ids = self.family.IO.BTree()
... self.refs = self.family.OI.BTree()
... def getId(self, obj):
... if not isinstance(obj, persistent.Persistent):
... raise ValueError('not a persistent object', obj)
... if obj._p_jar is None:
... self._p_jar.add(obj)
... ref = Reference(obj)
... id = self.refs.get(ref)
... if id is None:
... # naive for conflict resolution; see zope.app.intid
... if self.ids:
... id = self.ids.maxKey() + 1
... else:
... id = self.family.minint
... self.ids[id] = ref
... self.refs[ref] = id
... return id
... def __contains__(self, obj):
... if (not isinstance(obj, persistent.Persistent) or
... obj._p_oid is None):
... return False
... return Reference(obj) in self.refs
... def getObject(self, id, default=None):
... res = self.ids.get(id, None)
... if res is None:
... return default
... else:
... return res.object
... def remove(self, r):
... if isinstance(r, int):
... self.refs.pop(self.ids.pop(r))
... elif (not isinstance(r, persistent.Persistent) or
... r._p_oid is None):
... raise LookupError(r)
... else:
... self.ids.pop(self.refs.pop(Reference(r)))
...
>>> registry = root['registry'] = Registry()
>>> import transaction
>>> transaction.commit()
In this implementation of the "dump" method, we use the cache just to
show you how you might use it. It probably is overkill for this job,
and maybe even a speed loss, but you can see the idea.
>>> def dump(obj, catalog, cache):
... reg = cache.get('registry')
... if reg is None:
... reg = cache['registry'] = catalog._p_jar.root()['registry']
... return reg.getId(obj)
...
>>> def load(token, catalog, cache):
... reg = cache.get('registry')
... if reg is None:
... reg = cache['registry'] = catalog._p_jar.root()['registry']
... return reg.getObject(token)
...
Now we can create a relation catalog to hold these items.
>>> import zc.relation.catalog
>>> catalog = root['catalog'] = zc.relation.catalog.Catalog(dump, load)
>>> transaction.commit()
Now we set up our indexes. We'll start with just the organizations, and
set up the catalog with them. This part will be similar to the example
in README.rst, but will introduce more discussions of optimizations and
tokens. Then we'll add in the part about roles, and explore queries and
token-based "joins".
Organizations
=============
The organization will hold a set of organizations. This is actually not
inherently easy in the ZODB because this means that we need to compare
or hash persistent objects, which does not work reliably over time and
across machines out-of-the-box. To side-step the issue for this example,
and still do something a bit interesting and real-world, we'll use the
registry tokens introduced above. This will also give us a chance to
talk a bit more about optimizations and tokens. (If you would like
to sanely and transparently hold a set of persistent objects, try the
zc.set package XXX not yet.)
>>> import BTrees
>>> import persistent
>>> @zope.interface.implementer(IOrganization)
... @total_ordering
... class Organization(persistent.Persistent):
...
... def __init__(self, title):
... self.title = title
... self.parts = BTrees.family32.IF.TreeSet()
... # the next parts just make the tests prettier
... def __repr__(self):
... return '<Organization instance "' + self.title + '">'
... def __lt__(self, other):
... # pukes if other doesn't have name
... return self.title < other.title
... def __eq__(self, other):
... return self is other
... def __hash__(self):
... return 1 # dummy
...
OK, now we know how organizations will work. Now we can add the `parts`
index to the catalog. This will do a few new things from how we added
indexes in the README.
>>> catalog.addValueIndex(IOrganization['parts'], multiple=True,
... name="part")
So, what's different from the README examples?
First, we are using an interface element to define the value to be indexed.
It provides an interface to which objects will be adapted, a default name
for the index, and information as to whether the attribute should be used
directly or called.
Second, we are not specifying a dump or load. They are None. This
means that the indexed value can already be treated as a token. This
can allow a very significant optimization for reindexing if the indexed
value is a large collection using the same BTree family as the
index--which leads us to the next difference.
Third, we are specifying that `multiple=True`. This means that the value
on a given relation that provides or can be adapted to IOrganization will
have a collection of `parts`. These will always be regarded as a set,
whether the actual colection is a BTrees set or the keys of a BTree.
Last, we are specifying a name to be used for queries. I find that queries
read more easily when the query keys are singular, so I often rename plurals.
As in the README, We can add another simple transposing transitive query
factory, switching between 'part' and `None`.
>>> import zc.relation.queryfactory
>>> factory1 = zc.relation.queryfactory.TransposingTransitive(
... 'part', None)
>>> catalog.addDefaultQueryFactory(factory1)
Let's add a couple of search indexes in too, of the hierarchy looking up...
>>> import zc.relation.searchindex
>>> catalog.addSearchIndex(
... zc.relation.searchindex.TransposingTransitiveMembership(
... 'part', None))
...and down.
>>> catalog.addSearchIndex(
... zc.relation.searchindex.TransposingTransitiveMembership(
... None, 'part'))
PLEASE NOTE: the search index looking up is not a good idea practically. The
index is designed for looking down [#verifyObjectTransitive]_.
.. [#verifyObjectTransitive] The TransposingTransitiveMembership indexes
provide ISearchIndex.
>>> from zope.interface.verify import verifyObject
>>> import zc.relation.interfaces
>>> index = list(catalog.iterSearchIndexes())[0]
>>> verifyObject(zc.relation.interfaces.ISearchIndex, index)
True
Let's create and add a few organizations.
We'll make a structure like this [#silliness]_::
Ynod Corp Mangement Zookd Corp Management
/ | \ / | \
Ynod Devs Ynod SAs Ynod Admins Zookd Admins Zookd SAs Zookd Devs
/ \ \ / / \
Y3L4 Proj Bet Proj Ynod Zookd Task Force Zookd hOgnmd Zookd Nbd
Here's the Python.
>>> orgs = root['organizations'] = BTrees.family32.OO.BTree()
>>> for nm, parts in (
... ('Y3L4 Proj', ()),
... ('Bet Proj', ()),
... ('Ynod Zookd Task Force', ()),
... ('Zookd hOgnmd', ()),
... ('Zookd Nbd', ()),
... ('Ynod Devs', ('Y3L4 Proj', 'Bet Proj')),
... ('Ynod SAs', ()),
... ('Ynod Admins', ('Ynod Zookd Task Force',)),
... ('Zookd Admins', ('Ynod Zookd Task Force',)),
... ('Zookd SAs', ()),
... ('Zookd Devs', ('Zookd hOgnmd', 'Zookd Nbd')),
... ('Ynod Corp Management', ('Ynod Devs', 'Ynod SAs', 'Ynod Admins')),
... ('Zookd Corp Management', ('Zookd Devs', 'Zookd SAs',
... 'Zookd Admins'))):
... org = Organization(nm)
... for part in parts:
... ignore = org.parts.insert(registry.getId(orgs[part]))
... orgs[nm] = org
... catalog.index(org)
...
Now the catalog knows about the relations.
>>> len(catalog)
13
>>> root['dummy'] = Organization('Foo')
>>> root['dummy'] in catalog
False
>>> orgs['Y3L4 Proj'] in catalog
True
Also, now we can search. To do this, we can use some of the token methods that
the catalog provides. The most commonly used is `tokenizeQuery`. It takes a
query with values that are not tokenized and converts them to values that are
tokenized.
>>> Ynod_SAs_id = registry.getId(orgs['Ynod SAs'])
>>> catalog.tokenizeQuery({None: orgs['Ynod SAs']}) == {
... None: Ynod_SAs_id}
True
>>> Zookd_SAs_id = registry.getId(orgs['Zookd SAs'])
>>> Zookd_Devs_id = registry.getId(orgs['Zookd Devs'])
>>> catalog.tokenizeQuery(
... {None: zc.relation.catalog.any(
... orgs['Zookd SAs'], orgs['Zookd Devs'])}) == {
... None: zc.relation.catalog.any(Zookd_SAs_id, Zookd_Devs_id)}
True
Of course, right now doing this with 'part' alone is kind of silly, since it
does not change within the relation catalog (because we said that dump and
load were `None`, as discussed above).
>>> catalog.tokenizeQuery({'part': Ynod_SAs_id}) == {
... 'part': Ynod_SAs_id}
True
>>> catalog.tokenizeQuery(
... {'part': zc.relation.catalog.any(Zookd_SAs_id, Zookd_Devs_id)}
... ) == {'part': zc.relation.catalog.any(Zookd_SAs_id, Zookd_Devs_id)}
True
The `tokenizeQuery` method is so common that we're going to assign it to
a variable in our example. Then we'll do a search or two.
So...find the relations that Ynod Devs supervise.
>>> t = catalog.tokenizeQuery
>>> res = list(catalog.findRelationTokens(t({None: orgs['Ynod Devs']})))
OK...we used `findRelationTokens`, as opposed to `findRelations`, so res
is a couple of numbers now. How do we convert them back?
`resolveRelationTokens` will do the trick.
>>> len(res)
3
>>> sorted(catalog.resolveRelationTokens(res))
... # doctest: +NORMALIZE_WHITESPACE
[<Organization instance "Bet Proj">, <Organization instance "Y3L4 Proj">,
<Organization instance "Ynod Devs">]
`resolveQuery` is the mirror image of `tokenizeQuery`: it converts
tokenized queries to queries with "loaded" values.
>>> original = {'part': zc.relation.catalog.any(
... Zookd_SAs_id, Zookd_Devs_id),
... None: orgs['Zookd Devs']}
>>> tokenized = catalog.tokenizeQuery(original)
>>> original == catalog.resolveQuery(tokenized)
True
>>> original = {None: zc.relation.catalog.any(
... orgs['Zookd SAs'], orgs['Zookd Devs']),
... 'part': Zookd_Devs_id}
>>> tokenized = catalog.tokenizeQuery(original)
>>> original == catalog.resolveQuery(tokenized)
True
Likewise, `tokenizeRelations` is the mirror image of `resolveRelationTokens`.
>>> sorted(catalog.tokenizeRelations(
... [orgs["Bet Proj"], orgs["Y3L4 Proj"]])) == sorted(
... registry.getId(o) for o in
... [orgs["Bet Proj"], orgs["Y3L4 Proj"]])
True
The other token-related methods are as follows
[#show_remaining_token_methods]_:
.. [#show_remaining_token_methods] For what it's worth, here are some small
examples of the remaining token-related methods.
These two are the singular versions of `tokenizeRelations` and
`resolveRelationTokens`.
`tokenizeRelation` returns a token for the given relation.
>>> catalog.tokenizeRelation(orgs['Zookd Corp Management']) == (
... registry.getId(orgs['Zookd Corp Management']))
True
`resolveRelationToken` returns a relation for the given token.
>>> catalog.resolveRelationToken(registry.getId(
... orgs['Zookd Corp Management'])) is orgs['Zookd Corp Management']
True
The "values" ones are a bit lame to show now, since the only value
we have right now is not tokenized but used straight up. But here
goes, showing some fascinating no-ops.
`tokenizeValues`, returns an iterable of tokens for the values of
the given index name.
>>> list(catalog.tokenizeValues((1,2,3), 'part'))
[1, 2, 3]
`resolveValueTokens` returns an iterable of values for the tokens of
the given index name.
>>> list(catalog.resolveValueTokens((1,2,3), 'part'))
[1, 2, 3]
- `tokenizeValues`, which returns an iterable of tokens for the values
of the given index name;
- `resolveValueTokens`, which returns an iterable of values for the tokens of
the given index name;
- `tokenizeRelation`, which returns a token for the given relation; and
- `resolveRelationToken`, which returns a relation for the given token.
Why do we bother with these tokens, instead of hiding them away and
making the API prettier? By exposing them, we enable efficient joining,
and efficient use in other contexts. For instance, if you use the same
intid utility to tokenize in other catalogs, our results can be merged
with the results of other catalogs. Similarly, you can use the results
of queries to other catalogs--or even "joins" from earlier results of
querying this catalog--as query values here. We'll explore this in the
next section.
Roles
=====
We have set up the Organization relations. Now let's set up the roles, and
actually be able to answer the questions that we described at the beginning
of the document.
In our Roles object, roles and principals will simply be strings--ids, if
this were a real system. The organization will be a direct object reference.
>>> @zope.interface.implementer(IRoles)
... @total_ordering
... class Roles(persistent.Persistent):
...
... def __init__(self, principal_id, role_ids, organization):
... self.principal_id = principal_id
... self.role_ids = BTrees.family32.OI.TreeSet(role_ids)
... self._organization = organization
... def getOrganization(self):
... return self._organization
... # the rest is for prettier/easier tests
... def __repr__(self):
... return "<Roles instance (%s has %s in %s)>" % (
... self.principal_id, ', '.join(self.role_ids),
... self._organization.title)
... def __lt__(self, other):
... _self = (
... self.principal_id,
... tuple(self.role_ids),
... self._organization.title,
... )
... _other = (
... other.principal_id,
... tuple(other.role_ids),
... other._organization.title,
... )
... return _self <_other
... def __eq__(self, other):
... return self is other
... def __hash__(self):
... return 1 # dummy
...
Now let's add add the value indexes to the relation catalog.
>>> catalog.addValueIndex(IRoles['principal_id'], btree=BTrees.family32.OI)
>>> catalog.addValueIndex(IRoles['role_ids'], btree=BTrees.family32.OI,
... multiple=True, name='role_id')
>>> catalog.addValueIndex(IRoles['getOrganization'], dump, load,
... name='organization')
Those are some slightly new variations of what we've seen in `addValueIndex`
before, but all mixing and matching on the same ingredients.
As a reminder, here is our organization structure::
Ynod Corp Mangement Zookd Corp Management
/ | \ / | \
Ynod Devs Ynod SAs Ynod Admins Zookd Admins Zookd SAs Zookd Devs
/ \ \ / / \
Y3L4 Proj Bet Proj Ynod Zookd Task Force Zookd hOgnmd Zookd Nbd
Now let's create and add some roles.
>>> principal_ids = [
... 'abe', 'bran', 'cathy', 'david', 'edgar', 'frank', 'gertrude',
... 'harriet', 'ignas', 'jacob', 'karyn', 'lettie', 'molly', 'nancy',
... 'ophelia', 'pat']
>>> role_ids = ['user manager', 'writer', 'reviewer', 'publisher']
>>> get_role = dict((v[0], v) for v in role_ids).__getitem__
>>> roles = root['roles'] = BTrees.family32.IO.BTree()
>>> next = 0
>>> for prin, org, role_ids in (
... ('abe', orgs['Zookd Corp Management'], 'uwrp'),
... ('bran', orgs['Ynod Corp Management'], 'uwrp'),
... ('cathy', orgs['Ynod Devs'], 'w'),
... ('cathy', orgs['Y3L4 Proj'], 'r'),
... ('david', orgs['Bet Proj'], 'wrp'),
... ('edgar', orgs['Ynod Devs'], 'up'),
... ('frank', orgs['Ynod SAs'], 'uwrp'),
... ('frank', orgs['Ynod Admins'], 'w'),
... ('gertrude', orgs['Ynod Zookd Task Force'], 'uwrp'),
... ('harriet', orgs['Ynod Zookd Task Force'], 'w'),
... ('harriet', orgs['Ynod Admins'], 'r'),
... ('ignas', orgs['Zookd Admins'], 'r'),
... ('ignas', orgs['Zookd Corp Management'], 'w'),
... ('karyn', orgs['Zookd Corp Management'], 'uwrp'),
... ('karyn', orgs['Ynod Corp Management'], 'uwrp'),
... ('lettie', orgs['Zookd Corp Management'], 'u'),
... ('lettie', orgs['Ynod Zookd Task Force'], 'w'),
... ('lettie', orgs['Zookd SAs'], 'w'),
... ('molly', orgs['Zookd SAs'], 'uwrp'),
... ('nancy', orgs['Zookd Devs'], 'wrp'),
... ('nancy', orgs['Zookd hOgnmd'], 'u'),
... ('ophelia', orgs['Zookd Corp Management'], 'w'),
... ('ophelia', orgs['Zookd Devs'], 'r'),
... ('ophelia', orgs['Zookd Nbd'], 'p'),
... ('pat', orgs['Zookd Nbd'], 'wrp')):
... assert prin in principal_ids
... role_ids = [get_role(l) for l in role_ids]
... role = roles[next] = Roles(prin, role_ids, org)
... role.key = next
... next += 1
... catalog.index(role)
...
Now we can begin to do searches [#real_value_tokens]_.
.. [#real_value_tokens] We can also show the values token methods more
sanely now.
>>> original = sorted((orgs['Zookd Devs'], orgs['Ynod SAs']))
>>> tokens = list(catalog.tokenizeValues(original, 'organization'))
>>> original == sorted(catalog.resolveValueTokens(tokens, 'organization'))
True
What are all the role settings for ophelia?
>>> sorted(catalog.findRelations({'principal_id': 'ophelia'}))
... # doctest: +NORMALIZE_WHITESPACE
[<Roles instance (ophelia has publisher in Zookd Nbd)>,
<Roles instance (ophelia has reviewer in Zookd Devs)>,
<Roles instance (ophelia has writer in Zookd Corp Management)>]
That answer does not need to be transitive: we're done.
Next question. Where does ophelia have the 'writer' role?
>>> list(catalog.findValues(
... 'organization', {'principal_id': 'ophelia',
... 'role_id': 'writer'}))
[<Organization instance "Zookd Corp Management">]
Well, that's correct intransitively. Do we need a transitive queries
factory? No! This is a great chance to look at the token join we talked
about in the previous section. This should actually be a two-step
operation: find all of the organizations in which ophelia has writer,
and then find all of the transitive parts to that organization.
>>> sorted(catalog.findRelations({None: zc.relation.catalog.Any(
... catalog.findValueTokens('organization',
... {'principal_id': 'ophelia',
... 'role_id': 'writer'}))}))
... # doctest: +NORMALIZE_WHITESPACE
[<Organization instance "Ynod Zookd Task Force">,
<Organization instance "Zookd Admins">,
<Organization instance "Zookd Corp Management">,
<Organization instance "Zookd Devs">,
<Organization instance "Zookd Nbd">,
<Organization instance "Zookd SAs">,
<Organization instance "Zookd hOgnmd">]
That's more like it.
Next question. What users have roles in the 'Zookd Devs' organization?
Intransitively, that's pretty easy.
>>> sorted(catalog.findValueTokens(
... 'principal_id', t({'organization': orgs['Zookd Devs']})))
['nancy', 'ophelia']
Transitively, we should do another join.
>>> org_id = registry.getId(orgs['Zookd Devs'])
>>> sorted(catalog.findValueTokens(
... 'principal_id', {
... 'organization': zc.relation.catalog.any(
... org_id, *catalog.findRelationTokens({'part': org_id}))}))
['abe', 'ignas', 'karyn', 'lettie', 'nancy', 'ophelia']
That's a little awkward, but it does the trick.
Last question, and the kind of question that started the entire example.
What roles does ophelia have in the "Zookd Nbd" organization?
>>> list(catalog.findValueTokens(
... 'role_id', t({'organization': orgs['Zookd Nbd'],
... 'principal_id': 'ophelia'})))
['publisher']
Intransitively, that's correct. But, transitively, ophelia also has
reviewer and writer, and that's the answer we want to be able to get quickly.
We could ask the question a different way, then, again leveraging a join.
We'll set it up as a function, because we will want to use it a little later
without repeating the code.
>>> def getRolesInOrganization(principal_id, org):
... org_id = registry.getId(org)
... return sorted(catalog.findValueTokens(
... 'role_id', {
... 'organization': zc.relation.catalog.any(
... org_id,
... *catalog.findRelationTokens({'part': org_id})),
... 'principal_id': principal_id}))
...
>>> getRolesInOrganization('ophelia', orgs['Zookd Nbd'])
['publisher', 'reviewer', 'writer']
As you can see, then, working with tokens makes interesting joins possible,
as long as the tokens are the same across the two queries.
We have examined tokens methods and token techniques like joins. The example
story we have told can let us get into a few more advanced topics, such as
query factory joins and search indexes that can increase their read speed.
Query Factory Joins
===================
We can build a query factory that makes the join automatic. A query
factory is a callable that takes two arguments: a query (the one that
starts the search) and the catalog. The factory either returns None,
indicating that the query factory cannot be used for this query, or it
returns another callable that takes a chain of relations. The last
token in the relation chain is the most recent. The output of this
inner callable is expected to be an iterable of
BTrees.family32.OO.Bucket queries to search further from the given chain
of relations.
Here's a flawed approach to this problem.
>>> def flawed_factory(query, catalog):
... if (len(query) == 2 and
... 'organization' in query and
... 'principal_id' in query):
... def getQueries(relchain):
... if not relchain:
... yield query
... return
... current = catalog.getValueTokens(
... 'organization', relchain[-1])
... if current:
... organizations = catalog.getRelationTokens(
... {'part': zc.relation.catalog.Any(current)})
... if organizations:
... res = BTrees.family32.OO.Bucket(query)
... res['organization'] = zc.relation.catalog.Any(
... organizations)
... yield res
... return getQueries
...
That works for our current example.
>>> sorted(catalog.findValueTokens(
... 'role_id', t({'organization': orgs['Zookd Nbd'],
... 'principal_id': 'ophelia'}),
... queryFactory=flawed_factory))
['publisher', 'reviewer', 'writer']
However, it won't work for other similar queries.
>>> getRolesInOrganization('abe', orgs['Zookd Nbd'])
['publisher', 'reviewer', 'user manager', 'writer']
>>> sorted(catalog.findValueTokens(
... 'role_id', t({'organization': orgs['Zookd Nbd'],
... 'principal_id': 'abe'}),
... queryFactory=flawed_factory))
[]
oops.
The flawed_factory is actually a useful pattern for more typical relation
traversal. It goes from relation to relation to relation, and ophelia has
connected relations all the way to the top. However, abe only has them at
the top, so nothing is traversed.
Instead, we can make a query factory that modifies the initial query.
>>> def factory2(query, catalog):
... if (len(query) == 2 and
... 'organization' in query and
... 'principal_id' in query):
... def getQueries(relchain):
... if not relchain:
... res = BTrees.family32.OO.Bucket(query)
... org_id = query['organization']
... if org_id is not None:
... res['organization'] = zc.relation.catalog.any(
... org_id,
... *catalog.findRelationTokens({'part': org_id}))
... yield res
... return getQueries
...
>>> sorted(catalog.findValueTokens(
... 'role_id', t({'organization': orgs['Zookd Nbd'],
... 'principal_id': 'ophelia'}),
... queryFactory=factory2))
['publisher', 'reviewer', 'writer']
>>> sorted(catalog.findValueTokens(
... 'role_id', t({'organization': orgs['Zookd Nbd'],
... 'principal_id': 'abe'}),
... queryFactory=factory2))
['publisher', 'reviewer', 'user manager', 'writer']
A difference between this and the other approach is that it is essentially
intransitive: this query factory modifies the initial query, and then does
not give further queries. The catalog currently always stops calling the
query factory if the queries do not return any results, so an approach like
the flawed_factory simply won't work for this kind of problem.
We could add this query factory as another default.
>>> catalog.addDefaultQueryFactory(factory2)
>>> sorted(catalog.findValueTokens(
... 'role_id', t({'organization': orgs['Zookd Nbd'],
... 'principal_id': 'ophelia'})))
['publisher', 'reviewer', 'writer']
>>> sorted(catalog.findValueTokens(
... 'role_id', t({'organization': orgs['Zookd Nbd'],
... 'principal_id': 'abe'})))
['publisher', 'reviewer', 'user manager', 'writer']
The previously installed query factory is still available.
>>> list(catalog.iterDefaultQueryFactories()) == [factory1, factory2]
True
>>> list(catalog.findRelations(
... {'part': registry.getId(orgs['Y3L4 Proj'])}))
... # doctest: +NORMALIZE_WHITESPACE
[<Organization instance "Ynod Devs">,
<Organization instance "Ynod Corp Management">]
>>> sorted(catalog.findRelations(
... {None: registry.getId(orgs['Ynod Corp Management'])}))
... # doctest: +NORMALIZE_WHITESPACE
[<Organization instance "Bet Proj">, <Organization instance "Y3L4 Proj">,
<Organization instance "Ynod Admins">,
<Organization instance "Ynod Corp Management">,
<Organization instance "Ynod Devs">, <Organization instance "Ynod SAs">,
<Organization instance "Ynod Zookd Task Force">]
Search Index for Query Factory Joins
====================================
Now that we have written a query factory that encapsulates the join, we can
use a search index that speeds it up. We've only used transitive search
indexes so far. Now we will add an intransitive search index.
The intransitive search index generally just needs the search value
names it should be indexing, optionally the result name (defaulting to
relations), and optionally the query factory to be used.
We need to use two additional options because of the odd join trick we're
doing. We need to specify what organization and principal_id values need
to be changed when an object is indexed, and we need to indicate that we
should update when organization, principal_id, *or* parts changes.
`getValueTokens` specifies the values that need to be indexed. It gets
the index, the name for the tokens desired, the token, the catalog that
generated the token change (it may not be the same as the index's
catalog, the source dictionary that contains a dictionary of the values
that will be used for tokens if you do not override them, a dict of the
added values for this token (keys are value names), a dict of the
removed values for this token, and whether the token has been removed.
The method can return None, which will leave the index to its default
behavior that should work if no query factory is used; or an iterable of
values.
>>> def getValueTokens(index, name, token, catalog, source,
... additions, removals, removed):
... if name == 'organization':
... orgs = source.get('organization')
... if not removed or not orgs:
... orgs = index.catalog.getValueTokens(
... 'organization', token)
... if not orgs:
... orgs = [token]
... orgs.extend(removals.get('part', ()))
... orgs = set(orgs)
... orgs.update(index.catalog.findValueTokens(
... 'part',
... {None: zc.relation.catalog.Any(
... t for t in orgs if t is not None)}))
... return orgs
... elif name == 'principal_id':
... # we only want custom behavior if this is an organization
... if 'principal_id' in source or index.catalog.getValueTokens(
... 'principal_id', token):
... return ''
... orgs = set((token,))
... orgs.update(index.catalog.findRelationTokens(
... {'part': token}))
... return set(index.catalog.findValueTokens(
... 'principal_id', {
... 'organization': zc.relation.catalog.Any(orgs)}))
...
>>> index = zc.relation.searchindex.Intransitive(
... ('organization', 'principal_id'), 'role_id', factory2,
... getValueTokens,
... ('organization', 'principal_id', 'part', 'role_id'),
... unlimitedDepth=True)
>>> catalog.addSearchIndex(index)
>>> res = catalog.findValueTokens(
... 'role_id', t({'organization': orgs['Zookd Nbd'],
... 'principal_id': 'ophelia'}))
>>> list(res)
['publisher', 'reviewer', 'writer']
>>> list(res)
['publisher', 'reviewer', 'writer']
>>> res = catalog.findValueTokens(
... 'role_id', t({'organization': orgs['Zookd Nbd'],
... 'principal_id': 'abe'}))
>>> list(res)
['publisher', 'reviewer', 'user manager', 'writer']
>>> list(res)
['publisher', 'reviewer', 'user manager', 'writer']
[#verifyObjectIntransitive]_
.. [#verifyObjectIntransitive] The Intransitive search index provides
ISearchIndex and IListener.
>>> from zope.interface.verify import verifyObject
>>> import zc.relation.interfaces
>>> verifyObject(zc.relation.interfaces.ISearchIndex, index)
True
>>> verifyObject(zc.relation.interfaces.IListener, index)
True
Now we can change and remove relations--both organizations and roles--and
have the index maintain correct state. Given the current state of
organizations--
::
Ynod Corp Mangement Zookd Corp Management
/ | \ / | \
Ynod Devs Ynod SAs Ynod Admins Zookd Admins Zookd SAs Zookd Devs
/ \ \ / / \
Y3L4 Proj Bet Proj Ynod Zookd Task Force Zookd hOgnmd Zookd Nbd
--first we will move Ynod Devs to beneath Zookd Devs, and back out. This will
briefly give abe full privileges to Y3L4 Proj., among others.
>>> list(catalog.findValueTokens(
... 'role_id', t({'organization': orgs['Y3L4 Proj'],
... 'principal_id': 'abe'})))
[]
>>> orgs['Zookd Devs'].parts.insert(registry.getId(orgs['Ynod Devs']))
1
>>> catalog.index(orgs['Zookd Devs'])
>>> res = catalog.findValueTokens(
... 'role_id', t({'organization': orgs['Y3L4 Proj'],
... 'principal_id': 'abe'}))
>>> list(res)
['publisher', 'reviewer', 'user manager', 'writer']
>>> list(res)
['publisher', 'reviewer', 'user manager', 'writer']
>>> orgs['Zookd Devs'].parts.remove(registry.getId(orgs['Ynod Devs']))
>>> catalog.index(orgs['Zookd Devs'])
>>> list(catalog.findValueTokens(
... 'role_id', t({'organization': orgs['Y3L4 Proj'],
... 'principal_id': 'abe'})))
[]
As another example, we will change the roles abe has, and see that it is
propagated down to Zookd Nbd.
>>> rels = list(catalog.findRelations(t(
... {'principal_id': 'abe',
... 'organization': orgs['Zookd Corp Management']})))
>>> len(rels)
1
>>> rels[0].role_ids.remove('reviewer')
>>> catalog.index(rels[0])
>>> res = catalog.findValueTokens(
... 'role_id', t({'organization': orgs['Zookd Nbd'],
... 'principal_id': 'abe'}))
>>> list(res)
['publisher', 'user manager', 'writer']
>>> list(res)
['publisher', 'user manager', 'writer']
Note that search index order matters. In our case, our intransitive search
index is relying on our transitive index, so the transitive index needs to
come first. You want transitive relation indexes before name. Right now,
you are in charge of this order: it will be difficult to come up with a
reliable algorithm for guessing this.
Listeners, Catalog Administration, and Joining Across Relation Catalogs
=======================================================================
We've done all of our examples so far with a single catalog that indexes
both kinds of relations. What if we want to have two catalogs with
homogenous collections of relations? That can feel cleaner, but it also
introduces some new wrinkles.
Let's use our current catalog for organizations, removing the extra
information; and create a new one for roles.
>>> role_catalog = root['role_catalog'] = catalog.copy()
>>> transaction.commit()
>>> org_catalog = catalog
>>> del catalog
We'll need a slightly different query factory and a slightly different
search index `getValueTokens` function. We'll write those, then modify the
configuration of our two catalogs for the new world.
The transitive factory we write here is for the role catalog. It needs
access to the organzation catalog. We could do this a variety of
ways--relying on a utility, or finding the catalog from context. We will
make the role_catalog have a .org_catalog attribute, and rely on that.
>>> role_catalog.org_catalog = org_catalog
>>> def factory3(query, catalog):
... if (len(query) == 2 and
... 'organization' in query and
... 'principal_id' in query):
... def getQueries(relchain):
... if not relchain:
... res = BTrees.family32.OO.Bucket(query)
... org_id = query['organization']
... if org_id is not None:
... res['organization'] = zc.relation.catalog.any(
... org_id,
... *catalog.org_catalog.findRelationTokens(
... {'part': org_id}))
... yield res
... return getQueries
...
>>> def getValueTokens2(index, name, token, catalog, source,
... additions, removals, removed):
... is_role_catalog = catalog is index.catalog # role_catalog
... if name == 'organization':
... if is_role_catalog:
... orgs = set(source.get('organization') or
... index.catalog.getValueTokens(
... 'organization', token) or ())
... else:
... orgs = set((token,))
... orgs.update(removals.get('part', ()))
... orgs.update(index.catalog.org_catalog.findValueTokens(
... 'part',
... {None: zc.relation.catalog.Any(
... t for t in orgs if t is not None)}))
... return orgs
... elif name == 'principal_id':
... # we only want custom behavior if this is an organization
... if not is_role_catalog:
... orgs = set((token,))
... orgs.update(index.catalog.org_catalog.findRelationTokens(
... {'part': token}))
... return set(index.catalog.findValueTokens(
... 'principal_id', {
... 'organization': zc.relation.catalog.Any(orgs)}))
... return ''
If you are following along in the code and comparing to the originals, you may
see that this approach is a bit cleaner than the one when the relations were
in the same catalog.
Now we will fix up the the organization catalog [#compare_copy]_.
.. [#compare_copy] Before we modify them, let's look at the copy we made.
The copy should currently behave identically to the original.
>>> len(org_catalog)
38
>>> len(role_catalog)
38
>>> indexed = list(org_catalog)
>>> len(indexed)
38
>>> orgs['Zookd Devs'] in indexed
True
>>> for r in indexed:
... if r not in role_catalog:
... print('bad')
... break
... else:
... print('good')
...
good
>>> org_names = set(dir(org_catalog))
>>> role_names = set(dir(role_catalog))
>>> sorted(org_names - role_names)
[]
>>> sorted(role_names - org_names)
['org_catalog']
>>> def checkYnodDevsParts(catalog):
... res = sorted(catalog.findRelations(t({None: orgs['Ynod Devs']})))
... if res != [
... orgs["Bet Proj"], orgs["Y3L4 Proj"], orgs["Ynod Devs"]]:
... print("bad", res)
...
>>> checkYnodDevsParts(org_catalog)
>>> checkYnodDevsParts(role_catalog)
>>> def checkOpheliaRoles(catalog):
... res = sorted(catalog.findRelations({'principal_id': 'ophelia'}))
... if repr(res) != (
... "[<Roles instance (ophelia has publisher in Zookd Nbd)>, " +
... "<Roles instance (ophelia has reviewer in Zookd Devs)>, " +
... "<Roles instance (ophelia has writer in " +
... "Zookd Corp Management)>]"):
... print("bad", res)
...
>>> checkOpheliaRoles(org_catalog)
>>> checkOpheliaRoles(role_catalog)
>>> def checkOpheliaWriterOrganizations(catalog):
... res = sorted(catalog.findRelations({None: zc.relation.catalog.Any(
... catalog.findValueTokens(
... 'organization', {'principal_id': 'ophelia',
... 'role_id': 'writer'}))}))
... if repr(res) != (
... '[<Organization instance "Ynod Zookd Task Force">, ' +
... '<Organization instance "Zookd Admins">, ' +
... '<Organization instance "Zookd Corp Management">, ' +
... '<Organization instance "Zookd Devs">, ' +
... '<Organization instance "Zookd Nbd">, ' +
... '<Organization instance "Zookd SAs">, ' +
... '<Organization instance "Zookd hOgnmd">]'):
... print("bad", res)
...
>>> checkOpheliaWriterOrganizations(org_catalog)
>>> checkOpheliaWriterOrganizations(role_catalog)
>>> def checkPrincipalsWithRolesInZookdDevs(catalog):
... org_id = registry.getId(orgs['Zookd Devs'])
... res = sorted(catalog.findValueTokens(
... 'principal_id',
... {'organization': zc.relation.catalog.any(
... org_id, *catalog.findRelationTokens({'part': org_id}))}))
... if res != ['abe', 'ignas', 'karyn', 'lettie', 'nancy', 'ophelia']:
... print("bad", res)
...
>>> checkPrincipalsWithRolesInZookdDevs(org_catalog)
>>> checkPrincipalsWithRolesInZookdDevs(role_catalog)
>>> def checkOpheliaRolesInZookdNbd(catalog):
... res = sorted(catalog.findValueTokens(
... 'role_id', {
... 'organization': registry.getId(orgs['Zookd Nbd']),
... 'principal_id': 'ophelia'}))
... if res != ['publisher', 'reviewer', 'writer']:
... print("bad", res)
...
>>> checkOpheliaRolesInZookdNbd(org_catalog)
>>> checkOpheliaRolesInZookdNbd(role_catalog)
>>> def checkAbeRolesInZookdNbd(catalog):
... res = sorted(catalog.findValueTokens(
... 'role_id', {
... 'organization': registry.getId(orgs['Zookd Nbd']),
... 'principal_id': 'abe'}))
... if res != ['publisher', 'user manager', 'writer']:
... print("bad", res)
...
>>> checkAbeRolesInZookdNbd(org_catalog)
>>> checkAbeRolesInZookdNbd(role_catalog)
>>> org_catalog.removeDefaultQueryFactory(None) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
LookupError: ('factory not found', None)
>>> org_catalog.removeValueIndex('organization')
>>> org_catalog.removeValueIndex('role_id')
>>> org_catalog.removeValueIndex('principal_id')
>>> org_catalog.removeDefaultQueryFactory(factory2)
>>> org_catalog.removeSearchIndex(index)
>>> org_catalog.clear()
>>> len(org_catalog)
0
>>> for v in orgs.values():
... org_catalog.index(v)
This also shows using the `removeDefaultQueryFactory` and `removeSearchIndex`
methods [#removeDefaultQueryFactoryExceptions]_.
.. [#removeDefaultQueryFactoryExceptions] You get errors by removing query
factories that are not registered.
>>> org_catalog.removeDefaultQueryFactory(factory2) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
LookupError: ('factory not found', <function factory2 at ...>)
Now we will set up the role catalog [#copy_unchanged]_.
.. [#copy_unchanged] Changes to one copy should not affect the other. That
means the role_catalog should still work as before.
>>> len(org_catalog)
13
>>> len(list(org_catalog))
13
>>> len(role_catalog)
38
>>> indexed = list(role_catalog)
>>> len(indexed)
38
>>> orgs['Zookd Devs'] in indexed
True
>>> orgs['Zookd Devs'] in role_catalog
True
>>> checkYnodDevsParts(role_catalog)
>>> checkOpheliaRoles(role_catalog)
>>> checkOpheliaWriterOrganizations(role_catalog)
>>> checkPrincipalsWithRolesInZookdDevs(role_catalog)
>>> checkOpheliaRolesInZookdNbd(role_catalog)
>>> checkAbeRolesInZookdNbd(role_catalog)
>>> role_catalog.removeValueIndex('part')
>>> for ix in list(role_catalog.iterSearchIndexes()):
... role_catalog.removeSearchIndex(ix)
...
>>> role_catalog.removeDefaultQueryFactory(factory1)
>>> role_catalog.removeDefaultQueryFactory(factory2)
>>> role_catalog.addDefaultQueryFactory(factory3)
>>> root['index2'] = index2 = zc.relation.searchindex.Intransitive(
... ('organization', 'principal_id'), 'role_id', factory3,
... getValueTokens2,
... ('organization', 'principal_id', 'part', 'role_id'),
... unlimitedDepth=True)
>>> role_catalog.addSearchIndex(index2)
The new role_catalog index needs to be updated from the org_catalog.
We'll set that up using listeners, a new concept.
>>> org_catalog.addListener(index2)
>>> list(org_catalog.iterListeners()) == [index2]
True
Now the role_catalog should be able to answer the same questions as the old
single catalog approach.
>>> t = role_catalog.tokenizeQuery
>>> list(role_catalog.findValueTokens(
... 'role_id', t({'organization': orgs['Zookd Nbd'],
... 'principal_id': 'abe'})))
['publisher', 'user manager', 'writer']
>>> list(role_catalog.findValueTokens(
... 'role_id', t({'organization': orgs['Zookd Nbd'],
... 'principal_id': 'ophelia'})))
['publisher', 'reviewer', 'writer']
We can also make changes to both catalogs and the search indexes are
maintained.
>>> list(role_catalog.findValueTokens(
... 'role_id', t({'organization': orgs['Y3L4 Proj'],
... 'principal_id': 'abe'})))
[]
>>> orgs['Zookd Devs'].parts.insert(registry.getId(orgs['Ynod Devs']))
1
>>> org_catalog.index(orgs['Zookd Devs'])
>>> list(role_catalog.findValueTokens(
... 'role_id', t({'organization': orgs['Y3L4 Proj'],
... 'principal_id': 'abe'})))
['publisher', 'user manager', 'writer']
>>> orgs['Zookd Devs'].parts.remove(registry.getId(orgs['Ynod Devs']))
>>> org_catalog.index(orgs['Zookd Devs'])
>>> list(role_catalog.findValueTokens(
... 'role_id', t({'organization': orgs['Y3L4 Proj'],
... 'principal_id': 'abe'})))
[]
>>> rels = list(role_catalog.findRelations(t(
... {'principal_id': 'abe',
... 'organization': orgs['Zookd Corp Management']})))
>>> len(rels)
1
>>> rels[0].role_ids.insert('reviewer')
1
>>> role_catalog.index(rels[0])
>>> res = role_catalog.findValueTokens(
... 'role_id', t({'organization': orgs['Zookd Nbd'],
... 'principal_id': 'abe'}))
>>> list(res)
['publisher', 'reviewer', 'user manager', 'writer']
Here we add a new organization.
>>> orgs['Zookd hOnc'] = org = Organization('Zookd hOnc')
>>> orgs['Zookd Devs'].parts.insert(registry.getId(org))
1
>>> org_catalog.index(orgs['Zookd hOnc'])
>>> org_catalog.index(orgs['Zookd Devs'])
>>> list(role_catalog.findValueTokens(
... 'role_id', t({'organization': orgs['Zookd hOnc'],
... 'principal_id': 'abe'})))
['publisher', 'reviewer', 'user manager', 'writer']
>>> list(role_catalog.findValueTokens(
... 'role_id', t({'organization': orgs['Zookd hOnc'],
... 'principal_id': 'ophelia'})))
['reviewer', 'writer']
Now we'll remove it.
>>> orgs['Zookd Devs'].parts.remove(registry.getId(org))
>>> org_catalog.index(orgs['Zookd Devs'])
>>> org_catalog.unindex(orgs['Zookd hOnc'])
TODO make sure that intransitive copy looks the way we expect
[#administrivia]_
.. [#administrivia]
You can add listeners multiple times.
>>> org_catalog.addListener(index2)
>>> list(org_catalog.iterListeners()) == [index2, index2]
True
Now we will remove the listeners, to show we can.
>>> org_catalog.removeListener(index2)
>>> org_catalog.removeListener(index2)
>>> org_catalog.removeListener(index2)
... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
LookupError: ('listener not found',
<zc.relation.searchindex.Intransitive object at ...>)
>>> org_catalog.removeListener(None)
... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
LookupError: ('listener not found', None)
Here's the same for removing a search index we don't have
>>> org_catalog.removeSearchIndex(index2)
... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
LookupError: ('index not found',
<zc.relation.searchindex.Intransitive object at ...>)
.. ......... ..
.. Footnotes ..
.. ......... ..
.. [#silliness] In "2001: A Space Odyssey", many people believe the name HAL
was chosen because it was ROT25 of IBM.... I cheat a bit sometimes and
use ROT1 because the result sounds better.
| zc.relation | /zc.relation-2.0.tar.gz/zc.relation-2.0/src/zc/relation/tokens.rst | tokens.rst |
import pprint
import timeit
# see zc/relation/searchindex.rst
brute_setup = '''
import BTrees
relations = BTrees.family64.IO.BTree()
relations[99] = None # just to give us a start
class Relation(object):
def __init__(self, token, children=()):
self.token = token
self.children = BTrees.family64.IF.TreeSet(children)
self.id = relations.maxKey() + 1
relations[self.id] = self
def token(rel, self):
return rel.token
def children(rel, self):
return rel.children
def dumpRelation(obj, index, cache):
return obj.id
def loadRelation(token, index, cache):
return relations[token]
import zc.relation.queryfactory
factory = zc.relation.queryfactory.TransposingTransitive(
'token', 'children')
import zc.relation.catalog
catalog = zc.relation.catalog.Catalog(
dumpRelation, loadRelation, BTrees.family64.IO, BTrees.family64)
catalog.addValueIndex(token)
catalog.addValueIndex(children, multiple=True)
catalog.addDefaultQueryFactory(factory)
for token, children in (
(0, (1, 2)), (1, (3, 4)), (2, (10, 11, 12)), (3, (5, 6)),
(4, (13, 14)), (5, (7, 8, 9)), (6, (15, 16)), (7, (17, 18, 19)),
(8, (20, 21, 22)), (9, (23, 24)), (10, (25, 26)),
(11, (27, 28, 29, 30, 31, 32))):
catalog.index(Relation(token, children))
'''
# _____________0_____________
# / \
# ________1_______ ______2____________
# / \ / | \
# ______3_____ _4_ 10 ____11_____ 12
# / \ / \ / \ / / | \ \ \
# _______5_______ 6 13 14 25 26 27 28 29 30 31 32
# / | \ / \
# _7_ _8_ 9 15 16
# / | \ / | \ / \
# 17 18 19 20 21 22 23 24
relation_index_setup = brute_setup + '''
import zc.relation.searchindex
catalog.addSearchIndex(
zc.relation.searchindex.TransposingTransitive('token', 'children'))
'''
value_index_setup = brute_setup + '''
import zc.relation.searchindex
catalog.addSearchIndex(
zc.relation.searchindex.TransposingTransitive(
'token', 'children', names=('children',)))
'''
relations_run_template = '''
res = list(catalog.findRelationTokens({'token': %d}))
'''
value_run_template = '''
res = list(catalog.findValueTokens('children', {'token': %d}))
'''
canfind_run_template = '''
res = catalog.canFind({'token': %d}, targetQuery={'children': 23})
'''
options = (9, 7, 5, 3, 1, 0)
runs = 10000
control = timeit.Timer('res = catalog.__len__()\nlist()', brute_setup)
control_result = min(control.repeat(3, runs))
d = [('control_result', control_result)]
for template in (relations_run_template, value_run_template,
canfind_run_template):
for o in options:
run = template % (o,)
# verify we get the same results
brute_globs = {}
relation_globs = {}
value_globs = {}
exec(brute_setup + run, brute_globs)
exec(relation_index_setup + run, relation_globs)
exec(value_index_setup + run, value_globs)
brute = brute_globs['res']
relation = relation_globs['res']
value = value_globs['res']
canfind = template == canfind_run_template
if not canfind:
brute.sort()
assert brute == relation == value, '{}: {!r}, {!r}, {!r}'.format(
run, brute, relation, value)
# end verify
d.append('**** {} ****'.format(run.strip()))
d.append('**** {} ****'.format(brute))
if not canfind:
# show how long it takes to make the generator
altered = run.replace('list(', '', 1)
altered = altered.replace(')', '', 1)
d.append((
'brute_generate',
min(timeit.Timer(
altered, brute_setup).repeat(3, runs)) - control_result))
d.append((
'brute',
min(timeit.Timer(
run, brute_setup).repeat(3, runs)) - control_result))
d.append((
'relation',
min(timeit.Timer(
run, relation_index_setup).repeat(3, runs)) - control_result))
d.append((
'value',
min(timeit.Timer(
run, value_index_setup).repeat(3, runs)) - control_result))
d.append('------------------')
d.append('------------------')
print(' Test 1\n\n')
pprint.pprint(d)
reverse_setup = brute_setup + """
import zc.relation.searchindex
catalog.addSearchIndex(
zc.relation.searchindex.TransposingTransitive('children', 'token'))
"""
relations_run_template = '''
res = catalog.findRelationTokens({'token': %d})
'''
value_run_template = '''
res = catalog.findValueTokens('children', {'token': %d})
'''
print('\n\n Test 2\n\n')
control = timeit.Timer('res = catalog.__len__()', brute_setup)
control_result = min(control.repeat(3, runs))
d = [('control_result', control_result)]
for template in (relations_run_template, value_run_template):
for o in (9, 0):
run = template % (o,)
d.append('**** {} ****'.format(run.strip()))
d.append((
'brute',
min(timeit.Timer(
run, brute_setup).repeat(3, runs)) - control_result))
d.append((
'index',
min(timeit.Timer(
run, reverse_setup).repeat(3, runs)) - control_result))
d.append('------------------')
d.append('------------------')
pprint.pprint(d) | zc.relation | /zc.relation-2.0.tar.gz/zc.relation-2.0/src/zc/relation/timeit/transitive_search_index.py | transitive_search_index.py |
import timeit
setup = '''
import BTrees
one = BTrees.family32.IO.TreeSet((0,))
ten = BTrees.family32.IO.TreeSet(range(10))
hundred = BTrees.family32.IO.TreeSet(range(100))
thousand = BTrees.family32.IO.TreeSet(range(1000))
tenthousand = BTrees.family32.IO.TreeSet(range(10000))
sets = [BTrees.family32.IO.TreeSet(tenthousand) for i in range(1000)]
'''
base = 's = sets.pop()'
create_template = base + '''
BTrees.family32.IO.TreeSet(%s)'''
remove_template = base + '''
for i in range(0, 10000, %d):
s.remove(i)'''
len_template = base + '''
len(%s)'''
control = timeit.Timer(base, setup)
create_empty = timeit.Timer(create_template % ('',), setup)
create_one = timeit.Timer(create_template % ('one',), setup)
create_ten = timeit.Timer(create_template % ('ten',), setup)
create_hundred = timeit.Timer(create_template % ('hundred',), setup)
create_thousand = timeit.Timer(create_template % ('thousand',), setup)
create_tenthousand = timeit.Timer(create_template % ('tenthousand',), setup)
remove_one = timeit.Timer(remove_template % (10000,), setup)
remove_ten = timeit.Timer(remove_template % (1000,), setup)
remove_hundred = timeit.Timer(remove_template % (100,), setup)
remove_thousand = timeit.Timer(remove_template % (10,), setup)
remove_tenthousand = timeit.Timer(remove_template % (1,), setup)
len_one = timeit.Timer(len_template % ('one',), setup)
len_ten = timeit.Timer(len_template % ('ten',), setup)
len_hundred = timeit.Timer(len_template % ('hundred',), setup)
len_thousand = timeit.Timer(len_template % ('thousand',), setup)
len_tenthousand = timeit.Timer(len_template % ('tenthousand',), setup)
d = {}
control_result = d['control_result'] = min(control.repeat(3, 1000))
d['create_empty_result'] = min(create_empty.repeat(3, 1000))
d['create_one_result'] = min(create_one.repeat(3, 1000))
d['create_ten_result'] = min(create_ten.repeat(3, 1000))
d['create_hundred_result'] = min(create_hundred.repeat(3, 1000))
d['create_thousand_result'] = min(create_thousand.repeat(3, 1000))
d['create_tenthousand_result'] = min(create_tenthousand.repeat(3, 1000))
d['remove_one_result'] = min(remove_one.repeat(3, 1000))
d['remove_ten_result'] = min(remove_ten.repeat(3, 1000))
d['remove_hundred_result'] = min(remove_hundred.repeat(3, 1000))
d['remove_thousand_result'] = min(remove_thousand.repeat(3, 1000))
d['remove_tenthousand_result'] = min(remove_tenthousand.repeat(3, 1000))
d['len_one_result'] = min(len_one.repeat(3, 1000))
d['len_ten_result'] = min(len_ten.repeat(3, 1000))
d['len_hundred_result'] = min(len_hundred.repeat(3, 1000))
d['len_thousand_result'] = min(len_thousand.repeat(3, 1000))
d['len_tenthousand_result'] = min(len_tenthousand.repeat(3, 1000))
for k, v in d.items():
if k == 'control_result':
continue
d[k[:-7]] = v - control_result
print('''
control: %(control_result)s
(the following results have the control subtracted)
create_empty: %(create_empty)s
create_one: %(create_one)s
create_ten: %(create_ten)s
create_hundred: %(create_hundred)s
create_thousand: %(create_thousand)s
create_tenthousand: %(create_tenthousand)s
remove_one: %(remove_one)s
remove_ten: %(remove_ten)s
remove_hundred: %(remove_hundred)s
remove_thousand: %(remove_thousand)s
remove_tenthousand: %(remove_tenthousand)s
len_one: %(len_one)s
len_ten: %(len_ten)s
len_hundred: %(len_hundred)s
len_thousand: %(len_thousand)s
len_tenthousand: %(len_tenthousand)s
''' % d) | zc.relation | /zc.relation-2.0.tar.gz/zc.relation-2.0/src/zc/relation/timeit/set_creation_vs_removal.py | set_creation_vs_removal.py |
=======
Changes
=======
2.1 (2021-03-22)
================
- Add support for Python 3.7 up to 3.9.
- Update to ``zope.component >= 5``.
2.0.post1 (2018-06-19)
======================
- Fix PyPI page by using correct ReST syntax.
2.0 (2018-06-19)
================
The 2.x line is almost completely compatible with the 1.x line.
The one notable incompatibility does not affect the use of relationship
containers and is small enough that it will hopefully affect noone.
New Requirements
----------------
- zc.relation
Incompatibilities with 1.0
--------------------------
- ``findRelationships`` will now use the defaultTransitiveQueriesFactory if it
is set. Set ``maxDepth`` to 1 if you do not want this behavior.
- Some instantiation exceptions have different error messages.
Changes in 2.0
--------------
- the relationship index code has been moved out to zc.relation and
significantly refactored there. A fully backwards compatible subclass
remains in zc.relationship.index
- support both 64-bit and 32-bit BTree families
- support specifying indexed values by passing callables rather than
interface elements (which are also still supported).
- in findValues and findValueTokens, `query` argument is now optional. If
the query evaluates to False in a boolean context, all values, or value
tokens, are returned. Value tokens are explicitly returned using the
underlying BTree storage. This can then be used directly for other BTree
operations.
In these and other cases, you should not ever mutate returned results!
They may be internal data structures (and are intended to be so, so
that they can be used for efficient set operations for other uses).
The interfaces hopefully clarify what calls will return an internal
data structure.
- README has a new beginning, which both demonstrates some of the new features
and tries to be a bit simpler than the later sections.
- `findRelationships` and new method `findRelationshipTokens` can find
relationships transitively and intransitively. `findRelationshipTokens`
when used intransitively repeats the behavior of `findRelationshipTokenSet`.
(`findRelationshipTokenSet` remains in the API, not deprecated, a companion
to `findValueTokenSet`.)
- 100% test coverage (per the usual misleading line analysis :-) of index
module. (Note that the significantly lower test coverage of the container
code is unlikely to change without contributions: I use the index
exclusively. See plone.relations for a zc.relationship container with
very good test coverage.)
- Tested with Python 2.7 and Python >= 3.5
- Added test extra to declare test dependency on ``zope.app.folder``.
Branch 1.1
==========
(supports Zope 3.4/Zope 2.11/ZODB 3.8)
1.1.0
-----
- adjust to BTrees changes in ZODB 3.8 (thanks Juergen Kartnaller)
- converted buildout to rely exclusively on eggs
Branch 1.0
==========
(supports Zope 3.3/Zope 2.10/ZODB 3.7)
1.0.2
-----
- Incorporated tests and bug fixes to relationship containers from
Markus Kemmerling:
* ManyToOneRelationship instantiation was broken
* The `findRelationships` method misbehaved if both, `source` and `target`,
are not None, but `bool(target)` evaluated to False.
* ISourceRelationship and ITargetRelationship had errors.
1.0.1
-----
- Incorporated test and bug fix from Gabriel Shaar::
if the target parameter is a container with no objects, then
`shared.AbstractContainer.isLinked` resolves to False in a bool context and
tokenization fails. `target and tokenize({'target': target})` returns the
target instead of the result of the tokenize function.
- Made README.rst tests pass on hopefully wider set of machines (this was a
test improvement; the relationship index did not have the fragility).
Reported by Gabriel Shaar.
1.0.0
-----
Initial release
| zc.relationship | /zc.relationship-2.1.tar.gz/zc.relationship-2.1/CHANGES.rst | CHANGES.rst |
import random
import six
import persistent
from zope import interface
import zope.app.container.contained
import zope.app.container.btree
from zc.relationship import interfaces, index
##############################################################################
# some useful relationship variants
#
try:
import zc.listcontainer
except ImportError:
class RelationshipBase(
persistent.Persistent, zope.app.container.contained.Contained):
pass
else:
class RelationshipBase(
persistent.Persistent,
zope.app.container.contained.Contained,
zc.listcontainer.Contained):
pass
try:
apply
except NameError:
# PY3
def apply(func, *args, **kw):
return func(*args, **kw)
@interface.implementer(interfaces.IRelationship)
class ImmutableRelationship(RelationshipBase):
_marker = __name__ = __parent__ = None
def __init__(self, sources, targets):
self._sources = tuple(sources)
self._targets = tuple(targets)
@property
def sources(self):
return self._sources
@property
def targets(self):
return self._targets
def __repr__(self):
return '<Relationship from %r to %r>' % (self.sources, self.targets)
@interface.implementer(interfaces.IMutableRelationship)
class Relationship(ImmutableRelationship):
@apply
def sources():
def get(self):
return self._sources
def set(self, value):
self._sources = tuple(value)
if interfaces.IBidirectionalRelationshipIndex.providedBy(
self.__parent__):
self.__parent__.reindex(self)
return property(get, set)
@apply
def targets():
def get(self):
return self._targets
def set(self, value):
self._targets = tuple(value)
if interfaces.IBidirectionalRelationshipIndex.providedBy(
self.__parent__):
self.__parent__.reindex(self)
return property(get, set)
# some small conveniences; maybe overkill, but I wanted some for a client
# package.
@interface.implementer(interfaces.IOneToOneRelationship)
class OneToOneRelationship(ImmutableRelationship):
def __init__(self, source, target):
super(OneToOneRelationship, self).__init__((source,), (target,))
@apply
def source():
def get(self):
return self._sources[0]
def set(self, value):
self._sources = (value,)
if interfaces.IBidirectionalRelationshipIndex.providedBy(
self.__parent__):
self.__parent__.reindex(self)
return property(get, set)
@apply
def target():
def get(self):
return self._targets[0]
def set(self, value):
self._targets = (value,)
if interfaces.IBidirectionalRelationshipIndex.providedBy(
self.__parent__):
self.__parent__.reindex(self)
return property(get, set)
@interface.implementer(interfaces.IOneToManyRelationship)
class OneToManyRelationship(ImmutableRelationship):
def __init__(self, source, targets):
super(OneToManyRelationship, self).__init__((source,), targets)
@apply
def source():
def get(self):
return self._sources[0]
def set(self, value):
self._sources = (value,)
if interfaces.IBidirectionalRelationshipIndex.providedBy(
self.__parent__):
self.__parent__.reindex(self)
return property(get, set)
@apply
def targets():
def get(self):
return self._targets
def set(self, value):
self._targets = tuple(value)
if interfaces.IBidirectionalRelationshipIndex.providedBy(
self.__parent__):
self.__parent__.reindex(self)
return property(get, set)
@interface.implementer(interfaces.IManyToOneRelationship)
class ManyToOneRelationship(ImmutableRelationship):
def __init__(self, sources, target):
super(ManyToOneRelationship, self).__init__(sources, (target,))
@apply
def sources():
def get(self):
return self._sources
def set(self, value):
self._sources = tuple(value)
if interfaces.IBidirectionalRelationshipIndex.providedBy(
self.__parent__):
self.__parent__.reindex(self)
return property(get, set)
@apply
def target():
def get(self):
return self._targets[0]
def set(self, value):
self._targets = (value,)
if interfaces.IBidirectionalRelationshipIndex.providedBy(
self.__parent__):
self.__parent__.reindex(self)
return property(get, set)
##############################################################################
class ResolvingFilter(object):
def __init__(self, filter, container):
self.filter = filter
self.container = container
def __call__(self, relchain, query, index, cache):
obj = self.container.relationIndex.resolveRelationshipToken(
relchain[-1])
return self.filter(obj)
def minDepthFilter(depth):
if depth is None:
return None
if not isinstance(depth, six.integer_types) or depth < 1:
raise ValueError('invalid minDepth', depth)
return lambda relchain, query, index, cache: len(relchain) >= depth
class AbstractContainer(persistent.Persistent):
def __init__(self,
dumpSource=None, loadSource=None, sourceFamily=None,
dumpTarget=None, loadTarget=None, targetFamily=None,
**kwargs):
source = {'element': interfaces.IRelationship['sources'],
'name': 'source', 'multiple': True}
target = {'element': interfaces.IRelationship['targets'],
'name': 'target', 'multiple': True}
if dumpSource is not None:
target['dump'] = source['dump'] = dumpSource
if loadSource is not None:
target['load'] = source['load'] = loadSource
if sourceFamily is not None:
target['btree'] = source['btree'] = sourceFamily
if dumpTarget is not None:
target['dump'] = dumpTarget
if loadTarget is not None:
target['load'] = loadTarget
if targetFamily is not None:
target['btree'] = targetFamily
ix = index.Index(
(source, target),
index.TransposingTransitiveQueriesFactory('source', 'target'),
**kwargs)
self.relationIndex = ix
ix.__parent__ = self
def reindex(self, object):
assert object.__parent__ is self
self.relationIndex.index(object)
def findTargets(self, source, maxDepth=1, minDepth=None, filter=None):
return self.relationIndex.findValues(
'target', self.relationIndex.tokenizeQuery({'source': source}),
maxDepth, filter and ResolvingFilter(filter, self),
targetFilter=minDepthFilter(minDepth))
def findSources(self, target, maxDepth=1, minDepth=None, filter=None):
return self.relationIndex.findValues(
'source', self.relationIndex.tokenizeQuery({'target': target}),
maxDepth, filter and ResolvingFilter(filter, self),
targetFilter=minDepthFilter(minDepth))
def findTargetTokens(self, source, maxDepth=1, minDepth=None, filter=None):
return self.relationIndex.findValueTokens(
'target', self.relationIndex.tokenizeQuery({'source': source}),
maxDepth, filter and ResolvingFilter(filter, self),
targetFilter=minDepthFilter(minDepth))
def findSourceTokens(self, target, maxDepth=1, minDepth=None, filter=None):
return self.relationIndex.findValueTokens(
'source', self.relationIndex.tokenizeQuery({'target': target}),
maxDepth, filter and ResolvingFilter(filter, self),
targetFilter=minDepthFilter(minDepth))
def isLinked(self, source=None, target=None, maxDepth=1, minDepth=None,
filter=None):
tokenize = self.relationIndex.tokenizeQuery
if source is not None:
if target is not None:
targetQuery = tokenize({'target': target})
else:
targetQuery = None
return self.relationIndex.isLinked(
tokenize({'source': source}),
maxDepth, filter and ResolvingFilter(filter, self),
targetQuery,
targetFilter=minDepthFilter(minDepth))
elif target is not None:
return self.relationIndex.isLinked(
tokenize({'target': target}),
maxDepth, filter and ResolvingFilter(filter, self),
targetFilter=minDepthFilter(minDepth))
else:
raise ValueError(
'at least one of `source` and `target` must be provided')
def _reverse(self, iterable):
for i in iterable:
if interfaces.ICircularRelationshipPath.providedBy(i):
yield index.CircularRelationshipPath(
reversed(i),
[self.relationIndex.resolveQuery(d) for d in i.cycled])
else:
yield tuple(reversed(i))
def _forward(self, iterable):
for i in iterable:
if interfaces.ICircularRelationshipPath.providedBy(i):
yield index.CircularRelationshipPath(
i,
[self.relationIndex.resolveQuery(d) for d in i.cycled])
else:
yield i
def findRelationshipTokens(self, source=None, target=None, maxDepth=1,
minDepth=None, filter=None):
tokenize = self.relationIndex.tokenizeQuery
if source is not None:
if target is not None:
targetQuery = tokenize({'target': target})
else:
targetQuery = None
res = self.relationIndex.findRelationshipTokenChains(
tokenize({'source': source}),
maxDepth, filter and ResolvingFilter(filter, self),
targetQuery,
targetFilter=minDepthFilter(minDepth))
return self._forward(res)
elif target is not None:
res = self.relationIndex.findRelationshipTokenChains(
tokenize({'target': target}),
maxDepth, filter and ResolvingFilter(filter, self),
targetFilter=minDepthFilter(minDepth))
return self._reverse(res)
else:
raise ValueError(
'at least one of `source` and `target` must be provided')
def _resolveRelationshipChains(self, iterable):
for i in iterable:
chain = tuple(self.relationIndex.resolveRelationshipTokens(i))
if interfaces.ICircularRelationshipPath.providedBy(i):
yield index.CircularRelationshipPath(chain, i.cycled)
else:
yield tuple(chain)
def findRelationships(self, source=None, target=None, maxDepth=1,
minDepth=None, filter=None):
return self._resolveRelationshipChains(
self.findRelationshipTokens(
source, target, maxDepth, minDepth, filter))
class Container(AbstractContainer, zope.app.container.btree.BTreeContainer):
def __init__(self, *args, **kwargs):
AbstractContainer.__init__(self, *args, **kwargs)
zope.app.container.btree.BTreeContainer.__init__(self)
# subclass API
def _generate_id(self, relationship):
return ''.join(random.sample(
"abcdefghijklmnopqrtstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_1234567890",
30)) # somewhat less than 64 ** 30 variations (64*63*...*35)
# end subclass API
def add(self, object):
key = self._generate_id(object)
while key in self._SampleContainer__data:
key = self._generate_id(object)
super(AbstractContainer, self).__setitem__(key, object)
self.relationIndex.index(object)
def remove(self, object):
key = object.__name__
if self[key] is not object:
raise ValueError("Relationship is not stored as its __name__")
self.relationIndex.unindex(object)
super(AbstractContainer, self).__delitem__(key)
@property
def __setitem__(self):
raise AttributeError
__delitem__ = __setitem__ | zc.relationship | /zc.relationship-2.1.tar.gz/zc.relationship-2.1/src/zc/relationship/shared.py | shared.py |
~~~~~~~~~~~~~~~
zc.relationship
~~~~~~~~~~~~~~~
The zc.relationship package currently contains two main types of
components: a relationship index, and some relationship containers.
Both are designed to be used within the ZODB, although the index is
flexible enough to be used in other contexts. They share the model that
relationships are full-fledged objects that are indexed for optimized
searches. They also share the ability to perform optimized intransitive
and transitive relationship searches, and to support arbitrary filter
searches on relationship tokens.
The index is a very generic component that can be used to optimize searches
for N-ary relationships, can be used standalone or within a catalog, can be
used with pluggable token generation schemes, and generally tries to provide
a relatively policy-free tool. It is expected to be used primarily as an
engine for more specialized and constrained tools and APIs.
The relationship containers use the index to manage two-way
relationships, using a derived mapping interface. It is a reasonable
example of the index in standalone use.
Another example, using the container model but supporting five-way
relationships ("sources", "targets", "relation", "getContext", "state"), can
be found in plone.relations. Its README is a good read.
http://dev.plone.org/plone/browser/plone.relations/trunk/plone/relations
This current document describes the relationship index. See
container.rst for documentation of the relationship container.
**PLEASE NOTE: the index in zc.relationship, described below, now exists for
backwards compatibility. zc.relation.catalog now contains the most recent,
backward-incompatible version of the index code.**
=====
Index
=====
.. contents::
Overview
========
The index takes a very precise view of the world: instantiation requires
multiple arguments specifying the configuration; and using the index
requires that you acknowledge that the relationships and their
associated indexed values are usually tokenized within the index. This
precision trades some ease-of-use for the possibility of flexibility,
power, and efficiency. That said, the index's API is intended to be
consistent, and to largely adhere to "there's only one way to do it"
[#apply]_.
Simplest Example
----------------
Before diving into the N-way flexibility and the other more complex
bits, then, let's have a quick basic demonstration: a two way
relationship from one value to another. This will give you a taste of
the relationship index, and let you use it reasonably well for
light-to-medium usage. If you are going to use more of its features or
use it more in a potentially high-volume capacity, please consider
trying to understand the entire document.
Let's say that we are modeling a relationship of people to their
supervisors: an employee may have a single supervisor.
Let's say further that employee names are unique and can be used to
represent employees. We can use names as our "tokens". Tokens are
similar to the primary key in a relational database, or in intid or
keyreference in Zope 3--some way to uniquely identify an object, which
sorts reliably and can be resolved to the object given the right context.
>>> from __future__ import print_function
>>> from functools import total_ordering
>>> employees = {} # we'll use this to resolve the "name" tokens
>>> @total_ordering
... class Employee(object):
... def __init__(self, name, supervisor=None):
... if name in employees:
... raise ValueError('employee with same name already exists')
... self.name = name # expect this to be readonly
... self.supervisor = supervisor
... employees[name] = self
... def __repr__(self): # to make the tests prettier...
... return '<' + self.name + '>'
... def __eq__(self, other):
... return self is other
... def __lt__(self, other): # to make the tests prettier...
... # pukes if other doesn't have name
... return self.name < other.name
...
So, we need to define how to turn employees into their tokens. That's
trivial. (We explain the arguments to this function in detail below,
but for now we're aiming for "breezy overview".)
>>> def dumpEmployees(emp, index, cache):
... return emp.name
...
We also need a way to turn tokens into employees. We use our dict for that.
>>> def loadEmployees(token, index, cache):
... return employees[token]
...
We also need a way to tell the index to find the supervisor for indexing:
>>> def supervisor(emp, index):
... return emp.supervisor # None or another employee
...
Now we have enough to get started with an index. The first argument to
Index is the attributes to index: we pass the `supervisor` function
(which is also used in this case to define the index's name, since we do
not pass one explicitly), the dump and load functions, and a BTree
module that specifies sets that can hold our tokens (OO or OL should
also work). As keyword arguments, we tell the index how to dump and
load our relationship tokens--the same functions in this case--and what
a reasonable BTree module is for sets (again, we choose OI, but OO or OL
should work).
>>> from zc.relationship import index
>>> import BTrees
>>> ix = index.Index(
... ({'callable': supervisor, 'dump': dumpEmployees,
... 'load': loadEmployees, 'btree': BTrees.family32.OI},),
... dumpRel=dumpEmployees, loadRel=loadEmployees,
... relFamily=BTrees.family32.OI)
Now let's create a few employees.
>>> a = Employee('Alice')
>>> b = Employee('Betty', a)
>>> c = Employee('Chuck', a)
>>> d = Employee('Duane', b)
>>> e = Employee('Edgar', b)
>>> f = Employee('Frank', c)
>>> g = Employee('Grant', c)
>>> h = Employee('Howie', d)
In a diagram style with which you will become familiar if you make it to
the end of this document, let's show the hierarchy.
::
Alice
__/ \__
Betty Chuck
/ \ / \
Duane Edgar Frank Grant
|
Howie
So who works for Alice? To ask the index, we need to tell it about them.
>>> for emp in (a,b,c,d,e,f,g,h):
... ix.index(emp)
...
Now we can ask. We always need to ask with tokens. The index provides
a method to try and make this more convenient: `tokenizeQuery`
[#resolveQuery]_.
.. [#resolveQuery] You can also resolve queries.
>>> ix.resolveQuery({None: 'Alice'})
{None: <Alice>}
>>> ix.resolveQuery({'supervisor': 'Alice'})
{'supervisor': <Alice>}
The spelling of the query is described in more detail
later, but the idea is simply that keys in a dictionary specify
attribute names, and the values specify the constraints.
>>> t = ix.tokenizeQuery
>>> sorted(ix.findRelationshipTokens(t({'supervisor': a})))
['Betty', 'Chuck']
>>> sorted(ix.findRelationships(t({'supervisor': a})))
[<Betty>, <Chuck>]
How do we find what the employee's supervisor is? Well, in this case,
look at the attribute! If you can use an attribute that will usually be
a win in the ZODB. If you want to look at the data in the index,
though, that's easy enough. Who is Howie's supervisor? The None key in
the query indicates that we are matching against the relationship token
itself [#None_details]_.
.. [#None_details] You can search for relations that haven't been indexed.
>>> list(ix.findRelationshipTokens({None: 'Ygritte'}))
[]
You can also combine searches with None, just for completeness.
>>> list(ix.findRelationshipTokens({None: 'Alice', 'supervisor': None}))
['Alice']
>>> list(ix.findRelationshipTokens({None: 'Alice', 'supervisor': 'Betty'}))
[]
>>> list(ix.findRelationshipTokens({None: 'Betty', 'supervisor': 'Alice'}))
['Betty']
>>> h.supervisor
<Duane>
>>> list(ix.findValueTokens('supervisor', t({None: h})))
['Duane']
>>> list(ix.findValues('supervisor', t({None: h})))
[<Duane>]
What about transitive searching? Well, you need to tell the index how to
walk the tree. In simple cases like this, the index's
TransposingTransitiveQueriesFactory will do the trick. We just want to tell
the factory to transpose the two keys, None and 'supervisor'. We can then use
it in queries for transitive searches.
>>> factory = index.TransposingTransitiveQueriesFactory(None, 'supervisor')
Who are all of Howie's supervisors transitively (this looks up in the
diagram)?
>>> list(ix.findValueTokens('supervisor', t({None: h}),
... transitiveQueriesFactory=factory))
['Duane', 'Betty', 'Alice']
>>> list(ix.findValues('supervisor', t({None: h}),
... transitiveQueriesFactory=factory))
[<Duane>, <Betty>, <Alice>]
Who are all of the people Betty supervises transitively, breadth first (this
looks down in the diagram)?
>>> people = list(ix.findRelationshipTokens(
... t({'supervisor': b}), transitiveQueriesFactory=factory))
>>> sorted(people[:2])
['Duane', 'Edgar']
>>> people[2]
'Howie'
>>> people = list(ix.findRelationships(
... t({'supervisor': b}), transitiveQueriesFactory=factory))
>>> sorted(people[:2])
[<Duane>, <Edgar>]
>>> people[2]
<Howie>
This transitive search is really the only transitive factory you would want
here, so it probably is safe to wire it in as a default. While most
attributes on the index must be set at instantiation, this happens to be one
we can set after the fact.
>>> ix.defaultTransitiveQueriesFactory = factory
Now all searches are transitive.
>>> list(ix.findValueTokens('supervisor', t({None: h})))
['Duane', 'Betty', 'Alice']
>>> list(ix.findValues('supervisor', t({None: h})))
[<Duane>, <Betty>, <Alice>]
>>> people = list(ix.findRelationshipTokens(t({'supervisor': b})))
>>> sorted(people[:2])
['Duane', 'Edgar']
>>> people[2]
'Howie'
>>> people = list(ix.findRelationships(t({'supervisor': b})))
>>> sorted(people[:2])
[<Duane>, <Edgar>]
>>> people[2]
<Howie>
We can force a non-transitive search, or a specific search depth, with
maxDepth [#needs_a_transitive_queries_factory]_.
.. [#needs_a_transitive_queries_factory] A search with a maxDepth > 1 but
no transitiveQueriesFactory raises an error.
>>> ix.defaultTransitiveQueriesFactory = None
>>> ix.findRelationshipTokens({'supervisor': 'Duane'}, maxDepth=3)
Traceback (most recent call last):
...
ValueError: if maxDepth not in (None, 1), queryFactory must be available
>>> ix.defaultTransitiveQueriesFactory = factory
>>> list(ix.findValueTokens('supervisor', t({None: h}), maxDepth=1))
['Duane']
>>> list(ix.findValues('supervisor', t({None: h}), maxDepth=1))
[<Duane>]
>>> sorted(ix.findRelationshipTokens(t({'supervisor': b}), maxDepth=1))
['Duane', 'Edgar']
>>> sorted(ix.findRelationships(t({'supervisor': b}), maxDepth=1))
[<Duane>, <Edgar>]
Transitive searches can handle recursive loops and have other features as
discussed in the larger example and the interface.
Our last two introductory examples show off three other methods: `isLinked`
`findRelationshipTokenChains` and `findRelationshipChains`.
isLinked lets you answer whether two queries are linked. Is Alice a
supervisor of Howie? What about Chuck? (Note that, if your
relationships describe a hierarchy, searching up a hierarchy is usually
more efficient, so the second pair of questions is generally preferable
to the first in that case.)
>>> ix.isLinked(t({'supervisor': a}), targetQuery=t({None: h}))
True
>>> ix.isLinked(t({'supervisor': c}), targetQuery=t({None: h}))
False
>>> ix.isLinked(t({None: h}), targetQuery=t({'supervisor': a}))
True
>>> ix.isLinked(t({None: h}), targetQuery=t({'supervisor': c}))
False
`findRelationshipTokenChains` and `findRelationshipChains` help you discover
*how* things are transitively related. A "chain" is a transitive path of
relationships. For instance, what's the chain of command between Alice and
Howie?
>>> list(ix.findRelationshipTokenChains(
... t({'supervisor': a}), targetQuery=t({None: h})))
[('Betty', 'Duane', 'Howie')]
>>> list(ix.findRelationshipChains(
... t({'supervisor': a}), targetQuery=t({None: h})))
[(<Betty>, <Duane>, <Howie>)]
This gives you a quick overview of the basic index features. This should be
enough to get you going. Now we'll dig in some more, if you want to know the
details.
Starting the N-Way Examples
===========================
To exercise the index further, we'll come up with a somewhat complex
relationship to index. Let's say we are modeling a generic set-up like
SUBJECT RELATIONSHIPTYPE OBJECT in CONTEXT. This could let you let
users define relationship types, then index them on the fly. The
context can be something like a project, so we could say
"Fred" "has the role of" "Project Manager" on the "zope.org redesign project".
Mapped to the parts of the relationship object, that's
["Fred" (SUBJECT)] ["has the role of" (RELATIONSHIPTYPE)]
["Project Manager" (OBJECT)] on the ["zope.org redesign project" (CONTEXT)].
Without the context, you can still do interesting things like
["Ygritte" (SUBJECT)] ["manages" (RELATIONSHIPTYPE)] ["Uther" (OBJECT)]
In our new example, we'll leverage the fact that the index can accept
interface attributes to index. So let's define a basic interface
without the context, and then an extended interface with the context.
>>> from zope import interface
>>> class IRelationship(interface.Interface):
... subjects = interface.Attribute(
... 'The sources of the relationship; the subject of the sentence')
... relationshiptype = interface.Attribute(
... '''unicode: the single relationship type of this relationship;
... usually contains the verb of the sentence.''')
... objects = interface.Attribute(
... '''the targets of the relationship; usually a direct or
... indirect object in the sentence''')
...
>>> class IContextAwareRelationship(IRelationship):
... def getContext():
... '''return a context for the relationship'''
...
Now we'll create an index. To do that, we must minimally pass in an
iterable describing the indexed values. Each item in the iterable must
either be an interface element (a zope.interface.Attribute or
zope.interface.Method associated with an interface, typically obtained
using a spelling like `IRelationship['subjects']`) or a dict. Each dict
must have either the 'element' key, which is the interface element to be
indexed; or the 'callable' key, which is the callable shown in the
simpler, introductory example above [#there_can_be_only_one]_.
.. [#there_can_be_only_one] instantiating an index with a dictionary containing
both the 'element' and the 'callable' key is an error:
>>> def subjects(obj, index, cache):
... return obj.subjects
...
>>> ix = index.Index(
... ({'element': IRelationship['subjects'],
... 'callable': subjects, 'multiple': True},
... IRelationship['relationshiptype'],
... {'element': IRelationship['objects'], 'multiple': True},
... IContextAwareRelationship['getContext']),
... index.TransposingTransitiveQueriesFactory('subjects', 'objects'))
Traceback (most recent call last):
...
ValueError: cannot provide both callable and element
While we're at it, as you might expect, you must provide one of them.
>>> ix = index.Index(
... ({'multiple': True},
... IRelationship['relationshiptype'],
... {'element': IRelationship['objects'], 'multiple': True},
... IContextAwareRelationship['getContext']),
... index.TransposingTransitiveQueriesFactory('subjects', 'objects'))
Traceback (most recent call last):
...
ValueError: must provide element or callable
It then
can contain other keys to override the default indexing behavior for the
element.
The element's or callable's __name__ will be used to refer to this
element in queries, unless the dict has a 'name' key, which must be a
non-empty string [#name_errors]_.
.. [#name_errors] It's possible to pass a callable without a name, in which
case you must explicitly specify a name.
>>> @total_ordering
... class AttrGetter(object):
... def __init__(self, attr):
... self.attr = attr
... def __eq__(self, other):
... return self is other
... def __lt__(self, other):
... return self.attr < getattr(other, 'attr', other)
... def __call__(self, obj, index, cache):
... return getattr(obj, self.attr, None)
...
>>> subjects = AttrGetter('subjects')
>>> ix = index.Index(
... ({'callable': subjects, 'multiple': True},
... IRelationship['relationshiptype'],
... {'element': IRelationship['objects'], 'multiple': True},
... IContextAwareRelationship['getContext']),
... index.TransposingTransitiveQueriesFactory('subjects', 'objects'))
Traceback (most recent call last):
...
ValueError: no name specified
>>> ix = index.Index(
... ({'callable': subjects, 'multiple': True, 'name': subjects},
... IRelationship['relationshiptype'],
... {'element': IRelationship['objects'], 'multiple': True},
... IContextAwareRelationship['getContext']),
... index.TransposingTransitiveQueriesFactory('subjects', 'objects'))
It's also an error to specify the same name or element twice,
however you do it.
>>> ix = index.Index(
... ({'callable': subjects, 'multiple': True, 'name': 'objects'},
... IRelationship['relationshiptype'],
... {'element': IRelationship['objects'], 'multiple': True},
... IContextAwareRelationship['getContext']),
... index.TransposingTransitiveQueriesFactory('subjects', 'objects'))
... # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: ('name already used', 'objects')
>>> ix = index.Index(
... ({'callable': subjects, 'multiple': True, 'name': 'subjects'},
... IRelationship['relationshiptype'],
... {'callable': subjects, 'multiple': True, 'name': 'objects'},
... IContextAwareRelationship['getContext']),
... index.TransposingTransitiveQueriesFactory('subjects', 'objects'))
... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
ValueError: ('element already indexed',
<zc.relationship.README.AttrGetter object at ...>)
>>> ix = index.Index(
... ({'element': IRelationship['objects'], 'multiple': True,
... 'name': 'subjects'},
... IRelationship['relationshiptype'],
... {'element': IRelationship['objects'], 'multiple': True},
... IContextAwareRelationship['getContext']),
... index.TransposingTransitiveQueriesFactory('subjects', 'objects'))
... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
ValueError: ('element already indexed',
<zope.interface.interface.Attribute object at ...>)
The element is assumed to be a single value, unless the dict has a 'multiple'
key with a value equivalent True. In our example, "subjects" and "objects" are
potentially multiple values, while "relationshiptype" and "getContext" are
single values.
By default, the values for the element will be tokenized and resolved using an
intid utility, and stored in a BTrees.IFBTree. This is a good choice if you
want to make object tokens easily mergable with typical Zope 3 catalog
results. If you need different behavior for any element, you can specify
three keys per dict:
- 'dump', the tokenizer, a callable taking (obj, index, cache) and returning a
token;
- 'load' the token resolver, a callable taking (token, index, cache) to return
the object which the token represents; and
- 'btree', the btree module to use to store and process the tokens, such as
BTrees.OOBTree.
If you provide a custom 'dump' you will almost certainly need to provide a
custom 'load'; and if your tokens are not integers then you will need to
specify a different 'btree' (either BTrees.OOBTree or BTrees.OIBTree, as of
this writing).
The tokenizing function ('dump') *must* return homogenous, immutable tokens:
that is, any given tokenizer should only return tokens that sort
unambiguously, across Python versions, which usually mean that they are all of
the same type. For instance, a tokenizer should only return ints, or only
return strings, or only tuples of strings, and so on. Different tokenizers
used for different elements in the same index may return different types. They
also may return the same value as the other tokenizers to mean different
objects: the stores are separate.
Note that both dump and load may also be explicitly None in the dictionary:
this will mean that the values are already appropriate to be used as tokens.
It enables an optimization described in the
`Optimizing relationship index use`_ section [#neither_or_both]_.
.. [#neither_or_both] It is not allowed to provide only one or the other of
'load' and 'dump'.
>>> ix = index.Index(
... ({'element': IRelationship['subjects'], 'multiple': True,
... 'name': 'subjects','dump': None},
... IRelationship['relationshiptype'],
... {'element': IRelationship['objects'], 'multiple': True},
... IContextAwareRelationship['getContext']),
... index.TransposingTransitiveQueriesFactory('subjects', 'objects'))
... # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: either both of 'dump' and 'load' must be None, or neither
>>> ix = index.Index(
... ({'element': IRelationship['objects'], 'multiple': True,
... 'name': 'subjects','load': None},
... IRelationship['relationshiptype'],
... {'element': IRelationship['objects'], 'multiple': True},
... IContextAwareRelationship['getContext']),
... index.TransposingTransitiveQueriesFactory('subjects', 'objects'))
... # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: either both of 'dump' and 'load' must be None, or neither
In addition to the one required argument to the class, the signature contains
four optional arguments. The 'defaultTransitiveQueriesFactory' is the next,
and allows you to specify a callable as described in
interfaces.ITransitiveQueriesFactory. Without it transitive searches will
require an explicit factory every time, which can be tedious. The index
package provides a simple implementation that supports transitive searches
following two indexed elements (TransposingTransitiveQueriesFactory) and this
document describes more complex possible transitive behaviors that can be
modeled. For our example, "subjects" and "objects" are the default transitive
fields, so if Ygritte (SUBJECT) manages Uther (OBJECT), and Uther (SUBJECT)
manages Emily (OBJECT), a search for all those transitively managed by Ygritte
will transpose Uther from OBJECT to SUBJECT and find that Uther manages Emily.
Similarly, to find all transitive managers of Emily, Uther will change place
from SUBJECT to OBJECT in the search [#TransposingTransitiveQueriesFactory]_.
.. [#TransposingTransitiveQueriesFactory] The factory lets you specify two
names, which are transposed for transitive walks. This is usually what
you want for a hierarchy and similar variations: as the text describes
later, more complicated traversal might be desired in more complicated
relationships, as found in genealogy.
It supports both transposing values and relationship tokens, as seen in
the text.
In this footnote, we'll explore the factory in the small, with index
stubs.
>>> factory = index.TransposingTransitiveQueriesFactory(
... 'subjects', 'objects')
>>> class StubIndex(object):
... def findValueTokenSet(self, rel, name):
... return {
... ('foo', 'objects'): ('bar',),
... ('bar', 'subjects'): ('foo',)}[(rel, name)]
...
>>> ix = StubIndex()
>>> list(factory(['foo'], {'subjects': 'foo'}, ix, {}))
[{'subjects': 'bar'}]
>>> list(factory(['bar'], {'objects': 'bar'}, ix, {}))
[{'objects': 'foo'}]
If you specify both fields then it won't transpose.
>>> list(factory(['foo'], {'objects': 'bar', 'subjects': 'foo'}, ix, {}))
[]
If you specify additional fields then it keeps them statically.
>>> list(factory(['foo'], {'subjects': 'foo', 'getContext': 'shazam'},
... ix, {})) == [{'subjects': 'bar', 'getContext': 'shazam'}]
True
The next three arguments, 'dumpRel', 'loadRel' and 'relFamily', have
to do with the relationship tokens. The default values assume that you will
be using intid tokens for the relationships, and so 'dumpRel' and
'loadRel' tokenize and resolve, respectively, using the intid utility; and
'relFamily' defaults to BTrees.IFBTree.
If relationship tokens (from 'findRelationshipChains' or 'apply' or
'findRelationshipTokenSet', or in a filter to most of the search methods) are
to be merged with other catalog results, relationship tokens should be based
on intids, as in the default. For instance, if some relationships are only
available to some users on the basis of security, and you keep an index of
this, then you will want to use a filter based on the relationship tokens
viewable by the current user as kept by the catalog index.
If you are unable or unwilling to use intid relationship tokens, tokens must
still be homogenous and immutable as described above for indexed values tokens.
The last argument is 'family', which effectively defaults to BTrees.family32.
If you don't expicitly specify BTree modules for your value and relationship
sets, this value will determine whether you use the 32 bit or the 64 bit
IFBTrees [#family64]_.
.. [#family64] Here's an example of specifying the family64. This is a "white
box" demonstration that looks at some of the internals.
>>> ix = index.Index( # 32 bit default
... ({'element': IRelationship['subjects'], 'multiple': True},
... IRelationship['relationshiptype'],
... {'element': IRelationship['objects'], 'multiple': True},
... IContextAwareRelationship['getContext']),
... index.TransposingTransitiveQueriesFactory('subjects', 'objects'))
>>> ix._relTools['BTree'] is BTrees.family32.IF.BTree
True
>>> ix._attrs['subjects']['BTree'] is BTrees.family32.IF.BTree
True
>>> ix._attrs['objects']['BTree'] is BTrees.family32.IF.BTree
True
>>> ix._attrs['getContext']['BTree'] is BTrees.family32.IF.BTree
True
>>> ix = index.Index( # explicit 32 bit
... ({'element': IRelationship['subjects'], 'multiple': True},
... IRelationship['relationshiptype'],
... {'element': IRelationship['objects'], 'multiple': True},
... IContextAwareRelationship['getContext']),
... index.TransposingTransitiveQueriesFactory('subjects', 'objects'),
... family=BTrees.family32)
>>> ix._relTools['BTree'] is BTrees.family32.IF.BTree
True
>>> ix._attrs['subjects']['BTree'] is BTrees.family32.IF.BTree
True
>>> ix._attrs['objects']['BTree'] is BTrees.family32.IF.BTree
True
>>> ix._attrs['getContext']['BTree'] is BTrees.family32.IF.BTree
True
>>> ix = index.Index( # explicit 64 bit
... ({'element': IRelationship['subjects'], 'multiple': True},
... IRelationship['relationshiptype'],
... {'element': IRelationship['objects'], 'multiple': True},
... IContextAwareRelationship['getContext']),
... index.TransposingTransitiveQueriesFactory('subjects', 'objects'),
... family=BTrees.family64)
>>> ix._relTools['BTree'] is BTrees.family64.IF.BTree
True
>>> ix._attrs['subjects']['BTree'] is BTrees.family64.IF.BTree
True
>>> ix._attrs['objects']['BTree'] is BTrees.family64.IF.BTree
True
>>> ix._attrs['getContext']['BTree'] is BTrees.family64.IF.BTree
True
If we had an IIntId utility registered and wanted to use the defaults, then
instantiation of an index for our relationship would look like this:
>>> ix = index.Index(
... ({'element': IRelationship['subjects'], 'multiple': True},
... IRelationship['relationshiptype'],
... {'element': IRelationship['objects'], 'multiple': True},
... IContextAwareRelationship['getContext']),
... index.TransposingTransitiveQueriesFactory('subjects', 'objects'))
That's the simple case. With relatively little fuss, we have an IIndex, and a
defaultTransitiveQueriesFactory, implementing ITransitiveQueriesFactory, that
switches subjects and objects as described above.
>>> from zc.relationship import interfaces
>>> from zope.interface.verify import verifyObject
>>> verifyObject(interfaces.IIndex, ix)
True
>>> verifyObject(
... interfaces.ITransitiveQueriesFactory,
... ix.defaultTransitiveQueriesFactory)
True
For the purposes of a more complex example, though, we are going to exercise
more of the index's options--we'll use at least one of 'name', 'dump', 'load',
and 'btree'.
- 'subjects' and 'objects' will use a custom integer-based token generator.
They will share tokens, which will let us use the default
TransposingTransitiveQueriesFactory. We can keep using the IFBTree sets,
because the tokens are still integers.
- 'relationshiptype' will use a name 'reltype' and will just use the unicode
value as the token, without translation but with a registration check.
- 'getContext' will use a name 'context' but will continue to use the intid
utility and use the names from their interface. We will see later that
making transitive walks between different token sources must be handled with
care.
We will also use the intid utility to resolve relationship tokens. See the
relationship container (and container.rst) for examples of changing the
relationship type, especially in keyref.py.
Here are the methods we'll use for the 'subjects' and 'objects' tokens,
followed by the methods we'll use for the 'relationshiptypes' tokens.
>>> lookup = {}
>>> counter = [0]
>>> prefix = '_z_token__'
>>> def dump(obj, index, cache):
... assert (interfaces.IIndex.providedBy(index) and
... isinstance(cache, dict)), (
... 'did not receive correct arguments')
... token = getattr(obj, prefix, None)
... if token is None:
... token = counter[0]
... counter[0] += 1
... if counter[0] >= 2147483647:
... raise RuntimeError("Whoa! That's a lot of ids!")
... assert token not in lookup
... setattr(obj, prefix, token)
... lookup[token] = obj
... return token
...
>>> def load(token, index, cache):
... assert (interfaces.IIndex.providedBy(index) and
... isinstance(cache, dict)), (
... 'did not receive correct arguments')
... return lookup[token]
...
>>> relTypes = []
>>> def relTypeDump(obj, index, cache):
... assert obj in relTypes, 'unknown relationshiptype'
... return obj
...
>>> def relTypeLoad(token, index, cache):
... assert token in relTypes, 'unknown relationshiptype'
... return token
...
Note that these implementations are completely silly if we actually cared about
ZODB-based persistence: to even make it half-acceptable we should make the
counter, lookup, and and relTypes persistently stored somewhere using a
reasonable persistent data structure. This is just a demonstration example.
Now we can make an index.
As in our initial example, we are going to use the simple transitive query
factory defined in the index module for our default transitive behavior: when
you want to do transitive searches, transpose 'subjects' with 'objects' and
keep everything else; and if both subjects and objects are provided, don't do
any transitive search.
>>> from BTrees import OIBTree # could also be OOBTree
>>> ix = index.Index(
... ({'element': IRelationship['subjects'], 'multiple': True,
... 'dump': dump, 'load': load},
... {'element': IRelationship['relationshiptype'],
... 'dump': relTypeDump, 'load': relTypeLoad, 'btree': OIBTree,
... 'name': 'reltype'},
... {'element': IRelationship['objects'], 'multiple': True,
... 'dump': dump, 'load': load},
... {'element': IContextAwareRelationship['getContext'],
... 'name': 'context'}),
... index.TransposingTransitiveQueriesFactory('subjects', 'objects'))
We'll want to put the index somewhere in the system so it can find the intid
utility. We'll add it as a utility just as part of the example. As long as
the index has a valid __parent__ that is itself connected transitively to a
site manager with the desired intid utility, everything should work fine, so
no need to install it as utility. This is just an example.
>>> from zope import interface
>>> sm = app.getSiteManager()
>>> sm['rel_index'] = ix
>>> import zope.interface.interfaces
>>> registry = zope.interface.interfaces.IComponentRegistry(sm)
>>> registry.registerUtility(ix, interfaces.IIndex)
>>> import transaction
>>> transaction.commit()
Now we'll create some representative objects that we can relate, and create
and index our first example relationship.
In the example, note that the context will only be available as an adapter to
ISpecialRelationship objects: the index tries to adapt objects to the
appropriate interface, and considers the value to be empty if it cannot adapt.
>>> import persistent
>>> from zope.app.container.contained import Contained
>>> class Base(persistent.Persistent, Contained):
... def __init__(self, name):
... self.name = name
... def __repr__(self):
... return '<%s %r>' % (self.__class__.__name__, self.name)
...
>>> class Person(Base): pass
...
>>> class Role(Base): pass
...
>>> class Project(Base): pass
...
>>> class Company(Base): pass
...
>>> @interface.implementer(IRelationship)
... class Relationship(persistent.Persistent, Contained):
... def __init__(self, subjects, relationshiptype, objects):
... self.subjects = subjects
... assert relationshiptype in relTypes
... self.relationshiptype = relationshiptype
... self.objects = objects
... def __repr__(self):
... return '<%r %s %r>' % (
... self.subjects, self.relationshiptype, self.objects)
...
>>> class ISpecialRelationship(interface.Interface):
... pass
...
>>> from zope import component
>>> @component.adapter(ISpecialRelationship)
... @interface.implementer(IContextAwareRelationship)
... class ContextRelationshipAdapter(object):
... def __init__(self, adapted):
... self.adapted = adapted
... def getContext(self):
... return getattr(self.adapted, '_z_context__', None)
... def setContext(self, value):
... self.adapted._z_context__ = value
... def __getattr__(self, name):
... return getattr(self.adapted, name)
...
>>> component.provideAdapter(ContextRelationshipAdapter)
>>> @interface.implementer(ISpecialRelationship)
... class SpecialRelationship(Relationship):
... pass
...
>>> people = {}
>>> for p in ['Abe', 'Bran', 'Cathy', 'David', 'Emily', 'Fred', 'Gary',
... 'Heather', 'Ingrid', 'Jim', 'Karyn', 'Lee', 'Mary',
... 'Nancy', 'Olaf', 'Perry', 'Quince', 'Rob', 'Sam', 'Terry',
... 'Uther', 'Van', 'Warren', 'Xen', 'Ygritte', 'Zane']:
... app[p] = people[p] = Person(p)
...
>>> relTypes.extend(
... ['has the role of', 'manages', 'taught', 'commissioned'])
>>> roles = {}
>>> for r in ['Project Manager', 'Software Engineer', 'Designer',
... 'Systems Administrator', 'Team Leader', 'Mascot']:
... app[r] = roles[r] = Role(r)
...
>>> projects = {}
>>> for p in ['zope.org redesign', 'Zope 3 manual',
... 'improved test coverage', 'Vault design and implementation']:
... app[p] = projects[p] = Project(p)
...
>>> companies = {}
>>> for c in ['Ynod Corporation', 'HAL, Inc.', 'Zookd']:
... app[c] = companies[c] = Company(c)
...
>>> app['fredisprojectmanager'] = rel = SpecialRelationship(
... (people['Fred'],), 'has the role of', (roles['Project Manager'],))
>>> IContextAwareRelationship(rel).setContext(
... projects['zope.org redesign'])
>>> ix.index(rel)
>>> transaction.commit()
Token conversion
================
Before we examine the searching features, we should quickly discuss the
tokenizing API on the index. All search queries must use value tokens, and
search results can sometimes be value or relationship tokens. Therefore
converting between tokens and real values can be important. The index
provides a number of conversion methods for this purpose.
Arguably the most important is `tokenizeQuery`: it takes a query, in which
each key and value are the name of an indexed value and an actual value,
respectively; and returns a query in which the actual values have been
converted to tokens. For instance, consider the following example. It's a
bit hard to show the conversion reliably (we can't know what the intid tokens
will be, for instance) so we just show that the result's values are tokenized
versions of the inputs.
>>> res = ix.tokenizeQuery(
... {'objects': roles['Project Manager'],
... 'context': projects['zope.org redesign']})
>>> res['objects'] == dump(roles['Project Manager'], ix, {})
True
>>> from zope.app.intid.interfaces import IIntIds
>>> intids = component.getUtility(IIntIds, context=ix)
>>> res['context'] == intids.getId(projects['zope.org redesign'])
True
Tokenized queries can be resolved to values again using resolveQuery.
>>> sorted(ix.resolveQuery(res).items()) # doctest: +NORMALIZE_WHITESPACE
[('context', <Project 'zope.org redesign'>),
('objects', <Role 'Project Manager'>)]
Other useful conversions are `tokenizeValues`, which returns an iterable of
tokens for the values of the given index name;
>>> examples = (people['Abe'], people['Bran'], people['Cathy'])
>>> res = list(ix.tokenizeValues(examples, 'subjects'))
>>> res == [dump(o, ix, {}) for o in examples]
True
`resolveValueTokens`, which returns an iterable of values for the tokens of
the given index name;
>>> list(ix.resolveValueTokens(res, 'subjects'))
[<Person 'Abe'>, <Person 'Bran'>, <Person 'Cathy'>]
`tokenizeRelationship`, which returns a token for the given relationship;
>>> res = ix.tokenizeRelationship(rel)
>>> res == intids.getId(rel)
True
`resolveRelationshipToken`, which returns a relationship for the given token;
>>> ix.resolveRelationshipToken(res) is rel
True
`tokenizeRelationships`, which returns an iterable of tokens for the relations
given; and
>>> app['another_rel'] = another_rel = Relationship(
... (companies['Ynod Corporation'],), 'commissioned',
... (projects['Vault design and implementation'],))
>>> res = list(ix.tokenizeRelationships((another_rel, rel)))
>>> res == [intids.getId(r) for r in (another_rel, rel)]
True
`resolveRelationshipTokens`, which returns an iterable of relations for the
tokens given.
>>> list(ix.resolveRelationshipTokens(res)) == [another_rel, rel]
True
Basic searching
===============
Now we move to the meat of the interface: searching. The index interface
defines several searching methods:
- `findValues` and `findValueTokens` ask "to what is this related?";
- `findRelationshipChains` and `findRelationshipTokenChains` ask "how is this
related?", especially for transitive searches;
- `isLinked` asks "does a relationship like this exist?";
- `findRelationshipTokenSet` asks "what are the intransitive relationships
that match my query?" and is particularly useful for low-level usage of the
index data structures;
- `findRelationships` asks the same question, but returns an iterable of
relationships rather than a set of tokens;
- `findValueTokenSet` asks "what are the value tokens for this particular
indexed name and this relationship token?" and is useful for low-level
usage of the index data structures such as transitive query factories; and
- the standard zope.index method `apply` essentially exposes the
`findRelationshipTokenSet` and `findValueTokens` methods via a query object
spelling.
`findRelationshipChains` and `findRelationshipTokenChains` are paired methods,
doing the same work but with and without resolving the resulting tokens; and
`findValues` and `findValueTokens` are also paired in the same way.
It is very important to note that all queries must use tokens, not actual
objects. As introduced above, the index provides a method to ease that
requirement, in the form of a `tokenizeQuery` method that converts a dict with
objects to a dict with tokens. You'll see below that we shorten our calls by
stashing `tokenizeQuery` away in the 'q' name.
>>> q = ix.tokenizeQuery
We have indexed our first example relationship--"Fred has the role of project
manager in the zope.org redesign"--so we can search for it. We'll first look
at `findValues` and `findValueTokens`. Here, we ask 'who has the role of
project manager in the zope.org redesign?'. We do it first with findValues
and then with findValueTokens [#findValue_errors]_.
.. [#findValue_errors] `findValueTokens` and `findValues` raise errors if
you try to get a value that is not indexed.
>>> list(ix.findValues(
... 'folks',
... q({'reltype': 'has the role of',
... 'objects': roles['Project Manager'],
... 'context': projects['zope.org redesign']})))
Traceback (most recent call last):
...
ValueError: ('name not indexed', 'folks')
>>> list(ix.findValueTokens(
... 'folks',
... q({'reltype': 'has the role of',
... 'objects': roles['Project Manager'],
... 'context': projects['zope.org redesign']})))
Traceback (most recent call last):
...
ValueError: ('name not indexed', 'folks')
>>> list(ix.findValues(
... 'subjects',
... q({'reltype': 'has the role of',
... 'objects': roles['Project Manager'],
... 'context': projects['zope.org redesign']})))
[<Person 'Fred'>]
>>> [load(t, ix, {}) for t in ix.findValueTokens(
... 'subjects',
... q({'reltype': 'has the role of',
... 'objects': roles['Project Manager'],
... 'context': projects['zope.org redesign']}))]
[<Person 'Fred'>]
If you don't pass a query to these methods, you get all indexed values for the
given name in a BTree (don't modify this! this is an internal data structure--
we pass it out directly because you can do efficient things with it with BTree
set operations). In this case, we've only indexed a single relationship,
so its subjects are the subjects in this result.
>>> res = ix.findValueTokens('subjects', maxDepth=1)
>>> res # doctest: +ELLIPSIS
<BTrees.IOBTree.IOBTree object at ...>
>>> [load(t, ix, {}) for t in res]
[<Person 'Fred'>]
If we want to find all the relationships for which Fred is a subject, we can
use `findRelationshipTokenSet`. It, combined with `findValueTokenSet`, is
useful for querying the index data structures at a fairly low level, when you
want to use the data in a way that the other search methods don't support.
`findRelationshipTokenSet`, given a single dictionary of {indexName: token},
returns a set (based on the btree family for relationships in the index) of
relationship tokens that match it, intransitively.
>>> res = ix.findRelationshipTokenSet(q({'subjects': people['Fred']}))
>>> res # doctest: +ELLIPSIS
<BTrees.IFBTree.IFTreeSet object at ...>
>>> [intids.getObject(t) for t in res]
[<(<Person 'Fred'>,) has the role of (<Role 'Project Manager'>,)>]
It is in fact equivalent to `findRelationshipTokens` called without
transitivity and without any filtering.
>>> res2 = ix.findRelationshipTokens(
... q({'subjects': people['Fred']}), maxDepth=1)
>>> res2 is res
True
The `findRelationshipTokenSet` method always returns a set, even if the
query does not have any results.
>>> res = ix.findRelationshipTokenSet(q({'subjects': people['Ygritte']}))
>>> res # doctest: +ELLIPSIS
<BTrees.IFBTree.IFTreeSet object at ...>
>>> list(res)
[]
An empty query returns all relationships in the index (this is true of other
search methods as well).
>>> res = ix.findRelationshipTokenSet({})
>>> res # doctest: +ELLIPSIS
<BTrees.IFBTree.IFTreeSet object at ...>
>>> len(res) == ix.documentCount()
True
>>> for r in ix.resolveRelationshipTokens(res):
... if r not in ix:
... print('oops')
... break
... else:
... print('correct')
...
correct
`findRelationships` can do the same thing but with resolving the relationships.
>>> list(ix.findRelationships(q({'subjects': people['Fred']})))
[<(<Person 'Fred'>,) has the role of (<Role 'Project Manager'>,)>]
However, like `findRelationshipTokens` and unlike
`findRelationshipTokenSet`, `findRelationships` can be used
transitively, as shown in the introductory section of this document.
`findValueTokenSet`, given a relationship token and a value name, returns a
set (based on the btree family for the value) of value tokens for that
relationship.
>>> src = ix.findRelationshipTokenSet(q({'subjects': people['Fred']}))
>>> res = ix.findValueTokenSet(list(src)[0], 'subjects')
>>> res # doctest: +ELLIPSIS
<BTrees.IFBTree.IFTreeSet object at ...>
>>> [load(t, ix, {}) for t in res]
[<Person 'Fred'>]
Like `findRelationshipTokenSet` and `findRelationshipTokens`,
`findValueTokenSet` is equivalent to `findValueTokens` without a
transitive search or filtering.
>>> res2 = ix.findValueTokenSet(list(src)[0], 'subjects')
>>> res2 is res
True
The apply method, part of the zope.index.interfaces.IIndexSearch interface,
can essentially only duplicate the `findValueTokens` and
`findRelationshipTokenSet` search calls. The only additional functionality
is that the results always are IFBTree sets: if the tokens requested are not
in an IFBTree set (on the basis of the 'btree' key during instantiation, for
instance) then the index raises a ValueError. A wrapper dict specifies the
type of search with the key, and the value should be the arguments for the
search.
Here, we ask for the current known roles on the zope.org redesign.
>>> res = ix.apply({'values':
... {'resultName': 'objects', 'query':
... q({'reltype': 'has the role of',
... 'context': projects['zope.org redesign']})}})
>>> res # doctest: +ELLIPSIS
IFSet([...])
>>> [load(t, ix, {}) for t in res]
[<Role 'Project Manager'>]
Ideally, this would fail, because the tokens, while integers, are not actually
mergable with a intid-based catalog results. However, the index only complains
if it can tell that the returning set is not an IFTreeSet or IFSet.
Here, we ask for the relationships that have the 'has the role of' type.
>>> res = ix.apply({'relationships':
... q({'reltype': 'has the role of'})})
>>> res # doctest: +ELLIPSIS
<BTrees.IFBTree.IFTreeSet object at ...>
>>> [intids.getObject(t) for t in res]
[<(<Person 'Fred'>,) has the role of (<Role 'Project Manager'>,)>]
Here, we ask for the known relationships types for the zope.org redesign. It
will fail, because the result cannot be expressed as an IFBTree.IFTreeSet.
>>> res = ix.apply({'values':
... {'resultName': 'reltype', 'query':
... q({'context': projects['zope.org redesign']})}})
... # doctest: +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
ValueError: cannot fulfill `apply` interface because cannot return an
(I|L)FBTree-based result
The same kind of error will be raised if you request relationships and the
relationships are not stored in IFBTree or LFBTree structures [#apply_errors]_.
.. [#apply_errors] Only one key may be in the dictionary.
>>> res = ix.apply({'values':
... {'resultName': 'objects', 'query':
... q({'reltype': 'has the role of',
... 'context': projects['zope.org redesign']})},
... 'relationships': q({'reltype': 'has the role of'})})
Traceback (most recent call last):
...
ValueError: one key in the primary query dictionary
The keys must be one of 'values' or 'relationships'.
>>> res = ix.apply({'kumquats':
... {'resultName': 'objects', 'query':
... q({'reltype': 'has the role of',
... 'context': projects['zope.org redesign']})}})
Traceback (most recent call last):
...
ValueError: ('unknown query type', 'kumquats')
If a relationship uses LFBTrees, searches are fine.
>>> ix2 = index.Index( # explicit 64 bit
... ({'element': IRelationship['subjects'], 'multiple': True},
... IRelationship['relationshiptype'],
... {'element': IRelationship['objects'], 'multiple': True},
... IContextAwareRelationship['getContext']),
... index.TransposingTransitiveQueriesFactory('subjects', 'objects'),
... family=BTrees.family64)
>>> list(ix2.apply({'values':
... {'resultName': 'objects', 'query':
... q({'subjects': people['Gary']})}}))
[]
>>> list(ix2.apply({'relationships':
... q({'subjects': people['Gary']})}))
[]
But, as with shown in the main text for values, if you are using another
BTree module for relationships, you'll get an error.
>>> ix2 = index.Index( # explicit 64 bit
... ({'element': IRelationship['subjects'], 'multiple': True},
... IRelationship['relationshiptype'],
... {'element': IRelationship['objects'], 'multiple': True},
... IContextAwareRelationship['getContext']),
... index.TransposingTransitiveQueriesFactory('subjects', 'objects'),
... relFamily=BTrees.OIBTree)
>>> list(ix2.apply({'relationships':
... q({'subjects': people['Gary']})}))
Traceback (most recent call last):
...
ValueError: cannot fulfill `apply` interface because cannot return an (I|L)FBTree-based result
The last basic search methods, `isLinked`, `findRelationshipTokenChains`, and
`findRelationshipChains`, are most useful for transitive searches. We
have not yet created any relationships that we can use transitively. They
still will work with intransitive searches, so we will demonstrate them here
as an introduction, then discuss them more below when we introduce transitive
relationships.
`findRelationshipChains` and `findRelationshipTokenChains` let you find
transitive relationship paths. Right now a single relationship--a single
point--can't create much of a line. So first, here's a somewhat useless
example:
>>> [[intids.getObject(t) for t in path] for path in
... ix.findRelationshipTokenChains(
... q({'reltype': 'has the role of'}))]
... # doctest: +NORMALIZE_WHITESPACE
[[<(<Person 'Fred'>,) has the role of (<Role 'Project Manager'>,)>]]
That's useless, because there's no chance of it being a transitive search, and
so you might as well use findRelationshipTokenSet. This will become more
interesting later on.
Here's the same example with findRelationshipChains, which resolves the
relationship tokens itself.
>>> list(ix.findRelationshipChains(q({'reltype': 'has the role of'})))
... # doctest: +NORMALIZE_WHITESPACE
[(<(<Person 'Fred'>,) has the role of (<Role 'Project Manager'>,)>,)]
`isLinked` returns a boolean if there is at least one path that matches the
search--in fact, the implementation is essentially ::
try:
iter(ix.findRelationshipTokenChains(...args...)).next()
except StopIteration:
return False
else:
return True
So, we can say
>>> ix.isLinked(q({'subjects': people['Fred']}))
True
>>> ix.isLinked(q({'subjects': people['Gary']}))
False
>>> ix.isLinked(q({'subjects': people['Fred'],
... 'reltype': 'manages'}))
False
This is reasonably useful as is, to test basic assertions. It also works with
transitive searches, as we will see below.
An even simpler example
-----------------------
(This was added to test that searching for a simple relationship works
even when the transitive query factory is not set.)
Let's create a very simple relation type, using strings as the source
and target types:
>>> class IStringRelation(interface.Interface):
... name = interface.Attribute("The name of the value.")
... value = interface.Attribute("The value associated with the name.")
>>> @interface.implementer(IStringRelation)
... class StringRelation(persistent.Persistent, Contained):
...
... def __init__(self, name, value):
... self.name = name
... self.value = value
>>> app[u"string-relation-1"] = StringRelation("name1", "value1")
>>> app[u"string-relation-2"] = StringRelation("name2", "value2")
>>> transaction.commit()
We can now create an index that uses these:
>>> from BTrees import OOBTree
>>> sx = index.Index(
... ({"element": IStringRelation["name"],
... "load": None, "dump": None, "btree": OOBTree},
... {"element": IStringRelation["value"],
... "load": None, "dump": None, "btree": OOBTree},
... ))
>>> app["sx"] = sx
>>> transaction.commit()
And we'll add the relations to the index:
>>> app["sx"].index(app["string-relation-1"])
>>> app["sx"].index(app["string-relation-2"])
Getting a relationship back out should be very simple. Let's look for
all the values associates with "name1":
>>> query = sx.tokenizeQuery({"name": "name1"})
>>> list(sx.findValues("value", query))
['value1']
Searching for empty sets
------------------------
We've examined the most basic search capabilities. One other feature of the
index and search is that one can search for relationships to an empty set, or,
for single-value relationships like 'reltype' and 'context' in our
examples, None.
Let's add a relationship with a 'manages' relationshiptype, and no context; and
a relationship with a 'commissioned' relationship type, and a company context.
Notice that there are two ways of adding indexes, by the way. We have already
seen that the index has an 'index' method that takes a relationship. Here we
use 'index_doc' which is a method defined in zope.index.interfaces.IInjection
that requires the token to already be generated. Since we are using intids
to tokenize the relationships, we must add them to the ZODB app object to give
them the possibility of a connection.
>>> app['abeAndBran'] = rel = Relationship(
... (people['Abe'],), 'manages', (people['Bran'],))
>>> ix.index_doc(intids.register(rel), rel)
>>> app['abeAndVault'] = rel = SpecialRelationship(
... (people['Abe'],), 'commissioned',
... (projects['Vault design and implementation'],))
>>> IContextAwareRelationship(rel).setContext(companies['Zookd'])
>>> ix.index_doc(intids.register(rel), rel)
Now we can search for Abe's relationship that does not have a context. The
None value is always used to match both an empty set and a single `None` value.
The index does not support any other "empty" values at this time.
>>> sorted(
... repr(load(t, ix, {})) for t in ix.findValueTokens(
... 'objects',
... q({'subjects': people['Abe']})))
["<Person 'Bran'>", "<Project 'Vault design and implementation'>"]
>>> [load(t, ix, {}) for t in ix.findValueTokens(
... 'objects', q({'subjects': people['Abe'], 'context': None}))]
[<Person 'Bran'>]
>>> sorted(
... repr(v) for v in ix.findValues(
... 'objects',
... q({'subjects': people['Abe']})))
["<Person 'Bran'>", "<Project 'Vault design and implementation'>"]
>>> list(ix.findValues(
... 'objects', q({'subjects': people['Abe'], 'context': None})))
[<Person 'Bran'>]
Note that the index does not currently support searching for relationships that
have any value, or one of a set of values. This may be added at a later date;
the spelling for such queries are among the more troublesome parts.
Working with transitive searches
================================
It's possible to do transitive searches as well. This can let you find all
transitive bosses, or transitive subordinates, in our 'manages' relationship
type. Let's set up some example relationships. Using letters to represent our
people, we'll create three hierarchies like this::
A JK R
/ \ / \
B C LM NOP S T U
/ \ | | /| | \
D E F Q V W X |
| | \--Y
H G |
| Z
I
This means that, for instance, person "A" ("Abe") manages "B" ("Bran") and "C"
("Cathy").
We already have a relationship from Abe to Bran, so we'll only be adding the
rest.
>>> relmap = (
... ('A', 'C'), ('B', 'D'), ('B', 'E'), ('C', 'F'),
... ('F', 'G'), ('D', 'H'), ('H', 'I'), ('JK', 'LM'), ('JK', 'NOP'),
... ('LM', 'Q'), ('R', 'STU'), ('S', 'VW'), ('T', 'X'), ('UX', 'Y'),
... ('Y', 'Z'))
>>> letters = dict((name[0], ob) for name, ob in people.items())
>>> for subs, obs in relmap:
... subs = tuple(letters[l] for l in subs)
... obs = tuple(letters[l] for l in obs)
... app['%sManages%s' % (''.join(o.name for o in subs),
... ''.join(o.name for o in obs))] = rel = (
... Relationship(subs, 'manages', obs))
... ix.index(rel)
...
Now we can do both transitive and intransitive searches. Here are a few
examples.
>>> [load(t, ix, {}) for t in ix.findValueTokens(
... 'subjects',
... q({'objects': people['Ingrid'],
... 'reltype': 'manages'}))
... ]
[<Person 'Heather'>, <Person 'David'>, <Person 'Bran'>, <Person 'Abe'>]
Here's the same thing using findValues.
>>> list(ix.findValues(
... 'subjects',
... q({'objects': people['Ingrid'],
... 'reltype': 'manages'})))
[<Person 'Heather'>, <Person 'David'>, <Person 'Bran'>, <Person 'Abe'>]
Notice that they are in order, walking away from the search start. It also
is breadth-first--for instance, look at the list of superiors to Zane: Xen and
Uther come before Rob and Terry.
>>> res = list(ix.findValues(
... 'subjects',
... q({'objects': people['Zane'], 'reltype': 'manages'})))
>>> res[0]
<Person 'Ygritte'>
>>> sorted(repr(p) for p in res[1:3])
["<Person 'Uther'>", "<Person 'Xen'>"]
>>> sorted(repr(p) for p in res[3:])
["<Person 'Rob'>", "<Person 'Terry'>"]
Notice that all the elements of the search are maintained as it is walked--only
the transposed values are changed, and the rest remain statically. For
instance, notice the difference between these two results.
>>> [load(t, ix, {}) for t in ix.findValueTokens(
... 'objects',
... q({'subjects': people['Cathy'], 'reltype': 'manages'}))]
[<Person 'Fred'>, <Person 'Gary'>]
>>> res = [load(t, ix, {}) for t in ix.findValueTokens(
... 'objects',
... q({'subjects': people['Cathy']}))]
>>> res[0]
<Person 'Fred'>
>>> sorted(repr(i) for i in res[1:])
["<Person 'Gary'>", "<Role 'Project Manager'>"]
The first search got what we expected for our management relationshiptype--
walking from Cathy, the relationshiptype was maintained, and we only got the
Gary subordinate. The second search didn't specify the relationshiptype, so
the transitive search included the Role we added first (Fred has the role of
Project Manager for the zope.org redesign).
The `maxDepth` argument allows control over how far to search. For instance,
if we only want to search for Bran's subordinates a maximum of two steps deep,
we can do so:
>>> res = [load(t, ix, {}) for t in ix.findValueTokens(
... 'objects',
... q({'subjects': people['Bran']}),
... maxDepth=2)]
>>> sorted(repr(i) for i in res)
["<Person 'David'>", "<Person 'Emily'>", "<Person 'Heather'>"]
The same is true for findValues.
>>> res = list(ix.findValues(
... 'objects',
... q({'subjects': people['Bran']}), maxDepth=2))
>>> sorted(repr(i) for i in res)
["<Person 'David'>", "<Person 'Emily'>", "<Person 'Heather'>"]
A minimum depth--a number of relationships that must be traversed before
results are desired--can also be achieved trivially using the targetFilter
argument described soon below. For now, we will continue in the order of the
arguments list, so `filter` is up next.
The `filter` argument takes an object (such as a function) that provides
interfaces.IFilter. As the interface lists, it receives the current chain
of relationship tokens ("relchain"), the original query that started the search
("query"), the index object ("index"), and a dictionary that will be used
throughout the search and then discarded that can be used for optimizations
("cache"). It should return a boolean, which determines whether the given
relchain should be used at all--traversed or returned. For instance, if
security dictates that the current user can only see certain relationships,
the filter could be used to make only the available relationships traversable.
Other uses are only getting relationships that were created after a given time,
or that have some annotation (available after resolving the token).
Let's look at an example of a filter that only allows relationships in a given
set, the way a security-based filter might work. We'll then use it to model
a situation in which the current user can't see that Ygritte is managed by
Uther, in addition to Xen.
>>> s = set(intids.getId(r) for r in app.values()
... if IRelationship.providedBy(r))
>>> relset = list(
... ix.findRelationshipTokenSet(q({'subjects': people['Xen']})))
>>> len(relset)
1
>>> s.remove(relset[0])
>>> dump(people['Uther'], ix, {}) in list(
... ix.findValueTokens('subjects', q({'objects': people['Ygritte']})))
True
>>> dump(people['Uther'], ix, {}) in list(ix.findValueTokens(
... 'subjects', q({'objects': people['Ygritte']}),
... filter=lambda relchain, query, index, cache: relchain[-1] in s))
False
>>> people['Uther'] in list(
... ix.findValues('subjects', q({'objects': people['Ygritte']})))
True
>>> people['Uther'] in list(ix.findValues(
... 'subjects', q({'objects': people['Ygritte']}),
... filter=lambda relchain, query, index, cache: relchain[-1] in s))
False
The next two search arguments are the targetQuery and the targetFilter. They
both are filters on the output of the search methods, while not affecting the
traversal/search process. The targetQuery takes a query identical to the main
query, and the targetFilter takes an IFilter identical to the one used by the
`filter` argument. The targetFilter can do all of the work of the targetQuery,
but the targetQuery makes a common case--wanting to find the paths between two
objects, or if two objects are linked at all, for instance--convenient.
We'll skip over targetQuery for a moment (we'll return when we revisit
`findRelationshipChains` and `isLinked`), and look at targetFilter.
targetFilter can be used for many tasks, such as only returning values that
are in specially annotated relationships, or only returning values that have
traversed a certain hinge relationship in a two-part search, or other tasks.
A very simple one, though, is to effectively specify a minimum traversal depth.
Here, we find the people who are precisely two steps down from Bran, no more
and no less. We do it twice, once with findValueTokens and once with
findValues.
>>> [load(t, ix, {}) for t in ix.findValueTokens(
... 'objects', q({'subjects': people['Bran']}), maxDepth=2,
... targetFilter=lambda relchain, q, i, c: len(relchain)>=2)]
[<Person 'Heather'>]
>>> list(ix.findValues(
... 'objects', q({'subjects': people['Bran']}), maxDepth=2,
... targetFilter=lambda relchain, q, i, c: len(relchain)>=2))
[<Person 'Heather'>]
Heather is the only person precisely two steps down from Bran.
Notice that we specified both maxDepth and targetFilter. We could have
received the same output by specifying a targetFilter of `len(relchain)==2`
and no maxDepth, but there is an important difference in efficiency. maxDepth
and filter can reduce the amount of work done by the index because they can
stop searching after reaching the maxDepth, or failing the filter; the
targetFilter and targetQuery arguments simply hide the results obtained, which
can reduce a bit of work in the case of getValues but generally don't reduce
any of the traversal work.
The last argument to the search methods is `transitiveQueriesFactory`. It is
a powertool that replaces the index's default traversal factory for the
duration of the search. This allows custom traversal for individual searches,
and can support a number of advanced use cases. For instance, our index
assumes that you want to traverse objects and sources, and that the context
should be constant; that may not always be the desired traversal behavior. If
we had a relationship of PERSON1 TAUGHT PERSON2 (the lessons of PERSON3) then
to find the teachers of any given person you might want to traverse PERSON1,
but sometimes you might want to traverse PERSON3 as well. You can change the
behavior by providing a different factory.
To show this example we will need to add a few more relationships. We will say
that Mary teaches Rob the lessons of Abe; Olaf teaches Zane the lessons of
Bran; Cathy teaches Bran the lessons of Lee; David teaches Abe the lessons of
Zane; and Emily teaches Mary the lessons of Ygritte.
In the diagram, left-hand lines indicate "taught" and right-hand lines indicate
"the lessons of", so ::
E Y
\ /
M
should be read as "Emily taught Mary the lessons of Ygritte". Here's the full
diagram::
C L
\ /
O B
\ /
E Y D Z
\ / \ /
M A
\ /
\ /
R
You can see then that the transitive path of Rob's teachers is Mary and Emily,
but the transitive path of Rob's lessons is Abe, Zane, Bran, and Lee.
Transitive queries factories must do extra work when the transitive walk is
across token types. We have used the TransposingTransitiveQueriesFactory to
build our transposers before, but now we need to write a custom one that
translates the tokens (ooh! a
TokenTranslatingTransposingTransitiveQueriesFactory! ...maybe we won't go that
far...).
We will add the relationships, build the custom transitive factory, and then
again do the search work twice, once with findValueTokens and once with
findValues.
>>> for triple in ('EMY', 'MRA', 'DAZ', 'OZB', 'CBL'):
... teacher, student, source = (letters[l] for l in triple)
... rel = SpecialRelationship((teacher,), 'taught', (student,))
... app['%sTaught%sTo%s' % (
... teacher.name, source.name, student.name)] = rel
... IContextAwareRelationship(rel).setContext(source)
... ix.index_doc(intids.register(rel), rel)
...
>>> def transitiveFactory(relchain, query, index, cache):
... dynamic = cache.get('dynamic')
... if dynamic is None:
... intids = cache['intids'] = component.getUtility(
... IIntIds, context=index)
... static = cache['static'] = {}
... dynamic = cache['dynamic'] = []
... names = ['objects', 'context']
... for nm, val in query.items():
... try:
... ix = names.index(nm)
... except ValueError:
... static[nm] = val
... else:
... if dynamic:
... # both were specified: no transitive search known.
... del dynamic[:]
... cache['intids'] = False
... break
... else:
... dynamic.append(nm)
... dynamic.append(names[not ix])
... else:
... intids = component.getUtility(IIntIds, context=index)
... if dynamic[0] == 'objects':
... def translate(t):
... return dump(intids.getObject(t), index, cache)
... else:
... def translate(t):
... return intids.register(load(t, index, cache))
... cache['translate'] = translate
... else:
... static = cache['static']
... translate = cache['translate']
... if dynamic:
... for r in index.findValueTokenSet(relchain[-1], dynamic[1]):
... res = {dynamic[0]: translate(r)}
... res.update(static)
... yield res
>>> [load(t, ix, {}) for t in ix.findValueTokens(
... 'subjects',
... q({'objects': people['Rob'], 'reltype': 'taught'}))]
[<Person 'Mary'>, <Person 'Emily'>]
>>> [intids.getObject(t) for t in ix.findValueTokens(
... 'context',
... q({'objects': people['Rob'], 'reltype': 'taught'}),
... transitiveQueriesFactory=transitiveFactory)]
[<Person 'Abe'>, <Person 'Zane'>, <Person 'Bran'>, <Person 'Lee'>]
>>> list(ix.findValues(
... 'subjects',
... q({'objects': people['Rob'], 'reltype': 'taught'})))
[<Person 'Mary'>, <Person 'Emily'>]
>>> list(ix.findValues(
... 'context',
... q({'objects': people['Rob'], 'reltype': 'taught'}),
... transitiveQueriesFactory=transitiveFactory))
[<Person 'Abe'>, <Person 'Zane'>, <Person 'Bran'>, <Person 'Lee'>]
transitiveQueryFactories can be very powerful, and we aren't finished talking
about them in this document: see "Transitively mapping multiple elements"
below.
We have now discussed, or at least mentioned, all of the available search
arguments. The `apply` method's 'values' search has the same arguments and
features as `findValues`, so it can also do these transitive tricks. Let's
get all of Karyn's subordinates.
>>> res = ix.apply({'values':
... {'resultName': 'objects', 'query':
... q({'reltype': 'manages',
... 'subjects': people['Karyn']})}})
>>> res # doctest: +ELLIPSIS
IFSet([...])
>>> sorted(repr(load(t, ix, {})) for t in res)
... # doctest: +NORMALIZE_WHITESPACE
["<Person 'Lee'>", "<Person 'Mary'>", "<Person 'Nancy'>",
"<Person 'Olaf'>", "<Person 'Perry'>", "<Person 'Quince'>"]
As we return to `findRelationshipChains` and `findRelationshipTokenChains`, we
also return to the search argument we postponed above: targetQuery.
The `findRelationshipChains` and `findRelationshipTokenChains` can simply find
all paths:
>>> res = [repr([intids.getObject(t) for t in path]) for path in
... ix.findRelationshipTokenChains(
... q({'reltype': 'manages', 'subjects': people['Jim']}
... ))]
>>> len(res)
3
>>> sorted(res[:2]) # doctest: +NORMALIZE_WHITESPACE
["[<(<Person 'Jim'>, <Person 'Karyn'>) manages
(<Person 'Lee'>, <Person 'Mary'>)>]",
"[<(<Person 'Jim'>, <Person 'Karyn'>) manages
(<Person 'Nancy'>, <Person 'Olaf'>, <Person 'Perry'>)>]"]
>>> res[2] # doctest: +NORMALIZE_WHITESPACE
"[<(<Person 'Jim'>, <Person 'Karyn'>) manages
(<Person 'Lee'>, <Person 'Mary'>)>,
<(<Person 'Lee'>, <Person 'Mary'>) manages
(<Person 'Quince'>,)>]"
>>> res == [repr(list(p)) for p in
... ix.findRelationshipChains(
... q({'reltype': 'manages', 'subjects': people['Jim']}
... ))]
True
Like `findValues`, this is a breadth-first search.
If we use a targetQuery with `findRelationshipChains`, you can find all paths
between two searches. For instance, consider the paths between Rob and
Ygritte. While a `findValues` search would only include Rob once if asked to
search for supervisors, there are two paths. These can be found with the
targetQuery.
>>> res = [repr([intids.getObject(t) for t in path]) for path in
... ix.findRelationshipTokenChains(
... q({'reltype': 'manages', 'subjects': people['Rob']}),
... targetQuery=q({'objects': people['Ygritte']}))]
>>> len(res)
2
>>> sorted(res[:2]) # doctest: +NORMALIZE_WHITESPACE
["[<(<Person 'Rob'>,) manages
(<Person 'Sam'>, <Person 'Terry'>, <Person 'Uther'>)>,
<(<Person 'Terry'>,) manages (<Person 'Xen'>,)>,
<(<Person 'Uther'>, <Person 'Xen'>) manages (<Person 'Ygritte'>,)>]",
"[<(<Person 'Rob'>,) manages
(<Person 'Sam'>, <Person 'Terry'>, <Person 'Uther'>)>,
<(<Person 'Uther'>, <Person 'Xen'>) manages (<Person 'Ygritte'>,)>]"]
Here's a query with no results:
>>> len(list(ix.findRelationshipTokenChains(
... q({'reltype': 'manages', 'subjects': people['Rob']}),
... targetQuery=q({'objects': companies['Zookd']}))))
0
You can combine targetQuery with targetFilter. Here we arbitrarily say we
are looking for a path between Rob and Ygritte that is at least 3 links long.
>>> res = [repr([intids.getObject(t) for t in path]) for path in
... ix.findRelationshipTokenChains(
... q({'reltype': 'manages', 'subjects': people['Rob']}),
... targetQuery=q({'objects': people['Ygritte']}),
... targetFilter=lambda relchain, q, i, c: len(relchain)>=3)]
>>> len(res)
1
>>> res # doctest: +NORMALIZE_WHITESPACE
["[<(<Person 'Rob'>,) manages
(<Person 'Sam'>, <Person 'Terry'>, <Person 'Uther'>)>,
<(<Person 'Terry'>,) manages (<Person 'Xen'>,)>,
<(<Person 'Uther'>, <Person 'Xen'>) manages (<Person 'Ygritte'>,)>]"]
`isLinked` takes the same arguments as all of the other transitive-aware
methods. For instance, Rob and Ygritte are transitively linked, but Abe and
Zane are not.
>>> ix.isLinked(
... q({'reltype': 'manages', 'subjects': people['Rob']}),
... targetQuery=q({'objects': people['Ygritte']}))
True
>>> ix.isLinked(
... q({'reltype': 'manages', 'subjects': people['Abe']}),
... targetQuery=q({'objects': people['Ygritte']}))
False
Detecting cycles
----------------
Suppose we're modeling a 'king in disguise': someone high up in management also
works as a peon to see how his employees' lives are. We could model this a
number of ways that might make more sense than what we'll do now, but to show
cycles at work we'll just add an additional relationship so that Abe works for
Gary. That means that the very longest path from Ingrid up gets a lot longer--
in theory, it's infinitely long, because of the cycle.
The index keeps track of this and stops right when the cycle happens, and right
before the cycle duplicates any relationships. It marks the chain that has
cycle as a special kind of tuple that implements ICircularRelationshipPath.
The tuple has a 'cycled' attribute that contains the one or more searches
that would be equivalent to following the cycle (given the same transitiveMap).
Let's actually look at the example we described.
>>> res = list(ix.findRelationshipTokenChains(
... q({'objects': people['Ingrid'], 'reltype': 'manages'})))
>>> len(res)
4
>>> len(res[3])
4
>>> interfaces.ICircularRelationshipPath.providedBy(res[3])
False
>>> rel = Relationship(
... (people['Gary'],), 'manages', (people['Abe'],))
>>> app['GaryManagesAbe'] = rel
>>> ix.index(rel)
>>> res = list(ix.findRelationshipTokenChains(
... q({'objects': people['Ingrid'], 'reltype': 'manages'})))
>>> len(res)
8
>>> len(res[7])
8
>>> interfaces.ICircularRelationshipPath.providedBy(res[7])
True
>>> [sorted(ix.resolveQuery(search).items()) for search in res[7].cycled]
[[('objects', <Person 'Abe'>), ('reltype', 'manages')]]
>>> tuple(ix.resolveRelationshipTokens(res[7]))
... # doctest: +NORMALIZE_WHITESPACE
(<(<Person 'Heather'>,) manages (<Person 'Ingrid'>,)>,
<(<Person 'David'>,) manages (<Person 'Heather'>,)>,
<(<Person 'Bran'>,) manages (<Person 'David'>,)>,
<(<Person 'Abe'>,) manages (<Person 'Bran'>,)>,
<(<Person 'Gary'>,) manages (<Person 'Abe'>,)>,
<(<Person 'Fred'>,) manages (<Person 'Gary'>,)>,
<(<Person 'Cathy'>,) manages (<Person 'Fred'>,)>,
<(<Person 'Abe'>,) manages (<Person 'Cathy'>,)>)
The same kind of thing works for `findRelationshipChains`. Notice that the
query in the .cycled attribute is not resolved: it is still the query that
would be needed to continue the cycle.
>>> res = list(ix.findRelationshipChains(
... q({'objects': people['Ingrid'], 'reltype': 'manages'})))
>>> len(res)
8
>>> len(res[7])
8
>>> interfaces.ICircularRelationshipPath.providedBy(res[7])
True
>>> [sorted(ix.resolveQuery(search).items()) for search in res[7].cycled]
[[('objects', <Person 'Abe'>), ('reltype', 'manages')]]
>>> res[7] # doctest: +NORMALIZE_WHITESPACE
cycle(<(<Person 'Heather'>,) manages (<Person 'Ingrid'>,)>,
<(<Person 'David'>,) manages (<Person 'Heather'>,)>,
<(<Person 'Bran'>,) manages (<Person 'David'>,)>,
<(<Person 'Abe'>,) manages (<Person 'Bran'>,)>,
<(<Person 'Gary'>,) manages (<Person 'Abe'>,)>,
<(<Person 'Fred'>,) manages (<Person 'Gary'>,)>,
<(<Person 'Cathy'>,) manages (<Person 'Fred'>,)>,
<(<Person 'Abe'>,) manages (<Person 'Cathy'>,)>)
Notice that there is nothing special about the new relationship, by the way.
If we had started to look for Fred's supervisors, the cycle marker would have
been given for the relationship that points back to Fred as a supervisor to
himself. There's no way for the computer to know which is the "cause" without
further help and policy.
Handling cycles can be tricky. Now imagine that we have a cycle that involves
a relationship with two objects, only one of which causes the cycle. The other
object should continue to be followed.
For instance, lets have Q manage L and Y. The link to L will be a cycle, but
the link to Y is not, and should be followed. This means that only the middle
relationship chain will be marked as a cycle.
>>> rel = Relationship((people['Quince'],), 'manages',
... (people['Lee'], people['Ygritte']))
>>> app['QuinceManagesLeeYgritte'] = rel
>>> ix.index_doc(intids.register(rel), rel)
>>> res = [p for p in ix.findRelationshipTokenChains(
... q({'reltype': 'manages', 'subjects': people['Mary']}))]
>>> [interfaces.ICircularRelationshipPath.providedBy(p) for p in res]
[False, True, False]
>>> [[intids.getObject(t) for t in p] for p in res]
... # doctest: +NORMALIZE_WHITESPACE
[[<(<Person 'Lee'>, <Person 'Mary'>) manages (<Person 'Quince'>,)>],
[<(<Person 'Lee'>, <Person 'Mary'>) manages (<Person 'Quince'>,)>,
<(<Person 'Quince'>,) manages (<Person 'Lee'>, <Person 'Ygritte'>)>],
[<(<Person 'Lee'>, <Person 'Mary'>) manages (<Person 'Quince'>,)>,
<(<Person 'Quince'>,) manages (<Person 'Lee'>, <Person 'Ygritte'>)>,
<(<Person 'Ygritte'>,) manages (<Person 'Zane'>,)>]]
>>> [sorted(
... (nm, nm == 'reltype' and t or load(t, ix, {}))
... for nm, t in search.items()) for search in res[1].cycled]
[[('reltype', 'manages'), ('subjects', <Person 'Lee'>)]]
Transitively mapping multiple elements
--------------------------------------
Transitive searches can do whatever searches the transitiveQueriesFactory
returns, which means that complex transitive behavior can be modeled. For
instance, imagine genealogical relationships. Let's say the basic
relationship is "MALE and FEMALE had CHILDREN". Walking transitively to get
ancestors or descendants would need to distinguish between male children and
female children in order to correctly generate the transitive search. This
could be accomplished by resolving each child token and examining the object
or, probably more efficiently, getting an indexed collection of males and
females (and cacheing it in the cache dictionary for further transitive steps)
and checking the gender by membership in the indexed collections. Either of
these approaches could be performed by a transitiveQueriesFactory. A full
example is left as an exercise to the reader.
Lies, damn lies, and statistics
===============================
The zope.index.interfaces.IStatistics methods are implemented to provide
minimal introspectability. wordCount always returns 0, because words are
irrelevant to this kind of index. documentCount returns the number of
relationships indexed.
>>> ix.wordCount()
0
>>> ix.documentCount()
25
Reindexing and removing relationships
=====================================
Using an index over an application's lifecycle usually requires changes to the
indexed objects. As per the zope.index interfaces, `index_doc` can reindex
relationships, `unindex_doc` can remove them, and `clear` can clear the entire
index.
Here we change the zope.org project manager from Fred to Emily.
>>> [load(t, ix, {}) for t in ix.findValueTokens(
... 'subjects',
... q({'reltype': 'has the role of',
... 'objects': roles['Project Manager'],
... 'context': projects['zope.org redesign']}))]
[<Person 'Fred'>]
>>> rel = intids.getObject(list(ix.findRelationshipTokenSet(
... q({'reltype': 'has the role of',
... 'objects': roles['Project Manager'],
... 'context': projects['zope.org redesign']})))[0])
>>> rel.subjects = (people['Emily'],)
>>> ix.index_doc(intids.register(rel), rel)
>>> q = ix.tokenizeQuery
>>> [load(t, ix, {}) for t in ix.findValueTokens(
... 'subjects',
... q({'reltype': 'has the role of',
... 'objects': roles['Project Manager'],
... 'context': projects['zope.org redesign']}))]
[<Person 'Emily'>]
Here we remove the relationship that made a cycle for Abe in the 'king in
disguise' scenario.
>>> res = list(ix.findRelationshipTokenChains(
... q({'objects': people['Ingrid'],
... 'reltype': 'manages'})))
>>> len(res)
8
>>> len(res[7])
8
>>> interfaces.ICircularRelationshipPath.providedBy(res[7])
True
>>> rel = intids.getObject(list(ix.findRelationshipTokenSet(
... q({'subjects': people['Gary'], 'reltype': 'manages',
... 'objects': people['Abe']})))[0])
>>> ix.unindex(rel) # == ix.unindex_doc(intids.getId(rel))
>>> ix.documentCount()
24
>>> res = list(ix.findRelationshipTokenChains(
... q({'objects': people['Ingrid'], 'reltype': 'manages'})))
>>> len(res)
4
>>> len(res[3])
4
>>> interfaces.ICircularRelationshipPath.providedBy(res[3])
False
Finally we clear out the whole index.
>>> ix.clear()
>>> ix.documentCount()
0
>>> list(ix.findRelationshipTokenChains(
... q({'objects': people['Ingrid'], 'reltype': 'manages'})))
[]
>>> [load(t, ix, {}) for t in ix.findValueTokens(
... 'subjects',
... q({'reltype': 'has the role of',
... 'objects': roles['Project Manager'],
... 'context': projects['zope.org redesign']}))]
[]
Optimizing relationship index use
=================================
There are three optimization opportunities built into the index.
- use the cache to load and dump tokens;
- don't load or dump tokens (the values themselves may be used as tokens); and
- have the returned value be of the same btree family as the result family.
For some operations, particularly with hundreds or thousands of members in a
single relationship value, some of these optimizations can speed up some
common-case reindexing work by around 100 times.
The easiest (and perhaps least useful) optimization is that all dump
calls and all load calls generated by a single operation share a cache
dictionary per call type (dump/load), per indexed relationship value.
Therefore, for instance, we could stash an intids utility, so that we
only had to do a utility lookup once, and thereafter it was only a
single dictionary lookup. This is what the default `generateToken` and
`resolveToken` functions in index.py do: look at them for an example.
A further optimization is to not load or dump tokens at all, but use values
that may be tokens. This will be particularly useful if the tokens have
__cmp__ (or equivalent) in C, such as built-in types like ints. To specify
this behavior, you create an index with the 'load' and 'dump' values for the
indexed attribute descriptions explicitly set to None.
>>> ix = index.Index(
... ({'element': IRelationship['subjects'], 'multiple': True,
... 'dump': None, 'load': None},
... {'element': IRelationship['relationshiptype'],
... 'dump': relTypeDump, 'load': relTypeLoad, 'btree': OIBTree,
... 'name': 'reltype'},
... {'element': IRelationship['objects'], 'multiple': True,
... 'dump': None, 'load': None},
... {'element': IContextAwareRelationship['getContext'],
... 'name': 'context'}),
... index.TransposingTransitiveQueriesFactory('subjects', 'objects'))
...
>>> sm['rel_index_2'] = ix
>>> app['ex_rel_1'] = rel = Relationship((1,), 'has the role of', (2,))
>>> ix.index(rel)
>>> list(ix.findValueTokens('objects', {'subjects': 1}))
[2]
Finally, if you have single relationships that relate hundreds or thousands
of objects, it can be a huge win if the value is a 'multiple' of the same type
as the stored BTree for the given attribute. The default BTree family for
attributes is IFBTree; IOBTree is also a good choice, and may be preferrable
for some applications.
>>> ix = index.Index(
... ({'element': IRelationship['subjects'], 'multiple': True,
... 'dump': None, 'load': None},
... {'element': IRelationship['relationshiptype'],
... 'dump': relTypeDump, 'load': relTypeLoad, 'btree': OIBTree,
... 'name': 'reltype'},
... {'element': IRelationship['objects'], 'multiple': True,
... 'dump': None, 'load': None},
... {'element': IContextAwareRelationship['getContext'],
... 'name': 'context'}),
... index.TransposingTransitiveQueriesFactory('subjects', 'objects'))
...
>>> sm['rel_index_3'] = ix
>>> from BTrees import IFBTree
>>> app['ex_rel_2'] = rel = Relationship(
... IFBTree.IFTreeSet((1,)), 'has the role of', IFBTree.IFTreeSet())
>>> ix.index(rel)
>>> list(ix.findValueTokens('objects', {'subjects': 1}))
[]
>>> list(ix.findValueTokens('subjects', {'objects': None}))
[1]
Reindexing is where some of the big improvements can happen. The following
gyrations exercise the optimization code.
>>> rel.objects.insert(2)
1
>>> ix.index(rel)
>>> list(ix.findValueTokens('objects', {'subjects': 1}))
[2]
>>> rel.subjects = IFBTree.IFTreeSet((3,4,5))
>>> ix.index(rel)
>>> list(ix.findValueTokens('objects', {'subjects': 3}))
[2]
>>> rel.subjects.insert(6)
1
>>> ix.index(rel)
>>> list(ix.findValueTokens('objects', {'subjects': 6}))
[2]
>>> rel.subjects.update(range(100, 200))
100
>>> ix.index(rel)
>>> list(ix.findValueTokens('objects', {'subjects': 100}))
[2]
>>> rel.subjects = IFBTree.IFTreeSet((3,4,5,6))
>>> ix.index(rel)
>>> list(ix.findValueTokens('objects', {'subjects': 3}))
[2]
>>> rel.subjects = IFBTree.IFTreeSet(())
>>> ix.index(rel)
>>> list(ix.findValueTokens('objects', {'subjects': 3}))
[]
>>> rel.subjects = IFBTree.IFTreeSet((3,4,5))
>>> ix.index(rel)
>>> list(ix.findValueTokens('objects', {'subjects': 3}))
[2]
tokenizeValues and resolveValueTokens work correctly without loaders and
dumpers--that is, they do nothing.
>>> ix.tokenizeValues((3,4,5), 'subjects')
(3, 4, 5)
>>> ix.resolveValueTokens((3,4,5), 'subjects')
(3, 4, 5)
__contains__ and Unindexing
=============================
You can test whether a relationship is in an index with __contains__. Note
that this uses the actual relationship, not the relationship token.
>>> ix = index.Index(
... ({'element': IRelationship['subjects'], 'multiple': True,
... 'dump': dump, 'load': load},
... {'element': IRelationship['relationshiptype'],
... 'dump': relTypeDump, 'load': relTypeLoad, 'btree': OIBTree,
... 'name': 'reltype'},
... {'element': IRelationship['objects'], 'multiple': True,
... 'dump': dump, 'load': load},
... {'element': IContextAwareRelationship['getContext'],
... 'name': 'context'}),
... index.TransposingTransitiveQueriesFactory('subjects', 'objects'))
>>> ix.documentCount()
0
>>> app['fredisprojectmanager'].subjects = (people['Fred'],)
>>> ix.index(app['fredisprojectmanager'])
>>> ix.index(app['another_rel'])
>>> ix.documentCount()
2
>>> app['fredisprojectmanager'] in ix
True
>>> list(ix.findValues(
... 'subjects',
... q({'reltype': 'has the role of',
... 'objects': roles['Project Manager'],
... 'context': projects['zope.org redesign']})))
[<Person 'Fred'>]
>>> app['another_rel'] in ix
True
>>> app['abeAndBran'] in ix
False
As noted, you can unindex using unindex(relationship) or
unindex_doc(relationship token).
>>> ix.unindex_doc(ix.tokenizeRelationship(app['fredisprojectmanager']))
>>> app['fredisprojectmanager'] in ix
False
>>> list(ix.findValues(
... 'subjects',
... q({'reltype': 'has the role of',
... 'objects': roles['Project Manager'],
... 'context': projects['zope.org redesign']})))
[]
>>> ix.unindex(app['another_rel'])
>>> app['another_rel'] in ix
False
As defined by zope.index.interfaces.IInjection, if the relationship is
not in the index then calling unindex_doc is a no-op; the same holds
true for unindex.
>>> ix.unindex(app['abeAndBran'])
>>> ix.unindex_doc(ix.tokenizeRelationship(app['abeAndBran']))
.. ......... ..
.. FOOTNOTES ..
.. ......... ..
.. [#apply] `apply` and the other zope.index-related methods are the obvious
exceptions.
| zc.relationship | /zc.relationship-2.1.tar.gz/zc.relationship-2.1/src/zc/relationship/README.rst | README.rst |
from zope import interface
from zope.app.container.interfaces import IReadContainer
import zope.index.interfaces
import zc.relation.interfaces
ICircularRelationshipPath = zc.relation.interfaces.ICircularRelationPath
class ITransitiveQueriesFactory(interface.Interface):
def __call__(relchain, query, index, cache):
"""return iterable of queries to search further from given relchain.
last relationship token in relchain is the most recent.
query is original query that started the search."""
class IFilter(interface.Interface):
def __call__(relchain, query, index, cache):
"""return boolean: whether to accept the given relchain.
last relationship token in relchain is the most recent.
query is original query that started the search.
Used for the filter and targetFilter arguments of the IIndex query
methods. Cache is a dictionary that will be used throughout a given
search."""
class IIndex(zope.index.interfaces.IInjection,
zope.index.interfaces.IIndexSearch,
zope.index.interfaces.IStatistics):
defaultTransitiveQueriesFactory = interface.Attribute(
'''the standard way for the index to determine transitive queries.
Must implement ITransitiveQueriesFactory, or be None''')
def index(relationship):
"""obtains the token for the relationship and indexes (calls
IInjection.index_doc)"""
def unindex(relationship):
"""obtains the token for the relationship and unindexes (calls
IInjection.unindex_doc)"""
def __contains__(relationship):
"""returns whether the relationship is in the index"""
def findValueTokens(resultName, query=None, maxDepth=None, filter=None,
targetQuery=None, targetFilter=None,
transitiveQueriesFactory=None):
"""find token results for searchTerms.
- resultName is the index name wanted for results.
- if query is None (or evaluates to boolean False), returns the
underlying btree data structure; which is an iterable result but
can also be used with BTree operations
Otherwise, same arguments as findRelationshipChains.
"""
def findValues(resultName, query=None, maxDepth=None, filter=None,
targetQuery=None, targetFilter=None,
transitiveQueriesFactory=None):
"""Like findValueTokens, but resolves value tokens"""
def findRelationshipTokenChains(query, maxDepth=None, filter=None,
targetQuery=None, targetFilter=None,
transitiveQueriesFactory=None):
"""find tuples of relationship tokens for searchTerms.
- query is a dictionary of {indexName: token}
- maxDepth is None or a positive integer that specifies maximum depth
for transitive results. None means that the transitiveMap will be
followed until a cycle is detected. It is a ValueError to provide a
non-None depth if transitiveQueriesFactory is None and
index.defaultTransitiveQueriesFactory is None.
- filter is a an optional callable providing IFilter that determines
whether relationships will be traversed at all.
- targetQuery is an optional query that specifies that only paths with
final relationships that match the targetQuery should be returned.
It represents a useful subset of the jobs that can be done with the
targetFilter.
- targetFilter is an optional callable providing IFilter that
determines whether a given path will be included in results (it will
still be traversed)
- optional transitiveQueriesFactory takes the place of the index's
defaultTransitiveQueriesFactory
"""
def findRelationshipChains(query, maxDepth=None, filter=None,
targetQuery=None, targetFilter=None,
transitiveQueriesFactory=None):
"Like findRelationshipTokenChains, but resolves relationship tokens"
def isLinked(query, maxDepth=None, filter=None, targetQuery=None,
targetFilter=None, transitiveQueriesFactory=None):
"""boolean if there is any result for the given search.
Same arguments as findRelationshipChains.
The general algorithm for using the arguments is this:
try to yield a single chain from findRelationshipTokenChains with the
given arguments. If one can be found, return True, else False."""
def tokenizeQuery(query):
'''Given a dictionary of {indexName: value} returns a dictionary of
{indexname: token} appropriate for the search methods'''
def resolveQuery(query):
'''Given a dictionary of {indexName: token} returns a dictionary of
{indexname: value}'''
def tokenizeValues(values, name):
"""Returns an iterable of tokens for the values of the given index
name"""
def resolveValueTokens(tokens, name):
"""Returns an iterable of values for the tokens of the given index
name"""
def tokenizeRelationship(rel):
"""Returns a token for the given relationship"""
def resolveRelationshipToken(token):
"""Returns a relationship for the given token"""
def tokenizeRelationships(rels):
"""Returns an iterable of tokens for the relations given"""
def resolveRelationshipTokens(tokens):
"""Returns an iterable of relations for the tokens given"""
def findRelationshipTokenSet(query):
"""Given a single dictionary of {indexName: token}, return a set (based
on the btree family for relationships in the index) of relationship
tokens that match it. Intransitive."""
def findRelationships(query):
"""Given a single dictionary of {indexName: token}, return an iterable
of relationships that match the query intransitively"""
def findValueTokenSet(reltoken, name):
"""Given a relationship token and a value name, return a set (based on
the btree family for the value) of value tokens for that relationship.
"""
class IRelationship(interface.Interface):
"""An asymmetric relationship."""
__parent__ = interface.Attribute(
"""The relationship container of which this relationship is a member
""")
sources = interface.Attribute(
"""Objects pointing in the relationship. Readonly.""")
targets = interface.Attribute(
"""Objects being pointed to in the relationship. Readonly.""")
class IMutableRelationship(IRelationship):
"""An asymmetric relationship. Sources and targets can be changed."""
class ISourceRelationship(IMutableRelationship):
source = interface.Attribute(
"""the source for this object. Mutable""")
class ITargetRelationship(IMutableRelationship):
target = interface.Attribute(
"""the target for this object. Mutable""")
class IOneToOneRelationship(ISourceRelationship, ITargetRelationship):
pass
class IOneToManyRelationship(ISourceRelationship):
pass
class IManyToOneRelationship(ITargetRelationship):
pass
class IBidirectionalRelationshipIndex(interface.Interface):
def findTargets(source, maxDepth=1, filter=None):
"""Given a source, iterate over objects to which it points.
maxDepth is the number of relationships through which the search
should walk transitively. It must be a positive integer.
filter is an optional callable that takes a relationship and returns
a boolean True value if it should be included, and a False if not.
"""
def findSources(target, maxDepth=1, filter=None):
"""Given a target, iterate over objects that point to it.
maxDepth is the number of relationships through which the search
should walk transitively. It must be a positive integer.
filter is an optional callable that takes a relationship and returns
a boolean True value if it should be included, and a False if not.
"""
def isLinked(source=None, target=None, maxDepth=1, filter=None):
"""given source, target, or both, return True if a link exists.
maxDepth is the number of relationships through which the search
should walk transitively. It must be a positive integer.
filter is an optional callable that takes a relationship and returns
a boolean True value if it should be included, and a False if not.
"""
def findRelationships(
source=None, target=None, maxDepth=1, filter=None):
"""given source, target, or both, iterate over all relationship paths.
maxDepth is the number of relationships through which the search
should walk transitively. It must be a positive integer.
filter is an optional callable that takes a relationship and returns
a boolean True value if it should be included, and a False if not.
If a cycle is found, it is omitted by default. if includeCycles is
True, it returns the cycle in an ICircularRelationshipPath and then
does not continue down the cycle.
"""
def findTargetTokens(source, maxDepth=1, filter=None):
"""As findTargets, but returns tokens rather than the objects"""
def findSourceTokens(source, maxDepth=1, filter=None):
"""As findSources, but returns tokens rather than the objects"""
def findRelationshipTokens(source, maxDepth=1, filter=None):
"""As findRelationships, but returns tokens rather than the objects"""
class IRelationshipContainer(IReadContainer, IBidirectionalRelationshipIndex):
def add(object):
"""Add a relationship to the container"""
def remove(object):
"""Remove a relationship from the container"""
class IKeyReferenceRelationshipContainer(IRelationshipContainer):
"""holds relationships of objects that can be adapted to IKeyReference.
tokens are key references.
"""
class IIntIdRelationshipContainer(IRelationshipContainer):
"""relationships and the objects they relate must have/be given an intid.
tokens are intids.
"""
try:
import zc.listcontainer.interfaces
except ImportError:
pass
else:
class IRelationshipListContainer(
zc.listcontainer.interfaces.IListContainer,
IBidirectionalRelationshipIndex):
"""Uses the list container API to manage the relationships"""
class IIntIdRelationshipListContainer(IRelationshipListContainer):
"""tokens are intids""" | zc.relationship | /zc.relationship-2.1.tar.gz/zc.relationship-2.1/src/zc/relationship/interfaces.py | interfaces.py |
=====================
RelationshipContainer
=====================
The relationship container holds IRelationship objects. It includes an API to
search for relationships and the objects to which they link, transitively and
intransitively. The relationships are objects in and of themselves, and they
can themselves be related as sources or targets in other relationships.
There are currently two implementations of the interface in this package. One
uses intids, and the other uses key references. They have different
advantages and disadvantages.
The intids makes it possible to get intid values directly. This can make it
easier to merge the results with catalog searches and other intid-based
indexes. Possibly more importantly, it does not create ghosted objects for
the relationships as they are searched unless absolutely necessary (for
instance, using a relationship filter), but uses the intids alone for
searches. This can be very important if you are searching large databases of
relationships: the relationship objects and the associated keyref links in the
other implementation can flush the entire ZODB object cache, possibly leading
to unpleasant performance characteristics for your entire application.
On the other hand, there are a limited number of intids available: sys.maxint,
or 2147483647 on a 32 bit machine. As the intid usage increases, the
efficiency of finding unique intids decreases. This can be addressed by
increasing IOBTrees maximum integer to be 64 bit (9223372036854775807) or by
using the keyref implementation. The keyref implementation also eliminates a
dependency--the intid utility itself--if that is desired. This can be
important if you can't rely on having an intid utility, or if objects to be
related span intid utilities. Finally, it's possible that the direct
attribute access that underlies the keyref implementation might be quicker
than the intid dereferencing, but this is unproven and may be false.
For our examples, we'll assume we've already imported a container and a
relationship from one of the available sources. You can use a relationship
specific to your usage, or the generic one in shared, as long as it meets the
interface requirements.
It's also important to note that, while the relationship objects are an
important part of the design, they should not be abused. If you want to store
other data on the relationship, it should be stored in another persistent
object, such as an attribute annotation's btree. Typically relationship
objects will differ on the basis of interfaces, annotations, and possibly
small lightweight values on the objects themselves.
We'll assume that there is an application named `app` with 30 objects in it
(named 'ob0' through 'ob29') that we'll be relating.
Creating a relationship container is easy. We'll use an abstract Container,
but it could be from the keyref or the intid modules.
>>> from zc.relationship import interfaces
>>> container = Container()
>>> from zope.interface.verify import verifyObject
>>> verifyObject(interfaces.IRelationshipContainer, container)
True
The containers can be used as parts of other objects, or as standalone local
utilities. Here's an example of adding one as a local utilty.
>>> sm = app.getSiteManager()
>>> sm['lineage_relationship'] = container
>>> import zope.interface.interfaces
>>> registry = zope.interface.interfaces.IComponentRegistry(sm)
>>> registry.registerUtility(
... container, interfaces.IRelationshipContainer, 'lineage')
>>> import transaction
>>> transaction.commit()
Adding relationships is also easy: instantiate and add. The `add` method adds
objects and assigns them random alphanumeric keys.
>>> rel = Relationship((app['ob0'],), (app['ob1'],))
>>> verifyObject(interfaces.IRelationship, rel)
True
>>> container.add(rel)
Although the container does not have `__setitem__` and `__delitem__` (defining
`add` and `remove` instead), it does define the read-only elements of the basic
Python mapping interface.
>>> container[rel.__name__] is rel
True
>>> len(container)
1
>>> list(container.keys()) == [rel.__name__]
True
>>> list(container) == [rel.__name__]
True
>>> list(container.values()) == [rel]
True
>>> container.get(rel.__name__) is rel
True
>>> container.get('17') is None
True
>>> rel.__name__ in container
True
>>> '17' in container
False
>>> list(container.items()) == [(rel.__name__, rel)]
True
It also supports four searching methods: `findTargets`, `findSources`,
`findRelationships`, and `isLinked`. Let's add a few more relationships and
examine some relatively simple cases.
>>> container.add(Relationship((app['ob1'],), (app['ob2'],)))
>>> container.add(Relationship((app['ob1'],), (app['ob3'],)))
>>> container.add(Relationship((app['ob0'],), (app['ob3'],)))
>>> container.add(Relationship((app['ob0'],), (app['ob4'],)))
>>> container.add(Relationship((app['ob2'],), (app['ob5'],)))
>>> transaction.commit() # this is indicative of a bug in ZODB; if you
... # do not do this then new objects will deactivate themselves into
... # nothingness when _p_deactivate is called
Now there are six direct relationships (all of the relationships point down
in the diagram)::
ob0
| |\
ob1 | |
| | | |
ob2 ob3 ob4
|
ob5
The mapping methods still have kept up with the new additions.
>>> len(container)
6
>>> len(container.keys())
6
>>> sorted(container.keys()) == sorted(
... v.__name__ for v in container.values())
True
>>> sorted(container.items()) == sorted(
... zip(container.keys(), container.values()))
True
>>> len([v for v in container.values() if container[v.__name__] is v])
6
>>> sorted(container.keys()) == sorted(container)
True
More interestingly, lets examine some of the searching methods. What are the
direct targets of ob0?
>>> container.findTargets(app['ob0']) # doctest: +ELLIPSIS
<generator object ...>
Ah-ha! It's a generator! Let's try that again.
>>> sorted(o.id for o in container.findTargets(app['ob0']))
['ob1', 'ob3', 'ob4']
OK, what about the ones no more than two relationships away? We use the
`maxDepth` argument, which is the second placeful argument.
>>> sorted(o.id for o in container.findTargets(app['ob0'], 2))
['ob1', 'ob2', 'ob3', 'ob4']
Notice that, even though ob3 is available both through one and two
relationships, it is returned only once.
Passing in None will get all related objects--the same here as passing in 3, or
any greater integer.
>>> sorted(o.id for o in container.findTargets(app['ob0'], None))
['ob1', 'ob2', 'ob3', 'ob4', 'ob5']
>>> sorted(o.id for o in container.findTargets(app['ob0'], 3))
['ob1', 'ob2', 'ob3', 'ob4', 'ob5']
>>> sorted(o.id for o in container.findTargets(app['ob0'], 25))
['ob1', 'ob2', 'ob3', 'ob4', 'ob5']
This is true even if we put in a cycle. We'll put in a cycle between ob5 and
ob1 and look at the results.
An important aspect of the algorithm used is that it returns closer
relationships first, which we can begin to see here.
>>> container.add(Relationship((app['ob5'],), (app['ob1'],)))
>>> transaction.commit()
>>> sorted(o.id for o in container.findTargets(app['ob0'], None))
['ob1', 'ob2', 'ob3', 'ob4', 'ob5']
>>> res = list(o.id for o in container.findTargets(app['ob0'], None))
>>> sorted(res[:3]) # these are all one step away
['ob1', 'ob3', 'ob4']
>>> res[3:] # ob 2 is two steps, and ob5 is three steps.
['ob2', 'ob5']
When you see the source in the targets, you know you are somewhere inside a
cycle.
>>> sorted(o.id for o in container.findTargets(app['ob1'], None))
['ob1', 'ob2', 'ob3', 'ob5']
>>> sorted(o.id for o in container.findTargets(app['ob2'], None))
['ob1', 'ob2', 'ob3', 'ob5']
>>> sorted(o.id for o in container.findTargets(app['ob5'], None))
['ob1', 'ob2', 'ob3', 'ob5']
If you ask for objects of a distance that is not a positive integer, you'll get
a ValueError.
>>> container.findTargets(app['ob0'], 0)
Traceback (most recent call last):
...
ValueError: maxDepth must be None or a positive integer
>>> container.findTargets(app['ob0'], -1)
Traceback (most recent call last):
...
ValueError: maxDepth must be None or a positive integer
>>> container.findTargets(app['ob0'], 'kumquat') # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: ...
The `findSources` method is the mirror of `findTargets`: given a target, it
finds all sources. Using the same relationship tree built above, we'll search
for some sources.
>>> container.findSources(app['ob0']) # doctest: +ELLIPSIS
<generator object ...>
>>> list(container.findSources(app['ob0']))
[]
>>> list(o.id for o in container.findSources(app['ob4']))
['ob0']
>>> list(o.id for o in container.findSources(app['ob4'], None))
['ob0']
>>> sorted(o.id for o in container.findSources(app['ob1']))
['ob0', 'ob5']
>>> sorted(o.id for o in container.findSources(app['ob1'], 2))
['ob0', 'ob2', 'ob5']
>>> sorted(o.id for o in container.findSources(app['ob1'], 3))
['ob0', 'ob1', 'ob2', 'ob5']
>>> sorted(o.id for o in container.findSources(app['ob1'], None))
['ob0', 'ob1', 'ob2', 'ob5']
>>> sorted(o.id for o in container.findSources(app['ob3']))
['ob0', 'ob1']
>>> sorted(o.id for o in container.findSources(app['ob3'], None))
['ob0', 'ob1', 'ob2', 'ob5']
>>> list(o.id for o in container.findSources(app['ob5']))
['ob2']
>>> list(o.id for o in container.findSources(app['ob5'], maxDepth=2))
['ob2', 'ob1']
>>> sorted(o.id for o in container.findSources(app['ob5'], maxDepth=3))
['ob0', 'ob1', 'ob2', 'ob5']
>>> container.findSources(app['ob0'], 0)
Traceback (most recent call last):
...
ValueError: maxDepth must be None or a positive integer
>>> container.findSources(app['ob0'], -1)
Traceback (most recent call last):
...
ValueError: maxDepth must be None or a positive integer
>>> container.findSources(app['ob0'], 'kumquat') # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: ...
The `findRelationships` method finds all relationships from, to, or between
two objects. Because it supports transitive relationships, each member of the
resulting iterator is a tuple of one or more relationships.
All arguments to findRelationships are optional, but at least one of `source`
or `target` must be passed in. A search depth defaults to one relationship
deep, like the other methods.
>>> container.findRelationships(source=app['ob0']) # doctest: +ELLIPSIS
<generator object ...>
>>> sorted(
... [repr(rel) for rel in path]
... for path in container.findRelationships(source=app['ob0']))
... # doctest: +NORMALIZE_WHITESPACE
[['<Relationship from (<Demo ob0>,) to (<Demo ob1>,)>'],
['<Relationship from (<Demo ob0>,) to (<Demo ob3>,)>'],
['<Relationship from (<Demo ob0>,) to (<Demo ob4>,)>']]
>>> list(container.findRelationships(target=app['ob0']))
[]
>>> sorted(
... [repr(rel) for rel in path]
... for path in container.findRelationships(target=app['ob3']))
... # doctest: +NORMALIZE_WHITESPACE
[['<Relationship from (<Demo ob0>,) to (<Demo ob3>,)>'],
['<Relationship from (<Demo ob1>,) to (<Demo ob3>,)>']]
>>> list(
... [repr(rel) for rel in path]
... for path in container.findRelationships(
... source=app['ob1'], target=app['ob3']))
... # doctest: +NORMALIZE_WHITESPACE
[['<Relationship from (<Demo ob1>,) to (<Demo ob3>,)>']]
>>> container.findRelationships()
Traceback (most recent call last):
...
ValueError: at least one of `source` and `target` must be provided
They may also be used as positional arguments, with the order `source` and
`target`.
>>> sorted(
... [repr(rel) for rel in path]
... for path in container.findRelationships(app['ob1']))
... # doctest: +NORMALIZE_WHITESPACE
[['<Relationship from (<Demo ob1>,) to (<Demo ob2>,)>'],
['<Relationship from (<Demo ob1>,) to (<Demo ob3>,)>']]
>>> sorted(
... [repr(rel) for rel in path]
... for path in container.findRelationships(app['ob5'], app['ob1']))
... # doctest: +NORMALIZE_WHITESPACE
[['<Relationship from (<Demo ob5>,) to (<Demo ob1>,)>']]
`maxDepth` is again available, but it is the third positional argument now, so
keyword usage will be more frequent than with the others. Notice that the
second path has two members: from ob1 to ob2, then from ob2 to ob5.
>>> sorted(
... [repr(rel) for rel in path]
... for path in container.findRelationships(app['ob1'], maxDepth=2))
... # doctest: +NORMALIZE_WHITESPACE
[['<Relationship from (<Demo ob1>,) to (<Demo ob2>,)>'],
['<Relationship from (<Demo ob1>,) to (<Demo ob2>,)>',
'<Relationship from (<Demo ob2>,) to (<Demo ob5>,)>'],
['<Relationship from (<Demo ob1>,) to (<Demo ob3>,)>']]
Unique relationships are returned, rather than unique objects. Therefore,
while ob3 only has two transitive sources, ob1 and ob0, it has three transitive
paths.
>>> sorted(
... [repr(rel) for rel in path]
... for path in container.findRelationships(
... target=app['ob3'], maxDepth=2))
... # doctest: +NORMALIZE_WHITESPACE
[['<Relationship from (<Demo ob0>,) to (<Demo ob1>,)>',
'<Relationship from (<Demo ob1>,) to (<Demo ob3>,)>'],
['<Relationship from (<Demo ob0>,) to (<Demo ob3>,)>'],
['<Relationship from (<Demo ob1>,) to (<Demo ob3>,)>'],
['<Relationship from (<Demo ob5>,) to (<Demo ob1>,)>',
'<Relationship from (<Demo ob1>,) to (<Demo ob3>,)>']]
The same is true for the targets of ob0.
>>> sorted(
... [repr(rel) for rel in path]
... for path in container.findRelationships(
... source=app['ob0'], maxDepth=2))
... # doctest: +NORMALIZE_WHITESPACE
[['<Relationship from (<Demo ob0>,) to (<Demo ob1>,)>'],
['<Relationship from (<Demo ob0>,) to (<Demo ob1>,)>',
'<Relationship from (<Demo ob1>,) to (<Demo ob2>,)>'],
['<Relationship from (<Demo ob0>,) to (<Demo ob1>,)>',
'<Relationship from (<Demo ob1>,) to (<Demo ob3>,)>'],
['<Relationship from (<Demo ob0>,) to (<Demo ob3>,)>'],
['<Relationship from (<Demo ob0>,) to (<Demo ob4>,)>']]
Cyclic relationships are returned in a special tuple that implements
ICircularRelationshipPath. For instance, consider all of the paths that lead
from ob0. Notice first that all the paths are in order from shortest to
longest.
>>> res = list(
... [repr(rel) for rel in path]
... for path in container.findRelationships(
... app['ob0'], maxDepth=None))
... # doctest: +NORMALIZE_WHITESPACE
>>> sorted(res[:3]) # one step away # doctest: +NORMALIZE_WHITESPACE
[['<Relationship from (<Demo ob0>,) to (<Demo ob1>,)>'],
['<Relationship from (<Demo ob0>,) to (<Demo ob3>,)>'],
['<Relationship from (<Demo ob0>,) to (<Demo ob4>,)>']]
>>> sorted(res[3:5]) # two steps away # doctest: +NORMALIZE_WHITESPACE
[['<Relationship from (<Demo ob0>,) to (<Demo ob1>,)>',
'<Relationship from (<Demo ob1>,) to (<Demo ob2>,)>'],
['<Relationship from (<Demo ob0>,) to (<Demo ob1>,)>',
'<Relationship from (<Demo ob1>,) to (<Demo ob3>,)>']]
>>> res[5:] # three and four steps away # doctest: +NORMALIZE_WHITESPACE
[['<Relationship from (<Demo ob0>,) to (<Demo ob1>,)>',
'<Relationship from (<Demo ob1>,) to (<Demo ob2>,)>',
'<Relationship from (<Demo ob2>,) to (<Demo ob5>,)>'],
['<Relationship from (<Demo ob0>,) to (<Demo ob1>,)>',
'<Relationship from (<Demo ob1>,) to (<Demo ob2>,)>',
'<Relationship from (<Demo ob2>,) to (<Demo ob5>,)>',
'<Relationship from (<Demo ob5>,) to (<Demo ob1>,)>']]
The very last one is circular.
Now we'll change the expression to only include paths that implement
ICircularRelationshipPath.
>>> list(
... [repr(rel) for rel in path]
... for path in container.findRelationships(
... app['ob0'], maxDepth=None)
... if interfaces.ICircularRelationshipPath.providedBy(path))
... # doctest: +NORMALIZE_WHITESPACE
[['<Relationship from (<Demo ob0>,) to (<Demo ob1>,)>',
'<Relationship from (<Demo ob1>,) to (<Demo ob2>,)>',
'<Relationship from (<Demo ob2>,) to (<Demo ob5>,)>',
'<Relationship from (<Demo ob5>,) to (<Demo ob1>,)>']]
Note that, because relationships may have multiple targets, a relationship
that has a cycle may still be traversed for targets that do not generate a
cycle. The further paths will not be marked as a cycle.
Cycle paths not only have a marker interface to identify them, but include a
`cycled` attribute that is a frozenset of the one or more searches that would
be equivalent to following the cycle(s). If a source is provided, the searches
cycled searches would continue from the end of the path.
>>> path = [path for path in container.findRelationships(
... app['ob0'], maxDepth=None)
... if interfaces.ICircularRelationshipPath.providedBy(path)][0]
>>> path.cycled
[{'source': <Demo ob1>}]
>>> app['ob1'] in path[-1].targets
True
If only a target is provided, the `cycled` search will continue from the
first relationship in the path.
>>> path = [path for path in container.findRelationships(
... target=app['ob5'], maxDepth=None)
... if interfaces.ICircularRelationshipPath.providedBy(path)][0]
>>> path # doctest: +NORMALIZE_WHITESPACE
cycle(<Relationship from (<Demo ob5>,) to (<Demo ob1>,)>,
<Relationship from (<Demo ob1>,) to (<Demo ob2>,)>,
<Relationship from (<Demo ob2>,) to (<Demo ob5>,)>)
>>> path.cycled
[{'target': <Demo ob5>}]
maxDepth can also be used with the combination of source and target.
>>> list(container.findRelationships(
... app['ob0'], app['ob5'], maxDepth=None))
... # doctest: +NORMALIZE_WHITESPACE
[(<Relationship from (<Demo ob0>,) to (<Demo ob1>,)>,
<Relationship from (<Demo ob1>,) to (<Demo ob2>,)>,
<Relationship from (<Demo ob2>,) to (<Demo ob5>,)>)]
As usual, maxDepth must be a positive integer or None.
>>> container.findRelationships(app['ob0'], maxDepth=0)
Traceback (most recent call last):
...
ValueError: maxDepth must be None or a positive integer
>>> container.findRelationships(app['ob0'], maxDepth=-1)
Traceback (most recent call last):
...
ValueError: maxDepth must be None or a positive integer
>>> container.findRelationships(app['ob0'], maxDepth='kumquat')
... # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: ...
The `isLinked` method is a convenient way to test if two objects are linked,
or if an object is a source or target in the graph. It defaults to a maxDepth
of 1.
>>> container.isLinked(app['ob0'], app['ob1'])
True
>>> container.isLinked(app['ob0'], app['ob2'])
False
Note that maxDepth is pointless when supplying only one of source or target.
>>> container.isLinked(source=app['ob29'])
False
>>> container.isLinked(target=app['ob29'])
False
>>> container.isLinked(source=app['ob0'])
True
>>> container.isLinked(target=app['ob4'])
True
>>> container.isLinked(source=app['ob4'])
False
>>> container.isLinked(target=app['ob0'])
False
Setting maxDepth works as usual when searching for a link between two objects,
though.
>>> container.isLinked(app['ob0'], app['ob2'], maxDepth=2)
True
>>> container.isLinked(app['ob0'], app['ob5'], maxDepth=2)
False
>>> container.isLinked(app['ob0'], app['ob5'], maxDepth=3)
True
>>> container.isLinked(app['ob0'], app['ob5'], maxDepth=None)
True
As usual, maxDepth must be a positive integer or None.
>>> container.isLinked(app['ob0'], app['ob1'], maxDepth=0)
Traceback (most recent call last):
...
ValueError: maxDepth must be None or a positive integer
>>> container.isLinked(app['ob0'], app['ob1'], maxDepth=-1)
Traceback (most recent call last):
...
ValueError: maxDepth must be None or a positive integer
>>> container.isLinked(app['ob0'], app['ob1'], maxDepth='kumquat')
... # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: ...
The `remove` method is the next to last of the core interface: it allows you
to remove relationships from a container. It takes a relationship object.
As an example, let's remove the relationship from ob5 to ob1 that we created
to make the cycle.
>>> res = list(container.findTargets(app['ob2'], None)) # before removal
>>> len(res)
4
>>> res[:2]
[<Demo ob5>, <Demo ob1>]
>>> sorted(repr(o) for o in res[2:])
['<Demo ob2>', '<Demo ob3>']
>>> res = list(container.findSources(app['ob2'], None)) # before removal
>>> res[0]
<Demo ob1>
>>> res[3]
<Demo ob2>
>>> sorted(repr(o) for o in res[1:3])
['<Demo ob0>', '<Demo ob5>']
>>> rel = list(container.findRelationships(app['ob5'], app['ob1']))[0][0]
>>> rel.sources
(<Demo ob5>,)
>>> rel.targets
(<Demo ob1>,)
>>> container.remove(rel)
>>> list(container.findRelationships(app['ob5'], app['ob1']))
[]
>>> list(container.findTargets(app['ob2'], None)) # after removal
[<Demo ob5>]
>>> list(container.findSources(app['ob2'], None)) # after removal
[<Demo ob1>, <Demo ob0>]
Finally, the `reindex` method allows objects already in the container to be
reindexed. The default implementation of the relationship objects calls this
automatically when sources and targets are changed.
To reiterate, the relationships looked like this before. ::
ob0
| |\
ob1 | |
| | | |
ob2 ob3 ob4
|
ob5
We'll switch out ob3 and ob4, so the diagram looks like this. ::
ob0
| |\
ob1 | |
| | | |
ob2 ob4 ob3
|
ob5
>>> sorted(ob.id for ob in container.findTargets(app['ob1']))
['ob2', 'ob3']
>>> sorted(ob.id for ob in container.findSources(app['ob3']))
['ob0', 'ob1']
>>> sorted(ob.id for ob in container.findSources(app['ob4']))
['ob0']
>>> rel = next(
... iter(container.findRelationships(app['ob1'], app['ob3'])
... ))[0]
>>> rel.targets
(<Demo ob3>,)
>>> rel.targets = [app['ob4']] # this calls reindex
>>> rel.targets
(<Demo ob4>,)
>>> sorted(ob.id for ob in container.findTargets(app['ob1']))
['ob2', 'ob4']
>>> sorted(ob.id for ob in container.findSources(app['ob3']))
['ob0']
>>> sorted(ob.id for ob in container.findSources(app['ob4']))
['ob0', 'ob1']
The same sort of thing happens if we change sources. We'll change the
diagram to look like this. ::
ob0
| |\
ob1 | |
| | |
ob2 | ob3
| \ |
ob5 ob4
>>> rel.sources
(<Demo ob1>,)
>>> rel.sources = (app['ob2'],) # this calls reindex
>>> rel.sources
(<Demo ob2>,)
>>> sorted(ob.id for ob in container.findTargets(app['ob1']))
['ob2']
>>> sorted(ob.id for ob in container.findTargets(app['ob2']))
['ob4', 'ob5']
>>> sorted(ob.id for ob in container.findTargets(app['ob0']))
['ob1', 'ob3', 'ob4']
>>> sorted(ob.id for ob in container.findSources(app['ob4']))
['ob0', 'ob2']
Advanced Usage
==============
There are four other advanced tricks that the relationship container can do:
enable search filters; allow multiple sources and targets for a single
relationship; allow relating relationships; and exposing unresolved token
results.
Search Filters
--------------
Because relationships are objects themselves, a number of interesting usages
are possible. They can implement additional interfaces, have annotations,
and have other attributes. One use for this is to only find objects along
relationship paths with relationships that provide a given interface. The
`filter` argument, allowed in `findSources`, `findTargets`,
`findRelationships`, and `isLinked`, supports this kind of use case.
For instance, imagine that we change the relationships to look like the diagram
below. The `xxx` lines indicate a relationship that implements
ISpecialRelationship. ::
ob0
x |x
ob1 | x
x | x
ob2 | ob3
| x |
ob5 ob4
That is, the relationships from ob0 to ob1, ob0 to ob3, ob1 to ob2, and ob2 to
ob4 implement the special interface. Let's make this happen first.
>>> from zope import interface
>>> class ISpecialInterface(interface.Interface):
... """I'm special! So special!"""
...
>>> for src, tgt in (
... (app['ob0'], app['ob1']),
... (app['ob0'], app['ob3']),
... (app['ob1'], app['ob2']),
... (app['ob2'], app['ob4'])):
... rel = list(container.findRelationships(src, tgt))[0][0]
... interface.directlyProvides(rel, ISpecialInterface)
...
Now we can use `ISpecialInterface.providedBy` as a filter for all of the
methods mentioned above.
`findTargets`
>>> sorted(ob.id for ob in container.findTargets(app['ob0']))
['ob1', 'ob3', 'ob4']
>>> sorted(ob.id for ob in container.findTargets(
... app['ob0'], filter=ISpecialInterface.providedBy))
['ob1', 'ob3']
>>> sorted(ob.id for ob in container.findTargets(
... app['ob0'], maxDepth=None))
['ob1', 'ob2', 'ob3', 'ob4', 'ob5']
>>> sorted(ob.id for ob in container.findTargets(
... app['ob0'], maxDepth=None, filter=ISpecialInterface.providedBy))
['ob1', 'ob2', 'ob3', 'ob4']
`findSources`
>>> sorted(ob.id for ob in container.findSources(app['ob4']))
['ob0', 'ob2']
>>> sorted(ob.id for ob in container.findSources(
... app['ob4'], filter=ISpecialInterface.providedBy))
['ob2']
>>> sorted(ob.id for ob in container.findSources(
... app['ob4'], maxDepth=None))
['ob0', 'ob1', 'ob2']
>>> sorted(ob.id for ob in container.findSources(
... app['ob4'], maxDepth=None, filter=ISpecialInterface.providedBy))
['ob0', 'ob1', 'ob2']
>>> sorted(ob.id for ob in container.findSources(
... app['ob5'], maxDepth=None))
['ob0', 'ob1', 'ob2']
>>> list(ob.id for ob in container.findSources(
... app['ob5'], filter=ISpecialInterface.providedBy))
[]
`findRelationships`
>>> len(list(container.findRelationships(
... app['ob0'], app['ob4'], maxDepth=None)))
2
>>> len(list(container.findRelationships(
... app['ob0'], app['ob4'], maxDepth=None,
... filter=ISpecialInterface.providedBy)))
1
>>> len(list(container.findRelationships(app['ob0'])))
3
>>> len(list(container.findRelationships(
... app['ob0'], filter=ISpecialInterface.providedBy)))
2
`isLinked`
>>> container.isLinked(app['ob0'], app['ob5'], maxDepth=None)
True
>>> container.isLinked(
... app['ob0'], app['ob5'], maxDepth=None,
... filter=ISpecialInterface.providedBy)
False
>>> container.isLinked(
... app['ob0'], app['ob2'], maxDepth=None,
... filter=ISpecialInterface.providedBy)
True
>>> container.isLinked(
... app['ob0'], app['ob4'])
True
>>> container.isLinked(
... app['ob0'], app['ob4'],
... filter=ISpecialInterface.providedBy)
False
Multiple Sources and/or Targets; Duplicate Relationships
--------------------------------------------------------
Relationships are not always between a single source and a single target. Many
approaches to this are possible, but a simple one is to allow relationships to
have multiple sources and multiple targets. This is an approach that the
relationship container supports.
>>> container.add(Relationship(
... (app['ob2'], app['ob4'], app['ob5'], app['ob6'], app['ob7']),
... (app['ob1'], app['ob4'], app['ob8'], app['ob9'], app['ob10'])))
>>> container.add(Relationship(
... (app['ob10'], app['ob0']),
... (app['ob7'], app['ob3'])))
Before we examine the results, look at those for a second.
Among the interesting items is that we have duplicated the ob2->ob4
relationship in the first example, and duplicated the ob0->ob3 relationship
in the second. The relationship container does not limit duplicate
relationships: it simply adds and indexes them, and will include the additional
relationship path in findRelationships.
>>> sorted(o.id for o in container.findTargets(app['ob4']))
['ob1', 'ob10', 'ob4', 'ob8', 'ob9']
>>> sorted(o.id for o in container.findTargets(app['ob10']))
['ob3', 'ob7']
>>> sorted(o.id for o in container.findTargets(app['ob4'], maxDepth=2))
['ob1', 'ob10', 'ob2', 'ob3', 'ob4', 'ob7', 'ob8', 'ob9']
>>> sorted(
... [repr(rel) for rel in path]
... for path in container.findRelationships(
... app['ob2'], app['ob4']))
... # doctest: +NORMALIZE_WHITESPACE
[['<Relationship from
(<Demo ob2>, <Demo ob4>, <Demo ob5>, <Demo ob6>, <Demo ob7>)
to
(<Demo ob1>, <Demo ob4>, <Demo ob8>, <Demo ob9>, <Demo ob10>)>'],
['<Relationship from (<Demo ob2>,) to (<Demo ob4>,)>']]
There's also a reflexive relationship in there, with ob4 pointing to ob4. It's
marked as a cycle.
>>> list(container.findRelationships(app['ob4'], app['ob4']))
... # doctest: +NORMALIZE_WHITESPACE
[cycle(<Relationship from
(<Demo ob2>, <Demo ob4>, <Demo ob5>, <Demo ob6>, <Demo ob7>)
to
(<Demo ob1>, <Demo ob4>, <Demo ob8>, <Demo ob9>, <Demo ob10>)>,)]
>>> list(container.findRelationships(app['ob4'], app['ob4']))[0].cycled
[{'source': <Demo ob4>}]
Relating Relationships and Relationship Containers
--------------------------------------------------
Relationships are objects. We've already shown and discussed how this means
that they can implement different interfaces and be annotated. It also means
that relationships are first-class objects that can be related themselves.
This allows relationships that keep track of who created other relationships,
and other use cases.
Even the relationship containers themselves can be nodes in a relationship
container.
>>> container1 = app['container1'] = Container()
>>> container2 = app['container2'] = Container()
>>> rel = Relationship((container1,), (container2,))
>>> container.add(rel)
>>> container.isLinked(container1, container2)
True
Exposing Unresolved Tokens
--------------------------
For specialized use cases, usually optimizations, sometimes it is useful to
have access to raw results from a given implementation. For instance, if a
relationship has many members, it might make sense to have an intid-based
relationship container return the actual intids.
The containers include three methods for these sorts of use cases:
`findTargetTokens`, `findSourceTokens`, and `findRelationshipTokens`. They
take the same arguments as their similarly-named cousins.
Convenience classes
-------------------
Three convenience classes exist for relationships with a single source and/or a
single target only.
One-To-One Relationship
~~~~~~~~~~~~~~~~~~~~~~~
A `OneToOneRelationship` relates a single source to a single target.
>>> from zc.relationship.shared import OneToOneRelationship
>>> rel = OneToOneRelationship(app['ob20'], app['ob21'])
>>> verifyObject(interfaces.IOneToOneRelationship, rel)
True
All container methods work as for the general many-to-many relationship. We
repeat some of the tests defined in the main section above (all relationships
defined there are actually one-to-one relationships).
>>> container.add(rel)
>>> container.add(OneToOneRelationship(app['ob21'], app['ob22']))
>>> container.add(OneToOneRelationship(app['ob21'], app['ob23']))
>>> container.add(OneToOneRelationship(app['ob20'], app['ob23']))
>>> container.add(OneToOneRelationship(app['ob20'], app['ob24']))
>>> container.add(OneToOneRelationship(app['ob22'], app['ob25']))
>>> rel = OneToOneRelationship(app['ob25'], app['ob21'])
>>> container.add(rel)
`findTargets`
>>> sorted(o.id for o in container.findTargets(app['ob20'], 2))
['ob21', 'ob22', 'ob23', 'ob24']
`findSources`
>>> sorted(o.id for o in container.findSources(app['ob21'], 2))
['ob20', 'ob22', 'ob25']
`findRelationships`
>>> sorted(
... [repr(rel) for rel in path]
... for path in container.findRelationships(app['ob21'], maxDepth=2))
... # doctest: +NORMALIZE_WHITESPACE
[['<Relationship from (<Demo ob21>,) to (<Demo ob22>,)>'],
['<Relationship from (<Demo ob21>,) to (<Demo ob22>,)>',
'<Relationship from (<Demo ob22>,) to (<Demo ob25>,)>'],
['<Relationship from (<Demo ob21>,) to (<Demo ob23>,)>']]
>>> sorted(
... [repr(rel) for rel in path]
... for path in container.findRelationships(
... target=app['ob23'], maxDepth=2))
... # doctest: +NORMALIZE_WHITESPACE
[['<Relationship from (<Demo ob20>,) to (<Demo ob21>,)>',
'<Relationship from (<Demo ob21>,) to (<Demo ob23>,)>'],
['<Relationship from (<Demo ob20>,) to (<Demo ob23>,)>'],
['<Relationship from (<Demo ob21>,) to (<Demo ob23>,)>'],
['<Relationship from (<Demo ob25>,) to (<Demo ob21>,)>',
'<Relationship from (<Demo ob21>,) to (<Demo ob23>,)>']]
>>> list(container.findRelationships(
... app['ob20'], app['ob25'], maxDepth=None))
... # doctest: +NORMALIZE_WHITESPACE
[(<Relationship from (<Demo ob20>,) to (<Demo ob21>,)>,
<Relationship from (<Demo ob21>,) to (<Demo ob22>,)>,
<Relationship from (<Demo ob22>,) to (<Demo ob25>,)>)]
>>> list(
... [repr(rel) for rel in path]
... for path in container.findRelationships(
... app['ob20'], maxDepth=None)
... if interfaces.ICircularRelationshipPath.providedBy(path))
... # doctest: +NORMALIZE_WHITESPACE
[['<Relationship from (<Demo ob20>,) to (<Demo ob21>,)>',
'<Relationship from (<Demo ob21>,) to (<Demo ob22>,)>',
'<Relationship from (<Demo ob22>,) to (<Demo ob25>,)>',
'<Relationship from (<Demo ob25>,) to (<Demo ob21>,)>']]
`isLinked`
>>> container.isLinked(source=app['ob20'])
True
>>> container.isLinked(target=app['ob24'])
True
>>> container.isLinked(source=app['ob24'])
False
>>> container.isLinked(target=app['ob20'])
False
>>> container.isLinked(app['ob20'], app['ob22'], maxDepth=2)
True
>>> container.isLinked(app['ob20'], app['ob25'], maxDepth=2)
False
`remove`
>>> res = list(container.findTargets(app['ob22'], None)) # before removal
>>> res[:2]
[<Demo ob25>, <Demo ob21>]
>>> container.remove(rel)
>>> list(container.findTargets(app['ob22'], None)) # after removal
[<Demo ob25>]
`reindex`
>>> rel = next(
... iter(container.findRelationships(app['ob21'], app['ob23']))
... )[0]
>>> rel.target
<Demo ob23>
>>> rel.target = app['ob24'] # this calls reindex
>>> rel.target
<Demo ob24>
>>> rel.source
<Demo ob21>
>>> rel.source = app['ob22'] # this calls reindex
>>> rel.source
<Demo ob22>
ManyToOneRelationship
~~~~~~~~~~~~~~~~~~~~~
A `ManyToOneRelationship` relates multiple sources to a single target.
>>> from zc.relationship.shared import ManyToOneRelationship
>>> rel = ManyToOneRelationship((app['ob22'], app['ob26']), app['ob24'])
>>> verifyObject(interfaces.IManyToOneRelationship, rel)
True
>>> container.add(rel)
>>> container.add(ManyToOneRelationship(
... (app['ob26'], app['ob23']),
... app['ob20']))
The relationship diagram now looks like this::
ob20 (ob22, obj26) (ob26, obj23)
| |\ | |
ob21 | | obj24 obj20
| | |
ob22 | ob23
| \ |
ob25 ob24
We created a cycle for obj20 via obj23.
>>> sorted(o.id for o in container.findSources(app['ob24'], None))
['ob20', 'ob21', 'ob22', 'ob23', 'ob26']
>>> sorted(o.id for o in container.findSources(app['ob20'], None))
['ob20', 'ob23', 'ob26']
>>> list(container.findRelationships(app['ob20'], app['ob20'], None))
... # doctest: +NORMALIZE_WHITESPACE
[cycle(<Relationship from (<Demo ob20>,) to (<Demo ob23>,)>,
<Relationship from (<Demo ob26>, <Demo ob23>) to (<Demo ob20>,)>)]
>>> list(container.findRelationships(
... app['ob20'], app['ob20'], 2))[0].cycled
[{'source': <Demo ob20>}]
The `ManyToOneRelationship`'s `sources` attribute is mutable, while it's
`targets` attribute is immutable.
>>> rel.sources
(<Demo ob22>, <Demo ob26>)
>>> rel.sources = [app['ob26'], app['ob24']]
>>> rel.targets
(<Demo ob24>,)
>>> rel.targets = (app['ob22'],)
Traceback (most recent call last):
...
AttributeError: can't set attribute
But the relationship has an additional mutable `target` attribute.
>>> rel.target
<Demo ob24>
>>> rel.target = app['ob22']
OneToManyRelationship
~~~~~~~~~~~~~~~~~~~~~
A `OneToManyRelationship` relates a single source to multiple targets.
>>> from zc.relationship.shared import OneToManyRelationship
>>> rel = OneToManyRelationship(app['ob22'], (app['ob20'], app['ob27']))
>>> verifyObject(interfaces.IOneToManyRelationship, rel)
True
>>> container.add(rel)
>>> container.add(OneToManyRelationship(
... app['ob20'],
... (app['ob23'], app['ob28'])))
The updated diagram looks like this::
ob20 (ob26, obj24) (ob26, obj23)
| |\ | |
ob21 | | obj22 obj20
| | | | |
ob22 | ob23 (ob20, obj27) (ob23, obj28)
| \ |
ob25 ob24
Alltogether there are now three cycles for ob22.
>>> sorted(o.id for o in container.findTargets(app['ob22']))
['ob20', 'ob24', 'ob25', 'ob27']
>>> sorted(o.id for o in container.findTargets(app['ob22'], None))
['ob20', 'ob21', 'ob22', 'ob23', 'ob24', 'ob25', 'ob27', 'ob28']
>>> sorted(o.id for o in container.findTargets(app['ob20']))
['ob21', 'ob23', 'ob24', 'ob28']
>>> sorted(o.id for o in container.findTargets(app['ob20'], None))
['ob20', 'ob21', 'ob22', 'ob23', 'ob24', 'ob25', 'ob27', 'ob28']
>>> sorted(repr(c) for c in
... container.findRelationships(app['ob22'], app['ob22'], None))
... # doctest: +NORMALIZE_WHITESPACE
['cycle(<Relationship from (<Demo ob22>,) to (<Demo ob20>, <Demo ob27>)>,
<Relationship from (<Demo ob20>,) to (<Demo ob21>,)>,
<Relationship from (<Demo ob21>,) to (<Demo ob22>,)>)',
'cycle(<Relationship from (<Demo ob22>,) to (<Demo ob20>, <Demo ob27>)>,
<Relationship from (<Demo ob20>,) to (<Demo ob24>,)>,
<Relationship from (<Demo ob26>, <Demo ob24>) to (<Demo ob22>,)>)',
'cycle(<Relationship from (<Demo ob22>,) to (<Demo ob24>,)>,
<Relationship from (<Demo ob26>, <Demo ob24>) to (<Demo ob22>,)>)']
The `OneToManyRelationship`'s `targets` attribute is mutable, while it's
`sources` attribute is immutable.
>>> rel.targets
(<Demo ob20>, <Demo ob27>)
>>> rel.targets = [app['ob28'], app['ob21']]
>>> rel.sources
(<Demo ob22>,)
>>> rel.sources = (app['ob23'],)
Traceback (most recent call last):
...
AttributeError: can't set attribute
But the relationship has an additional mutable `source` attribute.
>>> rel.source
<Demo ob22>
>>> rel.target = app['ob23']
| zc.relationship | /zc.relationship-2.1.tar.gz/zc.relationship-2.1/src/zc/relationship/container.rst | container.rst |
import persistent
import persistent.interfaces
import BTrees
from zope import interface, component
import zope.interface.interfaces
from zope.app.intid.interfaces import IIntIds
import zope.app.container.contained
from zc.relationship import interfaces
import zc.relation.catalog
# N.B.
# this is now a subclass of the zc.relation.catalog.Catalog. It only exists
# to provide backwards compatibility. New work should go in zc.relation.
# Ideally, new code should use the zc.relation code directly.
##############################################################################
# the marker that shows that a path is circular
#
CircularRelationshipPath = zc.relation.catalog.CircularRelationPath
##############################################################################
# a common case transitive queries factory
@interface.implementer(interfaces.ITransitiveQueriesFactory)
class TransposingTransitiveQueriesFactory(persistent.Persistent):
def __init__(self, name1, name2):
self.names = [name1, name2] # a list so we can use index
def __call__(self, relchain, query, index, cache):
dynamic = cache.get('dynamic')
if dynamic is None:
static = cache['static'] = {}
dynamic = cache['dynamic'] = []
for nm, val in query.items():
try:
ix = self.names.index(nm)
except ValueError:
static[nm] = val
else:
if dynamic:
# both were specified: no transitive search known.
del dynamic[:]
break
else:
dynamic.append(nm)
dynamic.append(self.names[not ix])
else:
static = cache['static']
if dynamic:
name = dynamic[1]
if name is None:
rels = (relchain[-1],)
else:
rels = index.findValueTokenSet(relchain[-1], name)
for r in rels:
res = {dynamic[0]: r}
res.update(static)
yield res
def factoryWrapper(factory, query, index):
cache = {}
def getQueries(relchain):
if not relchain:
return (query,)
return factory(relchain, query, index, cache)
return getQueries
##############################################################################
# a common case intid getter and setter
def generateToken(obj, index, cache):
intids = cache.get('intids')
if intids is None:
intids = cache['intids'] = component.getUtility(IIntIds)
return intids.register(obj)
def resolveToken(token, index, cache):
intids = cache.get('intids')
if intids is None:
intids = cache['intids'] = component.getUtility(IIntIds)
return intids.getObject(token)
##############################################################################
# the relationship index
@interface.implementer_only(
interfaces.IIndex, interface.implementedBy(persistent.Persistent),
interface.implementedBy(zope.app.container.contained.Contained)
)
class Index(zc.relation.catalog.Catalog,
zope.app.container.contained.Contained):
def __init__(self, attrs, defaultTransitiveQueriesFactory=None,
dumpRel=generateToken, loadRel=resolveToken,
relFamily=None, family=None, deactivateSets=False):
super(Index, self).__init__(dumpRel, loadRel, relFamily, family)
self.defaultTransitiveQueriesFactory = defaultTransitiveQueriesFactory
for data in attrs:
if zope.interface.interfaces.IElement.providedBy(data):
data = {'element': data}
if 'callable' in data:
if 'element' in data:
raise ValueError(
'cannot provide both callable and element')
data['element'] = data.pop('callable')
elif 'element' not in data:
raise ValueError('must provide element or callable')
if 'dump' not in data:
data['dump'] = generateToken
if 'load' not in data:
data['load'] = resolveToken
self.addValueIndex(**data)
# deactivateSets is now ignored. It was broken before.
# disable zc.relation default query factories, enable zc.relationship
addDefaultQueryFactory = iterDefaultQueryFactories = None
removeDefaultQueryFactory = None
def _getQueryFactory(self, query, queryFactory):
res = None
if queryFactory is None:
queryFactory = self.defaultTransitiveQueriesFactory
if queryFactory is not None:
res = factoryWrapper(queryFactory, query, self)
return queryFactory, res
# disable search indexes
_iterListeners = zc.relation.catalog.Catalog.iterListeners
addSearchIndex = iterSearchIndexes = removeSearchIndex = None
def documentCount(self):
return self._relLength.value
def wordCount(self):
return 0 # we don't index words
def apply(self, query):
# there are two kinds of queries: values and relationships.
if len(query) != 1:
raise ValueError('one key in the primary query dictionary')
(searchType, query) = list(query.items())[0]
if searchType == 'relationships':
relTools = self.getRelationModuleTools()
if relTools['TreeSet'].__name__[:2] not in ('IF', 'LF'):
raise ValueError(
'cannot fulfill `apply` interface because cannot return '
'an (I|L)FBTree-based result')
res = self.getRelationTokens(query)
if res is None:
res = relTools['TreeSet']()
return res
elif searchType == 'values':
data = self._attrs[query['resultName']]
if data['TreeSet'].__name__[:2] not in ('IF', 'LF'):
raise ValueError(
'cannot fulfill `apply` interface because cannot return '
'an (I|L)FBTree-based result')
q = BTrees.family32.OO.Bucket(query.get('query', ()))
targetq = BTrees.family32.OO.Bucket(query.get('targetQuery', ()))
queryFactory, getQueries = self._getQueryFactory(
q, query.get('transitiveQueriesFactory'))
iterable = self._yieldValueTokens(
query['resultName'], *(self._parse(
q, query.get('maxDepth'), query.get('filter'), targetq,
query.get('targetFilter'), getQueries) +
(True,)))
# IF and LF have multiunion; can demand its presence
return data['multiunion'](tuple(iterable))
else:
raise ValueError('unknown query type', searchType)
tokenizeRelationship = zc.relation.catalog.Catalog.tokenizeRelation
resolveRelationshipToken = (
zc.relation.catalog.Catalog.resolveRelationToken)
tokenizeRelationships = zc.relation.catalog.Catalog.tokenizeRelations
resolveRelationshipTokens = (
zc.relation.catalog.Catalog.resolveRelationTokens)
def findRelationshipTokenSet(self, query):
# equivalent to findRelationshipTokens(query, maxDepth=1)
res = self._relData(query)
if res is None:
res = self._relTools['TreeSet']()
return res
def findValueTokenSet(self, reltoken, name):
# equivalent to findValueTokens(name, {None: reltoken}, maxDepth=1)
res = self._reltoken_name_TO_objtokenset.get((reltoken, name))
if res is None:
res = self._attrs[name]['TreeSet']()
return res
def findValueTokens(self, resultName, query=(), maxDepth=None,
filter=None, targetQuery=None, targetFilter=None,
transitiveQueriesFactory=None, _ignored=None):
# argument names changed slightly
if targetQuery is None:
targetQuery = ()
return super(Index, self).findValueTokens(
resultName, query, maxDepth, filter, targetQuery, targetFilter,
transitiveQueriesFactory, True)
def findValues(self, resultName, query=(), maxDepth=None, filter=None,
targetQuery=None, targetFilter=None,
transitiveQueriesFactory=None):
# argument names changed slightly
if targetQuery is None:
targetQuery = ()
return super(Index, self).findValues(
resultName, query, maxDepth, filter, targetQuery, targetFilter,
transitiveQueriesFactory)
def findRelationships(self, query=(), maxDepth=None, filter=None,
targetQuery=None, targetFilter=None,
transitiveQueriesFactory=None):
# argument names changed slightly
if targetQuery is None:
targetQuery = ()
return super(Index, self).findRelations(
query, maxDepth, filter, targetQuery, targetFilter,
transitiveQueriesFactory)
def findRelationshipTokens(self, query=(), maxDepth=None, filter=None,
targetQuery=None, targetFilter=None,
transitiveQueriesFactory=None, _ignored=None):
# argument names changed slightly
if targetQuery is None:
targetQuery = ()
return super(Index, self).findRelationTokens(
query, maxDepth, filter, targetQuery, targetFilter,
transitiveQueriesFactory, True)
def findRelationshipTokenChains(self, query=(), maxDepth=None, filter=None,
targetQuery=None, targetFilter=None,
transitiveQueriesFactory=None):
# argument names changed slightly
if targetQuery is None:
targetQuery = ()
return super(Index, self).findRelationTokenChains(
query, maxDepth, filter, targetQuery, targetFilter,
transitiveQueriesFactory)
def findRelationshipChains(self, query=(), maxDepth=None, filter=None,
targetQuery=None, targetFilter=None,
transitiveQueriesFactory=None):
# argument names changed slightly
if targetQuery is None:
targetQuery = ()
return super(Index, self).findRelationChains(
query, maxDepth, filter, targetQuery, targetFilter,
transitiveQueriesFactory)
def isLinked(self, query=(), maxDepth=None, filter=None,
targetQuery=None, targetFilter=None,
transitiveQueriesFactory=None):
# argument names changed slightly
if targetQuery is None:
targetQuery = ()
return super(Index, self).canFind(
query, maxDepth, filter, targetQuery, targetFilter,
transitiveQueriesFactory) | zc.relationship | /zc.relationship-2.1.tar.gz/zc.relationship-2.1/src/zc/relationship/index.py | index.py |
zc.reloadmonitor
****************
zc.reloadmonitor provides a plug-in for zc.monitor. It allows you to
cause already imported modules to be reloaded.
To use, just connect to the monitor port and give the command::
reload my.module
To configure/enable from Python, use::
import zc.reloadmodule
zc.reloadmonitor.configure()
To configure from ZCML, use::
<include package="zc.reloadmonitor" />
Changes
*******
0.3.0 (2010-10-07)
==================
- Fixed setup.py so that `configure.zcml` gets properly included on install.
0.2.0 (2010-10-07)
==================
- Make the reload monitor compatible with zope.interface 3.5.
0.1.0 (2010-09-03)
==================
Initial release
| zc.reloadmonitor | /zc.reloadmonitor-0.3.0.tar.gz/zc.reloadmonitor-0.3.0/README.txt | README.txt |
=========
CHANGES
=========
2.1.0 (2018-10-19)
==================
- Add support for Python 3.7.
2.0.0 (2017-05-23)
==================
- Add support for Python 3.4, 3.5, 3.6 and PyPy.
- Drop test dependency on ``zope.app.testing`` and
``zope.app.zcmlfiles``, among others.
- Make zope.app.publication dependency optional.
1.3.4 (2012-01-20)
==================
- Register adapters with getSiteManager rather than getGlobalSiteManager. This
allows registering resource libraries in non-global sites. For detais see:
- https://mail.zope.org/pipermail/zope-dev/2010-March/039657.html
- http://docs.pylonsproject.org/projects/pyramid_zcml/en/latest/narr.html#using-broken-zcml-directives
- Raise NotImplementedError if we find that a second ZCML declaration would
change the global library_info dict in a way that may (depending on ZCML
ordering) break applications at runtime. These errors were pretty hard to
debug.
- Remove unneeded test dependencies on ``zope.app.authentication`` and
``zope.app.securitypolicy``.
- Remove dependency on ``zope.app.pagetemplate``.
1.3.2 (2010-08-16)
==================
- Response._addDependencies will only include a ResourceLibrary in the
list of dependencies if the ResourceLibrary actually has included
resources.
This makes directives that simply declare dependencies on other
libraries work again.
- Add missing depedency on ``zope.app.pagetemplate``, clean up unused
imports and whitespace.
1.3.1 (2010-03-24)
==================
- Resource libraries that are required during a retried request are now
correctly registered and injected to the HTML.
- Import hooks functionality from zope.component after it was moved there from
zope.site. This lifts the dependency on zope.site.
- Removed an unused ISite import and thereby, the undeclared dependency on
zope.location.
1.3.0 (2009-10-08)
==================
- Use ``zope.browserresource`` instead of ``zope.app.publisher``, removing
a dependency on latter.
- Look up the "resources view" via queryMultiAdapter instead of looking into
the adapter registry.
- Moved the dependency on zope.site to the test dependencies.
1.2.0 (2009-06-04)
==================
- Use ``zope.site`` instead of ``zope.app.component``. Removes direct
dependency on ``zope.app.component``.
1.1.0 (2009-05-05)
==================
New features:
- An attempt to generate resource URLs using the "resources view" (@@)
is now made; if unsuccesful, we fall back to the previous method of
crafting the URL by hand from the site url. This ensures that the
resource library respects the existing plugging points for resource
publishing (see ``zope.app.publisher.browser.resources``).
- You can now explicitly specify where resource links should be
inserted using the special marker comment '<!-- zc.resourcelibrary -->'.
1.0.2 (2009-01-27)
==================
- Remove zope.app.zapi from dependencies, substituting
its uses with direct imports.
- Use zope-dev at zope.org mailing list address instead of
zope3-dev at zope.org as the latter one is retired.
- Change "cheeseshop" to "pypi" in the package homepage.
1.0.1 (2008-03-07)
==================
Bugs fixed:
- added the behavior from the standard Zope 3 response to guess that a body
that is not HTML without an explicit mimetype should have a
'text/plain' mimetype. This means that, for instance, redirects with
a body of '' and no explicit content type will no longer cause an
exception in the resourcelibrary response code.
1.0.0 (2008-02-17)
==================
New features:
- You can now provide an alternative "directory-resource"
factory. This facilitates implementation of dynamic resources.
Bugs fixed:
- Updated the functional-testing zcml file to get rid of a deprecation
warning.
0.8.2 (2007-12-07)
==================
- bug fix: when checking content type, take into account that it may be None
0.8.1 (2007-12-05)
==================
- changed MIME type handling to be more restrictive about whitespace to
conform to RfC 2045
0.8 (2007-12-04)
================
- fixed the check for HTML and XML content to allow content type parameters
0.6.1 (2007-11-03)
==================
- Update package meta-data.
- Fixed package dependencies.
- Merged functional and unit tests.
0.6.0 (2006-09-22)
==================
???
0.5.2 (2006-06-15)
==================
- Add more package meta-data.
0.5.1 (2006-06-06)
==================
- Update package code to work with newer versions of other packages.
0.5.0 (2006-04-24)
==================
- Initial release.
| zc.resourcelibrary | /zc.resourcelibrary-2.1.0.tar.gz/zc.resourcelibrary-2.1.0/CHANGES.rst | CHANGES.rst |
import os
import shutil
import sys
import tempfile
from optparse import OptionParser
__version__ = '2015-07-01'
# See zc.buildout's changelog if this version is up to date.
tmpeggs = tempfile.mkdtemp(prefix='bootstrap-')
usage = '''\
[DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options]
Bootstraps a buildout-based project.
Simply run this script in a directory containing a buildout.cfg, using the
Python that you want bin/buildout to use.
Note that by using --find-links to point to local resources, you can keep
this script from going over the network.
'''
parser = OptionParser(usage=usage)
parser.add_option("--version",
action="store_true", default=False,
help=("Return bootstrap.py version."))
parser.add_option("-t", "--accept-buildout-test-releases",
dest='accept_buildout_test_releases',
action="store_true", default=False,
help=("Normally, if you do not specify a --version, the "
"bootstrap script and buildout gets the newest "
"*final* versions of zc.buildout and its recipes and "
"extensions for you. If you use this flag, "
"bootstrap and buildout will get the newest releases "
"even if they are alphas or betas."))
parser.add_option("-c", "--config-file",
help=("Specify the path to the buildout configuration "
"file to be used."))
parser.add_option("-f", "--find-links",
help=("Specify a URL to search for buildout releases"))
parser.add_option("--allow-site-packages",
action="store_true", default=False,
help=("Let bootstrap.py use existing site packages"))
parser.add_option("--buildout-version",
help="Use a specific zc.buildout version")
parser.add_option("--setuptools-version",
help="Use a specific setuptools version")
parser.add_option("--setuptools-to-dir",
help=("Allow for re-use of existing directory of "
"setuptools versions"))
options, args = parser.parse_args()
if options.version:
print("bootstrap.py version %s" % __version__)
sys.exit(0)
######################################################################
# load/install setuptools
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
ez = {}
if os.path.exists('ez_setup.py'):
exec(open('ez_setup.py').read(), ez)
else:
exec(urlopen('https://bootstrap.pypa.io/ez_setup.py').read(), ez)
if not options.allow_site_packages:
# ez_setup imports site, which adds site packages
# this will remove them from the path to ensure that incompatible versions
# of setuptools are not in the path
import site
# inside a virtualenv, there is no 'getsitepackages'.
# We can't remove these reliably
if hasattr(site, 'getsitepackages'):
for sitepackage_path in site.getsitepackages():
# Strip all site-packages directories from sys.path that
# are not sys.prefix; this is because on Windows
# sys.prefix is a site-package directory.
if sitepackage_path != sys.prefix:
sys.path[:] = [x for x in sys.path
if sitepackage_path not in x]
setup_args = dict(to_dir=tmpeggs, download_delay=0)
if options.setuptools_version is not None:
setup_args['version'] = options.setuptools_version
if options.setuptools_to_dir is not None:
setup_args['to_dir'] = options.setuptools_to_dir
ez['use_setuptools'](**setup_args)
import setuptools
import pkg_resources
# This does not (always?) update the default working set. We will
# do it.
for path in sys.path:
if path not in pkg_resources.working_set.entries:
pkg_resources.working_set.add_entry(path)
######################################################################
# Install buildout
ws = pkg_resources.working_set
setuptools_path = ws.find(
pkg_resources.Requirement.parse('setuptools')).location
# Fix sys.path here as easy_install.pth added before PYTHONPATH
cmd = [sys.executable, '-c',
'import sys; sys.path[0:0] = [%r]; ' % setuptools_path +
'from setuptools.command.easy_install import main; main()',
'-mZqNxd', tmpeggs]
find_links = os.environ.get(
'bootstrap-testing-find-links',
options.find_links or
('http://downloads.buildout.org/'
if options.accept_buildout_test_releases else None)
)
if find_links:
cmd.extend(['-f', find_links])
requirement = 'zc.buildout'
version = options.buildout_version
if version is None and not options.accept_buildout_test_releases:
# Figure out the most recent final version of zc.buildout.
import setuptools.package_index
_final_parts = '*final-', '*final'
def _final_version(parsed_version):
try:
return not parsed_version.is_prerelease
except AttributeError:
# Older setuptools
for part in parsed_version:
if (part[:1] == '*') and (part not in _final_parts):
return False
return True
index = setuptools.package_index.PackageIndex(
search_path=[setuptools_path])
if find_links:
index.add_find_links((find_links,))
req = pkg_resources.Requirement.parse(requirement)
if index.obtain(req) is not None:
best = []
bestv = None
for dist in index[req.project_name]:
distv = dist.parsed_version
if _final_version(distv):
if bestv is None or distv > bestv:
best = [dist]
bestv = distv
elif distv == bestv:
best.append(dist)
if best:
best.sort()
version = best[-1].version
if version:
requirement = '=='.join((requirement, version))
cmd.append(requirement)
import subprocess
if subprocess.call(cmd) != 0:
raise Exception(
"Failed to execute command:\n%s" % repr(cmd)[1:-1])
######################################################################
# Import and run buildout
ws.add_entry(tmpeggs)
ws.require(requirement)
import zc.buildout.buildout
if not [a for a in args if '=' not in a]:
args.append('bootstrap')
# if -c was provided, we push it back into args for buildout' main function
if options.config_file is not None:
args[0:0] = ['-c', options.config_file]
zc.buildout.buildout.main(args)
shutil.rmtree(tmpeggs) | zc.resourcelibrary | /zc.resourcelibrary-2.1.0.tar.gz/zc.resourcelibrary-2.1.0/bootstrap.py | bootstrap.py |
from zope import interface
from zope.component import queryMultiAdapter, getMultiAdapter
from zope.publisher.browser import BrowserRequest, BrowserResponse
from zope.publisher.browser import isHTML
from zope.publisher.interfaces.browser import IBrowserPublisher
from zope.traversing.browser.interfaces import IAbsoluteURL
import zc.resourcelibrary
import zope.component.hooks
try:
from zope.app.publication.interfaces import IBrowserRequestFactory
except: # pragma: no cover
class IBrowserRequestFactory(interface.Interface):
pass
@interface.provider(IBrowserRequestFactory)
class Request(BrowserRequest):
# __slots__ = ('resource_libraries',)
def _createResponse(self):
response = Response()
self.resource_libraries = response.resource_libraries = []
return response
def retry(self):
"""Returns request object to be used in a retry attempt.
In addition to BrowswerRequest's retry() the libraries are copied over
to the new request. Otherwise it is not possible to add even new
libraries to a retried request.
>>> from io import BytesIO
>>> request = Request(BytesIO(), {})
>>> request.resource_libraries = ['foo']
>>> retry_request = request.retry()
>>> retry_request is request
False
>>> request.resource_libraries is retry_request.resource_libraries
True
The assigned libraries are flushed because a new request will define
its own set of required libraries.
>>> request.resource_libraries
[]
"""
request = super(Request, self).retry()
if hasattr(self, 'resource_libraries'):
request.resource_libraries = self.resource_libraries
request.resource_libraries[:] = []
return request
class Response(BrowserResponse):
def retry(self):
"""
Returns a response object to be used in a retry attempt.
>>> response = Response()
>>> response
<zc.resourcelibrary.publication.Response object at ...>
>>> response1 = response.retry()
The returned object is not the same.
>>> response1 is response
False
If resource_libraries are defined they are assigned to the new
response.
>>> rl = ['a','b','c']
>>> response.resource_libraries = rl
>>> response.retry().resource_libraries is rl
True
>>> response.retry().retry().resource_libraries is rl
True
"""
response = super(Response, self).retry()
if hasattr(self, 'resource_libraries'):
response.resource_libraries = self.resource_libraries
return response
def _implicitResult(self, body):
# figure out the content type
content_type = self.getHeader('content-type')
if content_type is None:
if isHTML(body):
content_type = 'text/html'
else:
content_type = 'text/plain'
self.setHeader('x-content-type-warning', 'guessed from content')
self.setHeader('content-type', content_type)
# check the content type disregarding parameters and case
if content_type and content_type.split(';', 1)[0].lower() in (
'text/html', 'text/xml'):
# act on HTML and XML content only!
resource_libraries = self._addDependencies(self.resource_libraries)
html = self._generateIncludes(resource_libraries)
if html:
# This is a pretty low-rent way of adding things to the head.
# We should probably use a real HTML parser instead.
marker = body.find('<!-- zc.resourcelibrary -->')
if marker != -1:
body = body[:marker] + html + body[marker+27:]
else:
body = body.replace('<head>', '<head>\n %s\n' %
html, 1)
return super(Response, self)._implicitResult(body)
def _generateIncludes(self, libraries):
# generate the HTML that will be included in the response
site = zope.component.hooks.getSite()
if site is None:
return
resources = queryMultiAdapter(
(site, self._request), interface.Interface, name='')
if not IBrowserPublisher.providedBy(resources):
# a setup with no resources factory is supported; in this
# case, we manually craft a URL to the resource publisher
# (see ``zope.browserresource.resource``).
resources = None
base = queryMultiAdapter(
(site, self._request), IAbsoluteURL, name="resource")
if base is None:
base = getMultiAdapter(
(site, self._request), IAbsoluteURL)
baseURL = str(base)
html = []
for lib in libraries:
if resources is not None:
library_resources = resources[lib]
included = zc.resourcelibrary.getIncluded(lib)
for file_name in included:
if resources is not None:
url = library_resources[file_name]()
else:
url = "%s/@@/%s/%s" % (baseURL, lib, file_name)
if file_name.endswith('.js'):
html.append('<script src="%s" ' % url)
html.append(' type="text/javascript">')
html.append('</script>')
elif file_name.endswith('.css'):
html.append('<style type="text/css" media="all">')
html.append(' <!--')
html.append(' @import url("%s");' % url)
html.append(' -->')
html.append('</style>')
elif file_name.endswith('.kss'):
html.append('<link type="text/kss" href="%s" rel="kinetic-stylesheet" />' % url)
else:
# shouldn't get here; zcml.py is supposed to check includes
raise NotImplementedError("Resource library doesn't know how to "
'include this file: "%s"' % file_name)
return '\n '.join(html)
def _addDependencies(self, resource_libraries):
result = []
def add_lib(lib):
if lib in result:
return # Nothing to do
try:
required = zc.resourcelibrary.getRequired(lib)
except KeyError:
raise RuntimeError('Unknown resource library: "%s"' % lib)
for other in required:
add_lib(other)
if zc.resourcelibrary.getIncluded(lib):
result.append(lib)
for lib in resource_libraries:
add_lib(lib)
return result | zc.resourcelibrary | /zc.resourcelibrary-2.1.0.tar.gz/zc.resourcelibrary-2.1.0/src/zc/resourcelibrary/publication.py | publication.py |
==================
Resource Library
==================
The resource library is designed to make the inclusion of JavaScript, CSS, and
other resources easy, cache-friendly, and component-friendly. For instance, if
two widgets on a page need the same JavaScript library, the library should be
only loaded once, but the widget designers should not have to concern
themselves with the presence of other widgets.
Imagine that one widget has a copy of a fictional Javascript library. To
configure that library as available use ZCML like this:
>>> zcml("""
... <configure
... xmlns="http://namespaces.zope.org/zope"
... package="zc.resourcelibrary">
... <include package="." file="meta.zcml" />
... <resourceLibrary name="some-library">
... <directory source="tests/example"/>
... </resourceLibrary>
...
... </configure>
... """)
This is exactly equivalent to a resourceDirectory tag, with no additional
effect.
Loading Files
=============
It is also possible to indicate that one or more Javascript or CSS files should
be included (by reference) into the HTML of a page that needs the library.
This is the current difference between resourceLibrary and resourceDirectory.
>>> zcml("""
... <configure
... xmlns="http://namespaces.zope.org/zope"
... package="zc.resourcelibrary">
... <include package="." file="meta.zcml" />
... <resourceLibrary name="my-lib">
... <directory
... source="tests/example/my-lib"
... include="included.js included.css included.kss"
... />
... </resourceLibrary>
...
... </configure>
... """)
If a file is included that the resource library doesn't understand (i.e. it
isn't Javascript or CSS), an exception will occur.
>>> zcml("""
... <configure
... xmlns="http://namespaces.zope.org/zope"
... package="zc.resourcelibrary">
... <include package="." file="meta.zcml" />
... <resourceLibrary name="bad-lib">
... <directory
... source="tests/example/my-lib"
... include="included.bad"
... />
... </resourceLibrary>
...
... </configure>
... """)
Traceback (most recent call last):
...
ConfigurationError: Resource library doesn't know how to include this file: "included.bad".
File...
Usage
=====
Components signal their need for a particular resource library (Javascript or
otherwise) by using a special TAL expression. (The use of replace is not
mandated, the result may be assigned to a dummy variable, or otherwise
ignored.)
>>> zpt('<tal:block replace="resource_library:my-lib"/>')
We'll be using a testbrowser.Browser to simulate a user viewing web pages.
>>> from zope.testbrowser.wsgi import Browser
>>> browser = Browser()
>>> browser.addHeader('Authorization', 'Basic mgr:mgrpw')
>>> browser.handleErrors = False
When a page is requested that does not need any resource libraries, the HTML
will be untouched.
>>> browser.open('http://localhost/zc.resourcelibrary.test_template_1')
>>> browser.contents
'...<head></head>...'
When a page is requested that uses a component that needs a resource library,
the library will be referenced in the rendered page.
>>> browser.open('http://localhost/zc.resourcelibrary.test_template_2')
A reference to the JavaScript is inserted into the HTML.
>>> '/@@/my-lib/included.js' in browser.contents
True
And the JavaScript is available from the URL referenced.
>>> browser.open('/@@/my-lib/included.js')
>>> browser.headers['Content-Type']
'application/javascript'
>>> print(browser.contents.decode('ascii'))
function be_annoying() {
alert('Hi there!');
}
For inclusion of resources the full base url with namespaces is used.
>>> browser.open('http://localhost/++skin++Basic/zc.resourcelibrary.test_template_2')
>>> print(browser.contents)
<html...
src="http://localhost/++skin++Basic/@@/my-lib/included.js"...
</html>
A reference to the CSS is also inserted into the HTML.
>>> browser.open('http://localhost/zc.resourcelibrary.test_template_2')
>>> '/@@/my-lib/included.css' in browser.contents
True
And the CSS is available from the URL referenced.
>>> browser.open('/@@/my-lib/included.css')
>>> browser.headers['Content-Type']
'text/css'
>>> print(browser.contents.decode('ascii'))
div .border {
border: 1px silid black;
}
A reference to an unknown library causes an exception.
>>> browser.open('http://localhost/zc.resourcelibrary.test_template_3')
Traceback (most recent call last):
...
RuntimeError: Unknown resource library: "does-not-exist"
Library usage may also be signaled programattically. For example, if a page
would not otherwise include a resource library...
>>> page = ('<html><head></head>'
... '<body tal:define="unused view/doSomething">'
... 'This is the body.</body>')
>>> class View(object):
... context = getRootFolder()
... def doSomething(self):
... pass
>>> zpt(page, view=View())
'...<head></head>...'
If we then programmatically indicate that a resource library is needed, it will
be included.
>>> import zc.resourcelibrary
>>> class View(object):
... context = getRootFolder()
... def doSomething(self):
... zc.resourcelibrary.need('my-lib')
>>> '/@@/my-lib/included.js' in zpt(page, view=View())
True
Content-type checking
=====================
Resources should be referenced only from HTML and XML content, other content
types should not be touched by the resource library:
>>> page = ('<html><head>'
... '<tal:block replace="resource_library:my-lib"/>'
... '</head><body></body></html>')
>>> '/@@/my-lib/included.js' in zpt(page, content_type='text/html')
True
>>> '/@@/my-lib/included.js' in zpt(page, content_type='text/xml')
True
>>> '/@@/my-lib/included.js' in zpt(page, content_type='text/none')
False
This also works if the content type contains uppercase characters, as per RfC
2045 on the syntax of MIME type specifications (we can't test uppercase
characters in the major type yet since the publisher is not completely up to
the RfC on that detail yet):
>>> '/@@/my-lib/included.js' in zpt(page, content_type='text/hTMl')
True
>>> '/@@/my-lib/included.js' in zpt(page, content_type='text/nOne')
False
Parameters to the content type can't fool the check either:
>>> '/@@/my-lib/included.js' in zpt(
... page, content_type='text/xml; charset=utf-8')
True
>>> '/@@/my-lib/included.js' in zpt(
... page, content_type='text/none; charset=utf-8')
False
The content type is, however, assumed to be a strictly valid MIME type
specification, implying that it can't contain any whitespace up to the
semicolon signalling the start of parameters, if any (we can't test whitespace
around the major type as that would already upset the publisher):
>>> '/@@/my-lib/included.js' in zpt(
... page, content_type='text/ xml')
False
>>> '/@@/my-lib/included.js' in zpt(
... page, content_type='text/xml ; charset=utf-8')
False
The content type may also be None if it was never set, which of course doesn't
count as HTML or XML either:
>>> from zc.resourcelibrary import publication
>>> from io import BytesIO
>>> request = publication.Request(body_instream=BytesIO(), environ={})
>>> request.response.setResult("This is not HTML text.")
>>> b'/@@/my-lib/included.js' in request.response.consumeBody()
False
Dependencies
============
If a resource library registers a dependency on another library, the dependency
must be satisfied or an error will be generated.
>>> zcml("""
... <configure
... xmlns="http://namespaces.zope.org/zope"
... package="zc.resourcelibrary">
... <include package="." file="meta.zcml" />
...
... <resourceLibrary name="dependent-but-unsatisfied" require="not-here">
... <directory source="tests/example"/>
... </resourceLibrary>
...
... </configure>
... """)
Traceback (most recent call last):
...
ConfigurationError:...Resource library "dependent-but-unsatisfied" has unsatisfied dependency on "not-here"...
...
When the dependencies are satisfied, the registrations will succeed.
>>> zcml("""
... <configure
... xmlns="http://namespaces.zope.org/zope"
... package="zc.resourcelibrary">
... <include package="." file="meta.zcml" />
...
... <resourceLibrary name="dependent" require="dependency">
... <directory source="tests/example" include="1.js"/>
... </resourceLibrary>
...
... <resourceLibrary name="dependency">
... <directory source="tests/example" include="2.css"/>
... </resourceLibrary>
...
... </configure>
... """)
If one library depends on another and the first library is referenced on a
page, the second library will also be included in the rendered HTML.
>>> zpt('<tal:block replace="resource_library:dependent"/>')
>>> browser.open('http://localhost/zc.resourcelibrary.test_template_4')
>>> '/@@/dependent/1.js' in browser.contents
True
>>> '/@@/dependency/2.css' in browser.contents
True
Order matters, espacially for js files, so the dependency should
appear before the dependent library in the page
>>> print(browser.contents.strip())
<html>...dependency/2.css...dependent/1.js...</html>
It is possible for a resource library to only register a list of dependencies
and not specify any resources.
When such a library is used in a resource_library statement in a template,
only its dependencies are referenced in the final rendered page.
>>> zcml("""
... <configure
... xmlns="http://namespaces.zope.org/zope"
... package="zc.resourcelibrary">
... <include package="." file="meta.zcml" />
...
... <resourceLibrary name="only_require" require="my-lib dependent"/>
...
... </configure>
... """)
>>> zpt('<tal:block replace="resource_library:only_require"/>')
>>> browser.open('http://localhost/zc.resourcelibrary.test_template_7')
>>> '/@@/my-lib/included.js' in browser.contents
True
>>> '/@@/my-lib/included.css' in browser.contents
True
>>> '/@@/dependent/1.js' in browser.contents
True
>>> '/@@/dependency/2.css' in browser.contents
True
>>> '/@@/only_require' in browser.contents
False
Error Conditions
================
Errors are reported if you do something wrong.
>>> zcml("""
... <configure
... xmlns="http://namespaces.zope.org/zope"
... package="zc.resourcelibrary">
... <include package="." file="meta.zcml" />
...
... <resourceLibrary name="some-library">
... <directory source="does-not-exist"/>
... </resourceLibrary>
...
... </configure>
... """)
Traceback (most recent call last):
...
ConfigurationError: Directory u'...does-not-exist' does not exist
File...
Multiple Heads
==============
On occasion the body of an HTML document may contain the text "<head>". In
those cases, only the actual head tag should be manipulated. The first
occurrence of "<head>" has the script tag inserted...
>>> browser.open('http://localhost/zc.resourcelibrary.test_template_5')
>>> print(browser.contents)
<html>...<head> <script src="http://localhost/@@/my-lib/included.js"...
...but that is the only time it is inserted.
>>> browser.contents.count('src="http://localhost/@@/my-lib/included.js"')
1
Error during publishing
=======================
Note that in case an exception is raised during publishing, the
resource library is disabled.
>>> browser.handleErrors = True
>>> browser.post(
... 'http://localhost/zc.resourcelibrary.test_template_5',
... 'value:int=dummy', 'multipart/form-data')
Traceback (most recent call last):
...
urllib.error.HTTPError: ...
>>> '/@@/my-lib/included.js' in browser.contents
False
Custom "directory" factories
============================
By default, a resource directory is created when a directory directive
is used. You can add a factory option to specify a different
resource-directory factory. This can be used, for example, to provide
dynamic resources.
>>> zcml("""
... <configure
... xmlns="http://namespaces.zope.org/zope"
... package="zc.resourcelibrary">
... <include package="." file="meta.zcml" />
...
... <resourceLibrary name="my-lib">
... <directory
... source="tests/example/my-lib"
... include="foo.js"
... factory="zc.resourcelibrary.tests.tests.TestFactory"
... />
... </resourceLibrary>
...
... </configure>
... """, clear=['my-lib'])
The factory will be called with a source directory, a security checker
and a name. We've created a class that implements a resource
directory dynamically.
>>> browser.open('http://localhost/zc.resourcelibrary.test_template_2')
>>> '/@@/my-lib/foo.js' in browser.contents
True
>>> browser.open('http://localhost/@@/my-lib/foo.js')
>>> print(browser.contents)
foo = 1;
Library insertion place marker
==============================
You can explicitly mark where to insert HTML. Do do that, add the
special comment "<!-- zc.resourcelibrary -->" (exact string, w/o quotes)
to the template. It will be replaced by resource libraries HTML on
processing.
>>> browser.open('http://localhost/zc.resourcelibrary.test_template_6')
A reference to the JavaScript is inserted into the HTML.
>>> print(browser.contents)
<html>
<head>
<title>Marker test</title>
<BLANKLINE>
<!-- Libraries will be included below -->
<script src="http://localhost/@@/my-lib/foo.js"
type="text/javascript">
</script>
</head>
...
</html>
Future Work
===========
* We want to be able to specify a single file to add to the resource.
* We may want to be able to override a file in the resource with a different
file.
* Currently only one <directory> tag is allowed per-library. If multiple tags
are allowed, should they be merged or have distinct prefixes?
* Add a test to ensure that files are only included once, and in the proper
order
| zc.resourcelibrary | /zc.resourcelibrary-2.1.0.tar.gz/zc.resourcelibrary-2.1.0/src/zc/resourcelibrary/README.rst | README.rst |
import os.path
from zope.browserresource.directory import DirectoryResourceFactory
from zope.browserresource.metadirectives import IBasicResourceInformation
from zope.browserresource.metaconfigure import allowed_names
from zope.component import getSiteManager
from zope.configuration.exceptions import ConfigurationError
from zope.interface import Interface
from zope.publisher.interfaces.browser import IBrowserRequest
from zope.publisher.interfaces.browser import IDefaultBrowserLayer
from zope.security.checker import CheckerPublic, NamesChecker
import zope.configuration.fields
from zc.resourcelibrary.resourcelibrary import LibraryInfo, library_info
class IResourceLibraryDirective(IBasicResourceInformation):
"""
Defines a resource library
"""
name = zope.schema.TextLine(
title=u"The name of the resource library",
description=u"""\
This is the name used to disambiguate resource libraries. No two
libraries can be active with the same name.""",
required=True,
)
require = zope.configuration.fields.Tokens(
title=u"Require",
description=u"The resource libraries on which this library depends.",
required=False,
value_type=zope.schema.Text(),
)
class IDirectoryDirective(Interface):
"""
Identifies a directory to be included in a resource library
"""
source = zope.configuration.fields.Path(
title=u"Source",
description=u"The directory containing the files to add.",
required=True,
)
include = zope.configuration.fields.Tokens(
title=u"Include",
description=u"The files which should be included in HTML pages which "
u"reference this resource library.",
required=False,
value_type=zope.schema.Text(),
)
factory = zope.configuration.fields.GlobalObject(
title=u"Factory",
description=u"Alternate directory-resource factory",
required=False,
)
def handler(name, dependencies, required, provided, adapter_name, factory, info=''):
if dependencies:
for dep in dependencies:
if dep not in library_info:
raise ConfigurationError(
'Resource library "%s" has unsatisfied dependency on "%s".'
% (name, dep))
getSiteManager().registerAdapter(
factory, required, provided, adapter_name, info)
INCLUDABLE_EXTENSIONS = ('.js', '.css', '.kss')
class ResourceLibrary(object):
def __init__(self, _context, name, require=(),
layer=IDefaultBrowserLayer, permission='zope.Public'):
self.name = name
self.layer = layer
if permission == 'zope.Public':
permission = CheckerPublic
self.checker = NamesChecker(allowed_names, permission)
# make note of the library in a global registry
self.old_library_info = library_info.get(name)
library_info[name] = LibraryInfo()
library_info[name].required.extend(require)
def directory(self, _context, source, include=(), factory=None):
if not os.path.isdir(source):
raise ConfigurationError("Directory %r does not exist" % source)
for file_name in include:
ext = os.path.splitext(file_name)[1]
if ext not in INCLUDABLE_EXTENSIONS:
raise ConfigurationError(
'Resource library doesn\'t know how to include this '
'file: "%s".' % file_name)
# remember which files should be included in the HTML when this library
# is referenced
library_info[self.name].included.extend(include)
if factory is None:
factory = DirectoryResourceFactory
factory = factory(source, self.checker, self.name)
_context.action(
discriminator = ('resource', self.name, IBrowserRequest, self.layer),
callable = handler,
args = (self.name, library_info[self.name].required, (self.layer,),
Interface, self.name, factory, _context.info),
)
def __call__(self):
if self.old_library_info is None:
return
curr_li = library_info[self.name]
if self.old_library_info.included != curr_li.included or \
self.old_library_info.required != curr_li.required:
raise NotImplementedError(
"Can't cope with 2 different registrations of the same "
"library: %s (%s, %s) (%s, %s)" % (self.name,
self.old_library_info.required,
self.old_library_info.included,
curr_li.required,
curr_li.included)) | zc.resourcelibrary | /zc.resourcelibrary-2.1.0.tar.gz/zc.resourcelibrary-2.1.0/src/zc/resourcelibrary/zcml.py | zcml.py |
"""ZooKeeper integration
"""
import gevent
import gevent.pool
import gevent.pywsgi
import gevent.server
import gevent.socket
import json
import logging
import os
import re
import signal
import socket
import sys
import time
import zc.parse_addr
import zc.zk
def worker(app, global_conf, zookeeper, path, loggers=None, address=':0',
threads=None, backdoor=False, description=None, version=None,
run=True, **kw):
"""Paste deploy server runner
"""
if loggers:
if re.match(r'\d+$', loggers):
logging.basicConfig(level=int(loggers))
elif loggers in ('CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG'):
logging.basicConfig(level=getattr(logging, loggers))
else:
import ZConfig
ZConfig.configureLoggers(loggers)
zk = zc.zk.ZooKeeper(zookeeper)
address = zc.parse_addr.parse_addr(address)
from zc.resumelb.worker import Worker
worker = Worker(app, address, threads=threads and int(threads),
**kw)
# Set up notification of settings changes.
settings = zk.properties(path)
watcher = gevent.get_hub().loop.async()
watcher.start(lambda : worker.update_settings(settings))
settings(lambda _: watcher.send())
registration_data = {}
if backdoor == 'true':
from gevent import backdoor
bd = backdoor.BackdoorServer(('127.0.0.1', 0), locals())
bd.start()
registration_data['backdoor'] = '127.0.0.1:%s' % bd.server_port
worker.__bd = bd
if description:
registration_data['description'] = description
if version:
registration_data['version'] = version
zk.register_server(path+'/providers', worker.addr, **registration_data)
worker.zk = zk
worker.__zksettings = settings
def shutdown():
zk.close()
worker.shutdown()
gevent.signal(signal.SIGTERM, shutdown)
if run:
try:
worker.server.serve_forever()
finally:
logging.getLogger(__name__+'.worker').info('exiting')
zk.close()
else:
gevent.sleep(.01)
return worker
class WSGIServer(gevent.pywsgi.WSGIServer):
def __init__(self, *args, **kw):
self.__socket_timeout = kw.pop('socket_timeout')
gevent.pywsgi.WSGIServer.__init__(self, *args, **kw)
def handle(self, socket, address):
socket.settimeout(self.__socket_timeout)
return gevent.pywsgi.WSGIServer.handle(self, socket, address)
def _resolve(path):
rcmod, rcexpr = path.split(':')
__import__(rcmod)
rcmod = sys.modules[rcmod]
return eval(rcexpr, rcmod.__dict__)
def lbmain(args=None, run=True):
"""%prog [options] zookeeper_connection path
Run a resume-based load balancer on addr.
"""
if args is None:
args = sys.argv[1:]
elif isinstance(args, str):
args = args.split()
run = False
import optparse
parser = optparse.OptionParser(lbmain.__doc__)
parser.add_option(
'-a', '--address', default=':0',
help="Address to listed on for web requests"
)
parser.add_option(
'-b', '--backlog', type='int',
help="Server backlog setting.")
parser.add_option(
'-d', '--backdoor', action='store_true',
help="Run a backdoor server. Use with caution!")
parser.add_option(
'-e', '--disconnect-message',
help="Path to error page to use when a request is lost due to "
"worker disconnection"
)
parser.add_option(
'-L', '--logger-configuration',
help=
"Read logger configuration from the given configuration file path.\n"
"\n"
"The configuration file must be in ZConfig logger configuration syntax."
"\n"
"Alternatively, you can give a Python logger level name or number."
)
parser.add_option('-l', '--access-logger', help='Access-log logger name.')
parser.add_option(
'-m', '--max-connections', type='int',
help="Maximum number of simultanious accepted connections.")
parser.add_option(
'-r', '--request-classifier', default='zc.resumelb.lb:host_classifier',
help="Request classification function (module:expr)"
)
parser.add_option(
'-p', '--pool-factory', default='zc.resumelb.lb:Pool',
help=
"Callable which creates a pool (module:expr)."
" Will be called with settings as keyword arguments."
)
parser.add_option(
'-s', '--status-server',
help=("Run a status server for getting pool information. "
"The argument is a unix-domain socket path to listen on."))
parser.add_option(
'-t', '--socket-timeout', type='float', default=99.,
help=('HTTP socket timeout.'))
parser.add_option(
'-v', '--single-version', action='store_true',
help=('Only use a single worker version.'))
try:
options, args = parser.parse_args(args)
if len(args) != 2:
print 'Error: must supply a zookeeper connection string and path.'
parser.parse_args(['-h'])
zookeeper, path = args
except SystemExit:
if run:
raise
else:
return
if options.logger_configuration:
logger_config = options.logger_configuration
if re.match(r'\d+$', logger_config):
logging.basicConfig(level=int(logger_config))
elif logger_config in ('CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG'):
logging.basicConfig(level=getattr(logging, logger_config))
else:
import ZConfig
with open(logger_config) as f:
ZConfig.configureLoggers(f.read())
zk = zc.zk.ZooKeeper(zookeeper)
worker_path = zk.resolve(path+'/workers/providers')
addrs = zk.children(worker_path)
request_classifier = _resolve(options.request_classifier)
pool_factory = _resolve(options.pool_factory)
disconnect_message = options.disconnect_message
if disconnect_message:
with open(disconnect_message) as f:
disconnect_message = f.read()
else:
disconnect_message = zc.resumelb.lb.default_disconnect_message
from zc.resumelb.lb import LB
lb = LB(map(zc.parse_addr.parse_addr, ()),
request_classifier, disconnect_message,
pool_factory=pool_factory,
single_version=options.single_version)
to_send = [[]]
# Set up notification of address changes.
awatcher = gevent.get_hub().loop.async()
@awatcher.start
def _():
lb.set_worker_addrs(to_send[0])
if options.single_version or pool_factory != zc.resumelb.lb.Pool:
@addrs
def get_addrs(a):
to_send[0] = dict(
(zc.parse_addr.parse_addr(addr),
zk.get_properties(
worker_path + '/' + addr).get('version')
)
for addr in addrs)
awatcher.send()
else:
@addrs
def get_addrs(a):
to_send[0] = map(zc.parse_addr.parse_addr, addrs)
awatcher.send()
# Set up notification of address changes.
settings = zk.properties(path)
swatcher = gevent.get_hub().loop.async()
swatcher.start(lambda : lb.update_settings(settings))
settings(lambda a: swatcher.send())
lb.zk = zk
lb.__zk = addrs, settings
# Now, start a wsgi server
addr = zc.parse_addr.parse_addr(options.address)
if options.max_connections:
spawn= gevent.pool.Pool(options.max_connections)
else:
spawn = 'default'
if options.access_logger:
accesslog = AccessLog(options.access_logger)
else:
accesslog = None
server = WSGIServer(
addr, lb.handle_wsgi, backlog=options.backlog,
spawn=spawn, log=accesslog, socket_timeout=options.socket_timeout)
server.start()
registration_data = {}
if options.backdoor:
from gevent import backdoor
bd = backdoor.BackdoorServer(('127.0.0.1', 0), locals())
bd.start()
registration_data['backdoor'] = '127.0.0.1:%s' % bd.server_port
status_server = None
if options.status_server:
def status(socket, addr):
pool = lb.pool
status = pool.status()
writer = socket.makefile('w')
writer.write(json.dumps(status) + '\n')
writer.close()
socket.close()
status_server_address = options.status_server
if os.path.exists(status_server_address):
os.remove(status_server_address)
sock = gevent.socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.bind(status_server_address)
sock.listen(5)
status_server = gevent.server.StreamServer(sock, status)
status_server.start()
zk.register_server(path+'/providers', (addr[0], server.server_port),
**registration_data)
def shutdown():
zk.close()
server.close()
if status_server is not None:
status_server.close()
lb.shutdown()
gevent.signal(signal.SIGTERM, shutdown)
if run:
try:
server.serve_forever()
finally:
logging.getLogger(__name__+'.lbmain').info('exiting')
zk.close()
else:
gevent.sleep(.01)
return lb, server
class AccessLog:
def __init__(self, logger):
self.write = logging.getLogger(logger).info
worker_format = '%30s%8s%8s%8s'
def get_lb_status(args=None):
if args is None:
args = sys.argv[1:]
for addr in args:
print 'status for', addr
status_socket = gevent.socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
status_socket.connect(addr)
status_file = status_socket.makefile()
status = json.loads(status_file.read())
status_file.close()
status_socket.close()
workers = status['workers']
if workers:
now = time.time()
print ' backlog: %s, mean backlog: %.1f' % (
status['backlog'], status['mean_backlog'])
print ' workers: %s, mean backlog per worker: %.1f' % (
len(workers), status['mean_backlog'] / len(workers),
)
print
print worker_format % (
'worker', 'backlog', 'mean bl', 'age')
for name, bl, mbl, start in sorted(workers):
print worker_format % (
name, bl, "%.1f" % mbl,
("%.1f" % (now-start) if start is not None else '-'))
else:
print 'This load-balancer has no workers!' | zc.resumelb | /zc.resumelb-1.0.2.tar.gz/zc.resumelb-1.0.2/src/zc/resumelb/zk.py | zk.py |
from struct import pack, unpack
from marshal import loads, dumps, dump, load
import errno
import gevent.queue
import logging
import socket
import tempfile
logger = logging.getLogger(__name__)
disconnected_errors = (errno.EPIPE, errno.ECONNRESET, errno.ENOTCONN,
errno.ESHUTDOWN, errno.ECONNABORTED)
class Disconnected(Exception):
pass
def read_message(sock):
data = ''
while len(data) < 8:
try:
received = sock.recv(8-len(data))
except socket.error, err:
if err.args[0] in disconnected_errors:
logger.debug("read_message disconnected %s %r", sock, err)
raise Disconnected()
else:
raise
if not received:
if data:
logger.info("read_message disconnected (l) %r", sock)
raise Disconnected()
data += received
rno, l = unpack(">II", data)
data = ''
while len(data) < l:
received = sock.recv(l-len(data))
if not received:
logger.info("read_message disconnected (d) %r", sock)
raise Disconnected()
data += received
return rno, loads(data)
def write_message(sock, rno, *a):
to_send = []
for data in a:
data = dumps(data)
to_send.append(pack(">II", rno, len(data)))
to_send.append(data)
data = ''.join(to_send)
while data:
try:
sent = sock.send(data)
except socket.error, err:
if err.args[0] in disconnected_errors or sock.closed:
logger.debug("write_message disconnected %s", sock)
raise Disconnected()
else:
raise
data = data[sent:]
SEND_SIZE = 1 << 16
KEEP_ALIVE = pack(">II", 0, 1) + 'N'
def writer(writeq, sock, multiplexer):
get = writeq.get
write_message_ = write_message
timeout = multiplexer.write_keepalive_interval
Empty = gevent.queue.Empty
send = sock.send
dumps_ = dumps
pack_ = pack
while 1:
try:
rno, data = get(True, timeout)
except Empty:
data = KEEP_ALIVE
else:
to_send = []
append = to_send.append
nsend = 0
while 1:
data = dumps_(data)
append(pack_(">II", rno, len(data)))
append(data)
nsend += len(data) + 8
if nsend > SEND_SIZE:
break
try:
rno, data = get(False)
except Empty:
break
data = ''.join(to_send)
while data:
try:
sent = send(data)
except socket.error, err:
if err.args[0] in disconnected_errors or sock.closed:
logger.debug("write_message disconnected %s", sock)
multiplexer.disconnected()
return
else:
raise
data = data[sent:]
queue_size_bytes = 99999
class ByteSizedQueue(gevent.queue.Queue):
__size = 0
def _get(self):
item = super(ByteSizedQueue, self)._get()
if item:
self.__size -= len(item)
return item
def _put(self, item):
super(ByteSizedQueue, self)._put(item)
if item:
self.__size += len(item)
def qsize(self):
return self.__size or super(ByteSizedQueue, self).qsize()
class BufferedQueue:
buffer = None
def __init__(self):
self.queue = ByteSizedQueue(queue_size_bytes)
self._put = self.queue.put
self.get = self.queue.get
def put(self, data):
try:
self._put(data, False, .001)
except gevent.queue.Full:
self.queue = queue = Buffer(self.queue)
self._put = queue.put
self.close = queue.close
queue.put(data)
def qsize(self):
return self.queue.qsize()
def close(self):
pass
class Buffer:
size = size_bytes = read_position = write_position = 0
def __init__(self, queue):
self.queue = queue
self.file = tempfile.TemporaryFile(suffix='.rlbob')
def qsize(self):
return self.queue.qsize() + self.size_bytes
def close(self):
# Close the queue. There are 2 possibilities:
# 1. The file buffer is non-empty and there's a greenlet
# emptying it. (See the feed greenlet in the put method.)
# The greenlet is blocked puting data in the underlying
# queue. We can set size to -1, marking us as closed and
# close the file. The greenlet will check sise before
# trying trying to read the file again.
# 2. The file bugger is empty and there's no running greenlet.
# We can set the size to -1 and close the file.
# In either case, we'll empty the underying queue, both for
# cleanliness and to unblock a greenlet, if there is one, so
# it can die a normal death,
if self.size < 0:
return # already closed
self.size = -1
self.file.close()
queue = self.queue
while queue.qsize():
queue.get()
self.size_bytes = 0
def put(self, data, block=False, timeout=None):
if self.size < 0:
return # closed
file = self.file
file.seek(self.write_position)
dump(data, file)
self.write_position = file.tell()
if data:
self.size_bytes += len(data)
self.size += 1
if self.size == 1:
@gevent.spawn
def feed():
queue = self.queue
while self.size > 0:
file.seek(self.read_position)
data = load(file)
self.read_position = file.tell()
queue.put(data)
if self.size > 0:
# We check the size here, in case the queue was closed
if data:
self.size_bytes -= len(data)
self.size -= 1
else:
assert self.size == -1
class Worker:
ReadQueue = gevent.queue.Queue
write_keepalive_interval = None
def connected(self, socket, addr=None):
if addr is None:
addr = socket.getpeername()
logger.info('worker connected %s', addr)
self.addr = addr
self.readers = {}
self.write_queue = writeq = ByteSizedQueue(queue_size_bytes)
gevent.Greenlet.spawn(writer, writeq, socket, self)
self.put = writeq.put
self.is_connected = True
self.socket = socket
return self.readers
def __len__(self):
return len(self.readers)
def start(self, rno):
readq = self.ReadQueue()
self.readers[rno] = readq.put
return readq
def end(self, rno):
try:
queue = self.readers.pop(rno)
except KeyError:
return # previously cancelled
def put_disconnected(self, *a, **k):
raise Disconnected()
def disconnected(self):
logger.info('worker disconnected %s', self.addr)
self.is_connected = False
for put in self.readers.itervalues():
put(None)
self.socket.close()
self.put = self.put_disconnected
class LBWorker(Worker):
write_keepalive_interval = 0.1
ReadQueue = BufferedQueue
def connected(self, socket, addr=None):
self.queues = {}
return Worker.connected(self, socket, addr)
def start(self, rno):
self.queues[rno] = queue = Worker.start(self, rno)
return queue
def end(self, rno):
try:
queue = self.readers.pop(rno)
except KeyError:
return # previously cancelled
self.queues.pop(rno).close() | zc.resumelb | /zc.resumelb-1.0.2.tar.gz/zc.resumelb-1.0.2/src/zc/resumelb/util.py | util.py |
import gevent.event
import llist
import zc.resumelb.lb
class ClasslessPool(zc.resumelb.lb.PoolBase):
def __init__(self, single_version=False):
super(ClasslessPool, self).__init__(single_version)
self.backlog = 0
self.workers = set()
self.line = llist.dllist()
self.event = gevent.event.Event()
def get(self, request_class, timeout=None):
line = self.line
if not line:
self.event.wait(timeout)
if not line:
return None
node = self.line.first
best_worker = None
best_backlog = 999999999
while node is not None:
worker = node.value
backlog = worker.backlog
if backlog == 0:
best_worker = worker
break
if backlog < best_backlog:
best_backlog = backlog
best_worker = worker
node = node.next
# Move worker from lru to mru end of queue
line.remove(best_worker.lnode)
best_worker.lnode = line.append(best_worker)
best_worker.backlog += 1
self.backlog += 1
return best_worker
@property
def mbacklog(self):
nworkers = len(self.workers)
if nworkers:
return self.backlog / nworkers
else:
return None
def _new_resume(self, worker, resume):
if worker not in self.workers:
self.workers.add(worker)
worker.lnode = self.line.appendleft(worker)
worker.backlog = 0
self.event.set()
def put(self, worker):
self.backlog -= 1
assert self.backlog >= 0, self.backlog
worker.backlog -= 1
assert worker.backlog >= 0, worker.backlog
def _remove(self, worker):
if getattr(worker, 'lnode', None) is not None:
self.line.remove(worker.lnode)
worker.lnode = None
self.workers.remove(worker)
if not self.workers:
self.event.clear()
def update_settings(self, settings):
pass
def classifier(_):
return '' | zc.resumelb | /zc.resumelb-1.0.2.tar.gz/zc.resumelb-1.0.2/src/zc/resumelb/classlesspool.py | classlesspool.py |
from pprint import pprint
import json
import logging
import os
import pylru
import random
import sys
import time
import threading
import zc.mappingobject
import zc.parse_addr
import zc.thread
import zc.zk
import zookeeper
import zope.testing.wait
logger = logging.getLogger(__name__)
class Sample:
def __init__(self, size=1000, data=None):
self.size = size
self.data = data or []
self.n = len(self.data)
def add(self, v):
self.n += 1
try:
self.data[self.n % self.size] = v
except IndexError:
self.data.append(v)
def stats(self, prefix=None):
data = sorted(self.data)
return {
'n': self.n,
'mean': float(sum(data))/len(data),
'min': data[0],
'10': data[len(data)/10],
'50': data[len(data)/2],
'90': data[9*len(data)/10],
'max': data[-1],
}
def __repr__(self):
return ("%(n)s %(min)s %(10)s %(50)s(%(mean)s) %(90)s %(max)s" %
self.stats(''))
class App:
def __init__(self, properties):
settings = zc.mappingobject.mappingobject(properties)
self.cache_size = settings.cache_size
self.cache = pylru.lrucache(self.cache_size)
self.hitrates = Sample()
@properties
def changed(*a):
if settings.cache_size != self.cache_size:
self.cache_size = settings.cache_size
self.cache.size(self.cache_size)
def __call__(self, environ, start_response):
n = nhit = nmiss = nevict = 0
for oid in environ['PATH_INFO'].rsplit('/', 1)[1].split('_'):
n += 1
key = environ['HTTP_HOST'], oid
if key in self.cache:
nhit += 1
else:
nmiss += 1
if len(self.cache) >= self.cache_size:
nevict += 1
self.cache[key] = 1
time.sleep(.01)
result = ' '.join(map(str, (os.getpid(), n, nhit, nmiss, nevict)))+'\n'
response_headers = [
('Content-type', 'text/plain'),
('Content-Length', str(len(result))),
]
start_response('200 OK', response_headers)
if n:
self.hitrates.add(100.0*nhit/n)
if self.hitrates.n % 1000 == 0:
print os.getpid(), 'hitrate', self.hitrates
return [result]
def worker(path):
import logging
logging.basicConfig()
logger = logging.getLogger(__name__+'-worker')
try:
import zc.resumelb.zk
zk = zc.zk.ZooKeeper()
properties = zk.properties(path)
app = App(properties)
resume_file = 'resume%s.mar' % os.getpid()
if os.path.exists(resume_file):
os.remove(resume_file)
zc.resumelb.zk.worker(
app, {},
zookeeper='127.0.0.1:2181',
path=path+'/lb/workers',
address='127.0.0.1:0',
resume_file=resume_file,
)
except:
logger.exception('worker')
def clients(path):
logging.basicConfig()
random.seed(0)
import zc.zk
zk = zc.zk.ZooKeeper()
properties = zk.properties(path)
settings = zc.mappingobject.mappingobject(properties)
siteids = []
@properties
def _(*a):
n = settings.sites
siteids[:] = [0]
for i in range(4):
if n:
siteids.extend(range(n))
n /= 2
wpath = path + '/lb/providers'
zope.testing.wait.wait(lambda : zk.get_children(wpath))
[waddr] = zk.get_children(wpath)
waddr = zc.parse_addr.parse_addr(waddr)
stats = zc.mappingobject.mappingobject(dict(
truncated = 0,
requests = 0,
bypid = {},
nobs = 0,
nhits = 0,
))
spath = path + '/stats'
if not zk.exists(spath):
zk.create(spath, '', zc.zk.OPEN_ACL_UNSAFE)
import gevent.socket
def do_request():
siteid = random.choice(siteids)
oids = set(
int(random.gauss(0, settings.objects_per_site/4))
for i in range(settings.objects_per_request)
)
socket = gevent.socket.create_connection(waddr)
try:
socket.sendall(
request_template % dict(
data='_'.join(map(str, oids)),
host='h%s' % siteid,
)
)
response = ''
while '\r\n\r\n' not in response:
data = socket.recv(9999)
if not data:
stats.truncated += 1
return
response += data
headers, body = response.split('\r\n\r\n')
headers = headers.split('\r\n')
status = headers.pop(0)
headers = dict(l.strip().lower().split(':', 1)
for l in headers if ':' in l)
content_length = int(headers['content-length'])
while len(body) < content_length:
data = socket.recv(9999)
if not data:
stats.truncated += 1
return
body += data
pid, n, nhit, nmiss, nevict = map(int, body.strip().split())
stats.requests += 1
stats.nobs += n
stats.nhits += nhit
bypid = stats.bypid.get(pid)
if bypid is None:
bypid = stats.bypid[pid] = dict(nr=0, n=0, nhit=0)
bypid['nr'] += 1
bypid['n'] += n
bypid['nhit'] += nhit
logger.info(' '.join(map(str, (
100*stats.nhits/stats.nobs,
pid, n, nhit, 100*nhit/n,
))))
finally:
socket.close()
def client():
try:
while 1:
do_request()
except:
print 'client error'
logging.getLogger(__name__+'-client').exception('client')
greenlets = [gevent.spawn(client) for i in range(settings.clients)]
# Set up notification of address changes.
watcher = gevent.get_hub().loop.async()
@watcher.start
def _():
print 'got update event'
while settings.clients > len(greenlets):
greenlets.append(gevent.spawn(client))
while settings.clients < len(greenlets):
greenlets.pop().kill()
properties(lambda a: watcher.send())
while 1:
gevent.sleep(60.0)
request_template = """GET /%(data)s HTTP/1.1\r
Host: %(host)s\r
\r
"""
class LBLogger:
def __init__(self):
self.requests = Sample()
self.nr = self.requests.n
self.then = time.time()
def write(self, line):
status, _, t = line.split()[-3:]
if status != '200':
print 'error', line
self.requests.add(float(t))
if ((time.time() - self.then > 30)
#or self.nr < 30
):
pool = self.lb.pool
self.then = time.time()
print
print time.ctime()
print 'requests', self.requests.n-self.nr, self.requests
self.nr = self.requests.n
# print pool
print 'backlogs', str(Sample(data=[
worker.backlog for worker in pool.workers]))
print 'resumes', str(Sample(data=[
len(worker.resume) for worker in pool.workers]))
print 'skilled', str(Sample(
data=map(len, pool.skilled.values())))
for rclass, skilled in sorted(pool.skilled.items()):
if (len(skilled) > len(pool.workers) or
len(set(i[1] for i in skilled)) != len(skilled)
):
print 'bad skilled', sorted(skilled, key=lambda i: i[1])
def main(args=None):
if args is None:
args = sys.argv[1:]
[path] = args
logging.basicConfig()
zk = zc.zk.ZooKeeper()
properties = zk.properties(path)
settings = zc.mappingobject.mappingobject(properties)
workers = [zc.thread.Process(worker, args=(path,))
for i in range(settings.workers)]
@zc.thread.Process(args=(path,))
def lb(path):
import logging
logging.basicConfig()
logger = logging.getLogger(__name__+'-lb')
try:
import zc.resumelb.zk
lb, server, logger = zc.resumelb.zk.lbmain(
['-a127.0.0.1:0', '-l', LBLogger(),
'127.0.0.1:2181', '/simul/lb'],
run=False)
logger.lb = lb
server.serve_forever()
except:
logger.exception('lb')
clients_process = zc.thread.Process(clients, args=(path,))
@properties
def update(*a):
while settings.workers > len(workers):
workers.append(zc.thread.Process(worker, args=(path,)))
while settings.workers < len(workers):
workers.pop().terminate()
threading.Event().wait() # sleep forever | zc.resumelb | /zc.resumelb-1.0.2.tar.gz/zc.resumelb-1.0.2/src/zc/resumelb/simul.py | simul.py |
Nagios monitor for the resumelb load balancer
=============================================
The monitor provides basic monitoring and optional metrics.
It's provided as a Nagios plugin and, therefore, a script that can be
run form the command line. To find out what options are available, use
the -h option:
$ rlb-nagios -h
.. -> src
>>> args = src.strip().split()[1:]
>>> entry = args.pop(0)
>>> import pkg_resources, os
>>> monitor = pkg_resources.load_entry_point(
... 'zc.resumelb', 'console_scripts', entry)
>>> os.environ['COLUMNS'] = '72'
>>> try: monitor(args)
... except SystemExit: pass
... else: print 'should have exited'
... # doctest: +NORMALIZE_WHITESPACE
usage: test [-h] [--worker-mean-backlog-warn WORKER_MEAN_BACKLOG_WARN]
[--worker-mean-backlog-error WORKER_MEAN_BACKLOG_ERROR]
[--worker-max-backlog-warn WORKER_MAX_BACKLOG_WARN]
[--worker-max-backlog-error WORKER_MAX_BACKLOG_ERROR]
[--worker-request-age-warn WORKER_REQUEST_AGE_WARN]
[--worker-request-age-error WORKER_REQUEST_AGE_ERROR]
[--minimum-worker-warn MINIMUM_WORKER_WARN]
[--minimum-worker-error MINIMUM_WORKER_ERROR] [--metrics]
socket
<BLANKLINE>
positional arguments:
socket Path to a load-balancer status socket
<BLANKLINE>
optional arguments:
-h, --help show this help message and exit
--worker-mean-backlog-warn WORKER_MEAN_BACKLOG_WARN,
-b WORKER_MEAN_BACKLOG_WARN
Mean worker backlog at which we warn.
--worker-mean-backlog-error WORKER_MEAN_BACKLOG_ERROR,
-B WORKER_MEAN_BACKLOG_ERROR
Mean worker backlog at which we error.
--worker-max-backlog-warn WORKER_MAX_BACKLOG_WARN,
-x WORKER_MAX_BACKLOG_WARN
Maximum worker backlog at which we warn.
--worker-max-backlog-error WORKER_MAX_BACKLOG_ERROR,
-X WORKER_MAX_BACKLOG_ERROR
Maximim worker backlog at which we error.
--worker-request-age-warn WORKER_REQUEST_AGE_WARN,
-a WORKER_REQUEST_AGE_WARN
Maximum request age at which we warn.
--worker-request-age-error WORKER_REQUEST_AGE_ERROR,
-A WORKER_REQUEST_AGE_ERROR
Maximim request age at which we error.
--minimum-worker-warn MINIMUM_WORKER_WARN, -w MINIMUM_WORKER_WARN
Maximum request age at which we warn.
--minimum-worker-error MINIMUM_WORKER_ERROR, -W MINIMUM_WORKER_ERROR
Maximim request age at which we error.
--metrics, -m Output metrics.
Faux status server:
>>> import zc.resumelb.nagiosfauxstatus
>>> pool = zc.resumelb.nagiosfauxstatus.Pool()
>>> import gevent.server, gevent.socket, socket
>>> server = gevent.socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
>>> server.bind('status.sock')
>>> server.listen(1)
>>> server = gevent.server.StreamServer(server, pool.handle)
>>> server.start()
This results in output like the following::
usage: test [-h] [--worker-mean-backlog-warn WORKER_MEAN_BACKLOG_WARN]
[--worker-mean-backlog-error WORKER_MEAN_BACKLOG_ERROR]
[--worker-max-backlog-warn WORKER_MAX_BACKLOG_WARN]
[--worker-max-backlog-error WORKER_MAX_BACKLOG_ERROR]
[--worker-request-age-warn WORKER_REQUEST_AGE_WARN]
[--worker-request-age-error WORKER_REQUEST_AGE_ERROR]
[--minimum-worker-warn MINIMUM_WORKER_WARN]
[--minimum-worker-error MINIMUM_WORKER_ERROR] [--metrics]
socket
<BLANKLINE>
positional arguments:
socket Path to a load-balancer status socket
<BLANKLINE>
optional arguments:
-h, --help show this help message and exit
--worker-mean-backlog-warn WORKER_MEAN_BACKLOG_WARN,
-b WORKER_MEAN_BACKLOG_WARN
Mean worker backlog at which we warn.
--worker-mean-backlog-error WORKER_MEAN_BACKLOG_ERROR,
-B WORKER_MEAN_BACKLOG_ERROR
Mean worker backlog at which we error.
--worker-max-backlog-warn WORKER_MAX_BACKLOG_WARN,
-x WORKER_MAX_BACKLOG_WARN
Maximum worker backlog at which we warn.
--worker-max-backlog-error WORKER_MAX_BACKLOG_ERROR,
-X WORKER_MAX_BACKLOG_ERROR
Maximim worker backlog at which we error.
--worker-request-age-warn WORKER_REQUEST_AGE_WARN,
-a WORKER_REQUEST_AGE_WARN
Maximum request age at which we warn.
--worker-request-age-error WORKER_REQUEST_AGE_ERROR,
-A WORKER_REQUEST_AGE_ERROR
Maximim request age at which we error.
--minimum-worker-warn MINIMUM_WORKER_WARN, -w MINIMUM_WORKER_WARN
Maximum request age at which we warn.
--minimum-worker-error MINIMUM_WORKER_ERROR, -W MINIMUM_WORKER_ERROR
Maximim request age at which we error.
--metrics, -m Output metrics.
None of the options have defaults. If you run the monitor without
options, you'll get an error reminding you that you need to specify
metrics output or thresholds.
.. Now test :)
We have three idle workers.
By default, all is well:
>>> m = lambda s: monitor(s.split() + ['status.sock'])
>>> m('')
You need to request metrics and/or alert settings
3
>>> m('-b3 -B9 -x9 -X19 -a1 -A2 -w2 -W1')
OK 3 0 0 0
Make sure max_age metric shows 0 when no backlog:
>>> m('-b3 -B9 -x9 -X19 -a1 -A2 -w2 -W1 -m')
OK 3 0 0 0|workers=3 mean_backlog=0 max_backlog=0 max_age=0.0seconds
>>> pool.get(1)
>>> m('-b3 -B9 -x9 -X19 -a1 -A2 -w2 -W1')
OK 3 0 1 0
>>> _ = [pool.get(0) for i in range(8)]
>>> m('-b3 -B9 -x9 -X19 -a1 -A2 -w2 -W1')
mean backlog high (3)
1
>>> _ = [pool.get(0) for i in range(10)]
>>> m('-b3 -B9 -x9 -X19 -a1 -A2 -w2 -W1')
mean backlog high (6) max backlog high (18) max age too high (1.8)
1
>>> _ = [pool.get(2) for i in range(10)]
>>> m('-b3 -B9 -x9 -X19 -a1 -A2 -w2 -W1')
mean backlog high (9) max backlog high (18) max age too high (1.8)
2
>>> _ = [pool.put(2) for i in range(10)]
>>> m('-b3 -B9 -x9 -X19 -a1 -A2 -w2 -W1')
mean backlog high (6) max backlog high (18) max age too high (1.8)
1
>>> _ = [pool.get(0) for i in range(10)]
>>> m('-b333 -B99 -x9 -X19 -a1 -A22 -w2 -W1')
max backlog high (28) max age too high (2.8)
2
>>> m('-b333 -B99 -x9 -X199 -a1 -A2 -w2 -W1')
max backlog high (28) max age too high (2.8)
2
>>> m('-w3 -W1')
too few workers (3)
1
>>> m('-w8 -W3')
too few workers (3)
2
Metrics:
>>> m('-w8 -W3 -m') # doctest: +NORMALIZE_WHITESPACE
too few workers (3)|workers=3 mean_backlog=9 max_backlog=28
max_age=2.8seconds
2
| zc.resumelb | /zc.resumelb-1.0.2.tar.gz/zc.resumelb-1.0.2/src/zc/resumelb/nagios.rst | nagios.rst |
from __future__ import print_function
import argparse
import gevent.socket
import json
import socket
import sys
import time
parser = argparse.ArgumentParser()
parser.add_argument('socket',
help='Path to a load-balancer status socket')
parser.add_argument('--worker-mean-backlog-warn', '-b', type=int,
help='Mean worker backlog at which we warn.')
parser.add_argument('--worker-mean-backlog-error', '-B', type=int,
help='Mean worker backlog at which we error.')
parser.add_argument('--worker-max-backlog-warn', '-x', type=int,
help='Maximum worker backlog at which we warn.')
parser.add_argument('--worker-max-backlog-error', '-X', type=int,
help='Maximim worker backlog at which we error.')
parser.add_argument('--worker-request-age-warn', '-a', type=int,
help='Maximum request age at which we warn.')
parser.add_argument('--worker-request-age-error', '-A', type=int,
help='Maximim request age at which we error.')
parser.add_argument('--minimum-worker-warn', '-w', type=int,
help='Maximum request age at which we warn.')
parser.add_argument('--minimum-worker-error', '-W', type=int,
help='Maximim request age at which we error.')
parser.add_argument('--metrics', '-m', action="store_true",
help='Output metrics.')
def _check(value, warn, error, format, message, severity, sign=1):
if error is not None and sign*value >= sign*error:
message.append(format % abs(value))
return 2
if warn is not None and sign*value >= sign*warn:
message.append(format % abs(value))
return max(1, severity)
return severity
def main(args=None):
if args is None:
args = sys.argv[1:]
args = parser.parse_args(args)
for o in (args.worker_mean_backlog_warn, args.worker_mean_backlog_error,
args.worker_max_backlog_warn, args.worker_max_backlog_error,
args.minimum_worker_warn, args.minimum_worker_error):
if o is not None:
break
else:
if not args.metrics:
print("You need to request metrics and/or alert settings")
return 3
now = time.time()
status_socket = gevent.socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
status_socket.connect(args.socket)
status_file = status_socket.makefile()
status = status_file.read()
status = json.loads(status)
status_file.close()
status_socket.close()
nworkers = len(status['workers'])
mbacklog = status["mean_backlog"]
max_backlog = max(w[1] for w in status['workers'])
max_age = max((now-w[3] if w[3] else 0) for w in status['workers'])
severity = 0
message = []
severity = _check(
mbacklog, args.worker_mean_backlog_warn, args.worker_mean_backlog_error,
"mean backlog high (%s)", message, severity)
severity = _check(
max_backlog,
args.worker_max_backlog_warn, args.worker_max_backlog_error,
"max backlog high (%s)", message, severity)
severity = _check(
max_age, args.worker_request_age_warn, args.worker_request_age_error,
"max age too high (%.1f)", message, severity)
severity = _check(
nworkers, args.minimum_worker_warn, args.minimum_worker_error,
"too few workers (%s)", message, severity, -1)
if message:
message = ' '.join(message)
else:
message = "OK %s %s %s %s" % (
nworkers, mbacklog, max_backlog,
int(round(max_age)) if max_age >= 0 else '-')
if args.metrics:
message += (
'|workers=%s mean_backlog=%s max_backlog=%s max_age=%.1fseconds'
% (nworkers, mbacklog, max_backlog, max_age))
print(message)
return severity or None
if __name__ == '__main__':
main() | zc.resumelb | /zc.resumelb-1.0.2.tar.gz/zc.resumelb-1.0.2/src/zc/resumelb/nagios.py | nagios.py |
import cStringIO
import datetime
import errno
import gevent
import gevent.hub
import gevent.server
import gevent.socket
import gevent.threadpool
import logging
import marshal
import os
import sys
import tempfile
import time
import zc.parse_addr
import zc.resumelb.util
logger = logging.getLogger(__name__)
def error(mess):
logger.exception(mess)
# import traceback, warnings
# warnings.warn("Debugging error function needs to be removed after debugging.")
# def error(mess):
# print >>sys.stderr, mess
# traceback.print_exc()
STRING_BUFFER_SIZE = 9999999
class Worker:
def __init__(self, app, addr,
history=None, max_skill_age=None,
resume_file=None, threads=None, tracelog=None,
tracelog_key='tracelog'):
self.app = app
self.update_settings(dict(history=history, max_skill_age=max_skill_age))
self.resume_file = resume_file
self.perf_data = {} # rclass -> (gen, decayed times, decayed counts)
self.generation = 0
self.resume = {}
if self.resume_file and os.path.exists(self.resume_file):
try:
with open(self.resume_file) as f:
self.resume = marshal.load(f)
except Exception:
logger.exception('reading resume file')
else:
for rclass, rpm in self.resume.iteritems():
if rpm > 0:
self.perf_data[rclass] = 0, 1.0/rpm, self.history
self.connections = set()
if threads:
self.threadpool = gevent.threadpool.ThreadPool(int(threads))
pool_apply = self.threadpool.apply
else:
pool_apply = None
def call_app(trno, env):
response = [0]
env['zc.resumelb.time'] = time.time()
def start_response(status, headers, exc_info=None):
assert not exc_info # XXX
response[0] = (status, headers)
try:
body = iter(app(env, start_response))
try:
first = body.next()
except StopIteration:
first = ''
if hasattr(body, 'close'):
body.close()
body = ()
except Exception:
error("Uncaught application exception for %s" % trno)
import webob
body = iter(
webob.Response(
'A system error occurred', status=500
)(env, start_response)
)
first = ''
return response[0], first, body
if tracelog:
info = logging.getLogger(tracelog).info
no_message_format = '%s %s %s'
message_format = '%s %s %s %s'
now = datetime.datetime.now
def log(trno, code, message=None):
if message:
info(message_format, code, trno, now(), message)
else:
info(no_message_format, code, trno, now())
tracelog = log
tracelog('0', "S") # process started
class ApplicationTraceLog(object):
def __init__(self, trno):
self.trno = trno
def log(self, msg=None, code='-'):
log(self.trno, code, msg)
def call_app_w_tracelog(trno, env):
log(trno, 'C')
env[tracelog_key] = ApplicationTraceLog(trno)
response, first, body = call_app(trno, env)
content_length = [v for (h, v) in response[1]
if h.lower() == 'content-length']
content_length = content_length[-1] if content_length else '?'
log(trno, 'A', "%s %s" % (response[0], content_length))
def body_iter():
try:
for data in body:
yield data
finally:
if hasattr(body, 'close'):
body.close()
log(trno, 'E')
return response, first, body_iter()
if threads:
def call_app_w_threads(trno, env):
return pool_apply(call_app_w_tracelog, (trno, env))
self.call_app = call_app_w_threads
else:
self.call_app = call_app_w_tracelog
elif threads:
self.call_app = lambda trno, env: pool_apply(call_app, (trno, env))
else:
self.call_app = call_app
self.tracelog = tracelog
self.server = gevent.server.StreamServer(addr, self.handle_connection)
self.server.start()
self.addr = addr[0], self.server.server_port
def update_settings(self, data):
history = data.get('history')
if history is None:
history = 9999
else:
history = int(history)
self.history = history
max_skill_age = data.get('max_skill_age')
if max_skill_age is None:
max_skill_age = history * 10
else:
max_skill_age = int(max_skill_age)
self.max_skill_age = max_skill_age
self.decay = 1 - 1.0/history
def stop(self):
self.server.stop()
if hasattr(self, 'threadpool'):
self.threadpool.kill()
if self.tracelog is not None:
self.tracelog('0', 'X')
def shutdown(self):
self.server.close()
while 1:
if [conn for conn in self.connections if conn.readers]:
gevent.sleep(.01)
else:
break
self.stop()
def handle_connection(self, sock, addr):
try:
conn = zc.resumelb.util.Worker()
# compute a short unique id for the connection/lb
connid = 0
while [c for c in self.connections if c.id == connid]:
connid += 1
conn.id = connid
self.connections.add(conn)
readers = conn.connected(sock, "%s(%s)" % (addr, connid))
conn.put((0, self.resume))
while conn.is_connected:
try:
rno, data = zc.resumelb.util.read_message(sock)
except zc.resumelb.util.Disconnected:
conn.disconnected()
self.connections.remove(conn)
return
rput = readers.get(rno)
if rput is None:
if data:
env = data
env['zc.resumelb.lb_addr'] = addr
gevent.spawn(
self.handle, conn, rno, conn.start(rno).get, env)
else:
rput(data)
if data is None:
del readers[rno]
except:
error('handle_connection')
def handle(self, conn, rno, get, env):
try:
tracelog = self.tracelog
if tracelog:
trno = "%s.%s" % (conn.id, rno)
query_string = env.get('QUERY_STRING')
url = env['PATH_INFO']
if query_string:
url += '?' + query_string
tracelog(trno, 'B', '%s %s' % (env['REQUEST_METHOD'], url))
else:
trno = rno
env['wsgi.errors'] = sys.stderr
# XXX We're buffering input. Maybe should to have option not to.
content_length = int(env.get('CONTENT_LENGTH', 0))
if content_length > STRING_BUFFER_SIZE:
f = tempfile.TemporaryFile(suffix='.rlbwi')
else:
f = cStringIO.StringIO()
while 1:
data = get()
if data:
f.write(data)
elif data is None:
# Request cancelled (or worker disconnected)
return
else:
break
f.seek(0)
env['wsgi.input'] = f
if tracelog:
tracelog(trno, 'I', env.get('CONTENT_LENGTH') or '0')
response, first, body = self.call_app(trno, env)
try:
requests = conn.readers
if rno not in requests:
return # cancelled
conn.put((rno, response))
if rno not in requests:
return # cancelled
if first:
conn.put((rno, first))
for data in body:
if rno not in requests:
return # cancelled
if data:
conn.put((rno, data))
conn.put((rno, ''))
# Update resume
elapsed = max(time.time() - env['zc.resumelb.time'], 1e-9)
rclass = env['zc.resumelb.request_class']
generation = self.generation + 1
perf_data = self.perf_data.get(rclass)
if perf_data:
rgen, rtime, rcount = perf_data
else:
rgen = generation
rtime = rcount = 0
decay = self.decay ** (generation - rgen)
rgen = generation
rtime = rtime * decay + elapsed
rcount = rcount * decay + 1
self.generation = generation
self.perf_data[rclass] = rgen, rtime, rcount
self.resume[rclass] = rcount / rtime
if generation % self.history == 0:
min_gen = generation - self.max_skill_age
for rclass in [r for (r, d) in self.perf_data.iteritems()
if d[0] < min_gen]:
del self.perf_data[rclass]
del self.resume[rclass]
self.new_resume(self.resume)
except zc.resumelb.util.Disconnected:
return # whatever
finally:
if hasattr(body, 'close'):
body.close()
except:
error('handle_connection')
finally:
f = env.get('wsgi.input')
if f is not None:
f.close()
conn.end(rno)
def new_resume(self, resume):
self.resume = resume
if self.resume_file:
try:
with open(self.resume_file, 'w') as f:
marshal.dump(resume, f)
except Exception:
logger.exception('reading resume file')
for conn in self.connections:
if conn.is_connected:
try:
conn.put((0, resume))
except zc.resumelb.util.Disconnected:
pass
def get_resume(addr):
socket = gevent.socket.create_connection(addr)
rno, data = zc.resumelb.util.read_message(socket)
socket.close()
assert rno == 0, rno
return data
def get_resume_main(args=None):
if args is None:
args = sys.argv[1:]
from pprint import pprint
for arg in args:
print arg
pprint(get_resume(zc.parse_addr.parse_addr(arg)), width=1)
def server_runner(app, global_conf, address, **kw):
# paste deploy hook
logging.basicConfig(level=logging.INFO)
host, port = address.split(':')
Worker(app, (host, int(port)), **kw).server.serve_forever() | zc.resumelb | /zc.resumelb-1.0.2.tar.gz/zc.resumelb-1.0.2/src/zc/resumelb/worker.py | worker.py |
from bisect import bisect_left, insort
import collections
import gevent
import gevent.hub
import gevent.pywsgi
import gevent.socket
import llist
import logging
import re
import socket
import sys
import time
import webob
import zc.parse_addr
import zc.resumelb.util
block_size = 1<<16
logger = logging.getLogger(__name__)
retry_methods = set(('GET', 'HEAD'))
default_disconnect_message = '''
<html><meta http-equiv="refresh" content="1"><body>
The server was unable to handle your request due to a transient failure.
Please try again.
</body></html>
'''
class LB:
def __init__(self, worker_addrs, classifier,
disconnect_message=default_disconnect_message,
pool_factory=None,
**pool_settings):
self.classifier = classifier
self.disconnect_message = disconnect_message
if pool_factory is None:
pool_factory = Pool
self.pool = pool_factory(**pool_settings)
self.update_settings = self.pool.update_settings
self.workletts = {}
self.set_worker_addrs(worker_addrs)
def set_worker_addrs(self, addrs):
# addrs can be an iterable of addresses, or a dict {addr -> version}
if not isinstance(addrs, dict):
addrs = dict((addr, None) for addr in addrs)
workletts = self.workletts
self.worker_addrs = addrs
for addr in addrs:
if addr not in workletts:
workletts[addr] = gevent.spawn(
self.connect, addr, workletts, addrs[addr])
connect_sleep = 1.0
def connect(self, addr, workletts, version):
try:
while addr in self.worker_addrs:
try:
sock = gevent.socket.create_connection(addr)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
Worker(self.pool, sock, addr, version)
except gevent.GreenletExit, v:
try:
sock.close()
except:
pass
raise
except Exception, v:
logger.exception('lb connecting to %r', addr)
gevent.sleep(self.connect_sleep)
finally:
del self.workletts[addr]
def stop(self):
for g in self.workletts.values():
g.kill()
self.workletts.clear()
def shutdown(self):
while self.pool.backlog:
gevent.sleep(.01)
self.stop()
def handle_wsgi(self, env, start_response):
rclass = self.classifier(env)
#logger.debug('wsgi: %s', rclass)
while 1:
worker = self.pool.get(rclass)
try:
return worker.handle(rclass, env, start_response)
except zc.resumelb.util.Disconnected:
if (int(env.get('CONTENT_LENGTH', 0)) == 0 and
env.get('REQUEST_METHOD') in retry_methods
):
logger.info("%s disconnected, retrying %s", worker, env)
else:
return webob.Response(
status = '502 Bad Gateway',
content_type= 'text/html',
body = self.disconnect_message
)(env, start_response)
finally:
self.pool.put(worker)
class PoolBase(object):
def __init__(self, single_version):
self.single_version = single_version
if single_version:
# {version -> {worker}}
self.byversion = collections.defaultdict(set)
self.version = None
def new_resume(self, worker, resume):
if self.single_version:
version = worker.version
self.byversion[version].add(worker)
if self.version is None:
logger.info('VERSION: %s', version)
self.version = version
if version == self.version:
# Adding a worker to the quorum will always preserve the quorum
self._new_resume(worker, resume)
else:
# Since the worker wasn't in the quorum, we don't call
# _new_resume, so we need to update it's resume ourselves:
worker.resume = resume
# Adding this worker might have created a new quorum
self._update_quorum()
else:
self._new_resume(worker, resume)
def remove(self, worker):
if self.single_version:
self.byversion[worker.version].remove(worker)
if worker.version == self.version:
self._remove(worker)
self._update_quorum()
# Note if the worker's version isn't self.version, it's
# not in the quorum, and it's removal can't cause the
# quorum to change.
else:
self._remove(worker)
def _update_quorum(self):
byversion = self.byversion
version = sorted(byversion, key=lambda v: -len(byversion[v]))[0]
if (version == self.version or
len(byversion[version]) == len(byversion[self.version])
):
return # No change
for worker in byversion[self.version]:
# XXX Maybe we should try to retry requests in worker's existing
# backlog.
self._remove(worker)
logger.info('VERSION: %s', version)
self.version = version
for worker in byversion[version]:
self._new_resume(worker, worker.resume)
def status(self):
return dict(
backlog = self.backlog,
mean_backlog = self.mbacklog,
workers = [
(worker.__name__,
worker.backlog,
getattr(worker, 'mbacklog', worker.backlog),
(worker.oldest_time if worker.oldest_time else None),
)
for worker in sorted(
self.workers, key=lambda w: w.__name__)
],
workers_ex = [
(worker.__name__,
worker.write_queue.qsize()
if hasattr(worker, 'write_queue') else 0,
)
for worker in sorted(
self.workers, key=lambda w: w.__name__)
],
)
class Pool(PoolBase):
def __init__(self,
unskilled_score=None, variance=None, backlog_history=None,
single_version=False):
super(Pool, self).__init__(single_version)
self.workers = set()
self.nworkers = 0
self.unskilled = llist.dllist()
self.skilled = {} # rclass -> {[(score, workers)]}
self.event = gevent.event.Event()
_init_backlog(self)
self.update_settings(dict(
unskilled_score=unskilled_score,
variance=variance,
backlog_history=backlog_history))
_meta_settings = dict(
unskilled_score=1.0,
variance=1.0,
backlog_history=9
)
def update_settings(self, settings):
for name, default in self._meta_settings.iteritems():
setting = settings.get(name)
if setting is None:
setting = default
else:
setting = type(default)(setting)
setattr(self, name, setting)
self._update_worker_decay()
self._update_decay()
def _update_decay(self):
if self.nworkers:
self.decay = 1.0 - 1.0/(self.backlog_history*2*self.nworkers)
def _update_worker_decay(self):
self.worker_decay = 1.0 - 1.0/(self.backlog_history*2)
def __repr__(self):
outl = []
out = outl.append
if self.single_version:
out('Version: %s' % self.version)
for v in self.byversion:
if v != self.version and self.byversion[v]:
out(' Inactive: %s: %r' % (v, self.byversion[v]))
out('Request classes:')
for (rclass, skilled) in sorted(self.skilled.items()):
out(' %s: %s'
% (rclass,
', '.join(
'%s(%s,%s)' %
(worker, score, worker.mbacklog)
for (score, worker) in sorted(skilled)
))
)
out('Backlogs:')
out(" overall backlog: %s Decayed: %s Avg: %s" % (
self.backlog, self.mbacklog,
(self.mbacklog / self.nworkers) if self.nworkers else None
))
backlogs = {}
for worker in self.workers:
backlogs.setdefault(worker.backlog, []).append(worker)
for backlog, workers in sorted(backlogs.items()):
out(' %s: %r' % (backlog, sorted(workers)))
return '\n'.join(outl)
def _new_resume(self, worker, resume):
skilled = self.skilled
workers = self.workers
if worker in workers:
for rclass, score in worker.resume.iteritems():
skilled[rclass].remove((score, worker))
else:
_init_backlog(worker)
workers.add(worker)
self.nworkers = len(self.workers)
self._update_decay()
worker.lnode = self.unskilled.appendleft(worker)
self.event.set()
worker.resume = resume
for rclass, score in resume.iteritems():
try:
skilled[rclass].add((score, worker))
except KeyError:
skilled[rclass] = set(((score, worker), ))
logger.info('new resume: %s', worker)
def _remove(self, worker):
skilled = self.skilled
for rclass, score in worker.resume.iteritems():
skilled[rclass].remove((score, worker))
if getattr(worker, 'lnode', None) is not None:
self.unskilled.remove(worker.lnode)
worker.lnode = None
self.workers.remove(worker)
self.nworkers = len(self.workers)
if self.nworkers:
self._update_decay()
else:
self.event.clear()
def get(self, rclass, timeout=None):
"""Get a worker to handle a request class
"""
unskilled = self.unskilled
if not unskilled:
self.event.wait(timeout)
if not unskilled:
return None
# Look for a skilled worker
best_score = 0
best_worker = None
skilled = self.skilled.get(rclass)
if skilled is None:
skilled = self.skilled[rclass] = set()
max_backlog = max(self.variance * self.mbacklog / self.nworkers, 1)
min_backlog = unskilled.first.value.mbacklog + 1
for score, worker in skilled:
if (worker.mbacklog - min_backlog) > max_backlog:
continue
backlog = worker.backlog
if backlog > 1:
score /= backlog
if (score > best_score):
best_score = score
best_worker = worker
if not best_score:
best_worker = unskilled.first.value
if rclass not in best_worker.resume:
# We now have an unskilled worker and we need to
# assign it a score.
score = self.unskilled_score
best_worker.resume[rclass] = score
skilled.add((score, best_worker))
# Move worker from lru to mru end of queue
unskilled.remove(best_worker.lnode)
best_worker.lnode = unskilled.append(best_worker)
best_worker.backlog += 1
_decay_backlog(best_worker, self.worker_decay)
self.backlog += 1
_decay_backlog(self, self.decay)
return best_worker
def put(self, worker):
self.backlog -= 1
assert self.backlog >= 0, self.backlog
_decay_backlog(self, self.decay)
worker.backlog -= 1
assert worker.backlog >= 0
_decay_backlog(worker, self.worker_decay)
def _init_backlog(worker):
worker.backlog = getattr(worker, 'backlog', 0)
worker.dbacklog = getattr(worker, 'dbacklog', worker.backlog)
worker.nbacklog = getattr(worker, 'nbacklog', 0)
worker.mbacklog = getattr(worker, 'mbacklog', worker.backlog)
def _decay_backlog(worker, decay):
worker.dbacklog = worker.dbacklog*decay + worker.backlog
worker.nbacklog = worker.nbacklog*decay + 1
worker.mbacklog = worker.dbacklog / worker.nbacklog
class Worker(zc.resumelb.util.LBWorker):
maxrno = (1<<32) - 1
def __init__(self, pool, socket, addr, version):
self.pool = pool
self.nrequest = 0
self.requests = {}
self.__name__ = '%s:%s' % addr
self.version = version
readers = self.connected(socket, addr)
while self.is_connected:
try:
rno, data = zc.resumelb.util.read_message(socket)
except zc.resumelb.util.Disconnected:
self.disconnected()
return
if rno == 0:
pool.new_resume(self, data)
else:
try:
reader = readers[rno]
except KeyError:
pass
else:
reader(data)
@property
def oldest_time(self):
if self.requests:
return min(self.requests.itervalues())
def __repr__(self):
return self.__name__
def handle(self, rclass, env, start_response):
#logger.debug('handled by %s', self.addr)
env = env.copy()
err = env.pop('wsgi.errors')
input = env.pop('wsgi.input')
env['zc.resumelb.request_class'] = rclass
rno = self.nrequest + 1
self.nrequest = rno % self.maxrno
self.requests[rno] = time.time()
try:
get = self.start(rno).get
put = self.put
try:
put((rno, env))
content_length = int(env.get('CONTENT_LENGTH', 0))
while content_length > 0:
data = input.read(min(content_length, block_size))
if not data:
# Browser disconnected, cancel the request
put((rno, None))
self.end(rno)
return
content_length -= len(data)
put((rno, data))
put((rno, ''))
data = get()
if data is None:
raise zc.resumelb.util.Disconnected()
#logger.debug('start_response %r', data)
start_response(*data)
except:
# not using finally here, because we only want to end on error
self.end(rno)
raise
def content():
try:
# We yield a first value to get into the try so
# the generator close will execute thf finally block. :(
yield 1
while 1:
data = get()
if data:
yield data
else:
if data is None:
logger.warning(
'Disconnected while returning body')
break
finally:
self.end(rno)
# See the "yield 1" comment above. :(
content = content()
content.next()
return content
finally:
del self.requests[rno]
def disconnected(self):
# keep-alive messages send after disconnecting can cause
# disconnected to be called a second time. To avoid this, we
# replace the method on the instance with a noop.
self.disconnected = already_disconnected
self.pool.remove(self)
zc.resumelb.util.Worker.disconnected(self)
def already_disconnected():
pass
def parse_addr(addr):
host, port = addr.split(':')
return host, int(port)
def host_classifier(env):
host = env.get("HTTP_HOST", '')
if host.startswith('www.'):
return host[4:]
return host
def re_classifier(name, regex):
search = re.compile(regex).search
def classifier(env):
value = env.get(name)
if value is not None:
match = search(value)
if match:
return match.group('class')
return ''
return classifier
def main(args=None):
"""%prog [options] worker_addresses
Run a resume-based load balancer on the give addresses.
"""
if args is None:
args = sys.argv[1:]
import optparse
parser = optparse.OptionParser(main.__doc__)
parser.add_option(
'-a', '--address', default=':0',
help="Address to listed on for web requests"
)
parser.add_option(
'-l', '--access-log', default='-',
help='Access-log path.\n\n'
'Use - (default) for standard output.\n'
)
parser.add_option(
'-b', '--backlog', type='int',
help="Server backlog setting.")
parser.add_option(
'-m', '--max-connections', type='int',
help="Maximum number of simultanious accepted connections.")
parser.add_option(
'-L', '--logger-configuration',
help=
"Read logger configuration from the given configuration file path.\n"
"\n"
"The configuration file must be in ZConfig logger configuration syntax."
)
parser.add_option(
'-r', '--request-classifier', default='zc.resumelb.lb:host_classifier',
help="Request classification function (module:expr)"
)
parser.add_option(
'-e', '--disconnect-message',
help="Path to error page to use when a request is lost due to "
"worker disconnection"
)
parser.add_option(
'-v', '--variance', type='float', default=4.0,
help="Maximum ration of a worker backlog to the mean backlog"
)
parser.add_option(
'--backlog-history', type='int', default=9,
help="Rough numner of requests to average worker backlogs over"
)
parser.add_option(
'--unskilled-score', type='float', default=1.0,
help="Score (requests/second) to assign to new workers."
)
options, args = parser.parse_args(args)
if not args:
print 'Error: must supply one or more worker addresses.'
parser.parse_args(['-h'])
if options.logger_configuration:
logger_config = options.logger_configuration
if re.match(r'\d+$', logger_config):
logging.basicConfig(level=int(logger_config))
elif logger_config in ('CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG'):
logging.basicConfig(level=getattr(logging, logger_config))
else:
import ZConfig
with open(logger_config) as f:
ZConfig.configureLoggers(f.read())
addrs = map(parse_addr, args)
wsgi_addr = parse_addr(options.address)
lb = LB(addrs, host_classifier,
variance=options.variance,
backlog_history=options.backlog_history,
unskilled_score=options.unskilled_score)
# Now, start a wsgi server
addr = zc.parse_addr.parse_addr(options.address)
if options.max_connections:
spawn= gevent.pool.Pool(options.max_connections)
else:
spawn = 'default'
accesslog = options.access_log
if isinstance(accesslog, str):
accesslog = sys.stdout if accesslog == '-' else open(accesslog, 'a')
gevent.pywsgi.WSGIServer(
wsgi_addr, lb.handle_wsgi, backlog = options.backlog,
spawn = spawn, log = accesslog)
gevent.pywsgi.WSGIServer(wsgi_addr, lb.handle_wsgi).serve_forever() | zc.resumelb | /zc.resumelb-1.0.2.tar.gz/zc.resumelb-1.0.2/src/zc/resumelb/lb.py | lb.py |
Use a file-system directory as an queue for uploading files to S3
=================================================================
This package provides support for implementing an S3 upload queue
using a file directory.
An application that wants to upload to S3 writes a temporary file and
then moves it into a directory and then goes on about it's business.
Separately, either in a daemon, or in a separate application thread,
zc.s3uploadqueue.main is run, which watches the directory and moves
files to S3 as they appear.
The main function takes the name of a configuration file.
The configuration file has 2 sections:
Credentials
The AWS credentials, with options:
aws_access_key_id
Your AWS access key
aws_secret_access_key
Your AWS secret access key
Queue
Option controlling the queue processing:
directory
The directory containing files to be moved to S3
bucket
The S3 bucket name
poll-interval
How often to poll for files.
This defaults to 9 seconds.
threads
The number of threads to use for processing files.
Defaults to 9.
log-level
Basic logging log level.
Defaults to INFO.
The file names in the directory must be URL-encoded S3 Keys. This
allows '/'s to be included without using directories.
The ``main`` function will poll the directory every poll interval and
upload any files found. As it uploads each file, it will remove it
from the source directory. After uploading all of the files found, it
will poll immediately, in case new files were added while processing
files.
Here's a sample configuration::
[Credentials]
aws_access_key_id = 42
aws_secret_access_key = k3y
[Queue]
directory = test
bucket = testbucket
poll-interval = 1
threads = 2
.. -> config
>>> import os
>>> os.mkdir('test')
>>> write('queue.cfg', config)
If we were to put files in S3, we'd place them in the ``test``
directory. For example, to put data at the key:
``2012-06-14/01.txt``, we'd store the data in the file::
2012-06-14%2F01.txt
.. -> name
This is the key name urlquoted with no safe characters::
urllib.quote(key, safe='')
We can run the updater as a long-running script (using something like
`zdaemon <http://pypi.python.org/pypi/zdaemon>`_ or `supervisor
<http://pypi.python.org/pypi/supervisor>`_) or as a from an existing
process. To run from an existing process, just import the ``process``
function and run it::
import zc.s3uploadqueue
stop = zc.s3uploadqueue.process('queue.cfg')
if stop: stop()
.. -> src
This starts a daemonic threads that upload any files placed in the directory.
.. basic test with above data and code
Place some data:
>>> write('/'.join(['test', name.strip()]), '')
>>> import logging
>>> import zope.testing.loggingsupport
>>> handler = zope.testing.loggingsupport.InstalledHandler(
... "zc.s3uploadqueue", level=logging.INFO)
>>> def show_log():
... print handler
... handler.clear()
Start the processor:
>>> exec src
Wait a bit and see that boto was called:
>>> import time
>>> time.sleep(.1)
The two threads we created setup the necessary connection with S3:
>>> import boto.s3.connection, pprint
>>> pprint.pprint(boto.s3.connection.S3Connection.mock_calls) #doctest: +ELLIPSIS
[call('42', 'k3y', calling_format=<boto.s3.connection.OrdinaryCallingFormat object at ...>),
call().get_bucket('testbucket'),
call('42', 'k3y', calling_format=<boto.s3.connection.OrdinaryCallingFormat object at ...>),
call().get_bucket('testbucket')]
The file that we put in is processed and uploaded to S3:
>>> pprint.pprint(boto.s3.key.Key.mock_calls) #doctest: +ELLIPSIS
[call(<MagicMock name='S3Connection().get_bucket()' id='...'>),
call(<MagicMock name='S3Connection().get_bucket()' id='...'>),
call().set_contents_from_filename('test/2012-06-14%2F01.txt')]
>>> show_log()
zc.s3uploadqueue INFO
Transferred '2012-06-14%2F01.txt'
If there's an exception, that'll be logged as well. To simulate an exception,
we'll monkey-patch the "urllib.unquote" method to raise an exception.
>>> import urllib
>>> orig_unquote = urllib.unquote
>>> def fake_unquote(s):
... 1/0
>>> urllib.unquote = fake_unquote
>>> write('/'.join(['test', name.strip()]), '')
>>> exec src
>>> show_log()
zc.s3uploadqueue ERROR
processing '2012-06-14%2F01.txt'
>>> urllib.unquote = orig_unquote
If there's an error getting the S3 bucket, an exception will be printed.
>>> def foo(self, s):
... raise Exception('some error accessing an S3 bucket.')
>>> boto.s3.connection.S3Connection.return_value.get_bucket.side_effect = foo
>>> write('/'.join(['test', name.strip()]), '')
>>> exec src
>>> show_log()
zc.s3uploadqueue ERROR
Error accessing bucket: 'testbucket'
>>> handler.uninstall()
| zc.s3uploadqueue | /zc.s3uploadqueue-0.1.1.tar.gz/zc.s3uploadqueue-0.1.1/src/zc/s3uploadqueue/README.txt | README.txt |
import boto.s3.connection
import boto.s3.key
import ConfigParser
import logging
import os
import Queue
import sys
import time
import urllib
import zc.thread
logger = logging.getLogger(__name__)
levels = dict(
CRITICAL=50,
ERROR=40,
WARNING=30,
INFO=20,
DEBUG=10,
NOTSET=0,
)
def process(config=None):
return_stop = True
if config is None:
[config] = sys.argv[1:]
return_stop = False
parser = ConfigParser.RawConfigParser()
parser.read(config)
options = dict((section, dict(parser.items(section))) for section in parser.sections())
logging.basicConfig(level=levels[options['Queue'].get('log-level', 'INFO')])
queue = Queue.Queue()
srcdir = options['Queue']['directory']
nthreads = int(options['Queue'].get('threads', 9))
poll_interval = int(options['Queue'].get('poll-interval', 9))
def process_queue(bucket):
key = boto.s3.key.Key(bucket)
while 1:
try:
name = queue.get()
if name is None:
# stop
return
key.key = urllib.unquote(name)
path = os.path.join(srcdir, name)
key.set_contents_from_filename(path)
os.remove(path)
logger.info('Transferred %r', name)
except Exception:
logger.exception('processing %r', name)
finally:
queue.task_done()
running = [1]
threads = []
for i in range(nthreads):
conn = boto.s3.connection.S3Connection(
options['Credentials']['aws_access_key_id'],
options['Credentials']['aws_secret_access_key'],
calling_format=boto.s3.connection.OrdinaryCallingFormat()
)
try:
bucket = conn.get_bucket(options['Queue']['bucket'])
except Exception:
logger.exception('Error accessing bucket: %r', options['Queue']['bucket'])
return
threads.append(zc.thread.Thread(process_queue, args=[bucket]))
def stop():
running.pop()
for thread in threads:
thread.join(1)
@zc.thread.Thread(daemon=False)
def poll():
while running:
files = os.listdir(srcdir)
if files:
for name in files:
queue.put(name)
queue.join()
else:
time.sleep(poll_interval)
for thread in threads:
queue.put(None)
if return_stop:
return stop
if __name__ == '__main__':
process() | zc.s3uploadqueue | /zc.s3uploadqueue-0.1.1.tar.gz/zc.s3uploadqueue-0.1.1/src/zc/s3uploadqueue/__init__.py | __init__.py |
System Buildouts
****************
The system buildout script (``sbo``) provided by the zc.sbo package is
used to perform "system" buildouts that write to system directories
on unix-like systems. They are run using ``sudo`` or as ``root`` so
they can write to system directiories. You can install the ``sbo``
command into a Python environment using its setup script or a tool
like easy_install.
One installed, the ``sbo`` command is typically run with 2 arguments:
- The name of an application
- The name of a configuration
It expects the application to be a build-based application in
``/opt/APPLICATION-NAME``. It expects to find a buildout
configuration in ``/etc/APPLICATION-NAME/CONFIG-NAME.cfg``
For example, if invoked with::
sbo myapp abccorp
It will run::
/opt/myapp/bin/buildout buildout:directory=/opt/myapp \
-oUc /etc/myapp/sbccorp.cfg
Run with the -h option to get additional help.
Changes
*******
0.6.1 (2011-03-10)
==================
- Add missing --version option to report sbo's version.
0.6.0 (2010-11-05)
==================
- Add --installation to point to a specific software installation to use.
0.1.0 (yyyy-mm-dd)
==================
Initial release
| zc.sbo | /zc.sbo-0.6.1.tar.gz/zc.sbo-0.6.1/README.txt | README.txt |
import os, shutil, sys, tempfile, textwrap, urllib, urllib2, subprocess
from optparse import OptionParser
if sys.platform == 'win32':
def quote(c):
if ' ' in c:
return '"%s"' % c # work around spawn lamosity on windows
else:
return c
else:
quote = str
# See zc.buildout.easy_install._has_broken_dash_S for motivation and comments.
stdout, stderr = subprocess.Popen(
[sys.executable, '-Sc',
'try:\n'
' import ConfigParser\n'
'except ImportError:\n'
' print 1\n'
'else:\n'
' print 0\n'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
has_broken_dash_S = bool(int(stdout.strip()))
# In order to be more robust in the face of system Pythons, we want to
# run without site-packages loaded. This is somewhat tricky, in
# particular because Python 2.6's distutils imports site, so starting
# with the -S flag is not sufficient. However, we'll start with that:
if not has_broken_dash_S and 'site' in sys.modules:
# We will restart with python -S.
args = sys.argv[:]
args[0:0] = [sys.executable, '-S']
args = map(quote, args)
os.execv(sys.executable, args)
# Now we are running with -S. We'll get the clean sys.path, import site
# because distutils will do it later, and then reset the path and clean
# out any namespace packages from site-packages that might have been
# loaded by .pth files.
clean_path = sys.path[:]
import site
sys.path[:] = clean_path
for k, v in sys.modules.items():
if k in ('setuptools', 'pkg_resources') or (
hasattr(v, '__path__') and
len(v.__path__)==1 and
not os.path.exists(os.path.join(v.__path__[0],'__init__.py'))):
# This is a namespace package. Remove it.
sys.modules.pop(k)
is_jython = sys.platform.startswith('java')
setuptools_source = 'http://peak.telecommunity.com/dist/ez_setup.py'
distribute_source = 'http://python-distribute.org/distribute_setup.py'
# parsing arguments
def normalize_to_url(option, opt_str, value, parser):
if value:
if '://' not in value: # It doesn't smell like a URL.
value = 'file://%s' % (
urllib.pathname2url(
os.path.abspath(os.path.expanduser(value))),)
if opt_str == '--download-base' and not value.endswith('/'):
# Download base needs a trailing slash to make the world happy.
value += '/'
else:
value = None
name = opt_str[2:].replace('-', '_')
setattr(parser.values, name, value)
usage = '''\
[DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options]
Bootstraps a buildout-based project.
Simply run this script in a directory containing a buildout.cfg, using the
Python that you want bin/buildout to use.
Note that by using --setup-source and --download-base to point to
local resources, you can keep this script from going over the network.
'''
parser = OptionParser(usage=usage)
parser.add_option("-v", "--version", dest="version",
help="use a specific zc.buildout version")
parser.add_option("-d", "--distribute",
action="store_true", dest="use_distribute", default=False,
help="Use Distribute rather than Setuptools.")
parser.add_option("--setup-source", action="callback", dest="setup_source",
callback=normalize_to_url, nargs=1, type="string",
help=("Specify a URL or file location for the setup file. "
"If you use Setuptools, this will default to " +
setuptools_source + "; if you use Distribute, this "
"will default to " + distribute_source +"."))
parser.add_option("--download-base", action="callback", dest="download_base",
callback=normalize_to_url, nargs=1, type="string",
help=("Specify a URL or directory for downloading "
"zc.buildout and either Setuptools or Distribute. "
"Defaults to PyPI."))
parser.add_option("--eggs",
help=("Specify a directory for storing eggs. Defaults to "
"a temporary directory that is deleted when the "
"bootstrap script completes."))
parser.add_option("-t", "--accept-buildout-test-releases",
dest='accept_buildout_test_releases',
action="store_true", default=False,
help=("Normally, if you do not specify a --version, the "
"bootstrap script and buildout gets the newest "
"*final* versions of zc.buildout and its recipes and "
"extensions for you. If you use this flag, "
"bootstrap and buildout will get the newest releases "
"even if they are alphas or betas."))
parser.add_option("-c", None, action="store", dest="config_file",
help=("Specify the path to the buildout configuration "
"file to be used."))
options, args = parser.parse_args()
# if -c was provided, we push it back into args for buildout's main function
if options.config_file is not None:
args += ['-c', options.config_file]
if options.eggs:
eggs_dir = os.path.abspath(os.path.expanduser(options.eggs))
else:
eggs_dir = tempfile.mkdtemp()
if options.setup_source is None:
if options.use_distribute:
options.setup_source = distribute_source
else:
options.setup_source = setuptools_source
if options.accept_buildout_test_releases:
args.append('buildout:accept-buildout-test-releases=true')
args.append('bootstrap')
try:
import pkg_resources
import setuptools # A flag. Sometimes pkg_resources is installed alone.
if not hasattr(pkg_resources, '_distribute'):
raise ImportError
except ImportError:
ez_code = urllib2.urlopen(
options.setup_source).read().replace('\r\n', '\n')
ez = {}
exec ez_code in ez
setup_args = dict(to_dir=eggs_dir, download_delay=0)
if options.download_base:
setup_args['download_base'] = options.download_base
if options.use_distribute:
setup_args['no_fake'] = True
ez['use_setuptools'](**setup_args)
if 'pkg_resources' in sys.modules:
reload(sys.modules['pkg_resources'])
import pkg_resources
# This does not (always?) update the default working set. We will
# do it.
for path in sys.path:
if path not in pkg_resources.working_set.entries:
pkg_resources.working_set.add_entry(path)
cmd = [quote(sys.executable),
'-c',
quote('from setuptools.command.easy_install import main; main()'),
'-mqNxd',
quote(eggs_dir)]
if not has_broken_dash_S:
cmd.insert(1, '-S')
find_links = options.download_base
if not find_links:
find_links = os.environ.get('bootstrap-testing-find-links')
if find_links:
cmd.extend(['-f', quote(find_links)])
if options.use_distribute:
setup_requirement = 'distribute'
else:
setup_requirement = 'setuptools'
ws = pkg_resources.working_set
setup_requirement_path = ws.find(
pkg_resources.Requirement.parse(setup_requirement)).location
env = dict(
os.environ,
PYTHONPATH=setup_requirement_path)
requirement = 'zc.buildout'
version = options.version
if version is None and not options.accept_buildout_test_releases:
# Figure out the most recent final version of zc.buildout.
import setuptools.package_index
_final_parts = '*final-', '*final'
def _final_version(parsed_version):
for part in parsed_version:
if (part[:1] == '*') and (part not in _final_parts):
return False
return True
index = setuptools.package_index.PackageIndex(
search_path=[setup_requirement_path])
if find_links:
index.add_find_links((find_links,))
req = pkg_resources.Requirement.parse(requirement)
if index.obtain(req) is not None:
best = []
bestv = None
for dist in index[req.project_name]:
distv = dist.parsed_version
if _final_version(distv):
if bestv is None or distv > bestv:
best = [dist]
bestv = distv
elif distv == bestv:
best.append(dist)
if best:
best.sort()
version = best[-1].version
if version:
requirement = '=='.join((requirement, version))
cmd.append(requirement)
if is_jython:
import subprocess
exitcode = subprocess.Popen(cmd, env=env).wait()
else: # Windows prefers this, apparently; otherwise we would prefer subprocess
exitcode = os.spawnle(*([os.P_WAIT, sys.executable] + cmd + [env]))
if exitcode != 0:
sys.stdout.flush()
sys.stderr.flush()
print ("An error occurred when trying to install zc.buildout. "
"Look above this message for any errors that "
"were output by easy_install.")
sys.exit(exitcode)
ws.add_entry(eggs_dir)
ws.require(requirement)
import zc.buildout.buildout
zc.buildout.buildout.main(args)
if not options.eggs: # clean up temporary egg directory
shutil.rmtree(eggs_dir) | zc.sbo | /zc.sbo-0.6.1.tar.gz/zc.sbo-0.6.1/bootstrap.py | bootstrap.py |
import optparse
import os
import pkg_resources
import subprocess
import sys
import tempfile
for dist in pkg_resources.working_set:
if dist.project_name == "zc.sbo":
version = dist.version
assert version
parser = optparse.OptionParser("""\
Usage: %prog [options] application [configuration]
Configure or unconfigure an application defined by a buildout
configuration file. By default, an application is configured. If the
-u option is provided, then the application is unconfigured. An
optional configuration name may be given. If not given, the
configuration name defaults to the application name.
The buildout configuration path is computed as:
/etc/${application}/${configuration}.cfg
During configuration, the file:
/etc/${application}/${configuration}.configured
will be created, which records information about what was configured to
support unconfiguring.
To perform it's work, the script will run:
/opt/${application}/bin/buildout
So the named application must be installed in /opt.
""", version=("%%prog %s" % version))
parser.add_option(
'-a', '--all', action="store_true", dest="all",
help="Operate on all configurations.",
)
parser.add_option(
'-i', '--installation', action="store", dest="installation",
help="""Installation directory of the application.""",
)
parser.add_option(
'-l', '--list', action="store_true", dest="list",
help="""List available configurations.""",
)
parser.add_option("-q", action="count", dest="quiet",
help="Decrease the verbosity")
parser.add_option('--test-root', dest="test_root",
help="""\
The location of an alternate root directory for testing.
If this is used then the given directory will be used rather than / to
find the opt and etc directories.
""")
parser.add_option(
'-u', '--unconfigure', action="store_true", dest="unconfigure",
help="""\
Remove any configuration artifacts for the given configuration file.
This option reads the associated installation database to discover what
to unconfigure.""")
parser.add_option("-v", action="count", dest="verbosity",
help="Increase the verbosity")
def error(message):
print 'Error:\n%s\n' % message
try:
parser.parse_args(['-h'])
except SystemExit:
pass
sys.exit(1)
def assert_exists(label, path):
if not os.path.exists(path):
error("%s, %r, doesn't exist." % (label, path))
def configs(config_dir):
return sorted(
name[:-4] for name in os.listdir(config_dir)
if name.endswith('.cfg')
)
def main(args=None):
if args is None:
args = sys.argv[1:]
options, args = parser.parse_args(args)
root = options.test_root or '/'
if not args:
error("No application was specified.")
application = args.pop(0)
if options.installation:
app_dir = options.installation
else:
app_dir = os.path.join(root, 'opt', application)
assert_exists("The application directory", app_dir)
buildout = os.path.join(app_dir, 'bin', 'buildout')
assert_exists("The application buildout script", buildout)
config_dir = os.path.join(root, 'etc', application)
assert_exists("The application configuration directory", config_dir)
if options.list:
print '\n'.join(configs(config_dir))
sys.exit(0)
if options.all:
configurations = list(configs(config_dir))
if not configurations:
error("There aren't any configurations")
elif args:
configurations = [args.pop(0)]
else:
configurations = [application]
base_options = [
"buildout:directory=%s" % app_dir,
"-oU",
]
verbosity = (options.verbosity or 0) - (options.quiet or 0)
if verbosity > 0:
base_options[-1] += 'v'*verbosity
elif verbosity < 0:
base_options[-1] += 'q'*(-verbosity)
base_options[-1] += 'c'
for configuration in configurations:
configured = os.path.join(config_dir, '%s.configured' % configuration)
sbooptions = ([buildout] + args + ["buildout:installed=%s" % configured]
+ base_options)
if options.unconfigure:
if not os.path.exists(configured):
print "%r doesn't exist.\nNothing to unconfigure." % configured
sys.exit(0)
fd, configfile = tempfile.mkstemp("buildout")
os.write(fd, "[buildout]\nparts=\n")
os.close(fd)
if verbosity >= 0:
print "Unconfiguring:", configuration
proc = subprocess.Popen(sbooptions + [configfile]
)
proc.wait()
os.remove(configfile)
else:
configfile = os.path.join(config_dir, "%s.cfg" % configuration)
assert_exists("The configuration file", configfile)
if verbosity >= 0:
print "Configuring:", configuration
proc = subprocess.Popen(sbooptions + [configfile])
proc.wait() | zc.sbo | /zc.sbo-0.6.1.tar.gz/zc.sbo-0.6.1/src/zc/sbo/__init__.py | __init__.py |
from zc.security import interfaces
from zope.app.component import queryNextUtility
from zope.app.security import principalregistry
from zope.app.security.interfaces import IAuthentication
from zope.app.security.interfaces import PrincipalLookupError
from zope.security.interfaces import IGroup
import zope.app.authentication.authentication
import zope.app.authentication.groupfolder
import zope.app.authentication.interfaces
import zope.app.authentication.principalfolder
import zope.component
import zope.interface
class PASimpleSearch:
zope.component.adapts(
zope.app.authentication.interfaces.IPluggableAuthentication)
def __init__(self, context):
self.context = context
def searchPrincipals(self, filter, start, size):
if size <= 0:
return
prefix = self.context.prefix
n = 0
for name, plugin in self.context.getAuthenticatorPlugins():
searcher = self.type(plugin, None)
if searcher is None:
continue
sz = size + start - n
if sz <= 0:
return
search = getattr(searcher, self.meth)
for principal_id in search(filter, 0, sz):
if n >= start:
yield prefix + principal_id
n += 1
next = self.context
while 1:
next = queryNextUtility(next, IAuthentication)
if next is None:
return
searcher = self.type(next, None)
if searcher is None:
continue
sz = size + start - n
if sz <= 0:
return
search = getattr(searcher, self.meth)
for principal_id in search(filter, 0, sz):
if n >= start:
yield principal_id
n += 1
return
class PASimpleGroupSearch(PASimpleSearch):
type = interfaces.ISimpleGroupSearch
zope.interface.implements(type)
meth = 'searchGroups'
searchGroups = PASimpleSearch.searchPrincipals
class PASimpleUserSearch(PASimpleSearch):
type = interfaces.ISimpleUserSearch
zope.interface.implements(type)
meth = 'searchUsers'
searchUsers = PASimpleSearch.searchPrincipals
class GroupFolderSimpleGroupSearch:
def __init__(self, context):
self.context = context
def searchGroups(self, filter, start, size):
return self.context.search({'search': filter}, start, size)
zope.component.adapts(zope.app.authentication.groupfolder.IGroupFolder)
zope.interface.implements(interfaces.ISimpleGroupSearch)
class UserFolderSimpleUserSearch:
zope.component.adapts(
zope.app.authentication.principalfolder.PrincipalFolder)
zope.interface.implements(interfaces.ISimpleUserSearch)
def __init__(self, context):
self.context = context
def searchUsers(self, filter, start, size):
return self.context.search({'search': filter}, start, size)
class UserRegistrySimpleUserSearch:
zope.component.adapts(principalregistry.PrincipalRegistry)
zope.interface.implements(interfaces.ISimpleUserSearch)
def __init__(self, context):
self.context = context
def searchUsers(self, filter, start, size):
filter = filter.lower()
result = [p.id for p in list(self.context.getPrincipals(''))
if (filter in p.getLogin().lower()
or
filter in p.title.lower()
or
filter in p.description.lower()
) and not IGroup.providedBy(p)]
result.sort()
return result[start:start+size]
class UserRegistrySimpleGroupSearch(UserRegistrySimpleUserSearch):
zope.interface.implementsOnly(interfaces.ISimpleGroupSearch)
def searchGroups(self, filter, start, size):
filter = filter.lower()
result = [p.id for p in list(self.context.getPrincipals(''))
if (filter in p.getLogin().lower()
or
filter in p.title.lower()
or
filter in p.description.lower()
) and IGroup.providedBy(p)]
result.sort()
return result[start:start+size]
class SimplePrincipalSource(zope.app.security.vocabulary.PrincipalSource):
zope.interface.implementsOnly(interfaces.ISimplePrincipalSource)
class SimpleUserSource(zope.app.security.vocabulary.PrincipalSource):
zope.interface.implementsOnly(interfaces.ISimpleUserSource)
def __contains__(self, id):
auth = zope.component.getUtility(IAuthentication)
try:
return not IGroup.providedBy(auth.getPrincipal(id))
except PrincipalLookupError:
return False
class SimpleGroupSource(zope.app.security.vocabulary.PrincipalSource):
zope.interface.implementsOnly(interfaces.ISimpleGroupSource)
def __contains__(self, id):
auth = zope.component.getUtility(IAuthentication)
try:
return IGroup.providedBy(auth.getPrincipal(id))
except PrincipalLookupError:
return False
class SimplePrincipalSearch:
zope.interface.implements(interfaces.ISimplePrincipalSearch)
zope.component.adapts(IAuthentication)
def __init__(self, context):
self.context = context
def searchPrincipals(self, filter, start, size):
count = 0
user_search = interfaces.ISimpleUserSearch(self.context, None)
if user_search is not None:
users = user_search.searchUsers(filter, 0, size+start)
for user in users:
if count >= start:
yield user
count += 1
if count-start == size:
return
group_search = interfaces.ISimpleGroupSearch(self.context, None)
if group_search is not None:
groups = group_search.searchGroups(filter, 0, size+start-count)
for group in groups:
if count >= start:
yield group
count += 1
if count-start == size:
return | zc.security | /zc.security-4.2.0.tar.gz/zc.security-4.2.0/src/zc/security/search.py | search.py |
import zope.interface
import zope.schema.interfaces
import zope.app.security.vocabulary
class ISimplePrincipalSource(zope.schema.interfaces.ISource):
"""Supports simple querying."""
class ISimpleUserSource(ISimplePrincipalSource):
"""Supports simple querying."""
class ISimpleGroupSource(ISimplePrincipalSource):
"""Supports simple querying."""
# XXX the search interfaces below should commit to searching by title, or
# have some other specified contract about sorting.
class ISimpleUserSearch(zope.interface.Interface):
"""Simple search limited to users
"""
def searchUsers(filter, start, size):
"""Search for principals
Return an iterable of principal ids.
If a filter is supplied, principals are restricted to
principals that "match" the filter string. Typically,
matching is based on subscrings of text such as principal
titles, descriptions, etc.
Results should be ordered in some consistent fashion, to make
batching work in a reasonable way.
No more than that number of
principal ids will be returned.
"""
class ISimpleGroupSearch(zope.interface.Interface):
"""Simple search limited to users
"""
def searchGroups(filter, start, size):
"""Search for principals
Return an iterable of principal ids.
If a filter is supplied, principals are restricted to
principals that "match" the filter string. Typically,
matching is based on subscrings of text such as principal
titles, descriptions, etc.
Results should be ordered in some consistent fashion, to make
batching work in a reasonable way.
No more than that number of
principal ids will be returned.
"""
class ISimplePrincipalSearch(zope.interface.Interface):
"""Simple search of all principals
"""
def searchPrincipals(filter, start, size):
"""Search for principals
Return an iterable of principal ids.
If a filter is supplied, principals are restricted to
principals that "match" the filter string. Typically,
matching is based on subscrings of text such as principal
titles, descriptions, etc.
Results should be ordered in some consistent fashion, to make
batching work in a reasonable way.
No more than that number of
principal ids will be returned.
""" | zc.security | /zc.security-4.2.0.tar.gz/zc.security-4.2.0/src/zc/security/interfaces.py | interfaces.py |
import zope.app.form.browser.interfaces
import zope.publisher.interfaces.browser
from zope import component, interface, i18n
from zope.app import zapi
from zope.app import pagetemplate
from zope.schema.interfaces import ITitledTokenizedTerm
from zc.security.i18n import _
from zc.security.interfaces import ISimpleUserSource
from zc.security.interfaces import ISimpleUserSearch
from zc.security.interfaces import ISimpleGroupSource
from zc.security.interfaces import ISimpleGroupSearch
from zc.security.interfaces import ISimplePrincipalSource
from zc.security.interfaces import ISimplePrincipalSearch
SEARCH_FIELD_NAME = _('source_query_view_search', 'Search String')
SEARCH_BUTTON = _('search-button', 'Search')
class SimplePrincipalSourceQueryBaseView(object):
interface.implements(zope.app.form.browser.interfaces.ISourceQueryView)
def __init__(self, source, request):
self.context = source
self.request = request
_render = pagetemplate.ViewPageTemplateFile('queryview.pt')
def render(self, name):
field_name = name + '.searchstring'
self.searchstring = self.request.get(field_name)
return self._render(field_name = field_name,
button_name = name + '.search')
def results(self, name):
if not (name+'.search' in self.request):
return None
searchstring = self.request[name+'.searchstring']
if not searchstring:
return None
principals = zapi.principals()
return self.search(principals, searchstring, 0, 999999999999)
def search(self, principals, searchstring, start, size):
raise NotImplementedError('override in subclasses')
class SimpleUserSourceQueryView(SimplePrincipalSourceQueryBaseView):
component.adapts(ISimpleUserSource,
zope.publisher.interfaces.browser.IBrowserRequest)
def search(self, principals, searchstring, start, size):
search = ISimpleUserSearch(principals)
return search.searchUsers(searchstring, start, size)
class SimpleGroupSourceQueryView(SimplePrincipalSourceQueryBaseView):
component.adapts(ISimpleGroupSource,
zope.publisher.interfaces.browser.IBrowserRequest)
def search(self, principals, searchstring, start, size):
search = ISimpleGroupSearch(principals)
return search.searchGroups(searchstring, start, size)
class SimplePrincipalSourceQueryView(SimplePrincipalSourceQueryBaseView):
component.adapts(ISimplePrincipalSource,
zope.publisher.interfaces.browser.IBrowserRequest)
def search(self, principals, searchstring, start, size):
search = ISimplePrincipalSearch(principals)
return search.searchPrincipals(searchstring, start, size)
class Term:
zope.interface.implements(ITitledTokenizedTerm)
def __init__(self, title, token):
self.title = title
self.token = token
class SourceTerms:
"""Term and value support needed by query widgets."""
zope.interface.implements(zope.app.form.browser.interfaces.ITerms)
component.adapts(ISimplePrincipalSource,
zope.publisher.interfaces.browser.IBrowserRequest)
def __init__(self, source, request):
pass
def getTerm(self, value):
principal = zapi.principals().getPrincipal(value)
token = value.encode('base64').strip()
return Term(principal.title, token)
def getValue(self, token):
return token.decode('base64') | zc.security | /zc.security-4.2.0.tar.gz/zc.security-4.2.0/src/zc/security/browser/queryview.py | queryview.py |
from Queue import Queue, Empty
import optparse
import os
import random
import socket
import sys
import threading
import time
import urllib2
import webbrowser
import wsgiref.simple_server
from zope.testing import testrunner
from zc.selenium.pytest import selectTestsToRun
# Compute a default port; this is simple and doesn't ensure that the
# port is available, but does better than just hardcoding a port
# number. The goal is to avoid browser cache effects due to resource
# changes (especially in JavaScript resources).
#
DEFAULT_PORT = "8034"
def run_zope(config, port):
# This removes the script directory from sys.path, which we do
# since there are no modules here.
from zope.app.server.main import main
main(["-C", config, "-X", "http0/address=" + port] + sys.argv[1:])
def make_wsgi_run_zope(app_path):
module, name = app_path.rsplit('.', 1)
app_factory = getattr(__import__(module, globals(), locals(), ["extra"]), name)
def run_zope(config, port):
server = wsgiref.simple_server.make_server(
'0.0.0.0', int(port), app_factory(config))
server.serve_forever()
return run_zope
def run_tests(zope_thread, auto_start, browser_name, port, base_url):
start_time = time.time()
# wait for the server to start
old_timeout = socket.getdefaulttimeout()
socket.setdefaulttimeout(5)
url = base_url % {'port': port}
url += ('/@@/selenium/TestRunner.html'
'?test=tests%%2FTestSuite.html&'
'baseUrl=%s&'
'resultsUrl=%s/@@/selenium_results' % (url,url,))
time.sleep(1)
while zope_thread.isAlive():
try:
urllib2.urlopen(url)
except urllib2.URLError:
time.sleep(1)
else:
break
socket.setdefaulttimeout(old_timeout)
if not zope_thread.isAlive():
return
# start the tests
browser = webbrowser.get(browser_name)
if auto_start:
extra = '&auto=true'
else:
extra = ''
browser.open(url + extra)
# wait for the test results to come in (the reason we don't do a
# blocking-get here is because it keeps Ctrl-C from working)
exit_now = False
while zope_thread.isAlive():
try:
time.sleep(0.1)
except KeyboardInterrupt:
exit_now = True
try:
results = messages.get(False)
except Empty:
if exit_now:
break
else:
break
time.sleep(1) # wait for the last request to finish so stdout is quiet
if exit_now:
return False
print
print 'Selenium test result:', results['result']
if results['result'] != 'passed':
print
print results['log'].replace('\r', '')
print
print '%s tests passed, %s tests failed.' % (
results['numTestPasses'], results['numTestFailures'])
print ('%s commands passed, %s commands failed, %s commands had errors.'
% (results['numCommandPasses'], results['numCommandFailures'],
results['numCommandErrors']))
print 'Elapsed time: %s seconds' % int(time.time() - start_time)
print
return results['result'] == 'passed'
def random_port():
"""Compute a random port number.
This is simple and doesn't ensure that the port is available, but
does better than just hardcoding a port number. The goal is to
avoid browser cache effects due to resource changes (especially in
JavaScript resources).
"""
port_offsets = range(1024)
port_offsets.remove(0)
port_offsets.remove(80) # ignore 8080 since that's often in use
return str(random.choice(port_offsets) + 8000)
def parseOptions():
if '--' in sys.argv:
sep_index = sys.argv.index('--')
extra_args = sys.argv[sep_index+1:]
del sys.argv[sep_index:]
else:
extra_args = []
# First arg is zope.conf file. This is provided by wrapper script
config = sys.argv.pop(1)
usage = 'usage: %prog [options] [-- runzope_options]'
parser = optparse.OptionParser(usage)
parser.add_option('-b', '--browser', metavar="BROWSER", default=None,
help='choose browser to use (mozilla, netscape, '
'kfm, internet-config)')
parser.add_option('-k', '--keep-running',
action='store_true',
help='keep running after finishing the tests')
parser.add_option('-A', '--no-auto-start', dest='auto_start',
action='store_false', default=True,
help='don\'t automatically start the tests (implies -k)')
parser.add_option('-S', '--server-only', dest='server_only',
action='store_true',
help="Just start the Zope server. Don't run any tests")
parser.add_option('-p', '--port', dest='port', default=DEFAULT_PORT,
help='port to run server on')
parser.add_option('-r', '--random-port', dest='random_port',
action='store_true',
help='use a random port for the server')
parser.add_option('-u', '--base-url', dest='base_url',
default='http://localhost:%(port)s/',
help='The base URL of the Zope site (may contain skin).')
parser.add_option('-t', '--test', action="append", dest='tests',
help='specify tests to run')
parser.add_option(
'--coverage', action="store", type='string', dest='coverage',
help="""\
Perform code-coverage analysis, saving trace data to the directory
with the given name. A code coverage summary is printed to standard
out.
""")
parser.add_option(
'--package', '--dir', '-s', action="append", dest='package',
help="A package to be included in the coverage report.")
parser.add_option(
'--wsgi_app', '-w', action="store", dest='wsgi_app',
help="The path to the WSGI application to use.")
options, positional = parser.parse_args()
options.config = config
sys.argv[1:] = extra_args
return options
def main():
global messages
messages = Queue()
# Hack around fact that zc.selenium.results expects zope to be run
# from __main__:
if __name__ != '__main__':
sys.modules['__main__'] = sys.modules[__name__]
options = parseOptions()
if options.random_port:
options.port = random_port()
selectTestsToRun(options.tests)
runner = run_zope
if options.wsgi_app:
runner = make_wsgi_run_zope(options.wsgi_app)
if options.server_only:
runner(options.config, port=options.port)
sys.exit(0)
if options.coverage:
options.package = ('keas',)
options.prefix = (('/', 'keas'),)
options.test_path = []
tracer = testrunner.TestTrace(options, trace=False, count=True)
tracer.start()
zope_thread = threading.Thread(
target=runner, args=(options.config, options.port))
zope_thread.setDaemon(True)
zope_thread.start()
test_result = run_tests(
zope_thread, options.auto_start, options.browser, options.port,
options.base_url)
if options.coverage:
tracer.stop()
coverdir = os.path.join(os.getcwd(), options.coverage)
res = tracer.results()
res.write_results(summary=True, coverdir=coverdir)
if options.keep_running or not options.auto_start:
while True:
time.sleep(10000)
else:
# exit with 0 if all tests passed, 1 if any failed
sys.exit(not test_result)
if __name__ == '__main__':
main() | zc.selenium | /zc.selenium-1.2.1.tar.gz/zc.selenium-1.2.1/src/zc/selenium/selenium.py | selenium.py |
function TestLoop(commandFactory) {
this.commandFactory = commandFactory;
}
TestLoop.prototype = {
start : function() {
selenium.reset();
LOG.debug("currentTest.start()");
this.continueTest();
},
continueTest : function() {
/**
* Select the next command and continue the test.
*/
LOG.debug("currentTest.continueTest() - acquire the next command");
if (! this.aborted) {
this.currentCommand = this.nextCommand();
}
if (! this.requiresCallBack) {
this.continueTestAtCurrentCommand();
} // otherwise, just finish and let the callback invoke continueTestAtCurrentCommand()
},
continueTestAtCurrentCommand : function() {
LOG.debug("currentTest.continueTestAtCurrentCommand()");
if (this.currentCommand) {
// TODO: rename commandStarted to commandSelected, OR roll it into nextCommand
this.commandStarted(this.currentCommand);
this._resumeAfterDelay();
} else {
this._testComplete();
}
},
_resumeAfterDelay : function() {
/**
* Pause, then execute the current command.
*/
// Get the command delay. If a pauseInterval is set, use it once
// and reset it. Otherwise, use the defined command-interval.
var delay = this.pauseInterval || this.getCommandInterval();
this.pauseInterval = undefined;
if (this.currentCommand.isBreakpoint || delay < 0) {
// Pause: enable the "next/continue" button
this.pause();
} else {
window.setTimeout(fnBind(this.resume, this), delay);
}
},
resume: function() {
/**
* Select the next command and continue the test.
*/
LOG.debug("currentTest.resume() - actually execute");
try {
selenium.browserbot.runScheduledPollers();
this._executeCurrentCommand();
this.continueTestWhenConditionIsTrue();
} catch (e) {
if (!this._handleCommandError(e)) {
this.testComplete();
} else {
this.continueTest();
}
}
},
_testComplete : function() {
selenium.ensureNoUnhandledPopups();
this.testComplete();
},
_executeCurrentCommand : function() {
/**
* Execute the current command.
*
* @return a function which will be used to determine when
* execution can continue, or null if we can continue immediately
*/
var command = this.currentCommand;
LOG.info("Executing: |" + command.command + " | " + command.target + " | " + command.value + " |");
var handler = this.commandFactory.getCommandHandler(command.command);
if (handler == null) {
throw new SeleniumError("Unknown command: '" + command.command + "'");
}
command.target = selenium.preprocessParameter(command.target);
command.value = selenium.preprocessParameter(command.value);
LOG.debug("Command found, going to execute " + command.command);
this.result = handler.execute(selenium, command);
this.waitForCondition = this.result.terminationCondition;
},
_handleCommandError : function(e) {
if (!e.isSeleniumError) {
LOG.exception(e);
var msg = "Selenium failure. Please report to the Selenium Users forum at http://forums.openqa.org, with error details from the log window.";
msg += " The error message is: " + extractExceptionMessage(e);
return this.commandError(msg);
} else {
LOG.error(e.message);
return this.commandError(e.message);
}
},
continueTestWhenConditionIsTrue: function () {
/**
* Busy wait for waitForCondition() to become true, and then carry
* on with test. Fail the current test if there's a timeout or an
* exception.
*/
//LOG.debug("currentTest.continueTestWhenConditionIsTrue()");
selenium.browserbot.runScheduledPollers();
try {
if (this.waitForCondition == null) {
LOG.debug("null condition; let's continueTest()");
LOG.debug("Command complete");
this.commandComplete(this.result);
this.continueTest();
} else if (this.waitForCondition()) {
LOG.debug("condition satisfied; let's continueTest()");
this.waitForCondition = null;
LOG.debug("Command complete");
this.commandComplete(this.result);
this.continueTest();
} else {
//LOG.debug("waitForCondition was false; keep waiting!");
window.setTimeout(fnBind(this.continueTestWhenConditionIsTrue, this), 10);
}
} catch (e) {
this.result = {};
this.result.failed = true;
this.result.failureMessage = extractExceptionMessage(e);
this.commandComplete(this.result);
this.continueTest();
}
},
pause : function() {},
nextCommand : function() {},
commandStarted : function() {},
commandComplete : function() {},
commandError : function() {},
testComplete : function() {},
getCommandInterval : function() {
return 0;
}
} | zc.selenium | /zc.selenium-1.2.1.tar.gz/zc.selenium-1.2.1/src/zc/selenium/resources/scripts/selenium-executionloop.js | selenium-executionloop.js |
var storedVars = new Object();
function Selenium(browserbot) {
/**
* Defines an object that runs Selenium commands.
*
* <h3><a name="locators"></a>Element Locators</h3>
* <p>
* Element Locators tell Selenium which HTML element a command refers to.
* The format of a locator is:</p>
* <blockquote>
* <em>locatorType</em><strong>=</strong><em>argument</em>
* </blockquote>
*
* <p>
* We support the following strategies for locating elements:
* </p>
*
* <ul>
* <li><strong>identifier</strong>=<em>id</em>:
* Select the element with the specified @id attribute. If no match is
* found, select the first element whose @name attribute is <em>id</em>.
* (This is normally the default; see below.)</li>
* <li><strong>id</strong>=<em>id</em>:
* Select the element with the specified @id attribute.</li>
*
* <li><strong>name</strong>=<em>name</em>:
* Select the first element with the specified @name attribute.
* <ul class="first last simple">
* <li>username</li>
* <li>name=username</li>
* </ul>
*
* <p>The name may optionally be followed by one or more <em>element-filters</em>, separated from the name by whitespace. If the <em>filterType</em> is not specified, <strong>value</strong> is assumed.</p>
*
* <ul class="first last simple">
* <li>name=flavour value=chocolate</li>
* </ul>
* </li>
* <li><strong>dom</strong>=<em>javascriptExpression</em>:
*
* Find an element by evaluating the specified string. This allows you to traverse the HTML Document Object
* Model using JavaScript. Note that you must not return a value in this string; simply make it the last expression in the block.
* <ul class="first last simple">
* <li>dom=document.forms['myForm'].myDropdown</li>
* <li>dom=document.images[56]</li>
* <li>dom=function foo() { return document.links[1]; }; foo();</li>
* </ul>
*
* </li>
*
* <li><strong>xpath</strong>=<em>xpathExpression</em>:
* Locate an element using an XPath expression.
* <ul class="first last simple">
* <li>xpath=//img[@alt='The image alt text']</li>
* <li>xpath=//table[@id='table1']//tr[4]/td[2]</li>
* <li>xpath=//a[contains(@href,'#id1')]</li>
* <li>xpath=//a[contains(@href,'#id1')]/@class</li>
* <li>xpath=(//table[@class='stylee'])//th[text()='theHeaderText']/../td</li>
* <li>xpath=//input[@name='name2' and @value='yes']</li>
* <li>xpath=//*[text()="right"]</li>
*
* </ul>
* </li>
* <li><strong>link</strong>=<em>textPattern</em>:
* Select the link (anchor) element which contains text matching the
* specified <em>pattern</em>.
* <ul class="first last simple">
* <li>link=The link text</li>
* </ul>
*
* </li>
*
* <li><strong>css</strong>=<em>cssSelectorSyntax</em>:
* Select the element using css selectors. Please refer to <a href="http://www.w3.org/TR/REC-CSS2/selector.html">CSS2 selectors</a>, <a href="http://www.w3.org/TR/2001/CR-css3-selectors-20011113/">CSS3 selectors</a> for more information. You can also check the TestCssLocators test in the selenium test suite for an example of usage, which is included in the downloaded selenium core package.
* <ul class="first last simple">
* <li>css=a[href="#id3"]</li>
* <li>css=span#firstChild + span</li>
* </ul>
* <p>Currently the css selector locator supports all css1, css2 and css3 selectors except namespace in css3, some pseudo classes(:nth-of-type, :nth-last-of-type, :first-of-type, :last-of-type, :only-of-type, :visited, :hover, :active, :focus, :indeterminate) and pseudo elements(::first-line, ::first-letter, ::selection, ::before, ::after). </p>
* </li>
* </ul>
*
* <p>
* Without an explicit locator prefix, Selenium uses the following default
* strategies:
* </p>
*
* <ul class="simple">
* <li><strong>dom</strong>, for locators starting with "document."</li>
* <li><strong>xpath</strong>, for locators starting with "//"</li>
* <li><strong>identifier</strong>, otherwise</li>
* </ul>
*
* <h3><a name="element-filters">Element Filters</a></h3>
* <blockquote>
* <p>Element filters can be used with a locator to refine a list of candidate elements. They are currently used only in the 'name' element-locator.</p>
* <p>Filters look much like locators, ie.</p>
* <blockquote>
* <em>filterType</em><strong>=</strong><em>argument</em></blockquote>
*
* <p>Supported element-filters are:</p>
* <p><strong>value=</strong><em>valuePattern</em></p>
* <blockquote>
* Matches elements based on their values. This is particularly useful for refining a list of similarly-named toggle-buttons.</blockquote>
* <p><strong>index=</strong><em>index</em></p>
* <blockquote>
* Selects a single element based on its position in the list (offset from zero).</blockquote>
* </blockquote>
*
* <h3><a name="patterns"></a>String-match Patterns</h3>
*
* <p>
* Various Pattern syntaxes are available for matching string values:
* </p>
* <ul>
* <li><strong>glob:</strong><em>pattern</em>:
* Match a string against a "glob" (aka "wildmat") pattern. "Glob" is a
* kind of limited regular-expression syntax typically used in command-line
* shells. In a glob pattern, "*" represents any sequence of characters, and "?"
* represents any single character. Glob patterns match against the entire
* string.</li>
* <li><strong>regexp:</strong><em>regexp</em>:
* Match a string using a regular-expression. The full power of JavaScript
* regular-expressions is available.</li>
* <li><strong>exact:</strong><em>string</em>:
*
* Match a string exactly, verbatim, without any of that fancy wildcard
* stuff.</li>
* </ul>
* <p>
* If no pattern prefix is specified, Selenium assumes that it's a "glob"
* pattern.
* </p>
*/
this.browserbot = browserbot;
this.optionLocatorFactory = new OptionLocatorFactory();
// DGF for backwards compatibility
this.page = function() {
return browserbot;
};
this.defaultTimeout = Selenium.DEFAULT_TIMEOUT;
this.mouseSpeed = 10;
}
Selenium.DEFAULT_TIMEOUT = 30 * 1000;
Selenium.DEFAULT_MOUSE_SPEED = 10;
Selenium.decorateFunctionWithTimeout = function(f, timeout) {
if (f == null) {
return null;
}
var timeoutValue = parseInt(timeout);
if (isNaN(timeoutValue)) {
throw new SeleniumError("Timeout is not a number: '" + timeout + "'");
}
var now = new Date().getTime();
var timeoutTime = now + timeoutValue;
return function() {
if (new Date().getTime() > timeoutTime) {
throw new SeleniumError("Timed out after " + timeoutValue + "ms");
}
return f();
};
}
Selenium.createForWindow = function(window, proxyInjectionMode) {
if (!window.location) {
throw "error: not a window!";
}
return new Selenium(BrowserBot.createForWindow(window, proxyInjectionMode));
};
Selenium.prototype.reset = function() {
this.defaultTimeout = Selenium.DEFAULT_TIMEOUT;
// todo: this.browserbot.reset()
this.browserbot.selectWindow("null");
this.browserbot.resetPopups();
};
Selenium.prototype.doClick = function(locator) {
/**
* Clicks on a link, button, checkbox or radio button. If the click action
* causes a new page to load (like a link usually does), call
* waitForPageToLoad.
*
* @param locator an element locator
*
*/
var element = this.browserbot.findElement(locator);
this.browserbot.clickElement(element);
};
Selenium.prototype.doDoubleClick = function(locator) {
/**
* Double clicks on a link, button, checkbox or radio button. If the double click action
* causes a new page to load (like a link usually does), call
* waitForPageToLoad.
*
* @param locator an element locator
*
*/
var element = this.browserbot.findElement(locator);
this.browserbot.doubleClickElement(element);
};
Selenium.prototype.doClickAt = function(locator, coordString) {
/**
* Clicks on a link, button, checkbox or radio button. If the click action
* causes a new page to load (like a link usually does), call
* waitForPageToLoad.
*
* @param locator an element locator
* @param coordString specifies the x,y position (i.e. - 10,20) of the mouse
* event relative to the element returned by the locator.
*
*/
var element = this.browserbot.findElement(locator);
var clientXY = getClientXY(element, coordString)
this.browserbot.clickElement(element, clientXY[0], clientXY[1]);
};
Selenium.prototype.doDoubleClickAt = function(locator, coordString) {
/**
* Doubleclicks on a link, button, checkbox or radio button. If the action
* causes a new page to load (like a link usually does), call
* waitForPageToLoad.
*
* @param locator an element locator
* @param coordString specifies the x,y position (i.e. - 10,20) of the mouse
* event relative to the element returned by the locator.
*
*/
var element = this.browserbot.findElement(locator);
var clientXY = getClientXY(element, coordString)
this.browserbot.doubleClickElement(element, clientXY[0], clientXY[1]);
};
Selenium.prototype.doFireEvent = function(locator, eventName) {
/**
* Explicitly simulate an event, to trigger the corresponding "on<em>event</em>"
* handler.
*
* @param locator an <a href="#locators">element locator</a>
* @param eventName the event name, e.g. "focus" or "blur"
*/
var element = this.browserbot.findElement(locator);
triggerEvent(element, eventName, false);
};
Selenium.prototype.doKeyPress = function(locator, keySequence) {
/**
* Simulates a user pressing and releasing a key.
*
* @param locator an <a href="#locators">element locator</a>
* @param keySequence Either be a string("\" followed by the numeric keycode
* of the key to be pressed, normally the ASCII value of that key), or a single
* character. For example: "w", "\119".
*/
var element = this.browserbot.findElement(locator);
triggerKeyEvent(element, 'keypress', keySequence, true,
this.browserbot.controlKeyDown,
this.browserbot.altKeyDown,
this.browserbot.shiftKeyDown,
this.browserbot.metaKeyDown);
};
Selenium.prototype.doShiftKeyDown = function() {
/**
* Press the shift key and hold it down until doShiftUp() is called or a new page is loaded.
*
*/
this.browserbot.shiftKeyDown = true;
};
Selenium.prototype.doShiftKeyUp = function() {
/**
* Release the shift key.
*
*/
this.browserbot.shiftKeyDown = false;
};
Selenium.prototype.doMetaKeyDown = function() {
/**
* Press the meta key and hold it down until doMetaUp() is called or a new page is loaded.
*
*/
this.browserbot.metaKeyDown = true;
};
Selenium.prototype.doMetaKeyUp = function() {
/**
* Release the meta key.
*
*/
this.browserbot.metaKeyDown = false;
};
Selenium.prototype.doAltKeyDown = function() {
/**
* Press the alt key and hold it down until doAltUp() is called or a new page is loaded.
*
*/
this.browserbot.altKeyDown = true;
};
Selenium.prototype.doAltKeyUp = function() {
/**
* Release the alt key.
*
*/
this.browserbot.altKeyDown = false;
};
Selenium.prototype.doControlKeyDown = function() {
/**
* Press the control key and hold it down until doControlUp() is called or a new page is loaded.
*
*/
this.browserbot.controlKeyDown = true;
};
Selenium.prototype.doControlKeyUp = function() {
/**
* Release the control key.
*
*/
this.browserbot.controlKeyDown = false;
};
Selenium.prototype.doKeyDown = function(locator, keySequence) {
/**
* Simulates a user pressing a key (without releasing it yet).
*
* @param locator an <a href="#locators">element locator</a>
* @param keySequence Either be a string("\" followed by the numeric keycode
* of the key to be pressed, normally the ASCII value of that key), or a single
* character. For example: "w", "\119".
*/
var element = this.browserbot.findElement(locator);
triggerKeyEvent(element, 'keydown', keySequence, true,
this.browserbot.controlKeyDown,
this.browserbot.altKeyDown,
this.browserbot.shiftKeyDown,
this.browserbot.metaKeyDown);
};
Selenium.prototype.doKeyUp = function(locator, keySequence) {
/**
* Simulates a user releasing a key.
*
* @param locator an <a href="#locators">element locator</a>
* @param keySequence Either be a string("\" followed by the numeric keycode
* of the key to be pressed, normally the ASCII value of that key), or a single
* character. For example: "w", "\119".
*/
var element = this.browserbot.findElement(locator);
triggerKeyEvent(element, 'keyup', keySequence, true,
this.browserbot.controlKeyDown,
this.browserbot.altKeyDown,
this.browserbot.shiftKeyDown,
this.browserbot.metaKeyDown);
};
function getClientXY(element, coordString) {
// Parse coordString
var coords = null;
var x;
var y;
if (coordString) {
coords = coordString.split(/,/);
x = Number(coords[0]);
y = Number(coords[1]);
}
else {
x = y = 0;
}
// Get position of element,
// Return 2 item array with clientX and clientY
return [Selenium.prototype.getElementPositionLeft(element) + x, Selenium.prototype.getElementPositionTop(element) + y];
}
Selenium.prototype.doMouseOver = function(locator) {
/**
* Simulates a user hovering a mouse over the specified element.
*
* @param locator an <a href="#locators">element locator</a>
*/
var element = this.browserbot.findElement(locator);
this.browserbot.triggerMouseEvent(element, 'mouseover', true);
};
Selenium.prototype.doMouseOut = function(locator) {
/**
* Simulates a user moving the mouse pointer away from the specified element.
*
* @param locator an <a href="#locators">element locator</a>
*/
var element = this.browserbot.findElement(locator);
this.browserbot.triggerMouseEvent(element, 'mouseout', true);
};
Selenium.prototype.doMouseDown = function(locator) {
/**
* Simulates a user pressing the mouse button (without releasing it yet) on
* the specified element.
*
* @param locator an <a href="#locators">element locator</a>
*/
var element = this.browserbot.findElement(locator);
this.browserbot.triggerMouseEvent(element, 'mousedown', true);
};
Selenium.prototype.doMouseDownAt = function(locator, coordString) {
/**
* Simulates a user pressing the mouse button (without releasing it yet) at
* the specified location.
*
* @param locator an <a href="#locators">element locator</a>
* @param coordString specifies the x,y position (i.e. - 10,20) of the mouse
* event relative to the element returned by the locator.
*/
var element = this.browserbot.findElement(locator);
var clientXY = getClientXY(element, coordString)
this.browserbot.triggerMouseEvent(element, 'mousedown', true, clientXY[0], clientXY[1]);
};
Selenium.prototype.doMouseUp = function(locator) {
/**
* Simulates the event that occurs when the user releases the mouse button (i.e., stops
* holding the button down) on the specified element.
*
* @param locator an <a href="#locators">element locator</a>
*/
var element = this.browserbot.findElement(locator);
this.browserbot.triggerMouseEvent(element, 'mouseup', true);
};
Selenium.prototype.doMouseUpAt = function(locator, coordString) {
/**
* Simulates the event that occurs when the user releases the mouse button (i.e., stops
* holding the button down) at the specified location.
*
* @param locator an <a href="#locators">element locator</a>
* @param coordString specifies the x,y position (i.e. - 10,20) of the mouse
* event relative to the element returned by the locator.
*/
var element = this.browserbot.findElement(locator);
var clientXY = getClientXY(element, coordString)
this.browserbot.triggerMouseEvent(element, 'mouseup', true, clientXY[0], clientXY[1]);
};
Selenium.prototype.doMouseMove = function(locator) {
/**
* Simulates a user pressing the mouse button (without releasing it yet) on
* the specified element.
*
* @param locator an <a href="#locators">element locator</a>
*/
var element = this.browserbot.findElement(locator);
this.browserbot.triggerMouseEvent(element, 'mousemove', true);
};
Selenium.prototype.doMouseMoveAt = function(locator, coordString) {
/**
* Simulates a user pressing the mouse button (without releasing it yet) on
* the specified element.
*
* @param locator an <a href="#locators">element locator</a>
* @param coordString specifies the x,y position (i.e. - 10,20) of the mouse
* event relative to the element returned by the locator.
*/
var element = this.browserbot.findElement(locator);
var clientXY = getClientXY(element, coordString)
this.browserbot.triggerMouseEvent(element, 'mousemove', true, clientXY[0], clientXY[1]);
};
Selenium.prototype.doType = function(locator, value) {
/**
* Sets the value of an input field, as though you typed it in.
*
* <p>Can also be used to set the value of combo boxes, check boxes, etc. In these cases,
* value should be the value of the option selected, not the visible text.</p>
*
* @param locator an <a href="#locators">element locator</a>
* @param value the value to type
*/
if (this.browserbot.controlKeyDown || this.browserbot.altKeyDown || this.browserbot.metaKeyDown) {
throw new SeleniumError("type not supported immediately after call to controlKeyDown() or altKeyDown() or metaKeyDown()");
}
// TODO fail if it can't be typed into.
var element = this.browserbot.findElement(locator);
if (this.browserbot.shiftKeyDown) {
value = new String(value).toUpperCase();
}
this.browserbot.replaceText(element, value);
};
Selenium.prototype.doTypeKeys = function(locator, value) {
/**
* Simulates keystroke events on the specified element, as though you typed the value key-by-key.
*
* <p>This is a convenience method for calling keyDown, keyUp, keyPress for every character in the specified string;
* this is useful for dynamic UI widgets (like auto-completing combo boxes) that require explicit key events.</p>
*
* <p>Unlike the simple "type" command, which forces the specified value into the page directly, this command
* may or may not have any visible effect, even in cases where typing keys would normally have a visible effect.
* For example, if you use "typeKeys" on a form element, you may or may not see the results of what you typed in
* the field.</p>
* <p>In some cases, you may need to use the simple "type" command to set the value of the field and then the "typeKeys" command to
* send the keystroke events corresponding to what you just typed.</p>
*
* @param locator an <a href="#locators">element locator</a>
* @param value the value to type
*/
var keys = new String(value).split("");
for (var i = 0; i < keys.length; i++) {
var c = keys[i];
this.doKeyDown(locator, c);
this.doKeyUp(locator, c);
this.doKeyPress(locator, c);
}
};
Selenium.prototype.doSetSpeed = function(value) {
/**
* Set execution speed (i.e., set the millisecond length of a delay which will follow each selenium operation). By default, there is no such delay, i.e.,
* the delay is 0 milliseconds.
*
* @param value the number of milliseconds to pause after operation
*/
throw new SeleniumError("this operation is only implemented in selenium-rc, and should never result in a request making it across the wire");
};
Selenium.prototype.doGetSpeed = function() {
/**
* Get execution speed (i.e., get the millisecond length of the delay following each selenium operation). By default, there is no such delay, i.e.,
* the delay is 0 milliseconds.
*
* See also setSpeed.
*/
throw new SeleniumError("this operation is only implemented in selenium-rc, and should never result in a request making it across the wire");
};
Selenium.prototype.findToggleButton = function(locator) {
var element = this.browserbot.findElement(locator);
if (element.checked == null) {
Assert.fail("Element " + locator + " is not a toggle-button.");
}
return element;
}
Selenium.prototype.doCheck = function(locator) {
/**
* Check a toggle-button (checkbox/radio)
*
* @param locator an <a href="#locators">element locator</a>
*/
this.findToggleButton(locator).checked = true;
};
Selenium.prototype.doUncheck = function(locator) {
/**
* Uncheck a toggle-button (checkbox/radio)
*
* @param locator an <a href="#locators">element locator</a>
*/
this.findToggleButton(locator).checked = false;
};
Selenium.prototype.doSelect = function(selectLocator, optionLocator) {
/**
* Select an option from a drop-down using an option locator.
*
* <p>
* Option locators provide different ways of specifying options of an HTML
* Select element (e.g. for selecting a specific option, or for asserting
* that the selected option satisfies a specification). There are several
* forms of Select Option Locator.
* </p>
* <ul>
* <li><strong>label</strong>=<em>labelPattern</em>:
* matches options based on their labels, i.e. the visible text. (This
* is the default.)
* <ul class="first last simple">
* <li>label=regexp:^[Oo]ther</li>
* </ul>
* </li>
* <li><strong>value</strong>=<em>valuePattern</em>:
* matches options based on their values.
* <ul class="first last simple">
* <li>value=other</li>
* </ul>
*
*
* </li>
* <li><strong>id</strong>=<em>id</em>:
*
* matches options based on their ids.
* <ul class="first last simple">
* <li>id=option1</li>
* </ul>
* </li>
* <li><strong>index</strong>=<em>index</em>:
* matches an option based on its index (offset from zero).
* <ul class="first last simple">
*
* <li>index=2</li>
* </ul>
* </li>
* </ul>
* <p>
* If no option locator prefix is provided, the default behaviour is to match on <strong>label</strong>.
* </p>
*
*
* @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
* @param optionLocator an option locator (a label by default)
*/
var element = this.browserbot.findElement(selectLocator);
if (!("options" in element)) {
throw new SeleniumError("Specified element is not a Select (has no options)");
}
var locator = this.optionLocatorFactory.fromLocatorString(optionLocator);
var option = locator.findOption(element);
this.browserbot.selectOption(element, option);
};
Selenium.prototype.doAddSelection = function(locator, optionLocator) {
/**
* Add a selection to the set of selected options in a multi-select element using an option locator.
*
* @see #doSelect for details of option locators
*
* @param locator an <a href="#locators">element locator</a> identifying a multi-select box
* @param optionLocator an option locator (a label by default)
*/
var element = this.browserbot.findElement(locator);
if (!("options" in element)) {
throw new SeleniumError("Specified element is not a Select (has no options)");
}
var locator = this.optionLocatorFactory.fromLocatorString(optionLocator);
var option = locator.findOption(element);
this.browserbot.addSelection(element, option);
};
Selenium.prototype.doRemoveSelection = function(locator, optionLocator) {
/**
* Remove a selection from the set of selected options in a multi-select element using an option locator.
*
* @see #doSelect for details of option locators
*
* @param locator an <a href="#locators">element locator</a> identifying a multi-select box
* @param optionLocator an option locator (a label by default)
*/
var element = this.browserbot.findElement(locator);
if (!("options" in element)) {
throw new SeleniumError("Specified element is not a Select (has no options)");
}
var locator = this.optionLocatorFactory.fromLocatorString(optionLocator);
var option = locator.findOption(element);
this.browserbot.removeSelection(element, option);
};
Selenium.prototype.doRemoveAllSelections = function(locator) {
/**
* Unselects all of the selected options in a multi-select element.
*
* @param locator an <a href="#locators">element locator</a> identifying a multi-select box
*/
var element = this.browserbot.findElement(locator);
if (!("options" in element)) {
throw new SeleniumError("Specified element is not a Select (has no options)");
}
for (var i = 0; i < element.options.length; i++) {
this.browserbot.removeSelection(element, element.options[i]);
}
}
Selenium.prototype.doSubmit = function(formLocator) {
/**
* Submit the specified form. This is particularly useful for forms without
* submit buttons, e.g. single-input "Search" forms.
*
* @param formLocator an <a href="#locators">element locator</a> for the form you want to submit
*/
var form = this.browserbot.findElement(formLocator);
return this.browserbot.submit(form);
};
Selenium.prototype.makePageLoadCondition = function(timeout) {
if (timeout == null) {
timeout = this.defaultTimeout;
}
return Selenium.decorateFunctionWithTimeout(fnBind(this._isNewPageLoaded, this), timeout);
};
Selenium.prototype.doOpen = function(url) {
/**
* Opens an URL in the test frame. This accepts both relative and absolute
* URLs.
*
* The "open" command waits for the page to load before proceeding,
* ie. the "AndWait" suffix is implicit.
*
* <em>Note</em>: The URL must be on the same domain as the runner HTML
* due to security restrictions in the browser (Same Origin Policy). If you
* need to open an URL on another domain, use the Selenium Server to start a
* new browser session on that domain.
*
* @param url the URL to open; may be relative or absolute
*/
this.browserbot.openLocation(url);
if (window["proxyInjectionMode"] == null || !window["proxyInjectionMode"]) {
return this.makePageLoadCondition();
} // in PI mode, just return "OK"; the server will waitForLoad
};
Selenium.prototype.doOpenWindow = function(url, windowID) {
/**
* Opens a popup window (if a window with that ID isn't already open).
* After opening the window, you'll need to select it using the selectWindow
* command.
*
* <p>This command can also be a useful workaround for bug SEL-339. In some cases, Selenium will be unable to intercept a call to window.open (if the call occurs during or before the "onLoad" event, for example).
* In those cases, you can force Selenium to notice the open window's name by using the Selenium openWindow command, using
* an empty (blank) url, like this: openWindow("", "myFunnyWindow").</p>
*
* @param url the URL to open, which can be blank
* @param windowID the JavaScript window ID of the window to select
*/
this.browserbot.openWindow(url, windowID);
};
Selenium.prototype.doSelectWindow = function(windowID) {
/**
* Selects a popup window; once a popup window has been selected, all
* commands go to that window. To select the main window again, use null
* as the target.
*
* <p>Note that there is a big difference between a window's internal JavaScript "name" property
* and the "title" of a given window's document (which is normally what you actually see, as an end user,
* in the title bar of the window). The "name" is normally invisible to the end-user; it's the second
* parameter "windowName" passed to the JavaScript method window.open(url, windowName, windowFeatures, replaceFlag)
* (which selenium intercepts).</p>
*
* <p>Selenium has several strategies for finding the window object referred to by the "windowID" parameter.</p>
*
* <p>1.) if windowID is null, (or the string "null") then it is assumed the user is referring to the original window instantiated by the browser).</p>
* <p>2.) if the value of the "windowID" parameter is a JavaScript variable name in the current application window, then it is assumed
* that this variable contains the return value from a call to the JavaScript window.open() method.</p>
* <p>3.) Otherwise, selenium looks in a hash it maintains that maps string names to window "names".</p>
* <p>4.) If <i>that</i> fails, we'll try looping over all of the known windows to try to find the appropriate "title".
* Since "title" is not necessarily unique, this may have unexpected behavior.</p>
*
* <p>If you're having trouble figuring out what is the name of a window that you want to manipulate, look at the selenium log messages
* which identify the names of windows created via window.open (and therefore intercepted by selenium). You will see messages
* like the following for each window as it is opened:</p>
*
* <p><code>debug: window.open call intercepted; window ID (which you can use with selectWindow()) is "myNewWindow"</code></p>
*
* <p>In some cases, Selenium will be unable to intercept a call to window.open (if the call occurs during or before the "onLoad" event, for example).
* (This is bug SEL-339.) In those cases, you can force Selenium to notice the open window's name by using the Selenium openWindow command, using
* an empty (blank) url, like this: openWindow("", "myFunnyWindow").</p>
*
* @param windowID the JavaScript window ID of the window to select
*/
this.browserbot.selectWindow(windowID);
};
Selenium.prototype.doSelectFrame = function(locator) {
/**
* Selects a frame within the current window. (You may invoke this command
* multiple times to select nested frames.) To select the parent frame, use
* "relative=parent" as a locator; to select the top frame, use "relative=top".
* You can also select a frame by its 0-based index number; select the first frame with
* "index=0", or the third frame with "index=2".
*
* <p>You may also use a DOM expression to identify the frame you want directly,
* like this: <code>dom=frames["main"].frames["subframe"]</code></p>
*
* @param locator an <a href="#locators">element locator</a> identifying a frame or iframe
*/
this.browserbot.selectFrame(locator);
};
Selenium.prototype.getWhetherThisFrameMatchFrameExpression = function(currentFrameString, target) {
/**
* Determine whether current/locator identify the frame containing this running code.
*
* <p>This is useful in proxy injection mode, where this code runs in every
* browser frame and window, and sometimes the selenium server needs to identify
* the "current" frame. In this case, when the test calls selectFrame, this
* routine is called for each frame to figure out which one has been selected.
* The selected frame will return true, while all others will return false.</p>
*
* @param currentFrameString starting frame
* @param target new frame (which might be relative to the current one)
* @return boolean true if the new frame is this code's window
*/
return this.browserbot.doesThisFrameMatchFrameExpression(currentFrameString, target);
};
Selenium.prototype.getWhetherThisWindowMatchWindowExpression = function(currentWindowString, target) {
/**
* Determine whether currentWindowString plus target identify the window containing this running code.
*
* <p>This is useful in proxy injection mode, where this code runs in every
* browser frame and window, and sometimes the selenium server needs to identify
* the "current" window. In this case, when the test calls selectWindow, this
* routine is called for each window to figure out which one has been selected.
* The selected window will return true, while all others will return false.</p>
*
* @param currentWindowString starting window
* @param target new window (which might be relative to the current one, e.g., "_parent")
* @return boolean true if the new window is this code's window
*/
if (window.opener!=null && window.opener[target]!=null && window.opener[target]==window) {
return true;
}
return false;
};
Selenium.prototype.doWaitForPopUp = function(windowID, timeout) {
/**
* Waits for a popup window to appear and load up.
*
* @param windowID the JavaScript window ID of the window that will appear
* @param timeout a timeout in milliseconds, after which the action will return with an error
*/
var popupLoadedPredicate = function () {
var targetWindow = selenium.browserbot.getWindowByName(windowID, true);
if (!targetWindow) return false;
if (!targetWindow.location) return false;
if ("about:blank" == targetWindow.location) return false;
if (browserVersion.isKonqueror) {
if ("/" == targetWindow.location.href) {
// apparently Konqueror uses this as the temporary location, instead of about:blank
return false;
}
}
if (browserVersion.isSafari) {
if(targetWindow.location.href == selenium.browserbot.buttonWindow.location.href) {
// Apparently Safari uses this as the temporary location, instead of about:blank
// what a world!
LOG.debug("DGF what a world!");
return false;
}
}
if (!targetWindow.document) return false;
if (!selenium.browserbot.getCurrentWindow().document.readyState) {
// This is Firefox, with no readyState extension
return true;
}
if ('complete' != targetWindow.document.readyState) return false;
return true;
};
return Selenium.decorateFunctionWithTimeout(popupLoadedPredicate, timeout);
}
Selenium.prototype.doWaitForPopUp.dontCheckAlertsAndConfirms = true;
Selenium.prototype.doChooseCancelOnNextConfirmation = function() {
/**
* By default, Selenium's overridden window.confirm() function will
* return true, as if the user had manually clicked OK; after running
* this command, the next call to confirm() will return false, as if
* the user had clicked Cancel. Selenium will then resume using the
* default behavior for future confirmations, automatically returning
* true (OK) unless/until you explicitly call this command for each
* confirmation.
*
*/
this.browserbot.cancelNextConfirmation(false);
};
Selenium.prototype.doChooseOkOnNextConfirmation = function() {
/**
* Undo the effect of calling chooseCancelOnNextConfirmation. Note
* that Selenium's overridden window.confirm() function will normally automatically
* return true, as if the user had manually clicked OK, so you shouldn't
* need to use this command unless for some reason you need to change
* your mind prior to the next confirmation. After any confirmation, Selenium will resume using the
* default behavior for future confirmations, automatically returning
* true (OK) unless/until you explicitly call chooseCancelOnNextConfirmation for each
* confirmation.
*
*/
this.browserbot.cancelNextConfirmation(true);
};
Selenium.prototype.doAnswerOnNextPrompt = function(answer) {
/**
* Instructs Selenium to return the specified answer string in response to
* the next JavaScript prompt [window.prompt()].
*
*
* @param answer the answer to give in response to the prompt pop-up
*/
this.browserbot.setNextPromptResult(answer);
};
Selenium.prototype.doGoBack = function() {
/**
* Simulates the user clicking the "back" button on their browser.
*
*/
this.browserbot.goBack();
};
Selenium.prototype.doRefresh = function() {
/**
* Simulates the user clicking the "Refresh" button on their browser.
*
*/
this.browserbot.refresh();
};
Selenium.prototype.doClose = function() {
/**
* Simulates the user clicking the "close" button in the titlebar of a popup
* window or tab.
*/
this.browserbot.close();
};
Selenium.prototype.ensureNoUnhandledPopups = function() {
if (this.browserbot.hasAlerts()) {
throw new SeleniumError("There was an unexpected Alert! [" + this.browserbot.getNextAlert() + "]");
}
if ( this.browserbot.hasConfirmations() ) {
throw new SeleniumError("There was an unexpected Confirmation! [" + this.browserbot.getNextConfirmation() + "]");
}
};
Selenium.prototype.isAlertPresent = function() {
/**
* Has an alert occurred?
*
* <p>
* This function never throws an exception
* </p>
* @return boolean true if there is an alert
*/
return this.browserbot.hasAlerts();
};
Selenium.prototype.isPromptPresent = function() {
/**
* Has a prompt occurred?
*
* <p>
* This function never throws an exception
* </p>
* @return boolean true if there is a pending prompt
*/
return this.browserbot.hasPrompts();
};
Selenium.prototype.isConfirmationPresent = function() {
/**
* Has confirm() been called?
*
* <p>
* This function never throws an exception
* </p>
* @return boolean true if there is a pending confirmation
*/
return this.browserbot.hasConfirmations();
};
Selenium.prototype.getAlert = function() {
/**
* Retrieves the message of a JavaScript alert generated during the previous action, or fail if there were no alerts.
*
* <p>Getting an alert has the same effect as manually clicking OK. If an
* alert is generated but you do not get/verify it, the next Selenium action
* will fail.</p>
*
* <p>NOTE: under Selenium, JavaScript alerts will NOT pop up a visible alert
* dialog.</p>
*
* <p>NOTE: Selenium does NOT support JavaScript alerts that are generated in a
* page's onload() event handler. In this case a visible dialog WILL be
* generated and Selenium will hang until someone manually clicks OK.</p>
* @return string The message of the most recent JavaScript alert
*/
if (!this.browserbot.hasAlerts()) {
Assert.fail("There were no alerts");
}
return this.browserbot.getNextAlert();
};
Selenium.prototype.getAlert.dontCheckAlertsAndConfirms = true;
Selenium.prototype.getConfirmation = function() {
/**
* Retrieves the message of a JavaScript confirmation dialog generated during
* the previous action.
*
* <p>
* By default, the confirm function will return true, having the same effect
* as manually clicking OK. This can be changed by prior execution of the
* chooseCancelOnNextConfirmation command. If an confirmation is generated
* but you do not get/verify it, the next Selenium action will fail.
* </p>
*
* <p>
* NOTE: under Selenium, JavaScript confirmations will NOT pop up a visible
* dialog.
* </p>
*
* <p>
* NOTE: Selenium does NOT support JavaScript confirmations that are
* generated in a page's onload() event handler. In this case a visible
* dialog WILL be generated and Selenium will hang until you manually click
* OK.
* </p>
*
* @return string the message of the most recent JavaScript confirmation dialog
*/
if (!this.browserbot.hasConfirmations()) {
Assert.fail("There were no confirmations");
}
return this.browserbot.getNextConfirmation();
};
Selenium.prototype.getConfirmation.dontCheckAlertsAndConfirms = true;
Selenium.prototype.getPrompt = function() {
/**
* Retrieves the message of a JavaScript question prompt dialog generated during
* the previous action.
*
* <p>Successful handling of the prompt requires prior execution of the
* answerOnNextPrompt command. If a prompt is generated but you
* do not get/verify it, the next Selenium action will fail.</p>
*
* <p>NOTE: under Selenium, JavaScript prompts will NOT pop up a visible
* dialog.</p>
*
* <p>NOTE: Selenium does NOT support JavaScript prompts that are generated in a
* page's onload() event handler. In this case a visible dialog WILL be
* generated and Selenium will hang until someone manually clicks OK.</p>
* @return string the message of the most recent JavaScript question prompt
*/
if (! this.browserbot.hasPrompts()) {
Assert.fail("There were no prompts");
}
return this.browserbot.getNextPrompt();
};
Selenium.prototype.getLocation = function() {
/** Gets the absolute URL of the current page.
*
* @return string the absolute URL of the current page
*/
return this.browserbot.getCurrentWindow().location;
};
Selenium.prototype.getTitle = function() {
/** Gets the title of the current page.
*
* @return string the title of the current page
*/
return this.browserbot.getTitle();
};
Selenium.prototype.getBodyText = function() {
/**
* Gets the entire text of the page.
* @return string the entire text of the page
*/
return this.browserbot.bodyText();
};
Selenium.prototype.getValue = function(locator) {
/**
* Gets the (whitespace-trimmed) value of an input field (or anything else with a value parameter).
* For checkbox/radio elements, the value will be "on" or "off" depending on
* whether the element is checked or not.
*
* @param locator an <a href="#locators">element locator</a>
* @return string the element value, or "on/off" for checkbox/radio elements
*/
var element = this.browserbot.findElement(locator)
return getInputValue(element).trim();
}
Selenium.prototype.getText = function(locator) {
/**
* Gets the text of an element. This works for any element that contains
* text. This command uses either the textContent (Mozilla-like browsers) or
* the innerText (IE-like browsers) of the element, which is the rendered
* text shown to the user.
*
* @param locator an <a href="#locators">element locator</a>
* @return string the text of the element
*/
var element = this.browserbot.findElement(locator);
return getText(element).trim();
};
Selenium.prototype.doHighlight = function(locator) {
/**
* Briefly changes the backgroundColor of the specified element yellow. Useful for debugging.
*
* @param locator an <a href="#locators">element locator</a>
*/
var element = this.browserbot.findElement(locator);
this.browserbot.highlight(element, true);
};
Selenium.prototype.getEval = function(script) {
/** Gets the result of evaluating the specified JavaScript snippet. The snippet may
* have multiple lines, but only the result of the last line will be returned.
*
* <p>Note that, by default, the snippet will run in the context of the "selenium"
* object itself, so <code>this</code> will refer to the Selenium object. Use <code>window</code> to
* refer to the window of your application, e.g. <code>window.document.getElementById('foo')</code></p>
*
* <p>If you need to use
* a locator to refer to a single element in your application page, you can
* use <code>this.browserbot.findElement("id=foo")</code> where "id=foo" is your locator.</p>
*
* @param script the JavaScript snippet to run
* @return string the results of evaluating the snippet
*/
try {
var window = this.browserbot.getCurrentWindow();
var result = eval(script);
// Selenium RC doesn't allow returning null
if (null == result) return "null";
return result;
} catch (e) {
throw new SeleniumError("Threw an exception: " + e.message);
}
};
Selenium.prototype.isChecked = function(locator) {
/**
* Gets whether a toggle-button (checkbox/radio) is checked. Fails if the specified element doesn't exist or isn't a toggle-button.
* @param locator an <a href="#locators">element locator</a> pointing to a checkbox or radio button
* @return boolean true if the checkbox is checked, false otherwise
*/
var element = this.browserbot.findElement(locator);
if (element.checked == null) {
throw new SeleniumError("Element " + locator + " is not a toggle-button.");
}
return element.checked;
};
Selenium.prototype.getTable = function(tableCellAddress) {
/**
* Gets the text from a cell of a table. The cellAddress syntax
* tableLocator.row.column, where row and column start at 0.
*
* @param tableCellAddress a cell address, e.g. "foo.1.4"
* @return string the text from the specified cell
*/
// This regular expression matches "tableName.row.column"
// For example, "mytable.3.4"
pattern = /(.*)\.(\d+)\.(\d+)/;
if(!pattern.test(tableCellAddress)) {
throw new SeleniumError("Invalid target format. Correct format is tableName.rowNum.columnNum");
}
pieces = tableCellAddress.match(pattern);
tableName = pieces[1];
row = pieces[2];
col = pieces[3];
var table = this.browserbot.findElement(tableName);
if (row > table.rows.length) {
Assert.fail("Cannot access row " + row + " - table has " + table.rows.length + " rows");
}
else if (col > table.rows[row].cells.length) {
Assert.fail("Cannot access column " + col + " - table row has " + table.rows[row].cells.length + " columns");
}
else {
actualContent = getText(table.rows[row].cells[col]);
return actualContent.trim();
}
return null;
};
Selenium.prototype.getSelectedLabels = function(selectLocator) {
/** Gets all option labels (visible text) for selected options in the specified select or multi-select element.
*
* @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
* @return string[] an array of all selected option labels in the specified select drop-down
*/
return this.findSelectedOptionProperties(selectLocator, "text");
}
Selenium.prototype.getSelectedLabel = function(selectLocator) {
/** Gets option label (visible text) for selected option in the specified select element.
*
* @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
* @return string the selected option label in the specified select drop-down
*/
return this.findSelectedOptionProperty(selectLocator, "text");
}
Selenium.prototype.getSelectedValues = function(selectLocator) {
/** Gets all option values (value attributes) for selected options in the specified select or multi-select element.
*
* @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
* @return string[] an array of all selected option values in the specified select drop-down
*/
return this.findSelectedOptionProperties(selectLocator, "value");
}
Selenium.prototype.getSelectedValue = function(selectLocator) {
/** Gets option value (value attribute) for selected option in the specified select element.
*
* @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
* @return string the selected option value in the specified select drop-down
*/
return this.findSelectedOptionProperty(selectLocator, "value");
}
Selenium.prototype.getSelectedIndexes = function(selectLocator) {
/** Gets all option indexes (option number, starting at 0) for selected options in the specified select or multi-select element.
*
* @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
* @return string[] an array of all selected option indexes in the specified select drop-down
*/
return this.findSelectedOptionProperties(selectLocator, "index");
}
Selenium.prototype.getSelectedIndex = function(selectLocator) {
/** Gets option index (option number, starting at 0) for selected option in the specified select element.
*
* @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
* @return string the selected option index in the specified select drop-down
*/
return this.findSelectedOptionProperty(selectLocator, "index");
}
Selenium.prototype.getSelectedIds = function(selectLocator) {
/** Gets all option element IDs for selected options in the specified select or multi-select element.
*
* @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
* @return string[] an array of all selected option IDs in the specified select drop-down
*/
return this.findSelectedOptionProperties(selectLocator, "id");
}
Selenium.prototype.getSelectedId = function(selectLocator) {
/** Gets option element ID for selected option in the specified select element.
*
* @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
* @return string the selected option ID in the specified select drop-down
*/
return this.findSelectedOptionProperty(selectLocator, "id");
}
Selenium.prototype.isSomethingSelected = function(selectLocator) {
/** Determines whether some option in a drop-down menu is selected.
*
* @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
* @return boolean true if some option has been selected, false otherwise
*/
var element = this.browserbot.findElement(selectLocator);
if (!("options" in element)) {
throw new SeleniumError("Specified element is not a Select (has no options)");
}
var selectedOptions = [];
for (var i = 0; i < element.options.length; i++) {
if (element.options[i].selected)
{
return true;
}
}
return false;
}
Selenium.prototype.findSelectedOptionProperties = function(locator, property) {
var element = this.browserbot.findElement(locator);
if (!("options" in element)) {
throw new SeleniumError("Specified element is not a Select (has no options)");
}
var selectedOptions = [];
for (var i = 0; i < element.options.length; i++) {
if (element.options[i].selected)
{
var propVal = element.options[i][property];
selectedOptions.push(propVal);
}
}
if (selectedOptions.length == 0) Assert.fail("No option selected");
return selectedOptions;
}
Selenium.prototype.findSelectedOptionProperty = function(locator, property) {
var selectedOptions = this.findSelectedOptionProperties(locator, property);
if (selectedOptions.length > 1) {
Assert.fail("More than one selected option!");
}
return selectedOptions[0];
}
Selenium.prototype.getSelectOptions = function(selectLocator) {
/** Gets all option labels in the specified select drop-down.
*
* @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
* @return string[] an array of all option labels in the specified select drop-down
*/
var element = this.browserbot.findElement(selectLocator);
var selectOptions = [];
for (var i = 0; i < element.options.length; i++) {
var option = element.options[i].text;
selectOptions.push(option);
}
return selectOptions;
};
Selenium.prototype.getAttribute = function(attributeLocator) {
/**
* Gets the value of an element attribute.
*
* @param attributeLocator an element locator followed by an @ sign and then the name of the attribute, e.g. "foo@bar"
* @return string the value of the specified attribute
*/
var result = this.browserbot.findAttribute(attributeLocator);
if (result == null) {
throw new SeleniumError("Could not find element attribute: " + attributeLocator);
}
return result;
};
Selenium.prototype.isTextPresent = function(pattern) {
/**
* Verifies that the specified text pattern appears somewhere on the rendered page shown to the user.
* @param pattern a <a href="#patterns">pattern</a> to match with the text of the page
* @return boolean true if the pattern matches the text, false otherwise
*/
var allText = this.browserbot.bodyText();
var patternMatcher = new PatternMatcher(pattern);
if (patternMatcher.strategy == PatternMatcher.strategies.glob) {
if (pattern.indexOf("glob:")==0) {
pattern = pattern.substring("glob:".length); // strip off "glob:"
}
patternMatcher.matcher = new PatternMatcher.strategies.globContains(pattern);
}
else if (patternMatcher.strategy == PatternMatcher.strategies.exact) {
pattern = pattern.substring("exact:".length); // strip off "exact:"
return allText.indexOf(pattern) != -1;
}
return patternMatcher.matches(allText);
};
Selenium.prototype.isElementPresent = function(locator) {
/**
* Verifies that the specified element is somewhere on the page.
* @param locator an <a href="#locators">element locator</a>
* @return boolean true if the element is present, false otherwise
*/
var element = this.browserbot.findElementOrNull(locator);
if (element == null) {
return false;
}
return true;
};
Selenium.prototype.isVisible = function(locator) {
/**
* Determines if the specified element is visible. An
* element can be rendered invisible by setting the CSS "visibility"
* property to "hidden", or the "display" property to "none", either for the
* element itself or one if its ancestors. This method will fail if
* the element is not present.
*
* @param locator an <a href="#locators">element locator</a>
* @return boolean true if the specified element is visible, false otherwise
*/
var element;
element = this.browserbot.findElement(locator);
var visibility = this.findEffectiveStyleProperty(element, "visibility");
var _isDisplayed = this._isDisplayed(element);
return (visibility != "hidden" && _isDisplayed);
};
Selenium.prototype.findEffectiveStyleProperty = function(element, property) {
var effectiveStyle = this.findEffectiveStyle(element);
var propertyValue = effectiveStyle[property];
if (propertyValue == 'inherit' && element.parentNode.style) {
return this.findEffectiveStyleProperty(element.parentNode, property);
}
return propertyValue;
};
Selenium.prototype._isDisplayed = function(element) {
var display = this.findEffectiveStyleProperty(element, "display");
if (display == "none") return false;
if (element.parentNode.style) {
return this._isDisplayed(element.parentNode);
}
return true;
};
Selenium.prototype.findEffectiveStyle = function(element) {
if (element.style == undefined) {
return undefined; // not a styled element
}
if (window.getComputedStyle) {
// DOM-Level-2-CSS
return this.browserbot.getCurrentWindow().getComputedStyle(element, null);
}
if (element.currentStyle) {
// non-standard IE alternative
return element.currentStyle;
// TODO: this won't really work in a general sense, as
// currentStyle is not identical to getComputedStyle()
// ... but it's good enough for "visibility"
}
throw new SeleniumError("cannot determine effective stylesheet in this browser");
};
Selenium.prototype.isEditable = function(locator) {
/**
* Determines whether the specified input element is editable, ie hasn't been disabled.
* This method will fail if the specified element isn't an input element.
*
* @param locator an <a href="#locators">element locator</a>
* @return boolean true if the input element is editable, false otherwise
*/
var element = this.browserbot.findElement(locator);
if (element.value == undefined) {
Assert.fail("Element " + locator + " is not an input.");
}
return !element.disabled;
};
Selenium.prototype.getAllButtons = function() {
/** Returns the IDs of all buttons on the page.
*
* <p>If a given button has no ID, it will appear as "" in this array.</p>
*
* @return string[] the IDs of all buttons on the page
*/
return this.browserbot.getAllButtons();
};
Selenium.prototype.getAllLinks = function() {
/** Returns the IDs of all links on the page.
*
* <p>If a given link has no ID, it will appear as "" in this array.</p>
*
* @return string[] the IDs of all links on the page
*/
return this.browserbot.getAllLinks();
};
Selenium.prototype.getAllFields = function() {
/** Returns the IDs of all input fields on the page.
*
* <p>If a given field has no ID, it will appear as "" in this array.</p>
*
* @return string[] the IDs of all field on the page
*/
return this.browserbot.getAllFields();
};
Selenium.prototype.getAttributeFromAllWindows = function(attributeName) {
/** Returns every instance of some attribute from all known windows.
*
* @param attributeName name of an attribute on the windows
* @return string[] the set of values of this attribute from all known windows.
*/
var attributes = new Array();
var win = selenium.browserbot.topWindow;
// DGF normally you should use []s instead of eval "win."+attributeName
// but in this case, attributeName may contain dots (e.g. document.title)
// in that case, we have no choice but to use eval...
attributes.push(eval("win."+attributeName));
for (var windowName in this.browserbot.openedWindows)
{
try {
win = selenium.browserbot.openedWindows[windowName];
attributes.push(eval("win."+attributeName));
} catch (e) {} // DGF If we miss one... meh. It's probably closed or inaccessible anyway.
}
return attributes;
};
Selenium.prototype.findWindow = function(soughtAfterWindowPropertyValue) {
var targetPropertyName = "name";
if (soughtAfterWindowPropertyValue.match("^title=")) {
targetPropertyName = "document.title";
soughtAfterWindowPropertyValue = soughtAfterWindowPropertyValue.replace(/^title=/, "");
}
else {
// matching "name":
// If we are not in proxy injection mode, then the top-level test window will be named selenium_myiframe.
// But as far as the interface goes, we are expected to match a blank string to this window, if
// we are searching with respect to the widow name.
// So make a special case so that this logic will work:
if (PatternMatcher.matches(soughtAfterWindowPropertyValue, "")) {
return this.browserbot.getCurrentWindow();
}
}
// DGF normally you should use []s instead of eval "win."+attributeName
// but in this case, attributeName may contain dots (e.g. document.title)
// in that case, we have no choice but to use eval...
if (PatternMatcher.matches(soughtAfterWindowPropertyValue, eval("this.browserbot.topWindow." + targetPropertyName))) {
return this.browserbot.topWindow;
}
for (windowName in selenium.browserbot.openedWindows) {
var openedWindow = selenium.browserbot.openedWindows[windowName];
if (PatternMatcher.matches(soughtAfterWindowPropertyValue, eval("openedWindow." + targetPropertyName))) {
return openedWindow;
}
}
throw new SeleniumError("could not find window with property " + targetPropertyName + " matching " + soughtAfterWindowPropertyValue);
};
Selenium.prototype.doDragdrop = function(locator, movementsString) {
/** deprecated - use dragAndDrop instead
*
* @param locator an element locator
* @param movementsString offset in pixels from the current location to which the element should be moved, e.g., "+70,-300"
*/
this.doDragAndDrop(locator, movementsString);
};
Selenium.prototype.doSetMouseSpeed = function(pixels) {
/** Configure the number of pixels between "mousemove" events during dragAndDrop commands (default=10).
* <p>Setting this value to 0 means that we'll send a "mousemove" event to every single pixel
* in between the start location and the end location; that can be very slow, and may
* cause some browsers to force the JavaScript to timeout.</p>
*
* <p>If the mouse speed is greater than the distance between the two dragged objects, we'll
* just send one "mousemove" at the start location and then one final one at the end location.</p>
* @param pixels the number of pixels between "mousemove" events
*/
this.mouseSpeed = pixels;
}
Selenium.prototype.getMouseSpeed = function() {
/** Returns the number of pixels between "mousemove" events during dragAndDrop commands (default=10).
*
* @return number the number of pixels between "mousemove" events during dragAndDrop commands (default=10)
*/
this.mouseSpeed = pixels;
}
Selenium.prototype.doDragAndDrop = function(locator, movementsString) {
/** Drags an element a certain distance and then drops it
* @param locator an element locator
* @param movementsString offset in pixels from the current location to which the element should be moved, e.g., "+70,-300"
*/
var element = this.browserbot.findElement(locator);
var clientStartXY = getClientXY(element)
var clientStartX = clientStartXY[0];
var clientStartY = clientStartXY[1];
var movements = movementsString.split(/,/);
var movementX = Number(movements[0]);
var movementY = Number(movements[1]);
var clientFinishX = ((clientStartX + movementX) < 0) ? 0 : (clientStartX + movementX);
var clientFinishY = ((clientStartY + movementY) < 0) ? 0 : (clientStartY + movementY);
var mouseSpeed = this.mouseSpeed;
var move = function(current, dest) {
if (current == dest) return current;
if (Math.abs(current - dest) < mouseSpeed) return dest;
return (current < dest) ? current + mouseSpeed : current - mouseSpeed;
}
this.browserbot.triggerMouseEvent(element, 'mousedown', true, clientStartX, clientStartY);
this.browserbot.triggerMouseEvent(element, 'mousemove', true, clientStartX, clientStartY);
var clientX = clientStartX;
var clientY = clientStartY;
while ((clientX != clientFinishX) || (clientY != clientFinishY)) {
clientX = move(clientX, clientFinishX);
clientY = move(clientY, clientFinishY);
this.browserbot.triggerMouseEvent(element, 'mousemove', true, clientX, clientY);
}
this.browserbot.triggerMouseEvent(element, 'mousemove', true, clientFinishX, clientFinishY);
this.browserbot.triggerMouseEvent(element, 'mouseup', true, clientFinishX, clientFinishY);
};
Selenium.prototype.doDragAndDropToObject = function(locatorOfObjectToBeDragged, locatorOfDragDestinationObject) {
/** Drags an element and drops it on another element
*
* @param locatorOfObjectToBeDragged an element to be dragged
* @param locatorOfDragDestinationObject an element whose location (i.e., whose center-most pixel) will be the point where locatorOfObjectToBeDragged is dropped
*/
var startX = this.getElementPositionLeft(locatorOfObjectToBeDragged);
var startY = this.getElementPositionTop(locatorOfObjectToBeDragged);
var destinationLeftX = this.getElementPositionLeft(locatorOfDragDestinationObject);
var destinationTopY = this.getElementPositionTop(locatorOfDragDestinationObject);
var destinationWidth = this.getElementWidth(locatorOfDragDestinationObject);
var destinationHeight = this.getElementHeight(locatorOfDragDestinationObject);
var endX = Math.round(destinationLeftX + (destinationWidth / 2));
var endY = Math.round(destinationTopY + (destinationHeight / 2));
var deltaX = endX - startX;
var deltaY = endY - startY;
var movementsString = "" + deltaX + "," + deltaY;
this.doDragAndDrop(locatorOfObjectToBeDragged, movementsString);
};
Selenium.prototype.doWindowFocus = function() {
/** Gives focus to the currently selected window
*
*/
this.browserbot.getCurrentWindow().focus();
};
Selenium.prototype.doWindowMaximize = function() {
/** Resize currently selected window to take up the entire screen
*
*/
var window = this.browserbot.getCurrentWindow();
if (window!=null && window.screen) {
window.moveTo(0,0);
window.resizeTo(screen.availWidth, screen.availHeight);
}
};
Selenium.prototype.getAllWindowIds = function() {
/** Returns the IDs of all windows that the browser knows about.
*
* @return string[] the IDs of all windows that the browser knows about.
*/
return this.getAttributeFromAllWindows("id");
};
Selenium.prototype.getAllWindowNames = function() {
/** Returns the names of all windows that the browser knows about.
*
* @return string[] the names of all windows that the browser knows about.
*/
return this.getAttributeFromAllWindows("name");
};
Selenium.prototype.getAllWindowTitles = function() {
/** Returns the titles of all windows that the browser knows about.
*
* @return string[] the titles of all windows that the browser knows about.
*/
return this.getAttributeFromAllWindows("document.title");
};
Selenium.prototype.getHtmlSource = function() {
/** Returns the entire HTML source between the opening and
* closing "html" tags.
*
* @return string the entire HTML source
*/
return this.browserbot.getDocument().getElementsByTagName("html")[0].innerHTML;
};
Selenium.prototype.doSetCursorPosition = function(locator, position) {
/**
* Moves the text cursor to the specified position in the given input element or textarea.
* This method will fail if the specified element isn't an input element or textarea.
*
* @param locator an <a href="#locators">element locator</a> pointing to an input element or textarea
* @param position the numerical position of the cursor in the field; position should be 0 to move the position to the beginning of the field. You can also set the cursor to -1 to move it to the end of the field.
*/
var element = this.browserbot.findElement(locator);
if (element.value == undefined) {
Assert.fail("Element " + locator + " is not an input.");
}
if (position == -1) {
position = element.value.length;
}
if( element.setSelectionRange && !browserVersion.isOpera) {
element.focus();
element.setSelectionRange(/*start*/position,/*end*/position);
}
else if( element.createTextRange ) {
triggerEvent(element, 'focus', false);
var range = element.createTextRange();
range.collapse(true);
range.moveEnd('character',position);
range.moveStart('character',position);
range.select();
}
}
Selenium.prototype.getElementIndex = function(locator) {
/**
* Get the relative index of an element to its parent (starting from 0). The comment node and empty text node
* will be ignored.
*
* @param locator an <a href="#locators">element locator</a> pointing to an element
* @return number of relative index of the element to its parent (starting from 0)
*/
var element = this.browserbot.findElement(locator);
var previousSibling;
var index = 0;
while ((previousSibling = element.previousSibling) != null) {
if (!this._isCommentOrEmptyTextNode(previousSibling)) {
index++;
}
element = previousSibling;
}
return index;
}
Selenium.prototype.isOrdered = function(locator1, locator2) {
/**
* Check if these two elements have same parent and are ordered siblings in the DOM. Two same elements will
* not be considered ordered.
*
* @param locator1 an <a href="#locators">element locator</a> pointing to the first element
* @param locator2 an <a href="#locators">element locator</a> pointing to the second element
* @return boolean true if element1 is the previous sibling of element2, false otherwise
*/
var element1 = this.browserbot.findElement(locator1);
var element2 = this.browserbot.findElement(locator2);
if (element1 === element2) return false;
var previousSibling;
while ((previousSibling = element2.previousSibling) != null) {
if (previousSibling === element1) {
return true;
}
element2 = previousSibling;
}
return false;
}
Selenium.prototype._isCommentOrEmptyTextNode = function(node) {
return node.nodeType == 8 || ((node.nodeType == 3) && !(/[^\t\n\r ]/.test(node.data)));
}
Selenium.prototype.getElementPositionLeft = function(locator) {
/**
* Retrieves the horizontal position of an element
*
* @param locator an <a href="#locators">element locator</a> pointing to an element OR an element itself
* @return number of pixels from the edge of the frame.
*/
var element;
if ("string"==typeof locator) {
element = this.browserbot.findElement(locator);
}
else {
element = locator;
}
var x = element.offsetLeft;
var elementParent = element.offsetParent;
while (elementParent != null)
{
if(document.all)
{
if( (elementParent.tagName != "TABLE") && (elementParent.tagName != "BODY") )
{
x += elementParent.clientLeft;
}
}
else // Netscape/DOM
{
if(elementParent.tagName == "TABLE")
{
var parentBorder = parseInt(elementParent.border);
if(isNaN(parentBorder))
{
var parentFrame = elementParent.getAttribute('frame');
if(parentFrame != null)
{
x += 1;
}
}
else if(parentBorder > 0)
{
x += parentBorder;
}
}
}
x += elementParent.offsetLeft;
elementParent = elementParent.offsetParent;
}
return x;
};
Selenium.prototype.getElementPositionTop = function(locator) {
/**
* Retrieves the vertical position of an element
*
* @param locator an <a href="#locators">element locator</a> pointing to an element OR an element itself
* @return number of pixels from the edge of the frame.
*/
var element;
if ("string"==typeof locator) {
element = this.browserbot.findElement(locator);
}
else {
element = locator;
}
var y = 0;
while (element != null)
{
if(document.all)
{
if( (element.tagName != "TABLE") && (element.tagName != "BODY") )
{
y += element.clientTop;
}
}
else // Netscape/DOM
{
if(element.tagName == "TABLE")
{
var parentBorder = parseInt(element.border);
if(isNaN(parentBorder))
{
var parentFrame = element.getAttribute('frame');
if(parentFrame != null)
{
y += 1;
}
}
else if(parentBorder > 0)
{
y += parentBorder;
}
}
}
y += element.offsetTop;
// Netscape can get confused in some cases, such that the height of the parent is smaller
// than that of the element (which it shouldn't really be). If this is the case, we need to
// exclude this element, since it will result in too large a 'top' return value.
if (element.offsetParent && element.offsetParent.offsetHeight && element.offsetParent.offsetHeight < element.offsetHeight)
{
// skip the parent that's too small
element = element.offsetParent.offsetParent;
}
else
{
// Next up...
element = element.offsetParent;
}
}
return y;
};
Selenium.prototype.getElementWidth = function(locator) {
/**
* Retrieves the width of an element
*
* @param locator an <a href="#locators">element locator</a> pointing to an element
* @return number width of an element in pixels
*/
var element = this.browserbot.findElement(locator);
return element.offsetWidth;
};
Selenium.prototype.getElementHeight = function(locator) {
/**
* Retrieves the height of an element
*
* @param locator an <a href="#locators">element locator</a> pointing to an element
* @return number height of an element in pixels
*/
var element = this.browserbot.findElement(locator);
return element.offsetHeight;
};
Selenium.prototype.getCursorPosition = function(locator) {
/**
* Retrieves the text cursor position in the given input element or textarea; beware, this may not work perfectly on all browsers.
*
* <p>Specifically, if the cursor/selection has been cleared by JavaScript, this command will tend to
* return the position of the last location of the cursor, even though the cursor is now gone from the page. This is filed as <a href="http://jira.openqa.org/browse/SEL-243">SEL-243</a>.</p>
* This method will fail if the specified element isn't an input element or textarea, or there is no cursor in the element.
*
* @param locator an <a href="#locators">element locator</a> pointing to an input element or textarea
* @return number the numerical position of the cursor in the field
*/
var element = this.browserbot.findElement(locator);
var doc = this.browserbot.getDocument();
var win = this.browserbot.getCurrentWindow();
if( doc.selection && !browserVersion.isOpera){
try {
var selectRange = doc.selection.createRange().duplicate();
var elementRange = element.createTextRange();
selectRange.move("character",0);
elementRange.move("character",0);
var inRange1 = selectRange.inRange(elementRange);
var inRange2 = elementRange.inRange(selectRange);
elementRange.setEndPoint("EndToEnd", selectRange);
} catch (e) {
Assert.fail("There is no cursor on this page!");
}
var answer = String(elementRange.text).replace(/\r/g,"").length;
return answer;
} else {
if (typeof(element.selectionStart) != "undefined") {
if (win.getSelection && typeof(win.getSelection().rangeCount) != undefined && win.getSelection().rangeCount == 0) {
Assert.fail("There is no cursor on this page!");
}
return element.selectionStart;
}
}
throw new Error("Couldn't detect cursor position on this browser!");
}
Selenium.prototype.getExpression = function(expression) {
/**
* Returns the specified expression.
*
* <p>This is useful because of JavaScript preprocessing.
* It is used to generate commands like assertExpression and waitForExpression.</p>
*
* @param expression the value to return
* @return string the value passed in
*/
return expression;
}
Selenium.prototype.getXpathCount = function(xpath) {
/**
* Returns the number of nodes that match the specified xpath, eg. "//table" would give
* the number of tables.
*
* @param xpath the xpath expression to evaluate. do NOT wrap this expression in a 'count()' function; we will do that for you.
* @return number the number of nodes that match the specified xpath
*/
var result = this.browserbot.evaluateXPathCount(xpath, this.browserbot.getDocument());
return result;
}
Selenium.prototype.doAssignId = function(locator, identifier) {
/**
* Temporarily sets the "id" attribute of the specified element, so you can locate it in the future
* using its ID rather than a slow/complicated XPath. This ID will disappear once the page is
* reloaded.
* @param locator an <a href="#locators">element locator</a> pointing to an element
* @param identifier a string to be used as the ID of the specified element
*/
var element = this.browserbot.findElement(locator);
element.id = identifier;
}
Selenium.prototype.doAllowNativeXpath = function(allow) {
/**
* Specifies whether Selenium should use the native in-browser implementation
* of XPath (if any native version is available); if you pass "false" to
* this function, we will always use our pure-JavaScript xpath library.
* Using the pure-JS xpath library can improve the consistency of xpath
* element locators between different browser vendors, but the pure-JS
* version is much slower than the native implementations.
* @param allow boolean, true means we'll prefer to use native XPath; false means we'll only use JS XPath
*/
if ("false" == allow || "0" == allow) { // The strings "false" and "0" are true values in JS
allow = false;
}
this.browserbot.allowNativeXpath = allow;
}
Selenium.prototype.doWaitForCondition = function(script, timeout) {
/**
* Runs the specified JavaScript snippet repeatedly until it evaluates to "true".
* The snippet may have multiple lines, but only the result of the last line
* will be considered.
*
* <p>Note that, by default, the snippet will be run in the runner's test window, not in the window
* of your application. To get the window of your application, you can use
* the JavaScript snippet <code>selenium.browserbot.getCurrentWindow()</code>, and then
* run your JavaScript in there</p>
* @param script the JavaScript snippet to run
* @param timeout a timeout in milliseconds, after which this command will return with an error
*/
return Selenium.decorateFunctionWithTimeout(function () {
var window = selenium.browserbot.getCurrentWindow();
return eval(script);
}, timeout);
};
Selenium.prototype.doWaitForCondition.dontCheckAlertsAndConfirms = true;
Selenium.prototype.doSetTimeout = function(timeout) {
/**
* Specifies the amount of time that Selenium will wait for actions to complete.
*
* <p>Actions that require waiting include "open" and the "waitFor*" actions.</p>
* The default timeout is 30 seconds.
* @param timeout a timeout in milliseconds, after which the action will return with an error
*/
if (!timeout) {
timeout = Selenium.DEFAULT_TIMEOUT;
}
this.defaultTimeout = timeout;
}
Selenium.prototype.doWaitForPageToLoad = function(timeout) {
/**
* Waits for a new page to load.
*
* <p>You can use this command instead of the "AndWait" suffixes, "clickAndWait", "selectAndWait", "typeAndWait" etc.
* (which are only available in the JS API).</p>
*
* <p>Selenium constantly keeps track of new pages loading, and sets a "newPageLoaded"
* flag when it first notices a page load. Running any other Selenium command after
* turns the flag to false. Hence, if you want to wait for a page to load, you must
* wait immediately after a Selenium command that caused a page-load.</p>
* @param timeout a timeout in milliseconds, after which this command will return with an error
*/
// in pi-mode, the test and the harness share the window; thus if we are executing this code, then we have loaded
if (window["proxyInjectionMode"] == null || !window["proxyInjectionMode"]) {
return this.makePageLoadCondition(timeout);
}
};
Selenium.prototype.doWaitForFrameToLoad = function(frameAddress, timeout) {
/**
* Waits for a new frame to load.
*
* <p>Selenium constantly keeps track of new pages and frames loading,
* and sets a "newPageLoaded" flag when it first notices a page load.</p>
*
* See waitForPageToLoad for more information.
*
* @param frameAddress FrameAddress from the server side
* @param timeout a timeout in milliseconds, after which this command will return with an error
*/
// in pi-mode, the test and the harness share the window; thus if we are executing this code, then we have loaded
if (window["proxyInjectionMode"] == null || !window["proxyInjectionMode"]) {
return this.makePageLoadCondition(timeout);
}
};
Selenium.prototype._isNewPageLoaded = function() {
return this.browserbot.isNewPageLoaded();
};
Selenium.prototype.doWaitForPageToLoad.dontCheckAlertsAndConfirms = true;
/**
* Evaluate a parameter, performing JavaScript evaluation and variable substitution.
* If the string matches the pattern "javascript{ ... }", evaluate the string between the braces.
*/
Selenium.prototype.preprocessParameter = function(value) {
var match = value.match(/^javascript\{((.|\r?\n)+)\}$/);
if (match && match[1]) {
return eval(match[1]).toString();
}
return this.replaceVariables(value);
};
/*
* Search through str and replace all variable references ${varName} with their
* value in storedVars.
*/
Selenium.prototype.replaceVariables = function(str) {
var stringResult = str;
// Find all of the matching variable references
var match = stringResult.match(/\$\{\w+\}/g);
if (!match) {
return stringResult;
}
// For each match, lookup the variable value, and replace if found
for (var i = 0; match && i < match.length; i++) {
var variable = match[i]; // The replacement variable, with ${}
var name = variable.substring(2, variable.length - 1); // The replacement variable without ${}
var replacement = storedVars[name];
if (replacement != undefined) {
stringResult = stringResult.replace(variable, replacement);
}
}
return stringResult;
};
Selenium.prototype.getCookie = function() {
/**
* Return all cookies of the current page under test.
*
* @return string all cookies of the current page under test
*/
var doc = this.browserbot.getDocument();
return doc.cookie;
};
Selenium.prototype.doCreateCookie = function(nameValuePair, optionsString) {
/**
* Create a new cookie whose path and domain are same with those of current page
* under test, unless you specified a path for this cookie explicitly.
*
* @param nameValuePair name and value of the cookie in a format "name=value"
* @param optionsString options for the cookie. Currently supported options include 'path' and 'max_age'.
* the optionsString's format is "path=/path/, max_age=60". The order of options are irrelevant, the unit
* of the value of 'max_age' is second.
*/
var results = /[^\s=\[\]\(\),"\/\?@:;]+=[^\s=\[\]\(\),"\/\?@:;]*/.test(nameValuePair);
if (!results) {
throw new SeleniumError("Invalid parameter.");
}
var cookie = nameValuePair.trim();
results = /max_age=(\d+)/.exec(optionsString);
if (results) {
var expireDateInMilliseconds = (new Date()).getTime() + results[1] * 1000;
cookie += "; expires=" + new Date(expireDateInMilliseconds).toGMTString();
}
results = /path=([^\s,]+)[,]?/.exec(optionsString);
if (results) {
var path = results[1];
if (browserVersion.khtml) {
// Safari and conquerer don't like paths with / at the end
if ("/" != path) {
path = path.replace(/\/$/, "");
}
}
cookie += "; path=" + path;
}
LOG.debug("Setting cookie to: " + cookie);
this.browserbot.getDocument().cookie = cookie;
}
Selenium.prototype.doDeleteCookie = function(name,path) {
/**
* Delete a named cookie with specified path.
*
* @param name the name of the cookie to be deleted
* @param path the path property of the cookie to be deleted
*/
// set the expire time of the cookie to be deleted to one minute before now.
path = path.trim();
if (browserVersion.khtml) {
// Safari and conquerer don't like paths with / at the end
if ("/" != path) {
path = path.replace(/\/$/, "");
}
}
var expireDateInMilliseconds = (new Date()).getTime() + (-1 * 1000);
var cookie = name.trim() + "=deleted; path=" + path + "; expires=" + new Date(expireDateInMilliseconds).toGMTString();
LOG.debug("Setting cookie to: " + cookie);
this.browserbot.getDocument().cookie = cookie;
}
Selenium.prototype.doSetBrowserLogLevel = function(logLevel) {
/**
* Sets the threshold for browser-side logging messages; log messages beneath this threshold will be discarded.
* Valid logLevel strings are: "debug", "info", "warn", "error" or "off".
* To see the browser logs, you need to
* either show the log window in GUI mode, or enable browser-side logging in Selenium RC.
*
* @param logLevel one of the following: "debug", "info", "warn", "error" or "off"
*/
if (logLevel == null || logLevel == "") {
throw new SeleniumError("You must specify a log level");
}
logLevel = logLevel.toLowerCase();
if (LOG.logLevels[logLevel] == null) {
throw new SeleniumError("Invalid log level: " + logLevel);
}
LOG.setLogLevelThreshold(logLevel);
}
Selenium.prototype.doRunScript = function(script) {
/**
* Creates a new "script" tag in the body of the current test window, and
* adds the specified text into the body of the command. Scripts run in
* this way can often be debugged more easily than scripts executed using
* Selenium's "getEval" command. Beware that JS exceptions thrown in these script
* tags aren't managed by Selenium, so you should probably wrap your script
* in try/catch blocks if there is any chance that the script will throw
* an exception.
* @param script the JavaScript snippet to run
*/
var win = this.browserbot.getCurrentWindow();
var doc = win.document;
var scriptTag = doc.createElement("script");
scriptTag.type = "text/javascript"
scriptTag.text = script;
doc.body.appendChild(scriptTag);
}
Selenium.prototype.doAddLocationStrategy = function(strategyName, functionDefinition) {
/**
* Defines a new function for Selenium to locate elements on the page.
* For example,
* if you define the strategy "foo", and someone runs click("foo=blah"), we'll
* run your function, passing you the string "blah", and click on the element
* that your function
* returns, or throw an "Element not found" error if your function returns null.
*
* We'll pass three arguments to your function:
* <ul>
* <li>locator: the string the user passed in</li>
* <li>inWindow: the currently selected window</li>
* <li>inDocument: the currently selected document</li>
* </ul>
* The function must return null if the element can't be found.
*
* @param strategyName the name of the strategy to define; this should use only
* letters [a-zA-Z] with no spaces or other punctuation.
* @param functionDefinition a string defining the body of a function in JavaScript.
* For example: <code>return inDocument.getElementById(locator);</code>
*/
if (!/^[a-zA-Z]+$/.test(strategyName)) {
throw new SeleniumError("Invalid strategy name: " + strategyName);
}
var strategyFunction;
try {
strategyFunction = new Function("locator", "inDocument", "inWindow", functionDefinition);
} catch (ex) {
throw new SeleniumError("Error evaluating function definition: " + extractExceptionMessage(ex));
}
var safeStrategyFunction = function() {
try {
return strategyFunction.apply(this, arguments);
} catch (ex) {
throw new SeleniumError("Error executing strategy function " + strategyName + ": " + extractExceptionMessage(ex));
}
}
this.browserbot.locationStrategies[strategyName] = safeStrategyFunction;
}
/**
* Factory for creating "Option Locators".
* An OptionLocator is an object for dealing with Select options (e.g. for
* finding a specified option, or asserting that the selected option of
* Select element matches some condition.
* The type of locator returned by the factory depends on the locator string:
* label=<exp> (OptionLocatorByLabel)
* value=<exp> (OptionLocatorByValue)
* index=<exp> (OptionLocatorByIndex)
* id=<exp> (OptionLocatorById)
* <exp> (default is OptionLocatorByLabel).
*/
function OptionLocatorFactory() {
}
OptionLocatorFactory.prototype.fromLocatorString = function(locatorString) {
var locatorType = 'label';
var locatorValue = locatorString;
// If there is a locator prefix, use the specified strategy
var result = locatorString.match(/^([a-zA-Z]+)=(.*)/);
if (result) {
locatorType = result[1];
locatorValue = result[2];
}
if (this.optionLocators == undefined) {
this.registerOptionLocators();
}
if (this.optionLocators[locatorType]) {
return new this.optionLocators[locatorType](locatorValue);
}
throw new SeleniumError("Unkown option locator type: " + locatorType);
};
/**
* To allow for easy extension, all of the option locators are found by
* searching for all methods of OptionLocatorFactory.prototype that start
* with "OptionLocatorBy".
* TODO: Consider using the term "Option Specifier" instead of "Option Locator".
*/
OptionLocatorFactory.prototype.registerOptionLocators = function() {
this.optionLocators={};
for (var functionName in this) {
var result = /OptionLocatorBy([A-Z].+)$/.exec(functionName);
if (result != null) {
var locatorName = result[1].lcfirst();
this.optionLocators[locatorName] = this[functionName];
}
}
};
/**
* OptionLocator for options identified by their labels.
*/
OptionLocatorFactory.prototype.OptionLocatorByLabel = function(label) {
this.label = label;
this.labelMatcher = new PatternMatcher(this.label);
this.findOption = function(element) {
for (var i = 0; i < element.options.length; i++) {
if (this.labelMatcher.matches(element.options[i].text)) {
return element.options[i];
}
}
throw new SeleniumError("Option with label '" + this.label + "' not found");
};
this.assertSelected = function(element) {
var selectedLabel = element.options[element.selectedIndex].text;
Assert.matches(this.label, selectedLabel)
};
};
/**
* OptionLocator for options identified by their values.
*/
OptionLocatorFactory.prototype.OptionLocatorByValue = function(value) {
this.value = value;
this.valueMatcher = new PatternMatcher(this.value);
this.findOption = function(element) {
for (var i = 0; i < element.options.length; i++) {
if (this.valueMatcher.matches(element.options[i].value)) {
return element.options[i];
}
}
throw new SeleniumError("Option with value '" + this.value + "' not found");
};
this.assertSelected = function(element) {
var selectedValue = element.options[element.selectedIndex].value;
Assert.matches(this.value, selectedValue)
};
};
/**
* OptionLocator for options identified by their index.
*/
OptionLocatorFactory.prototype.OptionLocatorByIndex = function(index) {
this.index = Number(index);
if (isNaN(this.index) || this.index < 0) {
throw new SeleniumError("Illegal Index: " + index);
}
this.findOption = function(element) {
if (element.options.length <= this.index) {
throw new SeleniumError("Index out of range. Only " + element.options.length + " options available");
}
return element.options[this.index];
};
this.assertSelected = function(element) {
Assert.equals(this.index, element.selectedIndex);
};
};
/**
* OptionLocator for options identified by their id.
*/
OptionLocatorFactory.prototype.OptionLocatorById = function(id) {
this.id = id;
this.idMatcher = new PatternMatcher(this.id);
this.findOption = function(element) {
for (var i = 0; i < element.options.length; i++) {
if (this.idMatcher.matches(element.options[i].id)) {
return element.options[i];
}
}
throw new SeleniumError("Option with id '" + this.id + "' not found");
};
this.assertSelected = function(element) {
var selectedId = element.options[element.selectedIndex].id;
Assert.matches(this.id, selectedId)
};
}; | zc.selenium | /zc.selenium-1.2.1.tar.gz/zc.selenium-1.2.1/src/zc/selenium/resources/scripts/selenium-api.js | selenium-api.js |
var Logger = function() {
this.logWindow = null;
}
Logger.prototype = {
logLevels: {
debug: 0,
info: 1,
warn: 2,
error: 3,
off: 999
},
pendingMessages: new Array(),
threshold: "info",
setLogLevelThreshold: function(logLevel) {
this.threshold = logLevel;
var logWindow = this.getLogWindow()
if (logWindow && logWindow.setThresholdLevel) {
logWindow.setThresholdLevel(logLevel);
}
// NOTE: log messages will be discarded until the log window is
// fully loaded.
},
getLogWindow: function() {
if (this.logWindow && this.logWindow.closed) {
this.logWindow = null;
}
return this.logWindow;
},
openLogWindow: function() {
this.logWindow = window.open(
getDocumentBase(document) + "SeleniumLog.html?startingThreshold="+this.threshold, "SeleniumLog",
"width=600,height=1000,bottom=0,right=0,status,scrollbars,resizable"
);
this.logWindow.moveTo(window.screenX + 1210, window.screenY + window.outerHeight - 1400);
if (browserVersion.appearsToBeBrokenInitialIE6) {
// I would really prefer for the message to immediately appear in the log window, the instant the user requests that the log window be
// visible. But when I initially coded it this way, thou message simply didn't appear unless I stepped through the code with a debugger.
// So obviously there is some timing issue here which I don't have the patience to figure out.
var pendingMessage = new LogMessage("warn", "You appear to be running an unpatched IE 6, which is not stable and can crash due to memory problems. We recommend you run Windows update to install a more stable version of IE.");
this.pendingMessages.push(pendingMessage);
}
return this.logWindow;
},
show: function() {
if (! this.getLogWindow()) {
this.openLogWindow();
}
setTimeout(function(){LOG.error("Log window displayed. Logging events will now be recorded to this window.");}, 500);
},
logHook: function(logLevel, message) {
},
log: function(logLevel, message) {
if (this.logLevels[logLevel] < this.logLevels[this.threshold]) {
return;
}
this.logHook(logLevel, message);
var logWindow = this.getLogWindow();
if (logWindow) {
if (logWindow.append) {
if (logWindow.disabled) {
logWindow.callBack = fnBind(this.setLogLevelThreshold, this);
logWindow.enableButtons();
}
if (this.pendingMessages.length > 0) {
logWindow.append("info: Appending missed logging messages", "info");
while (this.pendingMessages.length > 0) {
var msg = this.pendingMessages.shift();
logWindow.append(msg.type + ": " + msg.msg, msg.type);
}
logWindow.append("info: Done appending missed logging messages", "info");
}
logWindow.append(logLevel + ": " + message, logLevel);
}
} else {
// TODO these logging messages are never flushed, which creates
// an enormous array of strings that never stops growing.
// there should at least be a way to clear the messages!
this.pendingMessages.push(new LogMessage(logLevel, message));
}
},
close: function(message) {
if (this.logWindow != null) {
try {
this.logWindow.close();
} catch (e) {
// swallow exception
// the window is probably closed if we get an exception here
}
this.logWindow = null;
}
},
debug: function(message) {
this.log("debug", message);
},
info: function(message) {
this.log("info", message);
},
warn: function(message) {
this.log("warn", message);
},
error: function(message) {
this.log("error", message);
},
exception: function(exception) {
this.error("Unexpected Exception: " + extractExceptionMessage(exception));
this.error("Exception details: " + describe(exception, ', '));
}
};
var LOG = new Logger();
var LogMessage = function(type, msg) {
this.type = type;
this.msg = msg;
} | zc.selenium | /zc.selenium-1.2.1.tar.gz/zc.selenium-1.2.1/src/zc/selenium/resources/scripts/selenium-logging.js | selenium-logging.js |
* Narcissus - JS implemented in JS.
*
* Lexical scanner and parser.
*/
// jrh
//module('JS.Parse');
// Build a regexp that recognizes operators and punctuators (except newline).
var opRegExp =
/^;|^,|^\?|^:|^\|\||^\&\&|^\||^\^|^\&|^===|^==|^=|^!==|^!=|^<<|^<=|^<|^>>>|^>>|^>=|^>|^\+\+|^\-\-|^\+|^\-|^\*|^\/|^%|^!|^~|^\.|^\[|^\]|^\{|^\}|^\(|^\)/;
// A regexp to match floating point literals (but not integer literals).
var fpRegExp = /^\d+\.\d*(?:[eE][-+]?\d+)?|^\d+(?:\.\d*)?[eE][-+]?\d+|^\.\d+(?:[eE][-+]?\d+)?/;
function Tokenizer(s, f, l) {
this.cursor = 0;
this.source = String(s);
this.tokens = [];
this.tokenIndex = 0;
this.lookahead = 0;
this.scanNewlines = false;
this.scanOperand = true;
this.filename = f || "";
this.lineno = l || 1;
}
Tokenizer.prototype = {
input : function() {
return this.source.substring(this.cursor);
},
done : function() {
return this.peek() == END;
},
token : function() {
return this.tokens[this.tokenIndex];
},
match: function (tt) {
return this.get() == tt || this.unget();
},
mustMatch: function (tt) {
if (!this.match(tt))
throw this.newSyntaxError("Missing " + this.tokens[tt].toLowerCase());
return this.token();
},
peek: function () {
var tt;
if (this.lookahead) {
tt = this.tokens[(this.tokenIndex + this.lookahead) & 3].type;
} else {
tt = this.get();
this.unget();
}
return tt;
},
peekOnSameLine: function () {
this.scanNewlines = true;
var tt = this.peek();
this.scanNewlines = false;
return tt;
},
get: function () {
var token;
while (this.lookahead) {
--this.lookahead;
this.tokenIndex = (this.tokenIndex + 1) & 3;
token = this.tokens[this.tokenIndex];
if (token.type != NEWLINE || this.scanNewlines)
return token.type;
}
for (;;) {
var input = this.input();
var rx = this.scanNewlines ? /^[ \t]+/ : /^\s+/;
var match = input.match(rx);
if (match) {
var spaces = match[0];
this.cursor += spaces.length;
var newlines = spaces.match(/\n/g);
if (newlines)
this.lineno += newlines.length;
input = this.input();
}
if (!(match = input.match(/^\/(?:\*(?:.|\n)*?\*\/|\/.*)/)))
break;
var comment = match[0];
this.cursor += comment.length;
newlines = comment.match(/\n/g);
if (newlines)
this.lineno += newlines.length
}
this.tokenIndex = (this.tokenIndex + 1) & 3;
token = this.tokens[this.tokenIndex];
if (!token)
this.tokens[this.tokenIndex] = token = {};
if (!input)
return token.type = END;
if ((match = input.match(fpRegExp))) {
token.type = NUMBER;
token.value = parseFloat(match[0]);
} else if ((match = input.match(/^0[xX][\da-fA-F]+|^0[0-7]*|^\d+/))) {
token.type = NUMBER;
token.value = parseInt(match[0]);
} else if ((match = input.match(/^((\$\w*)|(\w+))/))) {
var id = match[0];
token.type = keywords[id] || IDENTIFIER;
token.value = id;
} else if ((match = input.match(/^"(?:\\.|[^"])*"|^'(?:[^']|\\.)*'/))) {
token.type = STRING;
token.value = eval(match[0]);
} else if (this.scanOperand &&
(match = input.match(/^\/((?:\\.|[^\/])+)\/([gi]*)/))) {
token.type = REGEXP;
token.value = new RegExp(match[1], match[2]);
} else if ((match = input.match(opRegExp))) {
var op = match[0];
if (assignOps[op] && input[op.length] == '=') {
token.type = ASSIGN;
token.assignOp = GLOBAL[opTypeNames[op]];
match[0] += '=';
} else {
token.type = GLOBAL[opTypeNames[op]];
if (this.scanOperand &&
(token.type == PLUS || token.type == MINUS)) {
token.type += UNARY_PLUS - PLUS;
}
token.assignOp = null;
}
//debug('token.value => '+op+', token.type => '+token.type);
token.value = op;
} else {
throw this.newSyntaxError("Illegal token");
}
token.start = this.cursor;
this.cursor += match[0].length;
token.end = this.cursor;
token.lineno = this.lineno;
return token.type;
},
unget: function () {
if (++this.lookahead == 4) throw "PANIC: too much lookahead!";
this.tokenIndex = (this.tokenIndex - 1) & 3;
},
newSyntaxError: function (m) {
var e = new SyntaxError(m, this.filename, this.lineno);
e.source = this.source;
e.cursor = this.cursor;
return e;
}
};
function CompilerContext(inFunction) {
this.inFunction = inFunction;
this.stmtStack = [];
this.funDecls = [];
this.varDecls = [];
}
var CCp = CompilerContext.prototype;
CCp.bracketLevel = CCp.curlyLevel = CCp.parenLevel = CCp.hookLevel = 0;
CCp.ecmaStrictMode = CCp.inForLoopInit = false;
function Script(t, x) {
var n = Statements(t, x);
n.type = SCRIPT;
n.funDecls = x.funDecls;
n.varDecls = x.varDecls;
return n;
}
// Node extends Array, which we extend slightly with a top-of-stack method.
Array.prototype.top = function() {
return this.length && this[this.length-1];
}
function NarcNode(t, type) {
var token = t.token();
if (token) {
this.type = type || token.type;
this.value = token.value;
this.lineno = token.lineno;
this.start = token.start;
this.end = token.end;
} else {
this.type = type;
this.lineno = t.lineno;
}
this.tokenizer = t;
for (var i = 2; i < arguments.length; i++)
this.push(arguments[i]);
}
var Np = NarcNode.prototype = new Array();
Np.constructor = NarcNode;
Np.$length = 0;
Np.toSource = Object.prototype.toSource;
// Always use push to add operands to an expression, to update start and end.
Np.push = function (kid) {
if (kid.start < this.start)
this.start = kid.start;
if (this.end < kid.end)
this.end = kid.end;
//debug('length before => '+this.$length);
this[this.$length] = kid;
this.$length++;
//debug('length after => '+this.$length);
}
NarcNode.indentLevel = 0;
function tokenstr(tt) {
var t = tokens[tt];
return /^\W/.test(t) ? opTypeNames[t] : t.toUpperCase();
}
Np.toString = function () {
var a = [];
for (var i in this) {
if (this.hasOwnProperty(i) && i != 'type')
a.push({id: i, value: this[i]});
}
a.sort(function (a,b) { return (a.id < b.id) ? -1 : 1; });
INDENTATION = " ";
var n = ++NarcNode.indentLevel;
var s = "{\n" + INDENTATION.repeat(n) + "type: " + tokenstr(this.type);
for (i = 0; i < a.length; i++)
s += ",\n" + INDENTATION.repeat(n) + a[i].id + ": " + a[i].value;
n = --NarcNode.indentLevel;
s += "\n" + INDENTATION.repeat(n) + "}";
return s;
}
Np.getSource = function () {
return this.tokenizer.source.slice(this.start, this.end);
};
Np.filename = function () { return this.tokenizer.filename; };
String.prototype.repeat = function (n) {
var s = "", t = this + s;
while (--n >= 0)
s += t;
return s;
}
// Statement stack and nested statement handler.
function nest(t, x, node, func, end) {
x.stmtStack.push(node);
var n = func(t, x);
x.stmtStack.pop();
end && t.mustMatch(end);
return n;
}
function Statements(t, x) {
var n = new NarcNode(t, BLOCK);
x.stmtStack.push(n);
while (!t.done() && t.peek() != RIGHT_CURLY)
n.push(Statement(t, x));
x.stmtStack.pop();
return n;
}
function Block(t, x) {
t.mustMatch(LEFT_CURLY);
var n = Statements(t, x);
t.mustMatch(RIGHT_CURLY);
return n;
}
DECLARED_FORM = 0; EXPRESSED_FORM = 1; STATEMENT_FORM = 2;
function Statement(t, x) {
var i, label, n, n2, ss, tt = t.get();
// Cases for statements ending in a right curly return early, avoiding the
// common semicolon insertion magic after this switch.
switch (tt) {
case FUNCTION:
return FunctionDefinition(t, x, true,
(x.stmtStack.length > 1)
? STATEMENT_FORM
: DECLARED_FORM);
case LEFT_CURLY:
n = Statements(t, x);
t.mustMatch(RIGHT_CURLY);
return n;
case IF:
n = new NarcNode(t);
n.condition = ParenExpression(t, x);
x.stmtStack.push(n);
n.thenPart = Statement(t, x);
n.elsePart = t.match(ELSE) ? Statement(t, x) : null;
x.stmtStack.pop();
return n;
case SWITCH:
n = new NarcNode(t);
t.mustMatch(LEFT_PAREN);
n.discriminant = Expression(t, x);
t.mustMatch(RIGHT_PAREN);
n.cases = [];
n.defaultIndex = -1;
x.stmtStack.push(n);
t.mustMatch(LEFT_CURLY);
while ((tt = t.get()) != RIGHT_CURLY) {
switch (tt) {
case DEFAULT:
if (n.defaultIndex >= 0)
throw t.newSyntaxError("More than one switch default");
// FALL THROUGH
case CASE:
n2 = new NarcNode(t);
if (tt == DEFAULT)
n.defaultIndex = n.cases.length;
else
n2.caseLabel = Expression(t, x, COLON);
break;
default:
throw t.newSyntaxError("Invalid switch case");
}
t.mustMatch(COLON);
n2.statements = new NarcNode(t, BLOCK);
while ((tt=t.peek()) != CASE && tt != DEFAULT && tt != RIGHT_CURLY)
n2.statements.push(Statement(t, x));
n.cases.push(n2);
}
x.stmtStack.pop();
return n;
case FOR:
n = new NarcNode(t);
n.isLoop = true;
t.mustMatch(LEFT_PAREN);
if ((tt = t.peek()) != SEMICOLON) {
x.inForLoopInit = true;
if (tt == VAR || tt == CONST) {
t.get();
n2 = Variables(t, x);
} else {
n2 = Expression(t, x);
}
x.inForLoopInit = false;
}
if (n2 && t.match(IN)) {
n.type = FOR_IN;
if (n2.type == VAR) {
if (n2.$length != 1) {
throw new SyntaxError("Invalid for..in left-hand side",
t.filename, n2.lineno);
}
// NB: n2[0].type == IDENTIFIER and n2[0].value == n2[0].name.
n.iterator = n2[0];
n.varDecl = n2;
} else {
n.iterator = n2;
n.varDecl = null;
}
n.object = Expression(t, x);
} else {
n.setup = n2 || null;
t.mustMatch(SEMICOLON);
n.condition = (t.peek() == SEMICOLON) ? null : Expression(t, x);
t.mustMatch(SEMICOLON);
n.update = (t.peek() == RIGHT_PAREN) ? null : Expression(t, x);
}
t.mustMatch(RIGHT_PAREN);
n.body = nest(t, x, n, Statement);
return n;
case WHILE:
n = new NarcNode(t);
n.isLoop = true;
n.condition = ParenExpression(t, x);
n.body = nest(t, x, n, Statement);
return n;
case DO:
n = new NarcNode(t);
n.isLoop = true;
n.body = nest(t, x, n, Statement, WHILE);
n.condition = ParenExpression(t, x);
if (!x.ecmaStrictMode) {
// <script language="JavaScript"> (without version hints) may need
// automatic semicolon insertion without a newline after do-while.
// See http://bugzilla.mozilla.org/show_bug.cgi?id=238945.
t.match(SEMICOLON);
return n;
}
break;
case BREAK:
case CONTINUE:
n = new NarcNode(t);
if (t.peekOnSameLine() == IDENTIFIER) {
t.get();
n.label = t.token().value;
}
ss = x.stmtStack;
i = ss.length;
label = n.label;
if (label) {
do {
if (--i < 0)
throw t.newSyntaxError("Label not found");
} while (ss[i].label != label);
} else {
do {
if (--i < 0) {
throw t.newSyntaxError("Invalid " + ((tt == BREAK)
? "break"
: "continue"));
}
} while (!ss[i].isLoop && (tt != BREAK || ss[i].type != SWITCH));
}
n.target = ss[i];
break;
case TRY:
n = new NarcNode(t);
n.tryBlock = Block(t, x);
n.catchClauses = [];
while (t.match(CATCH)) {
n2 = new NarcNode(t);
t.mustMatch(LEFT_PAREN);
n2.varName = t.mustMatch(IDENTIFIER).value;
if (t.match(IF)) {
if (x.ecmaStrictMode)
throw t.newSyntaxError("Illegal catch guard");
if (n.catchClauses.length && !n.catchClauses.top().guard)
throw t.newSyntaxError("Guarded catch after unguarded");
n2.guard = Expression(t, x);
} else {
n2.guard = null;
}
t.mustMatch(RIGHT_PAREN);
n2.block = Block(t, x);
n.catchClauses.push(n2);
}
if (t.match(FINALLY))
n.finallyBlock = Block(t, x);
if (!n.catchClauses.length && !n.finallyBlock)
throw t.newSyntaxError("Invalid try statement");
return n;
case CATCH:
case FINALLY:
throw t.newSyntaxError(tokens[tt] + " without preceding try");
case THROW:
n = new NarcNode(t);
n.exception = Expression(t, x);
break;
case RETURN:
if (!x.inFunction)
throw t.newSyntaxError("Invalid return");
n = new NarcNode(t);
tt = t.peekOnSameLine();
if (tt != END && tt != NEWLINE && tt != SEMICOLON && tt != RIGHT_CURLY)
n.value = Expression(t, x);
break;
case WITH:
n = new NarcNode(t);
n.object = ParenExpression(t, x);
n.body = nest(t, x, n, Statement);
return n;
case VAR:
case CONST:
n = Variables(t, x);
break;
case DEBUGGER:
n = new NarcNode(t);
break;
case REQUIRE:
n = new NarcNode(t);
n.classPath = ParenExpression(t, x);
break;
case NEWLINE:
case SEMICOLON:
n = new NarcNode(t, SEMICOLON);
n.expression = null;
return n;
default:
if (tt == IDENTIFIER && t.peek() == COLON) {
label = t.token().value;
ss = x.stmtStack;
for (i = ss.length-1; i >= 0; --i) {
if (ss[i].label == label)
throw t.newSyntaxError("Duplicate label");
}
t.get();
n = new NarcNode(t, LABEL);
n.label = label;
n.statement = nest(t, x, n, Statement);
return n;
}
n = new NarcNode(t, SEMICOLON);
t.unget();
n.expression = Expression(t, x);
n.end = n.expression.end;
break;
}
if (t.lineno == t.token().lineno) {
tt = t.peekOnSameLine();
if (tt != END && tt != NEWLINE && tt != SEMICOLON && tt != RIGHT_CURLY)
throw t.newSyntaxError("Missing ; before statement");
}
t.match(SEMICOLON);
return n;
}
function FunctionDefinition(t, x, requireName, functionForm) {
var f = new NarcNode(t);
if (f.type != FUNCTION)
f.type = (f.value == "get") ? GETTER : SETTER;
if (t.match(IDENTIFIER)) {
f.name = t.token().value;
}
else if (requireName)
throw t.newSyntaxError("Missing function identifier");
t.mustMatch(LEFT_PAREN);
f.params = [];
var tt;
while ((tt = t.get()) != RIGHT_PAREN) {
if (tt != IDENTIFIER)
throw t.newSyntaxError("Missing formal parameter");
f.params.push(t.token().value);
if (t.peek() != RIGHT_PAREN)
t.mustMatch(COMMA);
}
t.mustMatch(LEFT_CURLY);
var x2 = new CompilerContext(true);
f.body = Script(t, x2);
t.mustMatch(RIGHT_CURLY);
f.end = t.token().end;
f.functionForm = functionForm;
if (functionForm == DECLARED_FORM) {
x.funDecls.push(f);
}
return f;
}
function Variables(t, x) {
var n = new NarcNode(t);
do {
t.mustMatch(IDENTIFIER);
var n2 = new NarcNode(t);
n2.name = n2.value;
if (t.match(ASSIGN)) {
if (t.token().assignOp)
throw t.newSyntaxError("Invalid variable initialization");
n2.initializer = Expression(t, x, COMMA);
}
n2.readOnly = (n.type == CONST);
n.push(n2);
x.varDecls.push(n2);
} while (t.match(COMMA));
return n;
}
function ParenExpression(t, x) {
t.mustMatch(LEFT_PAREN);
var n = Expression(t, x);
t.mustMatch(RIGHT_PAREN);
return n;
}
var opPrecedence = {
SEMICOLON: 0,
COMMA: 1,
ASSIGN: 2, HOOK: 2, COLON: 2, CONDITIONAL: 2,
// The above all have to have the same precedence, see bug 330975.
OR: 4,
AND: 5,
BITWISE_OR: 6,
BITWISE_XOR: 7,
BITWISE_AND: 8,
EQ: 9, NE: 9, STRICT_EQ: 9, STRICT_NE: 9,
LT: 10, LE: 10, GE: 10, GT: 10, IN: 10, INSTANCEOF: 10,
LSH: 11, RSH: 11, URSH: 11,
PLUS: 12, MINUS: 12,
MUL: 13, DIV: 13, MOD: 13,
DELETE: 14, VOID: 14, TYPEOF: 14, // PRE_INCREMENT: 14, PRE_DECREMENT: 14,
NOT: 14, BITWISE_NOT: 14, UNARY_PLUS: 14, UNARY_MINUS: 14,
INCREMENT: 15, DECREMENT: 15, // postfix
NEW: 16,
DOT: 17
};
// Map operator type code to precedence.
for (i in opPrecedence)
opPrecedence[GLOBAL[i]] = opPrecedence[i];
var opArity = {
COMMA: -2,
ASSIGN: 2,
CONDITIONAL: 3,
OR: 2,
AND: 2,
BITWISE_OR: 2,
BITWISE_XOR: 2,
BITWISE_AND: 2,
EQ: 2, NE: 2, STRICT_EQ: 2, STRICT_NE: 2,
LT: 2, LE: 2, GE: 2, GT: 2, IN: 2, INSTANCEOF: 2,
LSH: 2, RSH: 2, URSH: 2,
PLUS: 2, MINUS: 2,
MUL: 2, DIV: 2, MOD: 2,
DELETE: 1, VOID: 1, TYPEOF: 1, // PRE_INCREMENT: 1, PRE_DECREMENT: 1,
NOT: 1, BITWISE_NOT: 1, UNARY_PLUS: 1, UNARY_MINUS: 1,
INCREMENT: 1, DECREMENT: 1, // postfix
NEW: 1, NEW_WITH_ARGS: 2, DOT: 2, INDEX: 2, CALL: 2,
ARRAY_INIT: 1, OBJECT_INIT: 1, GROUP: 1
};
// Map operator type code to arity.
for (i in opArity)
opArity[GLOBAL[i]] = opArity[i];
function Expression(t, x, stop) {
var n, id, tt, operators = [], operands = [];
var bl = x.bracketLevel, cl = x.curlyLevel, pl = x.parenLevel,
hl = x.hookLevel;
function reduce() {
//debug('OPERATORS => '+operators);
var n = operators.pop();
var op = n.type;
var arity = opArity[op];
if (arity == -2) {
// Flatten left-associative trees.
var left = operands.length >= 2 && operands[operands.length-2];
if (left.type == op) {
var right = operands.pop();
left.push(right);
return left;
}
arity = 2;
}
// Always use push to add operands to n, to update start and end.
var a = operands.splice(operands.length - arity, operands.length);
for (var i = 0; i < arity; i++) {
n.push(a[i]);
}
// Include closing bracket or postfix operator in [start,end).
if (n.end < t.token().end)
n.end = t.token().end;
operands.push(n);
return n;
}
loop:
while ((tt = t.get()) != END) {
//debug('TT => '+tokens[tt]);
if (tt == stop &&
x.bracketLevel == bl && x.curlyLevel == cl && x.parenLevel == pl &&
x.hookLevel == hl) {
// Stop only if tt matches the optional stop parameter, and that
// token is not quoted by some kind of bracket.
break;
}
switch (tt) {
case SEMICOLON:
// NB: cannot be empty, Statement handled that.
break loop;
case ASSIGN:
case HOOK:
case COLON:
if (t.scanOperand)
break loop;
// Use >, not >=, for right-associative ASSIGN and HOOK/COLON.
while (operators.length && opPrecedence[operators.top().type] > opPrecedence[tt] ||
(tt == COLON && operators.top().type == ASSIGN)) {
reduce();
}
if (tt == COLON) {
n = operators.top();
if (n.type != HOOK)
throw t.newSyntaxError("Invalid label");
n.type = CONDITIONAL;
--x.hookLevel;
} else {
operators.push(new NarcNode(t));
if (tt == ASSIGN)
operands.top().assignOp = t.token().assignOp;
else
++x.hookLevel; // tt == HOOK
}
t.scanOperand = true;
break;
case IN:
// An in operator should not be parsed if we're parsing the head of
// a for (...) loop, unless it is in the then part of a conditional
// expression, or parenthesized somehow.
if (x.inForLoopInit && !x.hookLevel &&
!x.bracketLevel && !x.curlyLevel && !x.parenLevel) {
break loop;
}
// FALL THROUGH
case COMMA:
// Treat comma as left-associative so reduce can fold left-heavy
// COMMA trees into a single array.
// FALL THROUGH
case OR:
case AND:
case BITWISE_OR:
case BITWISE_XOR:
case BITWISE_AND:
case EQ: case NE: case STRICT_EQ: case STRICT_NE:
case LT: case LE: case GE: case GT:
case INSTANCEOF:
case LSH: case RSH: case URSH:
case PLUS: case MINUS:
case MUL: case DIV: case MOD:
case DOT:
if (t.scanOperand)
break loop;
while (operators.length && opPrecedence[operators.top().type] >= opPrecedence[tt])
reduce();
if (tt == DOT) {
t.mustMatch(IDENTIFIER);
operands.push(new NarcNode(t, DOT, operands.pop(), new NarcNode(t)));
} else {
operators.push(new NarcNode(t));
t.scanOperand = true;
}
break;
case DELETE: case VOID: case TYPEOF:
case NOT: case BITWISE_NOT: case UNARY_PLUS: case UNARY_MINUS:
case NEW:
if (!t.scanOperand)
break loop;
operators.push(new NarcNode(t));
break;
case INCREMENT: case DECREMENT:
if (t.scanOperand) {
operators.push(new NarcNode(t)); // prefix increment or decrement
} else {
// Use >, not >=, so postfix has higher precedence than prefix.
while (operators.length && opPrecedence[operators.top().type] > opPrecedence[tt])
reduce();
n = new NarcNode(t, tt, operands.pop());
n.postfix = true;
operands.push(n);
}
break;
case FUNCTION:
if (!t.scanOperand)
break loop;
operands.push(FunctionDefinition(t, x, false, EXPRESSED_FORM));
t.scanOperand = false;
break;
case NULL: case THIS: case TRUE: case FALSE:
case IDENTIFIER: case NUMBER: case STRING: case REGEXP:
if (!t.scanOperand)
break loop;
operands.push(new NarcNode(t));
t.scanOperand = false;
break;
case LEFT_BRACKET:
if (t.scanOperand) {
// Array initialiser. Parse using recursive descent, as the
// sub-grammar here is not an operator grammar.
n = new NarcNode(t, ARRAY_INIT);
while ((tt = t.peek()) != RIGHT_BRACKET) {
if (tt == COMMA) {
t.get();
n.push(null);
continue;
}
n.push(Expression(t, x, COMMA));
if (!t.match(COMMA))
break;
}
t.mustMatch(RIGHT_BRACKET);
operands.push(n);
t.scanOperand = false;
} else {
// Property indexing operator.
operators.push(new NarcNode(t, INDEX));
t.scanOperand = true;
++x.bracketLevel;
}
break;
case RIGHT_BRACKET:
if (t.scanOperand || x.bracketLevel == bl)
break loop;
while (reduce().type != INDEX)
continue;
--x.bracketLevel;
break;
case LEFT_CURLY:
if (!t.scanOperand)
break loop;
// Object initialiser. As for array initialisers (see above),
// parse using recursive descent.
++x.curlyLevel;
n = new NarcNode(t, OBJECT_INIT);
object_init:
if (!t.match(RIGHT_CURLY)) {
do {
tt = t.get();
if ((t.token().value == "get" || t.token().value == "set") &&
t.peek() == IDENTIFIER) {
if (x.ecmaStrictMode)
throw t.newSyntaxError("Illegal property accessor");
n.push(FunctionDefinition(t, x, true, EXPRESSED_FORM));
} else {
switch (tt) {
case IDENTIFIER:
case NUMBER:
case STRING:
id = new NarcNode(t);
break;
case RIGHT_CURLY:
if (x.ecmaStrictMode)
throw t.newSyntaxError("Illegal trailing ,");
break object_init;
default:
throw t.newSyntaxError("Invalid property name");
}
t.mustMatch(COLON);
n.push(new NarcNode(t, PROPERTY_INIT, id,
Expression(t, x, COMMA)));
}
} while (t.match(COMMA));
t.mustMatch(RIGHT_CURLY);
}
operands.push(n);
t.scanOperand = false;
--x.curlyLevel;
break;
case RIGHT_CURLY:
if (!t.scanOperand && x.curlyLevel != cl)
throw "PANIC: right curly botch";
break loop;
case LEFT_PAREN:
if (t.scanOperand) {
operators.push(new NarcNode(t, GROUP));
} else {
while (operators.length && opPrecedence[operators.top().type] > opPrecedence[NEW])
reduce();
// Handle () now, to regularize the n-ary case for n > 0.
// We must set scanOperand in case there are arguments and
// the first one is a regexp or unary+/-.
n = operators.top();
t.scanOperand = true;
if (t.match(RIGHT_PAREN)) {
if (n.type == NEW) {
--operators.length;
n.push(operands.pop());
} else {
n = new NarcNode(t, CALL, operands.pop(),
new NarcNode(t, LIST));
}
operands.push(n);
t.scanOperand = false;
break;
}
if (n.type == NEW)
n.type = NEW_WITH_ARGS;
else
operators.push(new NarcNode(t, CALL));
}
++x.parenLevel;
break;
case RIGHT_PAREN:
if (t.scanOperand || x.parenLevel == pl)
break loop;
while ((tt = reduce().type) != GROUP && tt != CALL &&
tt != NEW_WITH_ARGS) {
continue;
}
if (tt != GROUP) {
n = operands.top();
if (n[1].type != COMMA)
n[1] = new NarcNode(t, LIST, n[1]);
else
n[1].type = LIST;
}
--x.parenLevel;
break;
// Automatic semicolon insertion means we may scan across a newline
// and into the beginning of another statement. If so, break out of
// the while loop and let the t.scanOperand logic handle errors.
default:
break loop;
}
}
if (x.hookLevel != hl)
throw t.newSyntaxError("Missing : after ?");
if (x.parenLevel != pl)
throw t.newSyntaxError("Missing ) in parenthetical");
if (x.bracketLevel != bl)
throw t.newSyntaxError("Missing ] in index expression");
if (t.scanOperand)
throw t.newSyntaxError("Missing operand");
// Resume default mode, scanning for operands, not operators.
t.scanOperand = true;
t.unget();
while (operators.length)
reduce();
return operands.pop();
}
function parse(s, f, l) {
var t = new Tokenizer(s, f, l);
var x = new CompilerContext(false);
var n = Script(t, x);
if (!t.done())
throw t.newSyntaxError("Syntax error");
return n;
}
debug = function(msg) {
document.body.appendChild(document.createTextNode(msg));
document.body.appendChild(document.createElement('br'));
} | zc.selenium | /zc.selenium-1.2.1.tar.gz/zc.selenium-1.2.1/src/zc/selenium/resources/scripts/narcissus-parse.js | narcissus-parse.js |
var BrowserVersion = function() {
this.name = navigator.appName;
if (navigator.userAgent.indexOf('Mac OS X') != -1) {
this.isOSX = true;
}
if (navigator.userAgent.indexOf('Windows NT 6') != -1) {
this.isVista = true;
}
if (window.opera != null) {
this.browser = BrowserVersion.OPERA;
this.isOpera = true;
return;
}
var _getQueryParameter = function(searchKey) {
var str = location.search.substr(1);
if (str == null) return null;
var clauses = str.split('&');
for (var i = 0; i < clauses.length; i++) {
var keyValuePair = clauses[i].split('=', 2);
var key = unescape(keyValuePair[0]);
if (key == searchKey) {
return unescape(keyValuePair[1]);
}
}
return null;
};
var self = this;
var checkChrome = function() {
var loc = window.document.location.href;
try {
loc = window.top.document.location.href;
if (/^chrome:\/\//.test(loc)) {
self.isChrome = true;
} else {
self.isChrome = false;
}
} catch (e) {
// can't see the top (that means we might be chrome, but it's impossible to be sure)
self.isChromeDetectable = "no, top location couldn't be read in this window";
if (_getQueryParameter('thisIsChrome')) {
self.isChrome = true;
} else {
self.isChrome = false;
}
}
}
if (this.name == "Microsoft Internet Explorer") {
this.browser = BrowserVersion.IE;
this.isIE = true;
try {
if (window.top.SeleniumHTARunner && window.top.document.location.pathname.match(/.hta$/i)) {
this.isHTA = true;
}
} catch (e) {
this.isHTADetectable = "no, top location couldn't be read in this window";
if (_getQueryParameter('thisIsHTA')) {
self.isHTA = true;
} else {
self.isHTA = false;
}
}
if ("0" == navigator.appMinorVersion) {
this.preSV1 = true;
if (navigator.appVersion.match(/MSIE 6.0/)) {
this.appearsToBeBrokenInitialIE6 = true;
}
}
return;
}
if (navigator.userAgent.indexOf('Safari') != -1) {
this.browser = BrowserVersion.SAFARI;
this.isSafari = true;
this.khtml = true;
return;
}
if (navigator.userAgent.indexOf('Konqueror') != -1) {
this.browser = BrowserVersion.KONQUEROR;
this.isKonqueror = true;
this.khtml = true;
return;
}
if (navigator.userAgent.indexOf('Firefox') != -1) {
this.browser = BrowserVersion.FIREFOX;
this.isFirefox = true;
this.isGecko = true;
var result = /.*Firefox\/([\d\.]+).*/.exec(navigator.userAgent);
if (result) {
this.firefoxVersion = result[1];
}
checkChrome();
return;
}
if (navigator.userAgent.indexOf('Gecko') != -1) {
this.browser = BrowserVersion.MOZILLA;
this.isMozilla = true;
this.isGecko = true;
checkChrome();
return;
}
this.browser = BrowserVersion.UNKNOWN;
}
BrowserVersion.OPERA = "Opera";
BrowserVersion.IE = "IE";
BrowserVersion.KONQUEROR = "Konqueror";
BrowserVersion.SAFARI = "Safari";
BrowserVersion.FIREFOX = "Firefox";
BrowserVersion.MOZILLA = "Mozilla";
BrowserVersion.UNKNOWN = "Unknown";
var browserVersion = new BrowserVersion(); | zc.selenium | /zc.selenium-1.2.1.tar.gz/zc.selenium-1.2.1/src/zc/selenium/resources/scripts/selenium-browserdetect.js | selenium-browserdetect.js |
function classCreate() {
return function() {
this.initialize.apply(this, arguments);
}
}
function objectExtend(destination, source) {
for (var property in source) {
destination[property] = source[property];
}
return destination;
}
function sel$() {
var results = [], element;
for (var i = 0; i < arguments.length; i++) {
element = arguments[i];
if (typeof element == 'string')
element = document.getElementById(element);
results[results.length] = element;
}
return results.length < 2 ? results[0] : results;
}
function sel$A(iterable) {
if (!iterable) return [];
if (iterable.toArray) {
return iterable.toArray();
} else {
var results = [];
for (var i = 0; i < iterable.length; i++)
results.push(iterable[i]);
return results;
}
}
function fnBind() {
var args = sel$A(arguments), __method = args.shift(), object = args.shift();
var retval = function() {
return __method.apply(object, args.concat(sel$A(arguments)));
}
retval.__method = __method;
return retval;
}
function fnBindAsEventListener(fn, object) {
var __method = fn;
return function(event) {
return __method.call(object, event || window.event);
}
}
function removeClassName(element, name) {
var re = new RegExp("\\b" + name + "\\b", "g");
element.className = element.className.replace(re, "");
}
function addClassName(element, name) {
element.className = element.className + ' ' + name;
}
function elementSetStyle(element, style) {
for (var name in style) {
var value = style[name];
if (value == null) value = "";
element.style[name] = value;
}
}
function elementGetStyle(element, style) {
var value = element.style[style];
if (!value) {
if (document.defaultView && document.defaultView.getComputedStyle) {
var css = document.defaultView.getComputedStyle(element, null);
value = css ? css.getPropertyValue(style) : null;
} else if (element.currentStyle) {
value = element.currentStyle[style];
}
}
/** DGF necessary?
if (window.opera && ['left', 'top', 'right', 'bottom'].include(style))
if (Element.getStyle(element, 'position') == 'static') value = 'auto'; */
return value == 'auto' ? null : value;
}
String.prototype.trim = function() {
var result = this.replace(/^\s+/g, "");
// strip leading
return result.replace(/\s+$/g, "");
// strip trailing
};
String.prototype.lcfirst = function() {
return this.charAt(0).toLowerCase() + this.substr(1);
};
String.prototype.ucfirst = function() {
return this.charAt(0).toUpperCase() + this.substr(1);
};
String.prototype.startsWith = function(str) {
return this.indexOf(str) == 0;
};
// Returns the text in this element
function getText(element) {
var text = "";
var isRecentFirefox = (browserVersion.isFirefox && browserVersion.firefoxVersion >= "1.5");
if (isRecentFirefox || browserVersion.isKonqueror || browserVersion.isSafari || browserVersion.isOpera) {
text = getTextContent(element);
} else if (element.textContent) {
text = element.textContent;
} else if (element.innerText) {
text = element.innerText;
}
text = normalizeNewlines(text);
text = normalizeSpaces(text);
return text.trim();
}
function getTextContent(element, preformatted) {
if (element.nodeType == 3 /*Node.TEXT_NODE*/) {
var text = element.data;
if (!preformatted) {
text = text.replace(/\n|\r|\t/g, " ");
}
return text;
}
if (element.nodeType == 1 /*Node.ELEMENT_NODE*/) {
var childrenPreformatted = preformatted || (element.tagName == "PRE");
var text = "";
for (var i = 0; i < element.childNodes.length; i++) {
var child = element.childNodes.item(i);
text += getTextContent(child, childrenPreformatted);
}
// Handle block elements that introduce newlines
// -- From HTML spec:
//<!ENTITY % block
// "P | %heading; | %list; | %preformatted; | DL | DIV | NOSCRIPT |
// BLOCKQUOTE | F:wORM | HR | TABLE | FIELDSET | ADDRESS">
//
// TODO: should potentially introduce multiple newlines to separate blocks
if (element.tagName == "P" || element.tagName == "BR" || element.tagName == "HR" || element.tagName == "DIV") {
text += "\n";
}
return text;
}
return '';
}
/**
* Convert all newlines to \m
*/
function normalizeNewlines(text)
{
return text.replace(/\r\n|\r/g, "\n");
}
/**
* Replace multiple sequential spaces with a single space, and then convert to space.
*/
function normalizeSpaces(text)
{
// IE has already done this conversion, so doing it again will remove multiple nbsp
if (browserVersion.isIE)
{
return text;
}
// Replace multiple spaces with a single space
// TODO - this shouldn't occur inside PRE elements
text = text.replace(/\ +/g, " ");
// Replace with a space
var nbspPattern = new RegExp(String.fromCharCode(160), "g");
if (browserVersion.isSafari) {
return replaceAll(text, String.fromCharCode(160), " ");
} else {
return text.replace(nbspPattern, " ");
}
}
function replaceAll(text, oldText, newText) {
while (text.indexOf(oldText) != -1) {
text = text.replace(oldText, newText);
}
return text;
}
function xmlDecode(text) {
text = text.replace(/"/g, '"');
text = text.replace(/'/g, "'");
text = text.replace(/</g, "<");
text = text.replace(/>/g, ">");
text = text.replace(/&/g, "&");
return text;
}
// Sets the text in this element
function setText(element, text) {
if (element.textContent != null) {
element.textContent = text;
} else if (element.innerText != null) {
element.innerText = text;
}
}
// Get the value of an <input> element
function getInputValue(inputElement) {
if (inputElement.type) {
if (inputElement.type.toUpperCase() == 'CHECKBOX' ||
inputElement.type.toUpperCase() == 'RADIO')
{
return (inputElement.checked ? 'on' : 'off');
}
}
if (inputElement.value == null) {
throw new SeleniumError("This element has no value; is it really a form field?");
}
return inputElement.value;
}
/* Fire an event in a browser-compatible manner */
function triggerEvent(element, eventType, canBubble, controlKeyDown, altKeyDown, shiftKeyDown, metaKeyDown) {
canBubble = (typeof(canBubble) == undefined) ? true : canBubble;
if (element.fireEvent) {
var evt = createEventObject(element, controlKeyDown, altKeyDown, shiftKeyDown, metaKeyDown);
element.fireEvent('on' + eventType, evt);
}
else {
var evt = document.createEvent('HTMLEvents');
try {
evt.shiftKey = shiftKeyDown;
evt.metaKey = metaKeyDown;
evt.altKey = altKeyDown;
evt.ctrlKey = controlKeyDown;
} catch (e) {
// On Firefox 1.0, you can only set these during initMouseEvent or initKeyEvent
// we'll have to ignore them here
LOG.exception(e);
}
evt.initEvent(eventType, canBubble, true);
element.dispatchEvent(evt);
}
}
function getKeyCodeFromKeySequence(keySequence) {
var match = /^\\(\d{1,3})$/.exec(keySequence);
if (match != null) {
return match[1];
}
match = /^.$/.exec(keySequence);
if (match != null) {
return match[0].charCodeAt(0);
}
// this is for backward compatibility with existing tests
// 1 digit ascii codes will break however because they are used for the digit chars
match = /^\d{2,3}$/.exec(keySequence);
if (match != null) {
return match[0];
}
throw new SeleniumError("invalid keySequence");
}
function createEventObject(element, controlKeyDown, altKeyDown, shiftKeyDown, metaKeyDown) {
var evt = element.ownerDocument.createEventObject();
evt.shiftKey = shiftKeyDown;
evt.metaKey = metaKeyDown;
evt.altKey = altKeyDown;
evt.ctrlKey = controlKeyDown;
return evt;
}
function triggerKeyEvent(element, eventType, keySequence, canBubble, controlKeyDown, altKeyDown, shiftKeyDown, metaKeyDown) {
var keycode = getKeyCodeFromKeySequence(keySequence);
canBubble = (typeof(canBubble) == undefined) ? true : canBubble;
if (element.fireEvent) {
var keyEvent = createEventObject(element, controlKeyDown, altKeyDown, shiftKeyDown, metaKeyDown);
keyEvent.keyCode = keycode;
element.fireEvent('on' + eventType, keyEvent);
}
else {
var evt;
if (window.KeyEvent) {
evt = document.createEvent('KeyEvents');
evt.initKeyEvent(eventType, true, true, window, controlKeyDown, altKeyDown, shiftKeyDown, metaKeyDown, keycode, keycode);
} else {
evt = document.createEvent('UIEvents');
evt.shiftKey = shiftKeyDown;
evt.metaKey = metaKeyDown;
evt.altKey = altKeyDown;
evt.ctrlKey = controlKeyDown;
evt.initUIEvent(eventType, true, true, window, 1);
evt.keyCode = keycode;
evt.which = keycode;
}
element.dispatchEvent(evt);
}
}
function removeLoadListener(element, command) {
LOG.debug('Removing loadListenter for ' + element + ', ' + command);
if (window.removeEventListener)
element.removeEventListener("load", command, true);
else if (window.detachEvent)
element.detachEvent("onload", command);
}
function addLoadListener(element, command) {
LOG.debug('Adding loadListenter for ' + element + ', ' + command);
var augmentedCommand = function() {
command.call(this, element);
}
if (window.addEventListener && !browserVersion.isOpera)
element.addEventListener("load", augmentedCommand, true);
else if (window.attachEvent)
element.attachEvent("onload", augmentedCommand);
}
/**
* Override the broken getFunctionName() method from JsUnit
* This file must be loaded _after_ the jsunitCore.js
*/
function getFunctionName(aFunction) {
var regexpResult = aFunction.toString().match(/function (\w*)/);
if (regexpResult && regexpResult[1]) {
return regexpResult[1];
}
return 'anonymous';
}
function getDocumentBase(doc) {
var bases = document.getElementsByTagName("base");
if (bases && bases.length && bases[0].href) {
return bases[0].href;
}
return "";
}
function getTagName(element) {
var tagName;
if (element && element.tagName && element.tagName.toLowerCase) {
tagName = element.tagName.toLowerCase();
}
return tagName;
}
function selArrayToString(a) {
if (isArray(a)) {
// DGF copying the array, because the array-like object may be a non-modifiable nodelist
var retval = [];
for (var i = 0; i < a.length; i++) {
var item = a[i];
var replaced = new String(item).replace(/([,\\])/g, '\\$1');
retval[i] = replaced;
}
return retval;
}
return new String(a);
}
function isArray(x) {
return ((typeof x) == "object") && (x["length"] != null);
}
function absolutify(url, baseUrl) {
/** returns a relative url in its absolute form, given by baseUrl.
*
* This function is a little odd, because it can take baseUrls that
* aren't necessarily directories. It uses the same rules as the HTML
* <base> tag; if the baseUrl doesn't end with "/", we'll assume
* that it points to a file, and strip the filename off to find its
* base directory.
*
* So absolutify("foo", "http://x/bar") will return "http://x/foo" (stripping off bar),
* whereas absolutify("foo", "http://x/bar/") will return "http://x/bar/foo" (preserving bar).
* Naturally absolutify("foo", "http://x") will return "http://x/foo", appropriately.
*
* @param url the url to make absolute; if this url is already absolute, we'll just return that, unchanged
* @param baseUrl the baseUrl from which we'll absolutify, following the rules above.
* @return 'url' if it was already absolute, or the absolutized version of url if it was not absolute.
*/
// DGF isn't there some library we could use for this?
if (/^\w+:/.test(url)) {
// it's already absolute
return url;
}
var loc;
try {
loc = parseUrl(baseUrl);
} catch (e) {
// is it an absolute windows file path? let's play the hero in that case
if (/^\w:\\/.test(baseUrl)) {
baseUrl = "file:///" + baseUrl.replace(/\\/g, "/");
loc = parseUrl(baseUrl);
} else {
throw new SeleniumError("baseUrl wasn't absolute: " + baseUrl);
}
}
loc.search = null;
loc.hash = null;
// if url begins with /, then that's the whole pathname
if (/^\//.test(url)) {
loc.pathname = url;
var result = reassembleLocation(loc);
return result;
}
// if pathname is null, then we'll just append "/" + the url
if (!loc.pathname) {
loc.pathname = "/" + url;
var result = reassembleLocation(loc);
return result;
}
// if pathname ends with /, just append url
if (/\/$/.test(loc.pathname)) {
loc.pathname += url;
var result = reassembleLocation(loc);
return result;
}
// if we're here, then the baseUrl has a pathname, but it doesn't end with /
// in that case, we replace everything after the final / with the relative url
loc.pathname = loc.pathname.replace(/[^\/\\]+$/, url);
var result = reassembleLocation(loc);
return result;
}
var URL_REGEX = /^((\w+):\/\/)(([^:]+):?([^@]+)?@)?([^\/\?:]*):?(\d+)?(\/?[^\?#]+)?\??([^#]+)?#?(.+)?/;
function parseUrl(url) {
var fields = ['url', null, 'protocol', null, 'username', 'password', 'host', 'port', 'pathname', 'search', 'hash'];
var result = URL_REGEX.exec(url);
if (!result) {
throw new SeleniumError("Invalid URL: " + url);
}
var loc = new Object();
for (var i = 0; i < fields.length; i++) {
var field = fields[i];
if (field == null) {
continue;
}
loc[field] = result[i];
}
return loc;
}
function reassembleLocation(loc) {
if (!loc.protocol) {
throw new Error("Not a valid location object: " + o2s(loc));
}
var protocol = loc.protocol;
protocol = protocol.replace(/:$/, "");
var url = protocol + "://";
if (loc.username) {
url += loc.username;
if (loc.password) {
url += ":" + loc.password;
}
url += "@";
}
if (loc.host) {
url += loc.host;
}
if (loc.port) {
url += ":" + loc.port;
}
if (loc.pathname) {
url += loc.pathname;
}
if (loc.search) {
url += "?" + loc.search;
}
if (loc.hash) {
var hash = loc.hash;
hash = loc.hash.replace(/^#/, "");
url += "#" + hash;
}
return url;
}
function canonicalize(url) {
var tempLink = window.document.createElement("link");
tempLink.href = url; // this will canonicalize the href on most browsers
var loc = parseUrl(tempLink.href)
if (!/\/\.\.\//.test(loc.pathname)) {
return tempLink.href;
}
// didn't work... let's try it the hard way
var originalParts = loc.pathname.split("/");
var newParts = [];
newParts.push(originalParts.shift());
for (var i = 0; i < originalParts.length; i++) {
var part = originalParts[i];
if (".." == part) {
newParts.pop();
continue;
}
newParts.push(part);
}
loc.pathname = newParts.join("/");
return reassembleLocation(loc);
}
function extractExceptionMessage(ex) {
if (ex == null) return "null exception";
if (ex.message != null) return ex.message;
if (ex.toString && ex.toString() != null) return ex.toString();
}
function describe(object, delimiter) {
var props = new Array();
for (var prop in object) {
try {
props.push(prop + " -> " + object[prop]);
} catch (e) {
props.push(prop + " -> [htmlutils: ack! couldn't read this property! (Permission Denied?)]");
}
}
return props.join(delimiter || '\n');
}
var PatternMatcher = function(pattern) {
this.selectStrategy(pattern);
};
PatternMatcher.prototype = {
selectStrategy: function(pattern) {
this.pattern = pattern;
var strategyName = 'glob';
// by default
if (/^([a-z-]+):(.*)/.test(pattern)) {
var possibleNewStrategyName = RegExp.$1;
var possibleNewPattern = RegExp.$2;
if (PatternMatcher.strategies[possibleNewStrategyName]) {
strategyName = possibleNewStrategyName;
pattern = possibleNewPattern;
}
}
var matchStrategy = PatternMatcher.strategies[strategyName];
if (!matchStrategy) {
throw new SeleniumError("cannot find PatternMatcher.strategies." + strategyName);
}
this.strategy = matchStrategy;
this.matcher = new matchStrategy(pattern);
},
matches: function(actual) {
return this.matcher.matches(actual + '');
// Note: appending an empty string avoids a Konqueror bug
}
};
/**
* A "static" convenience method for easy matching
*/
PatternMatcher.matches = function(pattern, actual) {
return new PatternMatcher(pattern).matches(actual);
};
PatternMatcher.strategies = {
/**
* Exact matching, e.g. "exact:***"
*/
exact: function(expected) {
this.expected = expected;
this.matches = function(actual) {
return actual == this.expected;
};
},
/**
* Match by regular expression, e.g. "regexp:^[0-9]+$"
*/
regexp: function(regexpString) {
this.regexp = new RegExp(regexpString);
this.matches = function(actual) {
return this.regexp.test(actual);
};
},
regex: function(regexpString) {
this.regexp = new RegExp(regexpString);
this.matches = function(actual) {
return this.regexp.test(actual);
};
},
/**
* "globContains" (aka "wildmat") patterns, e.g. "glob:one,two,*",
* but don't require a perfect match; instead succeed if actual
* contains something that matches globString.
* Making this distinction is motivated by a bug in IE6 which
* leads to the browser hanging if we implement *TextPresent tests
* by just matching against a regular expression beginning and
* ending with ".*". The globcontains strategy allows us to satisfy
* the functional needs of the *TextPresent ops more efficiently
* and so avoid running into this IE6 freeze.
*/
globContains: function(globString) {
this.regexp = new RegExp(PatternMatcher.regexpFromGlobContains(globString));
this.matches = function(actual) {
return this.regexp.test(actual);
};
},
/**
* "glob" (aka "wildmat") patterns, e.g. "glob:one,two,*"
*/
glob: function(globString) {
this.regexp = new RegExp(PatternMatcher.regexpFromGlob(globString));
this.matches = function(actual) {
return this.regexp.test(actual);
};
}
};
PatternMatcher.convertGlobMetaCharsToRegexpMetaChars = function(glob) {
var re = glob;
re = re.replace(/([.^$+(){}\[\]\\|])/g, "\\$1");
re = re.replace(/\?/g, "(.|[\r\n])");
re = re.replace(/\*/g, "(.|[\r\n])*");
return re;
};
PatternMatcher.regexpFromGlobContains = function(globContains) {
return PatternMatcher.convertGlobMetaCharsToRegexpMetaChars(globContains);
};
PatternMatcher.regexpFromGlob = function(glob) {
return "^" + PatternMatcher.convertGlobMetaCharsToRegexpMetaChars(glob) + "$";
};
var Assert = {
fail: function(message) {
throw new AssertionFailedError(message);
},
/*
* Assert.equals(comment?, expected, actual)
*/
equals: function() {
var args = new AssertionArguments(arguments);
if (args.expected === args.actual) {
return;
}
Assert.fail(args.comment +
"Expected '" + args.expected +
"' but was '" + args.actual + "'");
},
/*
* Assert.matches(comment?, pattern, actual)
*/
matches: function() {
var args = new AssertionArguments(arguments);
if (PatternMatcher.matches(args.expected, args.actual)) {
return;
}
Assert.fail(args.comment +
"Actual value '" + args.actual +
"' did not match '" + args.expected + "'");
},
/*
* Assert.notMtches(comment?, pattern, actual)
*/
notMatches: function() {
var args = new AssertionArguments(arguments);
if (!PatternMatcher.matches(args.expected, args.actual)) {
return;
}
Assert.fail(args.comment +
"Actual value '" + args.actual +
"' did match '" + args.expected + "'");
}
};
// Preprocess the arguments to allow for an optional comment.
function AssertionArguments(args) {
if (args.length == 2) {
this.comment = "";
this.expected = args[0];
this.actual = args[1];
} else {
this.comment = args[0] + "; ";
this.expected = args[1];
this.actual = args[2];
}
}
function AssertionFailedError(message) {
this.isAssertionFailedError = true;
this.isSeleniumError = true;
this.message = message;
this.failureMessage = message;
}
function SeleniumError(message) {
var error = new Error(message);
if (typeof(arguments.caller) != 'undefined') { // IE, not ECMA
var result = '';
for (var a = arguments.caller; a != null; a = a.caller) {
result += '> ' + a.callee.toString() + '\n';
if (a.caller == a) {
result += '*';
break;
}
}
error.stack = result;
}
error.isSeleniumError = true;
return error;
}
function highlight(element) {
var highLightColor = "yellow";
if (element.originalColor == undefined) { // avoid picking up highlight
element.originalColor = elementGetStyle(element, "background-color");
}
elementSetStyle(element, {"backgroundColor" : highLightColor});
window.setTimeout(function() {
try {
//if element is orphan, probably page of it has already gone, so ignore
if (!element.parentNode) {
return;
}
elementSetStyle(element, {"backgroundColor" : element.originalColor});
} catch (e) {} // DGF unhighlighting is very dangerous and low priority
}, 200);
}
// for use from vs.2003 debugger
function o2s(obj) {
var s = "";
for (key in obj) {
var line = key + "->" + obj[key];
line.replace("\n", " ");
s += line + "\n";
}
return s;
}
var seenReadyStateWarning = false;
function openSeparateApplicationWindow(url, suppressMozillaWarning) {
// resize the Selenium window itself
window.resizeTo(1200, 500);
window.moveTo(window.screenX, 0);
var appWindow = window.open(url + '?start=true', 'main');
if (appWindow == null) {
var errorMessage = "Couldn't open app window; is the pop-up blocker enabled?"
LOG.error(errorMessage);
throw new Error("Couldn't open app window; is the pop-up blocker enabled?");
}
try {
var windowHeight = 500;
if (window.outerHeight) {
windowHeight = window.outerHeight;
} else if (document.documentElement && document.documentElement.offsetHeight) {
windowHeight = document.documentElement.offsetHeight;
}
if (window.screenLeft && !window.screenX) window.screenX = window.screenLeft;
if (window.screenTop && !window.screenY) window.screenY = window.screenTop;
appWindow.resizeTo(1200, screen.availHeight - windowHeight - 60);
appWindow.moveTo(window.screenX, window.screenY + windowHeight + 25);
} catch (e) {
LOG.error("Couldn't resize app window");
LOG.exception(e);
}
if (!suppressMozillaWarning && window.document.readyState == null && !seenReadyStateWarning) {
alert("Beware! Mozilla bug 300992 means that we can't always reliably detect when a new page has loaded. Install the Selenium IDE extension or the readyState extension available from selenium.openqa.org to make page load detection more reliable.");
seenReadyStateWarning = true;
}
return appWindow;
}
var URLConfiguration = classCreate();
objectExtend(URLConfiguration.prototype, {
initialize: function() {
},
_isQueryParameterTrue: function (name) {
var parameterValue = this._getQueryParameter(name);
if (parameterValue == null) return false;
if (parameterValue.toLowerCase() == "true") return true;
if (parameterValue.toLowerCase() == "on") return true;
return false;
},
_getQueryParameter: function(searchKey) {
var str = this.queryString
if (str == null) return null;
var clauses = str.split('&');
for (var i = 0; i < clauses.length; i++) {
var keyValuePair = clauses[i].split('=', 2);
var key = unescape(keyValuePair[0]);
if (key == searchKey) {
return unescape(keyValuePair[1]);
}
}
return null;
},
_extractArgs: function() {
var str = SeleniumHTARunner.commandLine;
if (str == null || str == "") return new Array();
var matches = str.match(/(?:\"([^\"]+)\"|(?!\"([^\"]+)\")(\S+))/g);
// We either want non quote stuff ([^"]+) surrounded by quotes
// or we want to look-ahead, see that the next character isn't
// a quoted argument, and then grab all the non-space stuff
// this will return for the line: "foo" bar
// the results "\"foo\"" and "bar"
// So, let's unquote the quoted arguments:
var args = new Array;
for (var i = 0; i < matches.length; i++) {
args[i] = matches[i];
args[i] = args[i].replace(/^"(.*)"$/, "$1");
}
return args;
},
isMultiWindowMode:function() {
return this._isQueryParameterTrue('multiWindow');
},
getBaseUrl:function() {
return this._getQueryParameter('baseUrl');
}
});
function safeScrollIntoView(element) {
if (element.scrollIntoView) {
element.scrollIntoView(false);
return;
}
// TODO: work out how to scroll browsers that don't support
// scrollIntoView (like Konqueror)
} | zc.selenium | /zc.selenium-1.2.1.tar.gz/zc.selenium-1.2.1/src/zc/selenium/resources/scripts/htmlutils.js | htmlutils.js |
passColor = "#cfffcf";
failColor = "#ffcfcf";
errorColor = "#ffffff";
workingColor = "#DEE7EC";
doneColor = "#FFFFCC";
var injectedSessionId;
var cmd1 = document.createElement("div");
var cmd2 = document.createElement("div");
var cmd3 = document.createElement("div");
var cmd4 = document.createElement("div");
var postResult = "START";
var debugMode = false;
var relayToRC = null;
var proxyInjectionMode = false;
var uniqueId = 'sel_' + Math.round(100000 * Math.random());
var seleniumSequenceNumber = 0;
var RemoteRunnerOptions = classCreate();
objectExtend(RemoteRunnerOptions.prototype, URLConfiguration.prototype);
objectExtend(RemoteRunnerOptions.prototype, {
initialize: function() {
this._acquireQueryString();
},
isDebugMode: function() {
return this._isQueryParameterTrue("debugMode");
},
getContinue: function() {
return this._getQueryParameter("continue");
},
getDriverUrl: function() {
return this._getQueryParameter("driverUrl");
},
getSessionId: function() {
return this._getQueryParameter("sessionId");
},
_acquireQueryString: function () {
if (this.queryString) return;
if (browserVersion.isHTA) {
var args = this._extractArgs();
if (args.length < 2) return null;
this.queryString = args[1];
} else if (proxyInjectionMode) {
this.queryString = window.location.search.substr(1);
} else {
this.queryString = top.location.search.substr(1);
}
}
});
var runOptions;
function runSeleniumTest() {
runOptions = new RemoteRunnerOptions();
var testAppWindow;
if (runOptions.isMultiWindowMode()) {
testAppWindow = openSeparateApplicationWindow('Blank.html', true);
} else if (sel$('selenium_myiframe') != null) {
var myiframe = sel$('selenium_myiframe');
if (myiframe) {
testAppWindow = myiframe.contentWindow;
}
}
else {
proxyInjectionMode = true;
testAppWindow = window;
}
selenium = Selenium.createForWindow(testAppWindow, proxyInjectionMode);
if (runOptions.getBaseUrl()) {
selenium.browserbot.baseUrl = runOptions.getBaseUrl();
}
if (!debugMode) {
debugMode = runOptions.isDebugMode();
}
if (proxyInjectionMode) {
LOG.logHook = logToRc;
selenium.browserbot._modifyWindow(testAppWindow);
}
else if (debugMode) {
LOG.logHook = logToRc;
}
window.selenium = selenium;
commandFactory = new CommandHandlerFactory();
commandFactory.registerAll(selenium);
currentTest = new RemoteRunner(commandFactory);
if (document.getElementById("commandList") != null) {
document.getElementById("commandList").appendChild(cmd4);
document.getElementById("commandList").appendChild(cmd3);
document.getElementById("commandList").appendChild(cmd2);
document.getElementById("commandList").appendChild(cmd1);
}
var doContinue = runOptions.getContinue();
if (doContinue != null) postResult = "OK";
currentTest.start();
}
function buildDriverUrl() {
var driverUrl = runOptions.getDriverUrl();
if (driverUrl != null) {
return driverUrl;
}
var s = window.location.href
var slashPairOffset = s.indexOf("//") + "//".length
var pathSlashOffset = s.substring(slashPairOffset).indexOf("/")
return s.substring(0, slashPairOffset + pathSlashOffset) + "/selenium-server/driver/";
//return "http://localhost" + uniqueId + "/selenium-server/driver/";
}
function logToRc(logLevel, message) {
if (debugMode) {
if (logLevel == null) {
logLevel = "debug";
}
sendToRCAndForget("logLevel=" + logLevel + ":" + message.replace(/[\n\r\015]/g, " ") + "\n", "logging=true");
}
}
function serializeString(name, s) {
return name + "=unescape(\"" + escape(s) + "\");";
}
function serializeObject(name, x)
{
var s = '';
if (isArray(x))
{
s = name + "=new Array(); ";
var len = x["length"];
for (var j = 0; j < len; j++)
{
s += serializeString(name + "[" + j + "]", x[j]);
}
}
else if (typeof x == "string")
{
s = serializeString(name, x);
}
else
{
throw "unrecognized object not encoded: " + name + "(" + x + ")";
}
return s;
}
function relayBotToRC(s) {
}
// seems like no one uses this, but in fact it is called using eval from server-side PI mode code; however,
// because multiple names can map to the same popup, assigning a single name confuses matters sometimes;
// thus, I'm disabling this for now. -Nelson 10/21/06
function setSeleniumWindowName(seleniumWindowName) {
//selenium.browserbot.getCurrentWindow()['seleniumWindowName'] = seleniumWindowName;
}
RemoteRunner = classCreate();
objectExtend(RemoteRunner.prototype, new TestLoop());
objectExtend(RemoteRunner.prototype, {
initialize : function(commandFactory) {
this.commandFactory = commandFactory;
this.requiresCallBack = true;
this.commandNode = null;
this.xmlHttpForCommandsAndResults = null;
},
nextCommand : function() {
var urlParms = "";
if (postResult == "START") {
urlParms += "seleniumStart=true";
}
this.xmlHttpForCommandsAndResults = XmlHttp.create();
sendToRC(postResult, urlParms, fnBind(this._HandleHttpResponse, this), this.xmlHttpForCommandsAndResults);
},
commandStarted : function(command) {
this.commandNode = document.createElement("div");
var cmdText = command.command + '(';
if (command.target != null && command.target != "") {
cmdText += command.target;
if (command.value != null && command.value != "") {
cmdText += ', ' + command.value;
}
}
cmdText += ")";
if (cmdText.length >40) {
cmdText = cmdText.substring(0,40);
cmdText += "...";
}
this.commandNode.appendChild(document.createTextNode(cmdText));
this.commandNode.style.backgroundColor = workingColor;
if (document.getElementById("commandList") != null) {
document.getElementById("commandList").removeChild(cmd1);
document.getElementById("commandList").removeChild(cmd2);
document.getElementById("commandList").removeChild(cmd3);
document.getElementById("commandList").removeChild(cmd4);
cmd4 = cmd3;
cmd3 = cmd2;
cmd2 = cmd1;
cmd1 = this.commandNode;
document.getElementById("commandList").appendChild(cmd4);
document.getElementById("commandList").appendChild(cmd3);
document.getElementById("commandList").appendChild(cmd2);
document.getElementById("commandList").appendChild(cmd1);
}
},
commandComplete : function(result) {
if (result.failed) {
if (postResult == "CONTINUATION") {
currentTest.aborted = true;
}
postResult = result.failureMessage;
this.commandNode.title = result.failureMessage;
this.commandNode.style.backgroundColor = failColor;
} else if (result.passed) {
postResult = "OK";
this.commandNode.style.backgroundColor = passColor;
} else {
if (result.result == null) {
postResult = "OK";
} else {
var actualResult = result.result;
actualResult = selArrayToString(actualResult);
postResult = "OK," + actualResult;
}
this.commandNode.style.backgroundColor = doneColor;
}
},
commandError : function(message) {
postResult = "ERROR: " + message;
this.commandNode.style.backgroundColor = errorColor;
this.commandNode.title = message;
},
testComplete : function() {
window.status = "Selenium Tests Complete, for this Test"
// Continue checking for new results
this.continueTest();
postResult = "START";
},
_HandleHttpResponse : function() {
// When request is completed
if (this.xmlHttpForCommandsAndResults.readyState == 4) {
// OK
if (this.xmlHttpForCommandsAndResults.status == 200) {
if (this.xmlHttpForCommandsAndResults.responseText=="") {
LOG.error("saw blank string xmlHttpForCommandsAndResults.responseText");
return;
}
var command = this._extractCommand(this.xmlHttpForCommandsAndResults);
this.currentCommand = command;
this.continueTestAtCurrentCommand();
}
// Not OK
else {
var s = 'xmlHttp returned: ' + this.xmlHttpForCommandsAndResults.status + ": " + this.xmlHttpForCommandsAndResults.statusText;
LOG.error(s);
this.currentCommand = null;
setTimeout(fnBind(this.continueTestAtCurrentCommand, this), 2000);
}
}
},
_extractCommand : function(xmlHttp) {
var command;
try {
var re = new RegExp("^(.*?)\n((.|[\r\n])*)");
if (re.exec(xmlHttp.responseText)) {
command = RegExp.$1;
var rest = RegExp.$2;
rest = rest.trim();
if (rest) {
eval(rest);
}
}
else {
command = xmlHttp.responseText;
}
} catch (e) {
alert('could not get responseText: ' + e.message);
}
if (command.substr(0, '|testComplete'.length) == '|testComplete') {
return null;
}
return this._createCommandFromRequest(command);
},
_delay : function(millis) {
var startMillis = new Date();
while (true) {
milli = new Date();
if (milli - startMillis > millis) {
break;
}
}
},
// Parses a URI query string into a SeleniumCommand object
_createCommandFromRequest : function(commandRequest) {
//decodeURIComponent doesn't strip plus signs
var processed = commandRequest.replace(/\+/g, "%20");
// strip trailing spaces
var processed = processed.replace(/\s+$/, "");
var vars = processed.split("&");
var cmdArgs = new Object();
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
cmdArgs[pair[0]] = pair[1];
}
var cmd = cmdArgs['cmd'];
var arg1 = cmdArgs['1'];
if (null == arg1) arg1 = "";
arg1 = decodeURIComponent(arg1);
var arg2 = cmdArgs['2'];
if (null == arg2) arg2 = "";
arg2 = decodeURIComponent(arg2);
if (cmd == null) {
throw new Error("Bad command request: " + commandRequest);
}
return new SeleniumCommand(cmd, arg1, arg2);
}
})
function sendToRC(dataToBePosted, urlParms, callback, xmlHttpObject, async) {
if (async == null) {
async = true;
}
if (xmlHttpObject == null) {
xmlHttpObject = XmlHttp.create();
}
var url = buildDriverUrl() + "?"
if (urlParms) {
url += urlParms;
}
url = addUrlParams(url);
url += "&sequenceNumber=" + seleniumSequenceNumber++;
var wrappingCallback;
if (callback == null) {
callback = function() {};
wrappingCallback = callback;
} else {
wrappingCallback = function() {
if (xmlHttpObject.readyState == 4) {
if (xmlHttpObject.status == 200) {
var retry = false;
if (typeof currentTest != 'undefined') {
var command = currentTest._extractCommand(xmlHttpObject);
//console.log("*********** " + command.command + " | " + command.target + " | " + command.value);
if (command.command == 'retryLast') {
retry = true;
}
}
if (retry) {
setTimeout(fnBind(function() {
sendToRC("RETRY", "retry=true", callback, xmlHttpObject, async);
}, this), 1000);
} else {
callback();
}
}
}
}
}
var postedData = "postedData=" + encodeURIComponent(dataToBePosted);
//xmlHttpObject.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttpObject.open("POST", url, async);
xmlHttpObject.onreadystatechange = wrappingCallback;
xmlHttpObject.send(postedData);
return null;
}
function addUrlParams(url) {
return url + "&localFrameAddress=" + (proxyInjectionMode ? makeAddressToAUTFrame() : "top")
+ getSeleniumWindowNameURLparameters()
+ "&uniqueId=" + uniqueId
+ buildDriverParams() + preventBrowserCaching()
}
function sendToRCAndForget(dataToBePosted, urlParams) {
var url;
if (!(browserVersion.isChrome || browserVersion.isHTA)) {
// DGF we're behind a proxy, so we can send our logging message to literally any host, to avoid 2-connection limit
var protocol = "http:";
if (window.location.protocol == "https:") {
// DGF if we're in HTTPS, use another HTTPS url to avoid security warning
protocol = "https:";
}
// we don't choose a super large random value, but rather 1 - 16, because this matches with the pre-computed
// tunnels waiting on the Selenium Server side. This gives us higher throughput than the two-connection-per-host
// limitation, but doesn't require we generate an extremely large ammount of fake SSL certs either.
url = protocol + "//" + Math.floor(Math.random()* 16 + 1) + ".selenium.doesnotexist/selenium-server/driver/?" + urlParams;
} else {
url = buildDriverUrl() + "?" + urlParams;
}
url = addUrlParams(url);
var method = "GET";
if (method == "POST") {
// DGF submit a request using an iframe; we can't see the response, but we don't need to
// TODO not using this mechanism because it screws up back-button
var loggingForm = document.createElement("form");
loggingForm.method = "POST";
loggingForm.action = url;
loggingForm.target = "seleniumLoggingFrame";
var postedDataInput = document.createElement("input");
postedDataInput.type = "hidden";
postedDataInput.name = "postedData";
postedDataInput.value = dataToBePosted;
loggingForm.appendChild(postedDataInput);
document.body.appendChild(loggingForm);
loggingForm.submit();
document.body.removeChild(loggingForm);
} else {
var postedData = "&postedData=" + encodeURIComponent(dataToBePosted);
var scriptTag = document.createElement("script");
scriptTag.src = url + postedData;
document.body.appendChild(scriptTag);
document.body.removeChild(scriptTag);
}
}
function buildDriverParams() {
var params = "";
var sessionId = runOptions.getSessionId();
if (sessionId == undefined) {
sessionId = injectedSessionId;
}
if (sessionId != undefined) {
params = params + "&sessionId=" + sessionId;
}
return params;
}
function preventBrowserCaching() {
var t = (new Date()).getTime();
return "&counterToMakeURsUniqueAndSoStopPageCachingInTheBrowser=" + t;
}
//
// Return URL parameters pertaining to the name(s?) of the current window
//
// In selenium, the main (i.e., first) window's name is a blank string.
//
// Additional pop-ups are associated with either 1.) the name given by the 2nd parameter to window.open, or 2.) the name of a
// property on the opening window which points at the window.
//
// An example of #2: if window X contains JavaScript as follows:
//
// var windowABC = window.open(...)
//
// Note that the example JavaScript above is equivalent to
//
// window["windowABC"] = window.open(...)
//
function getSeleniumWindowNameURLparameters() {
var w = (proxyInjectionMode ? selenium.browserbot.getCurrentWindow() : window).top;
var s = "&seleniumWindowName=";
if (w.opener == null) {
return s;
}
if (w["seleniumWindowName"] == null) {
if (w.name) {
w["seleniumWindowName"] = w.name;
} else {
w["seleniumWindowName"] = 'generatedSeleniumWindowName_' + Math.round(100000 * Math.random());
}
}
s += w["seleniumWindowName"];
var windowOpener = w.opener;
for (key in windowOpener) {
var val = null;
try {
val = windowOpener[key];
}
catch(e) {
}
if (val==w) {
s += "&jsWindowNameVar=" + key; // found a js variable in the opener referring to this window
}
}
return s;
}
// construct a JavaScript expression which leads to my frame (i.e., the frame containing the window
// in which this code is operating)
function makeAddressToAUTFrame(w, frameNavigationalJSexpression)
{
if (w == null)
{
w = top;
frameNavigationalJSexpression = "top";
}
if (w == selenium.browserbot.getCurrentWindow())
{
return frameNavigationalJSexpression;
}
for (var j = 0; j < w.frames.length; j++)
{
var t = makeAddressToAUTFrame(w.frames[j], frameNavigationalJSexpression + ".frames[" + j + "]");
if (t != null)
{
return t;
}
}
return null;
}
Selenium.prototype.doSetContext = function(context) {
/**
* Writes a message to the status bar and adds a note to the browser-side
* log.
*
* @param context
* the message to be sent to the browser
*/
//set the current test title
var ctx = document.getElementById("context");
if (ctx != null) {
ctx.innerHTML = context;
}
};
Selenium.prototype.doCaptureScreenshot = function(filename) {
/**
* Captures a PNG screenshot to the specified file.
*
* @param filename the absolute path to the file to be written, e.g. "c:\blah\screenshot.png"
*/
// This doesn't really do anything on the JS side; we let the Selenium Server take care of this for us!
}; | zc.selenium | /zc.selenium-1.2.1.tar.gz/zc.selenium-1.2.1/src/zc/selenium/resources/scripts/selenium-remoterunner.js | selenium-remoterunner.js |
* This script provides the Javascript API to drive the test application contained within
* a Browser Window.
* TODO:
* Add support for more events (keyboard and mouse)
* Allow to switch "user-entry" mode from mouse-based to keyboard-based, firing different
* events in different modes.
*/
// The window to which the commands will be sent. For example, to click on a
// popup window, first select that window, and then do a normal click command.
var BrowserBot = function(topLevelApplicationWindow) {
this.topWindow = topLevelApplicationWindow;
this.topFrame = this.topWindow;
this.baseUrl=window.location.href;
// the buttonWindow is the Selenium window
// it contains the Run/Pause buttons... this should *not* be the AUT window
this.buttonWindow = window;
this.currentWindow = this.topWindow;
this.currentWindowName = null;
this.allowNativeXpath = true;
// We need to know this in advance, in case the frame closes unexpectedly
this.isSubFrameSelected = false;
this.altKeyDown = false;
this.controlKeyDown = false;
this.shiftKeyDown = false;
this.metaKeyDown = false;
this.modalDialogTest = null;
this.recordedAlerts = new Array();
this.recordedConfirmations = new Array();
this.recordedPrompts = new Array();
this.openedWindows = {};
this.nextConfirmResult = true;
this.nextPromptResult = '';
this.newPageLoaded = false;
this.pageLoadError = null;
this.shouldHighlightLocatedElement = false;
this.uniqueId = "seleniumMarker" + new Date().getTime();
this.pollingForLoad = new Object();
this.permDeniedCount = new Object();
this.windowPollers = new Array();
// DGF for backwards compatibility
this.browserbot = this;
var self = this;
objectExtend(this, PageBot.prototype);
this._registerAllLocatorFunctions();
this.recordPageLoad = function(elementOrWindow) {
LOG.debug("Page load detected");
try {
if (elementOrWindow.location && elementOrWindow.location.href) {
LOG.debug("Page load location=" + elementOrWindow.location.href);
} else if (elementOrWindow.contentWindow && elementOrWindow.contentWindow.location && elementOrWindow.contentWindow.location.href) {
LOG.debug("Page load location=" + elementOrWindow.contentWindow.location.href);
} else {
LOG.debug("Page load location unknown, current window location=" + this.getCurrentWindow(true).location);
}
} catch (e) {
LOG.error("Caught an exception attempting to log location; this should get noticed soon!");
LOG.exception(e);
self.pageLoadError = e;
return;
}
self.newPageLoaded = true;
};
this.isNewPageLoaded = function() {
if (this.pageLoadError) {
LOG.error("isNewPageLoaded found an old pageLoadError");
var e = this.pageLoadError;
this.pageLoadError = null;
throw e;
}
return self.newPageLoaded;
};
};
// DGF PageBot exists for backwards compatibility with old user-extensions
var PageBot = function(){};
BrowserBot.createForWindow = function(window, proxyInjectionMode) {
var browserbot;
LOG.debug('createForWindow');
LOG.debug("browserName: " + browserVersion.name);
LOG.debug("userAgent: " + navigator.userAgent);
if (browserVersion.isIE) {
browserbot = new IEBrowserBot(window);
}
else if (browserVersion.isKonqueror) {
browserbot = new KonquerorBrowserBot(window);
}
else if (browserVersion.isOpera) {
browserbot = new OperaBrowserBot(window);
}
else if (browserVersion.isSafari) {
browserbot = new SafariBrowserBot(window);
}
else {
// Use mozilla by default
browserbot = new MozillaBrowserBot(window);
}
// getCurrentWindow has the side effect of modifying it to handle page loads etc
browserbot.proxyInjectionMode = proxyInjectionMode;
browserbot.getCurrentWindow(); // for modifyWindow side effect. This is not a transparent style
return browserbot;
};
// todo: rename? This doesn't actually "do" anything.
BrowserBot.prototype.doModalDialogTest = function(test) {
this.modalDialogTest = test;
};
BrowserBot.prototype.cancelNextConfirmation = function(result) {
this.nextConfirmResult = result;
};
BrowserBot.prototype.setNextPromptResult = function(result) {
this.nextPromptResult = result;
};
BrowserBot.prototype.hasAlerts = function() {
return (this.recordedAlerts.length > 0);
};
BrowserBot.prototype.relayBotToRC = function(s) {
// DGF need to do this funny trick to see if we're in PI mode, because
// "this" might be the window, rather than the browserbot (e.g. during window.alert)
var piMode = this.proxyInjectionMode;
if (!piMode) {
if (typeof(selenium) != "undefined") {
piMode = selenium.browserbot && selenium.browserbot.proxyInjectionMode;
}
}
if (piMode) {
this.relayToRC("selenium." + s);
}
};
BrowserBot.prototype.relayToRC = function(name) {
var object = eval(name);
var s = 'state:' + serializeObject(name, object) + "\n";
sendToRC(s,"state=true");
}
BrowserBot.prototype.resetPopups = function() {
this.recordedAlerts = [];
this.recordedConfirmations = [];
this.recordedPrompts = [];
}
BrowserBot.prototype.getNextAlert = function() {
var t = this.recordedAlerts.shift();
this.relayBotToRC("browserbot.recordedAlerts");
return t;
};
BrowserBot.prototype.hasConfirmations = function() {
return (this.recordedConfirmations.length > 0);
};
BrowserBot.prototype.getNextConfirmation = function() {
var t = this.recordedConfirmations.shift();
this.relayBotToRC("browserbot.recordedConfirmations");
return t;
};
BrowserBot.prototype.hasPrompts = function() {
return (this.recordedPrompts.length > 0);
};
BrowserBot.prototype.getNextPrompt = function() {
var t = this.recordedPrompts.shift();
this.relayBotToRC("browserbot.recordedPrompts");
return t;
};
/* Fire a mouse event in a browser-compatible manner */
BrowserBot.prototype.triggerMouseEvent = function(element, eventType, canBubble, clientX, clientY) {
clientX = clientX ? clientX : 0;
clientY = clientY ? clientY : 0;
LOG.debug("triggerMouseEvent assumes setting screenX and screenY to 0 is ok");
var screenX = 0;
var screenY = 0;
canBubble = (typeof(canBubble) == undefined) ? true : canBubble;
if (element.fireEvent) {
var evt = createEventObject(element, this.controlKeyDown, this.altKeyDown, this.shiftKeyDown, this.metaKeyDown);
evt.detail = 0;
evt.button = 1;
evt.relatedTarget = null;
if (!screenX && !screenY && !clientX && !clientY && !this.controlKeyDown && !this.altKeyDown && !this.shiftKeyDown && !this.metaKeyDown) {
element.fireEvent('on' + eventType);
}
else {
evt.screenX = screenX;
evt.screenY = screenY;
evt.clientX = clientX;
evt.clientY = clientY;
// when we go this route, window.event is never set to contain the event we have just created.
// ideally we could just slide it in as follows in the try-block below, but this normally
// doesn't work. This is why I try to avoid this code path, which is only required if we need to
// set attributes on the event (e.g., clientX).
try {
window.event = evt;
}
catch(e) {
// getting an "Object does not support this action or property" error. Save the event away
// for future reference.
// TODO: is there a way to update window.event?
// work around for http://jira.openqa.org/browse/SEL-280 -- make the event available somewhere:
selenium.browserbot.getCurrentWindow().selenium_event = evt;
}
element.fireEvent('on' + eventType, evt);
}
}
else {
var evt = document.createEvent('MouseEvents');
if (evt.initMouseEvent)
{
//Safari
evt.initMouseEvent(eventType, canBubble, true, document.defaultView, 1, screenX, screenY, clientX, clientY,
this.controlKeyDown, this.altKeyDown, this.shiftKeyDown, this.metaKeyDown, 0, null);
}
else {
LOG.warn("element doesn't have initMouseEvent; firing an event which should -- but doesn't -- have other mouse-event related attributes here, as well as controlKeyDown, altKeyDown, shiftKeyDown, metaKeyDown");
evt.initEvent(eventType, canBubble, true);
evt.shiftKey = this.shiftKeyDown;
evt.metaKey = this.metaKeyDown;
evt.altKey = this.altKeyDown;
evt.ctrlKey = this.controlKeyDown;
}
element.dispatchEvent(evt);
}
}
BrowserBot.prototype._windowClosed = function(win) {
var c = win.closed;
if (c == null) return true;
return c;
};
BrowserBot.prototype._modifyWindow = function(win) {
// In proxyInjectionMode, have to suppress LOG calls in _modifyWindow to avoid an infinite loop
if (this._windowClosed(win)) {
if (!this.proxyInjectionMode) {
LOG.error("modifyWindow: Window was closed!");
}
return null;
}
if (!this.proxyInjectionMode) {
LOG.debug('modifyWindow ' + this.uniqueId + ":" + win[this.uniqueId]);
}
if (!win[this.uniqueId]) {
win[this.uniqueId] = 1;
this.modifyWindowToRecordPopUpDialogs(win, this);
}
// In proxyInjection mode, we have our own mechanism for detecting page loads
if (!this.proxyInjectionMode) {
this.modifySeparateTestWindowToDetectPageLoads(win);
}
if (win.frames && win.frames.length && win.frames.length > 0) {
for (var i = 0; i < win.frames.length; i++) {
try {
this._modifyWindow(win.frames[i]);
} catch (e) {} // we're just trying to be opportunistic; don't worry if this doesn't work out
}
}
return win;
};
BrowserBot.prototype.selectWindow = function(target) {
// TODO implement a locator syntax here
if (target && target != "null") {
try {
this._selectWindowByName(target);
}
catch (e) {
this._selectWindowByTitle(target);
}
} else {
this._selectTopWindow();
}
};
BrowserBot.prototype._selectTopWindow = function() {
this.currentWindowName = null;
this.currentWindow = this.topWindow;
this.topFrame = this.topWindow;
this.isSubFrameSelected = false;
}
BrowserBot.prototype._selectWindowByName = function(target) {
this.currentWindow = this.getWindowByName(target, false);
this.topFrame = this.currentWindow;
this.currentWindowName = target;
this.isSubFrameSelected = false;
}
BrowserBot.prototype._selectWindowByTitle = function(target) {
var windowName = this.getWindowNameByTitle(target);
if (!windowName) {
this._selectTopWindow();
} else {
this._selectWindowByName(windowName);
}
}
BrowserBot.prototype.selectFrame = function(target) {
if (target.indexOf("index=") == 0) {
target = target.substr(6);
var frame = this.getCurrentWindow().frames[target];
if (frame == null) {
throw new SeleniumError("Not found: frames["+index+"]");
}
if (!frame.document) {
throw new SeleniumError("frames["+index+"] is not a frame");
}
this.currentWindow = frame;
this.isSubFrameSelected = true;
}
else if (target == "relative=up") {
this.currentWindow = this.getCurrentWindow().parent;
this.isSubFrameSelected = (this._getFrameElement(this.currentWindow) != null);
} else if (target == "relative=top") {
this.currentWindow = this.topFrame;
this.isSubFrameSelected = false;
} else {
var frame = this.findElement(target);
if (frame == null) {
throw new SeleniumError("Not found: " + target);
}
// now, did they give us a frame or a frame ELEMENT?
var match = false;
if (frame.contentWindow) {
// this must be a frame element
if (browserVersion.isHTA) {
// stupid HTA bug; can't get in the front door
target = frame.contentWindow.name;
} else {
this.currentWindow = frame.contentWindow;
this.isSubFrameSelected = true;
match = true;
}
} else if (frame.document && frame.location) {
// must be an actual window frame
this.currentWindow = frame;
this.isSubFrameSelected = true;
match = true;
}
if (!match) {
// neither, let's loop through the frame names
var win = this.getCurrentWindow();
if (win && win.frames && win.frames.length) {
for (var i = 0; i < win.frames.length; i++) {
if (win.frames[i].name == target) {
this.currentWindow = win.frames[i];
this.isSubFrameSelected = true;
match = true;
break;
}
}
}
if (!match) {
throw new SeleniumError("Not a frame: " + target);
}
}
}
// modifies the window
this.getCurrentWindow();
};
BrowserBot.prototype.doesThisFrameMatchFrameExpression = function(currentFrameString, target) {
var isDom = false;
if (target.indexOf("dom=") == 0) {
target = target.substr(4);
isDom = true;
} else if (target.indexOf("index=") == 0) {
target = "frames[" + target.substr(6) + "]";
isDom = true;
}
var t;
try {
eval("t=" + currentFrameString + "." + target);
} catch (e) {
}
var autWindow = this.browserbot.getCurrentWindow();
if (t != null) {
try {
if (t.window == autWindow) {
return true;
}
if (t.window.uniqueId == autWindow.uniqueId) {
return true;
}
return false;
} catch (permDenied) {
// DGF if the windows are incomparable, they're probably not the same...
}
}
if (isDom) {
return false;
}
var currentFrame;
eval("currentFrame=" + currentFrameString);
if (target == "relative=up") {
if (currentFrame.window.parent == autWindow) {
return true;
}
return false;
}
if (target == "relative=top") {
if (currentFrame.window.top == autWindow) {
return true;
}
return false;
}
if (currentFrame.window == autWindow.parent) {
if (autWindow.name == target) {
return true;
}
try {
var element = this.findElement(target, currentFrame.window);
if (element.contentWindow == autWindow) {
return true;
}
} catch (e) {}
}
return false;
};
BrowserBot.prototype.openLocation = function(target) {
// We're moving to a new page - clear the current one
var win = this.getCurrentWindow();
LOG.debug("openLocation newPageLoaded = false");
this.newPageLoaded = false;
this.setOpenLocation(win, target);
};
BrowserBot.prototype.openWindow = function(url, windowID) {
if (url != "") {
url = absolutify(url, this.baseUrl);
}
if (browserVersion.isHTA) {
// in HTA mode, calling .open on the window interprets the url relative to that window
// we need to absolute-ize the URL to make it consistent
var child = this.getCurrentWindow().open(url, windowID);
selenium.browserbot.openedWindows[windowID] = child;
} else {
this.getCurrentWindow().open(url, windowID);
}
};
BrowserBot.prototype.setIFrameLocation = function(iframe, location) {
iframe.src = location;
};
BrowserBot.prototype.setOpenLocation = function(win, loc) {
loc = absolutify(loc, this.baseUrl);
if (browserVersion.isHTA) {
var oldHref = win.location.href;
win.location.href = loc;
var marker = null;
try {
marker = this.isPollingForLoad(win);
if (marker && win.location[marker]) {
win.location[marker] = false;
}
} catch (e) {} // DGF don't know why, but this often fails
} else {
win.location.href = loc;
}
};
BrowserBot.prototype.getCurrentPage = function() {
return this;
};
BrowserBot.prototype.modifyWindowToRecordPopUpDialogs = function(windowToModify, browserBot) {
var self = this;
windowToModify.alert = function(alert) {
browserBot.recordedAlerts.push(alert);
self.relayBotToRC.call(self, "browserbot.recordedAlerts");
};
windowToModify.confirm = function(message) {
browserBot.recordedConfirmations.push(message);
var result = browserBot.nextConfirmResult;
browserBot.nextConfirmResult = true;
self.relayBotToRC.call(self, "browserbot.recordedConfirmations");
return result;
};
windowToModify.prompt = function(message) {
browserBot.recordedPrompts.push(message);
var result = !browserBot.nextConfirmResult ? null : browserBot.nextPromptResult;
browserBot.nextConfirmResult = true;
browserBot.nextPromptResult = '';
self.relayBotToRC.call(self, "browserbot.recordedPrompts");
return result;
};
// Keep a reference to all popup windows by name
// note that in IE the "windowName" argument must be a valid javascript identifier, it seems.
var originalOpen = windowToModify.open;
var originalOpenReference;
if (browserVersion.isHTA) {
originalOpenReference = 'selenium_originalOpen' + new Date().getTime();
windowToModify[originalOpenReference] = windowToModify.open;
}
var isHTA = browserVersion.isHTA;
var newOpen = function(url, windowName, windowFeatures, replaceFlag) {
var myOriginalOpen = originalOpen;
if (isHTA) {
myOriginalOpen = this[originalOpenReference];
}
var openedWindow = myOriginalOpen(url, windowName, windowFeatures, replaceFlag);
LOG.debug("window.open call intercepted; window ID (which you can use with selectWindow()) is \"" + windowName + "\"");
if (windowName!=null) {
openedWindow["seleniumWindowName"] = windowName;
}
selenium.browserbot.openedWindows[windowName] = openedWindow;
return openedWindow;
};
if (browserVersion.isHTA) {
originalOpenReference = 'selenium_originalOpen' + new Date().getTime();
newOpenReference = 'selenium_newOpen' + new Date().getTime();
var setOriginalRef = "this['" + originalOpenReference + "'] = this.open;";
if (windowToModify.eval) {
windowToModify.eval(setOriginalRef);
windowToModify.open = newOpen;
} else {
// DGF why can't I eval here? Seems like I'm querying the window at a bad time, maybe?
setOriginalRef += "this.open = this['" + newOpenReference + "'];";
windowToModify[newOpenReference] = newOpen;
windowToModify.setTimeout(setOriginalRef, 0);
}
} else {
windowToModify.open = newOpen;
}
};
/**
* Call the supplied function when a the current page unloads and a new one loads.
* This is done by polling continuously until the document changes and is fully loaded.
*/
BrowserBot.prototype.modifySeparateTestWindowToDetectPageLoads = function(windowObject) {
// Since the unload event doesn't fire in Safari 1.3, we start polling immediately
if (!windowObject) {
LOG.warn("modifySeparateTestWindowToDetectPageLoads: no windowObject!");
return;
}
if (this._windowClosed(windowObject)) {
LOG.info("modifySeparateTestWindowToDetectPageLoads: windowObject was closed");
return;
}
var oldMarker = this.isPollingForLoad(windowObject);
if (oldMarker) {
LOG.debug("modifySeparateTestWindowToDetectPageLoads: already polling this window: " + oldMarker);
return;
}
var marker = 'selenium' + new Date().getTime();
LOG.debug("Starting pollForLoad (" + marker + "): " + windowObject.location);
this.pollingForLoad[marker] = true;
// if this is a frame, add a load listener, otherwise, attach a poller
var frameElement = this._getFrameElement(windowObject);
// DGF HTA mode can't attach load listeners to subframes (yuk!)
var htaSubFrame = this._isHTASubFrame(windowObject);
if (frameElement && !htaSubFrame) {
LOG.debug("modifySeparateTestWindowToDetectPageLoads: this window is a frame; attaching a load listener");
addLoadListener(frameElement, this.recordPageLoad);
frameElement[marker] = true;
frameElement["frame"+this.uniqueId] = marker;
LOG.debug("dgf this.uniqueId="+this.uniqueId);
LOG.debug("dgf marker="+marker);
LOG.debug("dgf frameElement['frame'+this.uniqueId]="+frameElement['frame'+this.uniqueId]);
frameElement[this.uniqueId] = marker;
LOG.debug("dgf frameElement[this.uniqueId]="+frameElement[this.uniqueId]);
} else {
windowObject.location[marker] = true;
windowObject[this.uniqueId] = marker;
this.pollForLoad(this.recordPageLoad, windowObject, windowObject.document, windowObject.location, windowObject.location.href, marker);
}
};
BrowserBot.prototype._isHTASubFrame = function(win) {
if (!browserVersion.isHTA) return false;
// DGF this is wrong! what if "win" isn't the selected window?
return this.isSubFrameSelected;
}
BrowserBot.prototype._getFrameElement = function(win) {
var frameElement = null;
var caught;
try {
frameElement = win.frameElement;
} catch (e) {
caught = true;
}
if (caught) {
// on IE, checking frameElement in a pop-up results in a "No such interface supported" exception
// but it might have a frame element anyway!
var parentContainsIdenticallyNamedFrame = false;
try {
parentContainsIdenticallyNamedFrame = win.parent.frames[win.name];
} catch (e) {} // this may fail if access is denied to the parent; in that case, assume it's not a pop-up
if (parentContainsIdenticallyNamedFrame) {
// it can't be a coincidence that the parent has a frame with the same name as myself!
var result;
try {
result = parentContainsIdenticallyNamedFrame.frameElement;
if (result) {
return result;
}
} catch (e) {} // it was worth a try! _getFrameElementsByName is often slow
result = this._getFrameElementByName(win.name, win.parent.document, win);
return result;
}
}
LOG.debug("_getFrameElement: frameElement="+frameElement);
if (frameElement) {
LOG.debug("frameElement.name="+frameElement.name);
}
return frameElement;
}
BrowserBot.prototype._getFrameElementByName = function(name, doc, win) {
var frames;
var frame;
var i;
frames = doc.getElementsByTagName("iframe");
for (i = 0; i < frames.length; i++) {
frame = frames[i];
if (frame.name === name) {
return frame;
}
}
frames = doc.getElementsByTagName("frame");
for (i = 0; i < frames.length; i++) {
frame = frames[i];
if (frame.name === name) {
return frame;
}
}
// DGF weird; we only call this function when we know the doc contains the frame
LOG.warn("_getFrameElementByName couldn't find a frame or iframe; checking every element for the name " + name);
return BrowserBot.prototype.locateElementByName(win.name, win.parent.document);
}
/**
* Set up a polling timer that will keep checking the readyState of the document until it's complete.
* Since we might call this before the original page is unloaded, we first check to see that the current location
* or href is different from the original one.
*/
BrowserBot.prototype.pollForLoad = function(loadFunction, windowObject, originalDocument, originalLocation, originalHref, marker) {
LOG.debug("pollForLoad original (" + marker + "): " + originalHref);
try {
if (this._windowClosed(windowObject)) {
LOG.debug("pollForLoad WINDOW CLOSED (" + marker + ")");
delete this.pollingForLoad[marker];
return;
}
var isSamePage = this._isSamePage(windowObject, originalDocument, originalLocation, originalHref, marker);
var rs = this.getReadyState(windowObject, windowObject.document);
if (!isSamePage && rs == 'complete') {
var currentHref = windowObject.location.href;
LOG.debug("pollForLoad FINISHED (" + marker + "): " + rs + " (" + currentHref + ")");
delete this.pollingForLoad[marker];
this._modifyWindow(windowObject);
var newMarker = this.isPollingForLoad(windowObject);
if (!newMarker) {
LOG.debug("modifyWindow didn't start new poller: " + newMarker);
this.modifySeparateTestWindowToDetectPageLoads(windowObject);
}
newMarker = this.isPollingForLoad(windowObject);
var currentlySelectedWindow;
var currentlySelectedWindowMarker;
currentlySelectedWindow =this.getCurrentWindow(true);
currentlySelectedWindowMarker = currentlySelectedWindow[this.uniqueId];
LOG.debug("pollForLoad (" + marker + ") restarting " + newMarker);
if (/(TestRunner-splash|Blank)\.html\?start=true$/.test(currentHref)) {
LOG.debug("pollForLoad Oh, it's just the starting page. Never mind!");
} else if (currentlySelectedWindowMarker == newMarker) {
loadFunction(currentlySelectedWindow);
} else {
LOG.debug("pollForLoad page load detected in non-current window; ignoring (currentlySelected="+currentlySelectedWindowMarker+", detection in "+newMarker+")");
}
return;
}
LOG.debug("pollForLoad continue (" + marker + "): " + currentHref);
this.reschedulePoller(loadFunction, windowObject, originalDocument, originalLocation, originalHref, marker);
} catch (e) {
LOG.debug("Exception during pollForLoad; this should get noticed soon (" + e.message + ")!");
//DGF this is supposed to get logged later; log it at debug just in case
//LOG.exception(e);
this.pageLoadError = e;
}
};
BrowserBot.prototype._isSamePage = function(windowObject, originalDocument, originalLocation, originalHref, marker) {
var currentDocument = windowObject.document;
var currentLocation = windowObject.location;
var currentHref = currentLocation.href
var sameDoc = this._isSameDocument(originalDocument, currentDocument);
var sameLoc = (originalLocation === currentLocation);
// hash marks don't meant the page has loaded, so we need to strip them off if they exist...
var currentHash = currentHref.indexOf('#');
if (currentHash > 0) {
currentHref = currentHref.substring(0, currentHash);
}
var originalHash = originalHref.indexOf('#');
if (originalHash > 0) {
originalHref = originalHref.substring(0, originalHash);
}
LOG.debug("_isSamePage: currentHref: " + currentHref);
LOG.debug("_isSamePage: originalHref: " + originalHref);
var sameHref = (originalHref === currentHref);
var markedLoc = currentLocation[marker];
if (browserVersion.isKonqueror || browserVersion.isSafari) {
// the mark disappears too early on these browsers
markedLoc = true;
}
// since this is some _very_ important logic, especially for PI and multiWindow mode, we should log all these out
LOG.debug("_isSamePage: sameDoc: " + sameDoc);
LOG.debug("_isSamePage: sameLoc: " + sameLoc);
LOG.debug("_isSamePage: sameHref: " + sameHref);
LOG.debug("_isSamePage: markedLoc: " + markedLoc);
return sameDoc && sameLoc && sameHref && markedLoc
};
BrowserBot.prototype._isSameDocument = function(originalDocument, currentDocument) {
return originalDocument === currentDocument;
};
BrowserBot.prototype.getReadyState = function(windowObject, currentDocument) {
var rs = currentDocument.readyState;
if (rs == null) {
if ((this.buttonWindow!=null && this.buttonWindow.document.readyState == null) // not proxy injection mode (and therefore buttonWindow isn't null)
|| (top.document.readyState == null)) { // proxy injection mode (and therefore everything's in the top window, but buttonWindow doesn't exist)
// uh oh! we're probably on Firefox with no readyState extension installed!
// We'll have to just take a guess as to when the document is loaded; this guess
// will never be perfect. :-(
if (typeof currentDocument.getElementsByTagName != 'undefined'
&& typeof currentDocument.getElementById != 'undefined'
&& ( currentDocument.getElementsByTagName('body')[0] != null
|| currentDocument.body != null )) {
if (windowObject.frameElement && windowObject.location.href == "about:blank" && windowObject.frameElement.src != "about:blank") {
LOG.info("getReadyState not loaded, frame location was about:blank, but frame src = " + windowObject.frameElement.src);
return null;
}
LOG.debug("getReadyState = windowObject.frames.length = " + windowObject.frames.length);
for (var i = 0; i < windowObject.frames.length; i++) {
LOG.debug("i = " + i);
if (this.getReadyState(windowObject.frames[i], windowObject.frames[i].document) != 'complete') {
LOG.debug("getReadyState aha! the nested frame " + windowObject.frames[i].name + " wasn't ready!");
return null;
}
}
rs = 'complete';
} else {
LOG.debug("pollForLoad readyState was null and DOM appeared to not be ready yet");
}
}
}
else if (rs == "loading" && browserVersion.isIE) {
LOG.debug("pageUnloading = true!!!!");
this.pageUnloading = true;
}
LOG.debug("getReadyState returning " + rs);
return rs;
};
/** This function isn't used normally, but was the way we used to schedule pollers:
asynchronously executed autonomous units. This is deprecated, but remains here
for future reference.
*/
BrowserBot.prototype.XXXreschedulePoller = function(loadFunction, windowObject, originalDocument, originalLocation, originalHref, marker) {
var self = this;
window.setTimeout(function() {
self.pollForLoad(loadFunction, windowObject, originalDocument, originalLocation, originalHref, marker);
}, 500);
};
/** This function isn't used normally, but is useful for debugging asynchronous pollers
* To enable it, rename it to "reschedulePoller", so it will override the
* existing reschedulePoller function
*/
BrowserBot.prototype.XXXreschedulePoller = function(loadFunction, windowObject, originalDocument, originalLocation, originalHref, marker) {
var doc = this.buttonWindow.document;
var button = doc.createElement("button");
var buttonName = doc.createTextNode(marker + " - " + windowObject.name);
button.appendChild(buttonName);
var tools = doc.getElementById("tools");
var self = this;
button.onclick = function() {
tools.removeChild(button);
self.pollForLoad(loadFunction, windowObject, originalDocument, originalLocation, originalHref, marker);
};
tools.appendChild(button);
window.setTimeout(button.onclick, 500);
};
BrowserBot.prototype.reschedulePoller = function(loadFunction, windowObject, originalDocument, originalLocation, originalHref, marker) {
var self = this;
var pollerFunction = function() {
self.pollForLoad(loadFunction, windowObject, originalDocument, originalLocation, originalHref, marker);
};
this.windowPollers.push(pollerFunction);
};
BrowserBot.prototype.runScheduledPollers = function() {
LOG.debug("runScheduledPollers");
var oldPollers = this.windowPollers;
this.windowPollers = new Array();
for (var i = 0; i < oldPollers.length; i++) {
oldPollers[i].call();
}
LOG.debug("runScheduledPollers DONE");
};
BrowserBot.prototype.isPollingForLoad = function(win) {
var marker;
var frameElement = this._getFrameElement(win);
var htaSubFrame = this._isHTASubFrame(win);
if (frameElement && !htaSubFrame) {
marker = frameElement["frame"+this.uniqueId];
} else {
marker = win[this.uniqueId];
}
if (!marker) {
LOG.debug("isPollingForLoad false, missing uniqueId " + this.uniqueId + ": " + marker);
return false;
}
if (!this.pollingForLoad[marker]) {
LOG.debug("isPollingForLoad false, this.pollingForLoad[" + marker + "]: " + this.pollingForLoad[marker]);
return false;
}
return marker;
};
BrowserBot.prototype.getWindowByName = function(windowName, doNotModify) {
LOG.debug("getWindowByName(" + windowName + ")");
// First look in the map of opened windows
var targetWindow = this.openedWindows[windowName];
if (!targetWindow) {
targetWindow = this.topWindow[windowName];
}
if (!targetWindow && windowName == "_blank") {
for (var winName in this.openedWindows) {
// _blank can match selenium_blank*, if it looks like it's OK (valid href, not closed)
if (/^selenium_blank/.test(winName)) {
targetWindow = this.openedWindows[winName];
var ok;
try {
if (!this._windowClosed(targetWindow)) {
ok = targetWindow.location.href;
}
} catch (e) {}
if (ok) break;
}
}
}
if (!targetWindow) {
throw new SeleniumError("Window does not exist");
}
if (browserVersion.isHTA) {
try {
targetWindow.location.href;
} catch (e) {
targetWindow = window.open("", targetWindow.name);
this.openedWindows[targetWindow.name] = targetWindow;
}
}
if (!doNotModify) {
this._modifyWindow(targetWindow);
}
return targetWindow;
};
/**
* Find a window name from the window title.
*/
BrowserBot.prototype.getWindowNameByTitle = function(windowTitle) {
LOG.debug("getWindowNameByTitle(" + windowTitle + ")");
// First look in the map of opened windows and iterate them
for (var windowName in this.openedWindows) {
var targetWindow = this.openedWindows[windowName];
// If the target window's title is our title
try {
// TODO implement Pattern Matching here
if (!this._windowClosed(targetWindow) &&
targetWindow.document.title == windowTitle) {
return windowName;
}
} catch (e) {
// You'll often get Permission Denied errors here in IE
// eh, if we can't read this window's title,
// it's probably not available to us right now anyway
}
}
try {
if (this.topWindow.document.title == windowTitle) {
return "";
}
} catch (e) {} // IE Perm denied
throw new SeleniumError("Could not find window with title " + windowTitle);
};
BrowserBot.prototype.getCurrentWindow = function(doNotModify) {
if (this.proxyInjectionMode) {
return window;
}
var testWindow = this.currentWindow;
if (!doNotModify) {
this._modifyWindow(testWindow);
LOG.debug("getCurrentWindow newPageLoaded = false");
this.newPageLoaded = false;
}
testWindow = this._handleClosedSubFrame(testWindow, doNotModify);
return testWindow;
};
BrowserBot.prototype._handleClosedSubFrame = function(testWindow, doNotModify) {
if (this.proxyInjectionMode) {
return testWindow;
}
if (this.isSubFrameSelected) {
var missing = true;
if (testWindow.parent && testWindow.parent.frames && testWindow.parent.frames.length) {
for (var i = 0; i < testWindow.parent.frames.length; i++) {
if (testWindow.parent.frames[i] == testWindow) {
missing = false;
break;
}
}
}
if (missing) {
LOG.warn("Current subframe appears to have closed; selecting top frame");
this.selectFrame("relative=top");
return this.getCurrentWindow(doNotModify);
}
} else if (this._windowClosed(testWindow)) {
var closedError = new SeleniumError("Current window or frame is closed!");
closedError.windowClosed = true;
throw closedError;
}
return testWindow;
};
BrowserBot.prototype.highlight = function (element, force) {
if (force || this.shouldHighlightLocatedElement) {
try {
highlight(element);
} catch (e) {} // DGF element highlighting is low-priority and possibly dangerous
}
return element;
}
BrowserBot.prototype.setShouldHighlightElement = function (shouldHighlight) {
this.shouldHighlightLocatedElement = shouldHighlight;
}
/*****************************************************************/
/* BROWSER-SPECIFIC FUNCTIONS ONLY AFTER THIS LINE */
BrowserBot.prototype._registerAllLocatorFunctions = function() {
// TODO - don't do this in the constructor - only needed once ever
this.locationStrategies = {};
for (var functionName in this) {
var result = /^locateElementBy([A-Z].+)$/.exec(functionName);
if (result != null) {
var locatorFunction = this[functionName];
if (typeof(locatorFunction) != 'function') {
continue;
}
// Use a specified prefix in preference to one generated from
// the function name
var locatorPrefix = locatorFunction.prefix || result[1].toLowerCase();
this.locationStrategies[locatorPrefix] = locatorFunction;
}
}
/**
* Find a locator based on a prefix.
*/
this.findElementBy = function(locatorType, locator, inDocument, inWindow) {
var locatorFunction = this.locationStrategies[locatorType];
if (! locatorFunction) {
throw new SeleniumError("Unrecognised locator type: '" + locatorType + "'");
}
return locatorFunction.call(this, locator, inDocument, inWindow);
};
/**
* The implicit locator, that is used when no prefix is supplied.
*/
this.locationStrategies['implicit'] = function(locator, inDocument, inWindow) {
if (locator.startsWith('//')) {
return this.locateElementByXPath(locator, inDocument, inWindow);
}
if (locator.startsWith('document.')) {
return this.locateElementByDomTraversal(locator, inDocument, inWindow);
}
return this.locateElementByIdentifier(locator, inDocument, inWindow);
};
}
BrowserBot.prototype.getDocument = function() {
return this.getCurrentWindow().document;
}
BrowserBot.prototype.getTitle = function() {
var t = this.getDocument().title;
if (typeof(t) == "string") {
t = t.trim();
}
return t;
}
/*
* Finds an element recursively in frames and nested frames
* in the specified document, using various lookup protocols
*/
BrowserBot.prototype.findElementRecursive = function(locatorType, locatorString, inDocument, inWindow) {
var element = this.findElementBy(locatorType, locatorString, inDocument, inWindow);
if (element != null) {
return element;
}
for (var i = 0; i < inWindow.frames.length; i++) {
element = this.findElementRecursive(locatorType, locatorString, inWindow.frames[i].document, inWindow.frames[i]);
if (element != null) {
return element;
}
}
};
/*
* Finds an element on the current page, using various lookup protocols
*/
BrowserBot.prototype.findElementOrNull = function(locator, win) {
var locatorType = 'implicit';
var locatorString = locator;
// If there is a locator prefix, use the specified strategy
var result = locator.match(/^([A-Za-z]+)=(.+)/);
if (result) {
locatorType = result[1].toLowerCase();
locatorString = result[2];
}
if (win == null) {
win = this.getCurrentWindow();
}
var element = this.findElementRecursive(locatorType, locatorString, win.document, win);
if (element != null) {
return this.browserbot.highlight(element);
}
// Element was not found by any locator function.
return null;
};
BrowserBot.prototype.findElement = function(locator, win) {
var element = this.findElementOrNull(locator, win);
if (element == null) throw new SeleniumError("Element " + locator + " not found");
return element;
}
/**
* In non-IE browsers, getElementById() does not search by name. Instead, we
* we search separately by id and name.
*/
BrowserBot.prototype.locateElementByIdentifier = function(identifier, inDocument, inWindow) {
return BrowserBot.prototype.locateElementById(identifier, inDocument, inWindow)
|| BrowserBot.prototype.locateElementByName(identifier, inDocument, inWindow)
|| null;
};
/**
* Find the element with id - can't rely on getElementById, coz it returns by name as well in IE..
*/
BrowserBot.prototype.locateElementById = function(identifier, inDocument, inWindow) {
var element = inDocument.getElementById(identifier);
if (element && element.id === identifier) {
return element;
}
else {
return null;
}
};
/**
* Find an element by name, refined by (optional) element-filter
* expressions.
*/
BrowserBot.prototype.locateElementByName = function(locator, document, inWindow) {
var elements = document.getElementsByTagName("*");
var filters = locator.split(' ');
filters[0] = 'name=' + filters[0];
while (filters.length) {
var filter = filters.shift();
elements = this.selectElements(filter, elements, 'value');
}
if (elements.length > 0) {
return elements[0];
}
return null;
};
/**
* Finds an element using by evaluating the specfied string.
*/
BrowserBot.prototype.locateElementByDomTraversal = function(domTraversal, document, window) {
var browserbot = this.browserbot;
var element = null;
try {
element = eval(domTraversal);
} catch (e) {
return null;
}
if (!element) {
return null;
}
return element;
};
BrowserBot.prototype.locateElementByDomTraversal.prefix = "dom";
/**
* Finds an element identified by the xpath expression. Expressions _must_
* begin with "//".
*/
BrowserBot.prototype.locateElementByXPath = function(xpath, inDocument, inWindow) {
// Trim any trailing "/": not valid xpath, and remains from attribute
// locator.
if (xpath.charAt(xpath.length - 1) == '/') {
xpath = xpath.slice(0, -1);
}
// Handle //tag
var match = xpath.match(/^\/\/(\w+|\*)$/);
if (match) {
var elements = inDocument.getElementsByTagName(match[1].toUpperCase());
if (elements == null) return null;
return elements[0];
}
// Handle //tag[@attr='value']
var match = xpath.match(/^\/\/(\w+|\*)\[@(\w+)=('([^\']+)'|"([^\"]+)")\]$/);
if (match) {
// We don't return the value without checking if it is null first.
// This is beacuse in some rare cases, this shortcut actually WONT work
// but that the full XPath WILL. A known case, for example, is in IE
// when the attribute is onclick/onblur/onsubmit/etc. Due to a bug in IE
// this shortcut won't work because the actual function is returned
// by getAttribute() rather than the text of the attribute.
var val = this._findElementByTagNameAndAttributeValue(
inDocument,
match[1].toUpperCase(),
match[2].toLowerCase(),
match[3].slice(1, -1)
);
if (val) {
return val;
}
}
// Handle //tag[text()='value']
var match = xpath.match(/^\/\/(\w+|\*)\[text\(\)=('([^\']+)'|"([^\"]+)")\]$/);
if (match) {
return this._findElementByTagNameAndText(
inDocument,
match[1].toUpperCase(),
match[2].slice(1, -1)
);
}
return this._findElementUsingFullXPath(xpath, inDocument);
};
BrowserBot.prototype._findElementByTagNameAndAttributeValue = function(
inDocument, tagName, attributeName, attributeValue
) {
if (browserVersion.isIE && attributeName == "class") {
attributeName = "className";
}
var elements = inDocument.getElementsByTagName(tagName);
for (var i = 0; i < elements.length; i++) {
var elementAttr = elements[i].getAttribute(attributeName);
if (elementAttr == attributeValue) {
return elements[i];
}
}
return null;
};
BrowserBot.prototype._findElementByTagNameAndText = function(
inDocument, tagName, text
) {
var elements = inDocument.getElementsByTagName(tagName);
for (var i = 0; i < elements.length; i++) {
if (getText(elements[i]) == text) {
return elements[i];
}
}
return null;
};
BrowserBot.prototype._namespaceResolver = function(prefix) {
if (prefix == 'html' || prefix == 'xhtml' || prefix == 'x') {
return 'http://www.w3.org/1999/xhtml';
} else if (prefix == 'mathml') {
return 'http://www.w3.org/1998/Math/MathML';
} else {
throw new Error("Unknown namespace: " + prefix + ".");
}
}
BrowserBot.prototype._findElementUsingFullXPath = function(xpath, inDocument, inWindow) {
// HUGE hack - remove namespace from xpath for IE
if (browserVersion.isIE) {
xpath = xpath.replace(/x:/g, '')
}
// Use document.evaluate() if it's available
if (this.allowNativeXpath && inDocument.evaluate) {
return inDocument.evaluate(xpath, inDocument, this._namespaceResolver, 0, null).iterateNext();
}
// If not, fall back to slower JavaScript implementation
// DGF set xpathdebug = true (using getEval, if you like) to turn on JS XPath debugging
//xpathdebug = true;
var context = new ExprContext(inDocument);
var xpathObj = xpathParse(xpath);
var xpathResult = xpathObj.evaluate(context);
if (xpathResult && xpathResult.value) {
return xpathResult.value[0];
}
return null;
};
// DGF this may LOOK identical to _findElementUsingFullXPath, but
// fEUFX pops the first element off the resulting nodelist; this function
// wraps the xpath in a count() operator and returns the numeric value directly
BrowserBot.prototype.evaluateXPathCount = function(xpath, inDocument) {
// HUGE hack - remove namespace from xpath for IE
if (browserVersion.isIE) {
xpath = xpath.replace(/x:/g, '')
}
xpath = new String(xpath);
if (xpath.indexOf("xpath=") == 0) {
xpath = xpath.substring(6);
}
if (xpath.indexOf("count(") == 0) {
// DGF we COULD just fix this up for the user, but we might get it wrong (parens?)
throw new SeleniumError("XPath count expressions must not be wrapped in count() function: " + xpath);
}
xpath="count("+xpath+")";
// Use document.evaluate() if it's available
if (this.allowNativeXpath && inDocument.evaluate) {
var result = inDocument.evaluate(xpath, inDocument, this._namespaceResolver, XPathResult.NUMBER_TYPE, null);
return result.numberValue;
}
// If not, fall back to slower JavaScript implementation
// DGF set xpathdebug = true (using getEval, if you like) to turn on JS XPath debugging
//xpathdebug = true;
var context = new ExprContext(inDocument);
var xpathObj = xpathParse(xpath);
var xpathResult = xpathObj.evaluate(context);
if (xpathResult && xpathResult.value) {
return xpathResult.value;
}
return 0;
};
/**
* Finds a link element with text matching the expression supplied. Expressions must
* begin with "link:".
*/
BrowserBot.prototype.locateElementByLinkText = function(linkText, inDocument, inWindow) {
var links = inDocument.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
var element = links[i];
if (PatternMatcher.matches(linkText, getText(element))) {
return element;
}
}
return null;
};
BrowserBot.prototype.locateElementByLinkText.prefix = "link";
/**
* Returns an attribute based on an attribute locator. This is made up of an element locator
* suffixed with @attribute-name.
*/
BrowserBot.prototype.findAttribute = function(locator) {
// Split into locator + attributeName
var attributePos = locator.lastIndexOf("@");
var elementLocator = locator.slice(0, attributePos);
var attributeName = locator.slice(attributePos + 1);
// Find the element.
var element = this.findElement(elementLocator);
// Handle missing "class" attribute in IE.
if (browserVersion.isIE && attributeName == "class") {
attributeName = "className";
}
// Get the attribute value.
var attributeValue = element.getAttribute(attributeName);
return attributeValue ? attributeValue.toString() : null;
};
/*
* Select the specified option and trigger the relevant events of the element.
*/
BrowserBot.prototype.selectOption = function(element, optionToSelect) {
triggerEvent(element, 'focus', false);
var changed = false;
for (var i = 0; i < element.options.length; i++) {
var option = element.options[i];
if (option.selected && option != optionToSelect) {
option.selected = false;
changed = true;
}
else if (!option.selected && option == optionToSelect) {
option.selected = true;
changed = true;
}
}
if (changed) {
triggerEvent(element, 'change', true);
}
};
/*
* Select the specified option and trigger the relevant events of the element.
*/
BrowserBot.prototype.addSelection = function(element, option) {
this.checkMultiselect(element);
triggerEvent(element, 'focus', false);
if (!option.selected) {
option.selected = true;
triggerEvent(element, 'change', true);
}
};
/*
* Select the specified option and trigger the relevant events of the element.
*/
BrowserBot.prototype.removeSelection = function(element, option) {
this.checkMultiselect(element);
triggerEvent(element, 'focus', false);
if (option.selected) {
option.selected = false;
triggerEvent(element, 'change', true);
}
};
BrowserBot.prototype.checkMultiselect = function(element) {
if (!element.multiple)
{
throw new SeleniumError("Not a multi-select");
}
};
BrowserBot.prototype.replaceText = function(element, stringValue) {
triggerEvent(element, 'focus', false);
triggerEvent(element, 'select', true);
var maxLengthAttr = element.getAttribute("maxLength");
var actualValue = stringValue;
if (maxLengthAttr != null) {
var maxLength = parseInt(maxLengthAttr);
if (stringValue.length > maxLength) {
actualValue = stringValue.substr(0, maxLength);
}
}
if (getTagName(element) == "body") {
if (element.ownerDocument && element.ownerDocument.designMode) {
var designMode = new String(element.ownerDocument.designMode).toLowerCase();
if (designMode = "on") {
// this must be a rich text control!
element.innerHTML = actualValue;
}
}
} else {
element.value = actualValue;
}
// DGF this used to be skipped in chrome URLs, but no longer. Is xpcnativewrappers to blame?
try {
triggerEvent(element, 'change', true);
} catch (e) {}
};
BrowserBot.prototype.submit = function(formElement) {
var actuallySubmit = true;
this._modifyElementTarget(formElement);
if (formElement.onsubmit) {
if (browserVersion.isHTA) {
// run the code in the correct window so alerts are handled correctly even in HTA mode
var win = this.browserbot.getCurrentWindow();
var now = new Date().getTime();
var marker = 'marker' + now;
win[marker] = formElement;
win.setTimeout("var actuallySubmit = "+marker+".onsubmit();" +
"if (actuallySubmit) { " +
marker+".submit(); " +
"if ("+marker+".target && !/^_/.test("+marker+".target)) {"+
"window.open('', "+marker+".target);"+
"}"+
"};"+
marker+"=null", 0);
// pause for up to 2s while this command runs
var terminationCondition = function () {
return !win[marker];
}
return Selenium.decorateFunctionWithTimeout(terminationCondition, 2000);
} else {
actuallySubmit = formElement.onsubmit();
if (actuallySubmit) {
formElement.submit();
if (formElement.target && !/^_/.test(formElement.target)) {
this.browserbot.openWindow('', formElement.target);
}
}
}
} else {
formElement.submit();
}
}
BrowserBot.prototype.clickElement = function(element, clientX, clientY) {
this._fireEventOnElement("click", element, clientX, clientY);
};
BrowserBot.prototype.doubleClickElement = function(element, clientX, clientY) {
this._fireEventOnElement("dblclick", element, clientX, clientY);
};
BrowserBot.prototype._modifyElementTarget = function(element) {
if (element.target) {
if (element.target == "_blank" || /^selenium_blank/.test(element.target) ) {
var tagName = getTagName(element);
if (tagName == "a" || tagName == "form") {
var newTarget = "selenium_blank" + Math.round(100000 * Math.random());
LOG.warn("Link has target '_blank', which is not supported in Selenium! Randomizing target to be: " + newTarget);
this.browserbot.openWindow('', newTarget);
element.target = newTarget;
}
}
}
}
BrowserBot.prototype._handleClickingImagesInsideLinks = function(targetWindow, element) {
var itrElement = element;
while (itrElement != null) {
if (itrElement.href) {
targetWindow.location.href = itrElement.href;
break;
}
itrElement = itrElement.parentNode;
}
}
BrowserBot.prototype._getTargetWindow = function(element) {
var targetWindow = element.ownerDocument.defaultView;
if (element.target) {
targetWindow = this._getFrameFromGlobal(element.target);
}
return targetWindow;
}
BrowserBot.prototype._getFrameFromGlobal = function(target) {
if (target == "_top") {
return this.topFrame;
} else if (target == "_parent") {
return this.getCurrentWindow().parent;
} else if (target == "_blank") {
// TODO should this set cleverer window defaults?
return this.getCurrentWindow().open('', '_blank');
}
var frameElement = this.findElementBy("implicit", target, this.topFrame.document, this.topFrame);
if (frameElement) {
return frameElement.contentWindow;
}
var win = this.getWindowByName(target);
if (win) return win;
return this.getCurrentWindow().open('', target);
}
BrowserBot.prototype.bodyText = function() {
if (!this.getDocument().body) {
throw new SeleniumError("Couldn't access document.body. Is this HTML page fully loaded?");
}
return getText(this.getDocument().body);
};
BrowserBot.prototype.getAllButtons = function() {
var elements = this.getDocument().getElementsByTagName('input');
var result = [];
for (var i = 0; i < elements.length; i++) {
if (elements[i].type == 'button' || elements[i].type == 'submit' || elements[i].type == 'reset') {
result.push(elements[i].id);
}
}
return result;
};
BrowserBot.prototype.getAllFields = function() {
var elements = this.getDocument().getElementsByTagName('input');
var result = [];
for (var i = 0; i < elements.length; i++) {
if (elements[i].type == 'text') {
result.push(elements[i].id);
}
}
return result;
};
BrowserBot.prototype.getAllLinks = function() {
var elements = this.getDocument().getElementsByTagName('a');
var result = [];
for (var i = 0; i < elements.length; i++) {
result.push(elements[i].id);
}
return result;
};
function isDefined(value) {
return typeof(value) != undefined;
}
BrowserBot.prototype.goBack = function() {
this.getCurrentWindow().history.back();
};
BrowserBot.prototype.goForward = function() {
this.getCurrentWindow().history.forward();
};
BrowserBot.prototype.close = function() {
if (browserVersion.isChrome || browserVersion.isSafari || browserVersion.isOpera) {
this.getCurrentWindow().close();
} else {
this.getCurrentWindow().eval("window.close();");
}
};
BrowserBot.prototype.refresh = function() {
this.getCurrentWindow().location.reload(true);
};
/**
* Refine a list of elements using a filter.
*/
BrowserBot.prototype.selectElementsBy = function(filterType, filter, elements) {
var filterFunction = BrowserBot.filterFunctions[filterType];
if (! filterFunction) {
throw new SeleniumError("Unrecognised element-filter type: '" + filterType + "'");
}
return filterFunction(filter, elements);
};
BrowserBot.filterFunctions = {};
BrowserBot.filterFunctions.name = function(name, elements) {
var selectedElements = [];
for (var i = 0; i < elements.length; i++) {
if (elements[i].name === name) {
selectedElements.push(elements[i]);
}
}
return selectedElements;
};
BrowserBot.filterFunctions.value = function(value, elements) {
var selectedElements = [];
for (var i = 0; i < elements.length; i++) {
if (elements[i].value === value) {
selectedElements.push(elements[i]);
}
}
return selectedElements;
};
BrowserBot.filterFunctions.index = function(index, elements) {
index = Number(index);
if (isNaN(index) || index < 0) {
throw new SeleniumError("Illegal Index: " + index);
}
if (elements.length <= index) {
throw new SeleniumError("Index out of range: " + index);
}
return [elements[index]];
};
BrowserBot.prototype.selectElements = function(filterExpr, elements, defaultFilterType) {
var filterType = (defaultFilterType || 'value');
// If there is a filter prefix, use the specified strategy
var result = filterExpr.match(/^([A-Za-z]+)=(.+)/);
if (result) {
filterType = result[1].toLowerCase();
filterExpr = result[2];
}
return this.selectElementsBy(filterType, filterExpr, elements);
};
/**
* Find an element by class
*/
BrowserBot.prototype.locateElementByClass = function(locator, document) {
return elementFindFirstMatchingChild(document,
function(element) {
return element.className == locator
}
);
}
/**
* Find an element by alt
*/
BrowserBot.prototype.locateElementByAlt = function(locator, document) {
return elementFindFirstMatchingChild(document,
function(element) {
return element.alt == locator
}
);
}
/**
* Find an element by css selector
*/
BrowserBot.prototype.locateElementByCss = function(locator, document) {
var elements = cssQuery(locator, document);
if (elements.length != 0)
return elements[0];
return null;
}
/*****************************************************************/
/* BROWSER-SPECIFIC FUNCTIONS ONLY AFTER THIS LINE */
function MozillaBrowserBot(frame) {
BrowserBot.call(this, frame);
}
objectExtend(MozillaBrowserBot.prototype, BrowserBot.prototype);
function KonquerorBrowserBot(frame) {
BrowserBot.call(this, frame);
}
objectExtend(KonquerorBrowserBot.prototype, BrowserBot.prototype);
KonquerorBrowserBot.prototype.setIFrameLocation = function(iframe, location) {
// Window doesn't fire onload event when setting src to the current value,
// so we set it to blank first.
iframe.src = "about:blank";
iframe.src = location;
};
KonquerorBrowserBot.prototype.setOpenLocation = function(win, loc) {
// Window doesn't fire onload event when setting src to the current value,
// so we just refresh in that case instead.
loc = absolutify(loc, this.baseUrl);
loc = canonicalize(loc);
var startUrl = win.location.href;
if ("about:blank" != win.location.href) {
var startLoc = parseUrl(win.location.href);
startLoc.hash = null;
var startUrl = reassembleLocation(startLoc);
}
LOG.debug("startUrl="+startUrl);
LOG.debug("win.location.href="+win.location.href);
LOG.debug("loc="+loc);
if (startUrl == loc) {
LOG.debug("opening exact same location");
this.refresh();
} else {
LOG.debug("locations differ");
win.location.href = loc;
}
// force the current polling thread to detect a page load
var marker = this.isPollingForLoad(win);
if (marker) {
delete win.location[marker];
}
};
KonquerorBrowserBot.prototype._isSameDocument = function(originalDocument, currentDocument) {
// under Konqueror, there may be this case:
// originalDocument and currentDocument are different objects
// while their location are same.
if (originalDocument) {
return originalDocument.location == currentDocument.location
} else {
return originalDocument === currentDocument;
}
};
function SafariBrowserBot(frame) {
BrowserBot.call(this, frame);
}
objectExtend(SafariBrowserBot.prototype, BrowserBot.prototype);
SafariBrowserBot.prototype.setIFrameLocation = KonquerorBrowserBot.prototype.setIFrameLocation;
SafariBrowserBot.prototype.setOpenLocation = KonquerorBrowserBot.prototype.setOpenLocation;
function OperaBrowserBot(frame) {
BrowserBot.call(this, frame);
}
objectExtend(OperaBrowserBot.prototype, BrowserBot.prototype);
OperaBrowserBot.prototype.setIFrameLocation = function(iframe, location) {
if (iframe.src == location) {
iframe.src = location + '?reload';
} else {
iframe.src = location;
}
}
function IEBrowserBot(frame) {
BrowserBot.call(this, frame);
}
objectExtend(IEBrowserBot.prototype, BrowserBot.prototype);
IEBrowserBot.prototype._handleClosedSubFrame = function(testWindow, doNotModify) {
if (this.proxyInjectionMode) {
return testWindow;
}
try {
testWindow.location.href;
this.permDenied = 0;
} catch (e) {
this.permDenied++;
}
if (this._windowClosed(testWindow) || this.permDenied > 4) {
if (this.isSubFrameSelected) {
LOG.warn("Current subframe appears to have closed; selecting top frame");
this.selectFrame("relative=top");
return this.getCurrentWindow(doNotModify);
} else {
var closedError = new SeleniumError("Current window or frame is closed!");
closedError.windowClosed = true;
throw closedError;
}
}
return testWindow;
};
IEBrowserBot.prototype.modifyWindowToRecordPopUpDialogs = function(windowToModify, browserBot) {
BrowserBot.prototype.modifyWindowToRecordPopUpDialogs(windowToModify, browserBot);
// we will call the previous version of this method from within our own interception
oldShowModalDialog = windowToModify.showModalDialog;
windowToModify.showModalDialog = function(url, args, features) {
// Get relative directory to where TestRunner.html lives
// A risky assumption is that the user's TestRunner is named TestRunner.html
var doc_location = document.location.toString();
var end_of_base_ref = doc_location.indexOf('TestRunner.html');
var base_ref = doc_location.substring(0, end_of_base_ref);
var runInterval = '';
// Only set run interval if options is defined
if (typeof(window.runOptions) != undefined) {
runInterval = "&runInterval=" + runOptions.runInterval;
}
var testRunnerURL = "TestRunner.html?auto=true&singletest="
+ escape(browserBot.modalDialogTest)
+ "&autoURL="
+ escape(url)
+ runInterval;
var fullURL = base_ref + testRunnerURL;
browserBot.modalDialogTest = null;
// If using proxy injection mode
if (this.proxyInjectionMode) {
var sessionId = runOptions.getSessionId();
if (sessionId == undefined) {
sessionId = injectedSessionId;
}
if (sessionId != undefined) {
LOG.debug("Invoking showModalDialog and injecting URL " + fullURL);
}
fullURL = url;
}
var returnValue = oldShowModalDialog(fullURL, args, features);
return returnValue;
};
};
IEBrowserBot.prototype.modifySeparateTestWindowToDetectPageLoads = function(windowObject) {
this.pageUnloading = false;
var self = this;
var pageUnloadDetector = function() {
self.pageUnloading = true;
};
windowObject.attachEvent("onbeforeunload", pageUnloadDetector);
BrowserBot.prototype.modifySeparateTestWindowToDetectPageLoads.call(this, windowObject);
};
IEBrowserBot.prototype.pollForLoad = function(loadFunction, windowObject, originalDocument, originalLocation, originalHref, marker) {
LOG.debug("IEBrowserBot.pollForLoad: " + marker);
if (!this.permDeniedCount[marker]) this.permDeniedCount[marker] = 0;
BrowserBot.prototype.pollForLoad.call(this, loadFunction, windowObject, originalDocument, originalLocation, originalHref, marker);
if (this.pageLoadError) {
if (this.pageUnloading) {
var self = this;
LOG.debug("pollForLoad UNLOADING (" + marker + "): caught exception while firing events on unloading page: " + this.pageLoadError.message);
this.reschedulePoller(loadFunction, windowObject, originalDocument, originalLocation, originalHref, marker);
this.pageLoadError = null;
return;
} else if (((this.pageLoadError.message == "Permission denied") || (/^Access is denied/.test(this.pageLoadError.message)))
&& this.permDeniedCount[marker]++ < 8) {
if (this.permDeniedCount[marker] > 4) {
var canAccessThisWindow;
var canAccessCurrentlySelectedWindow;
try {
windowObject.location.href;
canAccessThisWindow = true;
} catch (e) {}
try {
this.getCurrentWindow(true).location.href;
canAccessCurrentlySelectedWindow = true;
} catch (e) {}
if (canAccessCurrentlySelectedWindow & !canAccessThisWindow) {
LOG.debug("pollForLoad (" + marker + ") ABORTING: " + this.pageLoadError.message + " (" + this.permDeniedCount[marker] + "), but the currently selected window is fine");
// returning without rescheduling
this.pageLoadError = null;
return;
}
}
var self = this;
LOG.debug("pollForLoad (" + marker + "): " + this.pageLoadError.message + " (" + this.permDeniedCount[marker] + "), waiting to see if it goes away");
this.reschedulePoller(loadFunction, windowObject, originalDocument, originalLocation, originalHref, marker);
this.pageLoadError = null;
return;
}
//handy for debugging!
//throw this.pageLoadError;
}
};
IEBrowserBot.prototype._windowClosed = function(win) {
try {
var c = win.closed;
// frame windows claim to be non-closed when their parents are closed
// but you can't access their document objects in that case
if (!c) {
try {
win.document;
} catch (de) {
if (de.message == "Permission denied") {
// the window is probably unloading, which means it's probably not closed yet
return false;
}
else if (/^Access is denied/.test(de.message)) {
// rare variation on "Permission denied"?
LOG.debug("IEBrowserBot.windowClosed: got " + de.message + " (this.pageUnloading=" + this.pageUnloading + "); assuming window is unloading, probably not closed yet");
return false;
} else {
// this is probably one of those frame window situations
LOG.debug("IEBrowserBot.windowClosed: couldn't read win.document, assume closed: " + de.message + " (this.pageUnloading=" + this.pageUnloading + ")");
return true;
}
}
}
if (c == null) {
LOG.debug("IEBrowserBot.windowClosed: win.closed was null, assuming closed");
return true;
}
return c;
} catch (e) {
LOG.debug("IEBrowserBot._windowClosed: Got an exception trying to read win.closed; we'll have to take a guess!");
if (browserVersion.isHTA) {
if (e.message == "Permission denied") {
// the window is probably unloading, which means it's not closed yet
return false;
} else {
// there's a good chance that we've lost contact with the window object if it is closed
return true;
}
} else {
// the window is probably unloading, which means it's not closed yet
return false;
}
}
};
/**
* In IE, getElementById() also searches by name - this is an optimisation for IE.
*/
IEBrowserBot.prototype.locateElementByIdentifer = function(identifier, inDocument, inWindow) {
return inDocument.getElementById(identifier);
};
IEBrowserBot.prototype._findElementByTagNameAndAttributeValue = function(
inDocument, tagName, attributeName, attributeValue
) {
if (attributeName == "class") {
attributeName = "className";
}
var elements = inDocument.getElementsByTagName(tagName);
for (var i = 0; i < elements.length; i++) {
var elementAttr = elements[i].getAttribute(attributeName);
if (elementAttr == attributeValue) {
return elements[i];
}
// DGF SEL-347, IE6 URL-escapes javascript href attribute
if (!elementAttr) continue;
elementAttr = unescape(new String(elementAttr));
if (elementAttr == attributeValue) {
return elements[i];
}
}
return null;
};
SafariBrowserBot.prototype.modifyWindowToRecordPopUpDialogs = function(windowToModify, browserBot) {
BrowserBot.prototype.modifyWindowToRecordPopUpDialogs(windowToModify, browserBot);
var originalOpen = windowToModify.open;
/*
* Safari seems to be broken, so that when we manually trigger the onclick method
* of a button/href, any window.open calls aren't resolved relative to the app location.
* So here we replace the open() method with one that does resolve the url correctly.
*/
windowToModify.open = function(url, windowName, windowFeatures, replaceFlag) {
if (url.startsWith("http://") || url.startsWith("https://") || url.startsWith("/")) {
return originalOpen(url, windowName, windowFeatures, replaceFlag);
}
// Reduce the current path to the directory
var currentPath = windowToModify.location.pathname || "/";
currentPath = currentPath.replace(/\/[^\/]*$/, "/");
// Remove any leading "./" from the new url.
url = url.replace(/^\.\//, "");
newUrl = currentPath + url;
var openedWindow = originalOpen(newUrl, windowName, windowFeatures, replaceFlag);
LOG.debug("window.open call intercepted; window ID (which you can use with selectWindow()) is \"" + windowName + "\"");
if (windowName!=null) {
openedWindow["seleniumWindowName"] = windowName;
}
return openedWindow;
};
};
MozillaBrowserBot.prototype._fireEventOnElement = function(eventType, element, clientX, clientY) {
var win = this.getCurrentWindow();
triggerEvent(element, 'focus', false);
// Add an event listener that detects if the default action has been prevented.
// (This is caused by a javascript onclick handler returning false)
// we capture the whole event, rather than the getPreventDefault() state at the time,
// because we need to let the entire event bubbling and capturing to go through
// before making a decision on whether we should force the href
var savedEvent = null;
element.addEventListener(eventType, function(evt) {
savedEvent = evt;
}, false);
this._modifyElementTarget(element);
// Trigger the event.
this.browserbot.triggerMouseEvent(element, eventType, true, clientX, clientY);
if (this._windowClosed(win)) {
return;
}
// Perform the link action if preventDefault was set.
// In chrome URL, the link action is already executed by triggerMouseEvent.
if (!browserVersion.isChrome && savedEvent != null && !savedEvent.getPreventDefault()) {
var targetWindow = this.browserbot._getTargetWindow(element);
if (element.href) {
targetWindow.location.href = element.href;
} else {
this.browserbot._handleClickingImagesInsideLinks(targetWindow, element);
}
}
};
OperaBrowserBot.prototype._fireEventOnElement = function(eventType, element, clientX, clientY) {
var win = this.getCurrentWindow();
triggerEvent(element, 'focus', false);
this._modifyElementTarget(element);
// Trigger the click event.
this.browserbot.triggerMouseEvent(element, eventType, true, clientX, clientY);
if (this._windowClosed(win)) {
return;
}
};
KonquerorBrowserBot.prototype._fireEventOnElement = function(eventType, element, clientX, clientY) {
var win = this.getCurrentWindow();
triggerEvent(element, 'focus', false);
this._modifyElementTarget(element);
if (element[eventType]) {
element[eventType]();
}
else {
this.browserbot.triggerMouseEvent(element, eventType, true, clientX, clientY);
}
if (this._windowClosed(win)) {
return;
}
};
SafariBrowserBot.prototype._fireEventOnElement = function(eventType, element, clientX, clientY) {
triggerEvent(element, 'focus', false);
var wasChecked = element.checked;
this._modifyElementTarget(element);
// For form element it is simple.
if (element[eventType]) {
element[eventType]();
}
// For links and other elements, event emulation is required.
else {
var targetWindow = this.browserbot._getTargetWindow(element);
// todo: deal with anchors?
this.browserbot.triggerMouseEvent(element, eventType, true, clientX, clientY);
}
};
SafariBrowserBot.prototype.refresh = function() {
var win = this.getCurrentWindow();
if (win.location.hash) {
// DGF Safari refuses to refresh when there's a hash symbol in the URL
win.location.hash = "";
var actuallyReload = function() {
win.location.reload(true);
}
window.setTimeout(actuallyReload, 1);
} else {
win.location.reload(true);
}
};
IEBrowserBot.prototype._fireEventOnElement = function(eventType, element, clientX, clientY) {
var win = this.getCurrentWindow();
triggerEvent(element, 'focus', false);
var wasChecked = element.checked;
// Set a flag that records if the page will unload - this isn't always accurate, because
// <a href="javascript:alert('foo'):"> triggers the onbeforeunload event, even thought the page won't unload
var pageUnloading = false;
var pageUnloadDetector = function() {
pageUnloading = true;
};
win.attachEvent("onbeforeunload", pageUnloadDetector);
this._modifyElementTarget(element);
if (element[eventType]) {
element[eventType]();
}
else {
this.browserbot.triggerMouseEvent(element, eventType, true, clientX, clientY);
}
// If the page is going to unload - still attempt to fire any subsequent events.
// However, we can't guarantee that the page won't unload half way through, so we need to handle exceptions.
try {
win.detachEvent("onbeforeunload", pageUnloadDetector);
if (this._windowClosed(win)) {
return;
}
// Onchange event is not triggered automatically in IE.
if (isDefined(element.checked) && wasChecked != element.checked) {
triggerEvent(element, 'change', true);
}
}
catch (e) {
// If the page is unloading, we may get a "Permission denied" or "Unspecified error".
// Just ignore it, because the document may have unloaded.
if (pageUnloading) {
LOG.logHook = function() {
};
LOG.warn("Caught exception when firing events on unloading page: " + e.message);
return;
}
throw e;
}
}; | zc.selenium | /zc.selenium-1.2.1.tar.gz/zc.selenium-1.2.1/src/zc/selenium/resources/scripts/selenium-browserbot.js | selenium-browserbot.js |
//<script>
//////////////////
// Helper Stuff //
//////////////////
// used to find the Automation server name
function getDomDocumentPrefix() {
if (getDomDocumentPrefix.prefix)
return getDomDocumentPrefix.prefix;
var prefixes = ["MSXML2", "Microsoft", "MSXML", "MSXML3"];
var o;
for (var i = 0; i < prefixes.length; i++) {
try {
// try to create the objects
o = new ActiveXObject(prefixes[i] + ".DomDocument");
return getDomDocumentPrefix.prefix = prefixes[i];
}
catch (ex) {};
}
throw new Error("Could not find an installed XML parser");
}
function getXmlHttpPrefix() {
if (getXmlHttpPrefix.prefix)
return getXmlHttpPrefix.prefix;
var prefixes = ["MSXML2", "Microsoft", "MSXML", "MSXML3"];
var o;
for (var i = 0; i < prefixes.length; i++) {
try {
// try to create the objects
o = new ActiveXObject(prefixes[i] + ".XmlHttp");
return getXmlHttpPrefix.prefix = prefixes[i];
}
catch (ex) {};
}
throw new Error("Could not find an installed XML parser");
}
//////////////////////////
// Start the Real stuff //
//////////////////////////
// XmlHttp factory
function XmlHttp() {}
XmlHttp.create = function () {
try {
if (window.XMLHttpRequest) {
var req = new XMLHttpRequest();
// some versions of Moz do not support the readyState property
// and the onreadystate event so we patch it!
if (req.readyState == null) {
req.readyState = 1;
req.addEventListener("load", function () {
req.readyState = 4;
if (typeof req.onreadystatechange == "function")
req.onreadystatechange();
}, false);
}
return req;
}
if (window.ActiveXObject) {
return new ActiveXObject(getXmlHttpPrefix() + ".XmlHttp");
}
}
catch (ex) {}
// fell through
throw new Error("Your browser does not support XmlHttp objects");
};
// XmlDocument factory
function XmlDocument() {}
XmlDocument.create = function () {
try {
// DOM2
if (document.implementation && document.implementation.createDocument) {
var doc = document.implementation.createDocument("", "", null);
// some versions of Moz do not support the readyState property
// and the onreadystate event so we patch it!
if (doc.readyState == null) {
doc.readyState = 1;
doc.addEventListener("load", function () {
doc.readyState = 4;
if (typeof doc.onreadystatechange == "function")
doc.onreadystatechange();
}, false);
}
return doc;
}
if (window.ActiveXObject)
return new ActiveXObject(getDomDocumentPrefix() + ".DomDocument");
}
catch (ex) {}
throw new Error("Your browser does not support XmlDocument objects");
};
// Create the loadXML method and xml getter for Mozilla
if (window.DOMParser &&
window.XMLSerializer &&
window.Node && Node.prototype && Node.prototype.__defineGetter__) {
// XMLDocument did not extend the Document interface in some versions
// of Mozilla. Extend both!
//XMLDocument.prototype.loadXML =
Document.prototype.loadXML = function (s) {
// parse the string to a new doc
var doc2 = (new DOMParser()).parseFromString(s, "text/xml");
// remove all initial children
while (this.hasChildNodes())
this.removeChild(this.lastChild);
// insert and import nodes
for (var i = 0; i < doc2.childNodes.length; i++) {
this.appendChild(this.importNode(doc2.childNodes[i], true));
}
};
/*
* xml getter
*
* This serializes the DOM tree to an XML String
*
* Usage: var sXml = oNode.xml
*
*/
// XMLDocument did not extend the Document interface in some versions
// of Mozilla. Extend both!
/*
XMLDocument.prototype.__defineGetter__("xml", function () {
return (new XMLSerializer()).serializeToString(this);
});
*/
Document.prototype.__defineGetter__("xml", function () {
return (new XMLSerializer()).serializeToString(this);
});
} | zc.selenium | /zc.selenium-1.2.1.tar.gz/zc.selenium-1.2.1/src/zc/selenium/resources/scripts/xmlextras.js | xmlextras.js |
var CommandHandlerFactory = classCreate();
objectExtend(CommandHandlerFactory.prototype, {
initialize: function() {
this.handlers = {};
},
registerAction: function(name, actionBlock, wait, dontCheckAlertsAndConfirms) {
this.handlers[name] = new ActionHandler(actionBlock, wait, dontCheckAlertsAndConfirms);
},
registerAccessor: function(name, accessBlock) {
this.handlers[name] = new AccessorHandler(accessBlock);
},
registerAssert: function(name, assertBlock, haltOnFailure) {
this.handlers[name] = new AssertHandler(assertBlock, haltOnFailure);
},
getCommandHandler: function(name) {
return this.handlers[name];
},
_registerAllAccessors: function(seleniumApi) {
// Methods of the form getFoo(target) result in commands:
// getFoo, assertFoo, verifyFoo, assertNotFoo, verifyNotFoo
// storeFoo, waitForFoo, and waitForNotFoo.
for (var functionName in seleniumApi) {
var match = /^(get|is)([A-Z].+)$/.exec(functionName);
if (match) {
var accessMethod = seleniumApi[functionName];
var accessBlock = fnBind(accessMethod, seleniumApi);
var baseName = match[2];
var isBoolean = (match[1] == "is");
var requiresTarget = (accessMethod.length == 1);
this.registerAccessor(functionName, accessBlock);
this._registerStoreCommandForAccessor(baseName, accessBlock, requiresTarget);
var predicateBlock = this._predicateForAccessor(accessBlock, requiresTarget, isBoolean);
this._registerAssertionsForPredicate(baseName, predicateBlock);
this._registerWaitForCommandsForPredicate(seleniumApi, baseName, predicateBlock);
}
}
},
_registerAllActions: function(seleniumApi) {
for (var functionName in seleniumApi) {
var match = /^do([A-Z].+)$/.exec(functionName);
if (match) {
var actionName = match[1].lcfirst();
var actionMethod = seleniumApi[functionName];
var dontCheckPopups = actionMethod.dontCheckAlertsAndConfirms;
var actionBlock = fnBind(actionMethod, seleniumApi);
this.registerAction(actionName, actionBlock, false, dontCheckPopups);
this.registerAction(actionName + "AndWait", actionBlock, true, dontCheckPopups);
}
}
},
_registerAllAsserts: function(seleniumApi) {
for (var functionName in seleniumApi) {
var match = /^assert([A-Z].+)$/.exec(functionName);
if (match) {
var assertBlock = fnBind(seleniumApi[functionName], seleniumApi);
// Register the assert with the "assert" prefix, and halt on failure.
var assertName = functionName;
this.registerAssert(assertName, assertBlock, true);
// Register the assert with the "verify" prefix, and do not halt on failure.
var verifyName = "verify" + match[1];
this.registerAssert(verifyName, assertBlock, false);
}
}
},
registerAll: function(seleniumApi) {
this._registerAllAccessors(seleniumApi);
this._registerAllActions(seleniumApi);
this._registerAllAsserts(seleniumApi);
},
_predicateForAccessor: function(accessBlock, requiresTarget, isBoolean) {
if (isBoolean) {
return this._predicateForBooleanAccessor(accessBlock);
}
if (requiresTarget) {
return this._predicateForSingleArgAccessor(accessBlock);
}
return this._predicateForNoArgAccessor(accessBlock);
},
_predicateForSingleArgAccessor: function(accessBlock) {
// Given an accessor function getBlah(target),
// return a "predicate" equivalient to isBlah(target, value) that
// is true when the value returned by the accessor matches the specified value.
return function(target, value) {
var accessorResult = accessBlock(target);
accessorResult = selArrayToString(accessorResult);
if (PatternMatcher.matches(value, accessorResult)) {
return new PredicateResult(true, "Actual value '" + accessorResult + "' did match '" + value + "'");
} else {
return new PredicateResult(false, "Actual value '" + accessorResult + "' did not match '" + value + "'");
}
};
},
_predicateForNoArgAccessor: function(accessBlock) {
// Given a (no-arg) accessor function getBlah(),
// return a "predicate" equivalient to isBlah(value) that
// is true when the value returned by the accessor matches the specified value.
return function(value) {
var accessorResult = accessBlock();
accessorResult = selArrayToString(accessorResult);
if (PatternMatcher.matches(value, accessorResult)) {
return new PredicateResult(true, "Actual value '" + accessorResult + "' did match '" + value + "'");
} else {
return new PredicateResult(false, "Actual value '" + accessorResult + "' did not match '" + value + "'");
}
};
},
_predicateForBooleanAccessor: function(accessBlock) {
// Given a boolean accessor function isBlah(),
// return a "predicate" equivalient to isBlah() that
// returns an appropriate PredicateResult value.
return function() {
var accessorResult;
if (arguments.length > 2) throw new SeleniumError("Too many arguments! " + arguments.length);
if (arguments.length == 2) {
accessorResult = accessBlock(arguments[0], arguments[1]);
} else if (arguments.length == 1) {
accessorResult = accessBlock(arguments[0]);
} else {
accessorResult = accessBlock();
}
if (accessorResult) {
return new PredicateResult(true, "true");
} else {
return new PredicateResult(false, "false");
}
};
},
_invertPredicate: function(predicateBlock) {
// Given a predicate, return the negation of that predicate.
// Leaves the message unchanged.
// Used to create assertNot, verifyNot, and waitForNot commands.
return function(target, value) {
var result = predicateBlock(target, value);
result.isTrue = !result.isTrue;
return result;
};
},
createAssertionFromPredicate: function(predicateBlock) {
// Convert an isBlahBlah(target, value) function into an assertBlahBlah(target, value) function.
return function(target, value) {
var result = predicateBlock(target, value);
if (!result.isTrue) {
Assert.fail(result.message);
}
};
},
_invertPredicateName: function(baseName) {
var matchResult = /^(.*)Present$/.exec(baseName);
if (matchResult != null) {
return matchResult[1] + "NotPresent";
}
return "Not" + baseName;
},
_registerAssertionsForPredicate: function(baseName, predicateBlock) {
// Register an assertion, a verification, a negative assertion,
// and a negative verification based on the specified accessor.
var assertBlock = this.createAssertionFromPredicate(predicateBlock);
this.registerAssert("assert" + baseName, assertBlock, true);
this.registerAssert("verify" + baseName, assertBlock, false);
var invertedPredicateBlock = this._invertPredicate(predicateBlock);
var negativeassertBlock = this.createAssertionFromPredicate(invertedPredicateBlock);
this.registerAssert("assert" + this._invertPredicateName(baseName), negativeassertBlock, true);
this.registerAssert("verify" + this._invertPredicateName(baseName), negativeassertBlock, false);
},
_waitForActionForPredicate: function(predicateBlock) {
// Convert an isBlahBlah(target, value) function into a waitForBlahBlah(target, value) function.
return function(target, value) {
var terminationCondition = function () {
try {
return predicateBlock(target, value).isTrue;
} catch (e) {
// Treat exceptions as meaning the condition is not yet met.
// Useful, for example, for waitForValue when the element has
// not even been created yet.
// TODO: possibly should rethrow some types of exception.
return false;
}
};
return Selenium.decorateFunctionWithTimeout(terminationCondition, this.defaultTimeout);
};
},
_registerWaitForCommandsForPredicate: function(seleniumApi, baseName, predicateBlock) {
// Register a waitForBlahBlah and waitForNotBlahBlah based on the specified accessor.
var waitForActionMethod = this._waitForActionForPredicate(predicateBlock);
var waitForActionBlock = fnBind(waitForActionMethod, seleniumApi);
var invertedPredicateBlock = this._invertPredicate(predicateBlock);
var waitForNotActionMethod = this._waitForActionForPredicate(invertedPredicateBlock);
var waitForNotActionBlock = fnBind(waitForNotActionMethod, seleniumApi);
this.registerAction("waitFor" + baseName, waitForActionBlock, false, true);
this.registerAction("waitFor" + this._invertPredicateName(baseName), waitForNotActionBlock, false, true);
//TODO decide remove "waitForNot.*Present" action name or not
//for the back compatiblity issues we still make waitForNot.*Present availble
this.registerAction("waitForNot" + baseName, waitForNotActionBlock, false, true);
},
_registerStoreCommandForAccessor: function(baseName, accessBlock, requiresTarget) {
var action;
if (requiresTarget) {
action = function(target, varName) {
storedVars[varName] = accessBlock(target);
};
} else {
action = function(varName) {
storedVars[varName] = accessBlock();
};
}
this.registerAction("store" + baseName, action, false, true);
}
});
function PredicateResult(isTrue, message) {
this.isTrue = isTrue;
this.message = message;
}
// NOTE: The CommandHandler is effectively an abstract base for
// various handlers including ActionHandler, AccessorHandler and AssertHandler.
// Subclasses need to implement an execute(seleniumApi, command) function,
// where seleniumApi is the Selenium object, and command a SeleniumCommand object.
function CommandHandler(type, haltOnFailure) {
this.type = type;
this.haltOnFailure = haltOnFailure;
}
// An ActionHandler is a command handler that executes the sepcified action,
// possibly checking for alerts and confirmations (if checkAlerts is set), and
// possibly waiting for a page load if wait is set.
function ActionHandler(actionBlock, wait, dontCheckAlerts) {
this.actionBlock = actionBlock;
CommandHandler.call(this, "action", true);
if (wait) {
this.wait = true;
}
// note that dontCheckAlerts could be undefined!!!
this.checkAlerts = (dontCheckAlerts) ? false : true;
}
ActionHandler.prototype = new CommandHandler;
ActionHandler.prototype.execute = function(seleniumApi, command) {
if (this.checkAlerts && (null == /(Alert|Confirmation)(Not)?Present/.exec(command.command))) {
// todo: this conditional logic is ugly
seleniumApi.ensureNoUnhandledPopups();
}
var terminationCondition = this.actionBlock(command.target, command.value);
// If the handler didn't return a wait flag, check to see if the
// handler was registered with the wait flag.
if (terminationCondition == undefined && this.wait) {
terminationCondition = seleniumApi.makePageLoadCondition();
}
return new ActionResult(terminationCondition);
};
function ActionResult(terminationCondition) {
this.terminationCondition = terminationCondition;
}
function AccessorHandler(accessBlock) {
this.accessBlock = accessBlock;
CommandHandler.call(this, "accessor", true);
}
AccessorHandler.prototype = new CommandHandler;
AccessorHandler.prototype.execute = function(seleniumApi, command) {
var returnValue = this.accessBlock(command.target, command.value);
return new AccessorResult(returnValue);
};
function AccessorResult(result) {
this.result = result;
}
/**
* Handler for assertions and verifications.
*/
function AssertHandler(assertBlock, haltOnFailure) {
this.assertBlock = assertBlock;
CommandHandler.call(this, "assert", haltOnFailure || false);
}
AssertHandler.prototype = new CommandHandler;
AssertHandler.prototype.execute = function(seleniumApi, command) {
var result = new AssertResult();
try {
this.assertBlock(command.target, command.value);
} catch (e) {
// If this is not a AssertionFailedError, or we should haltOnFailure, rethrow.
if (!e.isAssertionFailedError) {
throw e;
}
if (this.haltOnFailure) {
var error = new SeleniumError(e.failureMessage);
throw error;
}
result.setFailed(e.failureMessage);
}
return result;
};
function AssertResult() {
this.passed = true;
}
AssertResult.prototype.setFailed = function(message) {
this.passed = null;
this.failed = true;
this.failureMessage = message;
}
function SeleniumCommand(command, target, value, isBreakpoint) {
this.command = command;
this.target = target;
this.value = value;
this.isBreakpoint = isBreakpoint;
} | zc.selenium | /zc.selenium-1.2.1.tar.gz/zc.selenium-1.2.1/src/zc/selenium/resources/scripts/selenium-commandhandlers.js | selenium-commandhandlers.js |
* Narcissus - JS implemented in JS.
*
* Execution of parse trees.
*
* Standard classes except for eval, Function, Array, and String are borrowed
* from the host JS environment. Function is metacircular. Array and String
* are reflected via wrapping the corresponding native constructor and adding
* an extra level of prototype-based delegation.
*/
// jrh
//module('JS.Exec');
// end jrh
GLOBAL_CODE = 0; EVAL_CODE = 1; FUNCTION_CODE = 2;
function ExecutionContext(type) {
this.type = type;
}
// jrh
var agenda = new Array();
var skip_setup = 0;
// end jrh
var global = {
// Value properties.
NaN: NaN, Infinity: Infinity, undefined: undefined,
alert : function(msg) { alert(msg) },
confirm : function(msg) { return confirm(msg) },
document : document,
window : window,
// jrh
//debug: window.open('','debugwindow','width=600,height=400,scrollbars=yes,resizable=yes'),
// end jrh
navigator : navigator,
XMLHttpRequest : function() { return new XMLHttpRequest() },
// Function properties.
eval: function(s) {
if (typeof s != "string") {
return s;
}
var x = ExecutionContext.current;
var x2 = new ExecutionContext(EVAL_CODE);
x2.thisObject = x.thisObject;
x2.caller = x.caller;
x2.callee = x.callee;
x2.scope = x.scope;
ExecutionContext.current = x2;
try {
execute(parse(s), x2);
} catch (e) {
x.result = x2.result;
throw e;
} finally {
ExecutionContext.current = x;
}
return x2.result;
},
parseInt: parseInt, parseFloat: parseFloat,
isNaN: isNaN, isFinite: isFinite,
decodeURI: decodeURI, encodeURI: encodeURI,
decodeURIComponent: decodeURIComponent,
encodeURIComponent: encodeURIComponent,
// Class constructors. Where ECMA-262 requires C.length == 1, we declare
// a dummy formal parameter.
Object: Object,
Function: function(dummy) {
var p = "", b = "", n = arguments.length;
if (n) {
var m = n - 1;
if (m) {
p += arguments[0];
for (var k = 1; k < m; k++)
p += "," + arguments[k];
}
b += arguments[m];
}
// XXX We want to pass a good file and line to the tokenizer.
// Note the anonymous name to maintain parity with Spidermonkey.
var t = new Tokenizer("anonymous(" + p + ") {" + b + "}");
// NB: Use the STATEMENT_FORM constant since we don't want to push this
// function onto the null compilation context.
var f = FunctionDefinition(t, null, false, STATEMENT_FORM);
var s = {object: global, parent: null};
return new FunctionObject(f, s);
},
Array: function(dummy) {
// Array when called as a function acts as a constructor.
return GLOBAL.Array.apply(this, arguments);
},
String: function(s) {
// Called as function or constructor: convert argument to string type.
s = arguments.length ? "" + s : "";
if (this instanceof String) {
// Called as constructor: save the argument as the string value
// of this String object and return this object.
this.value = s;
return this;
}
return s;
},
Boolean: Boolean, Number: Number, Date: Date, RegExp: RegExp,
Error: Error, EvalError: EvalError, RangeError: RangeError,
ReferenceError: ReferenceError, SyntaxError: SyntaxError,
TypeError: TypeError, URIError: URIError,
// Other properties.
Math: Math,
// Extensions to ECMA.
//snarf: snarf,
evaluate: evaluate,
load: function(s) {
if (typeof s != "string")
return s;
var req = new XMLHttpRequest();
req.open('GET', s, false);
req.send(null);
evaluate(req.responseText, s, 1)
},
print: print, version: null
};
// jrh
//global.debug.document.body.innerHTML = ''
// end jrh
// Helper to avoid Object.prototype.hasOwnProperty polluting scope objects.
function hasDirectProperty(o, p) {
return Object.prototype.hasOwnProperty.call(o, p);
}
// Reflect a host class into the target global environment by delegation.
function reflectClass(name, proto) {
var gctor = global[name];
gctor.prototype = proto;
proto.constructor = gctor;
return proto;
}
// Reflect Array -- note that all Array methods are generic.
reflectClass('Array', new Array);
// Reflect String, overriding non-generic methods.
var gSp = reflectClass('String', new String);
gSp.toSource = function () { return this.value.toSource(); };
gSp.toString = function () { return this.value; };
gSp.valueOf = function () { return this.value; };
global.String.fromCharCode = String.fromCharCode;
var XCp = ExecutionContext.prototype;
ExecutionContext.current = XCp.caller = XCp.callee = null;
XCp.scope = {object: global, parent: null};
XCp.thisObject = global;
XCp.result = undefined;
XCp.target = null;
XCp.ecmaStrictMode = false;
function Reference(base, propertyName, node) {
this.base = base;
this.propertyName = propertyName;
this.node = node;
}
Reference.prototype.toString = function () { return this.node.getSource(); }
function getValue(v) {
if (v instanceof Reference) {
if (!v.base) {
throw new ReferenceError(v.propertyName + " is not defined",
v.node.filename(), v.node.lineno);
}
return v.base[v.propertyName];
}
return v;
}
function putValue(v, w, vn) {
if (v instanceof Reference)
return (v.base || global)[v.propertyName] = w;
throw new ReferenceError("Invalid assignment left-hand side",
vn.filename(), vn.lineno);
}
function isPrimitive(v) {
var t = typeof v;
return (t == "object") ? v === null : t != "function";
}
function isObject(v) {
var t = typeof v;
return (t == "object") ? v !== null : t == "function";
}
// If r instanceof Reference, v == getValue(r); else v === r. If passed, rn
// is the node whose execute result was r.
function toObject(v, r, rn) {
switch (typeof v) {
case "boolean":
return new global.Boolean(v);
case "number":
return new global.Number(v);
case "string":
return new global.String(v);
case "function":
return v;
case "object":
if (v !== null)
return v;
}
var message = r + " (type " + (typeof v) + ") has no properties";
throw rn ? new TypeError(message, rn.filename(), rn.lineno)
: new TypeError(message);
}
function execute(n, x) {
if (!this.new_block)
new_block = new Array();
//alert (n)
var a, f, i, j, r, s, t, u, v;
switch (n.type) {
case FUNCTION:
if (n.functionForm != DECLARED_FORM) {
if (!n.name || n.functionForm == STATEMENT_FORM) {
v = new FunctionObject(n, x.scope);
if (n.functionForm == STATEMENT_FORM)
x.scope.object[n.name] = v;
} else {
t = new Object;
x.scope = {object: t, parent: x.scope};
try {
v = new FunctionObject(n, x.scope);
t[n.name] = v;
} finally {
x.scope = x.scope.parent;
}
}
}
break;
case SCRIPT:
t = x.scope.object;
a = n.funDecls;
for (i = 0, j = a.length; i < j; i++) {
s = a[i].name;
f = new FunctionObject(a[i], x.scope);
t[s] = f;
}
a = n.varDecls;
for (i = 0, j = a.length; i < j; i++) {
u = a[i];
s = u.name;
if (u.readOnly && hasDirectProperty(t, s)) {
throw new TypeError("Redeclaration of const " + s,
u.filename(), u.lineno);
}
if (u.readOnly || !hasDirectProperty(t, s)) {
t[s] = null;
}
}
// FALL THROUGH
case BLOCK:
for (i = 0, j = n.$length; i < j; i++) {
//jrh
//execute(n[i], x);
//new_block.unshift([n[i], x]);
new_block.push([n[i], x]);
}
new_block.reverse();
agenda = agenda.concat(new_block);
//agenda = new_block.concat(agenda)
// end jrh
break;
case IF:
if (getValue(execute(n.condition, x)))
execute(n.thenPart, x);
else if (n.elsePart)
execute(n.elsePart, x);
break;
case SWITCH:
s = getValue(execute(n.discriminant, x));
a = n.cases;
var matchDefault = false;
switch_loop:
for (i = 0, j = a.length; ; i++) {
if (i == j) {
if (n.defaultIndex >= 0) {
i = n.defaultIndex - 1; // no case matched, do default
matchDefault = true;
continue;
}
break; // no default, exit switch_loop
}
t = a[i]; // next case (might be default!)
if (t.type == CASE) {
u = getValue(execute(t.caseLabel, x));
} else {
if (!matchDefault) // not defaulting, skip for now
continue;
u = s; // force match to do default
}
if (u === s) {
for (;;) { // this loop exits switch_loop
if (t.statements.length) {
try {
execute(t.statements, x);
} catch (e) {
if (!(e == BREAK && x.target == n)) { throw e }
break switch_loop;
}
}
if (++i == j)
break switch_loop;
t = a[i];
}
// NOT REACHED
}
}
break;
case FOR:
// jrh
// added "skip_setup" so initialization doesn't get called
// on every call..
if (!skip_setup)
n.setup && getValue(execute(n.setup, x));
// FALL THROUGH
case WHILE:
// jrh
//while (!n.condition || getValue(execute(n.condition, x))) {
if (!n.condition || getValue(execute(n.condition, x))) {
try {
// jrh
//execute(n.body, x);
new_block.push([n.body, x]);
agenda.push([n.body, x])
//agenda.unshift([n.body, x])
// end jrh
} catch (e) {
if (e == BREAK && x.target == n) {
break;
} else if (e == CONTINUE && x.target == n) {
// jrh
// 'continue' is invalid inside an 'if' clause
// I don't know what commenting this out will break!
//continue;
// end jrh
} else {
throw e;
}
}
n.update && getValue(execute(n.update, x));
// jrh
new_block.unshift([n, x])
agenda.splice(agenda.length-1,0,[n, x])
//agenda.splice(1,0,[n, x])
skip_setup = 1
// end jrh
} else {
skip_setup = 0
}
break;
case FOR_IN:
u = n.varDecl;
if (u)
execute(u, x);
r = n.iterator;
s = execute(n.object, x);
v = getValue(s);
// ECMA deviation to track extant browser JS implementation behavior.
t = (v == null && !x.ecmaStrictMode) ? v : toObject(v, s, n.object);
a = [];
for (i in t)
a.push(i);
for (i = 0, j = a.length; i < j; i++) {
putValue(execute(r, x), a[i], r);
try {
execute(n.body, x);
} catch (e) {
if (e == BREAK && x.target == n) {
break;
} else if (e == CONTINUE && x.target == n) {
continue;
} else {
throw e;
}
}
}
break;
case DO:
do {
try {
execute(n.body, x);
} catch (e) {
if (e == BREAK && x.target == n) {
break;
} else if (e == CONTINUE && x.target == n) {
continue;
} else {
throw e;
}
}
} while (getValue(execute(n.condition, x)));
break;
case BREAK:
case CONTINUE:
x.target = n.target;
throw n.type;
case TRY:
try {
execute(n.tryBlock, x);
} catch (e) {
if (!(e == THROW && (j = n.catchClauses.length))) {
throw e;
}
e = x.result;
x.result = undefined;
for (i = 0; ; i++) {
if (i == j) {
x.result = e;
throw THROW;
}
t = n.catchClauses[i];
x.scope = {object: {}, parent: x.scope};
x.scope.object[t.varName] = e;
try {
if (t.guard && !getValue(execute(t.guard, x)))
continue;
execute(t.block, x);
break;
} finally {
x.scope = x.scope.parent;
}
}
} finally {
if (n.finallyBlock)
execute(n.finallyBlock, x);
}
break;
case THROW:
x.result = getValue(execute(n.exception, x));
throw THROW;
case RETURN:
x.result = getValue(execute(n.value, x));
throw RETURN;
case WITH:
r = execute(n.object, x);
t = toObject(getValue(r), r, n.object);
x.scope = {object: t, parent: x.scope};
try {
execute(n.body, x);
} finally {
x.scope = x.scope.parent;
}
break;
case VAR:
case CONST:
for (i = 0, j = n.$length; i < j; i++) {
u = n[i].initializer;
if (!u)
continue;
t = n[i].name;
for (s = x.scope; s; s = s.parent) {
if (hasDirectProperty(s.object, t))
break;
}
u = getValue(execute(u, x));
if (n.type == CONST)
s.object[t] = u;
else
s.object[t] = u;
}
break;
case DEBUGGER:
throw "NYI: " + tokens[n.type];
case REQUIRE:
var req = new XMLHttpRequest();
req.open('GET', n.filename, 'false');
case SEMICOLON:
if (n.expression)
// print debugging statements
var the_start = n.start
var the_end = n.end
var the_statement = parse_result.tokenizer.source.slice(the_start,the_end)
//global.debug.document.body.innerHTML += ('<pre>>>> <b>' + the_statement + '</b></pre>')
LOG.info('>>>' + the_statement)
x.result = getValue(execute(n.expression, x));
//if (x.result)
//global.debug.document.body.innerHTML += ( '<pre>>>> ' + x.result + '</pre>')
break;
case LABEL:
try {
execute(n.statement, x);
} catch (e) {
if (!(e == BREAK && x.target == n)) { throw e }
}
break;
case COMMA:
for (i = 0, j = n.$length; i < j; i++)
v = getValue(execute(n[i], x));
break;
case ASSIGN:
r = execute(n[0], x);
t = n[0].assignOp;
if (t)
u = getValue(r);
v = getValue(execute(n[1], x));
if (t) {
switch (t) {
case BITWISE_OR: v = u | v; break;
case BITWISE_XOR: v = u ^ v; break;
case BITWISE_AND: v = u & v; break;
case LSH: v = u << v; break;
case RSH: v = u >> v; break;
case URSH: v = u >>> v; break;
case PLUS: v = u + v; break;
case MINUS: v = u - v; break;
case MUL: v = u * v; break;
case DIV: v = u / v; break;
case MOD: v = u % v; break;
}
}
putValue(r, v, n[0]);
break;
case CONDITIONAL:
v = getValue(execute(n[0], x)) ? getValue(execute(n[1], x))
: getValue(execute(n[2], x));
break;
case OR:
v = getValue(execute(n[0], x)) || getValue(execute(n[1], x));
break;
case AND:
v = getValue(execute(n[0], x)) && getValue(execute(n[1], x));
break;
case BITWISE_OR:
v = getValue(execute(n[0], x)) | getValue(execute(n[1], x));
break;
case BITWISE_XOR:
v = getValue(execute(n[0], x)) ^ getValue(execute(n[1], x));
break;
case BITWISE_AND:
v = getValue(execute(n[0], x)) & getValue(execute(n[1], x));
break;
case EQ:
v = getValue(execute(n[0], x)) == getValue(execute(n[1], x));
break;
case NE:
v = getValue(execute(n[0], x)) != getValue(execute(n[1], x));
break;
case STRICT_EQ:
v = getValue(execute(n[0], x)) === getValue(execute(n[1], x));
break;
case STRICT_NE:
v = getValue(execute(n[0], x)) !== getValue(execute(n[1], x));
break;
case LT:
v = getValue(execute(n[0], x)) < getValue(execute(n[1], x));
break;
case LE:
v = getValue(execute(n[0], x)) <= getValue(execute(n[1], x));
break;
case GE:
v = getValue(execute(n[0], x)) >= getValue(execute(n[1], x));
break;
case GT:
v = getValue(execute(n[0], x)) > getValue(execute(n[1], x));
break;
case IN:
v = getValue(execute(n[0], x)) in getValue(execute(n[1], x));
break;
case INSTANCEOF:
t = getValue(execute(n[0], x));
u = getValue(execute(n[1], x));
if (isObject(u) && typeof u.__hasInstance__ == "function")
v = u.__hasInstance__(t);
else
v = t instanceof u;
break;
case LSH:
v = getValue(execute(n[0], x)) << getValue(execute(n[1], x));
break;
case RSH:
v = getValue(execute(n[0], x)) >> getValue(execute(n[1], x));
break;
case URSH:
v = getValue(execute(n[0], x)) >>> getValue(execute(n[1], x));
break;
case PLUS:
v = getValue(execute(n[0], x)) + getValue(execute(n[1], x));
break;
case MINUS:
v = getValue(execute(n[0], x)) - getValue(execute(n[1], x));
break;
case MUL:
v = getValue(execute(n[0], x)) * getValue(execute(n[1], x));
break;
case DIV:
v = getValue(execute(n[0], x)) / getValue(execute(n[1], x));
break;
case MOD:
v = getValue(execute(n[0], x)) % getValue(execute(n[1], x));
break;
case DELETE:
t = execute(n[0], x);
v = !(t instanceof Reference) || delete t.base[t.propertyName];
break;
case VOID:
getValue(execute(n[0], x));
break;
case TYPEOF:
t = execute(n[0], x);
if (t instanceof Reference)
t = t.base ? t.base[t.propertyName] : undefined;
v = typeof t;
break;
case NOT:
v = !getValue(execute(n[0], x));
break;
case BITWISE_NOT:
v = ~getValue(execute(n[0], x));
break;
case UNARY_PLUS:
v = +getValue(execute(n[0], x));
break;
case UNARY_MINUS:
v = -getValue(execute(n[0], x));
break;
case INCREMENT:
case DECREMENT:
t = execute(n[0], x);
u = Number(getValue(t));
if (n.postfix)
v = u;
putValue(t, (n.type == INCREMENT) ? ++u : --u, n[0]);
if (!n.postfix)
v = u;
break;
case DOT:
r = execute(n[0], x);
t = getValue(r);
u = n[1].value;
v = new Reference(toObject(t, r, n[0]), u, n);
break;
case INDEX:
r = execute(n[0], x);
t = getValue(r);
u = getValue(execute(n[1], x));
v = new Reference(toObject(t, r, n[0]), String(u), n);
break;
case LIST:
// Curse ECMA for specifying that arguments is not an Array object!
v = {};
for (i = 0, j = n.$length; i < j; i++) {
u = getValue(execute(n[i], x));
v[i] = u;
}
v.length = i;
break;
case CALL:
r = execute(n[0], x);
a = execute(n[1], x);
f = getValue(r);
if (isPrimitive(f) || typeof f.__call__ != "function") {
throw new TypeError(r + " is not callable",
n[0].filename(), n[0].lineno);
}
t = (r instanceof Reference) ? r.base : null;
if (t instanceof Activation)
t = null;
v = f.__call__(t, a, x);
break;
case NEW:
case NEW_WITH_ARGS:
r = execute(n[0], x);
f = getValue(r);
if (n.type == NEW) {
a = {};
a.length = 0;
} else {
a = execute(n[1], x);
}
if (isPrimitive(f) || typeof f.__construct__ != "function") {
throw new TypeError(r + " is not a constructor",
n[0].filename(), n[0].lineno);
}
v = f.__construct__(a, x);
break;
case ARRAY_INIT:
v = [];
for (i = 0, j = n.$length; i < j; i++) {
if (n[i])
v[i] = getValue(execute(n[i], x));
}
v.length = j;
break;
case OBJECT_INIT:
v = {};
for (i = 0, j = n.$length; i < j; i++) {
t = n[i];
if (t.type == PROPERTY_INIT) {
v[t[0].value] = getValue(execute(t[1], x));
} else {
f = new FunctionObject(t, x.scope);
/*
u = (t.type == GETTER) ? '__defineGetter__'
: '__defineSetter__';
v[u](t.name, thunk(f, x));
*/
}
}
break;
case NULL:
v = null;
break;
case THIS:
v = x.thisObject;
break;
case TRUE:
v = true;
break;
case FALSE:
v = false;
break;
case IDENTIFIER:
for (s = x.scope; s; s = s.parent) {
if (n.value in s.object)
break;
}
v = new Reference(s && s.object, n.value, n);
break;
case NUMBER:
case STRING:
case REGEXP:
v = n.value;
break;
case GROUP:
v = execute(n[0], x);
break;
default:
throw "PANIC: unknown operation " + n.type + ": " + uneval(n);
}
return v;
}
function Activation(f, a) {
for (var i = 0, j = f.params.length; i < j; i++)
this[f.params[i]] = a[i];
this.arguments = a;
}
// Null Activation.prototype's proto slot so that Object.prototype.* does not
// pollute the scope of heavyweight functions. Also delete its 'constructor'
// property so that it doesn't pollute function scopes.
Activation.prototype.__proto__ = null;
delete Activation.prototype.constructor;
function FunctionObject(node, scope) {
this.node = node;
this.scope = scope;
this.length = node.params.length;
var proto = {};
this.prototype = proto;
proto.constructor = this;
}
var FOp = FunctionObject.prototype = {
// Internal methods.
__call__: function (t, a, x) {
var x2 = new ExecutionContext(FUNCTION_CODE);
x2.thisObject = t || global;
x2.caller = x;
x2.callee = this;
a.callee = this;
var f = this.node;
x2.scope = {object: new Activation(f, a), parent: this.scope};
ExecutionContext.current = x2;
try {
execute(f.body, x2);
} catch (e) {
if (!(e == RETURN)) { throw e } else if (e == RETURN) {
return x2.result;
}
if (e != THROW) { throw e }
x.result = x2.result;
throw THROW;
} finally {
ExecutionContext.current = x;
}
return undefined;
},
__construct__: function (a, x) {
var o = new Object;
var p = this.prototype;
if (isObject(p))
o.__proto__ = p;
// else o.__proto__ defaulted to Object.prototype
var v = this.__call__(o, a, x);
if (isObject(v))
return v;
return o;
},
__hasInstance__: function (v) {
if (isPrimitive(v))
return false;
var p = this.prototype;
if (isPrimitive(p)) {
throw new TypeError("'prototype' property is not an object",
this.node.filename(), this.node.lineno);
}
var o;
while ((o = v.__proto__)) {
if (o == p)
return true;
v = o;
}
return false;
},
// Standard methods.
toString: function () {
return this.node.getSource();
},
apply: function (t, a) {
// Curse ECMA again!
if (typeof this.__call__ != "function") {
throw new TypeError("Function.prototype.apply called on" +
" uncallable object");
}
if (t === undefined || t === null)
t = global;
else if (typeof t != "object")
t = toObject(t, t);
if (a === undefined || a === null) {
a = {};
a.length = 0;
} else if (a instanceof Array) {
var v = {};
for (var i = 0, j = a.length; i < j; i++)
v[i] = a[i];
v.length = i;
a = v;
} else if (!(a instanceof Object)) {
// XXX check for a non-arguments object
throw new TypeError("Second argument to Function.prototype.apply" +
" must be an array or arguments object",
this.node.filename(), this.node.lineno);
}
return this.__call__(t, a, ExecutionContext.current);
},
call: function (t) {
// Curse ECMA a third time!
var a = Array.prototype.splice.call(arguments, 1);
return this.apply(t, a);
}
};
// Connect Function.prototype and Function.prototype.constructor in global.
reflectClass('Function', FOp);
// Help native and host-scripted functions be like FunctionObjects.
var Fp = Function.prototype;
var REp = RegExp.prototype;
if (!('__call__' in Fp)) {
Fp.__call__ = function (t, a, x) {
// Curse ECMA yet again!
a = Array.prototype.splice.call(a, 0, a.length);
return this.apply(t, a);
};
REp.__call__ = function (t, a, x) {
a = Array.prototype.splice.call(a, 0, a.length);
return this.exec.apply(this, a);
};
Fp.__construct__ = function (a, x) {
switch (a.length) {
case 0:
return new this();
case 1:
return new this(a[0]);
case 2:
return new this(a[0], a[1]);
case 3:
return new this(a[0], a[1], a[2]);
case 4:
return new this(a[0], a[1], a[2], a[3]);
case 5:
return new this(a[0], a[1], a[2], a[3], a[4]);
case 6:
return new this(a[0], a[1], a[2], a[3], a[4], a[5]);
case 7:
return new this(a[0], a[1], a[2], a[3], a[4], a[5], a[6]);
}
throw "PANIC: too many arguments to constructor";
}
// Since we use native functions such as Date along with host ones such
// as global.eval, we want both to be considered instances of the native
// Function constructor.
Fp.__hasInstance__ = function (v) {
return v instanceof Function || v instanceof global.Function;
};
}
function thunk(f, x) {
return function () { return f.__call__(this, arguments, x); };
}
function evaluate(s, f, l) {
if (typeof s != "string")
return s;
var x = ExecutionContext.current;
var x2 = new ExecutionContext(GLOBAL_CODE);
ExecutionContext.current = x2;
try {
execute(parse(s, f, l), x2);
} catch (e) {
if (e != THROW) { throw e }
if (x) {
x.result = x2.result;
throw(THROW);
}
throw x2.result;
} finally {
ExecutionContext.current = x;
}
return x2.result;
} | zc.selenium | /zc.selenium-1.2.1.tar.gz/zc.selenium-1.2.1/src/zc/selenium/resources/scripts/narcissus-exec.js | narcissus-exec.js |
var HIDDEN="hidden";
var LEVEL = "level";
var PLUS_SRC="butplus.gif";
var MIN_SRC="butmin.gif";
var newRoot;
var maxColumns=1;
function loadDomViewer() {
// See if the rootDocument variable has been set on this window.
var rootDocument = window.rootDocument;
// If not look to the opener for an explicity rootDocument variable, otherwise, use the opener document
if (!rootDocument && window.opener) {
rootDocument = window.opener.rootDocument || window.opener.document;
}
if (rootDocument) {
document.body.innerHTML = displayDOM(rootDocument);
}
else {
document.body.innerHTML = "<b>Must specify rootDocument for window. This can be done by setting the rootDocument variable on this window, or on the opener window for a popup window.</b>";
}
}
function displayDOM(root){
var str = "";
str+="<table>";
str += treeTraversal(root,0);
// to make table columns work well.
str += "<tr>";
for (var i=0; i < maxColumns; i++) {
str+= "<td> </td>";
}
str += "</tr>";
str += "</table>";
return str;
}
function checkForChildren(element){
if(!element.hasChildNodes())
return false;
var nodes = element.childNodes;
var size = nodes.length;
var count=0;
for(var i=0; i< size; i++){
var node = nodes.item(i);
//if(node.toString()=="[object Text]"){
//this is equalent to the above
//but will work with more browsers
if(node.nodeType!=1){
count++;
}
}
if(count == size)
return false;
else
return true;
}
function treeTraversal(root, level){
var str = "";
var nodes= null;
var size = null;
//it is supposed to show the last node,
//but the last node is always nodeText type
//and we don't show it
if(!root.hasChildNodes())
return "";//displayNode(root,level,false);
nodes = root.childNodes;
size = nodes.length;
for(var i=0; i< size; i++){
var element = nodes.item(i);
//if the node is textNode, don't display
if(element.nodeType==1){
str+= displayNode(element,level,checkForChildren(element));
str+=treeTraversal(element, level+1);
}
}
return str;
}
function displayNode(element, level, isLink){
nodeContent = getNodeContent(element);
columns = Math.round((nodeContent.length / 12) + 0.5);
if (columns + level > maxColumns) {
maxColumns = columns + level;
}
var str ="<tr class='"+LEVEL+level+"'>";
for (var i=0; i < level; i++)
str+= "<td> </td>";
str+="<td colspan='"+ columns +"' class='box"+" boxlevel"+level+"' >";
if(isLink){
str+='<a onclick="hide(this);return false;" href="javascript:void();">';
str+='<img src="'+MIN_SRC+'" />';
}
str += nodeContent;
if(isLink)
str+="</a></td></tr>";
return str;
}
function getNodeContent(element) {
str = "";
id ="";
if (element.id != null && element.id != "") {
id = " ID(" + element.id +")";
}
name ="";
if (element.name != null && element.name != "") {
name = " NAME(" + element.name + ")";
}
value ="";
if (element.value != null && element.value != "") {
value = " VALUE(" + element.value + ")";
}
href ="";
if (element.href != null && element.href != "") {
href = " HREF(" + element.href + ")";
}
clazz = "";
if (element.className != null && element.className != "") {
clazz = " CLASS(" + element.className + ")";
}
src = "";
if (element.src != null && element.src != "") {
src = " SRC(" + element.src + ")";
}
alt = "";
if (element.alt != null && element.alt != "") {
alt = " ALT(" + element.alt + ")";
}
type = "";
if (element.type != null && element.type != "") {
type = " TYPE(" + element.type + ")";
}
text ="";
if (element.text != null && element.text != "" && element.text != "undefined") {
text = " #TEXT(" + trim(element.text) +")";
}
str+=" <b>"+ element.nodeName + id + alt + type + clazz + name + value + href + src + text + "</b>";
return str;
}
function trim(val) {
val2 = val.substring(0,40) + " ";
var spaceChr = String.fromCharCode(32);
var length = val2.length;
var retVal = "";
var ix = length -1;
while(ix > -1){
if(val2.charAt(ix) == spaceChr) {
} else {
retVal = val2.substring(0, ix +1);
break;
}
ix = ix-1;
}
if (val.length > 40) {
retVal += "...";
}
return retVal;
}
function hide(hlink){
var isHidden = false;
var image = hlink.firstChild;
if(image.src.toString().indexOf(MIN_SRC)!=-1){
image.src=PLUS_SRC;
isHidden=true;
}else{
image.src=MIN_SRC;
}
var rowObj= hlink.parentNode.parentNode;
var rowLevel = parseInt(rowObj.className.substring(LEVEL.length));
var sibling = rowObj.nextSibling;
var siblingLevel = sibling.className.substring(LEVEL.length);
if(siblingLevel.indexOf(HIDDEN)!=-1){
siblingLevel = siblingLevel.substring(0,siblingLevel.length - HIDDEN.length-1);
}
siblingLevel=parseInt(siblingLevel);
while(sibling!=null && rowLevel<siblingLevel){
if(isHidden){
sibling.className += " "+ HIDDEN;
}else if(!isHidden && sibling.className.indexOf(HIDDEN)!=-1){
var str = sibling.className;
sibling.className=str.substring(0, str.length - HIDDEN.length-1);
}
sibling = sibling.nextSibling;
siblingLevel = parseInt(sibling.className.substring(LEVEL.length));
}
}
function LOG(message) {
window.opener.LOG.warn(message);
} | zc.selenium | /zc.selenium-1.2.1.tar.gz/zc.selenium-1.2.1/src/zc/selenium/resources/domviewer/selenium-domviewer.js | selenium-domviewer.js |
var Prototype = {
Version: '1.5.0_rc0',
ScriptFragment: '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)',
emptyFunction: function() {},
K: function(x) {return x}
}
var Class = {
create: function() {
return function() {
this.initialize.apply(this, arguments);
}
}
}
var Abstract = new Object();
Object.extend = function(destination, source) {
for (var property in source) {
destination[property] = source[property];
}
return destination;
}
Object.inspect = function(object) {
try {
if (object == undefined) return 'undefined';
if (object == null) return 'null';
return object.inspect ? object.inspect() : object.toString();
} catch (e) {
if (e instanceof RangeError) return '...';
throw e;
}
}
Function.prototype.bind = function() {
var __method = this, args = $A(arguments), object = args.shift();
return function() {
return __method.apply(object, args.concat($A(arguments)));
}
}
Function.prototype.bindAsEventListener = function(object) {
var __method = this;
return function(event) {
return __method.call(object, event || window.event);
}
}
Object.extend(Number.prototype, {
toColorPart: function() {
var digits = this.toString(16);
if (this < 16) return '0' + digits;
return digits;
},
succ: function() {
return this + 1;
},
times: function(iterator) {
$R(0, this, true).each(iterator);
return this;
}
});
var Try = {
these: function() {
var returnValue;
for (var i = 0; i < arguments.length; i++) {
var lambda = arguments[i];
try {
returnValue = lambda();
break;
} catch (e) {}
}
return returnValue;
}
}
/*--------------------------------------------------------------------------*/
var PeriodicalExecuter = Class.create();
PeriodicalExecuter.prototype = {
initialize: function(callback, frequency) {
this.callback = callback;
this.frequency = frequency;
this.currentlyExecuting = false;
this.registerCallback();
},
registerCallback: function() {
setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
},
onTimerEvent: function() {
if (!this.currentlyExecuting) {
try {
this.currentlyExecuting = true;
this.callback();
} finally {
this.currentlyExecuting = false;
}
}
}
}
Object.extend(String.prototype, {
gsub: function(pattern, replacement) {
var result = '', source = this, match;
replacement = arguments.callee.prepareReplacement(replacement);
while (source.length > 0) {
if (match = source.match(pattern)) {
result += source.slice(0, match.index);
result += (replacement(match) || '').toString();
source = source.slice(match.index + match[0].length);
} else {
result += source, source = '';
}
}
return result;
},
sub: function(pattern, replacement, count) {
replacement = this.gsub.prepareReplacement(replacement);
count = count === undefined ? 1 : count;
return this.gsub(pattern, function(match) {
if (--count < 0) return match[0];
return replacement(match);
});
},
scan: function(pattern, iterator) {
this.gsub(pattern, iterator);
return this;
},
truncate: function(length, truncation) {
length = length || 30;
truncation = truncation === undefined ? '...' : truncation;
return this.length > length ?
this.slice(0, length - truncation.length) + truncation : this;
},
strip: function() {
return this.replace(/^\s+/, '').replace(/\s+$/, '');
},
stripTags: function() {
return this.replace(/<\/?[^>]+>/gi, '');
},
stripScripts: function() {
return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
},
extractScripts: function() {
var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
return (this.match(matchAll) || []).map(function(scriptTag) {
return (scriptTag.match(matchOne) || ['', ''])[1];
});
},
evalScripts: function() {
return this.extractScripts().map(function(script) { return eval(script) });
},
escapeHTML: function() {
var div = document.createElement('div');
var text = document.createTextNode(this);
div.appendChild(text);
return div.innerHTML;
},
unescapeHTML: function() {
var div = document.createElement('div');
div.innerHTML = this.stripTags();
return div.childNodes[0] ? div.childNodes[0].nodeValue : '';
},
toQueryParams: function() {
var pairs = this.match(/^\??(.*)$/)[1].split('&');
return pairs.inject({}, function(params, pairString) {
var pair = pairString.split('=');
params[pair[0]] = pair[1];
return params;
});
},
toArray: function() {
return this.split('');
},
camelize: function() {
var oStringList = this.split('-');
if (oStringList.length == 1) return oStringList[0];
var camelizedString = this.indexOf('-') == 0
? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1)
: oStringList[0];
for (var i = 1, len = oStringList.length; i < len; i++) {
var s = oStringList[i];
camelizedString += s.charAt(0).toUpperCase() + s.substring(1);
}
return camelizedString;
},
inspect: function() {
return "'" + this.replace(/\\/g, '\\\\').replace(/'/g, '\\\'') + "'";
}
});
String.prototype.gsub.prepareReplacement = function(replacement) {
if (typeof replacement == 'function') return replacement;
var template = new Template(replacement);
return function(match) { return template.evaluate(match) };
}
String.prototype.parseQuery = String.prototype.toQueryParams;
var Template = Class.create();
Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
Template.prototype = {
initialize: function(template, pattern) {
this.template = template.toString();
this.pattern = pattern || Template.Pattern;
},
evaluate: function(object) {
return this.template.gsub(this.pattern, function(match) {
var before = match[1];
if (before == '\\') return match[2];
return before + (object[match[3]] || '').toString();
});
}
}
var $break = new Object();
var $continue = new Object();
var Enumerable = {
each: function(iterator) {
var index = 0;
try {
this._each(function(value) {
try {
iterator(value, index++);
} catch (e) {
if (e != $continue) throw e;
}
});
} catch (e) {
if (e != $break) throw e;
}
},
all: function(iterator) {
var result = true;
this.each(function(value, index) {
result = result && !!(iterator || Prototype.K)(value, index);
if (!result) throw $break;
});
return result;
},
any: function(iterator) {
var result = true;
this.each(function(value, index) {
if (result = !!(iterator || Prototype.K)(value, index))
throw $break;
});
return result;
},
collect: function(iterator) {
var results = [];
this.each(function(value, index) {
results.push(iterator(value, index));
});
return results;
},
detect: function (iterator) {
var result;
this.each(function(value, index) {
if (iterator(value, index)) {
result = value;
throw $break;
}
});
return result;
},
findAll: function(iterator) {
var results = [];
this.each(function(value, index) {
if (iterator(value, index))
results.push(value);
});
return results;
},
grep: function(pattern, iterator) {
var results = [];
this.each(function(value, index) {
var stringValue = value.toString();
if (stringValue.match(pattern))
results.push((iterator || Prototype.K)(value, index));
})
return results;
},
include: function(object) {
var found = false;
this.each(function(value) {
if (value == object) {
found = true;
throw $break;
}
});
return found;
},
inject: function(memo, iterator) {
this.each(function(value, index) {
memo = iterator(memo, value, index);
});
return memo;
},
invoke: function(method) {
var args = $A(arguments).slice(1);
return this.collect(function(value) {
return value[method].apply(value, args);
});
},
max: function(iterator) {
var result;
this.each(function(value, index) {
value = (iterator || Prototype.K)(value, index);
if (result == undefined || value >= result)
result = value;
});
return result;
},
min: function(iterator) {
var result;
this.each(function(value, index) {
value = (iterator || Prototype.K)(value, index);
if (result == undefined || value < result)
result = value;
});
return result;
},
partition: function(iterator) {
var trues = [], falses = [];
this.each(function(value, index) {
((iterator || Prototype.K)(value, index) ?
trues : falses).push(value);
});
return [trues, falses];
},
pluck: function(property) {
var results = [];
this.each(function(value, index) {
results.push(value[property]);
});
return results;
},
reject: function(iterator) {
var results = [];
this.each(function(value, index) {
if (!iterator(value, index))
results.push(value);
});
return results;
},
sortBy: function(iterator) {
return this.collect(function(value, index) {
return {value: value, criteria: iterator(value, index)};
}).sort(function(left, right) {
var a = left.criteria, b = right.criteria;
return a < b ? -1 : a > b ? 1 : 0;
}).pluck('value');
},
toArray: function() {
return this.collect(Prototype.K);
},
zip: function() {
var iterator = Prototype.K, args = $A(arguments);
if (typeof args.last() == 'function')
iterator = args.pop();
var collections = [this].concat(args).map($A);
return this.map(function(value, index) {
return iterator(collections.pluck(index));
});
},
inspect: function() {
return '#<Enumerable:' + this.toArray().inspect() + '>';
}
}
Object.extend(Enumerable, {
map: Enumerable.collect,
find: Enumerable.detect,
select: Enumerable.findAll,
member: Enumerable.include,
entries: Enumerable.toArray
});
var $A = Array.from = function(iterable) {
if (!iterable) return [];
if (iterable.toArray) {
return iterable.toArray();
} else {
var results = [];
for (var i = 0; i < iterable.length; i++)
results.push(iterable[i]);
return results;
}
}
Object.extend(Array.prototype, Enumerable);
if (!Array.prototype._reverse)
Array.prototype._reverse = Array.prototype.reverse;
Object.extend(Array.prototype, {
_each: function(iterator) {
for (var i = 0; i < this.length; i++)
iterator(this[i]);
},
clear: function() {
this.length = 0;
return this;
},
first: function() {
return this[0];
},
last: function() {
return this[this.length - 1];
},
compact: function() {
return this.select(function(value) {
return value != undefined || value != null;
});
},
flatten: function() {
return this.inject([], function(array, value) {
return array.concat(value && value.constructor == Array ?
value.flatten() : [value]);
});
},
without: function() {
var values = $A(arguments);
return this.select(function(value) {
return !values.include(value);
});
},
indexOf: function(object) {
for (var i = 0; i < this.length; i++)
if (this[i] == object) return i;
return -1;
},
reverse: function(inline) {
return (inline !== false ? this : this.toArray())._reverse();
},
inspect: function() {
return '[' + this.map(Object.inspect).join(', ') + ']';
}
});
var Hash = {
_each: function(iterator) {
for (var key in this) {
var value = this[key];
if (typeof value == 'function') continue;
var pair = [key, value];
pair.key = key;
pair.value = value;
iterator(pair);
}
},
keys: function() {
return this.pluck('key');
},
values: function() {
return this.pluck('value');
},
merge: function(hash) {
return $H(hash).inject($H(this), function(mergedHash, pair) {
mergedHash[pair.key] = pair.value;
return mergedHash;
});
},
toQueryString: function() {
return this.map(function(pair) {
return pair.map(encodeURIComponent).join('=');
}).join('&');
},
inspect: function() {
return '#<Hash:{' + this.map(function(pair) {
return pair.map(Object.inspect).join(': ');
}).join(', ') + '}>';
}
}
function $H(object) {
var hash = Object.extend({}, object || {});
Object.extend(hash, Enumerable);
Object.extend(hash, Hash);
return hash;
}
ObjectRange = Class.create();
Object.extend(ObjectRange.prototype, Enumerable);
Object.extend(ObjectRange.prototype, {
initialize: function(start, end, exclusive) {
this.start = start;
this.end = end;
this.exclusive = exclusive;
},
_each: function(iterator) {
var value = this.start;
do {
iterator(value);
value = value.succ();
} while (this.include(value));
},
include: function(value) {
if (value < this.start)
return false;
if (this.exclusive)
return value < this.end;
return value <= this.end;
}
});
var $R = function(start, end, exclusive) {
return new ObjectRange(start, end, exclusive);
}
var Ajax = {
getTransport: function() {
return Try.these(
function() {return new XMLHttpRequest()},
function() {return new ActiveXObject('Msxml2.XMLHTTP')},
function() {return new ActiveXObject('Microsoft.XMLHTTP')}
) || false;
},
activeRequestCount: 0
}
Ajax.Responders = {
responders: [],
_each: function(iterator) {
this.responders._each(iterator);
},
register: function(responderToAdd) {
if (!this.include(responderToAdd))
this.responders.push(responderToAdd);
},
unregister: function(responderToRemove) {
this.responders = this.responders.without(responderToRemove);
},
dispatch: function(callback, request, transport, json) {
this.each(function(responder) {
if (responder[callback] && typeof responder[callback] == 'function') {
try {
responder[callback].apply(responder, [request, transport, json]);
} catch (e) {}
}
});
}
};
Object.extend(Ajax.Responders, Enumerable);
Ajax.Responders.register({
onCreate: function() {
Ajax.activeRequestCount++;
},
onComplete: function() {
Ajax.activeRequestCount--;
}
});
Ajax.Base = function() {};
Ajax.Base.prototype = {
setOptions: function(options) {
this.options = {
method: 'post',
asynchronous: true,
contentType: 'application/x-www-form-urlencoded',
parameters: ''
}
Object.extend(this.options, options || {});
},
responseIsSuccess: function() {
return this.transport.status == undefined
|| this.transport.status == 0
|| (this.transport.status >= 200 && this.transport.status < 300);
},
responseIsFailure: function() {
return !this.responseIsSuccess();
}
}
Ajax.Request = Class.create();
Ajax.Request.Events =
['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];
Ajax.Request.prototype = Object.extend(new Ajax.Base(), {
initialize: function(url, options) {
this.transport = Ajax.getTransport();
this.setOptions(options);
this.request(url);
},
request: function(url) {
var parameters = this.options.parameters || '';
if (parameters.length > 0) parameters += '&_=';
try {
this.url = url;
if (this.options.method == 'get' && parameters.length > 0)
this.url += (this.url.match(/\?/) ? '&' : '?') + parameters;
Ajax.Responders.dispatch('onCreate', this, this.transport);
this.transport.open(this.options.method, this.url,
this.options.asynchronous);
if (this.options.asynchronous) {
this.transport.onreadystatechange = this.onStateChange.bind(this);
setTimeout((function() {this.respondToReadyState(1)}).bind(this), 10);
}
this.setRequestHeaders();
var body = this.options.postBody ? this.options.postBody : parameters;
this.transport.send(this.options.method == 'post' ? body : null);
} catch (e) {
this.dispatchException(e);
}
},
setRequestHeaders: function() {
var requestHeaders =
['X-Requested-With', 'XMLHttpRequest',
'X-Prototype-Version', Prototype.Version,
'Accept', 'text/javascript, text/html, application/xml, text/xml, */*'];
if (this.options.method == 'post') {
requestHeaders.push('Content-type', this.options.contentType);
/* Force "Connection: close" for Mozilla browsers to work around
* a bug where XMLHttpReqeuest sends an incorrect Content-length
* header. See Mozilla Bugzilla #246651.
*/
if (this.transport.overrideMimeType)
requestHeaders.push('Connection', 'close');
}
if (this.options.requestHeaders)
requestHeaders.push.apply(requestHeaders, this.options.requestHeaders);
for (var i = 0; i < requestHeaders.length; i += 2)
this.transport.setRequestHeader(requestHeaders[i], requestHeaders[i+1]);
},
onStateChange: function() {
var readyState = this.transport.readyState;
if (readyState != 1)
this.respondToReadyState(this.transport.readyState);
},
header: function(name) {
try {
return this.transport.getResponseHeader(name);
} catch (e) {}
},
evalJSON: function() {
try {
return eval('(' + this.header('X-JSON') + ')');
} catch (e) {}
},
evalResponse: function() {
try {
return eval(this.transport.responseText);
} catch (e) {
this.dispatchException(e);
}
},
respondToReadyState: function(readyState) {
var event = Ajax.Request.Events[readyState];
var transport = this.transport, json = this.evalJSON();
if (event == 'Complete') {
try {
(this.options['on' + this.transport.status]
|| this.options['on' + (this.responseIsSuccess() ? 'Success' : 'Failure')]
|| Prototype.emptyFunction)(transport, json);
} catch (e) {
this.dispatchException(e);
}
if ((this.header('Content-type') || '').match(/^text\/javascript/i))
this.evalResponse();
}
try {
(this.options['on' + event] || Prototype.emptyFunction)(transport, json);
Ajax.Responders.dispatch('on' + event, this, transport, json);
} catch (e) {
this.dispatchException(e);
}
/* Avoid memory leak in MSIE: clean up the oncomplete event handler */
if (event == 'Complete')
this.transport.onreadystatechange = Prototype.emptyFunction;
},
dispatchException: function(exception) {
(this.options.onException || Prototype.emptyFunction)(this, exception);
Ajax.Responders.dispatch('onException', this, exception);
}
});
Ajax.Updater = Class.create();
Object.extend(Object.extend(Ajax.Updater.prototype, Ajax.Request.prototype), {
initialize: function(container, url, options) {
this.containers = {
success: container.success ? $(container.success) : $(container),
failure: container.failure ? $(container.failure) :
(container.success ? null : $(container))
}
this.transport = Ajax.getTransport();
this.setOptions(options);
var onComplete = this.options.onComplete || Prototype.emptyFunction;
this.options.onComplete = (function(transport, object) {
this.updateContent();
onComplete(transport, object);
}).bind(this);
this.request(url);
},
updateContent: function() {
var receiver = this.responseIsSuccess() ?
this.containers.success : this.containers.failure;
var response = this.transport.responseText;
if (!this.options.evalScripts)
response = response.stripScripts();
if (receiver) {
if (this.options.insertion) {
new this.options.insertion(receiver, response);
} else {
Element.update(receiver, response);
}
}
if (this.responseIsSuccess()) {
if (this.onComplete)
setTimeout(this.onComplete.bind(this), 10);
}
}
});
Ajax.PeriodicalUpdater = Class.create();
Ajax.PeriodicalUpdater.prototype = Object.extend(new Ajax.Base(), {
initialize: function(container, url, options) {
this.setOptions(options);
this.onComplete = this.options.onComplete;
this.frequency = (this.options.frequency || 2);
this.decay = (this.options.decay || 1);
this.updater = {};
this.container = container;
this.url = url;
this.start();
},
start: function() {
this.options.onComplete = this.updateComplete.bind(this);
this.onTimerEvent();
},
stop: function() {
this.updater.onComplete = undefined;
clearTimeout(this.timer);
(this.onComplete || Prototype.emptyFunction).apply(this, arguments);
},
updateComplete: function(request) {
if (this.options.decay) {
this.decay = (request.responseText == this.lastText ?
this.decay * this.options.decay : 1);
this.lastText = request.responseText;
}
this.timer = setTimeout(this.onTimerEvent.bind(this),
this.decay * this.frequency * 1000);
},
onTimerEvent: function() {
this.updater = new Ajax.Updater(this.container, this.url, this.options);
}
});
function $() {
var results = [], element;
for (var i = 0; i < arguments.length; i++) {
element = arguments[i];
if (typeof element == 'string')
element = document.getElementById(element);
results.push(Element.extend(element));
}
return results.length < 2 ? results[0] : results;
}
document.getElementsByClassName = function(className, parentElement) {
var children = ($(parentElement) || document.body).getElementsByTagName('*');
return $A(children).inject([], function(elements, child) {
if (child.className.match(new RegExp("(^|\\s)" + className + "(\\s|$)")))
elements.push(Element.extend(child));
return elements;
});
}
/*--------------------------------------------------------------------------*/
if (!window.Element)
var Element = new Object();
Element.extend = function(element) {
if (!element) return;
if (_nativeExtensions) return element;
if (!element._extended && element.tagName && element != window) {
var methods = Element.Methods, cache = Element.extend.cache;
for (property in methods) {
var value = methods[property];
if (typeof value == 'function')
element[property] = cache.findOrStore(value);
}
}
element._extended = true;
return element;
}
Element.extend.cache = {
findOrStore: function(value) {
return this[value] = this[value] || function() {
return value.apply(null, [this].concat($A(arguments)));
}
}
}
Element.Methods = {
visible: function(element) {
return $(element).style.display != 'none';
},
toggle: function() {
for (var i = 0; i < arguments.length; i++) {
var element = $(arguments[i]);
Element[Element.visible(element) ? 'hide' : 'show'](element);
}
},
hide: function() {
for (var i = 0; i < arguments.length; i++) {
var element = $(arguments[i]);
element.style.display = 'none';
}
},
show: function() {
for (var i = 0; i < arguments.length; i++) {
var element = $(arguments[i]);
element.style.display = '';
}
},
remove: function(element) {
element = $(element);
element.parentNode.removeChild(element);
},
update: function(element, html) {
$(element).innerHTML = html.stripScripts();
setTimeout(function() {html.evalScripts()}, 10);
},
replace: function(element, html) {
element = $(element);
if (element.outerHTML) {
element.outerHTML = html.stripScripts();
} else {
var range = element.ownerDocument.createRange();
range.selectNodeContents(element);
element.parentNode.replaceChild(
range.createContextualFragment(html.stripScripts()), element);
}
setTimeout(function() {html.evalScripts()}, 10);
},
getHeight: function(element) {
element = $(element);
return element.offsetHeight;
},
classNames: function(element) {
return new Element.ClassNames(element);
},
hasClassName: function(element, className) {
if (!(element = $(element))) return;
return Element.classNames(element).include(className);
},
addClassName: function(element, className) {
if (!(element = $(element))) return;
return Element.classNames(element).add(className);
},
removeClassName: function(element, className) {
if (!(element = $(element))) return;
return Element.classNames(element).remove(className);
},
// removes whitespace-only text node children
cleanWhitespace: function(element) {
element = $(element);
for (var i = 0; i < element.childNodes.length; i++) {
var node = element.childNodes[i];
if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
Element.remove(node);
}
},
empty: function(element) {
return $(element).innerHTML.match(/^\s*$/);
},
childOf: function(element, ancestor) {
element = $(element), ancestor = $(ancestor);
while (element = element.parentNode)
if (element == ancestor) return true;
return false;
},
scrollTo: function(element) {
element = $(element);
var x = element.x ? element.x : element.offsetLeft,
y = element.y ? element.y : element.offsetTop;
window.scrollTo(x, y);
},
getStyle: function(element, style) {
element = $(element);
var value = element.style[style.camelize()];
if (!value) {
if (document.defaultView && document.defaultView.getComputedStyle) {
var css = document.defaultView.getComputedStyle(element, null);
value = css ? css.getPropertyValue(style) : null;
} else if (element.currentStyle) {
value = element.currentStyle[style.camelize()];
}
}
if (window.opera && ['left', 'top', 'right', 'bottom'].include(style))
if (Element.getStyle(element, 'position') == 'static') value = 'auto';
return value == 'auto' ? null : value;
},
setStyle: function(element, style) {
element = $(element);
for (var name in style)
element.style[name.camelize()] = style[name];
},
getDimensions: function(element) {
element = $(element);
if (Element.getStyle(element, 'display') != 'none')
return {width: element.offsetWidth, height: element.offsetHeight};
// All *Width and *Height properties give 0 on elements with display none,
// so enable the element temporarily
var els = element.style;
var originalVisibility = els.visibility;
var originalPosition = els.position;
els.visibility = 'hidden';
els.position = 'absolute';
els.display = '';
var originalWidth = element.clientWidth;
var originalHeight = element.clientHeight;
els.display = 'none';
els.position = originalPosition;
els.visibility = originalVisibility;
return {width: originalWidth, height: originalHeight};
},
makePositioned: function(element) {
element = $(element);
var pos = Element.getStyle(element, 'position');
if (pos == 'static' || !pos) {
element._madePositioned = true;
element.style.position = 'relative';
// Opera returns the offset relative to the positioning context, when an
// element is position relative but top and left have not been defined
if (window.opera) {
element.style.top = 0;
element.style.left = 0;
}
}
},
undoPositioned: function(element) {
element = $(element);
if (element._madePositioned) {
element._madePositioned = undefined;
element.style.position =
element.style.top =
element.style.left =
element.style.bottom =
element.style.right = '';
}
},
makeClipping: function(element) {
element = $(element);
if (element._overflow) return;
element._overflow = element.style.overflow;
if ((Element.getStyle(element, 'overflow') || 'visible') != 'hidden')
element.style.overflow = 'hidden';
},
undoClipping: function(element) {
element = $(element);
if (element._overflow) return;
element.style.overflow = element._overflow;
element._overflow = undefined;
}
}
Object.extend(Element, Element.Methods);
var _nativeExtensions = false;
if(!HTMLElement && /Konqueror|Safari|KHTML/.test(navigator.userAgent)) {
var HTMLElement = {}
HTMLElement.prototype = document.createElement('div').__proto__;
}
Element.addMethods = function(methods) {
Object.extend(Element.Methods, methods || {});
if(typeof HTMLElement != 'undefined') {
var methods = Element.Methods, cache = Element.extend.cache;
for (property in methods) {
var value = methods[property];
if (typeof value == 'function')
HTMLElement.prototype[property] = cache.findOrStore(value);
}
_nativeExtensions = true;
}
}
Element.addMethods();
var Toggle = new Object();
Toggle.display = Element.toggle;
/*--------------------------------------------------------------------------*/
Abstract.Insertion = function(adjacency) {
this.adjacency = adjacency;
}
Abstract.Insertion.prototype = {
initialize: function(element, content) {
this.element = $(element);
this.content = content.stripScripts();
if (this.adjacency && this.element.insertAdjacentHTML) {
try {
this.element.insertAdjacentHTML(this.adjacency, this.content);
} catch (e) {
var tagName = this.element.tagName.toLowerCase();
if (tagName == 'tbody' || tagName == 'tr') {
this.insertContent(this.contentFromAnonymousTable());
} else {
throw e;
}
}
} else {
this.range = this.element.ownerDocument.createRange();
if (this.initializeRange) this.initializeRange();
this.insertContent([this.range.createContextualFragment(this.content)]);
}
setTimeout(function() {content.evalScripts()}, 10);
},
contentFromAnonymousTable: function() {
var div = document.createElement('div');
div.innerHTML = '<table><tbody>' + this.content + '</tbody></table>';
return $A(div.childNodes[0].childNodes[0].childNodes);
}
}
var Insertion = new Object();
Insertion.Before = Class.create();
Insertion.Before.prototype = Object.extend(new Abstract.Insertion('beforeBegin'), {
initializeRange: function() {
this.range.setStartBefore(this.element);
},
insertContent: function(fragments) {
fragments.each((function(fragment) {
this.element.parentNode.insertBefore(fragment, this.element);
}).bind(this));
}
});
Insertion.Top = Class.create();
Insertion.Top.prototype = Object.extend(new Abstract.Insertion('afterBegin'), {
initializeRange: function() {
this.range.selectNodeContents(this.element);
this.range.collapse(true);
},
insertContent: function(fragments) {
fragments.reverse(false).each((function(fragment) {
this.element.insertBefore(fragment, this.element.firstChild);
}).bind(this));
}
});
Insertion.Bottom = Class.create();
Insertion.Bottom.prototype = Object.extend(new Abstract.Insertion('beforeEnd'), {
initializeRange: function() {
this.range.selectNodeContents(this.element);
this.range.collapse(this.element);
},
insertContent: function(fragments) {
fragments.each((function(fragment) {
this.element.appendChild(fragment);
}).bind(this));
}
});
Insertion.After = Class.create();
Insertion.After.prototype = Object.extend(new Abstract.Insertion('afterEnd'), {
initializeRange: function() {
this.range.setStartAfter(this.element);
},
insertContent: function(fragments) {
fragments.each((function(fragment) {
this.element.parentNode.insertBefore(fragment,
this.element.nextSibling);
}).bind(this));
}
});
/*--------------------------------------------------------------------------*/
Element.ClassNames = Class.create();
Element.ClassNames.prototype = {
initialize: function(element) {
this.element = $(element);
},
_each: function(iterator) {
this.element.className.split(/\s+/).select(function(name) {
return name.length > 0;
})._each(iterator);
},
set: function(className) {
this.element.className = className;
},
add: function(classNameToAdd) {
if (this.include(classNameToAdd)) return;
this.set(this.toArray().concat(classNameToAdd).join(' '));
},
remove: function(classNameToRemove) {
if (!this.include(classNameToRemove)) return;
this.set(this.select(function(className) {
return className != classNameToRemove;
}).join(' '));
},
toString: function() {
return this.toArray().join(' ');
}
}
Object.extend(Element.ClassNames.prototype, Enumerable);
var Selector = Class.create();
Selector.prototype = {
initialize: function(expression) {
this.params = {classNames: []};
this.expression = expression.toString().strip();
this.parseExpression();
this.compileMatcher();
},
parseExpression: function() {
function abort(message) { throw 'Parse error in selector: ' + message; }
if (this.expression == '') abort('empty expression');
var params = this.params, expr = this.expression, match, modifier, clause, rest;
while (match = expr.match(/^(.*)\[([a-z0-9_:-]+?)(?:([~\|!]?=)(?:"([^"]*)"|([^\]\s]*)))?\]$/i)) {
params.attributes = params.attributes || [];
params.attributes.push({name: match[2], operator: match[3], value: match[4] || match[5] || ''});
expr = match[1];
}
if (expr == '*') return this.params.wildcard = true;
while (match = expr.match(/^([^a-z0-9_-])?([a-z0-9_-]+)(.*)/i)) {
modifier = match[1], clause = match[2], rest = match[3];
switch (modifier) {
case '#': params.id = clause; break;
case '.': params.classNames.push(clause); break;
case '':
case undefined: params.tagName = clause.toUpperCase(); break;
default: abort(expr.inspect());
}
expr = rest;
}
if (expr.length > 0) abort(expr.inspect());
},
buildMatchExpression: function() {
var params = this.params, conditions = [], clause;
if (params.wildcard)
conditions.push('true');
if (clause = params.id)
conditions.push('element.id == ' + clause.inspect());
if (clause = params.tagName)
conditions.push('element.tagName.toUpperCase() == ' + clause.inspect());
if ((clause = params.classNames).length > 0)
for (var i = 0; i < clause.length; i++)
conditions.push('Element.hasClassName(element, ' + clause[i].inspect() + ')');
if (clause = params.attributes) {
clause.each(function(attribute) {
var value = 'element.getAttribute(' + attribute.name.inspect() + ')';
var splitValueBy = function(delimiter) {
return value + ' && ' + value + '.split(' + delimiter.inspect() + ')';
}
switch (attribute.operator) {
case '=': conditions.push(value + ' == ' + attribute.value.inspect()); break;
case '~=': conditions.push(splitValueBy(' ') + '.include(' + attribute.value.inspect() + ')'); break;
case '|=': conditions.push(
splitValueBy('-') + '.first().toUpperCase() == ' + attribute.value.toUpperCase().inspect()
); break;
case '!=': conditions.push(value + ' != ' + attribute.value.inspect()); break;
case '':
case undefined: conditions.push(value + ' != null'); break;
default: throw 'Unknown operator ' + attribute.operator + ' in selector';
}
});
}
return conditions.join(' && ');
},
compileMatcher: function() {
this.match = new Function('element', 'if (!element.tagName) return false; \n' +
'return ' + this.buildMatchExpression());
},
findElements: function(scope) {
var element;
if (element = $(this.params.id))
if (this.match(element))
if (!scope || Element.childOf(element, scope))
return [element];
scope = (scope || document).getElementsByTagName(this.params.tagName || '*');
var results = [];
for (var i = 0; i < scope.length; i++)
if (this.match(element = scope[i]))
results.push(Element.extend(element));
return results;
},
toString: function() {
return this.expression;
}
}
function $$() {
return $A(arguments).map(function(expression) {
return expression.strip().split(/\s+/).inject([null], function(results, expr) {
var selector = new Selector(expr);
return results.map(selector.findElements.bind(selector)).flatten();
});
}).flatten();
}
var Field = {
clear: function() {
for (var i = 0; i < arguments.length; i++)
$(arguments[i]).value = '';
},
focus: function(element) {
$(element).focus();
},
present: function() {
for (var i = 0; i < arguments.length; i++)
if ($(arguments[i]).value == '') return false;
return true;
},
select: function(element) {
$(element).select();
},
activate: function(element) {
element = $(element);
element.focus();
if (element.select)
element.select();
}
}
/*--------------------------------------------------------------------------*/
var Form = {
serialize: function(form) {
var elements = Form.getElements($(form));
var queryComponents = new Array();
for (var i = 0; i < elements.length; i++) {
var queryComponent = Form.Element.serialize(elements[i]);
if (queryComponent)
queryComponents.push(queryComponent);
}
return queryComponents.join('&');
},
getElements: function(form) {
form = $(form);
var elements = new Array();
for (var tagName in Form.Element.Serializers) {
var tagElements = form.getElementsByTagName(tagName);
for (var j = 0; j < tagElements.length; j++)
elements.push(tagElements[j]);
}
return elements;
},
getInputs: function(form, typeName, name) {
form = $(form);
var inputs = form.getElementsByTagName('input');
if (!typeName && !name)
return inputs;
var matchingInputs = new Array();
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
if ((typeName && input.type != typeName) ||
(name && input.name != name))
continue;
matchingInputs.push(input);
}
return matchingInputs;
},
disable: function(form) {
var elements = Form.getElements(form);
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
element.blur();
element.disabled = 'true';
}
},
enable: function(form) {
var elements = Form.getElements(form);
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
element.disabled = '';
}
},
findFirstElement: function(form) {
return Form.getElements(form).find(function(element) {
return element.type != 'hidden' && !element.disabled &&
['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
});
},
focusFirstElement: function(form) {
Field.activate(Form.findFirstElement(form));
},
reset: function(form) {
$(form).reset();
}
}
Form.Element = {
serialize: function(element) {
element = $(element);
var method = element.tagName.toLowerCase();
var parameter = Form.Element.Serializers[method](element);
if (parameter) {
var key = encodeURIComponent(parameter[0]);
if (key.length == 0) return;
if (parameter[1].constructor != Array)
parameter[1] = [parameter[1]];
return parameter[1].map(function(value) {
return key + '=' + encodeURIComponent(value);
}).join('&');
}
},
getValue: function(element) {
element = $(element);
var method = element.tagName.toLowerCase();
var parameter = Form.Element.Serializers[method](element);
if (parameter)
return parameter[1];
}
}
Form.Element.Serializers = {
input: function(element) {
switch (element.type.toLowerCase()) {
case 'submit':
case 'hidden':
case 'password':
case 'text':
return Form.Element.Serializers.textarea(element);
case 'checkbox':
case 'radio':
return Form.Element.Serializers.inputSelector(element);
}
return false;
},
inputSelector: function(element) {
if (element.checked)
return [element.name, element.value];
},
textarea: function(element) {
return [element.name, element.value];
},
select: function(element) {
return Form.Element.Serializers[element.type == 'select-one' ?
'selectOne' : 'selectMany'](element);
},
selectOne: function(element) {
var value = '', opt, index = element.selectedIndex;
if (index >= 0) {
opt = element.options[index];
value = opt.value || opt.text;
}
return [element.name, value];
},
selectMany: function(element) {
var value = [];
for (var i = 0; i < element.length; i++) {
var opt = element.options[i];
if (opt.selected)
value.push(opt.value || opt.text);
}
return [element.name, value];
}
}
/*--------------------------------------------------------------------------*/
var $F = Form.Element.getValue;
/*--------------------------------------------------------------------------*/
Abstract.TimedObserver = function() {}
Abstract.TimedObserver.prototype = {
initialize: function(element, frequency, callback) {
this.frequency = frequency;
this.element = $(element);
this.callback = callback;
this.lastValue = this.getValue();
this.registerCallback();
},
registerCallback: function() {
setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
},
onTimerEvent: function() {
var value = this.getValue();
if (this.lastValue != value) {
this.callback(this.element, value);
this.lastValue = value;
}
}
}
Form.Element.Observer = Class.create();
Form.Element.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
getValue: function() {
return Form.Element.getValue(this.element);
}
});
Form.Observer = Class.create();
Form.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
getValue: function() {
return Form.serialize(this.element);
}
});
/*--------------------------------------------------------------------------*/
Abstract.EventObserver = function() {}
Abstract.EventObserver.prototype = {
initialize: function(element, callback) {
this.element = $(element);
this.callback = callback;
this.lastValue = this.getValue();
if (this.element.tagName.toLowerCase() == 'form')
this.registerFormCallbacks();
else
this.registerCallback(this.element);
},
onElementEvent: function() {
var value = this.getValue();
if (this.lastValue != value) {
this.callback(this.element, value);
this.lastValue = value;
}
},
registerFormCallbacks: function() {
var elements = Form.getElements(this.element);
for (var i = 0; i < elements.length; i++)
this.registerCallback(elements[i]);
},
registerCallback: function(element) {
if (element.type) {
switch (element.type.toLowerCase()) {
case 'checkbox':
case 'radio':
Event.observe(element, 'click', this.onElementEvent.bind(this));
break;
case 'password':
case 'text':
case 'textarea':
case 'select-one':
case 'select-multiple':
Event.observe(element, 'change', this.onElementEvent.bind(this));
break;
}
}
}
}
Form.Element.EventObserver = Class.create();
Form.Element.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
getValue: function() {
return Form.Element.getValue(this.element);
}
});
Form.EventObserver = Class.create();
Form.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
getValue: function() {
return Form.serialize(this.element);
}
});
if (!window.Event) {
var Event = new Object();
}
Object.extend(Event, {
KEY_BACKSPACE: 8,
KEY_TAB: 9,
KEY_RETURN: 13,
KEY_ESC: 27,
KEY_LEFT: 37,
KEY_UP: 38,
KEY_RIGHT: 39,
KEY_DOWN: 40,
KEY_DELETE: 46,
element: function(event) {
return event.target || event.srcElement;
},
isLeftClick: function(event) {
return (((event.which) && (event.which == 1)) ||
((event.button) && (event.button == 1)));
},
pointerX: function(event) {
return event.pageX || (event.clientX +
(document.documentElement.scrollLeft || document.body.scrollLeft));
},
pointerY: function(event) {
return event.pageY || (event.clientY +
(document.documentElement.scrollTop || document.body.scrollTop));
},
stop: function(event) {
if (event.preventDefault) {
event.preventDefault();
event.stopPropagation();
} else {
event.returnValue = false;
event.cancelBubble = true;
}
},
// find the first node with the given tagName, starting from the
// node the event was triggered on; traverses the DOM upwards
findElement: function(event, tagName) {
var element = Event.element(event);
while (element.parentNode && (!element.tagName ||
(element.tagName.toUpperCase() != tagName.toUpperCase())))
element = element.parentNode;
return element;
},
observers: false,
_observeAndCache: function(element, name, observer, useCapture) {
if (!this.observers) this.observers = [];
if (element.addEventListener) {
this.observers.push([element, name, observer, useCapture]);
element.addEventListener(name, observer, useCapture);
} else if (element.attachEvent) {
this.observers.push([element, name, observer, useCapture]);
element.attachEvent('on' + name, observer);
}
},
unloadCache: function() {
if (!Event.observers) return;
for (var i = 0; i < Event.observers.length; i++) {
Event.stopObserving.apply(this, Event.observers[i]);
Event.observers[i][0] = null;
}
Event.observers = false;
},
observe: function(element, name, observer, useCapture) {
var element = $(element);
useCapture = useCapture || false;
if (name == 'keypress' &&
(navigator.appVersion.match(/Konqueror|Safari|KHTML/)
|| element.attachEvent))
name = 'keydown';
this._observeAndCache(element, name, observer, useCapture);
},
stopObserving: function(element, name, observer, useCapture) {
var element = $(element);
useCapture = useCapture || false;
if (name == 'keypress' &&
(navigator.appVersion.match(/Konqueror|Safari|KHTML/)
|| element.detachEvent))
name = 'keydown';
if (element.removeEventListener) {
element.removeEventListener(name, observer, useCapture);
} else if (element.detachEvent) {
element.detachEvent('on' + name, observer);
}
}
});
/* prevent memory leaks in IE */
if (navigator.appVersion.match(/\bMSIE\b/))
Event.observe(window, 'unload', Event.unloadCache, false);
var Position = {
// set to true if needed, warning: firefox performance problems
// NOT neeeded for page scrolling, only if draggable contained in
// scrollable elements
includeScrollOffsets: false,
// must be called before calling withinIncludingScrolloffset, every time the
// page is scrolled
prepare: function() {
this.deltaX = window.pageXOffset
|| document.documentElement.scrollLeft
|| document.body.scrollLeft
|| 0;
this.deltaY = window.pageYOffset
|| document.documentElement.scrollTop
|| document.body.scrollTop
|| 0;
},
realOffset: function(element) {
var valueT = 0, valueL = 0;
do {
valueT += element.scrollTop || 0;
valueL += element.scrollLeft || 0;
element = element.parentNode;
} while (element);
return [valueL, valueT];
},
cumulativeOffset: function(element) {
var valueT = 0, valueL = 0;
do {
valueT += element.offsetTop || 0;
valueL += element.offsetLeft || 0;
element = element.offsetParent;
} while (element);
return [valueL, valueT];
},
positionedOffset: function(element) {
var valueT = 0, valueL = 0;
do {
valueT += element.offsetTop || 0;
valueL += element.offsetLeft || 0;
element = element.offsetParent;
if (element) {
p = Element.getStyle(element, 'position');
if (p == 'relative' || p == 'absolute') break;
}
} while (element);
return [valueL, valueT];
},
offsetParent: function(element) {
if (element.offsetParent) return element.offsetParent;
if (element == document.body) return element;
while ((element = element.parentNode) && element != document.body)
if (Element.getStyle(element, 'position') != 'static')
return element;
return document.body;
},
// caches x/y coordinate pair to use with overlap
within: function(element, x, y) {
if (this.includeScrollOffsets)
return this.withinIncludingScrolloffsets(element, x, y);
this.xcomp = x;
this.ycomp = y;
this.offset = this.cumulativeOffset(element);
return (y >= this.offset[1] &&
y < this.offset[1] + element.offsetHeight &&
x >= this.offset[0] &&
x < this.offset[0] + element.offsetWidth);
},
withinIncludingScrolloffsets: function(element, x, y) {
var offsetcache = this.realOffset(element);
this.xcomp = x + offsetcache[0] - this.deltaX;
this.ycomp = y + offsetcache[1] - this.deltaY;
this.offset = this.cumulativeOffset(element);
return (this.ycomp >= this.offset[1] &&
this.ycomp < this.offset[1] + element.offsetHeight &&
this.xcomp >= this.offset[0] &&
this.xcomp < this.offset[0] + element.offsetWidth);
},
// within must be called directly before
overlap: function(mode, element) {
if (!mode) return 0;
if (mode == 'vertical')
return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
element.offsetHeight;
if (mode == 'horizontal')
return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
element.offsetWidth;
},
clone: function(source, target) {
source = $(source);
target = $(target);
target.style.position = 'absolute';
var offsets = this.cumulativeOffset(source);
target.style.top = offsets[1] + 'px';
target.style.left = offsets[0] + 'px';
target.style.width = source.offsetWidth + 'px';
target.style.height = source.offsetHeight + 'px';
},
page: function(forElement) {
var valueT = 0, valueL = 0;
var element = forElement;
do {
valueT += element.offsetTop || 0;
valueL += element.offsetLeft || 0;
// Safari fix
if (element.offsetParent==document.body)
if (Element.getStyle(element,'position')=='absolute') break;
} while (element = element.offsetParent);
element = forElement;
do {
valueT -= element.scrollTop || 0;
valueL -= element.scrollLeft || 0;
} while (element = element.parentNode);
return [valueL, valueT];
},
clone: function(source, target) {
var options = Object.extend({
setLeft: true,
setTop: true,
setWidth: true,
setHeight: true,
offsetTop: 0,
offsetLeft: 0
}, arguments[2] || {})
// find page position of source
source = $(source);
var p = Position.page(source);
// find coordinate system to use
target = $(target);
var delta = [0, 0];
var parent = null;
// delta [0,0] will do fine with position: fixed elements,
// position:absolute needs offsetParent deltas
if (Element.getStyle(target,'position') == 'absolute') {
parent = Position.offsetParent(target);
delta = Position.page(parent);
}
// correct by body offsets (fixes Safari)
if (parent == document.body) {
delta[0] -= document.body.offsetLeft;
delta[1] -= document.body.offsetTop;
}
// set position
if(options.setLeft) target.style.left = (p[0] - delta[0] + options.offsetLeft) + 'px';
if(options.setTop) target.style.top = (p[1] - delta[1] + options.offsetTop) + 'px';
if(options.setWidth) target.style.width = source.offsetWidth + 'px';
if(options.setHeight) target.style.height = source.offsetHeight + 'px';
},
absolutize: function(element) {
element = $(element);
if (element.style.position == 'absolute') return;
Position.prepare();
var offsets = Position.positionedOffset(element);
var top = offsets[1];
var left = offsets[0];
var width = element.clientWidth;
var height = element.clientHeight;
element._originalLeft = left - parseFloat(element.style.left || 0);
element._originalTop = top - parseFloat(element.style.top || 0);
element._originalWidth = element.style.width;
element._originalHeight = element.style.height;
element.style.position = 'absolute';
element.style.top = top + 'px';;
element.style.left = left + 'px';;
element.style.width = width + 'px';;
element.style.height = height + 'px';;
},
relativize: function(element) {
element = $(element);
if (element.style.position == 'relative') return;
Position.prepare();
element.style.position = 'relative';
var top = parseFloat(element.style.top || 0) - (element._originalTop || 0);
var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);
element.style.top = top + 'px';
element.style.left = left + 'px';
element.style.height = element._originalHeight;
element.style.width = element._originalWidth;
}
}
// Safari returns margins on body which is incorrect if the child is absolutely
// positioned. For performance reasons, redefine Position.cumulativeOffset for
// KHTML/WebKit only.
if (/Konqueror|Safari|KHTML/.test(navigator.userAgent)) {
Position.cumulativeOffset = function(element) {
var valueT = 0, valueL = 0;
do {
valueT += element.offsetTop || 0;
valueL += element.offsetLeft || 0;
if (element.offsetParent == document.body)
if (Element.getStyle(element, 'position') == 'absolute') break;
element = element.offsetParent;
} while (element);
return [valueL, valueT];
}
} | zc.selenium | /zc.selenium-1.2.1.tar.gz/zc.selenium-1.2.1/src/zc/selenium/resources/lib/prototype.js | prototype.js |
// converts rgb() and #xxx to #xxxxxx format,
// returns self (or first argument) if not convertable
String.prototype.parseColor = function() {
var color = '#';
if(this.slice(0,4) == 'rgb(') {
var cols = this.slice(4,this.length-1).split(',');
var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3);
} else {
if(this.slice(0,1) == '#') {
if(this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase();
if(this.length==7) color = this.toLowerCase();
}
}
return(color.length==7 ? color : (arguments[0] || this));
}
/*--------------------------------------------------------------------------*/
Element.collectTextNodes = function(element) {
return $A($(element).childNodes).collect( function(node) {
return (node.nodeType==3 ? node.nodeValue :
(node.hasChildNodes() ? Element.collectTextNodes(node) : ''));
}).flatten().join('');
}
Element.collectTextNodesIgnoreClass = function(element, className) {
return $A($(element).childNodes).collect( function(node) {
return (node.nodeType==3 ? node.nodeValue :
((node.hasChildNodes() && !Element.hasClassName(node,className)) ?
Element.collectTextNodesIgnoreClass(node, className) : ''));
}).flatten().join('');
}
Element.setContentZoom = function(element, percent) {
element = $(element);
Element.setStyle(element, {fontSize: (percent/100) + 'em'});
if(navigator.appVersion.indexOf('AppleWebKit')>0) window.scrollBy(0,0);
}
Element.getOpacity = function(element){
var opacity;
if (opacity = Element.getStyle(element, 'opacity'))
return parseFloat(opacity);
if (opacity = (Element.getStyle(element, 'filter') || '').match(/alpha\(opacity=(.*)\)/))
if(opacity[1]) return parseFloat(opacity[1]) / 100;
return 1.0;
}
Element.setOpacity = function(element, value){
element= $(element);
if (value == 1){
Element.setStyle(element, { opacity:
(/Gecko/.test(navigator.userAgent) && !/Konqueror|Safari|KHTML/.test(navigator.userAgent)) ?
0.999999 : null });
if(/MSIE/.test(navigator.userAgent))
Element.setStyle(element, {filter: Element.getStyle(element,'filter').replace(/alpha\([^\)]*\)/gi,'')});
} else {
if(value < 0.00001) value = 0;
Element.setStyle(element, {opacity: value});
if(/MSIE/.test(navigator.userAgent))
Element.setStyle(element,
{ filter: Element.getStyle(element,'filter').replace(/alpha\([^\)]*\)/gi,'') +
'alpha(opacity='+value*100+')' });
}
}
Element.getInlineOpacity = function(element){
return $(element).style.opacity || '';
}
Element.childrenWithClassName = function(element, className, findFirst) {
var classNameRegExp = new RegExp("(^|\\s)" + className + "(\\s|$)");
var results = $A($(element).getElementsByTagName('*'))[findFirst ? 'detect' : 'select']( function(c) {
return (c.className && c.className.match(classNameRegExp));
});
if(!results) results = [];
return results;
}
Element.forceRerendering = function(element) {
try {
element = $(element);
var n = document.createTextNode(' ');
element.appendChild(n);
element.removeChild(n);
} catch(e) { }
};
/*--------------------------------------------------------------------------*/
Array.prototype.call = function() {
var args = arguments;
this.each(function(f){ f.apply(this, args) });
}
/*--------------------------------------------------------------------------*/
var Effect = {
tagifyText: function(element) {
var tagifyStyle = 'position:relative';
if(/MSIE/.test(navigator.userAgent)) tagifyStyle += ';zoom:1';
element = $(element);
$A(element.childNodes).each( function(child) {
if(child.nodeType==3) {
child.nodeValue.toArray().each( function(character) {
element.insertBefore(
Builder.node('span',{style: tagifyStyle},
character == ' ' ? String.fromCharCode(160) : character),
child);
});
Element.remove(child);
}
});
},
multiple: function(element, effect) {
var elements;
if(((typeof element == 'object') ||
(typeof element == 'function')) &&
(element.length))
elements = element;
else
elements = $(element).childNodes;
var options = Object.extend({
speed: 0.1,
delay: 0.0
}, arguments[2] || {});
var masterDelay = options.delay;
$A(elements).each( function(element, index) {
new effect(element, Object.extend(options, { delay: index * options.speed + masterDelay }));
});
},
PAIRS: {
'slide': ['SlideDown','SlideUp'],
'blind': ['BlindDown','BlindUp'],
'appear': ['Appear','Fade']
},
toggle: function(element, effect) {
element = $(element);
effect = (effect || 'appear').toLowerCase();
var options = Object.extend({
queue: { position:'end', scope:(element.id || 'global'), limit: 1 }
}, arguments[2] || {});
Effect[element.visible() ?
Effect.PAIRS[effect][1] : Effect.PAIRS[effect][0]](element, options);
}
};
var Effect2 = Effect; // deprecated
/* ------------- transitions ------------- */
Effect.Transitions = {}
Effect.Transitions.linear = function(pos) {
return pos;
}
Effect.Transitions.sinoidal = function(pos) {
return (-Math.cos(pos*Math.PI)/2) + 0.5;
}
Effect.Transitions.reverse = function(pos) {
return 1-pos;
}
Effect.Transitions.flicker = function(pos) {
return ((-Math.cos(pos*Math.PI)/4) + 0.75) + Math.random()/4;
}
Effect.Transitions.wobble = function(pos) {
return (-Math.cos(pos*Math.PI*(9*pos))/2) + 0.5;
}
Effect.Transitions.pulse = function(pos) {
return (Math.floor(pos*10) % 2 == 0 ?
(pos*10-Math.floor(pos*10)) : 1-(pos*10-Math.floor(pos*10)));
}
Effect.Transitions.none = function(pos) {
return 0;
}
Effect.Transitions.full = function(pos) {
return 1;
}
/* ------------- core effects ------------- */
Effect.ScopedQueue = Class.create();
Object.extend(Object.extend(Effect.ScopedQueue.prototype, Enumerable), {
initialize: function() {
this.effects = [];
this.interval = null;
},
_each: function(iterator) {
this.effects._each(iterator);
},
add: function(effect) {
var timestamp = new Date().getTime();
var position = (typeof effect.options.queue == 'string') ?
effect.options.queue : effect.options.queue.position;
switch(position) {
case 'front':
// move unstarted effects after this effect
this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) {
e.startOn += effect.finishOn;
e.finishOn += effect.finishOn;
});
break;
case 'end':
// start effect after last queued effect has finished
timestamp = this.effects.pluck('finishOn').max() || timestamp;
break;
}
effect.startOn += timestamp;
effect.finishOn += timestamp;
if(!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit))
this.effects.push(effect);
if(!this.interval)
this.interval = setInterval(this.loop.bind(this), 40);
},
remove: function(effect) {
this.effects = this.effects.reject(function(e) { return e==effect });
if(this.effects.length == 0) {
clearInterval(this.interval);
this.interval = null;
}
},
loop: function() {
var timePos = new Date().getTime();
this.effects.invoke('loop', timePos);
}
});
Effect.Queues = {
instances: $H(),
get: function(queueName) {
if(typeof queueName != 'string') return queueName;
if(!this.instances[queueName])
this.instances[queueName] = new Effect.ScopedQueue();
return this.instances[queueName];
}
}
Effect.Queue = Effect.Queues.get('global');
Effect.DefaultOptions = {
transition: Effect.Transitions.sinoidal,
duration: 1.0, // seconds
fps: 25.0, // max. 25fps due to Effect.Queue implementation
sync: false, // true for combining
from: 0.0,
to: 1.0,
delay: 0.0,
queue: 'parallel'
}
Effect.Base = function() {};
Effect.Base.prototype = {
position: null,
start: function(options) {
this.options = Object.extend(Object.extend({},Effect.DefaultOptions), options || {});
this.currentFrame = 0;
this.state = 'idle';
this.startOn = this.options.delay*1000;
this.finishOn = this.startOn + (this.options.duration*1000);
this.event('beforeStart');
if(!this.options.sync)
Effect.Queues.get(typeof this.options.queue == 'string' ?
'global' : this.options.queue.scope).add(this);
},
loop: function(timePos) {
if(timePos >= this.startOn) {
if(timePos >= this.finishOn) {
this.render(1.0);
this.cancel();
this.event('beforeFinish');
if(this.finish) this.finish();
this.event('afterFinish');
return;
}
var pos = (timePos - this.startOn) / (this.finishOn - this.startOn);
var frame = Math.round(pos * this.options.fps * this.options.duration);
if(frame > this.currentFrame) {
this.render(pos);
this.currentFrame = frame;
}
}
},
render: function(pos) {
if(this.state == 'idle') {
this.state = 'running';
this.event('beforeSetup');
if(this.setup) this.setup();
this.event('afterSetup');
}
if(this.state == 'running') {
if(this.options.transition) pos = this.options.transition(pos);
pos *= (this.options.to-this.options.from);
pos += this.options.from;
this.position = pos;
this.event('beforeUpdate');
if(this.update) this.update(pos);
this.event('afterUpdate');
}
},
cancel: function() {
if(!this.options.sync)
Effect.Queues.get(typeof this.options.queue == 'string' ?
'global' : this.options.queue.scope).remove(this);
this.state = 'finished';
},
event: function(eventName) {
if(this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this);
if(this.options[eventName]) this.options[eventName](this);
},
inspect: function() {
return '#<Effect:' + $H(this).inspect() + ',options:' + $H(this.options).inspect() + '>';
}
}
Effect.Parallel = Class.create();
Object.extend(Object.extend(Effect.Parallel.prototype, Effect.Base.prototype), {
initialize: function(effects) {
this.effects = effects || [];
this.start(arguments[1]);
},
update: function(position) {
this.effects.invoke('render', position);
},
finish: function(position) {
this.effects.each( function(effect) {
effect.render(1.0);
effect.cancel();
effect.event('beforeFinish');
if(effect.finish) effect.finish(position);
effect.event('afterFinish');
});
}
});
Effect.Opacity = Class.create();
Object.extend(Object.extend(Effect.Opacity.prototype, Effect.Base.prototype), {
initialize: function(element) {
this.element = $(element);
// make this work on IE on elements without 'layout'
if(/MSIE/.test(navigator.userAgent) && (!this.element.hasLayout))
this.element.setStyle({zoom: 1});
var options = Object.extend({
from: this.element.getOpacity() || 0.0,
to: 1.0
}, arguments[1] || {});
this.start(options);
},
update: function(position) {
this.element.setOpacity(position);
}
});
Effect.Move = Class.create();
Object.extend(Object.extend(Effect.Move.prototype, Effect.Base.prototype), {
initialize: function(element) {
this.element = $(element);
var options = Object.extend({
x: 0,
y: 0,
mode: 'relative'
}, arguments[1] || {});
this.start(options);
},
setup: function() {
// Bug in Opera: Opera returns the "real" position of a static element or
// relative element that does not have top/left explicitly set.
// ==> Always set top and left for position relative elements in your stylesheets
// (to 0 if you do not need them)
this.element.makePositioned();
this.originalLeft = parseFloat(this.element.getStyle('left') || '0');
this.originalTop = parseFloat(this.element.getStyle('top') || '0');
if(this.options.mode == 'absolute') {
// absolute movement, so we need to calc deltaX and deltaY
this.options.x = this.options.x - this.originalLeft;
this.options.y = this.options.y - this.originalTop;
}
},
update: function(position) {
this.element.setStyle({
left: this.options.x * position + this.originalLeft + 'px',
top: this.options.y * position + this.originalTop + 'px'
});
}
});
// for backwards compatibility
Effect.MoveBy = function(element, toTop, toLeft) {
return new Effect.Move(element,
Object.extend({ x: toLeft, y: toTop }, arguments[3] || {}));
};
Effect.Scale = Class.create();
Object.extend(Object.extend(Effect.Scale.prototype, Effect.Base.prototype), {
initialize: function(element, percent) {
this.element = $(element)
var options = Object.extend({
scaleX: true,
scaleY: true,
scaleContent: true,
scaleFromCenter: false,
scaleMode: 'box', // 'box' or 'contents' or {} with provided values
scaleFrom: 100.0,
scaleTo: percent
}, arguments[2] || {});
this.start(options);
},
setup: function() {
this.restoreAfterFinish = this.options.restoreAfterFinish || false;
this.elementPositioning = this.element.getStyle('position');
this.originalStyle = {};
['top','left','width','height','fontSize'].each( function(k) {
this.originalStyle[k] = this.element.style[k];
}.bind(this));
this.originalTop = this.element.offsetTop;
this.originalLeft = this.element.offsetLeft;
var fontSize = this.element.getStyle('font-size') || '100%';
['em','px','%'].each( function(fontSizeType) {
if(fontSize.indexOf(fontSizeType)>0) {
this.fontSize = parseFloat(fontSize);
this.fontSizeType = fontSizeType;
}
}.bind(this));
this.factor = (this.options.scaleTo - this.options.scaleFrom)/100;
this.dims = null;
if(this.options.scaleMode=='box')
this.dims = [this.element.offsetHeight, this.element.offsetWidth];
if(/^content/.test(this.options.scaleMode))
this.dims = [this.element.scrollHeight, this.element.scrollWidth];
if(!this.dims)
this.dims = [this.options.scaleMode.originalHeight,
this.options.scaleMode.originalWidth];
},
update: function(position) {
var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position);
if(this.options.scaleContent && this.fontSize)
this.element.setStyle({fontSize: this.fontSize * currentScale + this.fontSizeType });
this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale);
},
finish: function(position) {
if (this.restoreAfterFinish) this.element.setStyle(this.originalStyle);
},
setDimensions: function(height, width) {
var d = {};
if(this.options.scaleX) d.width = width + 'px';
if(this.options.scaleY) d.height = height + 'px';
if(this.options.scaleFromCenter) {
var topd = (height - this.dims[0])/2;
var leftd = (width - this.dims[1])/2;
if(this.elementPositioning == 'absolute') {
if(this.options.scaleY) d.top = this.originalTop-topd + 'px';
if(this.options.scaleX) d.left = this.originalLeft-leftd + 'px';
} else {
if(this.options.scaleY) d.top = -topd + 'px';
if(this.options.scaleX) d.left = -leftd + 'px';
}
}
this.element.setStyle(d);
}
});
Effect.Highlight = Class.create();
Object.extend(Object.extend(Effect.Highlight.prototype, Effect.Base.prototype), {
initialize: function(element) {
this.element = $(element);
var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || {});
this.start(options);
},
setup: function() {
// Prevent executing on elements not in the layout flow
if(this.element.getStyle('display')=='none') { this.cancel(); return; }
// Disable background image during the effect
this.oldStyle = {
backgroundImage: this.element.getStyle('background-image') };
this.element.setStyle({backgroundImage: 'none'});
if(!this.options.endcolor)
this.options.endcolor = this.element.getStyle('background-color').parseColor('#ffffff');
if(!this.options.restorecolor)
this.options.restorecolor = this.element.getStyle('background-color');
// init color calculations
this._base = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this));
this._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this));
},
update: function(position) {
this.element.setStyle({backgroundColor: $R(0,2).inject('#',function(m,v,i){
return m+(Math.round(this._base[i]+(this._delta[i]*position)).toColorPart()); }.bind(this)) });
},
finish: function() {
this.element.setStyle(Object.extend(this.oldStyle, {
backgroundColor: this.options.restorecolor
}));
}
});
Effect.ScrollTo = Class.create();
Object.extend(Object.extend(Effect.ScrollTo.prototype, Effect.Base.prototype), {
initialize: function(element) {
this.element = $(element);
this.start(arguments[1] || {});
},
setup: function() {
Position.prepare();
var offsets = Position.cumulativeOffset(this.element);
if(this.options.offset) offsets[1] += this.options.offset;
var max = window.innerHeight ?
window.height - window.innerHeight :
document.body.scrollHeight -
(document.documentElement.clientHeight ?
document.documentElement.clientHeight : document.body.clientHeight);
this.scrollStart = Position.deltaY;
this.delta = (offsets[1] > max ? max : offsets[1]) - this.scrollStart;
},
update: function(position) {
Position.prepare();
window.scrollTo(Position.deltaX,
this.scrollStart + (position*this.delta));
}
});
/* ------------- combination effects ------------- */
Effect.Fade = function(element) {
element = $(element);
var oldOpacity = element.getInlineOpacity();
var options = Object.extend({
from: element.getOpacity() || 1.0,
to: 0.0,
afterFinishInternal: function(effect) {
if(effect.options.to!=0) return;
effect.element.hide();
effect.element.setStyle({opacity: oldOpacity});
}}, arguments[1] || {});
return new Effect.Opacity(element,options);
}
Effect.Appear = function(element) {
element = $(element);
var options = Object.extend({
from: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0),
to: 1.0,
// force Safari to render floated elements properly
afterFinishInternal: function(effect) {
effect.element.forceRerendering();
},
beforeSetup: function(effect) {
effect.element.setOpacity(effect.options.from);
effect.element.show();
}}, arguments[1] || {});
return new Effect.Opacity(element,options);
}
Effect.Puff = function(element) {
element = $(element);
var oldStyle = { opacity: element.getInlineOpacity(), position: element.getStyle('position') };
return new Effect.Parallel(
[ new Effect.Scale(element, 200,
{ sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }),
new Effect.Opacity(element, { sync: true, to: 0.0 } ) ],
Object.extend({ duration: 1.0,
beforeSetupInternal: function(effect) {
effect.effects[0].element.setStyle({position: 'absolute'}); },
afterFinishInternal: function(effect) {
effect.effects[0].element.hide();
effect.effects[0].element.setStyle(oldStyle); }
}, arguments[1] || {})
);
}
Effect.BlindUp = function(element) {
element = $(element);
element.makeClipping();
return new Effect.Scale(element, 0,
Object.extend({ scaleContent: false,
scaleX: false,
restoreAfterFinish: true,
afterFinishInternal: function(effect) {
effect.element.hide();
effect.element.undoClipping();
}
}, arguments[1] || {})
);
}
Effect.BlindDown = function(element) {
element = $(element);
var elementDimensions = element.getDimensions();
return new Effect.Scale(element, 100,
Object.extend({ scaleContent: false,
scaleX: false,
scaleFrom: 0,
scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
restoreAfterFinish: true,
afterSetup: function(effect) {
effect.element.makeClipping();
effect.element.setStyle({height: '0px'});
effect.element.show();
},
afterFinishInternal: function(effect) {
effect.element.undoClipping();
}
}, arguments[1] || {})
);
}
Effect.SwitchOff = function(element) {
element = $(element);
var oldOpacity = element.getInlineOpacity();
return new Effect.Appear(element, {
duration: 0.4,
from: 0,
transition: Effect.Transitions.flicker,
afterFinishInternal: function(effect) {
new Effect.Scale(effect.element, 1, {
duration: 0.3, scaleFromCenter: true,
scaleX: false, scaleContent: false, restoreAfterFinish: true,
beforeSetup: function(effect) {
effect.element.makePositioned();
effect.element.makeClipping();
},
afterFinishInternal: function(effect) {
effect.element.hide();
effect.element.undoClipping();
effect.element.undoPositioned();
effect.element.setStyle({opacity: oldOpacity});
}
})
}
});
}
Effect.DropOut = function(element) {
element = $(element);
var oldStyle = {
top: element.getStyle('top'),
left: element.getStyle('left'),
opacity: element.getInlineOpacity() };
return new Effect.Parallel(
[ new Effect.Move(element, {x: 0, y: 100, sync: true }),
new Effect.Opacity(element, { sync: true, to: 0.0 }) ],
Object.extend(
{ duration: 0.5,
beforeSetup: function(effect) {
effect.effects[0].element.makePositioned();
},
afterFinishInternal: function(effect) {
effect.effects[0].element.hide();
effect.effects[0].element.undoPositioned();
effect.effects[0].element.setStyle(oldStyle);
}
}, arguments[1] || {}));
}
Effect.Shake = function(element) {
element = $(element);
var oldStyle = {
top: element.getStyle('top'),
left: element.getStyle('left') };
return new Effect.Move(element,
{ x: 20, y: 0, duration: 0.05, afterFinishInternal: function(effect) {
new Effect.Move(effect.element,
{ x: -40, y: 0, duration: 0.1, afterFinishInternal: function(effect) {
new Effect.Move(effect.element,
{ x: 40, y: 0, duration: 0.1, afterFinishInternal: function(effect) {
new Effect.Move(effect.element,
{ x: -40, y: 0, duration: 0.1, afterFinishInternal: function(effect) {
new Effect.Move(effect.element,
{ x: 40, y: 0, duration: 0.1, afterFinishInternal: function(effect) {
new Effect.Move(effect.element,
{ x: -20, y: 0, duration: 0.05, afterFinishInternal: function(effect) {
effect.element.undoPositioned();
effect.element.setStyle(oldStyle);
}}) }}) }}) }}) }}) }});
}
Effect.SlideDown = function(element) {
element = $(element);
element.cleanWhitespace();
// SlideDown need to have the content of the element wrapped in a container element with fixed height!
var oldInnerBottom = $(element.firstChild).getStyle('bottom');
var elementDimensions = element.getDimensions();
return new Effect.Scale(element, 100, Object.extend({
scaleContent: false,
scaleX: false,
scaleFrom: window.opera ? 0 : 1,
scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
restoreAfterFinish: true,
afterSetup: function(effect) {
effect.element.makePositioned();
effect.element.firstChild.makePositioned();
if(window.opera) effect.element.setStyle({top: ''});
effect.element.makeClipping();
effect.element.setStyle({height: '0px'});
effect.element.show(); },
afterUpdateInternal: function(effect) {
effect.element.firstChild.setStyle({bottom:
(effect.dims[0] - effect.element.clientHeight) + 'px' });
},
afterFinishInternal: function(effect) {
effect.element.undoClipping();
// IE will crash if child is undoPositioned first
if(/MSIE/.test(navigator.userAgent)){
effect.element.undoPositioned();
effect.element.firstChild.undoPositioned();
}else{
effect.element.firstChild.undoPositioned();
effect.element.undoPositioned();
}
effect.element.firstChild.setStyle({bottom: oldInnerBottom}); }
}, arguments[1] || {})
);
}
Effect.SlideUp = function(element) {
element = $(element);
element.cleanWhitespace();
var oldInnerBottom = $(element.firstChild).getStyle('bottom');
return new Effect.Scale(element, window.opera ? 0 : 1,
Object.extend({ scaleContent: false,
scaleX: false,
scaleMode: 'box',
scaleFrom: 100,
restoreAfterFinish: true,
beforeStartInternal: function(effect) {
effect.element.makePositioned();
effect.element.firstChild.makePositioned();
if(window.opera) effect.element.setStyle({top: ''});
effect.element.makeClipping();
effect.element.show(); },
afterUpdateInternal: function(effect) {
effect.element.firstChild.setStyle({bottom:
(effect.dims[0] - effect.element.clientHeight) + 'px' }); },
afterFinishInternal: function(effect) {
effect.element.hide();
effect.element.undoClipping();
effect.element.firstChild.undoPositioned();
effect.element.undoPositioned();
effect.element.setStyle({bottom: oldInnerBottom}); }
}, arguments[1] || {})
);
}
// Bug in opera makes the TD containing this element expand for a instance after finish
Effect.Squish = function(element) {
return new Effect.Scale(element, window.opera ? 1 : 0,
{ restoreAfterFinish: true,
beforeSetup: function(effect) {
effect.element.makeClipping(effect.element); },
afterFinishInternal: function(effect) {
effect.element.hide(effect.element);
effect.element.undoClipping(effect.element); }
});
}
Effect.Grow = function(element) {
element = $(element);
var options = Object.extend({
direction: 'center',
moveTransition: Effect.Transitions.sinoidal,
scaleTransition: Effect.Transitions.sinoidal,
opacityTransition: Effect.Transitions.full
}, arguments[1] || {});
var oldStyle = {
top: element.style.top,
left: element.style.left,
height: element.style.height,
width: element.style.width,
opacity: element.getInlineOpacity() };
var dims = element.getDimensions();
var initialMoveX, initialMoveY;
var moveX, moveY;
switch (options.direction) {
case 'top-left':
initialMoveX = initialMoveY = moveX = moveY = 0;
break;
case 'top-right':
initialMoveX = dims.width;
initialMoveY = moveY = 0;
moveX = -dims.width;
break;
case 'bottom-left':
initialMoveX = moveX = 0;
initialMoveY = dims.height;
moveY = -dims.height;
break;
case 'bottom-right':
initialMoveX = dims.width;
initialMoveY = dims.height;
moveX = -dims.width;
moveY = -dims.height;
break;
case 'center':
initialMoveX = dims.width / 2;
initialMoveY = dims.height / 2;
moveX = -dims.width / 2;
moveY = -dims.height / 2;
break;
}
return new Effect.Move(element, {
x: initialMoveX,
y: initialMoveY,
duration: 0.01,
beforeSetup: function(effect) {
effect.element.hide();
effect.element.makeClipping();
effect.element.makePositioned();
},
afterFinishInternal: function(effect) {
new Effect.Parallel(
[ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }),
new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }),
new Effect.Scale(effect.element, 100, {
scaleMode: { originalHeight: dims.height, originalWidth: dims.width },
sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true})
], Object.extend({
beforeSetup: function(effect) {
effect.effects[0].element.setStyle({height: '0px'});
effect.effects[0].element.show();
},
afterFinishInternal: function(effect) {
effect.effects[0].element.undoClipping();
effect.effects[0].element.undoPositioned();
effect.effects[0].element.setStyle(oldStyle);
}
}, options)
)
}
});
}
Effect.Shrink = function(element) {
element = $(element);
var options = Object.extend({
direction: 'center',
moveTransition: Effect.Transitions.sinoidal,
scaleTransition: Effect.Transitions.sinoidal,
opacityTransition: Effect.Transitions.none
}, arguments[1] || {});
var oldStyle = {
top: element.style.top,
left: element.style.left,
height: element.style.height,
width: element.style.width,
opacity: element.getInlineOpacity() };
var dims = element.getDimensions();
var moveX, moveY;
switch (options.direction) {
case 'top-left':
moveX = moveY = 0;
break;
case 'top-right':
moveX = dims.width;
moveY = 0;
break;
case 'bottom-left':
moveX = 0;
moveY = dims.height;
break;
case 'bottom-right':
moveX = dims.width;
moveY = dims.height;
break;
case 'center':
moveX = dims.width / 2;
moveY = dims.height / 2;
break;
}
return new Effect.Parallel(
[ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }),
new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}),
new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition })
], Object.extend({
beforeStartInternal: function(effect) {
effect.effects[0].element.makePositioned();
effect.effects[0].element.makeClipping(); },
afterFinishInternal: function(effect) {
effect.effects[0].element.hide();
effect.effects[0].element.undoClipping();
effect.effects[0].element.undoPositioned();
effect.effects[0].element.setStyle(oldStyle); }
}, options)
);
}
Effect.Pulsate = function(element) {
element = $(element);
var options = arguments[1] || {};
var oldOpacity = element.getInlineOpacity();
var transition = options.transition || Effect.Transitions.sinoidal;
var reverser = function(pos){ return transition(1-Effect.Transitions.pulse(pos)) };
reverser.bind(transition);
return new Effect.Opacity(element,
Object.extend(Object.extend({ duration: 3.0, from: 0,
afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); }
}, options), {transition: reverser}));
}
Effect.Fold = function(element) {
element = $(element);
var oldStyle = {
top: element.style.top,
left: element.style.left,
width: element.style.width,
height: element.style.height };
Element.makeClipping(element);
return new Effect.Scale(element, 5, Object.extend({
scaleContent: false,
scaleX: false,
afterFinishInternal: function(effect) {
new Effect.Scale(element, 1, {
scaleContent: false,
scaleY: false,
afterFinishInternal: function(effect) {
effect.element.hide();
effect.element.undoClipping();
effect.element.setStyle(oldStyle);
} });
}}, arguments[1] || {}));
};
['setOpacity','getOpacity','getInlineOpacity','forceRerendering','setContentZoom',
'collectTextNodes','collectTextNodesIgnoreClass','childrenWithClassName'].each(
function(f) { Element.Methods[f] = Element[f]; }
);
Element.Methods.visualEffect = function(element, effect, options) {
s = effect.gsub(/_/, '-').camelize();
effect_class = s.charAt(0).toUpperCase() + s.substring(1);
new Effect[effect_class](element, options);
return $(element);
};
Element.addMethods(); | zc.selenium | /zc.selenium-1.2.1.tar.gz/zc.selenium-1.2.1/src/zc/selenium/resources/lib/scriptaculous/effects.js | effects.js |
var Droppables = {
drops: [],
remove: function(element) {
this.drops = this.drops.reject(function(d) { return d.element==$(element) });
},
add: function(element) {
element = $(element);
var options = Object.extend({
greedy: true,
hoverclass: null,
tree: false
}, arguments[1] || {});
// cache containers
if(options.containment) {
options._containers = [];
var containment = options.containment;
if((typeof containment == 'object') &&
(containment.constructor == Array)) {
containment.each( function(c) { options._containers.push($(c)) });
} else {
options._containers.push($(containment));
}
}
if(options.accept) options.accept = [options.accept].flatten();
Element.makePositioned(element); // fix IE
options.element = element;
this.drops.push(options);
},
findDeepestChild: function(drops) {
deepest = drops[0];
for (i = 1; i < drops.length; ++i)
if (Element.isParent(drops[i].element, deepest.element))
deepest = drops[i];
return deepest;
},
isContained: function(element, drop) {
var containmentNode;
if(drop.tree) {
containmentNode = element.treeNode;
} else {
containmentNode = element.parentNode;
}
return drop._containers.detect(function(c) { return containmentNode == c });
},
isAffected: function(point, element, drop) {
return (
(drop.element!=element) &&
((!drop._containers) ||
this.isContained(element, drop)) &&
((!drop.accept) ||
(Element.classNames(element).detect(
function(v) { return drop.accept.include(v) } ) )) &&
Position.within(drop.element, point[0], point[1]) );
},
deactivate: function(drop) {
if(drop.hoverclass)
Element.removeClassName(drop.element, drop.hoverclass);
this.last_active = null;
},
activate: function(drop) {
if(drop.hoverclass)
Element.addClassName(drop.element, drop.hoverclass);
this.last_active = drop;
},
show: function(point, element) {
if(!this.drops.length) return;
var affected = [];
if(this.last_active) this.deactivate(this.last_active);
this.drops.each( function(drop) {
if(Droppables.isAffected(point, element, drop))
affected.push(drop);
});
if(affected.length>0) {
drop = Droppables.findDeepestChild(affected);
Position.within(drop.element, point[0], point[1]);
if(drop.onHover)
drop.onHover(element, drop.element, Position.overlap(drop.overlap, drop.element));
Droppables.activate(drop);
}
},
fire: function(event, element) {
if(!this.last_active) return;
Position.prepare();
if (this.isAffected([Event.pointerX(event), Event.pointerY(event)], element, this.last_active))
if (this.last_active.onDrop)
this.last_active.onDrop(element, this.last_active.element, event);
},
reset: function() {
if(this.last_active)
this.deactivate(this.last_active);
}
}
var Draggables = {
drags: [],
observers: [],
register: function(draggable) {
if(this.drags.length == 0) {
this.eventMouseUp = this.endDrag.bindAsEventListener(this);
this.eventMouseMove = this.updateDrag.bindAsEventListener(this);
this.eventKeypress = this.keyPress.bindAsEventListener(this);
Event.observe(document, "mouseup", this.eventMouseUp);
Event.observe(document, "mousemove", this.eventMouseMove);
Event.observe(document, "keypress", this.eventKeypress);
}
this.drags.push(draggable);
},
unregister: function(draggable) {
this.drags = this.drags.reject(function(d) { return d==draggable });
if(this.drags.length == 0) {
Event.stopObserving(document, "mouseup", this.eventMouseUp);
Event.stopObserving(document, "mousemove", this.eventMouseMove);
Event.stopObserving(document, "keypress", this.eventKeypress);
}
},
activate: function(draggable) {
window.focus(); // allows keypress events if window isn't currently focused, fails for Safari
this.activeDraggable = draggable;
},
deactivate: function() {
this.activeDraggable = null;
},
updateDrag: function(event) {
if(!this.activeDraggable) return;
var pointer = [Event.pointerX(event), Event.pointerY(event)];
// Mozilla-based browsers fire successive mousemove events with
// the same coordinates, prevent needless redrawing (moz bug?)
if(this._lastPointer && (this._lastPointer.inspect() == pointer.inspect())) return;
this._lastPointer = pointer;
this.activeDraggable.updateDrag(event, pointer);
},
endDrag: function(event) {
if(!this.activeDraggable) return;
this._lastPointer = null;
this.activeDraggable.endDrag(event);
this.activeDraggable = null;
},
keyPress: function(event) {
if(this.activeDraggable)
this.activeDraggable.keyPress(event);
},
addObserver: function(observer) {
this.observers.push(observer);
this._cacheObserverCallbacks();
},
removeObserver: function(element) { // element instead of observer fixes mem leaks
this.observers = this.observers.reject( function(o) { return o.element==element });
this._cacheObserverCallbacks();
},
notify: function(eventName, draggable, event) { // 'onStart', 'onEnd', 'onDrag'
if(this[eventName+'Count'] > 0)
this.observers.each( function(o) {
if(o[eventName]) o[eventName](eventName, draggable, event);
});
},
_cacheObserverCallbacks: function() {
['onStart','onEnd','onDrag'].each( function(eventName) {
Draggables[eventName+'Count'] = Draggables.observers.select(
function(o) { return o[eventName]; }
).length;
});
}
}
/*--------------------------------------------------------------------------*/
var Draggable = Class.create();
Draggable.prototype = {
initialize: function(element) {
var options = Object.extend({
handle: false,
starteffect: function(element) {
element._opacity = Element.getOpacity(element);
new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7});
},
reverteffect: function(element, top_offset, left_offset) {
var dur = Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02;
element._revert = new Effect.Move(element, { x: -left_offset, y: -top_offset, duration: dur});
},
endeffect: function(element) {
var toOpacity = typeof element._opacity == 'number' ? element._opacity : 1.0
new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity});
},
zindex: 1000,
revert: false,
scroll: false,
scrollSensitivity: 20,
scrollSpeed: 15,
snap: false // false, or xy or [x,y] or function(x,y){ return [x,y] }
}, arguments[1] || {});
this.element = $(element);
if(options.handle && (typeof options.handle == 'string')) {
var h = Element.childrenWithClassName(this.element, options.handle, true);
if(h.length>0) this.handle = h[0];
}
if(!this.handle) this.handle = $(options.handle);
if(!this.handle) this.handle = this.element;
if(options.scroll && !options.scroll.scrollTo && !options.scroll.outerHTML)
options.scroll = $(options.scroll);
Element.makePositioned(this.element); // fix IE
this.delta = this.currentDelta();
this.options = options;
this.dragging = false;
this.eventMouseDown = this.initDrag.bindAsEventListener(this);
Event.observe(this.handle, "mousedown", this.eventMouseDown);
Draggables.register(this);
},
destroy: function() {
Event.stopObserving(this.handle, "mousedown", this.eventMouseDown);
Draggables.unregister(this);
},
currentDelta: function() {
return([
parseInt(Element.getStyle(this.element,'left') || '0'),
parseInt(Element.getStyle(this.element,'top') || '0')]);
},
initDrag: function(event) {
if(Event.isLeftClick(event)) {
// abort on form elements, fixes a Firefox issue
var src = Event.element(event);
if(src.tagName && (
src.tagName=='INPUT' ||
src.tagName=='SELECT' ||
src.tagName=='OPTION' ||
src.tagName=='BUTTON' ||
src.tagName=='TEXTAREA')) return;
if(this.element._revert) {
this.element._revert.cancel();
this.element._revert = null;
}
var pointer = [Event.pointerX(event), Event.pointerY(event)];
var pos = Position.cumulativeOffset(this.element);
this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]) });
Draggables.activate(this);
Event.stop(event);
}
},
startDrag: function(event) {
this.dragging = true;
if(this.options.zindex) {
this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0);
this.element.style.zIndex = this.options.zindex;
}
if(this.options.ghosting) {
this._clone = this.element.cloneNode(true);
Position.absolutize(this.element);
this.element.parentNode.insertBefore(this._clone, this.element);
}
if(this.options.scroll) {
if (this.options.scroll == window) {
var where = this._getWindowScroll(this.options.scroll);
this.originalScrollLeft = where.left;
this.originalScrollTop = where.top;
} else {
this.originalScrollLeft = this.options.scroll.scrollLeft;
this.originalScrollTop = this.options.scroll.scrollTop;
}
}
Draggables.notify('onStart', this, event);
if(this.options.starteffect) this.options.starteffect(this.element);
},
updateDrag: function(event, pointer) {
if(!this.dragging) this.startDrag(event);
Position.prepare();
Droppables.show(pointer, this.element);
Draggables.notify('onDrag', this, event);
this.draw(pointer);
if(this.options.change) this.options.change(this);
if(this.options.scroll) {
this.stopScrolling();
var p;
if (this.options.scroll == window) {
with(this._getWindowScroll(this.options.scroll)) { p = [ left, top, left+width, top+height ]; }
} else {
p = Position.page(this.options.scroll);
p[0] += this.options.scroll.scrollLeft;
p[1] += this.options.scroll.scrollTop;
p.push(p[0]+this.options.scroll.offsetWidth);
p.push(p[1]+this.options.scroll.offsetHeight);
}
var speed = [0,0];
if(pointer[0] < (p[0]+this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[0]+this.options.scrollSensitivity);
if(pointer[1] < (p[1]+this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[1]+this.options.scrollSensitivity);
if(pointer[0] > (p[2]-this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[2]-this.options.scrollSensitivity);
if(pointer[1] > (p[3]-this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[3]-this.options.scrollSensitivity);
this.startScrolling(speed);
}
// fix AppleWebKit rendering
if(navigator.appVersion.indexOf('AppleWebKit')>0) window.scrollBy(0,0);
Event.stop(event);
},
finishDrag: function(event, success) {
this.dragging = false;
if(this.options.ghosting) {
Position.relativize(this.element);
Element.remove(this._clone);
this._clone = null;
}
if(success) Droppables.fire(event, this.element);
Draggables.notify('onEnd', this, event);
var revert = this.options.revert;
if(revert && typeof revert == 'function') revert = revert(this.element);
var d = this.currentDelta();
if(revert && this.options.reverteffect) {
this.options.reverteffect(this.element,
d[1]-this.delta[1], d[0]-this.delta[0]);
} else {
this.delta = d;
}
if(this.options.zindex)
this.element.style.zIndex = this.originalZ;
if(this.options.endeffect)
this.options.endeffect(this.element);
Draggables.deactivate(this);
Droppables.reset();
},
keyPress: function(event) {
if(event.keyCode!=Event.KEY_ESC) return;
this.finishDrag(event, false);
Event.stop(event);
},
endDrag: function(event) {
if(!this.dragging) return;
this.stopScrolling();
this.finishDrag(event, true);
Event.stop(event);
},
draw: function(point) {
var pos = Position.cumulativeOffset(this.element);
var d = this.currentDelta();
pos[0] -= d[0]; pos[1] -= d[1];
if(this.options.scroll && (this.options.scroll != window)) {
pos[0] -= this.options.scroll.scrollLeft-this.originalScrollLeft;
pos[1] -= this.options.scroll.scrollTop-this.originalScrollTop;
}
var p = [0,1].map(function(i){
return (point[i]-pos[i]-this.offset[i])
}.bind(this));
if(this.options.snap) {
if(typeof this.options.snap == 'function') {
p = this.options.snap(p[0],p[1],this);
} else {
if(this.options.snap instanceof Array) {
p = p.map( function(v, i) {
return Math.round(v/this.options.snap[i])*this.options.snap[i] }.bind(this))
} else {
p = p.map( function(v) {
return Math.round(v/this.options.snap)*this.options.snap }.bind(this))
}
}}
var style = this.element.style;
if((!this.options.constraint) || (this.options.constraint=='horizontal'))
style.left = p[0] + "px";
if((!this.options.constraint) || (this.options.constraint=='vertical'))
style.top = p[1] + "px";
if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering
},
stopScrolling: function() {
if(this.scrollInterval) {
clearInterval(this.scrollInterval);
this.scrollInterval = null;
Draggables._lastScrollPointer = null;
}
},
startScrolling: function(speed) {
this.scrollSpeed = [speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed];
this.lastScrolled = new Date();
this.scrollInterval = setInterval(this.scroll.bind(this), 10);
},
scroll: function() {
var current = new Date();
var delta = current - this.lastScrolled;
this.lastScrolled = current;
if(this.options.scroll == window) {
with (this._getWindowScroll(this.options.scroll)) {
if (this.scrollSpeed[0] || this.scrollSpeed[1]) {
var d = delta / 1000;
this.options.scroll.scrollTo( left + d*this.scrollSpeed[0], top + d*this.scrollSpeed[1] );
}
}
} else {
this.options.scroll.scrollLeft += this.scrollSpeed[0] * delta / 1000;
this.options.scroll.scrollTop += this.scrollSpeed[1] * delta / 1000;
}
Position.prepare();
Droppables.show(Draggables._lastPointer, this.element);
Draggables.notify('onDrag', this);
Draggables._lastScrollPointer = Draggables._lastScrollPointer || $A(Draggables._lastPointer);
Draggables._lastScrollPointer[0] += this.scrollSpeed[0] * delta / 1000;
Draggables._lastScrollPointer[1] += this.scrollSpeed[1] * delta / 1000;
if (Draggables._lastScrollPointer[0] < 0)
Draggables._lastScrollPointer[0] = 0;
if (Draggables._lastScrollPointer[1] < 0)
Draggables._lastScrollPointer[1] = 0;
this.draw(Draggables._lastScrollPointer);
if(this.options.change) this.options.change(this);
},
_getWindowScroll: function(w) {
var T, L, W, H;
with (w.document) {
if (w.document.documentElement && documentElement.scrollTop) {
T = documentElement.scrollTop;
L = documentElement.scrollLeft;
} else if (w.document.body) {
T = body.scrollTop;
L = body.scrollLeft;
}
if (w.innerWidth) {
W = w.innerWidth;
H = w.innerHeight;
} else if (w.document.documentElement && documentElement.clientWidth) {
W = documentElement.clientWidth;
H = documentElement.clientHeight;
} else {
W = body.offsetWidth;
H = body.offsetHeight
}
}
return { top: T, left: L, width: W, height: H };
}
}
/*--------------------------------------------------------------------------*/
var SortableObserver = Class.create();
SortableObserver.prototype = {
initialize: function(element, observer) {
this.element = $(element);
this.observer = observer;
this.lastValue = Sortable.serialize(this.element);
},
onStart: function() {
this.lastValue = Sortable.serialize(this.element);
},
onEnd: function() {
Sortable.unmark();
if(this.lastValue != Sortable.serialize(this.element))
this.observer(this.element)
}
}
var Sortable = {
sortables: {},
_findRootElement: function(element) {
while (element.tagName != "BODY") {
if(element.id && Sortable.sortables[element.id]) return element;
element = element.parentNode;
}
},
options: function(element) {
element = Sortable._findRootElement($(element));
if(!element) return;
return Sortable.sortables[element.id];
},
destroy: function(element){
var s = Sortable.options(element);
if(s) {
Draggables.removeObserver(s.element);
s.droppables.each(function(d){ Droppables.remove(d) });
s.draggables.invoke('destroy');
delete Sortable.sortables[s.element.id];
}
},
create: function(element) {
element = $(element);
var options = Object.extend({
element: element,
tag: 'li', // assumes li children, override with tag: 'tagname'
dropOnEmpty: false,
tree: false,
treeTag: 'ul',
overlap: 'vertical', // one of 'vertical', 'horizontal'
constraint: 'vertical', // one of 'vertical', 'horizontal', false
containment: element, // also takes array of elements (or id's); or false
handle: false, // or a CSS class
only: false,
hoverclass: null,
ghosting: false,
scroll: false,
scrollSensitivity: 20,
scrollSpeed: 15,
format: /^[^_]*_(.*)$/,
onChange: Prototype.emptyFunction,
onUpdate: Prototype.emptyFunction
}, arguments[1] || {});
// clear any old sortable with same element
this.destroy(element);
// build options for the draggables
var options_for_draggable = {
revert: true,
scroll: options.scroll,
scrollSpeed: options.scrollSpeed,
scrollSensitivity: options.scrollSensitivity,
ghosting: options.ghosting,
constraint: options.constraint,
handle: options.handle };
if(options.starteffect)
options_for_draggable.starteffect = options.starteffect;
if(options.reverteffect)
options_for_draggable.reverteffect = options.reverteffect;
else
if(options.ghosting) options_for_draggable.reverteffect = function(element) {
element.style.top = 0;
element.style.left = 0;
};
if(options.endeffect)
options_for_draggable.endeffect = options.endeffect;
if(options.zindex)
options_for_draggable.zindex = options.zindex;
// build options for the droppables
var options_for_droppable = {
overlap: options.overlap,
containment: options.containment,
tree: options.tree,
hoverclass: options.hoverclass,
onHover: Sortable.onHover
//greedy: !options.dropOnEmpty
}
var options_for_tree = {
onHover: Sortable.onEmptyHover,
overlap: options.overlap,
containment: options.containment,
hoverclass: options.hoverclass
}
// fix for gecko engine
Element.cleanWhitespace(element);
options.draggables = [];
options.droppables = [];
// drop on empty handling
if(options.dropOnEmpty || options.tree) {
Droppables.add(element, options_for_tree);
options.droppables.push(element);
}
(this.findElements(element, options) || []).each( function(e) {
// handles are per-draggable
var handle = options.handle ?
Element.childrenWithClassName(e, options.handle)[0] : e;
options.draggables.push(
new Draggable(e, Object.extend(options_for_draggable, { handle: handle })));
Droppables.add(e, options_for_droppable);
if(options.tree) e.treeNode = element;
options.droppables.push(e);
});
if(options.tree) {
(Sortable.findTreeElements(element, options) || []).each( function(e) {
Droppables.add(e, options_for_tree);
e.treeNode = element;
options.droppables.push(e);
});
}
// keep reference
this.sortables[element.id] = options;
// for onupdate
Draggables.addObserver(new SortableObserver(element, options.onUpdate));
},
// return all suitable-for-sortable elements in a guaranteed order
findElements: function(element, options) {
return Element.findChildren(
element, options.only, options.tree ? true : false, options.tag);
},
findTreeElements: function(element, options) {
return Element.findChildren(
element, options.only, options.tree ? true : false, options.treeTag);
},
onHover: function(element, dropon, overlap) {
if(Element.isParent(dropon, element)) return;
if(overlap > .33 && overlap < .66 && Sortable.options(dropon).tree) {
return;
} else if(overlap>0.5) {
Sortable.mark(dropon, 'before');
if(dropon.previousSibling != element) {
var oldParentNode = element.parentNode;
element.style.visibility = "hidden"; // fix gecko rendering
dropon.parentNode.insertBefore(element, dropon);
if(dropon.parentNode!=oldParentNode)
Sortable.options(oldParentNode).onChange(element);
Sortable.options(dropon.parentNode).onChange(element);
}
} else {
Sortable.mark(dropon, 'after');
var nextElement = dropon.nextSibling || null;
if(nextElement != element) {
var oldParentNode = element.parentNode;
element.style.visibility = "hidden"; // fix gecko rendering
dropon.parentNode.insertBefore(element, nextElement);
if(dropon.parentNode!=oldParentNode)
Sortable.options(oldParentNode).onChange(element);
Sortable.options(dropon.parentNode).onChange(element);
}
}
},
onEmptyHover: function(element, dropon, overlap) {
var oldParentNode = element.parentNode;
var droponOptions = Sortable.options(dropon);
if(!Element.isParent(dropon, element)) {
var index;
var children = Sortable.findElements(dropon, {tag: droponOptions.tag});
var child = null;
if(children) {
var offset = Element.offsetSize(dropon, droponOptions.overlap) * (1.0 - overlap);
for (index = 0; index < children.length; index += 1) {
if (offset - Element.offsetSize (children[index], droponOptions.overlap) >= 0) {
offset -= Element.offsetSize (children[index], droponOptions.overlap);
} else if (offset - (Element.offsetSize (children[index], droponOptions.overlap) / 2) >= 0) {
child = index + 1 < children.length ? children[index + 1] : null;
break;
} else {
child = children[index];
break;
}
}
}
dropon.insertBefore(element, child);
Sortable.options(oldParentNode).onChange(element);
droponOptions.onChange(element);
}
},
unmark: function() {
if(Sortable._marker) Element.hide(Sortable._marker);
},
mark: function(dropon, position) {
// mark on ghosting only
var sortable = Sortable.options(dropon.parentNode);
if(sortable && !sortable.ghosting) return;
if(!Sortable._marker) {
Sortable._marker = $('dropmarker') || document.createElement('DIV');
Element.hide(Sortable._marker);
Element.addClassName(Sortable._marker, 'dropmarker');
Sortable._marker.style.position = 'absolute';
document.getElementsByTagName("body").item(0).appendChild(Sortable._marker);
}
var offsets = Position.cumulativeOffset(dropon);
Sortable._marker.style.left = offsets[0] + 'px';
Sortable._marker.style.top = offsets[1] + 'px';
if(position=='after')
if(sortable.overlap == 'horizontal')
Sortable._marker.style.left = (offsets[0]+dropon.clientWidth) + 'px';
else
Sortable._marker.style.top = (offsets[1]+dropon.clientHeight) + 'px';
Element.show(Sortable._marker);
},
_tree: function(element, options, parent) {
var children = Sortable.findElements(element, options) || [];
for (var i = 0; i < children.length; ++i) {
var match = children[i].id.match(options.format);
if (!match) continue;
var child = {
id: encodeURIComponent(match ? match[1] : null),
element: element,
parent: parent,
children: new Array,
position: parent.children.length,
container: Sortable._findChildrenElement(children[i], options.treeTag.toUpperCase())
}
/* Get the element containing the children and recurse over it */
if (child.container)
this._tree(child.container, options, child)
parent.children.push (child);
}
return parent;
},
/* Finds the first element of the given tag type within a parent element.
Used for finding the first LI[ST] within a L[IST]I[TEM].*/
_findChildrenElement: function (element, containerTag) {
if (element && element.hasChildNodes)
for (var i = 0; i < element.childNodes.length; ++i)
if (element.childNodes[i].tagName == containerTag)
return element.childNodes[i];
return null;
},
tree: function(element) {
element = $(element);
var sortableOptions = this.options(element);
var options = Object.extend({
tag: sortableOptions.tag,
treeTag: sortableOptions.treeTag,
only: sortableOptions.only,
name: element.id,
format: sortableOptions.format
}, arguments[1] || {});
var root = {
id: null,
parent: null,
children: new Array,
container: element,
position: 0
}
return Sortable._tree (element, options, root);
},
/* Construct a [i] index for a particular node */
_constructIndex: function(node) {
var index = '';
do {
if (node.id) index = '[' + node.position + ']' + index;
} while ((node = node.parent) != null);
return index;
},
sequence: function(element) {
element = $(element);
var options = Object.extend(this.options(element), arguments[1] || {});
return $(this.findElements(element, options) || []).map( function(item) {
return item.id.match(options.format) ? item.id.match(options.format)[1] : '';
});
},
setSequence: function(element, new_sequence) {
element = $(element);
var options = Object.extend(this.options(element), arguments[2] || {});
var nodeMap = {};
this.findElements(element, options).each( function(n) {
if (n.id.match(options.format))
nodeMap[n.id.match(options.format)[1]] = [n, n.parentNode];
n.parentNode.removeChild(n);
});
new_sequence.each(function(ident) {
var n = nodeMap[ident];
if (n) {
n[1].appendChild(n[0]);
delete nodeMap[ident];
}
});
},
serialize: function(element) {
element = $(element);
var options = Object.extend(Sortable.options(element), arguments[1] || {});
var name = encodeURIComponent(
(arguments[1] && arguments[1].name) ? arguments[1].name : element.id);
if (options.tree) {
return Sortable.tree(element, arguments[1]).children.map( function (item) {
return [name + Sortable._constructIndex(item) + "=" +
encodeURIComponent(item.id)].concat(item.children.map(arguments.callee));
}).flatten().join('&');
} else {
return Sortable.sequence(element, arguments[1]).map( function(item) {
return name + "[]=" + encodeURIComponent(item);
}).join('&');
}
}
}
/* Returns true if child is contained within element */
Element.isParent = function(child, element) {
if (!child.parentNode || child == element) return false;
if (child.parentNode == element) return true;
return Element.isParent(child.parentNode, element);
}
Element.findChildren = function(element, only, recursive, tagName) {
if(!element.hasChildNodes()) return null;
tagName = tagName.toUpperCase();
if(only) only = [only].flatten();
var elements = [];
$A(element.childNodes).each( function(e) {
if(e.tagName && e.tagName.toUpperCase()==tagName &&
(!only || (Element.classNames(e).detect(function(v) { return only.include(v) }))))
elements.push(e);
if(recursive) {
var grandchildren = Element.findChildren(e, only, recursive, tagName);
if(grandchildren) elements.push(grandchildren);
}
});
return (elements.length>0 ? elements.flatten() : []);
}
Element.offsetSize = function (element, type) {
if (type == 'vertical' || type == 'height')
return element.offsetHeight;
else
return element.offsetWidth;
} | zc.selenium | /zc.selenium-1.2.1.tar.gz/zc.selenium-1.2.1/src/zc/selenium/resources/lib/scriptaculous/dragdrop.js | dragdrop.js |
if(!Control) var Control = {};
Control.Slider = Class.create();
// options:
// axis: 'vertical', or 'horizontal' (default)
//
// callbacks:
// onChange(value)
// onSlide(value)
Control.Slider.prototype = {
initialize: function(handle, track, options) {
var slider = this;
if(handle instanceof Array) {
this.handles = handle.collect( function(e) { return $(e) });
} else {
this.handles = [$(handle)];
}
this.track = $(track);
this.options = options || {};
this.axis = this.options.axis || 'horizontal';
this.increment = this.options.increment || 1;
this.step = parseInt(this.options.step || '1');
this.range = this.options.range || $R(0,1);
this.value = 0; // assure backwards compat
this.values = this.handles.map( function() { return 0 });
this.spans = this.options.spans ? this.options.spans.map(function(s){ return $(s) }) : false;
this.options.startSpan = $(this.options.startSpan || null);
this.options.endSpan = $(this.options.endSpan || null);
this.restricted = this.options.restricted || false;
this.maximum = this.options.maximum || this.range.end;
this.minimum = this.options.minimum || this.range.start;
// Will be used to align the handle onto the track, if necessary
this.alignX = parseInt(this.options.alignX || '0');
this.alignY = parseInt(this.options.alignY || '0');
this.trackLength = this.maximumOffset() - this.minimumOffset();
this.handleLength = this.isVertical() ? this.handles[0].offsetHeight : this.handles[0].offsetWidth;
this.active = false;
this.dragging = false;
this.disabled = false;
if(this.options.disabled) this.setDisabled();
// Allowed values array
this.allowedValues = this.options.values ? this.options.values.sortBy(Prototype.K) : false;
if(this.allowedValues) {
this.minimum = this.allowedValues.min();
this.maximum = this.allowedValues.max();
}
this.eventMouseDown = this.startDrag.bindAsEventListener(this);
this.eventMouseUp = this.endDrag.bindAsEventListener(this);
this.eventMouseMove = this.update.bindAsEventListener(this);
// Initialize handles in reverse (make sure first handle is active)
this.handles.each( function(h,i) {
i = slider.handles.length-1-i;
slider.setValue(parseFloat(
(slider.options.sliderValue instanceof Array ?
slider.options.sliderValue[i] : slider.options.sliderValue) ||
slider.range.start), i);
Element.makePositioned(h); // fix IE
Event.observe(h, "mousedown", slider.eventMouseDown);
});
Event.observe(this.track, "mousedown", this.eventMouseDown);
Event.observe(document, "mouseup", this.eventMouseUp);
Event.observe(document, "mousemove", this.eventMouseMove);
this.initialized = true;
},
dispose: function() {
var slider = this;
Event.stopObserving(this.track, "mousedown", this.eventMouseDown);
Event.stopObserving(document, "mouseup", this.eventMouseUp);
Event.stopObserving(document, "mousemove", this.eventMouseMove);
this.handles.each( function(h) {
Event.stopObserving(h, "mousedown", slider.eventMouseDown);
});
},
setDisabled: function(){
this.disabled = true;
},
setEnabled: function(){
this.disabled = false;
},
getNearestValue: function(value){
if(this.allowedValues){
if(value >= this.allowedValues.max()) return(this.allowedValues.max());
if(value <= this.allowedValues.min()) return(this.allowedValues.min());
var offset = Math.abs(this.allowedValues[0] - value);
var newValue = this.allowedValues[0];
this.allowedValues.each( function(v) {
var currentOffset = Math.abs(v - value);
if(currentOffset <= offset){
newValue = v;
offset = currentOffset;
}
});
return newValue;
}
if(value > this.range.end) return this.range.end;
if(value < this.range.start) return this.range.start;
return value;
},
setValue: function(sliderValue, handleIdx){
if(!this.active) {
this.activeHandle = this.handles[handleIdx];
this.activeHandleIdx = handleIdx;
this.updateStyles();
}
handleIdx = handleIdx || this.activeHandleIdx || 0;
if(this.initialized && this.restricted) {
if((handleIdx>0) && (sliderValue<this.values[handleIdx-1]))
sliderValue = this.values[handleIdx-1];
if((handleIdx < (this.handles.length-1)) && (sliderValue>this.values[handleIdx+1]))
sliderValue = this.values[handleIdx+1];
}
sliderValue = this.getNearestValue(sliderValue);
this.values[handleIdx] = sliderValue;
this.value = this.values[0]; // assure backwards compat
this.handles[handleIdx].style[this.isVertical() ? 'top' : 'left'] =
this.translateToPx(sliderValue);
this.drawSpans();
if(!this.dragging || !this.event) this.updateFinished();
},
setValueBy: function(delta, handleIdx) {
this.setValue(this.values[handleIdx || this.activeHandleIdx || 0] + delta,
handleIdx || this.activeHandleIdx || 0);
},
translateToPx: function(value) {
return Math.round(
((this.trackLength-this.handleLength)/(this.range.end-this.range.start)) *
(value - this.range.start)) + "px";
},
translateToValue: function(offset) {
return ((offset/(this.trackLength-this.handleLength) *
(this.range.end-this.range.start)) + this.range.start);
},
getRange: function(range) {
var v = this.values.sortBy(Prototype.K);
range = range || 0;
return $R(v[range],v[range+1]);
},
minimumOffset: function(){
return(this.isVertical() ? this.alignY : this.alignX);
},
maximumOffset: function(){
return(this.isVertical() ?
this.track.offsetHeight - this.alignY : this.track.offsetWidth - this.alignX);
},
isVertical: function(){
return (this.axis == 'vertical');
},
drawSpans: function() {
var slider = this;
if(this.spans)
$R(0, this.spans.length-1).each(function(r) { slider.setSpan(slider.spans[r], slider.getRange(r)) });
if(this.options.startSpan)
this.setSpan(this.options.startSpan,
$R(0, this.values.length>1 ? this.getRange(0).min() : this.value ));
if(this.options.endSpan)
this.setSpan(this.options.endSpan,
$R(this.values.length>1 ? this.getRange(this.spans.length-1).max() : this.value, this.maximum));
},
setSpan: function(span, range) {
if(this.isVertical()) {
span.style.top = this.translateToPx(range.start);
span.style.height = this.translateToPx(range.end - range.start + this.range.start);
} else {
span.style.left = this.translateToPx(range.start);
span.style.width = this.translateToPx(range.end - range.start + this.range.start);
}
},
updateStyles: function() {
this.handles.each( function(h){ Element.removeClassName(h, 'selected') });
Element.addClassName(this.activeHandle, 'selected');
},
startDrag: function(event) {
if(Event.isLeftClick(event)) {
if(!this.disabled){
this.active = true;
var handle = Event.element(event);
var pointer = [Event.pointerX(event), Event.pointerY(event)];
if(handle==this.track) {
var offsets = Position.cumulativeOffset(this.track);
this.event = event;
this.setValue(this.translateToValue(
(this.isVertical() ? pointer[1]-offsets[1] : pointer[0]-offsets[0])-(this.handleLength/2)
));
var offsets = Position.cumulativeOffset(this.activeHandle);
this.offsetX = (pointer[0] - offsets[0]);
this.offsetY = (pointer[1] - offsets[1]);
} else {
// find the handle (prevents issues with Safari)
while((this.handles.indexOf(handle) == -1) && handle.parentNode)
handle = handle.parentNode;
this.activeHandle = handle;
this.activeHandleIdx = this.handles.indexOf(this.activeHandle);
this.updateStyles();
var offsets = Position.cumulativeOffset(this.activeHandle);
this.offsetX = (pointer[0] - offsets[0]);
this.offsetY = (pointer[1] - offsets[1]);
}
}
Event.stop(event);
}
},
update: function(event) {
if(this.active) {
if(!this.dragging) this.dragging = true;
this.draw(event);
// fix AppleWebKit rendering
if(navigator.appVersion.indexOf('AppleWebKit')>0) window.scrollBy(0,0);
Event.stop(event);
}
},
draw: function(event) {
var pointer = [Event.pointerX(event), Event.pointerY(event)];
var offsets = Position.cumulativeOffset(this.track);
pointer[0] -= this.offsetX + offsets[0];
pointer[1] -= this.offsetY + offsets[1];
this.event = event;
this.setValue(this.translateToValue( this.isVertical() ? pointer[1] : pointer[0] ));
if(this.initialized && this.options.onSlide)
this.options.onSlide(this.values.length>1 ? this.values : this.value, this);
},
endDrag: function(event) {
if(this.active && this.dragging) {
this.finishDrag(event, true);
Event.stop(event);
}
this.active = false;
this.dragging = false;
},
finishDrag: function(event, success) {
this.active = false;
this.dragging = false;
this.updateFinished();
},
updateFinished: function() {
if(this.initialized && this.options.onChange)
this.options.onChange(this.values.length>1 ? this.values : this.value, this);
this.event = null;
}
} | zc.selenium | /zc.selenium-1.2.1.tar.gz/zc.selenium-1.2.1/src/zc/selenium/resources/lib/scriptaculous/slider.js | slider.js |
// Autocompleter.Base handles all the autocompletion functionality
// that's independent of the data source for autocompletion. This
// includes drawing the autocompletion menu, observing keyboard
// and mouse events, and similar.
//
// Specific autocompleters need to provide, at the very least,
// a getUpdatedChoices function that will be invoked every time
// the text inside the monitored textbox changes. This method
// should get the text for which to provide autocompletion by
// invoking this.getToken(), NOT by directly accessing
// this.element.value. This is to allow incremental tokenized
// autocompletion. Specific auto-completion logic (AJAX, etc)
// belongs in getUpdatedChoices.
//
// Tokenized incremental autocompletion is enabled automatically
// when an autocompleter is instantiated with the 'tokens' option
// in the options parameter, e.g.:
// new Ajax.Autocompleter('id','upd', '/url/', { tokens: ',' });
// will incrementally autocomplete with a comma as the token.
// Additionally, ',' in the above example can be replaced with
// a token array, e.g. { tokens: [',', '\n'] } which
// enables autocompletion on multiple tokens. This is most
// useful when one of the tokens is \n (a newline), as it
// allows smart autocompletion after linebreaks.
var Autocompleter = {}
Autocompleter.Base = function() {};
Autocompleter.Base.prototype = {
baseInitialize: function(element, update, options) {
this.element = $(element);
this.update = $(update);
this.hasFocus = false;
this.changed = false;
this.active = false;
this.index = 0;
this.entryCount = 0;
if (this.setOptions)
this.setOptions(options);
else
this.options = options || {};
this.options.paramName = this.options.paramName || this.element.name;
this.options.tokens = this.options.tokens || [];
this.options.frequency = this.options.frequency || 0.4;
this.options.minChars = this.options.minChars || 1;
this.options.onShow = this.options.onShow ||
function(element, update){
if(!update.style.position || update.style.position=='absolute') {
update.style.position = 'absolute';
Position.clone(element, update, {setHeight: false, offsetTop: element.offsetHeight});
}
Effect.Appear(update,{duration:0.15});
};
this.options.onHide = this.options.onHide ||
function(element, update){ new Effect.Fade(update,{duration:0.15}) };
if (typeof(this.options.tokens) == 'string')
this.options.tokens = new Array(this.options.tokens);
this.observer = null;
this.element.setAttribute('autocomplete','off');
Element.hide(this.update);
Event.observe(this.element, "blur", this.onBlur.bindAsEventListener(this));
Event.observe(this.element, "keypress", this.onKeyPress.bindAsEventListener(this));
},
show: function() {
if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
if(!this.iefix &&
(navigator.appVersion.indexOf('MSIE')>0) &&
(navigator.userAgent.indexOf('Opera')<0) &&
(Element.getStyle(this.update, 'position')=='absolute')) {
new Insertion.After(this.update,
'<iframe id="' + this.update.id + '_iefix" '+
'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
this.iefix = $(this.update.id+'_iefix');
}
if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50);
},
fixIEOverlapping: function() {
Position.clone(this.update, this.iefix);
this.iefix.style.zIndex = 1;
this.update.style.zIndex = 2;
Element.show(this.iefix);
},
hide: function() {
this.stopIndicator();
if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update);
if(this.iefix) Element.hide(this.iefix);
},
startIndicator: function() {
if(this.options.indicator) Element.show(this.options.indicator);
},
stopIndicator: function() {
if(this.options.indicator) Element.hide(this.options.indicator);
},
onKeyPress: function(event) {
if(this.active)
switch(event.keyCode) {
case Event.KEY_TAB:
case Event.KEY_RETURN:
this.selectEntry();
Event.stop(event);
case Event.KEY_ESC:
this.hide();
this.active = false;
Event.stop(event);
return;
case Event.KEY_LEFT:
case Event.KEY_RIGHT:
return;
case Event.KEY_UP:
this.markPrevious();
this.render();
if(navigator.appVersion.indexOf('AppleWebKit')>0) Event.stop(event);
return;
case Event.KEY_DOWN:
this.markNext();
this.render();
if(navigator.appVersion.indexOf('AppleWebKit')>0) Event.stop(event);
return;
}
else
if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN ||
(navigator.appVersion.indexOf('AppleWebKit') > 0 && event.keyCode == 0)) return;
this.changed = true;
this.hasFocus = true;
if(this.observer) clearTimeout(this.observer);
this.observer =
setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
},
activate: function() {
this.changed = false;
this.hasFocus = true;
this.getUpdatedChoices();
},
onHover: function(event) {
var element = Event.findElement(event, 'LI');
if(this.index != element.autocompleteIndex)
{
this.index = element.autocompleteIndex;
this.render();
}
Event.stop(event);
},
onClick: function(event) {
var element = Event.findElement(event, 'LI');
this.index = element.autocompleteIndex;
this.selectEntry();
this.hide();
},
onBlur: function(event) {
// needed to make click events working
setTimeout(this.hide.bind(this), 250);
this.hasFocus = false;
this.active = false;
},
render: function() {
if(this.entryCount > 0) {
for (var i = 0; i < this.entryCount; i++)
this.index==i ?
Element.addClassName(this.getEntry(i),"selected") :
Element.removeClassName(this.getEntry(i),"selected");
if(this.hasFocus) {
this.show();
this.active = true;
}
} else {
this.active = false;
this.hide();
}
},
markPrevious: function() {
if(this.index > 0) this.index--
else this.index = this.entryCount-1;
},
markNext: function() {
if(this.index < this.entryCount-1) this.index++
else this.index = 0;
},
getEntry: function(index) {
return this.update.firstChild.childNodes[index];
},
getCurrentEntry: function() {
return this.getEntry(this.index);
},
selectEntry: function() {
this.active = false;
this.updateElement(this.getCurrentEntry());
},
updateElement: function(selectedElement) {
if (this.options.updateElement) {
this.options.updateElement(selectedElement);
return;
}
var value = '';
if (this.options.select) {
var nodes = document.getElementsByClassName(this.options.select, selectedElement) || [];
if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
} else
value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
var lastTokenPos = this.findLastToken();
if (lastTokenPos != -1) {
var newValue = this.element.value.substr(0, lastTokenPos + 1);
var whitespace = this.element.value.substr(lastTokenPos + 1).match(/^\s+/);
if (whitespace)
newValue += whitespace[0];
this.element.value = newValue + value;
} else {
this.element.value = value;
}
this.element.focus();
if (this.options.afterUpdateElement)
this.options.afterUpdateElement(this.element, selectedElement);
},
updateChoices: function(choices) {
if(!this.changed && this.hasFocus) {
this.update.innerHTML = choices;
Element.cleanWhitespace(this.update);
Element.cleanWhitespace(this.update.firstChild);
if(this.update.firstChild && this.update.firstChild.childNodes) {
this.entryCount =
this.update.firstChild.childNodes.length;
for (var i = 0; i < this.entryCount; i++) {
var entry = this.getEntry(i);
entry.autocompleteIndex = i;
this.addObservers(entry);
}
} else {
this.entryCount = 0;
}
this.stopIndicator();
this.index = 0;
this.render();
}
},
addObservers: function(element) {
Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this));
Event.observe(element, "click", this.onClick.bindAsEventListener(this));
},
onObserverEvent: function() {
this.changed = false;
if(this.getToken().length>=this.options.minChars) {
this.startIndicator();
this.getUpdatedChoices();
} else {
this.active = false;
this.hide();
}
},
getToken: function() {
var tokenPos = this.findLastToken();
if (tokenPos != -1)
var ret = this.element.value.substr(tokenPos + 1).replace(/^\s+/,'').replace(/\s+$/,'');
else
var ret = this.element.value;
return /\n/.test(ret) ? '' : ret;
},
findLastToken: function() {
var lastTokenPos = -1;
for (var i=0; i<this.options.tokens.length; i++) {
var thisTokenPos = this.element.value.lastIndexOf(this.options.tokens[i]);
if (thisTokenPos > lastTokenPos)
lastTokenPos = thisTokenPos;
}
return lastTokenPos;
}
}
Ajax.Autocompleter = Class.create();
Object.extend(Object.extend(Ajax.Autocompleter.prototype, Autocompleter.Base.prototype), {
initialize: function(element, update, url, options) {
this.baseInitialize(element, update, options);
this.options.asynchronous = true;
this.options.onComplete = this.onComplete.bind(this);
this.options.defaultParams = this.options.parameters || null;
this.url = url;
},
getUpdatedChoices: function() {
entry = encodeURIComponent(this.options.paramName) + '=' +
encodeURIComponent(this.getToken());
this.options.parameters = this.options.callback ?
this.options.callback(this.element, entry) : entry;
if(this.options.defaultParams)
this.options.parameters += '&' + this.options.defaultParams;
new Ajax.Request(this.url, this.options);
},
onComplete: function(request) {
this.updateChoices(request.responseText);
}
});
// The local array autocompleter. Used when you'd prefer to
// inject an array of autocompletion options into the page, rather
// than sending out Ajax queries, which can be quite slow sometimes.
//
// The constructor takes four parameters. The first two are, as usual,
// the id of the monitored textbox, and id of the autocompletion menu.
// The third is the array you want to autocomplete from, and the fourth
// is the options block.
//
// Extra local autocompletion options:
// - choices - How many autocompletion choices to offer
//
// - partialSearch - If false, the autocompleter will match entered
// text only at the beginning of strings in the
// autocomplete array. Defaults to true, which will
// match text at the beginning of any *word* in the
// strings in the autocomplete array. If you want to
// search anywhere in the string, additionally set
// the option fullSearch to true (default: off).
//
// - fullSsearch - Search anywhere in autocomplete array strings.
//
// - partialChars - How many characters to enter before triggering
// a partial match (unlike minChars, which defines
// how many characters are required to do any match
// at all). Defaults to 2.
//
// - ignoreCase - Whether to ignore case when autocompleting.
// Defaults to true.
//
// It's possible to pass in a custom function as the 'selector'
// option, if you prefer to write your own autocompletion logic.
// In that case, the other options above will not apply unless
// you support them.
Autocompleter.Local = Class.create();
Autocompleter.Local.prototype = Object.extend(new Autocompleter.Base(), {
initialize: function(element, update, array, options) {
this.baseInitialize(element, update, options);
this.options.array = array;
},
getUpdatedChoices: function() {
this.updateChoices(this.options.selector(this));
},
setOptions: function(options) {
this.options = Object.extend({
choices: 10,
partialSearch: true,
partialChars: 2,
ignoreCase: true,
fullSearch: false,
selector: function(instance) {
var ret = []; // Beginning matches
var partial = []; // Inside matches
var entry = instance.getToken();
var count = 0;
for (var i = 0; i < instance.options.array.length &&
ret.length < instance.options.choices ; i++) {
var elem = instance.options.array[i];
var foundPos = instance.options.ignoreCase ?
elem.toLowerCase().indexOf(entry.toLowerCase()) :
elem.indexOf(entry);
while (foundPos != -1) {
if (foundPos == 0 && elem.length != entry.length) {
ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" +
elem.substr(entry.length) + "</li>");
break;
} else if (entry.length >= instance.options.partialChars &&
instance.options.partialSearch && foundPos != -1) {
if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
partial.push("<li>" + elem.substr(0, foundPos) + "<strong>" +
elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
foundPos + entry.length) + "</li>");
break;
}
}
foundPos = instance.options.ignoreCase ?
elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) :
elem.indexOf(entry, foundPos + 1);
}
}
if (partial.length)
ret = ret.concat(partial.slice(0, instance.options.choices - ret.length))
return "<ul>" + ret.join('') + "</ul>";
}
}, options || {});
}
});
// AJAX in-place editor
//
// see documentation on http://wiki.script.aculo.us/scriptaculous/show/Ajax.InPlaceEditor
// Use this if you notice weird scrolling problems on some browsers,
// the DOM might be a bit confused when this gets called so do this
// waits 1 ms (with setTimeout) until it does the activation
Field.scrollFreeActivate = function(field) {
setTimeout(function() {
Field.activate(field);
}, 1);
}
Ajax.InPlaceEditor = Class.create();
Ajax.InPlaceEditor.defaultHighlightColor = "#FFFF99";
Ajax.InPlaceEditor.prototype = {
initialize: function(element, url, options) {
this.url = url;
this.element = $(element);
this.options = Object.extend({
okButton: true,
okText: "ok",
cancelLink: true,
cancelText: "cancel",
savingText: "Saving...",
clickToEditText: "Click to edit",
okText: "ok",
rows: 1,
onComplete: function(transport, element) {
new Effect.Highlight(element, {startcolor: this.options.highlightcolor});
},
onFailure: function(transport) {
alert("Error communicating with the server: " + transport.responseText.stripTags());
},
callback: function(form) {
return Form.serialize(form);
},
handleLineBreaks: true,
loadingText: 'Loading...',
savingClassName: 'inplaceeditor-saving',
loadingClassName: 'inplaceeditor-loading',
formClassName: 'inplaceeditor-form',
highlightcolor: Ajax.InPlaceEditor.defaultHighlightColor,
highlightendcolor: "#FFFFFF",
externalControl: null,
submitOnBlur: false,
ajaxOptions: {},
evalScripts: false
}, options || {});
if(!this.options.formId && this.element.id) {
this.options.formId = this.element.id + "-inplaceeditor";
if ($(this.options.formId)) {
// there's already a form with that name, don't specify an id
this.options.formId = null;
}
}
if (this.options.externalControl) {
this.options.externalControl = $(this.options.externalControl);
}
this.originalBackground = Element.getStyle(this.element, 'background-color');
if (!this.originalBackground) {
this.originalBackground = "transparent";
}
this.element.title = this.options.clickToEditText;
this.onclickListener = this.enterEditMode.bindAsEventListener(this);
this.mouseoverListener = this.enterHover.bindAsEventListener(this);
this.mouseoutListener = this.leaveHover.bindAsEventListener(this);
Event.observe(this.element, 'click', this.onclickListener);
Event.observe(this.element, 'mouseover', this.mouseoverListener);
Event.observe(this.element, 'mouseout', this.mouseoutListener);
if (this.options.externalControl) {
Event.observe(this.options.externalControl, 'click', this.onclickListener);
Event.observe(this.options.externalControl, 'mouseover', this.mouseoverListener);
Event.observe(this.options.externalControl, 'mouseout', this.mouseoutListener);
}
},
enterEditMode: function(evt) {
if (this.saving) return;
if (this.editing) return;
this.editing = true;
this.onEnterEditMode();
if (this.options.externalControl) {
Element.hide(this.options.externalControl);
}
Element.hide(this.element);
this.createForm();
this.element.parentNode.insertBefore(this.form, this.element);
Field.scrollFreeActivate(this.editField);
// stop the event to avoid a page refresh in Safari
if (evt) {
Event.stop(evt);
}
return false;
},
createForm: function() {
this.form = document.createElement("form");
this.form.id = this.options.formId;
Element.addClassName(this.form, this.options.formClassName)
this.form.onsubmit = this.onSubmit.bind(this);
this.createEditField();
if (this.options.textarea) {
var br = document.createElement("br");
this.form.appendChild(br);
}
if (this.options.okButton) {
okButton = document.createElement("input");
okButton.type = "submit";
okButton.value = this.options.okText;
okButton.className = 'editor_ok_button';
this.form.appendChild(okButton);
}
if (this.options.cancelLink) {
cancelLink = document.createElement("a");
cancelLink.href = "#";
cancelLink.appendChild(document.createTextNode(this.options.cancelText));
cancelLink.onclick = this.onclickCancel.bind(this);
cancelLink.className = 'editor_cancel';
this.form.appendChild(cancelLink);
}
},
hasHTMLLineBreaks: function(string) {
if (!this.options.handleLineBreaks) return false;
return string.match(/<br/i) || string.match(/<p>/i);
},
convertHTMLLineBreaks: function(string) {
return string.replace(/<br>/gi, "\n").replace(/<br\/>/gi, "\n").replace(/<\/p>/gi, "\n").replace(/<p>/gi, "");
},
createEditField: function() {
var text;
if(this.options.loadTextURL) {
text = this.options.loadingText;
} else {
text = this.getText();
}
var obj = this;
if (this.options.rows == 1 && !this.hasHTMLLineBreaks(text)) {
this.options.textarea = false;
var textField = document.createElement("input");
textField.obj = this;
textField.type = "text";
textField.name = "value";
textField.value = text;
textField.style.backgroundColor = this.options.highlightcolor;
textField.className = 'editor_field';
var size = this.options.size || this.options.cols || 0;
if (size != 0) textField.size = size;
if (this.options.submitOnBlur)
textField.onblur = this.onSubmit.bind(this);
this.editField = textField;
} else {
this.options.textarea = true;
var textArea = document.createElement("textarea");
textArea.obj = this;
textArea.name = "value";
textArea.value = this.convertHTMLLineBreaks(text);
textArea.rows = this.options.rows;
textArea.cols = this.options.cols || 40;
textArea.className = 'editor_field';
if (this.options.submitOnBlur)
textArea.onblur = this.onSubmit.bind(this);
this.editField = textArea;
}
if(this.options.loadTextURL) {
this.loadExternalText();
}
this.form.appendChild(this.editField);
},
getText: function() {
return this.element.innerHTML;
},
loadExternalText: function() {
Element.addClassName(this.form, this.options.loadingClassName);
this.editField.disabled = true;
new Ajax.Request(
this.options.loadTextURL,
Object.extend({
asynchronous: true,
onComplete: this.onLoadedExternalText.bind(this)
}, this.options.ajaxOptions)
);
},
onLoadedExternalText: function(transport) {
Element.removeClassName(this.form, this.options.loadingClassName);
this.editField.disabled = false;
this.editField.value = transport.responseText.stripTags();
},
onclickCancel: function() {
this.onComplete();
this.leaveEditMode();
return false;
},
onFailure: function(transport) {
this.options.onFailure(transport);
if (this.oldInnerHTML) {
this.element.innerHTML = this.oldInnerHTML;
this.oldInnerHTML = null;
}
return false;
},
onSubmit: function() {
// onLoading resets these so we need to save them away for the Ajax call
var form = this.form;
var value = this.editField.value;
// do this first, sometimes the ajax call returns before we get a chance to switch on Saving...
// which means this will actually switch on Saving... *after* we've left edit mode causing Saving...
// to be displayed indefinitely
this.onLoading();
if (this.options.evalScripts) {
new Ajax.Request(
this.url, Object.extend({
parameters: this.options.callback(form, value),
onComplete: this.onComplete.bind(this),
onFailure: this.onFailure.bind(this),
asynchronous:true,
evalScripts:true
}, this.options.ajaxOptions));
} else {
new Ajax.Updater(
{ success: this.element,
// don't update on failure (this could be an option)
failure: null },
this.url, Object.extend({
parameters: this.options.callback(form, value),
onComplete: this.onComplete.bind(this),
onFailure: this.onFailure.bind(this)
}, this.options.ajaxOptions));
}
// stop the event to avoid a page refresh in Safari
if (arguments.length > 1) {
Event.stop(arguments[0]);
}
return false;
},
onLoading: function() {
this.saving = true;
this.removeForm();
this.leaveHover();
this.showSaving();
},
showSaving: function() {
this.oldInnerHTML = this.element.innerHTML;
this.element.innerHTML = this.options.savingText;
Element.addClassName(this.element, this.options.savingClassName);
this.element.style.backgroundColor = this.originalBackground;
Element.show(this.element);
},
removeForm: function() {
if(this.form) {
if (this.form.parentNode) Element.remove(this.form);
this.form = null;
}
},
enterHover: function() {
if (this.saving) return;
this.element.style.backgroundColor = this.options.highlightcolor;
if (this.effect) {
this.effect.cancel();
}
Element.addClassName(this.element, this.options.hoverClassName)
},
leaveHover: function() {
if (this.options.backgroundColor) {
this.element.style.backgroundColor = this.oldBackground;
}
Element.removeClassName(this.element, this.options.hoverClassName)
if (this.saving) return;
this.effect = new Effect.Highlight(this.element, {
startcolor: this.options.highlightcolor,
endcolor: this.options.highlightendcolor,
restorecolor: this.originalBackground
});
},
leaveEditMode: function() {
Element.removeClassName(this.element, this.options.savingClassName);
this.removeForm();
this.leaveHover();
this.element.style.backgroundColor = this.originalBackground;
Element.show(this.element);
if (this.options.externalControl) {
Element.show(this.options.externalControl);
}
this.editing = false;
this.saving = false;
this.oldInnerHTML = null;
this.onLeaveEditMode();
},
onComplete: function(transport) {
this.leaveEditMode();
this.options.onComplete.bind(this)(transport, this.element);
},
onEnterEditMode: function() {},
onLeaveEditMode: function() {},
dispose: function() {
if (this.oldInnerHTML) {
this.element.innerHTML = this.oldInnerHTML;
}
this.leaveEditMode();
Event.stopObserving(this.element, 'click', this.onclickListener);
Event.stopObserving(this.element, 'mouseover', this.mouseoverListener);
Event.stopObserving(this.element, 'mouseout', this.mouseoutListener);
if (this.options.externalControl) {
Event.stopObserving(this.options.externalControl, 'click', this.onclickListener);
Event.stopObserving(this.options.externalControl, 'mouseover', this.mouseoverListener);
Event.stopObserving(this.options.externalControl, 'mouseout', this.mouseoutListener);
}
}
};
Ajax.InPlaceCollectionEditor = Class.create();
Object.extend(Ajax.InPlaceCollectionEditor.prototype, Ajax.InPlaceEditor.prototype);
Object.extend(Ajax.InPlaceCollectionEditor.prototype, {
createEditField: function() {
if (!this.cached_selectTag) {
var selectTag = document.createElement("select");
var collection = this.options.collection || [];
var optionTag;
collection.each(function(e,i) {
optionTag = document.createElement("option");
optionTag.value = (e instanceof Array) ? e[0] : e;
if(this.options.value==optionTag.value) optionTag.selected = true;
optionTag.appendChild(document.createTextNode((e instanceof Array) ? e[1] : e));
selectTag.appendChild(optionTag);
}.bind(this));
this.cached_selectTag = selectTag;
}
this.editField = this.cached_selectTag;
if(this.options.loadTextURL) this.loadExternalText();
this.form.appendChild(this.editField);
this.options.callback = function(form, value) {
return "value=" + encodeURIComponent(value);
}
}
});
// Delayed observer, like Form.Element.Observer,
// but waits for delay after last key input
// Ideal for live-search fields
Form.Element.DelayedObserver = Class.create();
Form.Element.DelayedObserver.prototype = {
initialize: function(element, delay, callback) {
this.delay = delay || 0.5;
this.element = $(element);
this.callback = callback;
this.timer = null;
this.lastValue = $F(this.element);
Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this));
},
delayedListener: function(event) {
if(this.lastValue == $F(this.element)) return;
if(this.timer) clearTimeout(this.timer);
this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000);
this.lastValue = $F(this.element);
},
onTimerEvent: function() {
this.timer = null;
this.callback(this.element, $F(this.element));
}
}; | zc.selenium | /zc.selenium-1.2.1.tar.gz/zc.selenium-1.2.1/src/zc/selenium/resources/lib/scriptaculous/controls.js | controls.js |
var Builder = {
NODEMAP: {
AREA: 'map',
CAPTION: 'table',
COL: 'table',
COLGROUP: 'table',
LEGEND: 'fieldset',
OPTGROUP: 'select',
OPTION: 'select',
PARAM: 'object',
TBODY: 'table',
TD: 'table',
TFOOT: 'table',
TH: 'table',
THEAD: 'table',
TR: 'table'
},
// note: For Firefox < 1.5, OPTION and OPTGROUP tags are currently broken,
// due to a Firefox bug
node: function(elementName) {
elementName = elementName.toUpperCase();
// try innerHTML approach
var parentTag = this.NODEMAP[elementName] || 'div';
var parentElement = document.createElement(parentTag);
try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707
parentElement.innerHTML = "<" + elementName + "></" + elementName + ">";
} catch(e) {}
var element = parentElement.firstChild || null;
// see if browser added wrapping tags
if(element && (element.tagName != elementName))
element = element.getElementsByTagName(elementName)[0];
// fallback to createElement approach
if(!element) element = document.createElement(elementName);
// abort if nothing could be created
if(!element) return;
// attributes (or text)
if(arguments[1])
if(this._isStringOrNumber(arguments[1]) ||
(arguments[1] instanceof Array)) {
this._children(element, arguments[1]);
} else {
var attrs = this._attributes(arguments[1]);
if(attrs.length) {
try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707
parentElement.innerHTML = "<" +elementName + " " +
attrs + "></" + elementName + ">";
} catch(e) {}
element = parentElement.firstChild || null;
// workaround firefox 1.0.X bug
if(!element) {
element = document.createElement(elementName);
for(attr in arguments[1])
element[attr == 'class' ? 'className' : attr] = arguments[1][attr];
}
if(element.tagName != elementName)
element = parentElement.getElementsByTagName(elementName)[0];
}
}
// text, or array of children
if(arguments[2])
this._children(element, arguments[2]);
return element;
},
_text: function(text) {
return document.createTextNode(text);
},
_attributes: function(attributes) {
var attrs = [];
for(attribute in attributes)
attrs.push((attribute=='className' ? 'class' : attribute) +
'="' + attributes[attribute].toString().escapeHTML() + '"');
return attrs.join(" ");
},
_children: function(element, children) {
if(typeof children=='object') { // array can hold nodes and text
children.flatten().each( function(e) {
if(typeof e=='object')
element.appendChild(e)
else
if(Builder._isStringOrNumber(e))
element.appendChild(Builder._text(e));
});
} else
if(Builder._isStringOrNumber(children))
element.appendChild(Builder._text(children));
},
_isStringOrNumber: function(param) {
return(typeof param=='string' || typeof param=='number');
}
} | zc.selenium | /zc.selenium-1.2.1.tar.gz/zc.selenium-1.2.1/src/zc/selenium/resources/lib/scriptaculous/builder.js | builder.js |
eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)d[e(c)]=k[c]||e(c);k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('7 x=6(){7 1D="2.0.2";7 C=/\\s*,\\s*/;7 x=6(s,A){33{7 m=[];7 u=1z.32.2c&&!A;7 b=(A)?(A.31==22)?A:[A]:[1g];7 1E=18(s).1l(C),i;9(i=0;i<1E.y;i++){s=1y(1E[i]);8(U&&s.Z(0,3).2b("")==" *#"){s=s.Z(2);A=24([],b,s[1])}1A A=b;7 j=0,t,f,a,c="";H(j<s.y){t=s[j++];f=s[j++];c+=t+f;a="";8(s[j]=="("){H(s[j++]!=")")a+=s[j];a=a.Z(0,-1);c+="("+a+")"}A=(u&&V[c])?V[c]:21(A,t,f,a);8(u)V[c]=A}m=m.30(A)}2a x.2d;5 m}2Z(e){x.2d=e;5[]}};x.1Z=6(){5"6 x() {\\n [1D "+1D+"]\\n}"};7 V={};x.2c=L;x.2Y=6(s){8(s){s=1y(s).2b("");2a V[s]}1A V={}};7 29={};7 19=L;x.15=6(n,s){8(19)1i("s="+1U(s));29[n]=12 s()};x.2X=6(c){5 c?1i(c):o};7 D={};7 h={};7 q={P:/\\[([\\w-]+(\\|[\\w-]+)?)\\s*(\\W?=)?\\s*([^\\]]*)\\]/};7 T=[];D[" "]=6(r,f,t,n){7 e,i,j;9(i=0;i<f.y;i++){7 s=X(f[i],t,n);9(j=0;(e=s[j]);j++){8(M(e)&&14(e,n))r.z(e)}}};D["#"]=6(r,f,i){7 e,j;9(j=0;(e=f[j]);j++)8(e.B==i)r.z(e)};D["."]=6(r,f,c){c=12 1t("(^|\\\\s)"+c+"(\\\\s|$)");7 e,i;9(i=0;(e=f[i]);i++)8(c.l(e.1V))r.z(e)};D[":"]=6(r,f,p,a){7 t=h[p],e,i;8(t)9(i=0;(e=f[i]);i++)8(t(e,a))r.z(e)};h["2W"]=6(e){7 d=Q(e);8(d.1C)9(7 i=0;i<d.1C.y;i++){8(d.1C[i]==e)5 K}};h["2V"]=6(e){};7 M=6(e){5(e&&e.1c==1&&e.1f!="!")?e:23};7 16=6(e){H(e&&(e=e.2U)&&!M(e))28;5 e};7 G=6(e){H(e&&(e=e.2T)&&!M(e))28;5 e};7 1r=6(e){5 M(e.27)||G(e.27)};7 1P=6(e){5 M(e.26)||16(e.26)};7 1o=6(e){7 c=[];e=1r(e);H(e){c.z(e);e=G(e)}5 c};7 U=K;7 1h=6(e){7 d=Q(e);5(2S d.25=="2R")?/\\.1J$/i.l(d.2Q):2P(d.25=="2O 2N")};7 Q=6(e){5 e.2M||e.1g};7 X=6(e,t){5(t=="*"&&e.1B)?e.1B:e.X(t)};7 17=6(e,t,n){8(t=="*")5 M(e);8(!14(e,n))5 L;8(!1h(e))t=t.2L();5 e.1f==t};7 14=6(e,n){5!n||(n=="*")||(e.2K==n)};7 1e=6(e){5 e.1G};6 24(r,f,B){7 m,i,j;9(i=0;i<f.y;i++){8(m=f[i].1B.2J(B)){8(m.B==B)r.z(m);1A 8(m.y!=23){9(j=0;j<m.y;j++){8(m[j].B==B)r.z(m[j])}}}}5 r};8(![].z)22.2I.z=6(){9(7 i=0;i<1z.y;i++){o[o.y]=1z[i]}5 o.y};7 N=/\\|/;6 21(A,t,f,a){8(N.l(f)){f=f.1l(N);a=f[0];f=f[1]}7 r=[];8(D[t]){D[t](r,A,f,a)}5 r};7 S=/^[^\\s>+~]/;7 20=/[\\s#.:>+~()@]|[^\\s#.:>+~()@]+/g;6 1y(s){8(S.l(s))s=" "+s;5 s.P(20)||[]};7 W=/\\s*([\\s>+~(),]|^|$)\\s*/g;7 I=/([\\s>+~,]|[^(]\\+|^)([#.:@])/g;7 18=6(s){5 s.O(W,"$1").O(I,"$1*$2")};7 1u={1Z:6(){5"\'"},P:/^(\'[^\']*\')|("[^"]*")$/,l:6(s){5 o.P.l(s)},1S:6(s){5 o.l(s)?s:o+s+o},1Y:6(s){5 o.l(s)?s.Z(1,-1):s}};7 1s=6(t){5 1u.1Y(t)};7 E=/([\\/()[\\]?{}|*+-])/g;6 R(s){5 s.O(E,"\\\\$1")};x.15("1j-2H",6(){D[">"]=6(r,f,t,n){7 e,i,j;9(i=0;i<f.y;i++){7 s=1o(f[i]);9(j=0;(e=s[j]);j++)8(17(e,t,n))r.z(e)}};D["+"]=6(r,f,t,n){9(7 i=0;i<f.y;i++){7 e=G(f[i]);8(e&&17(e,t,n))r.z(e)}};D["@"]=6(r,f,a){7 t=T[a].l;7 e,i;9(i=0;(e=f[i]);i++)8(t(e))r.z(e)};h["2G-10"]=6(e){5!16(e)};h["1x"]=6(e,c){c=12 1t("^"+c,"i");H(e&&!e.13("1x"))e=e.1n;5 e&&c.l(e.13("1x"))};q.1X=/\\\\:/g;q.1w="@";q.J={};q.O=6(m,a,n,c,v){7 k=o.1w+m;8(!T[k]){a=o.1W(a,c||"",v||"");T[k]=a;T.z(a)}5 T[k].B};q.1Q=6(s){s=s.O(o.1X,"|");7 m;H(m=s.P(o.P)){7 r=o.O(m[0],m[1],m[2],m[3],m[4]);s=s.O(o.P,r)}5 s};q.1W=6(p,t,v){7 a={};a.B=o.1w+T.y;a.2F=p;t=o.J[t];t=t?t(o.13(p),1s(v)):L;a.l=12 2E("e","5 "+t);5 a};q.13=6(n){1d(n.2D()){F"B":5"e.B";F"2C":5"e.1V";F"9":5"e.2B";F"1T":8(U){5"1U((e.2A.P(/1T=\\\\1v?([^\\\\s\\\\1v]*)\\\\1v?/)||[])[1]||\'\')"}}5"e.13(\'"+n.O(N,":")+"\')"};q.J[""]=6(a){5 a};q.J["="]=6(a,v){5 a+"=="+1u.1S(v)};q.J["~="]=6(a,v){5"/(^| )"+R(v)+"( |$)/.l("+a+")"};q.J["|="]=6(a,v){5"/^"+R(v)+"(-|$)/.l("+a+")"};7 1R=18;18=6(s){5 1R(q.1Q(s))}});x.15("1j-2z",6(){D["~"]=6(r,f,t,n){7 e,i;9(i=0;(e=f[i]);i++){H(e=G(e)){8(17(e,t,n))r.z(e)}}};h["2y"]=6(e,t){t=12 1t(R(1s(t)));5 t.l(1e(e))};h["2x"]=6(e){5 e==Q(e).1H};h["2w"]=6(e){7 n,i;9(i=0;(n=e.1F[i]);i++){8(M(n)||n.1c==3)5 L}5 K};h["1N-10"]=6(e){5!G(e)};h["2v-10"]=6(e){e=e.1n;5 1r(e)==1P(e)};h["2u"]=6(e,s){7 n=x(s,Q(e));9(7 i=0;i<n.y;i++){8(n[i]==e)5 L}5 K};h["1O-10"]=6(e,a){5 1p(e,a,16)};h["1O-1N-10"]=6(e,a){5 1p(e,a,G)};h["2t"]=6(e){5 e.B==2s.2r.Z(1)};h["1M"]=6(e){5 e.1M};h["2q"]=6(e){5 e.1q===L};h["1q"]=6(e){5 e.1q};h["1L"]=6(e){5 e.1L};q.J["^="]=6(a,v){5"/^"+R(v)+"/.l("+a+")"};q.J["$="]=6(a,v){5"/"+R(v)+"$/.l("+a+")"};q.J["*="]=6(a,v){5"/"+R(v)+"/.l("+a+")"};6 1p(e,a,t){1d(a){F"n":5 K;F"2p":a="2n";1a;F"2o":a="2n+1"}7 1m=1o(e.1n);6 1k(i){7 i=(t==G)?1m.y-i:i-1;5 1m[i]==e};8(!Y(a))5 1k(a);a=a.1l("n");7 m=1K(a[0]);7 s=1K(a[1]);8((Y(m)||m==1)&&s==0)5 K;8(m==0&&!Y(s))5 1k(s);8(Y(s))s=0;7 c=1;H(e=t(e))c++;8(Y(m)||m==1)5(t==G)?(c<=s):(s>=c);5(c%m)==s}});x.15("1j-2m",6(){U=1i("L;/*@2l@8(@\\2k)U=K@2j@*/");8(!U){X=6(e,t,n){5 n?e.2i("*",t):e.X(t)};14=6(e,n){5!n||(n=="*")||(e.2h==n)};1h=1g.1I?6(e){5/1J/i.l(Q(e).1I)}:6(e){5 Q(e).1H.1f!="2g"};1e=6(e){5 e.2f||e.1G||1b(e)};6 1b(e){7 t="",n,i;9(i=0;(n=e.1F[i]);i++){1d(n.1c){F 11:F 1:t+=1b(n);1a;F 3:t+=n.2e;1a}}5 t}}});19=K;5 x}();',62,190,'|||||return|function|var|if|for||||||||pseudoClasses||||test|||this||AttributeSelector|||||||cssQuery|length|push|fr|id||selectors||case|nextElementSibling|while||tests|true|false|thisElement||replace|match|getDocument|regEscape||attributeSelectors|isMSIE|cache||getElementsByTagName|isNaN|slice|child||new|getAttribute|compareNamespace|addModule|previousElementSibling|compareTagName|parseSelector|loaded|break|_0|nodeType|switch|getTextContent|tagName|document|isXML|eval|css|_1|split|ch|parentNode|childElements|nthChild|disabled|firstElementChild|getText|RegExp|Quote|x22|PREFIX|lang|_2|arguments|else|all|links|version|se|childNodes|innerText|documentElement|contentType|xml|parseInt|indeterminate|checked|last|nth|lastElementChild|parse|_3|add|href|String|className|create|NS_IE|remove|toString|ST|select|Array|null|_4|mimeType|lastChild|firstChild|continue|modules|delete|join|caching|error|nodeValue|textContent|HTML|prefix|getElementsByTagNameNS|end|x5fwin32|cc_on|standard||odd|even|enabled|hash|location|target|not|only|empty|root|contains|level3|outerHTML|htmlFor|class|toLowerCase|Function|name|first|level2|prototype|item|scopeName|toUpperCase|ownerDocument|Document|XML|Boolean|URL|unknown|typeof|nextSibling|previousSibling|visited|link|valueOf|clearCache|catch|concat|constructor|callee|try'.split('|'),0,{})) | zc.selenium | /zc.selenium-1.2.1.tar.gz/zc.selenium-1.2.1/src/zc/selenium/resources/lib/cssQuery/cssQuery-p.js | cssQuery-p.js |
var cssQuery = function() {
var version = "2.0.2";
// -----------------------------------------------------------------------
// main query function
// -----------------------------------------------------------------------
var $COMMA = /\s*,\s*/;
var cssQuery = function($selector, $$from) {
try {
var $match = [];
var $useCache = arguments.callee.caching && !$$from;
var $base = ($$from) ? ($$from.constructor == Array) ? $$from : [$$from] : [document];
// process comma separated selectors
var $$selectors = parseSelector($selector).split($COMMA), i;
for (i = 0; i < $$selectors.length; i++) {
// convert the selector to a stream
$selector = _toStream($$selectors[i]);
// faster chop if it starts with id (MSIE only)
if (isMSIE && $selector.slice(0, 3).join("") == " *#") {
$selector = $selector.slice(2);
$$from = _msie_selectById([], $base, $selector[1]);
} else $$from = $base;
// process the stream
var j = 0, $token, $filter, $arguments, $cacheSelector = "";
while (j < $selector.length) {
$token = $selector[j++];
$filter = $selector[j++];
$cacheSelector += $token + $filter;
// some pseudo-classes allow arguments to be passed
// e.g. nth-child(even)
$arguments = "";
if ($selector[j] == "(") {
while ($selector[j++] != ")" && j < $selector.length) {
$arguments += $selector[j];
}
$arguments = $arguments.slice(0, -1);
$cacheSelector += "(" + $arguments + ")";
}
// process a token/filter pair use cached results if possible
$$from = ($useCache && cache[$cacheSelector]) ?
cache[$cacheSelector] : select($$from, $token, $filter, $arguments);
if ($useCache) cache[$cacheSelector] = $$from;
}
$match = $match.concat($$from);
}
delete cssQuery.error;
return $match;
} catch ($error) {
cssQuery.error = $error;
return [];
}};
// -----------------------------------------------------------------------
// public interface
// -----------------------------------------------------------------------
cssQuery.toString = function() {
return "function cssQuery() {\n [version " + version + "]\n}";
};
// caching
var cache = {};
cssQuery.caching = false;
cssQuery.clearCache = function($selector) {
if ($selector) {
$selector = _toStream($selector).join("");
delete cache[$selector];
} else cache = {};
};
// allow extensions
var modules = {};
var loaded = false;
cssQuery.addModule = function($name, $script) {
if (loaded) eval("$script=" + String($script));
modules[$name] = new $script();;
};
// hackery
cssQuery.valueOf = function($code) {
return $code ? eval($code) : this;
};
// -----------------------------------------------------------------------
// declarations
// -----------------------------------------------------------------------
var selectors = {};
var pseudoClasses = {};
// a safari bug means that these have to be declared here
var AttributeSelector = {match: /\[([\w-]+(\|[\w-]+)?)\s*(\W?=)?\s*([^\]]*)\]/};
var attributeSelectors = [];
// -----------------------------------------------------------------------
// selectors
// -----------------------------------------------------------------------
// descendant selector
selectors[" "] = function($results, $from, $tagName, $namespace) {
// loop through current selection
var $element, i, j;
for (i = 0; i < $from.length; i++) {
// get descendants
var $subset = getElementsByTagName($from[i], $tagName, $namespace);
// loop through descendants and add to results selection
for (j = 0; ($element = $subset[j]); j++) {
if (thisElement($element) && compareNamespace($element, $namespace))
$results.push($element);
}
}
};
// ID selector
selectors["#"] = function($results, $from, $id) {
// loop through current selection and check ID
var $element, j;
for (j = 0; ($element = $from[j]); j++) if ($element.id == $id) $results.push($element);
};
// class selector
selectors["."] = function($results, $from, $className) {
// create a RegExp version of the class
$className = new RegExp("(^|\\s)" + $className + "(\\s|$)");
// loop through current selection and check class
var $element, i;
for (i = 0; ($element = $from[i]); i++)
if ($className.test($element.className)) $results.push($element);
};
// pseudo-class selector
selectors[":"] = function($results, $from, $pseudoClass, $arguments) {
// retrieve the cssQuery pseudo-class function
var $test = pseudoClasses[$pseudoClass], $element, i;
// loop through current selection and apply pseudo-class filter
if ($test) for (i = 0; ($element = $from[i]); i++)
// if the cssQuery pseudo-class function returns "true" add the element
if ($test($element, $arguments)) $results.push($element);
};
// -----------------------------------------------------------------------
// pseudo-classes
// -----------------------------------------------------------------------
pseudoClasses["link"] = function($element) {
var $document = getDocument($element);
if ($document.links) for (var i = 0; i < $document.links.length; i++) {
if ($document.links[i] == $element) return true;
}
};
pseudoClasses["visited"] = function($element) {
// can't do this without jiggery-pokery
};
// -----------------------------------------------------------------------
// DOM traversal
// -----------------------------------------------------------------------
// IE5/6 includes comments (LOL) in it's elements collections.
// so we have to check for this. the test is tagName != "!". LOL (again).
var thisElement = function($element) {
return ($element && $element.nodeType == 1 && $element.tagName != "!") ? $element : null;
};
// return the previous element to the supplied element
// previousSibling is not good enough as it might return a text or comment node
var previousElementSibling = function($element) {
while ($element && ($element = $element.previousSibling) && !thisElement($element)) continue;
return $element;
};
// return the next element to the supplied element
var nextElementSibling = function($element) {
while ($element && ($element = $element.nextSibling) && !thisElement($element)) continue;
return $element;
};
// return the first child ELEMENT of an element
// NOT the first child node (though they may be the same thing)
var firstElementChild = function($element) {
return thisElement($element.firstChild) || nextElementSibling($element.firstChild);
};
var lastElementChild = function($element) {
return thisElement($element.lastChild) || previousElementSibling($element.lastChild);
};
// return child elements of an element (not child nodes)
var childElements = function($element) {
var $childElements = [];
$element = firstElementChild($element);
while ($element) {
$childElements.push($element);
$element = nextElementSibling($element);
}
return $childElements;
};
// -----------------------------------------------------------------------
// browser compatibility
// -----------------------------------------------------------------------
// all of the functions in this section can be overwritten. the default
// configuration is for IE. The functions below reflect this. standard
// methods are included in a separate module. It would probably be better
// the other way round of course but this makes it easier to keep IE7 trim.
var isMSIE = true;
var isXML = function($element) {
var $document = getDocument($element);
return (typeof $document.mimeType == "unknown") ?
/\.xml$/i.test($document.URL) :
Boolean($document.mimeType == "XML Document");
};
// return the element's containing document
var getDocument = function($element) {
return $element.ownerDocument || $element.document;
};
var getElementsByTagName = function($element, $tagName) {
return ($tagName == "*" && $element.all) ? $element.all : $element.getElementsByTagName($tagName);
};
var compareTagName = function($element, $tagName, $namespace) {
if ($tagName == "*") return thisElement($element);
if (!compareNamespace($element, $namespace)) return false;
if (!isXML($element)) $tagName = $tagName.toUpperCase();
return $element.tagName == $tagName;
};
var compareNamespace = function($element, $namespace) {
return !$namespace || ($namespace == "*") || ($element.scopeName == $namespace);
};
var getTextContent = function($element) {
return $element.innerText;
};
function _msie_selectById($results, $from, id) {
var $match, i, j;
for (i = 0; i < $from.length; i++) {
if ($match = $from[i].all.item(id)) {
if ($match.id == id) $results.push($match);
else if ($match.length != null) {
for (j = 0; j < $match.length; j++) {
if ($match[j].id == id) $results.push($match[j]);
}
}
}
}
return $results;
};
// for IE5.0
if (![].push) Array.prototype.push = function() {
for (var i = 0; i < arguments.length; i++) {
this[this.length] = arguments[i];
}
return this.length;
};
// -----------------------------------------------------------------------
// query support
// -----------------------------------------------------------------------
// select a set of matching elements.
// "from" is an array of elements.
// "token" is a character representing the type of filter
// e.g. ">" means child selector
// "filter" represents the tag name, id or class name that is being selected
// the function returns an array of matching elements
var $NAMESPACE = /\|/;
function select($$from, $token, $filter, $arguments) {
if ($NAMESPACE.test($filter)) {
$filter = $filter.split($NAMESPACE);
$arguments = $filter[0];
$filter = $filter[1];
}
var $results = [];
if (selectors[$token]) {
selectors[$token]($results, $$from, $filter, $arguments);
}
return $results;
};
// -----------------------------------------------------------------------
// parsing
// -----------------------------------------------------------------------
// convert css selectors to a stream of tokens and filters
// it's not a real stream. it's just an array of strings.
var $STANDARD_SELECT = /^[^\s>+~]/;
var $$STREAM = /[\s#.:>+~()@]|[^\s#.:>+~()@]+/g;
function _toStream($selector) {
if ($STANDARD_SELECT.test($selector)) $selector = " " + $selector;
return $selector.match($$STREAM) || [];
};
var $WHITESPACE = /\s*([\s>+~(),]|^|$)\s*/g;
var $IMPLIED_ALL = /([\s>+~,]|[^(]\+|^)([#.:@])/g;
var parseSelector = function($selector) {
return $selector
// trim whitespace
.replace($WHITESPACE, "$1")
// e.g. ".class1" --> "*.class1"
.replace($IMPLIED_ALL, "$1*$2");
};
var Quote = {
toString: function() {return "'"},
match: /^('[^']*')|("[^"]*")$/,
test: function($string) {
return this.match.test($string);
},
add: function($string) {
return this.test($string) ? $string : this + $string + this;
},
remove: function($string) {
return this.test($string) ? $string.slice(1, -1) : $string;
}
};
var getText = function($text) {
return Quote.remove($text);
};
var $ESCAPE = /([\/()[\]?{}|*+-])/g;
function regEscape($string) {
return $string.replace($ESCAPE, "\\$1");
};
// -----------------------------------------------------------------------
// modules
// -----------------------------------------------------------------------
// -------- >> insert modules here for packaging << -------- \\
loaded = true;
// -----------------------------------------------------------------------
// return the query function
// -----------------------------------------------------------------------
return cssQuery;
}(); // cssQuery | zc.selenium | /zc.selenium-1.2.1.tar.gz/zc.selenium-1.2.1/src/zc/selenium/resources/lib/cssQuery/src/cssQuery.js | cssQuery.js |
cssQuery.addModule("css-level2", function() {
// -----------------------------------------------------------------------
// selectors
// -----------------------------------------------------------------------
// child selector
selectors[">"] = function($results, $from, $tagName, $namespace) {
var $element, i, j;
for (i = 0; i < $from.length; i++) {
var $subset = childElements($from[i]);
for (j = 0; ($element = $subset[j]); j++)
if (compareTagName($element, $tagName, $namespace))
$results.push($element);
}
};
// sibling selector
selectors["+"] = function($results, $from, $tagName, $namespace) {
for (var i = 0; i < $from.length; i++) {
var $element = nextElementSibling($from[i]);
if ($element && compareTagName($element, $tagName, $namespace))
$results.push($element);
}
};
// attribute selector
selectors["@"] = function($results, $from, $attributeSelectorID) {
var $test = attributeSelectors[$attributeSelectorID].test;
var $element, i;
for (i = 0; ($element = $from[i]); i++)
if ($test($element)) $results.push($element);
};
// -----------------------------------------------------------------------
// pseudo-classes
// -----------------------------------------------------------------------
pseudoClasses["first-child"] = function($element) {
return !previousElementSibling($element);
};
pseudoClasses["lang"] = function($element, $code) {
$code = new RegExp("^" + $code, "i");
while ($element && !$element.getAttribute("lang")) $element = $element.parentNode;
return $element && $code.test($element.getAttribute("lang"));
};
// -----------------------------------------------------------------------
// attribute selectors
// -----------------------------------------------------------------------
// constants
AttributeSelector.NS_IE = /\\:/g;
AttributeSelector.PREFIX = "@";
// properties
AttributeSelector.tests = {};
// methods
AttributeSelector.replace = function($match, $attribute, $namespace, $compare, $value) {
var $key = this.PREFIX + $match;
if (!attributeSelectors[$key]) {
$attribute = this.create($attribute, $compare || "", $value || "");
// store the selector
attributeSelectors[$key] = $attribute;
attributeSelectors.push($attribute);
}
return attributeSelectors[$key].id;
};
AttributeSelector.parse = function($selector) {
$selector = $selector.replace(this.NS_IE, "|");
var $match;
while ($match = $selector.match(this.match)) {
var $replace = this.replace($match[0], $match[1], $match[2], $match[3], $match[4]);
$selector = $selector.replace(this.match, $replace);
}
return $selector;
};
AttributeSelector.create = function($propertyName, $test, $value) {
var $attributeSelector = {};
$attributeSelector.id = this.PREFIX + attributeSelectors.length;
$attributeSelector.name = $propertyName;
$test = this.tests[$test];
$test = $test ? $test(this.getAttribute($propertyName), getText($value)) : false;
$attributeSelector.test = new Function("e", "return " + $test);
return $attributeSelector;
};
AttributeSelector.getAttribute = function($name) {
switch ($name.toLowerCase()) {
case "id":
return "e.id";
case "class":
return "e.className";
case "for":
return "e.htmlFor";
case "href":
if (isMSIE) {
// IE always returns the full path not the fragment in the href attribute
// so we RegExp it out of outerHTML. Opera does the same thing but there
// is no way to get the original attribute.
return "String((e.outerHTML.match(/href=\\x22?([^\\s\\x22]*)\\x22?/)||[])[1]||'')";
}
}
return "e.getAttribute('" + $name.replace($NAMESPACE, ":") + "')";
};
// -----------------------------------------------------------------------
// attribute selector tests
// -----------------------------------------------------------------------
AttributeSelector.tests[""] = function($attribute) {
return $attribute;
};
AttributeSelector.tests["="] = function($attribute, $value) {
return $attribute + "==" + Quote.add($value);
};
AttributeSelector.tests["~="] = function($attribute, $value) {
return "/(^| )" + regEscape($value) + "( |$)/.test(" + $attribute + ")";
};
AttributeSelector.tests["|="] = function($attribute, $value) {
return "/^" + regEscape($value) + "(-|$)/.test(" + $attribute + ")";
};
// -----------------------------------------------------------------------
// parsing
// -----------------------------------------------------------------------
// override parseSelector to parse out attribute selectors
var _parseSelector = parseSelector;
parseSelector = function($selector) {
return _parseSelector(AttributeSelector.parse($selector));
};
}); // addModule | zc.selenium | /zc.selenium-1.2.1.tar.gz/zc.selenium-1.2.1/src/zc/selenium/resources/lib/cssQuery/src/cssQuery-level2.js | cssQuery-level2.js |
cssQuery.addModule("css-level3", function() {
// -----------------------------------------------------------------------
// selectors
// -----------------------------------------------------------------------
// indirect sibling selector
selectors["~"] = function($results, $from, $tagName, $namespace) {
var $element, i;
for (i = 0; ($element = $from[i]); i++) {
while ($element = nextElementSibling($element)) {
if (compareTagName($element, $tagName, $namespace))
$results.push($element);
}
}
};
// -----------------------------------------------------------------------
// pseudo-classes
// -----------------------------------------------------------------------
// I'm hoping these pseudo-classes are pretty readable. Let me know if
// any need explanation.
pseudoClasses["contains"] = function($element, $text) {
$text = new RegExp(regEscape(getText($text)));
return $text.test(getTextContent($element));
};
pseudoClasses["root"] = function($element) {
return $element == getDocument($element).documentElement;
};
pseudoClasses["empty"] = function($element) {
var $node, i;
for (i = 0; ($node = $element.childNodes[i]); i++) {
if (thisElement($node) || $node.nodeType == 3) return false;
}
return true;
};
pseudoClasses["last-child"] = function($element) {
return !nextElementSibling($element);
};
pseudoClasses["only-child"] = function($element) {
$element = $element.parentNode;
return firstElementChild($element) == lastElementChild($element);
};
pseudoClasses["not"] = function($element, $selector) {
var $negated = cssQuery($selector, getDocument($element));
for (var i = 0; i < $negated.length; i++) {
if ($negated[i] == $element) return false;
}
return true;
};
pseudoClasses["nth-child"] = function($element, $arguments) {
return nthChild($element, $arguments, previousElementSibling);
};
pseudoClasses["nth-last-child"] = function($element, $arguments) {
return nthChild($element, $arguments, nextElementSibling);
};
pseudoClasses["target"] = function($element) {
return $element.id == location.hash.slice(1);
};
// UI element states
pseudoClasses["checked"] = function($element) {
return $element.checked;
};
pseudoClasses["enabled"] = function($element) {
return $element.disabled === false;
};
pseudoClasses["disabled"] = function($element) {
return $element.disabled;
};
pseudoClasses["indeterminate"] = function($element) {
return $element.indeterminate;
};
// -----------------------------------------------------------------------
// attribute selector tests
// -----------------------------------------------------------------------
AttributeSelector.tests["^="] = function($attribute, $value) {
return "/^" + regEscape($value) + "/.test(" + $attribute + ")";
};
AttributeSelector.tests["$="] = function($attribute, $value) {
return "/" + regEscape($value) + "$/.test(" + $attribute + ")";
};
AttributeSelector.tests["*="] = function($attribute, $value) {
return "/" + regEscape($value) + "/.test(" + $attribute + ")";
};
// -----------------------------------------------------------------------
// nth child support (Bill Edney)
// -----------------------------------------------------------------------
function nthChild($element, $arguments, $traverse) {
switch ($arguments) {
case "n": return true;
case "even": $arguments = "2n"; break;
case "odd": $arguments = "2n+1";
}
var $$children = childElements($element.parentNode);
function _checkIndex($index) {
var $index = ($traverse == nextElementSibling) ? $$children.length - $index : $index - 1;
return $$children[$index] == $element;
};
// it was just a number (no "n")
if (!isNaN($arguments)) return _checkIndex($arguments);
$arguments = $arguments.split("n");
var $multiplier = parseInt($arguments[0]);
var $step = parseInt($arguments[1]);
if ((isNaN($multiplier) || $multiplier == 1) && $step == 0) return true;
if ($multiplier == 0 && !isNaN($step)) return _checkIndex($step);
if (isNaN($step)) $step = 0;
var $count = 1;
while ($element = $traverse($element)) $count++;
if (isNaN($multiplier) || $multiplier == 1)
return ($traverse == nextElementSibling) ? ($count <= $step) : ($step >= $count);
return ($count % $multiplier) == $step;
};
}); // addModule | zc.selenium | /zc.selenium-1.2.1.tar.gz/zc.selenium-1.2.1/src/zc/selenium/resources/lib/cssQuery/src/cssQuery-level3.js | cssQuery-level3.js |
// NOTE: The split() method in IE omits empty result strings. This is
// utterly annoying. So we don't use it here.
// Resolve entities in XML text fragments. According to the DOM
// specification, the DOM is supposed to resolve entity references at
// the API level. I.e. no entity references are passed through the
// API. See "Entities and the DOM core", p.12, DOM 2 Core
// Spec. However, different browsers actually pass very different
// values at the API.
//
function xmlResolveEntities(s) {
var parts = stringSplit(s, '&');
var ret = parts[0];
for (var i = 1; i < parts.length; ++i) {
var rp = stringSplit(parts[i], ';');
if (rp.length == 1) {
// no entity reference: just a & but no ;
ret += parts[i];
continue;
}
var ch;
switch (rp[0]) {
case 'lt':
ch = '<';
break;
case 'gt':
ch = '>';
break;
case 'amp':
ch = '&';
break;
case 'quot':
ch = '"';
break;
case 'apos':
ch = '\'';
break;
case 'nbsp':
ch = String.fromCharCode(160);
break;
default:
// Cool trick: let the DOM do the entity decoding. We assign
// the entity text through non-W3C DOM properties and read it
// through the W3C DOM. W3C DOM access is specified to resolve
// entities.
var span = window.document.createElement('span');
span.innerHTML = '&' + rp[0] + '; ';
ch = span.childNodes[0].nodeValue.charAt(0);
}
ret += ch + rp[1];
}
return ret;
}
// Parses the given XML string with our custom, JavaScript XML parser. Written
// by Steffen Meschkat ([email protected]).
function xmlParse(xml) {
Timer.start('xmlparse');
var regex_empty = /\/$/;
// See also <http://www.w3.org/TR/REC-xml/#sec-common-syn> for
// allowed chars in a tag and attribute name. TODO(mesch): the
// following is still not completely correct.
var regex_tagname = /^([\w:-]*)/;
var regex_attribute = /([\w:-]+)\s?=\s?('([^\']*)'|"([^\"]*)")/g;
var xmldoc = new XDocument();
var root = xmldoc;
// For the record: in Safari, we would create native DOM nodes, but
// in Opera that is not possible, because the DOM only allows HTML
// element nodes to be created, so we have to do our own DOM nodes.
// xmldoc = document.implementation.createDocument('','',null);
// root = xmldoc; // .createDocumentFragment();
// NOTE(mesch): using the DocumentFragment instead of the Document
// crashes my Safari 1.2.4 (v125.12).
var stack = [];
var parent = root;
stack.push(parent);
var x = stringSplit(xml, '<');
for (var i = 1; i < x.length; ++i) {
var xx = stringSplit(x[i], '>');
var tag = xx[0];
var text = xmlResolveEntities(xx[1] || '');
if (tag.charAt(0) == '/') {
stack.pop();
parent = stack[stack.length-1];
} else if (tag.charAt(0) == '?') {
// Ignore XML declaration and processing instructions
} else if (tag.charAt(0) == '!') {
// Ignore notation and comments
} else {
var empty = tag.match(regex_empty);
var tagname = regex_tagname.exec(tag)[1];
var node = xmldoc.createElement(tagname);
var att;
while (att = regex_attribute.exec(tag)) {
var val = xmlResolveEntities(att[3] || att[4] || '');
node.setAttribute(att[1], val);
}
if (empty) {
parent.appendChild(node);
} else {
parent.appendChild(node);
parent = node;
stack.push(node);
}
}
if (text && parent != root) {
parent.appendChild(xmldoc.createTextNode(text));
}
}
Timer.end('xmlparse');
return root;
}
// Our W3C DOM Node implementation. Note we call it XNode because we
// can't define the identifier Node. We do this mostly for Opera,
// where we can't reuse the HTML DOM for parsing our own XML, and for
// Safari, where it is too expensive to have the template processor
// operate on native DOM nodes.
function XNode(type, name, value, owner) {
this.attributes = [];
this.childNodes = [];
XNode.init.call(this, type, name, value, owner);
}
// Don't call as method, use apply() or call().
XNode.init = function(type, name, value, owner) {
this.nodeType = type - 0;
this.nodeName = '' + name;
this.nodeValue = '' + value;
this.ownerDocument = owner;
this.firstChild = null;
this.lastChild = null;
this.nextSibling = null;
this.previousSibling = null;
this.parentNode = null;
}
XNode.unused_ = [];
XNode.recycle = function(node) {
if (!node) {
return;
}
if (node.constructor == XDocument) {
XNode.recycle(node.documentElement);
return;
}
if (node.constructor != this) {
return;
}
XNode.unused_.push(node);
for (var a = 0; a < node.attributes.length; ++a) {
XNode.recycle(node.attributes[a]);
}
for (var c = 0; c < node.childNodes.length; ++c) {
XNode.recycle(node.childNodes[c]);
}
node.attributes.length = 0;
node.childNodes.length = 0;
XNode.init.call(node, 0, '', '', null);
}
XNode.create = function(type, name, value, owner) {
if (XNode.unused_.length > 0) {
var node = XNode.unused_.pop();
XNode.init.call(node, type, name, value, owner);
return node;
} else {
return new XNode(type, name, value, owner);
}
}
XNode.prototype.appendChild = function(node) {
// firstChild
if (this.childNodes.length == 0) {
this.firstChild = node;
}
// previousSibling
node.previousSibling = this.lastChild;
// nextSibling
node.nextSibling = null;
if (this.lastChild) {
this.lastChild.nextSibling = node;
}
// parentNode
node.parentNode = this;
// lastChild
this.lastChild = node;
// childNodes
this.childNodes.push(node);
}
XNode.prototype.replaceChild = function(newNode, oldNode) {
if (oldNode == newNode) {
return;
}
for (var i = 0; i < this.childNodes.length; ++i) {
if (this.childNodes[i] == oldNode) {
this.childNodes[i] = newNode;
var p = oldNode.parentNode;
oldNode.parentNode = null;
newNode.parentNode = p;
p = oldNode.previousSibling;
oldNode.previousSibling = null;
newNode.previousSibling = p;
if (newNode.previousSibling) {
newNode.previousSibling.nextSibling = newNode;
}
p = oldNode.nextSibling;
oldNode.nextSibling = null;
newNode.nextSibling = p;
if (newNode.nextSibling) {
newNode.nextSibling.previousSibling = newNode;
}
if (this.firstChild == oldNode) {
this.firstChild = newNode;
}
if (this.lastChild == oldNode) {
this.lastChild = newNode;
}
break;
}
}
}
XNode.prototype.insertBefore = function(newNode, oldNode) {
if (oldNode == newNode) {
return;
}
if (oldNode.parentNode != this) {
return;
}
if (newNode.parentNode) {
newNode.parentNode.removeChild(newNode);
}
var newChildren = [];
for (var i = 0; i < this.childNodes.length; ++i) {
var c = this.childNodes[i];
if (c == oldNode) {
newChildren.push(newNode);
newNode.parentNode = this;
newNode.previousSibling = oldNode.previousSibling;
oldNode.previousSibling = newNode;
if (newNode.previousSibling) {
newNode.previousSibling.nextSibling = newNode;
}
newNode.nextSibling = oldNode;
if (this.firstChild == oldNode) {
this.firstChild = newNode;
}
}
newChildren.push(c);
}
this.childNodes = newChildren;
}
XNode.prototype.removeChild = function(node) {
var newChildren = [];
for (var i = 0; i < this.childNodes.length; ++i) {
var c = this.childNodes[i];
if (c != node) {
newChildren.push(c);
} else {
if (c.previousSibling) {
c.previousSibling.nextSibling = c.nextSibling;
}
if (c.nextSibling) {
c.nextSibling.previousSibling = c.previousSibling;
}
if (this.firstChild == c) {
this.firstChild = c.nextSibling;
}
if (this.lastChild == c) {
this.lastChild = c.previousSibling;
}
}
}
this.childNodes = newChildren;
}
XNode.prototype.hasAttributes = function() {
return this.attributes.length > 0;
}
XNode.prototype.setAttribute = function(name, value) {
for (var i = 0; i < this.attributes.length; ++i) {
if (this.attributes[i].nodeName == name) {
this.attributes[i].nodeValue = '' + value;
return;
}
}
this.attributes.push(new XNode(DOM_ATTRIBUTE_NODE, name, value));
}
XNode.prototype.getAttribute = function(name) {
for (var i = 0; i < this.attributes.length; ++i) {
if (this.attributes[i].nodeName == name) {
return this.attributes[i].nodeValue;
}
}
return null;
}
XNode.prototype.removeAttribute = function(name) {
var a = [];
for (var i = 0; i < this.attributes.length; ++i) {
if (this.attributes[i].nodeName != name) {
a.push(this.attributes[i]);
}
}
this.attributes = a;
}
function XDocument() {
XNode.call(this, DOM_DOCUMENT_NODE, '#document', null, this);
this.documentElement = null;
}
XDocument.prototype = new XNode(DOM_DOCUMENT_NODE, '#document');
XDocument.prototype.clear = function() {
XNode.recycle(this.documentElement);
this.documentElement = null;
}
XDocument.prototype.appendChild = function(node) {
XNode.prototype.appendChild.call(this, node);
this.documentElement = this.childNodes[0];
}
XDocument.prototype.createElement = function(name) {
return XNode.create(DOM_ELEMENT_NODE, name, null, this);
}
XDocument.prototype.createDocumentFragment = function() {
return XNode.create(DOM_DOCUMENT_FRAGMENT_NODE, '#document-fragment',
null, this);
}
XDocument.prototype.createTextNode = function(value) {
return XNode.create(DOM_TEXT_NODE, '#text', value, this);
}
XDocument.prototype.createAttribute = function(name) {
return XNode.create(DOM_ATTRIBUTE_NODE, name, null, this);
}
XDocument.prototype.createComment = function(data) {
return XNode.create(DOM_COMMENT_NODE, '#comment', data, this);
}
XNode.prototype.getElementsByTagName = function(name, list) {
if (!list) {
list = [];
}
if (this.nodeName == name) {
list.push(this);
}
for (var i = 0; i < this.childNodes.length; ++i) {
this.childNodes[i].getElementsByTagName(name, list);
}
return list;
} | zc.selenium | /zc.selenium-1.2.1.tar.gz/zc.selenium-1.2.1/src/zc/selenium/resources/xpath/dom.js | dom.js |
function el(i) {
return document.getElementById(i);
}
function px(x) {
return x + 'px';
}
// Split a string s at all occurrences of character c. This is like
// the split() method of the string object, but IE omits empty
// strings, which violates the invariant (s.split(x).join(x) == s).
function stringSplit(s, c) {
var a = s.indexOf(c);
if (a == -1) {
return [ s ];
}
var parts = [];
parts.push(s.substr(0,a));
while (a != -1) {
var a1 = s.indexOf(c, a + 1);
if (a1 != -1) {
parts.push(s.substr(a + 1, a1 - a - 1));
} else {
parts.push(s.substr(a + 1));
}
a = a1;
}
return parts;
}
// Returns the text value if a node; for nodes without children this
// is the nodeValue, for nodes with children this is the concatenation
// of the value of all children.
function xmlValue(node) {
if (!node) {
return '';
}
var ret = '';
if (node.nodeType == DOM_TEXT_NODE ||
node.nodeType == DOM_CDATA_SECTION_NODE ||
node.nodeType == DOM_ATTRIBUTE_NODE) {
ret += node.nodeValue;
} else if (node.nodeType == DOM_ELEMENT_NODE ||
node.nodeType == DOM_DOCUMENT_NODE ||
node.nodeType == DOM_DOCUMENT_FRAGMENT_NODE) {
for (var i = 0; i < node.childNodes.length; ++i) {
ret += arguments.callee(node.childNodes[i]);
}
}
return ret;
}
// Returns the representation of a node as XML text.
function xmlText(node) {
var ret = '';
if (node.nodeType == DOM_TEXT_NODE) {
ret += xmlEscapeText(node.nodeValue);
} else if (node.nodeType == DOM_ELEMENT_NODE) {
ret += '<' + node.nodeName;
for (var i = 0; i < node.attributes.length; ++i) {
var a = node.attributes[i];
if (a && a.nodeName && a.nodeValue) {
ret += ' ' + a.nodeName;
ret += '="' + xmlEscapeAttr(a.nodeValue) + '"';
}
}
if (node.childNodes.length == 0) {
ret += '/>';
} else {
ret += '>';
for (var i = 0; i < node.childNodes.length; ++i) {
ret += arguments.callee(node.childNodes[i]);
}
ret += '</' + node.nodeName + '>';
}
} else if (node.nodeType == DOM_DOCUMENT_NODE ||
node.nodeType == DOM_DOCUMENT_FRAGMENT_NODE) {
for (var i = 0; i < node.childNodes.length; ++i) {
ret += arguments.callee(node.childNodes[i]);
}
}
return ret;
}
// Applies the given function to each element of the array.
function mapExec(array, func) {
for (var i = 0; i < array.length; ++i) {
func(array[i]);
}
}
// Returns an array that contains the return value of the given
// function applied to every element of the input array.
function mapExpr(array, func) {
var ret = [];
for (var i = 0; i < array.length; ++i) {
ret.push(func(array[i]));
}
return ret;
};
// Reverses the given array in place.
function reverseInplace(array) {
for (var i = 0; i < array.length / 2; ++i) {
var h = array[i];
var ii = array.length - i - 1;
array[i] = array[ii];
array[ii] = h;
}
}
// Shallow-copies an array.
function copyArray(dst, src) {
for (var i = 0; i < src.length; ++i) {
dst.push(src[i]);
}
}
function assert(b) {
if (!b) {
throw 'assertion failed';
}
}
// Based on
// <http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247>
var DOM_ELEMENT_NODE = 1;
var DOM_ATTRIBUTE_NODE = 2;
var DOM_TEXT_NODE = 3;
var DOM_CDATA_SECTION_NODE = 4;
var DOM_ENTITY_REFERENCE_NODE = 5;
var DOM_ENTITY_NODE = 6;
var DOM_PROCESSING_INSTRUCTION_NODE = 7;
var DOM_COMMENT_NODE = 8;
var DOM_DOCUMENT_NODE = 9;
var DOM_DOCUMENT_TYPE_NODE = 10;
var DOM_DOCUMENT_FRAGMENT_NODE = 11;
var DOM_NOTATION_NODE = 12;
var xpathdebug = false; // trace xpath parsing
var xsltdebug = false; // trace xslt processing
// Escape XML special markup chracters: tag delimiter < > and entity
// reference start delimiter &. The escaped string can be used in XML
// text portions (i.e. between tags).
function xmlEscapeText(s) {
return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
}
// Escape XML special markup characters: tag delimiter < > entity
// reference start delimiter & and quotes ". The escaped string can be
// used in double quoted XML attribute value portions (i.e. in
// attributes within start tags).
function xmlEscapeAttr(s) {
return xmlEscapeText(s).replace(/\"/g, '"');
}
// Escape markup in XML text, but don't touch entity references. The
// escaped string can be used as XML text (i.e. between tags).
function xmlEscapeTags(s) {
return s.replace(/</g, '<').replace(/>/g, '>');
}
// An implementation of the debug log.
var logging__ = false;
function Log() {};
Log.lines = [];
Log.write = function(s) {
LOG.debug("xpath logging: " + s);
};
// Writes the given XML with every tag on a new line.
Log.writeXML = function(xml) {
if (logging__) {
var s0 = xml.replace(/</g, '\n<');
var s1 = xmlEscapeText(s0);
var s2 = s1.replace(/\s*\n(\s|\n)*/g, '<br/>');
this.lines.push(s2);
this.show();
}
}
// Writes without any escaping
Log.writeRaw = function(s) {
if (logging__) {
this.lines.push(s);
this.show();
}
}
Log.clear = function() {
if (logging__) {
var l = this.div();
l.innerHTML = '';
this.lines = [];
}
}
Log.show = function() {
var l = this.div();
l.innerHTML += this.lines.join('<br/>') + '<br/>';
this.lines = [];
l.scrollTop = l.scrollHeight;
}
Log.div = function() {
var l = document.getElementById('log');
if (!l) {
l = document.createElement('div');
l.id = 'log';
l.style.position = 'absolute';
l.style.right = '5px';
l.style.top = '5px';
l.style.width = '250px';
l.style.height = '150px';
l.style.overflow = 'auto';
l.style.backgroundColor = '#f0f0f0';
l.style.border = '1px solid gray';
l.style.fontSize = '10px';
l.style.padding = '5px';
document.body.appendChild(l);
}
return l;
}
function Timer() {}
Timer.start = function() {}
Timer.end = function() {} | zc.selenium | /zc.selenium-1.2.1.tar.gz/zc.selenium-1.2.1/src/zc/selenium/resources/xpath/misc.js | misc.js |
// The entry point for the parser.
//
// @param expr a string that contains an XPath expression.
// @return an expression object that can be evaluated with an
// expression context.
function xpathParse(expr) {
//xpathdebug = true;
if (xpathdebug) {
Log.write('XPath parse ' + expr);
}
xpathParseInit();
var cached = xpathCacheLookup(expr);
if (cached) {
if (xpathdebug) {
Log.write(' ... cached');
}
return cached;
}
// Optimize for a few common cases: simple attribute node tests
// (@id), simple element node tests (page), variable references
// ($address), numbers (4), multi-step path expressions where each
// step is a plain element node test
// (page/overlay/locations/location).
if (expr.match(/^(\$|@)?\w+$/i)) {
var ret = makeSimpleExpr(expr);
xpathParseCache[expr] = ret;
if (xpathdebug) {
Log.write(' ... simple');
}
return ret;
}
if (expr.match(/^\w+(\/\w+)*$/i)) {
var ret = makeSimpleExpr2(expr);
xpathParseCache[expr] = ret;
if (xpathdebug) {
Log.write(' ... simple 2');
}
return ret;
}
var cachekey = expr; // expr is modified during parse
if (xpathdebug) {
Timer.start('XPath parse', cachekey);
}
var stack = [];
var ahead = null;
var previous = null;
var done = false;
var parse_count = 0;
var lexer_count = 0;
var reduce_count = 0;
while (!done) {
parse_count++;
expr = expr.replace(/^\s*/, '');
previous = ahead;
ahead = null;
var rule = null;
var match = '';
for (var i = 0; i < xpathTokenRules.length; ++i) {
var result = xpathTokenRules[i].re.exec(expr);
lexer_count++;
if (result && result.length > 0 && result[0].length > match.length) {
rule = xpathTokenRules[i];
match = result[0];
break;
}
}
// Special case: allow operator keywords to be element and
// variable names.
// NOTE(mesch): The parser resolves conflicts by looking ahead,
// and this is the only case where we look back to
// disambiguate. So this is indeed something different, and
// looking back is usually done in the lexer (via states in the
// general case, called "start conditions" in flex(1)). Also,the
// conflict resolution in the parser is not as robust as it could
// be, so I'd like to keep as much off the parser as possible (all
// these precedence values should be computed from the grammar
// rules and possibly associativity declarations, as in bison(1),
// and not explicitly set.
if (rule &&
(rule == TOK_DIV ||
rule == TOK_MOD ||
rule == TOK_AND ||
rule == TOK_OR) &&
(!previous ||
previous.tag == TOK_AT ||
previous.tag == TOK_DSLASH ||
previous.tag == TOK_SLASH ||
previous.tag == TOK_AXIS ||
previous.tag == TOK_DOLLAR)) {
rule = TOK_QNAME;
}
if (rule) {
expr = expr.substr(match.length);
if (xpathdebug) {
Log.write('token: ' + match + ' -- ' + rule.label);
}
ahead = {
tag: rule,
match: match,
prec: rule.prec ? rule.prec : 0, // || 0 is removed by the compiler
expr: makeTokenExpr(match)
};
} else {
if (xpathdebug) {
Log.write('DONE');
}
done = true;
}
while (xpathReduce(stack, ahead)) {
reduce_count++;
if (xpathdebug) {
Log.write('stack: ' + stackToString(stack));
}
}
}
if (xpathdebug) {
Log.write(stackToString(stack));
}
// DGF any valid XPath should "reduce" to a single Expr token
if (stack.length != 1) {
throw 'XPath parse error ' + cachekey + ':\n' + stackToString(stack);
}
var result = stack[0].expr;
xpathParseCache[cachekey] = result;
if (xpathdebug) {
Timer.end('XPath parse', cachekey);
}
if (xpathdebug) {
Log.write('XPath parse: ' + parse_count + ' / ' +
lexer_count + ' / ' + reduce_count);
}
return result;
}
var xpathParseCache = {};
function xpathCacheLookup(expr) {
return xpathParseCache[expr];
}
/*DGF xpathReduce is where the magic happens in this parser.
Skim down to the bottom of this file to find the table of
grammatical rules and precedence numbers, "The productions of the grammar".
The idea here
is that we want to take a stack of tokens and apply
grammatical rules to them, "reducing" them to higher-level
tokens. Ultimately, any valid XPath should reduce to exactly one
"Expr" token.
Reduce too early or too late and you'll have two tokens that can't reduce
to single Expr. For example, you may hastily reduce a qname that
should name a function, incorrectly treating it as a tag name.
Or you may reduce too late, accidentally reducing the last part of the
XPath into a top-level "Expr" that won't reduce with earlier parts of
the XPath.
A "cand" is a grammatical rule candidate, with a given precedence
number. "ahead" is the upcoming token, which also has a precedence
number. If the token has a higher precedence number than
the rule candidate, we'll "shift" the token onto the token stack,
instead of immediately applying the rule candidate.
Some tokens have left associativity, in which case we shift when they
have LOWER precedence than the candidate.
*/
function xpathReduce(stack, ahead) {
var cand = null;
if (stack.length > 0) {
var top = stack[stack.length-1];
var ruleset = xpathRules[top.tag.key];
if (ruleset) {
for (var i = 0; i < ruleset.length; ++i) {
var rule = ruleset[i];
var match = xpathMatchStack(stack, rule[1]);
if (match.length) {
cand = {
tag: rule[0],
rule: rule,
match: match
};
cand.prec = xpathGrammarPrecedence(cand);
break;
}
}
}
}
var ret;
if (cand && (!ahead || cand.prec > ahead.prec ||
(ahead.tag.left && cand.prec >= ahead.prec))) {
for (var i = 0; i < cand.match.matchlength; ++i) {
stack.pop();
}
if (xpathdebug) {
Log.write('reduce ' + cand.tag.label + ' ' + cand.prec +
' ahead ' + (ahead ? ahead.tag.label + ' ' + ahead.prec +
(ahead.tag.left ? ' left' : '')
: ' none '));
}
var matchexpr = mapExpr(cand.match, function(m) { return m.expr; });
if (xpathdebug) {
Log.write('about to run ' + cand.rule[3].toString());
}
cand.expr = cand.rule[3].apply(null, matchexpr);
stack.push(cand);
ret = true;
} else {
if (ahead) {
if (xpathdebug) {
Log.write('shift ' + ahead.tag.label + ' ' + ahead.prec +
(ahead.tag.left ? ' left' : '') +
' over ' + (cand ? cand.tag.label + ' ' +
cand.prec : ' none'));
}
stack.push(ahead);
}
ret = false;
}
return ret;
}
function xpathMatchStack(stack, pattern) {
// NOTE(mesch): The stack matches for variable cardinality are
// greedy but don't do backtracking. This would be an issue only
// with rules of the form A* A, i.e. with an element with variable
// cardinality followed by the same element. Since that doesn't
// occur in the grammar at hand, all matches on the stack are
// unambiguous.
var S = stack.length;
var P = pattern.length;
var p, s;
var match = [];
match.matchlength = 0;
var ds = 0;
for (p = P - 1, s = S - 1; p >= 0 && s >= 0; --p, s -= ds) {
ds = 0;
var qmatch = [];
if (pattern[p] == Q_MM) {
p -= 1;
match.push(qmatch);
while (s - ds >= 0 && stack[s - ds].tag == pattern[p]) {
qmatch.push(stack[s - ds]);
ds += 1;
match.matchlength += 1;
}
} else if (pattern[p] == Q_01) {
p -= 1;
match.push(qmatch);
while (s - ds >= 0 && ds < 2 && stack[s - ds].tag == pattern[p]) {
qmatch.push(stack[s - ds]);
ds += 1;
match.matchlength += 1;
}
} else if (pattern[p] == Q_1M) {
p -= 1;
match.push(qmatch);
if (stack[s].tag == pattern[p]) {
while (s - ds >= 0 && stack[s - ds].tag == pattern[p]) {
qmatch.push(stack[s - ds]);
ds += 1;
match.matchlength += 1;
}
} else {
return [];
}
} else if (stack[s].tag == pattern[p]) {
match.push(stack[s]);
ds += 1;
match.matchlength += 1;
} else {
return [];
}
reverseInplace(qmatch);
qmatch.expr = mapExpr(qmatch, function(m) { return m.expr; });
}
reverseInplace(match);
if (p == -1) {
return match;
} else {
return [];
}
}
function xpathTokenPrecedence(tag) {
return tag.prec || 2;
}
function xpathGrammarPrecedence(frame) {
var ret = 0;
if (frame.rule) { /* normal reduce */
if (frame.rule.length >= 3 && frame.rule[2] >= 0) {
ret = frame.rule[2];
} else {
for (var i = 0; i < frame.rule[1].length; ++i) {
var p = xpathTokenPrecedence(frame.rule[1][i]);
ret = Math.max(ret, p);
}
}
} else if (frame.tag) { /* TOKEN match */
ret = xpathTokenPrecedence(frame.tag);
} else if (frame.length) { /* Q_ match */
for (var j = 0; j < frame.length; ++j) {
var p = xpathGrammarPrecedence(frame[j]);
ret = Math.max(ret, p);
}
}
return ret;
}
function stackToString(stack) {
var ret = '';
for (var i = 0; i < stack.length; ++i) {
if (ret) {
ret += '\n';
}
ret += stack[i].tag.label;
}
return ret;
}
// XPath expression evaluation context. An XPath context consists of a
// DOM node, a list of DOM nodes that contains this node, a number
// that represents the position of the single node in the list, and a
// current set of variable bindings. (See XPath spec.)
//
// The interface of the expression context:
//
// Constructor -- gets the node, its position, the node set it
// belongs to, and a parent context as arguments. The parent context
// is used to implement scoping rules for variables: if a variable
// is not found in the current context, it is looked for in the
// parent context, recursively. Except for node, all arguments have
// default values: default position is 0, default node set is the
// set that contains only the node, and the default parent is null.
//
// Notice that position starts at 0 at the outside interface;
// inside XPath expressions this shows up as position()=1.
//
// clone() -- creates a new context with the current context as
// parent. If passed as argument to clone(), the new context has a
// different node, position, or node set. What is not passed is
// inherited from the cloned context.
//
// setVariable(name, expr) -- binds given XPath expression to the
// name.
//
// getVariable(name) -- what the name says.
//
// setNode(node, position) -- sets the context to the new node and
// its corresponding position. Needed to implement scoping rules for
// variables in XPath. (A variable is visible to all subsequent
// siblings, not only to its children.)
function ExprContext(node, position, nodelist, parent) {
this.node = node;
this.position = position || 0;
this.nodelist = nodelist || [ node ];
this.variables = {};
this.parent = parent || null;
this.root = parent ? parent.root : node.ownerDocument;
}
ExprContext.prototype.clone = function(node, position, nodelist) {
return new
ExprContext(node || this.node,
typeof position != 'undefined' ? position : this.position,
nodelist || this.nodelist, this);
};
ExprContext.prototype.setVariable = function(name, value) {
this.variables[name] = value;
};
ExprContext.prototype.getVariable = function(name) {
if (typeof this.variables[name] != 'undefined') {
return this.variables[name];
} else if (this.parent) {
return this.parent.getVariable(name);
} else {
return null;
}
}
ExprContext.prototype.setNode = function(node, position) {
this.node = node;
this.position = position;
}
// XPath expression values. They are what XPath expressions evaluate
// to. Strangely, the different value types are not specified in the
// XPath syntax, but only in the semantics, so they don't show up as
// nonterminals in the grammar. Yet, some expressions are required to
// evaluate to particular types, and not every type can be coerced
// into every other type. Although the types of XPath values are
// similar to the types present in JavaScript, the type coercion rules
// are a bit peculiar, so we explicitly model XPath types instead of
// mapping them onto JavaScript types. (See XPath spec.)
//
// The four types are:
//
// StringValue
//
// NumberValue
//
// BooleanValue
//
// NodeSetValue
//
// The common interface of the value classes consists of methods that
// implement the XPath type coercion rules:
//
// stringValue() -- returns the value as a JavaScript String,
//
// numberValue() -- returns the value as a JavaScript Number,
//
// booleanValue() -- returns the value as a JavaScript Boolean,
//
// nodeSetValue() -- returns the value as a JavaScript Array of DOM
// Node objects.
//
function StringValue(value) {
this.value = value;
this.type = 'string';
}
StringValue.prototype.stringValue = function() {
return this.value;
}
StringValue.prototype.booleanValue = function() {
return this.value.length > 0;
}
StringValue.prototype.numberValue = function() {
return this.value - 0;
}
StringValue.prototype.nodeSetValue = function() {
throw this + ' ' + Error().stack;
}
function BooleanValue(value) {
this.value = value;
this.type = 'boolean';
}
BooleanValue.prototype.stringValue = function() {
return '' + this.value;
}
BooleanValue.prototype.booleanValue = function() {
return this.value;
}
BooleanValue.prototype.numberValue = function() {
return this.value ? 1 : 0;
}
BooleanValue.prototype.nodeSetValue = function() {
throw this + ' ' + Error().stack;
}
function NumberValue(value) {
this.value = value;
this.type = 'number';
}
NumberValue.prototype.stringValue = function() {
return '' + this.value;
}
NumberValue.prototype.booleanValue = function() {
return !!this.value;
}
NumberValue.prototype.numberValue = function() {
return this.value - 0;
}
NumberValue.prototype.nodeSetValue = function() {
throw this + ' ' + Error().stack;
}
function NodeSetValue(value) {
this.value = value;
this.type = 'node-set';
}
NodeSetValue.prototype.stringValue = function() {
if (this.value.length == 0) {
return '';
} else {
return xmlValue(this.value[0]);
}
}
NodeSetValue.prototype.booleanValue = function() {
return this.value.length > 0;
}
NodeSetValue.prototype.numberValue = function() {
return this.stringValue() - 0;
}
NodeSetValue.prototype.nodeSetValue = function() {
return this.value;
};
// XPath expressions. They are used as nodes in the parse tree and
// possess an evaluate() method to compute an XPath value given an XPath
// context. Expressions are returned from the parser. Teh set of
// expression classes closely mirrors the set of non terminal symbols
// in the grammar. Every non trivial nonterminal symbol has a
// corresponding expression class.
//
// The common expression interface consists of the following methods:
//
// evaluate(context) -- evaluates the expression, returns a value.
//
// toString() -- returns the XPath text representation of the
// expression (defined in xsltdebug.js).
//
// parseTree(indent) -- returns a parse tree representation of the
// expression (defined in xsltdebug.js).
function TokenExpr(m) {
this.value = m;
}
TokenExpr.prototype.evaluate = function() {
return new StringValue(this.value);
};
function LocationExpr() {
this.absolute = false;
this.steps = [];
}
LocationExpr.prototype.appendStep = function(s) {
this.steps.push(s);
}
LocationExpr.prototype.prependStep = function(s) {
var steps0 = this.steps;
this.steps = [ s ];
for (var i = 0; i < steps0.length; ++i) {
this.steps.push(steps0[i]);
}
};
LocationExpr.prototype.evaluate = function(ctx) {
var start;
if (this.absolute) {
start = ctx.root;
} else {
start = ctx.node;
}
var nodes = [];
xPathStep(nodes, this.steps, 0, start, ctx);
return new NodeSetValue(nodes);
};
function xPathStep(nodes, steps, step, input, ctx) {
var s = steps[step];
var ctx2 = ctx.clone(input);
var nodelist = s.evaluate(ctx2).nodeSetValue();
for (var i = 0; i < nodelist.length; ++i) {
if (step == steps.length - 1) {
nodes.push(nodelist[i]);
} else {
xPathStep(nodes, steps, step + 1, nodelist[i], ctx);
}
}
}
function StepExpr(axis, nodetest, predicate) {
this.axis = axis;
this.nodetest = nodetest;
this.predicate = predicate || [];
}
StepExpr.prototype.appendPredicate = function(p) {
this.predicate.push(p);
}
StepExpr.prototype.evaluate = function(ctx) {
var input = ctx.node;
var nodelist = [];
// NOTE(mesch): When this was a switch() statement, it didn't work
// in Safari/2.0. Not sure why though; it resulted in the JavaScript
// console output "undefined" (without any line number or so).
if (this.axis == xpathAxis.ANCESTOR_OR_SELF) {
nodelist.push(input);
for (var n = input.parentNode; n; n = input.parentNode) {
nodelist.push(n);
}
} else if (this.axis == xpathAxis.ANCESTOR) {
for (var n = input.parentNode; n; n = input.parentNode) {
nodelist.push(n);
}
} else if (this.axis == xpathAxis.ATTRIBUTE) {
copyArray(nodelist, input.attributes);
} else if (this.axis == xpathAxis.CHILD) {
copyArray(nodelist, input.childNodes);
} else if (this.axis == xpathAxis.DESCENDANT_OR_SELF) {
nodelist.push(input);
xpathCollectDescendants(nodelist, input);
} else if (this.axis == xpathAxis.DESCENDANT) {
xpathCollectDescendants(nodelist, input);
} else if (this.axis == xpathAxis.FOLLOWING) {
for (var n = input.parentNode; n; n = n.parentNode) {
for (var nn = n.nextSibling; nn; nn = nn.nextSibling) {
nodelist.push(nn);
xpathCollectDescendants(nodelist, nn);
}
}
} else if (this.axis == xpathAxis.FOLLOWING_SIBLING) {
for (var n = input.nextSibling; n; n = input.nextSibling) {
nodelist.push(n);
}
} else if (this.axis == xpathAxis.NAMESPACE) {
alert('not implemented: axis namespace');
} else if (this.axis == xpathAxis.PARENT) {
if (input.parentNode) {
nodelist.push(input.parentNode);
}
} else if (this.axis == xpathAxis.PRECEDING) {
for (var n = input.parentNode; n; n = n.parentNode) {
for (var nn = n.previousSibling; nn; nn = nn.previousSibling) {
nodelist.push(nn);
xpathCollectDescendantsReverse(nodelist, nn);
}
}
} else if (this.axis == xpathAxis.PRECEDING_SIBLING) {
for (var n = input.previousSibling; n; n = input.previousSibling) {
nodelist.push(n);
}
} else if (this.axis == xpathAxis.SELF) {
nodelist.push(input);
} else {
throw 'ERROR -- NO SUCH AXIS: ' + this.axis;
}
// process node test
var nodelist0 = nodelist;
nodelist = [];
for (var i = 0; i < nodelist0.length; ++i) {
var n = nodelist0[i];
if (this.nodetest.evaluate(ctx.clone(n, i, nodelist0)).booleanValue()) {
nodelist.push(n);
}
}
// process predicates
for (var i = 0; i < this.predicate.length; ++i) {
var nodelist0 = nodelist;
nodelist = [];
for (var ii = 0; ii < nodelist0.length; ++ii) {
var n = nodelist0[ii];
if (this.predicate[i].evaluate(ctx.clone(n, ii, nodelist0)).booleanValue()) {
nodelist.push(n);
}
}
}
return new NodeSetValue(nodelist);
};
function NodeTestAny() {
this.value = new BooleanValue(true);
}
NodeTestAny.prototype.evaluate = function(ctx) {
return this.value;
};
function NodeTestElement() {}
NodeTestElement.prototype.evaluate = function(ctx) {
return new BooleanValue(ctx.node.nodeType == DOM_ELEMENT_NODE);
}
function NodeTestText() {}
NodeTestText.prototype.evaluate = function(ctx) {
return new BooleanValue(ctx.node.nodeType == DOM_TEXT_NODE);
}
function NodeTestComment() {}
NodeTestComment.prototype.evaluate = function(ctx) {
return new BooleanValue(ctx.node.nodeType == DOM_COMMENT_NODE);
}
function NodeTestPI(target) {
this.target = target;
}
NodeTestPI.prototype.evaluate = function(ctx) {
return new
BooleanValue(ctx.node.nodeType == DOM_PROCESSING_INSTRUCTION_NODE &&
(!this.target || ctx.node.nodeName == this.target));
}
function NodeTestNC(nsprefix) {
this.regex = new RegExp("^" + nsprefix + ":");
this.nsprefix = nsprefix;
}
NodeTestNC.prototype.evaluate = function(ctx) {
var n = ctx.node;
return new BooleanValue(this.regex.match(n.nodeName));
}
function NodeTestName(name) {
this.name = name;
}
NodeTestName.prototype.evaluate = function(ctx) {
var n = ctx.node;
// NOTE (Patrick Lightbody): this change allows node selection to be case-insensitive
return new BooleanValue(n.nodeName.toUpperCase() == this.name.toUpperCase());
}
function PredicateExpr(expr) {
this.expr = expr;
}
PredicateExpr.prototype.evaluate = function(ctx) {
var v = this.expr.evaluate(ctx);
if (v.type == 'number') {
// NOTE(mesch): Internally, position is represented starting with
// 0, however in XPath position starts with 1. See functions
// position() and last().
return new BooleanValue(ctx.position == v.numberValue() - 1);
} else {
return new BooleanValue(v.booleanValue());
}
};
function FunctionCallExpr(name) {
this.name = name;
this.args = [];
}
FunctionCallExpr.prototype.appendArg = function(arg) {
this.args.push(arg);
};
FunctionCallExpr.prototype.evaluate = function(ctx) {
var fn = '' + this.name.value;
var f = this.xpathfunctions[fn];
if (f) {
return f.call(this, ctx);
} else {
Log.write('XPath NO SUCH FUNCTION ' + fn);
return new BooleanValue(false);
}
};
FunctionCallExpr.prototype.xpathfunctions = {
'last': function(ctx) {
assert(this.args.length == 0);
// NOTE(mesch): XPath position starts at 1.
return new NumberValue(ctx.nodelist.length);
},
'position': function(ctx) {
assert(this.args.length == 0);
// NOTE(mesch): XPath position starts at 1.
return new NumberValue(ctx.position + 1);
},
'count': function(ctx) {
assert(this.args.length == 1);
var v = this.args[0].evaluate(ctx);
return new NumberValue(v.nodeSetValue().length);
},
'id': function(ctx) {
assert(this.args.length == 1);
var e = this.args[0].evaluate(ctx);
var ret = [];
var ids;
if (e.type == 'node-set') {
ids = [];
for (var i = 0; i < e.length; ++i) {
var v = xmlValue(e[i]).split(/\s+/);
for (var ii = 0; ii < v.length; ++ii) {
ids.push(v[ii]);
}
}
} else {
ids = e.stringValue().split(/\s+/);
}
var contextNode = ctx.node;
var d;
if (contextNode.nodeName == "#document") {
d = contextNode;
} else {
d = contextNode.ownerDocument;
}
for (var i = 0; i < ids.length; ++i) {
var n = d.getElementById(ids[i]);
if (n) {
ret.push(n);
}
}
return new NodeSetValue(ret);
},
'local-name': function(ctx) {
alert('not implmented yet: XPath function local-name()');
},
'namespace-uri': function(ctx) {
alert('not implmented yet: XPath function namespace-uri()');
},
'name': function(ctx) {
assert(this.args.length == 1 || this.args.length == 0);
var n;
if (this.args.length == 0) {
n = [ ctx.node ];
} else {
n = this.args[0].evaluate(ctx).nodeSetValue();
}
if (n.length == 0) {
return new StringValue('');
} else {
return new StringValue(n[0].nodeName);
}
},
'string': function(ctx) {
assert(this.args.length == 1 || this.args.length == 0);
if (this.args.length == 0) {
return new StringValue(new NodeSetValue([ ctx.node ]).stringValue());
} else {
return new StringValue(this.args[0].evaluate(ctx).stringValue());
}
},
'concat': function(ctx) {
var ret = '';
for (var i = 0; i < this.args.length; ++i) {
ret += this.args[i].evaluate(ctx).stringValue();
}
return new StringValue(ret);
},
'starts-with': function(ctx) {
assert(this.args.length == 2);
var s0 = this.args[0].evaluate(ctx).stringValue();
var s1 = this.args[1].evaluate(ctx).stringValue();
return new BooleanValue(s0.indexOf(s1) == 0);
},
'contains': function(ctx) {
assert(this.args.length == 2);
var s0 = this.args[0].evaluate(ctx).stringValue();
var s1 = this.args[1].evaluate(ctx).stringValue();
return new BooleanValue(s0.indexOf(s1) != -1);
},
'substring-before': function(ctx) {
assert(this.args.length == 2);
var s0 = this.args[0].evaluate(ctx).stringValue();
var s1 = this.args[1].evaluate(ctx).stringValue();
var i = s0.indexOf(s1);
var ret;
if (i == -1) {
ret = '';
} else {
ret = s0.substr(0,i);
}
return new StringValue(ret);
},
'substring-after': function(ctx) {
assert(this.args.length == 2);
var s0 = this.args[0].evaluate(ctx).stringValue();
var s1 = this.args[1].evaluate(ctx).stringValue();
var i = s0.indexOf(s1);
var ret;
if (i == -1) {
ret = '';
} else {
ret = s0.substr(i + s1.length);
}
return new StringValue(ret);
},
'substring': function(ctx) {
// NOTE: XPath defines the position of the first character in a
// string to be 1, in JavaScript this is 0 ([XPATH] Section 4.2).
assert(this.args.length == 2 || this.args.length == 3);
var s0 = this.args[0].evaluate(ctx).stringValue();
var s1 = this.args[1].evaluate(ctx).numberValue();
var ret;
if (this.args.length == 2) {
var i1 = Math.max(0, Math.round(s1) - 1);
ret = s0.substr(i1);
} else {
var s2 = this.args[2].evaluate(ctx).numberValue();
var i0 = Math.round(s1) - 1;
var i1 = Math.max(0, i0);
var i2 = Math.round(s2) - Math.max(0, -i0);
ret = s0.substr(i1, i2);
}
return new StringValue(ret);
},
'string-length': function(ctx) {
var s;
if (this.args.length > 0) {
s = this.args[0].evaluate(ctx).stringValue();
} else {
s = new NodeSetValue([ ctx.node ]).stringValue();
}
return new NumberValue(s.length);
},
'normalize-space': function(ctx) {
var s;
if (this.args.length > 0) {
s = this.args[0].evaluate(ctx).stringValue();
} else {
s = new NodeSetValue([ ctx.node ]).stringValue();
}
s = s.replace(/^\s*/,'').replace(/\s*$/,'').replace(/\s+/g, ' ');
return new StringValue(s);
},
'translate': function(ctx) {
assert(this.args.length == 3);
var s0 = this.args[0].evaluate(ctx).stringValue();
var s1 = this.args[1].evaluate(ctx).stringValue();
var s2 = this.args[2].evaluate(ctx).stringValue();
for (var i = 0; i < s1.length; ++i) {
s0 = s0.replace(new RegExp(s1.charAt(i), 'g'), s2.charAt(i));
}
return new StringValue(s0);
},
'boolean': function(ctx) {
assert(this.args.length == 1);
return new BooleanValue(this.args[0].evaluate(ctx).booleanValue());
},
'not': function(ctx) {
assert(this.args.length == 1);
var ret = !this.args[0].evaluate(ctx).booleanValue();
return new BooleanValue(ret);
},
'true': function(ctx) {
assert(this.args.length == 0);
return new BooleanValue(true);
},
'false': function(ctx) {
assert(this.args.length == 0);
return new BooleanValue(false);
},
'lang': function(ctx) {
assert(this.args.length == 1);
var lang = this.args[0].evaluate(ctx).stringValue();
var xmllang;
var n = ctx.node;
while (n && n != n.parentNode /* just in case ... */) {
xmllang = n.getAttribute('xml:lang');
if (xmllang) {
break;
}
n = n.parentNode;
}
if (!xmllang) {
return new BooleanValue(false);
} else {
var re = new RegExp('^' + lang + '$', 'i');
return new BooleanValue(xmllang.match(re) ||
xmllang.replace(/_.*$/,'').match(re));
}
},
'number': function(ctx) {
assert(this.args.length == 1 || this.args.length == 0);
if (this.args.length == 1) {
return new NumberValue(this.args[0].evaluate(ctx).numberValue());
} else {
return new NumberValue(new NodeSetValue([ ctx.node ]).numberValue());
}
},
'sum': function(ctx) {
assert(this.args.length == 1);
var n = this.args[0].evaluate(ctx).nodeSetValue();
var sum = 0;
for (var i = 0; i < n.length; ++i) {
sum += xmlValue(n[i]) - 0;
}
return new NumberValue(sum);
},
'floor': function(ctx) {
assert(this.args.length == 1);
var num = this.args[0].evaluate(ctx).numberValue();
return new NumberValue(Math.floor(num));
},
'ceiling': function(ctx) {
assert(this.args.length == 1);
var num = this.args[0].evaluate(ctx).numberValue();
return new NumberValue(Math.ceil(num));
},
'round': function(ctx) {
assert(this.args.length == 1);
var num = this.args[0].evaluate(ctx).numberValue();
return new NumberValue(Math.round(num));
},
// TODO(mesch): The following functions are custom. There is a
// standard that defines how to add functions, which should be
// applied here.
'ext-join': function(ctx) {
assert(this.args.length == 2);
var nodes = this.args[0].evaluate(ctx).nodeSetValue();
var delim = this.args[1].evaluate(ctx).stringValue();
var ret = '';
for (var i = 0; i < nodes.length; ++i) {
if (ret) {
ret += delim;
}
ret += xmlValue(nodes[i]);
}
return new StringValue(ret);
},
// ext-if() evaluates and returns its second argument, if the
// boolean value of its first argument is true, otherwise it
// evaluates and returns its third argument.
'ext-if': function(ctx) {
assert(this.args.length == 3);
if (this.args[0].evaluate(ctx).booleanValue()) {
return this.args[1].evaluate(ctx);
} else {
return this.args[2].evaluate(ctx);
}
},
'ext-sprintf': function(ctx) {
assert(this.args.length >= 1);
var args = [];
for (var i = 0; i < this.args.length; ++i) {
args.push(this.args[i].evaluate(ctx).stringValue());
}
return new StringValue(sprintf.apply(null, args));
},
// ext-cardinal() evaluates its single argument as a number, and
// returns the current node that many times. It can be used in the
// select attribute to iterate over an integer range.
'ext-cardinal': function(ctx) {
assert(this.args.length >= 1);
var c = this.args[0].evaluate(ctx).numberValue();
var ret = [];
for (var i = 0; i < c; ++i) {
ret.push(ctx.node);
}
return new NodeSetValue(ret);
}
};
function UnionExpr(expr1, expr2) {
this.expr1 = expr1;
this.expr2 = expr2;
}
UnionExpr.prototype.evaluate = function(ctx) {
var nodes1 = this.expr1.evaluate(ctx).nodeSetValue();
var nodes2 = this.expr2.evaluate(ctx).nodeSetValue();
var I1 = nodes1.length;
for (var i2 = 0; i2 < nodes2.length; ++i2) {
for (var i1 = 0; i1 < I1; ++i1) {
if (nodes1[i1] == nodes2[i2]) {
// break inner loop and continue outer loop, labels confuse
// the js compiler, so we don't use them here.
i1 = I1;
}
}
nodes1.push(nodes2[i2]);
}
return new NodeSetValue(nodes2);
};
function PathExpr(filter, rel) {
this.filter = filter;
this.rel = rel;
}
PathExpr.prototype.evaluate = function(ctx) {
var nodes = this.filter.evaluate(ctx).nodeSetValue();
var nodes1 = [];
for (var i = 0; i < nodes.length; ++i) {
var nodes0 = this.rel.evaluate(ctx.clone(nodes[i], i, nodes)).nodeSetValue();
for (var ii = 0; ii < nodes0.length; ++ii) {
nodes1.push(nodes0[ii]);
}
}
return new NodeSetValue(nodes1);
};
function FilterExpr(expr, predicate) {
this.expr = expr;
this.predicate = predicate;
}
FilterExpr.prototype.evaluate = function(ctx) {
var nodes = this.expr.evaluate(ctx).nodeSetValue();
for (var i = 0; i < this.predicate.length; ++i) {
var nodes0 = nodes;
nodes = [];
for (var j = 0; j < nodes0.length; ++j) {
var n = nodes0[j];
if (this.predicate[i].evaluate(ctx.clone(n, j, nodes0)).booleanValue()) {
nodes.push(n);
}
}
}
return new NodeSetValue(nodes);
}
function UnaryMinusExpr(expr) {
this.expr = expr;
}
UnaryMinusExpr.prototype.evaluate = function(ctx) {
return new NumberValue(-this.expr.evaluate(ctx).numberValue());
};
function BinaryExpr(expr1, op, expr2) {
this.expr1 = expr1;
this.expr2 = expr2;
this.op = op;
}
BinaryExpr.prototype.evaluate = function(ctx) {
var ret;
switch (this.op.value) {
case 'or':
ret = new BooleanValue(this.expr1.evaluate(ctx).booleanValue() ||
this.expr2.evaluate(ctx).booleanValue());
break;
case 'and':
ret = new BooleanValue(this.expr1.evaluate(ctx).booleanValue() &&
this.expr2.evaluate(ctx).booleanValue());
break;
case '+':
ret = new NumberValue(this.expr1.evaluate(ctx).numberValue() +
this.expr2.evaluate(ctx).numberValue());
break;
case '-':
ret = new NumberValue(this.expr1.evaluate(ctx).numberValue() -
this.expr2.evaluate(ctx).numberValue());
break;
case '*':
ret = new NumberValue(this.expr1.evaluate(ctx).numberValue() *
this.expr2.evaluate(ctx).numberValue());
break;
case 'mod':
ret = new NumberValue(this.expr1.evaluate(ctx).numberValue() %
this.expr2.evaluate(ctx).numberValue());
break;
case 'div':
ret = new NumberValue(this.expr1.evaluate(ctx).numberValue() /
this.expr2.evaluate(ctx).numberValue());
break;
case '=':
ret = this.compare(ctx, function(x1, x2) { return x1 == x2; });
break;
case '!=':
ret = this.compare(ctx, function(x1, x2) { return x1 != x2; });
break;
case '<':
ret = this.compare(ctx, function(x1, x2) { return x1 < x2; });
break;
case '<=':
ret = this.compare(ctx, function(x1, x2) { return x1 <= x2; });
break;
case '>':
ret = this.compare(ctx, function(x1, x2) { return x1 > x2; });
break;
case '>=':
ret = this.compare(ctx, function(x1, x2) { return x1 >= x2; });
break;
default:
alert('BinaryExpr.evaluate: ' + this.op.value);
}
return ret;
};
BinaryExpr.prototype.compare = function(ctx, cmp) {
var v1 = this.expr1.evaluate(ctx);
var v2 = this.expr2.evaluate(ctx);
var ret;
if (v1.type == 'node-set' && v2.type == 'node-set') {
var n1 = v1.nodeSetValue();
var n2 = v2.nodeSetValue();
ret = false;
for (var i1 = 0; i1 < n1.length; ++i1) {
for (var i2 = 0; i2 < n2.length; ++i2) {
if (cmp(xmlValue(n1[i1]), xmlValue(n2[i2]))) {
ret = true;
// Break outer loop. Labels confuse the jscompiler and we
// don't use them.
i2 = n2.length;
i1 = n1.length;
}
}
}
} else if (v1.type == 'node-set' || v2.type == 'node-set') {
if (v1.type == 'number') {
var s = v1.numberValue();
var n = v2.nodeSetValue();
ret = false;
for (var i = 0; i < n.length; ++i) {
var nn = xmlValue(n[i]) - 0;
if (cmp(s, nn)) {
ret = true;
break;
}
}
} else if (v2.type == 'number') {
var n = v1.nodeSetValue();
var s = v2.numberValue();
ret = false;
for (var i = 0; i < n.length; ++i) {
var nn = xmlValue(n[i]) - 0;
if (cmp(nn, s)) {
ret = true;
break;
}
}
} else if (v1.type == 'string') {
var s = v1.stringValue();
var n = v2.nodeSetValue();
ret = false;
for (var i = 0; i < n.length; ++i) {
var nn = xmlValue(n[i]);
if (cmp(s, nn)) {
ret = true;
break;
}
}
} else if (v2.type == 'string') {
var n = v1.nodeSetValue();
var s = v2.stringValue();
ret = false;
for (var i = 0; i < n.length; ++i) {
var nn = xmlValue(n[i]);
if (cmp(nn, s)) {
ret = true;
break;
}
}
} else {
ret = cmp(v1.booleanValue(), v2.booleanValue());
}
} else if (v1.type == 'boolean' || v2.type == 'boolean') {
ret = cmp(v1.booleanValue(), v2.booleanValue());
} else if (v1.type == 'number' || v2.type == 'number') {
ret = cmp(v1.numberValue(), v2.numberValue());
} else {
ret = cmp(v1.stringValue(), v2.stringValue());
}
return new BooleanValue(ret);
}
function LiteralExpr(value) {
this.value = value;
}
LiteralExpr.prototype.evaluate = function(ctx) {
return new StringValue(this.value);
};
function NumberExpr(value) {
this.value = value;
}
NumberExpr.prototype.evaluate = function(ctx) {
return new NumberValue(this.value);
};
function VariableExpr(name) {
this.name = name;
}
VariableExpr.prototype.evaluate = function(ctx) {
return ctx.getVariable(this.name);
}
// Factory functions for semantic values (i.e. Expressions) of the
// productions in the grammar. When a production is matched to reduce
// the current parse state stack, the function is called with the
// semantic values of the matched elements as arguments, and returns
// another semantic value. The semantic value is a node of the parse
// tree, an expression object with an evaluate() method that evaluates the
// expression in an actual context. These factory functions are used
// in the specification of the grammar rules, below.
function makeTokenExpr(m) {
return new TokenExpr(m);
}
function passExpr(e) {
return e;
}
function makeLocationExpr1(slash, rel) {
rel.absolute = true;
return rel;
}
function makeLocationExpr2(dslash, rel) {
rel.absolute = true;
rel.prependStep(makeAbbrevStep(dslash.value));
return rel;
}
function makeLocationExpr3(slash) {
var ret = new LocationExpr();
ret.appendStep(makeAbbrevStep('.'));
ret.absolute = true;
return ret;
}
function makeLocationExpr4(dslash) {
var ret = new LocationExpr();
ret.absolute = true;
ret.appendStep(makeAbbrevStep(dslash.value));
return ret;
}
function makeLocationExpr5(step) {
var ret = new LocationExpr();
ret.appendStep(step);
return ret;
}
function makeLocationExpr6(rel, slash, step) {
rel.appendStep(step);
return rel;
}
function makeLocationExpr7(rel, dslash, step) {
rel.appendStep(makeAbbrevStep(dslash.value));
rel.appendStep(step);
return rel;
}
function makeStepExpr1(dot) {
return makeAbbrevStep(dot.value);
}
function makeStepExpr2(ddot) {
return makeAbbrevStep(ddot.value);
}
function makeStepExpr3(axisname, axis, nodetest) {
return new StepExpr(axisname.value, nodetest);
}
function makeStepExpr4(at, nodetest) {
return new StepExpr('attribute', nodetest);
}
function makeStepExpr5(nodetest) {
return new StepExpr('child', nodetest);
}
function makeStepExpr6(step, predicate) {
step.appendPredicate(predicate);
return step;
}
function makeAbbrevStep(abbrev) {
switch (abbrev) {
case '//':
return new StepExpr('descendant-or-self', new NodeTestAny);
case '.':
return new StepExpr('self', new NodeTestAny);
case '..':
return new StepExpr('parent', new NodeTestAny);
}
}
function makeNodeTestExpr1(asterisk) {
return new NodeTestElement;
}
function makeNodeTestExpr2(ncname, colon, asterisk) {
return new NodeTestNC(ncname.value);
}
function makeNodeTestExpr3(qname) {
return new NodeTestName(qname.value);
}
function makeNodeTestExpr4(typeo, parenc) {
var type = typeo.value.replace(/\s*\($/, '');
switch(type) {
case 'node':
return new NodeTestAny;
case 'text':
return new NodeTestText;
case 'comment':
return new NodeTestComment;
case 'processing-instruction':
return new NodeTestPI;
}
}
function makeNodeTestExpr5(typeo, target, parenc) {
var type = typeo.replace(/\s*\($/, '');
if (type != 'processing-instruction') {
throw type + ' ' + Error().stack;
}
return new NodeTestPI(target.value);
}
function makePredicateExpr(pareno, expr, parenc) {
return new PredicateExpr(expr);
}
function makePrimaryExpr(pareno, expr, parenc) {
return expr;
}
function makeFunctionCallExpr1(name, pareno, parenc) {
return new FunctionCallExpr(name);
}
function makeFunctionCallExpr2(name, pareno, arg1, args, parenc) {
var ret = new FunctionCallExpr(name);
ret.appendArg(arg1);
for (var i = 0; i < args.length; ++i) {
ret.appendArg(args[i]);
}
return ret;
}
function makeArgumentExpr(comma, expr) {
return expr;
}
function makeUnionExpr(expr1, pipe, expr2) {
return new UnionExpr(expr1, expr2);
}
function makePathExpr1(filter, slash, rel) {
return new PathExpr(filter, rel);
}
function makePathExpr2(filter, dslash, rel) {
rel.prependStep(makeAbbrevStep(dslash.value));
return new PathExpr(filter, rel);
}
function makeFilterExpr(expr, predicates) {
if (predicates.length > 0) {
return new FilterExpr(expr, predicates);
} else {
return expr;
}
}
function makeUnaryMinusExpr(minus, expr) {
return new UnaryMinusExpr(expr);
}
function makeBinaryExpr(expr1, op, expr2) {
return new BinaryExpr(expr1, op, expr2);
}
function makeLiteralExpr(token) {
// remove quotes from the parsed value:
var value = token.value.substring(1, token.value.length - 1);
return new LiteralExpr(value);
}
function makeNumberExpr(token) {
return new NumberExpr(token.value);
}
function makeVariableReference(dollar, name) {
return new VariableExpr(name.value);
}
// Used before parsing for optimization of common simple cases. See
// the begin of xpathParse() for which they are.
function makeSimpleExpr(expr) {
if (expr.charAt(0) == '$') {
return new VariableExpr(expr.substr(1));
} else if (expr.charAt(0) == '@') {
var a = new NodeTestName(expr.substr(1));
var b = new StepExpr('attribute', a);
var c = new LocationExpr();
c.appendStep(b);
return c;
} else if (expr.match(/^[0-9]+$/)) {
return new NumberExpr(expr);
} else {
var a = new NodeTestName(expr);
var b = new StepExpr('child', a);
var c = new LocationExpr();
c.appendStep(b);
return c;
}
}
function makeSimpleExpr2(expr) {
var steps = expr.split('/');
var c = new LocationExpr();
for (var i in steps) {
var a = new NodeTestName(steps[i]);
var b = new StepExpr('child', a);
c.appendStep(b);
}
return c;
}
// The axes of XPath expressions.
var xpathAxis = {
ANCESTOR_OR_SELF: 'ancestor-or-self',
ANCESTOR: 'ancestor',
ATTRIBUTE: 'attribute',
CHILD: 'child',
DESCENDANT_OR_SELF: 'descendant-or-self',
DESCENDANT: 'descendant',
FOLLOWING_SIBLING: 'following-sibling',
FOLLOWING: 'following',
NAMESPACE: 'namespace',
PARENT: 'parent',
PRECEDING_SIBLING: 'preceding-sibling',
PRECEDING: 'preceding',
SELF: 'self'
};
var xpathAxesRe = [
xpathAxis.ANCESTOR_OR_SELF,
xpathAxis.ANCESTOR,
xpathAxis.ATTRIBUTE,
xpathAxis.CHILD,
xpathAxis.DESCENDANT_OR_SELF,
xpathAxis.DESCENDANT,
xpathAxis.FOLLOWING_SIBLING,
xpathAxis.FOLLOWING,
xpathAxis.NAMESPACE,
xpathAxis.PARENT,
xpathAxis.PRECEDING_SIBLING,
xpathAxis.PRECEDING,
xpathAxis.SELF
].join('|');
// The tokens of the language. The label property is just used for
// generating debug output. The prec property is the precedence used
// for shift/reduce resolution. Default precedence is 0 as a lookahead
// token and 2 on the stack. TODO(mesch): this is certainly not
// necessary and too complicated. Simplify this!
// NOTE: tabular formatting is the big exception, but here it should
// be OK.
var TOK_PIPE = { label: "|", prec: 17, re: new RegExp("^\\|") };
var TOK_DSLASH = { label: "//", prec: 19, re: new RegExp("^//") };
var TOK_SLASH = { label: "/", prec: 30, re: new RegExp("^/") };
var TOK_AXIS = { label: "::", prec: 20, re: new RegExp("^::") };
var TOK_COLON = { label: ":", prec: 1000, re: new RegExp("^:") };
var TOK_AXISNAME = { label: "[axis]", re: new RegExp('^(' + xpathAxesRe + ')') };
var TOK_PARENO = { label: "(", prec: 34, re: new RegExp("^\\(") };
var TOK_PARENC = { label: ")", re: new RegExp("^\\)") };
var TOK_DDOT = { label: "..", prec: 34, re: new RegExp("^\\.\\.") };
var TOK_DOT = { label: ".", prec: 34, re: new RegExp("^\\.") };
var TOK_AT = { label: "@", prec: 34, re: new RegExp("^@") };
var TOK_COMMA = { label: ",", re: new RegExp("^,") };
var TOK_OR = { label: "or", prec: 10, re: new RegExp("^or\\b") };
var TOK_AND = { label: "and", prec: 11, re: new RegExp("^and\\b") };
var TOK_EQ = { label: "=", prec: 12, re: new RegExp("^=") };
var TOK_NEQ = { label: "!=", prec: 12, re: new RegExp("^!=") };
var TOK_GE = { label: ">=", prec: 13, re: new RegExp("^>=") };
var TOK_GT = { label: ">", prec: 13, re: new RegExp("^>") };
var TOK_LE = { label: "<=", prec: 13, re: new RegExp("^<=") };
var TOK_LT = { label: "<", prec: 13, re: new RegExp("^<") };
var TOK_PLUS = { label: "+", prec: 14, re: new RegExp("^\\+"), left: true };
var TOK_MINUS = { label: "-", prec: 14, re: new RegExp("^\\-"), left: true };
var TOK_DIV = { label: "div", prec: 15, re: new RegExp("^div\\b"), left: true };
var TOK_MOD = { label: "mod", prec: 15, re: new RegExp("^mod\\b"), left: true };
var TOK_BRACKO = { label: "[", prec: 32, re: new RegExp("^\\[") };
var TOK_BRACKC = { label: "]", re: new RegExp("^\\]") };
var TOK_DOLLAR = { label: "$", re: new RegExp("^\\$") };
var TOK_NCNAME = { label: "[ncname]", re: new RegExp('^[a-z][-\\w]*','i') };
var TOK_ASTERISK = { label: "*", prec: 15, re: new RegExp("^\\*"), left: true };
var TOK_LITERALQ = { label: "[litq]", prec: 20, re: new RegExp("^'[^\\']*'") };
var TOK_LITERALQQ = {
label: "[litqq]",
prec: 20,
re: new RegExp('^"[^\\"]*"')
};
var TOK_NUMBER = {
label: "[number]",
prec: 35,
re: new RegExp('^\\d+(\\.\\d*)?') };
var TOK_QNAME = {
label: "[qname]",
re: new RegExp('^([a-z][-\\w]*:)?[a-z][-\\w]*','i')
};
var TOK_NODEO = {
label: "[nodetest-start]",
re: new RegExp('^(processing-instruction|comment|text|node)\\(')
};
// The table of the tokens of our grammar, used by the lexer: first
// column the tag, second column a regexp to recognize it in the
// input, third column the precedence of the token, fourth column a
// factory function for the semantic value of the token.
//
// NOTE: order of this list is important, because the first match
// counts. Cf. DDOT and DOT, and AXIS and COLON.
var xpathTokenRules = [
TOK_DSLASH,
TOK_SLASH,
TOK_DDOT,
TOK_DOT,
TOK_AXIS,
TOK_COLON,
TOK_AXISNAME,
TOK_NODEO,
TOK_PARENO,
TOK_PARENC,
TOK_BRACKO,
TOK_BRACKC,
TOK_AT,
TOK_COMMA,
TOK_OR,
TOK_AND,
TOK_NEQ,
TOK_EQ,
TOK_GE,
TOK_GT,
TOK_LE,
TOK_LT,
TOK_PLUS,
TOK_MINUS,
TOK_ASTERISK,
TOK_PIPE,
TOK_MOD,
TOK_DIV,
TOK_LITERALQ,
TOK_LITERALQQ,
TOK_NUMBER,
TOK_QNAME,
TOK_NCNAME,
TOK_DOLLAR
];
// All the nonterminals of the grammar. The nonterminal objects are
// identified by object identity; the labels are used in the debug
// output only.
var XPathLocationPath = { label: "LocationPath" };
var XPathRelativeLocationPath = { label: "RelativeLocationPath" };
var XPathAbsoluteLocationPath = { label: "AbsoluteLocationPath" };
var XPathStep = { label: "Step" };
var XPathNodeTest = { label: "NodeTest" };
var XPathPredicate = { label: "Predicate" };
var XPathLiteral = { label: "Literal" };
var XPathExpr = { label: "Expr" };
var XPathPrimaryExpr = { label: "PrimaryExpr" };
var XPathVariableReference = { label: "Variablereference" };
var XPathNumber = { label: "Number" };
var XPathFunctionCall = { label: "FunctionCall" };
var XPathArgumentRemainder = { label: "ArgumentRemainder" };
var XPathPathExpr = { label: "PathExpr" };
var XPathUnionExpr = { label: "UnionExpr" };
var XPathFilterExpr = { label: "FilterExpr" };
var XPathDigits = { label: "Digits" };
var xpathNonTerminals = [
XPathLocationPath,
XPathRelativeLocationPath,
XPathAbsoluteLocationPath,
XPathStep,
XPathNodeTest,
XPathPredicate,
XPathLiteral,
XPathExpr,
XPathPrimaryExpr,
XPathVariableReference,
XPathNumber,
XPathFunctionCall,
XPathArgumentRemainder,
XPathPathExpr,
XPathUnionExpr,
XPathFilterExpr,
XPathDigits
];
// Quantifiers that are used in the productions of the grammar.
var Q_01 = { label: "?" };
var Q_MM = { label: "*" };
var Q_1M = { label: "+" };
// Tag for left associativity (right assoc is implied by undefined).
var ASSOC_LEFT = true;
// The productions of the grammar. Columns of the table:
//
// - target nonterminal,
// - pattern,
// - precedence,
// - semantic value factory
//
// The semantic value factory is a function that receives parse tree
// nodes from the stack frames of the matched symbols as arguments and
// returns an a node of the parse tree. The node is stored in the top
// stack frame along with the target object of the rule. The node in
// the parse tree is an expression object that has an evaluate() method
// and thus evaluates XPath expressions.
//
// The precedence is used to decide between reducing and shifting by
// comparing the precendence of the rule that is candidate for
// reducing with the precedence of the look ahead token. Precedence of
// -1 means that the precedence of the tokens in the pattern is used
// instead. TODO: It shouldn't be necessary to explicitly assign
// precedences to rules.
// DGF Where do these precedence rules come from? I just tweaked some
// of these numbers to fix bug SEL-486.
var xpathGrammarRules =
[
[ XPathLocationPath, [ XPathRelativeLocationPath ], 18,
passExpr ],
[ XPathLocationPath, [ XPathAbsoluteLocationPath ], 18,
passExpr ],
[ XPathAbsoluteLocationPath, [ TOK_SLASH, XPathRelativeLocationPath ], 18,
makeLocationExpr1 ],
[ XPathAbsoluteLocationPath, [ TOK_DSLASH, XPathRelativeLocationPath ], 18,
makeLocationExpr2 ],
[ XPathAbsoluteLocationPath, [ TOK_SLASH ], 0,
makeLocationExpr3 ],
[ XPathAbsoluteLocationPath, [ TOK_DSLASH ], 0,
makeLocationExpr4 ],
[ XPathRelativeLocationPath, [ XPathStep ], 31,
makeLocationExpr5 ],
[ XPathRelativeLocationPath,
[ XPathRelativeLocationPath, TOK_SLASH, XPathStep ], 31,
makeLocationExpr6 ],
[ XPathRelativeLocationPath,
[ XPathRelativeLocationPath, TOK_DSLASH, XPathStep ], 31,
makeLocationExpr7 ],
[ XPathStep, [ TOK_DOT ], 33,
makeStepExpr1 ],
[ XPathStep, [ TOK_DDOT ], 33,
makeStepExpr2 ],
[ XPathStep,
[ TOK_AXISNAME, TOK_AXIS, XPathNodeTest ], 33,
makeStepExpr3 ],
[ XPathStep, [ TOK_AT, XPathNodeTest ], 33,
makeStepExpr4 ],
[ XPathStep, [ XPathNodeTest ], 33,
makeStepExpr5 ],
[ XPathStep, [ XPathStep, XPathPredicate ], 33,
makeStepExpr6 ],
[ XPathNodeTest, [ TOK_ASTERISK ], 33,
makeNodeTestExpr1 ],
[ XPathNodeTest, [ TOK_NCNAME, TOK_COLON, TOK_ASTERISK ], 33,
makeNodeTestExpr2 ],
[ XPathNodeTest, [ TOK_QNAME ], 33,
makeNodeTestExpr3 ],
[ XPathNodeTest, [ TOK_NODEO, TOK_PARENC ], 33,
makeNodeTestExpr4 ],
[ XPathNodeTest, [ TOK_NODEO, XPathLiteral, TOK_PARENC ], 33,
makeNodeTestExpr5 ],
[ XPathPredicate, [ TOK_BRACKO, XPathExpr, TOK_BRACKC ], 33,
makePredicateExpr ],
[ XPathPrimaryExpr, [ XPathVariableReference ], 33,
passExpr ],
[ XPathPrimaryExpr, [ TOK_PARENO, XPathExpr, TOK_PARENC ], 33,
makePrimaryExpr ],
[ XPathPrimaryExpr, [ XPathLiteral ], 30,
passExpr ],
[ XPathPrimaryExpr, [ XPathNumber ], 30,
passExpr ],
[ XPathPrimaryExpr, [ XPathFunctionCall ], 31,
passExpr ],
[ XPathFunctionCall, [ TOK_QNAME, TOK_PARENO, TOK_PARENC ], -1,
makeFunctionCallExpr1 ],
[ XPathFunctionCall,
[ TOK_QNAME, TOK_PARENO, XPathExpr, XPathArgumentRemainder, Q_MM,
TOK_PARENC ], -1,
makeFunctionCallExpr2 ],
[ XPathArgumentRemainder, [ TOK_COMMA, XPathExpr ], -1,
makeArgumentExpr ],
[ XPathUnionExpr, [ XPathPathExpr ], 20,
passExpr ],
[ XPathUnionExpr, [ XPathUnionExpr, TOK_PIPE, XPathPathExpr ], 20,
makeUnionExpr ],
[ XPathPathExpr, [ XPathLocationPath ], 20,
passExpr ],
[ XPathPathExpr, [ XPathFilterExpr ], 19,
passExpr ],
[ XPathPathExpr,
[ XPathFilterExpr, TOK_SLASH, XPathRelativeLocationPath ], 19,
makePathExpr1 ],
[ XPathPathExpr,
[ XPathFilterExpr, TOK_DSLASH, XPathRelativeLocationPath ], 19,
makePathExpr2 ],
[ XPathFilterExpr, [ XPathPrimaryExpr, XPathPredicate, Q_MM ], 31,
makeFilterExpr ],
[ XPathExpr, [ XPathPrimaryExpr ], 16,
passExpr ],
[ XPathExpr, [ XPathUnionExpr ], 16,
passExpr ],
[ XPathExpr, [ TOK_MINUS, XPathExpr ], -1,
makeUnaryMinusExpr ],
[ XPathExpr, [ XPathExpr, TOK_OR, XPathExpr ], -1,
makeBinaryExpr ],
[ XPathExpr, [ XPathExpr, TOK_AND, XPathExpr ], -1,
makeBinaryExpr ],
[ XPathExpr, [ XPathExpr, TOK_EQ, XPathExpr ], -1,
makeBinaryExpr ],
[ XPathExpr, [ XPathExpr, TOK_NEQ, XPathExpr ], -1,
makeBinaryExpr ],
[ XPathExpr, [ XPathExpr, TOK_LT, XPathExpr ], -1,
makeBinaryExpr ],
[ XPathExpr, [ XPathExpr, TOK_LE, XPathExpr ], -1,
makeBinaryExpr ],
[ XPathExpr, [ XPathExpr, TOK_GT, XPathExpr ], -1,
makeBinaryExpr ],
[ XPathExpr, [ XPathExpr, TOK_GE, XPathExpr ], -1,
makeBinaryExpr ],
[ XPathExpr, [ XPathExpr, TOK_PLUS, XPathExpr ], -1,
makeBinaryExpr, ASSOC_LEFT ],
[ XPathExpr, [ XPathExpr, TOK_MINUS, XPathExpr ], -1,
makeBinaryExpr, ASSOC_LEFT ],
[ XPathExpr, [ XPathExpr, TOK_ASTERISK, XPathExpr ], -1,
makeBinaryExpr, ASSOC_LEFT ],
[ XPathExpr, [ XPathExpr, TOK_DIV, XPathExpr ], -1,
makeBinaryExpr, ASSOC_LEFT ],
[ XPathExpr, [ XPathExpr, TOK_MOD, XPathExpr ], -1,
makeBinaryExpr, ASSOC_LEFT ],
[ XPathLiteral, [ TOK_LITERALQ ], -1,
makeLiteralExpr ],
[ XPathLiteral, [ TOK_LITERALQQ ], -1,
makeLiteralExpr ],
[ XPathNumber, [ TOK_NUMBER ], -1,
makeNumberExpr ],
[ XPathVariableReference, [ TOK_DOLLAR, TOK_QNAME ], 200,
makeVariableReference ]
];
// That function computes some optimizations of the above data
// structures and will be called right here. It merely takes the
// counter variables out of the global scope.
var xpathRules = [];
function xpathParseInit() {
if (xpathRules.length) {
return;
}
// Some simple optimizations for the xpath expression parser: sort
// grammar rules descending by length, so that the longest match is
// first found.
xpathGrammarRules.sort(function(a,b) {
var la = a[1].length;
var lb = b[1].length;
if (la < lb) {
return 1;
} else if (la > lb) {
return -1;
} else {
return 0;
}
});
var k = 1;
for (var i = 0; i < xpathNonTerminals.length; ++i) {
xpathNonTerminals[i].key = k++;
}
for (i = 0; i < xpathTokenRules.length; ++i) {
xpathTokenRules[i].key = k++;
}
Log.write('XPath parse INIT: ' + k + ' rules');
// Another slight optimization: sort the rules into bins according
// to the last element (observing quantifiers), so we can restrict
// the match against the stack to the subest of rules that match the
// top of the stack.
//
// TODO(mesch): What we actually want is to compute states as in
// bison, so that we don't have to do any explicit and iterated
// match against the stack.
function push_(array, position, element) {
if (!array[position]) {
array[position] = [];
}
array[position].push(element);
}
for (i = 0; i < xpathGrammarRules.length; ++i) {
var rule = xpathGrammarRules[i];
var pattern = rule[1];
for (var j = pattern.length - 1; j >= 0; --j) {
if (pattern[j] == Q_1M) {
push_(xpathRules, pattern[j-1].key, rule);
break;
} else if (pattern[j] == Q_MM || pattern[j] == Q_01) {
push_(xpathRules, pattern[j-1].key, rule);
--j;
} else {
push_(xpathRules, pattern[j].key, rule);
break;
}
}
}
Log.write('XPath parse INIT: ' + xpathRules.length + ' rule bins');
var sum = 0;
mapExec(xpathRules, function(i) {
if (i) {
sum += i.length;
}
});
Log.write('XPath parse INIT: ' + (sum / xpathRules.length) + ' average bin size');
}
// Local utility functions that are used by the lexer or parser.
function xpathCollectDescendants(nodelist, node) {
for (var n = node.firstChild; n; n = n.nextSibling) {
nodelist.push(n);
arguments.callee(nodelist, n);
}
}
function xpathCollectDescendantsReverse(nodelist, node) {
for (var n = node.lastChild; n; n = n.previousSibling) {
nodelist.push(n);
arguments.callee(nodelist, n);
}
}
// The entry point for the library: match an expression against a DOM
// node. Returns an XPath value.
function xpathDomEval(expr, node) {
var expr1 = xpathParse(expr);
var ret = expr1.evaluate(new ExprContext(node));
return ret;
}
// Utility function to sort a list of nodes. Used by xsltSort() and
// nxslSelect().
function xpathSort(input, sort) {
if (sort.length == 0) {
return;
}
var sortlist = [];
for (var i = 0; i < input.nodelist.length; ++i) {
var node = input.nodelist[i];
var sortitem = { node: node, key: [] };
var context = input.clone(node, 0, [ node ]);
for (var j = 0; j < sort.length; ++j) {
var s = sort[j];
var value = s.expr.evaluate(context);
var evalue;
if (s.type == 'text') {
evalue = value.stringValue();
} else if (s.type == 'number') {
evalue = value.numberValue();
}
sortitem.key.push({ value: evalue, order: s.order });
}
// Make the sort stable by adding a lowest priority sort by
// id. This is very convenient and furthermore required by the
// spec ([XSLT] - Section 10 Sorting).
sortitem.key.push({ value: i, order: 'ascending' });
sortlist.push(sortitem);
}
sortlist.sort(xpathSortByKey);
var nodes = [];
for (var i = 0; i < sortlist.length; ++i) {
nodes.push(sortlist[i].node);
}
input.nodelist = nodes;
input.setNode(nodes[0], 0);
}
// Sorts by all order criteria defined. According to the JavaScript
// spec ([ECMA] Section 11.8.5), the compare operators compare strings
// as strings and numbers as numbers.
//
// NOTE: In browsers which do not follow the spec, this breaks only in
// the case that numbers should be sorted as strings, which is very
// uncommon.
function xpathSortByKey(v1, v2) {
// NOTE: Sort key vectors of different length never occur in
// xsltSort.
for (var i = 0; i < v1.key.length; ++i) {
var o = v1.key[i].order == 'descending' ? -1 : 1;
if (v1.key[i].value > v2.key[i].value) {
return +1 * o;
} else if (v1.key[i].value < v2.key[i].value) {
return -1 * o;
}
}
return 0;
} | zc.selenium | /zc.selenium-1.2.1.tar.gz/zc.selenium-1.2.1/src/zc/selenium/resources/xpath/xpath.js | xpath.js |
=================================
WSGI middleware to wire in Sentry
=================================
This is a thin wrapper around the ``raven`` middleware which ensures SSL
validation is performed and logging configuration is also applied.
Release history
===============
1.1.0 (2014-11-26)
------------------
Update to a much newer ``raven``, and get out of the business of
rewiring SSL support.
1.0.1 (2014-11-26)
------------------
Fix ``requests`` dependency to reflect the minimum version that provides
``max_retries`` as a contructor argument for ``requests.adapters.HTTPAdapter``.
1.0.0 (2014-11-24)
------------------
Initial release.
| zc.sentrywsgi | /zc.sentrywsgi-1.1.0.tar.gz/zc.sentrywsgi-1.1.0/README.rst | README.rst |
Persistent sets are persistent objects that have the API of standard
Python sets. The persistent set should work the same as normal sets,
except that changes to them are persistent.
They have the same limitation as persistent lists and persistent
mappings, as found in the `persistent` package: unlike `BTree` package
data structures, changes copy the entire object in the database. This
generally means that persistent sets, like persistent lists and
persistent mappings, are inappropriate for very large collections. For
those, use `BTree` data structures.
The rest of this file is tests, not documentation. Find out about the
Python set API from standard Python documentation
(http://docs.python.org/lib/types-set.html, for instance) and find out about
persistence in the ZODB documentation
(http://www.zope.org/Wikis/ZODB/FrontPage/guide/index.html, for instance).
The persistent set module contains a simple persistent version of a set, that
inherits from persistent.Persistent and marks _p_changed = True for any
potentially mutating operation.
>>> from ZODB.tests.util import DB
>>> db = DB()
>>> conn = db.open()
>>> root = conn.root()
>>> import zope.app.folder # import rootFolder
>>> app = root['Application'] = zope.app.folder.rootFolder()
>>> import transaction
>>> transaction.commit()
>>> from zc.set import Set
>>> s = Set()
>>> app['s'] = s
>>> transaction.commit()
>>> import persistent.interfaces
>>> persistent.interfaces.IPersistent.providedBy(s)
True
>>> original = factory() # set in one test run; a persistent set in another
>>> sorted(set(dir(original)) - set(dir(s)))
[]
add sets _p_changed
>>> s._p_changed = False
>>> s.add(1) # add
>>> s._p_changed
True
__repr__ includes module, class, and a contents view like a normal set
>>> s # __repr__
zc.set.Set([1])
update works as normal, but sets _p_changed
>>> s._p_changed = False
>>> s.update((2,3,4,5,6,7)) # update
>>> s._p_changed
True
__iter__ works
>>> sorted(s) # __iter__
[1, 2, 3, 4, 5, 6, 7]
__len__ works
>>> len(s)
7
as does __contains__
>>> 3 in s
True
>>> 'kumquat' in s
False
__gt__, __ge__, __eq__, __ne__, __lt__, and __le__ work normally,
equating with normal set, at least if spelled in the right direction.
>>> s > original
True
>>> s >= original
True
>>> s < original
False
>>> s <= original
False
>>> s == original
False
>>> s != original
True
>>> original.update(s)
>>> s > original
False
>>> s >= original
True
>>> s < original
False
>>> s <= original
True
>>> s == original
True
>>> s != original
False
>>> original.add(8)
>>> s > original
False
>>> s >= original
False
>>> s < original
True
>>> s <= original
True
>>> s == original
False
>>> s != original
True
I don't know what __cmp__ is supposed to do--it doesn't work with sets--so
I won't test it.
issubset and issuperset work when it is a subset.
>>> s.issubset(original)
True
>>> s.issuperset(original)
False
__ior__ works, including setting _p_changed
>>> s._p_changed = False
>>> s |= original
>>> s._p_changed
True
>>> s == original
True
issubset and issuperset work when sets are equal.
>>> s.issubset(original)
True
>>> s.issuperset(original)
True
issubset and issuperset work when it is a superset.
>>> s.add(9)
>>> s.issubset(original)
False
>>> s.issuperset(original)
True
__hash__ works, insofar as raising an error as it is supposed to.
>>> hash(original)
Traceback (most recent call last):
...
TypeError:...unhashable...
__iand__ works, including setting _p_changed
>>> s._p_changed = False
>>> s &= original
>>> s._p_changed
True
>>> sorted(s)
[1, 2, 3, 4, 5, 6, 7, 8]
__isub__ works, including setting _p_changed
>>> s._p_changed = False
>>> s -= factory((1, 2, 3, 4, 5, 6, 7))
>>> s._p_changed
True
>>> sorted(s)
[8]
__ixor__ works, including setting _p_changed
>>> s._p_changed = False
>>> s ^= original
>>> s._p_changed
True
>>> sorted(s)
[1, 2, 3, 4, 5, 6, 7]
difference_update works, including setting _p_changed
>>> s._p_changed = False
>>> s.difference_update((7, 8))
>>> s._p_changed
True
>>> sorted(s)
[1, 2, 3, 4, 5, 6]
intersection_update works, including setting _p_changed
>>> s._p_changed = False
>>> s.intersection_update((2, 3, 4, 5, 6, 7))
>>> s._p_changed
True
>>> sorted(s)
[2, 3, 4, 5, 6]
symmetric_difference_update works, including setting _p_changed
>>> s._p_changed = False
>>> original.add(9)
>>> s.symmetric_difference_update(original)
>>> s._p_changed
True
>>> sorted(s)
[1, 7, 8, 9]
remove works, including setting _p_changed
>>> s._p_changed = False
>>> s.remove(1)
>>> s._p_changed
True
>>> sorted(s)
[7, 8, 9]
If it raises an error, _p_changed is not set.
>>> s._p_changed = False
>>> s.remove(1)
Traceback (most recent call last):
...
KeyError: 1
>>> s._p_changed
False
>>> sorted(s)
[7, 8, 9]
discard works, including setting _p_changed
>>> s._p_changed = False
>>> s.discard(9)
>>> s._p_changed
True
>>> sorted(s)
[7, 8]
If you discard something that wasn't in the set, _p_changed will still
be set. This is an efficiency decision, rather than our desired behavior,
necessarily.
>>> s._p_changed = False
>>> s.discard(9)
>>> s._p_changed
True
>>> sorted(s)
[7, 8]
pop works, including setting _p_changed
>>> s._p_changed = False
>>> s.pop() in (7, 8)
True
>>> s._p_changed
True
>>> len(s)
1
clear works, including setting _p_changed
>>> s._p_changed = False
>>> s.clear()
>>> s._p_changed
True
>>> len(s)
0
The methods that return sets all return persistent sets. They otherwise
work identically.
__and__
>>> s.update((0,1,2,3,4))
>>> res = s & original
>>> sorted(res)
[1, 2, 3, 4]
>>> res.__class__ is s.__class__
True
__or__
>>> res = s | original
>>> sorted(res)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> res.__class__ is s.__class__
True
__sub__
>>> res = s - original
>>> sorted(res)
[0]
>>> res.__class__ is s.__class__
True
__xor__
>>> res = s ^ original
>>> sorted(res)
[0, 5, 6, 7, 8, 9]
>>> res.__class__ is s.__class__
True
__rand__
>>> res = set((3,4,5)) & s
>>> sorted(res)
[3, 4]
>>> res.__class__ is s.__class__
True
__ror__
>>> res = set((3,4,5)) | s
>>> sorted(res)
[0, 1, 2, 3, 4, 5]
>>> res.__class__ is s.__class__
True
__rsub__
>>> res = set((3,4,5)) - s
>>> sorted(res)
[5]
>>> res.__class__ is s.__class__
True
__rxor__
>>> res = set((3,4,5)) ^ s
>>> sorted(res)
[0, 1, 2, 5]
>>> res.__class__ is s.__class__
True
difference
>>> res = s.difference((3,4,5))
>>> sorted(res)
[0, 1, 2]
>>> res.__class__ is s.__class__
True
intersection
>>> res = s.intersection((3,4,5))
>>> sorted(res)
[3, 4]
>>> res.__class__ is s.__class__
True
symmetric_difference
>>> res = s.symmetric_difference((3,4,5))
>>> sorted(res)
[0, 1, 2, 5]
>>> res.__class__ is s.__class__
True
union
>>> res = s.union((3,4,5))
>>> sorted(res)
[0, 1, 2, 3, 4, 5]
>>> res.__class__ is s.__class__
True
copy returns...a copy.
>>> res = s.copy()
>>> res == s
True
>>> res.__class__ is s.__class__
True
| zc.set | /zc.set-0.2.tar.gz/zc.set-0.2/src/zc/set/README.txt | README.txt |
import persistent
import sys
def simpleWrapper(name):
def wrapper(self, *args, **kwargs):
return getattr(self._data, name)(*args, **kwargs)
return wrapper
def mutatingWrapper(name):
def wrapper(self, *args, **kwargs):
res = getattr(self._data, name)(*args, **kwargs)
self._p_changed = True
return res
return wrapper
def mutatingStrippingWrapper(name):
def wrapper(self, other):
if isinstance(other, self.__class__):
other = other._data
getattr(self._data, name)(other)
self._p_changed = True
return self # this is used necessary for all the __i*__, so we have to
# return the mutated value
return wrapper
def persistentOutputWrapper(name):
def wrapper(self, *args, **kwargs):
res = getattr(self._data, name)(*args, **kwargs)
inst = self.__class__()
inst._data = res
return inst
return wrapper
def persistentOutputStrippingWrapper(name, can_reverse=False):
def wrapper(self, other):
if isinstance(other, self.__class__):
other = other._data
try:
meth = getattr(self._data, name)
arg = other
except AttributeError:
# See comments in the call to the outer function
if not can_reverse:
raise
meth = getattr(other, name.replace('__r', '__', 1))
arg = self._data
res = meth(arg)
inst = self.__class__()
inst._data = res
return inst
return wrapper
def strippingWrapper(name):
def wrapper(self, other):
if isinstance(other, self.__class__):
other = other._data
return getattr(self._data, name)(other)
return wrapper
class Set(persistent.Persistent):
def __init__(self, iterable=()):
self._data = set(iterable)
__hash__ = None
for nm in ('__cmp__', '__contains__', '__iter__', '__len__'):
locals()[nm] = simpleWrapper(nm)
for nm in ('__eq__', '__ge__', '__gt__', '__le__', '__lt__', '__ne__',
'issubset', 'issuperset'):
locals()[nm] = strippingWrapper(nm)
for nm in ('difference', 'intersection', 'isdisjoint',
'symmetric_difference', 'union'):
locals()[nm] = persistentOutputWrapper(nm)
for nm in (
'__and__', '__rand__',
'__or__', '__ror__',
'__sub__', '__rsub__',
'__xor__', '__rxor__',
):
# The __rXXX__ methods are not required to be present on the ``set``
# type by the language spec; the only documented requirements
# are the non-reversed versions. Accordingly, PyPy < 7.3 doesn't
# provide them.
locals()[nm] = persistentOutputStrippingWrapper(
nm,
can_reverse=nm.startswith('__r') and not hasattr(set, nm))
for nm in ('add', 'clear', 'difference_update', 'discard',
'intersection_update', 'pop', 'remove',
'symmetric_difference_update', 'update'):
locals()[nm] = mutatingWrapper(nm)
for nm in ('__iand__', '__ior__', '__isub__', '__ixor__'):
locals()[nm] = mutatingStrippingWrapper(nm)
def copy(self):
return self.__class__(self._data)
def __repr__(self):
if sys.version_info < (3,):
# set([1, 2, 3])
items = repr(self._data)[5:-2]
else:
# {1, 2, 3}
items = repr(self._data)[1:-1]
return '%s.%s([%s])' % (
self.__class__.__module__,
self.__class__.__name__,
items) | zc.set | /zc.set-0.2.tar.gz/zc.set-0.2/src/zc/set/__init__.py | __init__.py |
from zope import interface, schema
import zope.app.container.interfaces
import zope.component.interfaces
from zc.shortcut.i18n import _
REPOSITORY_NAME = "shortcutTargetRepository"
NEXT_URL_NAME = "nextURL"
class IShortcut(interface.Interface):
target = interface.Attribute('ITargetProxy of the referred-to object.')
raw_target = interface.Attribute(
'the referred-to object without the ITargetProxy wrapper')
class ITraversalProxy(interface.Interface):
__traversed_parent__ = interface.Attribute(
"Traversed parent of the proxied object.")
__traversed_name__ = schema.TextLine(
title=_("Shortcut name"),
description=_("Name used to traverse to the proxied object from the "
"traversal parent"),
required=False,
default=None,
)
class ITargetProxy(ITraversalProxy):
"""Proxy to an object provided by a shortcut.
This proxy provides some additional information based on the shortcut.
"""
__shortcut__ = interface.Attribute(
"The shortcut for which the proxied object was the target")
class ITraversedURL(interface.Interface):
def __str__():
"""Return a utf-8 encoded string of the traversed URL.
appropriate values are escaped."""
def __unicode__():
"""return unicode of the traversed URL.
values are not escaped"""
class IShortcutPackage(interface.Interface):
def traversedURL(ob, request):
"""return an ITraversedURL for the ob and request"""
class IAdding(zope.app.container.interfaces.IAdding):
"""traversal-aware and enhanced IAdding"""
def action(type_name='', id=''):
"""The same as zope.app's IAdding's action method, except that
redirects use traversedURL instead of absoluteURL."""
def nextURL():
"""tries to get a nextURL by getting a named adapter (the value in the
NEXT_URL_NAME constant above) for the adding, the newly added content
(adding.context[adding.contentName]), and the container
(adding.context). If a nextURL is returned, use it; otherwise, return
the traversedURL of the container + "/@@contents.html". """
class IObjectLinker(interface.Interface):
def linkTo(target, new_name=None):
"""Make a shortcut to this object in the `target` given.
Returns the new name of the shortcut within the `target`.
After the new shortcut is made, publish an IObjectCreated event for
the new shortcut.
"""
def linkable():
"""Returns ``True`` if the object is linkable, otherwise ``False``."""
def linkableTo(target, name=None):
"""Say whether the object can be linked to the given `target`.
Returns ``True`` if it can be linked there. Otherwise, returns
``False``.
"""
class IShortcutTypePrecondition(zope.interface.Interface):
def __call__(container, name, object):
"""Test whether container setitem arguments are valid.
Raise zope.interface.Invalid if the objet is invalid.
"""
def factory(container, name, factory):
"""Test whether objects provided by the factory are acceptable
Return a boolean value.
"""
class IShortcutFactory(zope.component.interfaces.IFactory):
"""factory that creats in a repository and returns a shortcut
getInterfaces should always return IShortcut.
"""
def getTargetInterfaces():
"return interfaces that the target will implement" | zc.shortcut | /zc.shortcut-1.0.tar.gz/zc.shortcut-1.0/src/zc/shortcut/interfaces.py | interfaces.py |
import urllib
from zope import interface, component, event
import zope.proxy
from zope.security.proxy import removeSecurityProxy
import zope.publisher.interfaces.browser
from zope.publisher.interfaces.browser import IBrowserRequest
from zope.publisher.interfaces.http import IHTTPRequest
from zope.location.pickling import locationCopy
from zope.dublincore.interfaces import IZopeDublinCore
from zope.lifecycleevent import ObjectCopiedEvent, ObjectCreatedEvent
from zope.size.interfaces import ISized
from zope.traversing.interfaces import ITraversable, IContainmentRoot
from zope.publisher.browser import BrowserView
from zope import copypastemove
from zope.app.container.constraints import checkObject
from zope.app.container.interfaces import INameChooser, IContainer
import zc.displayname.interfaces
from zc.displayname.adapters import INSUFFICIENT_CONTEXT
from zc.shortcut import interfaces, proxy, Shortcut
from zc.shortcut.i18n import _
_safe = '@+' # Characters that we don't want to have quoted
class MetaAdapter:
"""A helper that makes it easy for shortcuts to delegate adapters."""
def __init__(self, i):
self.interface = i
def __call__(self, shortcut):
return self.interface(shortcut.target, None)
ShortcutSizedAdapterFactory = MetaAdapter(ISized)
ShortcutZopeDoublinCoreAdapterFactory = MetaAdapter(IZopeDublinCore)
@component.adapter(interfaces.IShortcut, zope.publisher.interfaces.IRequest)
@interface.implementer(ITraversable)
def ShortcutTraversalAdapterFactory(shortcut, request):
return component.getMultiAdapter((shortcut.target, request),
ITraversable, 'view')
@component.adapter(interfaces.IShortcut, zope.publisher.interfaces.IRequest)
@interface.implementer(interface.Interface)
def ShortcutZMIIconFactory(shortcut, request):
return component.queryMultiAdapter(
(shortcut.target, request), name='zmi_icon')
def traverseTargetProxiedObject(object, request, name):
if zope.publisher.interfaces.IPublishTraverse.providedBy(object):
traverser = object
else:
# we have to do a careful dance in order to avoid looking up
# ourselves.
site = component.getSiteManager()
adapters = site.adapters # IAdapterRegistry
required = (interface.providedBy(proxy.removeProxy(object)),
interface.providedBy(request))
provided = zope.publisher.interfaces.IPublishTraverse
lookup_name = ''
factory = adapters.lookup(required, provided, lookup_name)
traverser = factory(object, request)
res = traverser.publishTraverse(request, name)
res = removeSecurityProxy(res) # this is necessary because otherwise
# code elsewhere (such as in our security machinery) cannot remove security
# proxies as it expects to because they are hidden within shortcut proxies.
if interfaces.IShortcut.providedBy(res):
res = proxy.ShortcutProxy(res, object, res.__name__)
else:
res = proxy.Proxy(res, object, res.__name__)
return res
class ShortcutPublishTraverseAdapter(object):
interface.implements(zope.publisher.interfaces.browser.IBrowserPublisher)
component.adapts(interfaces.IShortcut, IBrowserRequest)
def __init__(self, context, request):
self.context = context
def browserDefault(self, request):
ob = self.context.target
adapter = component.getMultiAdapter(
(ob, request),
zope.publisher.interfaces.browser.IBrowserPublisher)
return adapter.browserDefault(request)
def publishTraverse(self, request, name):
return traverseTargetProxiedObject(self.context.target, request, name)
class ProxyPublishTraverseAdapter(object):
interface.implements(zope.publisher.interfaces.IPublishTraverse)
component.adapts(interfaces.ITraversalProxy, IBrowserRequest)
def __init__(self, context, request):
self.context = context
def publishTraverse(self, request, name):
context = self.context
if interfaces.IShortcut.providedBy(context):
# optimization for a proxied shortcut;
# it also removes a source of problematic security proxies.
context = context.target
return traverseTargetProxiedObject(context, request, name)
@component.adapter(None, IHTTPRequest)
@interface.implementer(interface.Interface)
def traversedURL(ob, request):
return str(zope.component.getMultiAdapter((ob, request),
interfaces.ITraversedURL))
class TraversedURL(BrowserView):
interface.implementsOnly(interfaces.ITraversedURL)
component.adapts(interfaces.ITraversalProxy, IHTTPRequest)
def __unicode__(self):
return urllib.unquote(self.__str__()).decode('utf-8')
def __str__(self):
context = self.context
request = self.request
# The application URL contains all the namespaces that are at the
# beginning of the URL, such as skins, virtual host specifications and
# so on.
if zope.proxy.sameProxiedObjects(
context, request.getVirtualHostRoot()):
return request.getApplicationURL()
parent = context.__traversed_parent__
if parent is None:
raise TypeError, INSUFFICIENT_CONTEXT
url = str(zope.component.getMultiAdapter((parent, request),
interfaces.ITraversedURL))
name = context.__traversed_name__
if name is None:
raise TypeError, INSUFFICIENT_CONTEXT
if name:
url += '/' + urllib.quote(name.encode('utf-8'), _safe)
return url
class FallbackTraversedURL(BrowserView):
interface.implementsOnly(interfaces.ITraversedURL)
component.adapts(interface.Interface, IHTTPRequest)
def __unicode__(self):
return urllib.unquote(self.__str__()).decode('utf-8')
def __str__(self):
context = self.context
request = self.request
# The application URL contains all the namespaces that are at the
# beginning of the URL, such as skins, virtual host specifications and
# so on.
if zope.proxy.sameProxiedObjects(
context, request.getVirtualHostRoot()):
return request.getApplicationURL()
parent = getattr(context, '__parent__', None)
if parent is None:
raise TypeError, INSUFFICIENT_CONTEXT
url = str(zope.component.getMultiAdapter((parent, request),
interfaces.ITraversedURL))
name = getattr(context, '__name__', None)
if name is None:
raise TypeError, INSUFFICIENT_CONTEXT
if name:
url += '/' + urllib.quote(name.encode('utf-8'), _safe)
return url
class RootTraversedURL(BrowserView):
interface.implementsOnly(interfaces.ITraversedURL)
component.adapts(IContainmentRoot, IHTTPRequest)
def __unicode__(self):
return urllib.unquote(self.__str__()).decode('utf-8')
def __str__(self):
context = self.context
request = self.request
if zope.proxy.sameProxiedObjects(
context, request.getVirtualHostRoot()):
return request.getApplicationURL()
url = request.getApplicationURL()
name = getattr(context, '__name__', None)
if name:
url += '/' + urllib.quote(name.encode('utf-8'), _safe)
return url
class Breadcrumbs(BrowserView):
interface.implementsOnly(zc.displayname.interfaces.IBreadcrumbs)
component.adapts(interfaces.ITraversalProxy, IHTTPRequest)
def __call__(self, maxlength=None):
context = self.context
request = self.request
if zope.proxy.sameProxiedObjects(
context, request.getVirtualHostRoot()):
base = ()
else:
container = context.__traversed_parent__
view = component.getMultiAdapter(
(container, request), zc.displayname.interfaces.IBreadcrumbs)
base = tuple(view(maxlength))
name_gen = component.getMultiAdapter(
(context, request),
zc.displayname.interfaces.IDisplayNameGenerator)
url = traversedURL(context, request)
return base + (
{"name_gen": name_gen, "url": url, "name": name_gen(maxlength),
"object": context},)
# this will probably never be used, because targets are the things for which
# we generally get display names (in breadcrumbs, for instance). Included
# for completeness.
@component.adapter(
interfaces.IShortcut, zope.publisher.interfaces.IRequest)
@interface.implementer(zc.displayname.interfaces.IDisplayNameGenerator)
def ShortcutDisplayNameGenerator(context, request):
return component.getMultiAdapter(
(context.target, request),
zc.displayname.interfaces.IDisplayNameGenerator)
# cutcopypaste
class ObjectCopier(copypastemove.ObjectCopier):
"""This is identical to the usual object copier, except that if the object
is supposed to be created in a repository, it will be copied there and
place a shortcut to the new object in context."""
interface.implements(copypastemove.IObjectCopier)
component.adapts(interface.Interface)
def copyTo(self, target, new_name=None):
obj = self.context
container = obj.__parent__
orig_name = obj.__name__
if new_name is None:
new_name = orig_name
chooser = INameChooser(target)
new_name = chooser.chooseName(new_name, obj)
if not self.copyableTo(target, new_name):
raise interface.Invalid(
"Not copyableTo target with name", target, new_name)
copy = locationCopy(obj)
copy.__parent__ = copy.__name__ = None
event.notify(ObjectCopiedEvent(copy, obj))
repository = component.queryAdapter(
copy, IContainer, interfaces.REPOSITORY_NAME)
if repository is not None:
chooser = INameChooser(repository)
repo_name = chooser.chooseName(new_name, copy)
checkObject(repository, repo_name, copy)
repository[repo_name] = copy
shortcut = Shortcut(repository[repo_name]) # __getitem__ gets the
# ContainedProxy, if it was used
event.notify(ObjectCreatedEvent(shortcut))
target[new_name] = shortcut
else:
target[new_name] = copy
return new_name
# link interface.
class ObjectLinkerAdapter(object):
interface.implements(interfaces.IObjectLinker)
component.adapts(interface.Interface)
def __init__(self, context):
self.context = context
def linkTo(self, target, new_name=None):
obj = self.context
container = obj.__parent__
orig_name = obj.__name__
if new_name is None:
new_name = orig_name
chooser = INameChooser(target)
sc = self._createShortcut(obj)
new_name = chooser.chooseName(new_name, sc)
if not self.linkableTo(target, new_name):
raise interface.Invalid(
"Not linkableTo target with name", target, new_name)
event.notify(ObjectCreatedEvent(sc))
target[new_name] = sc
return new_name
def linkable(self):
return True
def linkableTo(self, target, name=None):
if name is None:
name = self.context.__name__
try:
checkObject(target, name, self._createShortcut(self.context))
except interface.Invalid:
return False
return True
def _createShortcut(self, target):
return Shortcut(target)
class ShortcutLinkerAdapter(object):
"""Linker that generates links based on shortcuts.
Links created are copies of the original shortcuts, so have any
associated attribute annotations or other information provided by
specialized shortcut implementations. The resulting shortcut is
not expected to be associated with the original shortcut in any
way, and refers directly to the target of the original shortcut.
"""
interface.implements(interfaces.IObjectLinker)
component.adapts(interfaces.IShortcut)
def __init__(self, context):
self.context = context
self.copier = copypastemove.IObjectCopier(removeSecurityProxy(context))
def linkTo(self, target, new_name=None):
try:
return self.copier.copyTo(target, new_name)
except interface.Invalid, e:
raise interface.Invalid("Not linkableTo target with name",
target, e.args[2])
def linkable(self):
return self.copier.copyable()
def linkableTo(self, target, name=None):
return self.copier.copyableTo(target, name)
# extra tricks
class ObjectCopierLinkingAdapter(object):
"""An object copier adapter that actually makes shortcuts, not clones"""
interface.implements(copypastemove.IObjectCopier)
# component.adapts deliberately not set; this is expected to be registered
# for certain specific interfaces.
def __init__(self, context):
self.context = context
def copyTo(self, target, new_name=None):
obj = self.context
container = obj.__parent__
orig_name = obj.__name__
if new_name is None:
new_name = orig_name
chooser = INameChooser(target)
sc = Shortcut(obj)
new_name = chooser.chooseName(new_name, sc)
if not self.copyableTo(target, new_name):
raise interface.Invalid(
"Not copyableTo target with name", target, new_name)
# the shortcut is created, not copied
event.notify(ObjectCreatedEvent(sc))
target[new_name] = sc
return new_name
def copyable(self):
return True
def copyableTo(self, target, name=None):
if name is None:
name = self.context.__name__
try:
checkObject(target, name, Shortcut(self.context))
except interface.Invalid:
return False
return True | zc.shortcut | /zc.shortcut-1.0.tar.gz/zc.shortcut-1.0/src/zc/shortcut/adapters.py | adapters.py |
from zope import interface, proxy
from zope.interface import declarations
try:
from zope.security.decorator import DecoratedSecurityCheckerDescriptor
except ImportError:
# BBB 2006/09/25 -- to be removed when Zope 3.3 is not supported any more.
from zope.decorator import DecoratedSecurityCheckerDescriptor
from zc.shortcut import interfaces
class DecoratorSpecificationDescriptor(
declarations.ObjectSpecificationDescriptor):
"""interface declarations on decorators that wish to have their interfaces
be the most specific, rather than the least (as in
DecoratorSpecificationDescriptor)."""
def __get__(self, inst, cls=None):
if inst is None:
return declarations.getObjectSpecification(cls)
else:
provided = interface.providedBy(proxy.getProxiedObject(inst))
# Use type rather than __class__ because inst is a proxy and
# will return the proxied object's class.
dec_impl = interface.implementedBy(type(inst))
return declarations.Declaration(dec_impl, provided)
def __set__(self, inst, v):
raise TypeError("assignment not allowed")
class Decorator(proxy.ProxyBase):
"Overriding specification decorator base class"
__providedBy__ = DecoratorSpecificationDescriptor()
__Security_checker__ = DecoratedSecurityCheckerDescriptor()
class DecoratorProvidesDescriptor(object):
def __get__(self, inst, cls):
if inst is None:
# We were accessed through a class, so we are the class'
# provides spec. Just return this object as is:
return self
return proxy.getProxiedObject(inst).__provides__
def __set__(self, inst, value):
proxy.getProxiedObject(inst).__provides__ = value
def __delete__(self, inst):
del proxy.getProxiedObject(inst).__provides__
def proxyImplements(cls, *interfaces):
interface.classImplements(cls, *interfaces)
if type(cls.__provides__) is not DecoratorProvidesDescriptor:
cls.__provides__ = DecoratorProvidesDescriptor()
def implements(*interfaces):
declarations._implements("implements", interfaces, proxyImplements)
class ClassAndInstanceDescr(object):
def __init__(self, *args):
self.funcs = args
def __get__(self, inst, cls):
if inst is None:
return self.funcs[1](cls)
return self.funcs[0](inst)
def __set__(self, inst, v):
raise TypeError("assignment not allowed")
class ProxyBase(proxy.ProxyBase):
__slots__ = '__traversed_parent__', '__traversed_name__'
def __new__(self, ob, parent, name):
return proxy.ProxyBase.__new__(self, ob)
def __init__(self, ob, parent, name):
proxy.ProxyBase.__init__(self, ob)
self.__traversed_parent__ = parent
self.__traversed_name__ = name
__doc__ = ClassAndInstanceDescr(
lambda inst: proxy.getProxiedObject(inst).__doc__,
lambda cls, __doc__ = __doc__: __doc__,
)
__providedBy__ = DecoratorSpecificationDescriptor()
__Security_checker__ = DecoratedSecurityCheckerDescriptor()
class Proxy(ProxyBase):
implements(interfaces.ITraversalProxy)
class TargetProxy(ProxyBase):
implements(interfaces.ITargetProxy)
__slots__ = '__shortcut__',
def __new__(self, ob, parent, name, shortcut):
return ProxyBase.__new__(self, ob, parent, name)
def __init__(self, ob, parent, name, shortcut):
ProxyBase.__init__(self, ob, parent, name)
self.__shortcut__ = shortcut
class ShortcutProxy(Proxy):
@property
def target(self):
shortcut = proxy.getProxiedObject(self)
return TargetProxy(
shortcut.raw_target, self.__traversed_parent__,
self.__traversed_name__, shortcut)
def removeProxy(obj):
p = proxy.queryInnerProxy(obj, ProxyBase)
if p is None:
return obj
else:
return proxy.getProxiedObject(p) | zc.shortcut | /zc.shortcut-1.0.tar.gz/zc.shortcut-1.0/src/zc/shortcut/proxy.py | proxy.py |
import sys
from zope import interface
from zope.app.container.interfaces import InvalidItemType, IContainer
from zc.shortcut import interfaces, Shortcut
class ShortcutTypePrecondition(object):
"""a `__setitem__` precondition that restricts shortcut target types
Items must be one of the given types.
>>> class I1(interface.Interface):
... pass
>>> class I2(interface.Interface):
... pass
>>> precondition = ShortcutTypePrecondition(I1, I2)
>>> types_precondition = ShortcutTypePrecondition(types=(I1, I2))
>>> mixed_precondition = ShortcutTypePrecondition(I2, types=(I2,))
>>> class Ob(object):
... pass
>>> ob = Ob()
>>> shortcut = Shortcut(ob)
>>> class Factory(object):
... def __call__(self):
... return Ob()
... def getInterfaces(self):
... return interface.implementedBy(Ob)
>>> class ShortcutFactory(object):
... interface.implements(interfaces.IShortcutFactory)
... def __call__(self):
... return Shortcut(Ob())
... def getTargetInterfaces(self):
... return interface.implementedBy(Ob)
... def getInterfaces(self):
... return interface.implementedBy(Shortcut)
>>> factory = Factory()
>>> shortcut_factory = ShortcutFactory()
>>> def check(condition, container, name, obj, expected):
... try:
... condition(container, name, obj)
... except InvalidItemType, v:
... print v[0], (v[1] is obj or v[1]), (v[2] == expected or v[2])
... else:
... print 'Should have failed'
...
>>> check(precondition, None, 'foo', ob, ())
None True True
>>> check(precondition.factory, None, 'foo', factory, ())
None True True
>>> check(types_precondition, None, 'foo', ob, (I1, I2))
None True True
>>> check(types_precondition.factory, None, 'foo', factory, (I1, I2))
None True True
>>> check(mixed_precondition, None, 'foo', ob, (I2,))
None True True
>>> check(mixed_precondition.factory, None, 'foo', factory, (I2,))
None True True
>>> check(precondition, None, 'foo', shortcut, (I1, I2))
None True True
>>> check(precondition.factory, None, 'foo', shortcut_factory, (I1, I2))
None True True
>>> check(types_precondition, None, 'foo', shortcut, ())
None True True
>>> check(types_precondition.factory, None, 'foo', shortcut_factory, ())
None True True
>>> check(mixed_precondition, None, 'foo', shortcut, (I2,))
None True True
>>> check(mixed_precondition.factory, None, 'foo', shortcut_factory, (I2,))
None True True
>>> interface.classImplements(Ob, I2)
>>> precondition(None, 'foo', shortcut)
>>> precondition.factory(None, 'foo', shortcut_factory)
>>> types_precondition(None, 'foo', ob)
>>> types_precondition.factory(None, 'foo', factory)
>>> mixed_precondition(None, 'foo', shortcut)
>>> mixed_precondition(None, 'foo', ob)
>>> mixed_precondition.factory(None, 'foo', shortcut_factory)
>>> mixed_precondition.factory(None, 'foo', factory)
"""
interface.implements(interfaces.IShortcutTypePrecondition)
def __init__(self, *target_types, **kwargs):
self.target_types = target_types
self.types = kwargs.pop('types', ())
if kwargs:
raise TypeError("ShortcutTypePrecondition.__init__ got an "
"unexpected keyword argument '%s'" %
(kwargs.iterkeys().next(),))
def __call__(self, container, name, object):
if interfaces.IShortcut.providedBy(object):
target = object.raw_target
for iface in self.target_types:
if iface.providedBy(target):
return
raise InvalidItemType(container, object, self.target_types)
else:
for iface in self.types:
if iface.providedBy(object):
return
raise InvalidItemType(container, object, self.types)
def factory(self, container, name, factory):
if interfaces.IShortcutFactory.providedBy(factory):
implemented = factory.getTargetInterfaces()
for iface in self.target_types:
if implemented.isOrExtends(iface):
return
raise InvalidItemType(container, factory, self.target_types)
else:
implemented = factory.getInterfaces()
for iface in self.types:
if implemented.isOrExtends(iface):
return
raise InvalidItemType(container, factory, self.types)
def contains(*types, **kwargs):
"""Declare that a container type contains only shortcuts to the given types
This is used within a class suite defining an interface to create
a __setitem__ specification with a precondition allowing only the
given types:
>>> class IFoo(interface.Interface):
... pass
>>> class IBar(interface.Interface):
... pass
>>> class IFooBarContainer(IContainer):
... contains(IFoo, IBar)
>>> __setitem__ = IFooBarContainer['__setitem__']
>>> __setitem__.getTaggedValue('precondition').target_types == (
... IFoo, IBar)
True
It is invalid to call contains outside a class suite:
>>> contains(IFoo, IBar)
Traceback (most recent call last):
...
TypeError: contains not called from suite
"""
frame = sys._getframe(1)
f_locals = frame.f_locals
f_globals = frame.f_globals
if not (f_locals is not f_globals
and f_locals.get('__module__')
and f_locals.get('__module__') == f_globals.get('__name__')
):
raise TypeError("contains not called from suite")
def __setitem__(key, value):
pass
__setitem__.__doc__ = IContainer['__setitem__'].__doc__
__setitem__.precondition = ShortcutTypePrecondition(*types, **kwargs)
f_locals['__setitem__'] = __setitem__ | zc.shortcut | /zc.shortcut-1.0.tar.gz/zc.shortcut-1.0/src/zc/shortcut/constraints.py | constraints.py |
from zope import interface, component
from zope.event import notify
import zope.security.checker
from zope.security.proxy import removeSecurityProxy
from zope.component.interfaces import IFactory
from zope.app.component.hooks import getSite
import zope.app.container.browser.adding
from zope.app.container.constraints import checkObject
from zope.lifecycleevent import ObjectCreatedEvent
from zope.exceptions.interfaces import UserError
from zope.location.interfaces import ILocation
from zope.location import LocationProxy
from zc.shortcut import Shortcut, traversedURL, interfaces
class Adding(zope.app.container.browser.adding.Adding):
interface.implements(interfaces.IAdding)
def action(self, type_name='', id=''):
# copied from zope.app.container.browser.adding.Adding;
# only change is that we use traversedURL, not absoluteURL
if not type_name:
raise UserError(_(u"You must select the type of object to add."))
if type_name.startswith('@@'):
type_name = type_name[2:]
if '/' in type_name:
view_name = type_name.split('/', 1)[0]
else:
view_name = type_name
if component.queryMultiAdapter((self, self.request),
name=view_name) is not None:
url = "%s/@@+/%s=%s" % (
traversedURL(self.context, self.request), type_name, id)
self.request.response.redirect(url)
return
if not self.contentName:
self.contentName = id
# TODO: If the factory wrapped by LocationProxy is already a Proxy,
# then ProxyFactory does not do the right thing and the
# original's checker info gets lost. No factory that was
# registered via ZCML and was used via addMenuItem worked
# here. (SR)
factory = component.getUtility(IFactory, type_name)
if not type(factory) is zope.security.checker.Proxy:
factory = LocationProxy(factory, self, type_name)
factory = zope.security.checker.ProxyFactory(factory)
content = factory()
# Can't store security proxies.
# Note that it is important to do this here, rather than
# in add, otherwise, someone might be able to trick add
# into unproxying an existing object,
content = removeSecurityProxy(content)
notify(ObjectCreatedEvent(content))
self.add(content)
self.request.response.redirect(self.nextURL())
def nextURL(self):
"""See zope.app.container.interfaces.IAdding"""
content = self.context[self.contentName] # this will be a shortcut
# when item was added to a repository
nextURL = component.queryMultiAdapter(
(self, content, self.context), name=interfaces.NEXT_URL_NAME)
if nextURL is None:
nextURL = (
traversedURL(self.context, self.request) + '/@@contents.html')
return nextURL | zc.shortcut | /zc.shortcut-1.0.tar.gz/zc.shortcut-1.0/src/zc/shortcut/adding.py | adding.py |
================
zc.signalhandler
================
This package allows registration of signal handlers from ``ZConfig``
configuration files within the framework provided by the Zope Toolkit.
Any number of handlers may be registered for any given signal.
To use this from your ``zope.conf`` file, ensure this package is
available to your application, and include a section like this::
%import zc.signalhandler
<signalhandlers log-handling>
USR1 ZConfig.components.logger.loghandler.reopenFiles
USR1 yourapp.tasks.doSomethingUseful
</signalhandlers>
See the ``README.txt`` inside the ``zc.signalhandler`` package for
complete documentation.
Release history
===============
1.2 (2010-11-12)
----------------
- Moved development to zope.org, licensed under the ZPL 2.1.
1.1 (2007-06-21)
----------------
This was a Zope Corporation internal release.
- Fix compatibility with ``zope.app.appsetup.product``.
1.0 (2007-06-21)
----------------
Initial Zope Corporation internal release.
| zc.signalhandler | /zc.signalhandler-1.2.0.tar.gz/zc.signalhandler-1.2.0/README.txt | README.txt |
===========================
Registering signal handlers
===========================
This package provides a way to register signal handlers from a ZConfig
configuration. There is a ZConfig component which is converted to a
mapping of signal names to a list of handler functions. The handlers
take no arguments.
The configuration section that provides signal handling information is
considered a "product configuration" section for Zope 3, so let's
create a simple schema that accepts product configurations::
>>> schema_text = '''\
... <schema>
... <abstracttype name="zope.product.base"/>
... <section type="zope.product.base"
... attribute="siginfo"
... name="*"
... />
... </schema>
... '''
>>> import os
>>> import signal
>>> import StringIO
>>> import ZConfig
>>> schema = ZConfig.loadSchemaFile(StringIO.StringIO(schema_text))
A sample configuration can simple import the ``zc.signalhandler``
component and use it::
>>> config_text = '''
...
... %import zc.signalhandler
...
... <signalhandlers foo>
... hup zc.signalhandler.tests.sample_handler_1
... hup zc.signalhandler.tests.sample_handler_2
... usr1 zc.signalhandler.tests.sample_handler_1
... </signalhandlers>
...
... '''
We can install some default behavior for a signal::
>>> def some_behavior(sign, frame):
... print "some old behavior"
>>> old = signal.signal(signal.SIGUSR1, some_behavior)
Let's try loading our sample configuration::
>>> config, config_handlers = ZConfig.loadConfigFile(
... schema, StringIO.StringIO(config_text))
>>> handlers = config.siginfo.handlers
>>> sorted(handlers)
['SIGHUP', 'SIGUSR1']
>>> import zc.signalhandler.tests
>>> h1, h2 = handlers["SIGHUP"]
>>> h1 is zc.signalhandler.tests.sample_handler_1
True
>>> h2 is zc.signalhandler.tests.sample_handler_2
True
>>> h1, = handlers["SIGUSR1"]
>>> h1 is zc.signalhandler.tests.sample_handler_1
True
At this point, the handlers are installed. We can signal ourselves,
and see that the handler is triggered::
>>> os.kill(os.getpid(), signal.SIGUSR1)
handler 1
We can even trigger multiple handlers for a single signal::
>>> os.kill(os.getpid(), signal.SIGHUP)
handler 1
handler 2
We can also uninstall the handlers::
>>> config.siginfo.uninstall()
>>> os.kill(os.getpid(), signal.SIGUSR1)
some old behavior
Now let's restore the previous behavior of the signal::
>>> x = signal.signal(signal.SIGUSR1, old)
The section value provides a couple of attributes that are used solely
to support the ``zope.app.appsetup.product`` APIs::
>>> config.siginfo.getSectionName()
'foo'
>>> config.siginfo.mapping is config.siginfo
True
| zc.signalhandler | /zc.signalhandler-1.2.0.tar.gz/zc.signalhandler-1.2.0/src/zc/signalhandler/README.txt | README.txt |
__docformat__ = "reStructuredText"
import signal
def name2signal(string):
"""Converts a signal name to canonical form.
Signal names are recognized without regard for case:
>>> name2signal('sighup')
'SIGHUP'
>>> name2signal('SigHup')
'SIGHUP'
>>> name2signal('SIGHUP')
'SIGHUP'
The leading 'SIG' is not required::
>>> name2signal('hup')
'SIGHUP'
>>> name2signal('HUP')
'SIGHUP'
Names that are not known cause an exception to be raised::
>>> name2signal('woohoo')
Traceback (most recent call last):
ValueError: could not convert 'woohoo' to signal name
>>> name2signal('sigwoohoo')
Traceback (most recent call last):
ValueError: could not convert 'sigwoohoo' to signal name
Numeric values are converted to names as well::
>>> name2signal(str(signal.SIGHUP))
'SIGHUP'
Numeric values that can't be matched to any signal known to Python
are treated as errors::
>>> name2signal('-234')
Traceback (most recent call last):
ValueError: unsupported signal on this platform: -234
>>> name2signal(str(signal.NSIG)) #doctest: +ELLIPSIS
Traceback (most recent call last):
ValueError: unsupported signal on this platform: ...
Non-signal attributes of the signal module are not mistakenly
converted::
>>> name2signal('_ign')
Traceback (most recent call last):
ValueError: could not convert '_ign' to signal name
>>> name2signal('_DFL')
Traceback (most recent call last):
ValueError: could not convert '_DFL' to signal name
>>> name2signal('sig_ign')
Traceback (most recent call last):
ValueError: could not convert 'sig_ign' to signal name
>>> name2signal('SIG_DFL')
Traceback (most recent call last):
ValueError: could not convert 'SIG_DFL' to signal name
>>> name2signal('getsignal')
Traceback (most recent call last):
ValueError: could not convert 'getsignal' to signal name
"""
try:
v = int(string)
except ValueError:
if "_" in string:
raise ValueError("could not convert %r to signal name" % string)
s = string.upper()
if not s.startswith("SIG"):
s = "SIG" + s
v = getattr(signal, s, None)
if isinstance(v, int):
return s
raise ValueError("could not convert %r to signal name" % string)
if v >= signal.NSIG:
raise ValueError("unsupported signal on this platform: %s" % string)
for name in dir(signal):
if "_" in name:
continue
if getattr(signal, name) == v:
return name
raise ValueError("unsupported signal on this platform: %s" % string)
class SignalHandlers(object):
def __init__(self, section):
self.handlers = section.mapping
self.name = section.getSectionName()
# Convert to an isolated signalnum->[handlers] mapping:
self._handlers = {}
self._oldhandlers = {}
for name in self.handlers:
signalnum = getattr(signal, name)
self._handlers[signalnum] = self.handlers[name][:]
self.install()
def install(self):
if not self.installed:
for signum in self._handlers:
old = signal.signal(signum, self._dispatch)
self._oldhandlers[signum] = old
def uninstall(self):
while self._oldhandlers:
signum, handler = self._oldhandlers.popitem()
signal.signal(signum, handler)
@property
def installed(self):
return self._oldhandlers
def _dispatch(self, signum, frame):
for f in self._handlers[signum]:
f()
# HACK: Thse are needed to keep zope.app.appsetup.product happy.
def getSectionName(self):
return self.name
@property
def mapping(self):
return self | zc.signalhandler | /zc.signalhandler-1.2.0.tar.gz/zc.signalhandler-1.2.0/src/zc/signalhandler/datatypes.py | datatypes.py |
__docformat__ = "reStructuredText"
import zope.interface
import zope.schema.interfaces
class ISourceFactory(zope.interface.Interface):
def __call__():
"""Create and return the source or source binder."""
class IFactoredSource(zope.schema.interfaces.IIterableSource):
"""An iterable source that was created from a source factory."""
factory = zope.interface.Attribute("The source factory.")
class IContextualSource(IFactoredSource):
"""A source operating in context."""
context = zope.interface.Attribute("The context the source is bound to.")
factory = zope.interface.Attribute("The source factory.")
class INamedSource(zope.interface.Interface):
"""A marker interface to register named source for."""
class IToken(zope.interface.Interface):
"""A string representing a token that uniquely identifies a value."""
# Policies
class ITokenPolicy(zope.interface.Interface):
"""The token policy maps values and tokens."""
def getValue(source, token):
"""Return a token for the value."""
def getToken(value):
"""Return a token for the value."""
class IContextualTokenPolicy(zope.interface.Interface):
"""The contextua token policy maps values and tokens.
It allows access to the context.
"""
def getValue(context, source, token):
"""Return a token for the value."""
def getToken(context, value):
"""Return a token for the value."""
class ITermPolicy(zope.interface.Interface):
"""The term policy creates terms and provides data for terms."""
def createTerm(source, value, title, token, request):
"""Create and return a term object."""
def getTitle(value):
"""Return a title for the value.
The return value should not be localized; that is the
responsibility of the user. The title may be an
internationalized message value.
"""
class IContextualTermPolicy(zope.interface.Interface):
"""The contextual term policy creates terms and provides data for terms.
It allows access to the context.
"""
def createTerm(context, source, value, title, token, request):
"""Create and return a term object."""
def getTitle(context, value):
"""Return a title for the value.
The return value should not be localized; that is the
responsibility of the user. The title may be an
internationalized message value.
"""
class IValuePolicy(zope.interface.Interface):
"""The value policy retrieves and filters values for a source."""
def getValues():
"""Return the values for the source."""
def filterValue(value):
"""Determine whether the value should be filtered out or not."""
class IContextualValuePolicy(zope.interface.Interface):
"""The contextual value policy retrieves and filters values for a source
within context.
"""
def getValues(context):
"""Return the values for the source in the given context."""
def filterValue(context, value):
"""Return the values for the source in the given context."""
# Standard combined policies
class ISourcePolicy(ITokenPolicy, ITermPolicy, IValuePolicy):
pass
class IContextualSourcePolicy(
ITokenPolicy, IContextualTermPolicy, IContextualValuePolicy):
pass | zc.sourcefactory | /zc.sourcefactory-2.0-py3-none-any.whl/zc/sourcefactory/interfaces.py | interfaces.py |
__docformat__ = "reStructuredText"
import zope.component
import zope.intid.interfaces
from zope.dublincore import interfaces as dublincoreinterfaces
import zc.sourcefactory.browser.source
import zc.sourcefactory.interfaces
# Term policies
@zope.interface.implementer(zc.sourcefactory.interfaces.ITermPolicy)
class BasicTermPolicy:
"""A basic term policy.
createTerm creates a FactoredTerm object.
getTitle uses IDCDescriptiveProperties.title and falls back to
`str`-representation of the value.
"""
def createTerm(self, source, value, title, token, request):
return zc.sourcefactory.browser.source.FactoredTerm(
value, title, token)
def getTitle(self, value):
try:
md = dublincoreinterfaces.IDCDescriptiveProperties(value)
except TypeError:
md = None
if md:
title = md.title
elif isinstance(value, bytes):
title = value.decode()
else:
title = str(value)
return title
@zope.interface.implementer(zc.sourcefactory.interfaces.ITermPolicy)
class BasicContextualTermPolicy(BasicTermPolicy):
"""A basic contextual term policy.
All methods are deferred to the BasicTermPolicy by removing the context
argument.
"""
def createTerm(self, context, source, value, title, token, request):
return super().createTerm(
source, value, title, token, request)
def getTitle(self, context, value):
return super().getTitle(value)
# Token policies
@zope.interface.implementer(zc.sourcefactory.interfaces.ITokenPolicy)
class BasicTokenPolicy:
"""A basic token policy.
getToken adapts the value to IToken
getValue iterates over the source comparing the tokens of the values to the
token.
"""
def getValue(self, source, token):
for value in source:
if source.factory.getToken(value) == token:
return value
raise KeyError("No value with token '%s'" % token)
def getToken(self, value):
return zc.sourcefactory.interfaces.IToken(value)
@zope.interface.implementer(zc.sourcefactory.interfaces.IContextualTokenPolicy)
class BasicContextualTokenPolicy(BasicTokenPolicy):
"""A basic contextual token policy.
This implements a fallback to the context-free token policy but satisfies
the contextual interfaces.
"""
def getValue(self, context, source, token):
for value in source:
if source.factory.getToken(context, value) == token:
return value
raise KeyError("No value with token '%s'" % token)
def getToken(self, context, value):
return super().getToken(value)
@zope.interface.implementer(zc.sourcefactory.interfaces.ITokenPolicy)
class IntIdTokenPolicy:
"""A token policy based on intids."""
def getValue(self, source, token):
iid = int(token)
value = self.intids.getObject(iid)
if value in self.source:
return value
else:
raise LookupError("no value matching token: %r" % token)
def getToken(self, value):
return str(self.intids.getId(value))
# We can't use zope.cachedescriptors.property.Lazy for this since
# the source factory exists across the entire process, and is used
# across different requests. Using Lazy for this would result in
# the wrong ZODB connection being used in most threads.
#
@property
def intids(self):
return zope.component.getUtility(
zope.intid.interfaces.IIntIds)
# Value policies
@zope.interface.implementer(zc.sourcefactory.interfaces.IValuePolicy)
class BasicValuePolicy:
"""An abstract basic value policy.
`getValues()` is not implemented.
The filter allows all values.
"""
def filterValue(self, value):
return True
@zope.interface.implementer(
zc.sourcefactory.interfaces.IContextualValuePolicy)
class BasicContextualValuePolicy(BasicValuePolicy):
"""An abstract basic value policy.
`getValues()` is not implemented.
The filter allows all values.
"""
def filterValue(self, context, value):
return True
# Standard combined policies
class BasicSourcePolicy(BasicValuePolicy, BasicTokenPolicy, BasicTermPolicy):
pass
class BasicContextualSourcePolicy(
BasicContextualValuePolicy,
BasicContextualTokenPolicy,
BasicContextualTermPolicy):
pass
class IntIdSourcePolicy(BasicValuePolicy, IntIdTokenPolicy, BasicTermPolicy):
pass | zc.sourcefactory | /zc.sourcefactory-2.0-py3-none-any.whl/zc/sourcefactory/policies.py | policies.py |
Simple case
===========
In the most simple case, you only have to provide a method that returns a list
of values and derive from `BasicSourceFactory`:
>>> import zc.sourcefactory.basic
>>> class MyStaticSource(zc.sourcefactory.basic.BasicSourceFactory):
... def getValues(self):
... return ['a', 'b', 'c']
When calling the source factory, we get a source:
>>> source = MyStaticSource()
>>> import zope.schema.interfaces
>>> zope.schema.interfaces.ISource.providedBy(source)
True
The values match our `getValues`-method of the factory:
>>> list(source)
['a', 'b', 'c']
>>> 'a' in source
True
>>> len(source)
3
Contextual sources
==================
Sometimes we need context to determine the values. In this case, the
`getValues`-method gets a parameter `context`.
Let's assume we have a small object containing data to be used by the source:
>>> class Context(object):
... values = []
>>> import zc.sourcefactory.contextual
>>> class MyDynamicSource(
... zc.sourcefactory.contextual.BasicContextualSourceFactory):
... def getValues(self, context):
... return context.values
When instanciating, we get a ContextSourceBinder:
>>> binder = MyDynamicSource()
>>> zope.schema.interfaces.IContextSourceBinder.providedBy(binder)
True
Binding it to a context, we get a source:
>>> context = Context()
>>> source = binder(context)
>>> zope.schema.interfaces.ISource.providedBy(source)
True
>>> list(source)
[]
Modifying the context also modifies the data in the source:
>>> context.values = [1,2,3,4]
>>> list(source)
[1, 2, 3, 4]
>>> 1 in source
True
>>> len(source)
4
It's possible to have the default machinery return different sources, by
providing a source_class argument when calling the binder. One can also
provide arguments to the source.
>>> class MultiplierSource(zc.sourcefactory.source.FactoredContextualSource):
... def __init__(self, factory, context, multiplier):
... super(MultiplierSource, self).__init__(factory, context)
... self.multiplier = multiplier
...
... def _get_filtered_values(self):
... for value in self.factory.getValues(self.context):
... yield self.multiplier * value
>>> class MultiplierSourceFactory(MyDynamicSource):
... source_class = MultiplierSource
>>> binder = MultiplierSourceFactory()
>>> source = binder(context, multiplier=5)
>>> list(source)
[5, 10, 15, 20]
>>> 5 in source
True
>>> len(source)
4
Filtering
=========
Additional to providing the `getValues`-method you can also provide a
`filterValue`-method that will allow you to reduce the items from the list,
piece by piece.
This is useful if you want to have more specific sources (by subclassing) that
share the same basic origin of the data but have different filters applied to
it:
>>> class FilteringSource(zc.sourcefactory.basic.BasicSourceFactory):
... def getValues(self):
... return iter(range(1,20))
... def filterValue(self, value):
... return value % 2
>>> source = FilteringSource()
>>> list(source)
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
Subclassing modifies the filter, not the original data:
>>> class OtherFilteringSource(FilteringSource):
... def filterValue(self, value):
... return not value % 2
>>> source = OtherFilteringSource()
>>> list(source)
[2, 4, 6, 8, 10, 12, 14, 16, 18]
The "in" operator gets applied also to filtered values:
>>> 2 in source
True
>>> 3 in source
False
The "len" also gets applied to filtered values:
>>> len(source)
9
Scaling
=======
Sometimes the number of items available through a source is very large. So
large that you only want to access them if absolutely neccesary. One such
occasion is with truth-testing a source. By default Python will call
__nonzero__ to get the boolean value of an object, but if that isn't available
__len__ is called to see what it returns. That might be very expensive, so we
want to make sure it isn't called.
>>> class MyExpensiveSource(zc.sourcefactory.basic.BasicSourceFactory):
... def getValues(self):
... yield 'a'
... raise RuntimeError('oops, iterated too far')
>>> source = MyExpensiveSource()
>>> bool(source)
True
Simple case
===========
In the most simple case, you only have to provide a method that returns a list
of values and derive from `BasicSourceFactory`:
>>> import zc.sourcefactory.basic
>>> class MyStaticSource(zc.sourcefactory.basic.BasicSourceFactory):
... def getValues(self):
... return ['a', 'b', 'c']
When calling the source factory, we get a source:
>>> source = MyStaticSource()
>>> import zope.schema.interfaces
>>> zope.schema.interfaces.ISource.providedBy(source)
True
The values match our `getValues`-method of the factory:
>>> list(source)
['a', 'b', 'c']
>>> 'a' in source
True
>>> len(source)
3
WARNING about the standard adapters for ITerms
==============================================
The standard adapters for ITerms are only suitable if the value types returned
by your `getValues` function are homogenous. Mixing integers, persistent
objects, strings, and unicode within one source may create non-unique tokens.
In this case, you have to provide a custom `getToken`-method to provide unique
and unambigous tokens.
| zc.sourcefactory | /zc.sourcefactory-2.0-py3-none-any.whl/zc/sourcefactory/README.txt | README.txt |
=====================================================
Browser views for sources created by source factories
=====================================================
Sources that were created using source factories already come with ready-made
terms and term objects.
Simple use
==========
Let's start with a simple source factory:
>>> import zc.sourcefactory.basic
>>> class DemoSource(zc.sourcefactory.basic.BasicSourceFactory):
... def getValues(self):
... return [b'a', b'b', b'c', b'd']
>>> source = DemoSource()
>>> list(source)
[b'a', b'b', b'c', b'd']
We need a request first, then we can adapt the source to ITerms:
>>> from zope.publisher.browser import TestRequest
>>> import zope.browser.interfaces
>>> import zope.component
>>> request = TestRequest()
>>> terms = zope.component.getMultiAdapter(
... (source, request), zope.browser.interfaces.ITerms)
>>> terms
<zc.sourcefactory.browser.source.FactoredTerms object at 0x...>
For each value we get a factored term:
>>> terms.getTerm(b'a')
<zc.sourcefactory.browser.source.FactoredTerm object at 0x...>
>>> terms.getTerm(b'b')
<zc.sourcefactory.browser.source.FactoredTerm object at 0x...>
>>> terms.getTerm(b'c')
<zc.sourcefactory.browser.source.FactoredTerm object at 0x...>
>>> terms.getTerm(b'd')
<zc.sourcefactory.browser.source.FactoredTerm object at 0x...>
Unicode values are allowed as well:
>>> terms.getTerm('\xd3')
<zc.sourcefactory.browser.source.FactoredTerm object at 0x...>
Our terms are ITitledTokenizedTerm-compatible:
>>> import zope.schema.interfaces
>>> zope.schema.interfaces.ITitledTokenizedTerm.providedBy(
... terms.getTerm('a'))
True
In the most simple case, the title of a term is the string representation of
the object:
>>> terms.getTerm('a').title
'a'
If an adapter from the value to IDCDescriptiveProperties exists, the title
will be retrieved from this adapter:
>>> import persistent
>>> class MyObject(persistent.Persistent):
... custom_title = 'My custom title'
... _p_oid = 12
>>> class DCDescriptivePropertiesAdapter(object):
... def __init__(self, context):
... self.title = context.custom_title
... self.description = u""
>>> from zope.component import provideAdapter
>>> from zope.dublincore.interfaces import IDCDescriptiveProperties
>>> provideAdapter(DCDescriptivePropertiesAdapter, [MyObject],
... IDCDescriptiveProperties)
>>> terms.getTerm(MyObject()).title
'My custom title'
Extended use: provide your own titles
=====================================
Instead of relying on string representation or IDCDescriptiveProperties
adapters you can specify the `getTitle` method on the source factory to
determine the title for a value:
>>> class DemoSourceWithTitles(DemoSource):
... def getTitle(self, value):
... return 'Custom title ' + value.custom_title
>>> source2 = DemoSourceWithTitles()
>>> terms2 = zope.component.getMultiAdapter(
... (source2, request), zope.browser.interfaces.ITerms)
>>> o1 = MyObject()
>>> o1.custom_title = u"Object one"
>>> o2 = MyObject()
>>> o2.custom_title = u"Object two"
>>> terms2.getTerm(o1).title
'Custom title Object one'
>>> terms2.getTerm(o2).title
'Custom title Object two'
Extended use: provide your own tokens
=====================================
Instead of relying on default adapters to generate tokens for your values, you
can override the `getToken` method on the source factory to determine the
token for a value:
>>> class DemoObjectWithToken(object):
... token = None
>>> o1 = DemoObjectWithToken()
>>> o1.token = "one"
>>> o2 = DemoObjectWithToken()
>>> o2.token = "two"
>>> class DemoSourceWithTokens(DemoSource):
... values = [o1, o2]
... def getValues(self):
... return self.values
... def getToken(self, value):
... return value.token
>>> source3 = DemoSourceWithTokens()
>>> terms3 = zope.component.getMultiAdapter(
... (source3, request), zope.browser.interfaces.ITerms)
>>> terms3.getTerm(o1).token
'one'
>>> terms3.getTerm(o2).token
'two'
Looking up by the custom tokens works as well:
>>> terms3.getValue("one") is o1
True
>>> terms3.getValue("two") is o2
True
>>> terms3.getValue("three")
Traceback (most recent call last):
KeyError: "No value with token 'three'"
Value mapping sources
=====================
XXX to come
Contextual sources
==================
Let's start with an object that we can use as the context:
>>> zip_to_city = {'06112': 'Halle',
... '06844': 'Dessa'}
>>> import zc.sourcefactory.contextual
>>> class DemoContextualSource(
... zc.sourcefactory.contextual.BasicContextualSourceFactory):
... def getValues(self, context):
... return context.keys()
... def getTitle(self, context, value):
... return context[value]
... def getToken(self, context, value):
... return 'token-%s' % value
>>> source = DemoContextualSource()(zip_to_city)
>>> sorted(list(source))
['06112', '06844']
Let's look at the terms:
>>> terms = zope.component.getMultiAdapter(
... (source, request), zope.browser.interfaces.ITerms)
>>> terms
<zc.sourcefactory.browser.source.FactoredContextualTerms object at 0x...>
For each value we get a factored term with the right title from the context:
>>> terms.getTerm('06112')
<zc.sourcefactory.browser.source.FactoredTerm object at 0x...>
>>> terms.getTerm('06112').title
'Halle'
>>> terms.getTerm('06844')
<zc.sourcefactory.browser.source.FactoredTerm object at 0x...>
>>> terms.getTerm('06844').title
'Dessa'
>>> terms.getTerm('06844').token
'token-06844'
And in reverse we can get the value for a given token as well:
>>> terms.getValue('token-06844')
'06844'
Interfaces
==========
Both the FactoredSource and FactoredContextualSource have associated
interfaces.
>>> from zc.sourcefactory import interfaces
>>> from zc.sourcefactory import source
>>> from zope import interface
>>> interface.classImplements(
... source.FactoredSource, interfaces.IFactoredSource)
>>> interface.classImplements(
... source.FactoredContextualSource, interfaces.IContextualSource)
| zc.sourcefactory | /zc.sourcefactory-2.0-py3-none-any.whl/zc/sourcefactory/browser/README.txt | README.txt |
"""Various token adapters.
"""
import hashlib
import persistent.interfaces
import ZODB.interfaces
import ZODB.utils
import zope.component
import zope.interface
import zope.proxy
import zc.sourcefactory.interfaces
@zope.component.adapter(bytes)
@zope.interface.implementer(zc.sourcefactory.interfaces.IToken)
def fromString(value):
# We hash generic strings to be sure they are suitable
# for URL encoding.
if not isinstance(value, bytes):
value = value.encode()
return hashlib.md5(value).hexdigest()
@zope.component.adapter(str)
@zope.interface.implementer(zc.sourcefactory.interfaces.IToken)
def fromUnicode(value):
value = value.encode("utf-8")
return fromString(value)
@zope.component.adapter(int)
@zope.interface.implementer(zc.sourcefactory.interfaces.IToken)
def fromInteger(value):
# We do not have to hash integers as their string representations
# are definitely suitable for URL encoding.
return str(value)
@zope.component.adapter(persistent.interfaces.IPersistent)
@zope.interface.implementer(zc.sourcefactory.interfaces.IToken)
def fromPersistent(value):
# Persistent objects are identified by their oid. If it is persistent but
# not added to the database, we try to get to the parent, add the value to
# the database and get the oid then.
# We have to remove proxies to avoid security here.
value_unproxied = zope.proxy.removeAllProxies(value)
try:
oid = value_unproxied._p_oid
except AttributeError:
oid = None
if oid is None:
if not hasattr(value, '__parent__'):
raise ValueError('Can not determine OID for %r' % value)
connection = ZODB.interfaces.IConnection(value_unproxied.__parent__)
connection.add(value_unproxied)
oid = value_unproxied._p_oid
return ZODB.utils.oid_repr(oid)
@zope.component.adapter(zope.interface.interfaces.IInterface)
@zope.interface.implementer(zc.sourcefactory.interfaces.IToken)
def fromInterface(value):
# Interface are identified by their module path and name
return "{}.{}".format(value.__module__, value.__name__) | zc.sourcefactory | /zc.sourcefactory-2.0-py3-none-any.whl/zc/sourcefactory/browser/token.py | token.py |
"""
"""
import zope.browser.interfaces
import zope.component
import zope.interface
import zope.publisher.interfaces.browser
import zope.schema.interfaces
import zc.sourcefactory.source
@zope.component.adapter(zc.sourcefactory.source.FactoredSource,
zope.publisher.interfaces.browser.IBrowserRequest)
@zope.interface.implementer(zope.browser.interfaces.ITerms)
class FactoredTerms:
"""A terms implementation that knows how to handle a source that was
created through a source factory.
"""
def __init__(self, source, request):
self.source = source
self.request = request
def getTerm(self, value):
title = self.source.factory.getTitle(value)
token = self.source.factory.getToken(value)
return self.source.factory.createTerm(
self.source, value, title, token, self.request)
def getValue(self, token):
return self.source.factory.getValue(self.source, token)
@zope.component.adapter(zc.sourcefactory.source.FactoredContextualSource,
zope.publisher.interfaces.browser.IBrowserRequest)
class FactoredContextualTerms(FactoredTerms):
"""A terms implementation that knows how to handle a source that was
created through a contextual source factory.
"""
def getTerm(self, value):
title = self.source.factory.getTitle(self.source.context, value)
token = self.source.factory.getToken(self.source.context, value)
return self.source.factory.createTerm(
self.source.context, self.source, value, title, token,
self.request)
def getValue(self, token):
return self.source.factory.getValue(self.source.context, self.source,
token)
@zope.interface.implementer(zope.schema.interfaces.ITitledTokenizedTerm)
class FactoredTerm:
"""A title tokenized term."""
def __init__(self, value, title, token):
self.value = value
self.title = title
self.token = token | zc.sourcefactory | /zc.sourcefactory-2.0-py3-none-any.whl/zc/sourcefactory/browser/source.py | source.py |
import optparse
import os
import shutil
import subprocess
import sys
import tarfile
import tempfile
import urlparse
import pkg_resources
import zc.buildout.buildout
def _system(*args):
p = subprocess.Popen(args)
r = p.wait()
if r:
raise SystemError("Subprocess failed!")
def _relative(path, to):
rel = []
# Remove trailing separators
while 1:
d, b = os.path.split(to)
if b:
break
to = d
while path and path != to and path != '/':
path, base = os.path.split(path)
if base:
rel.insert(0, base)
if path != to:
return None
return os.path.join(*rel)
def source_release(args=None):
if args is None:
args = sys.argv[1:]
# set up command line options
parser = optparse.OptionParser()
parser.add_option("-n", "--name", dest="filename",
help="create custom named files", default="None")
# retrieve options
(options, args) = parser.parse_args(args)
url = args.pop(0)
config = args.pop(0)
clopts = []
for arg in args:
name, value = arg.split('=', 1)
section, option = name.split(':')
clopts.append((section, option, value))
name = url.split('/')[-1]
# use optparse to find custom filename
if options.filename != 'None':
name = options.filename
t1 = tempfile.mkdtemp('source-release1')
t2 = tempfile.mkdtemp('source-release2')
co1 = os.path.join(t1, name)
co2 = os.path.join(t2, name)
here = os.getcwd()
print 'Creating source release in %s.tgz' % name
sys.stdout.flush()
try:
if url.startswith('file://'):
shutil.copytree(urlparse.urlparse(url)[2], co1, symlinks=True)
else:
_system('svn', 'export', url, co1)
shutil.copytree(co1, co2, symlinks=True)
cache = os.path.join(co2, 'release-distributions')
os.mkdir(cache)
buildout = zc.buildout.buildout.Buildout(
os.path.join(co1, config), clopts,
False, False, 'bootstrap',
)
eggs_directory = buildout['buildout']['eggs-directory']
reggs = _relative(eggs_directory, co1)
if reggs is None:
print 'Invalid eggs directory (perhaps not a relative path)', \
eggs_directory
sys.exit(0)
buildout.bootstrap([])
buildargs = args[:]+[
'-Uvc', os.path.join(co1, config),
'buildout:download-cache='+cache
]
_system(os.path.join(co1, 'bin', 'buildout'), *buildargs)
os.chdir(here)
env = pkg_resources.Environment([eggs_directory])
projects = ['zc.buildout']
if env['setuptools']:
projects.append('setuptools')
else:
projects.append('distribute')
dists = [env[project][0].location
for project in projects]
eggs = os.path.join(co2, reggs)
os.mkdir(eggs)
for dist in dists:
if os.path.isdir(dist):
shutil.copytree(dist,
os.path.join(eggs, os.path.basename(dist)),
symlinks=True)
else:
shutil.copy(dist, eggs)
open(os.path.join(co2, 'install.py'), 'w').write(
install_template % dict(
path = [os.path.basename(dist) for dist in dists],
config = config,
version = sys.version_info[:2],
eggs_directory = reggs,
args = args and repr(args)[1:-1]+',' or '',
))
tar = tarfile.open(name+'.tgz', 'w:gz')
tar.add(co2, name)
tar.close()
finally:
shutil.rmtree(t1)
shutil.rmtree(t2)
install_template = """
import os, sys
if sys.version_info[:2] != %(version)r:
print "Invalid Python version, %%s.%%s." %% sys.version_info[:2]
print "Python %%s.%%s is required." %% %(version)r
sys.exit(1)
here = os.path.abspath(os.path.dirname(__file__))
sys.path[0:0] = [
os.path.join(here, %(eggs_directory)r, dist)
for dist in %(path)r
]
config = os.path.join(here, %(config)r)
import zc.buildout.buildout
zc.buildout.buildout.main([
%(args)s
'-Uc', config,
'buildout:download-cache='+os.path.join(here, 'release-distributions'),
'buildout:install-from-cache=true',
]+sys.argv[1:])
""" | zc.sourcerelease | /zc.sourcerelease-0.4.0.tar.gz/zc.sourcerelease-0.4.0/src/zc/sourcerelease/__init__.py | __init__.py |
==================
Amazon SQS support
==================
This is a small wrapper around SQS that provides some testing support
and and some abstraction over the boto SQS APIs.
There are 2 basic parts, a producer API and a worker API.
Note that these APIs don't let you pass AWS credentials. This means
that you must either pass credentials through ~/.boto configuration,
through environment variables, or through temporary credentials
provided via EC2 instance roles.
Producing jobs
==============
To send work to workers, instantiate a Queue:
>>> import zc.sqs
>>> queue = zc.sqs.Queue("myqueue")
Connected to region us-east-1.
The SQS queue must already exist. Creating queues is outside the
scope of these APIs. Trying to create a Queue instance with a
nonexistent queue name will result in an exception being raised.
>>> import mock
>>> with mock.patch("boto.sqs.connect_to_region") as conn:
... conn().get_queue.return_value = None
... zc.sqs.Queue("nonexistent") # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
NonExistentQueue: nonexistent
To place data in the queue, you call it. You can pass positional,
and/or keyword arguments.
>>> queue(1, 2, x=3)
[[1, 2], {'x': 3}]
In this example, we're running in test mode. In test mode, data are
simply echoed back (unless we wire up a worker, as will be discussed
below).
Arguments must be json encodable.
Workers
=======
Workers are provided as factories that accept configuration data and
return callables that are called with queued messages. A worker
factory could be implemented with a class that has __init__ and
__call__ methods, or with a function that takes configuration data and
returns a nested function to handle messages.
Normally, workers don't return anything. If the input is bad, the
worker should raise an exception. The exception will be logged, as
will the input data. If the input is good, but the worker can't
perform the request, it should raise zc.sqs.TransientError to indicate
that the work should be retried later.
Containers
==========
To attach your workers to queues, you use a container, which is just a
program that polls an SQS queue and calls your worker. There are
currently 2 containers:
sequential
The sequential container pulls requests from an SQS queue and hands
them to a worker, one at a time.
This is a script entry point and accepts an argument list,
containing the path to an ini file. It uses "long polling" to loop
efficiently.
test
The test container is used for writing tests. It supports
integration tests of producer and worker code. When running in
test mode, it replaces (part of) the sequential container.
The sequential entry point takes the name of an ini file with 2 sections:
container
The container section configures the container with options:
worker MODULE:expr
The worker constructor
queue
The name of an sqs queue to listen to.
loggers
A ZConfig-based logger configuration string.
worker (optional)
Worker options, passed to the worker constructor as a dictionary.
If not provided, an empty dictionary will be passed.
Here's a simple (pointless) example to illustrate how this is wired
up. First, we'll define a worker factory::
def scaled_addr(config):
scale = float(config.get('scale', 1))
def add(a, b, x):
if x == 'later':
print ("not now")
raise zc.sqs.TransientError # Not very imaginative, I know
print (scale * (a + b + x))
return add
.. -> src
>>> import zc.sqs.tests
>>> exec(src, zc.sqs.tests.__dict__)
Now, we'll define a container configuration::
[container]
worker = zc.sqs.tests:scaled_addr
queue = adder
loggers =
<logger>
level INFO
<logfile>
path STDOUT
format %(levelname)s %(name)s %(message)s
</logfile>
</logger>
<logger>
level INFO
propagate false
name zc.sqs.messages
<logfile>
path messages.log
format %(message)s
</logfile>
</logger>
[worker]
scale = 2
.. -> ini
>>> with open('ini', 'w') as f:
... _ = f.write(ini)
Now, we'll run the container.
>>> import zc.thread
>>> @zc.thread.Thread
... def thread():
... zc.sqs.sequential(['ini'])
.. give it some time
>>> import time
>>> time.sleep(.1)
Connected to region us-east-1.
We ran the container in a thread because it runs forever and wouldn't
return.
Normally, the entry point would run forever, but since we're running
in test mode, the container just wires the worker up to the test
environment.
Now, if we create a queue (in test mode):
>>> adder = zc.sqs.Queue("adder")
Connected to region us-east-1.
and send it work:
>>> adder(1, 2, 3)
12.0
deleted '[[1, 2, 3], {}]'
We see that the worker ran.
We also see a testing message showing that the test succeeded.
If a worker can't perform an action immediately, it indicates that the
message should be delayed by raising TransientError as shown in the
worker example above:
>>> adder(1, 2, 'later')
not now
In this case, since the worker raised TransientError, the message
wasn't deleted from the queue. This means that it'll be handled later
when the job times out.
If the worker rasies an exception, the exception and the message are
logged:
>>> adder(1, 2, '') # doctest: +ELLIPSIS
ERROR zc.sqs Handling a message
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for +: 'int' and '...'
deleted '[[1, 2, ""], {}]'
>>> with open("messages.log") as f:
... print(f.read())
[[1, 2, ""], {}]
<BLANKLINE>
Silencing tests
===============
Sometimes, you don't want the testing infrastructure to output
information when sending messages. There testing ``setUp`` method
adds an ``sqs_queues`` attribute to globals. You can call
``be_silent`` to make it stop outputting infomation:
>>> sqs_queues.be_silent()
After calling this, any subsequent queues will be quiet:
>>> queue = zc.sqs.Queue("quiet")
>>> queue(1)
You can get the queued data:
>>> [m.get_body() for m in sqs_queues.get_queue("quiet").get_messages()]
['[[1], {}]']
You can switch back to being noisy:
>>> sqs_queues.be_silent()
>>> queue = zc.sqs.Queue("loud")
>>> queue(1)
.. cleanup
>>> print('Stopping'); adder.queue.queue.put('STOP'); time.sleep(.01) # doctest: +ELLIPSIS
Stopping...
Changes
=======
1.0.0
-----
- Python 3 support.
0.3.0 (2014-10-17)
------------------
- Use long polling instead of a configurable polling interval.
0.2.1 (2013-05-15)
------------------
- Better error handling when SQS queues don't exist.
0.2.0 (2013-05-15)
------------------
- A new silent mode for test queues.
0.1.0 (2013-04-23)
------------------
Initial release.
| zc.sqs | /zc.sqs-1.0.0.tar.gz/zc.sqs-1.0.0/README.rst | README.rst |
from __future__ import print_function
try:
import ConfigParser
except ImportError:
import configparser as ConfigParser
import boto.sqs
import boto.sqs.message
import json
import logging
import sys
import time
import ZConfig
logger = logging.getLogger(__name__)
message_logger = logging.getLogger(__name__ + ".messages")
class TransientError(Exception):
"A job failed, but should be retried."
class NonExistentQueue(Exception):
"""An SQS queue with the specified name does not exist"""
class Queue:
def __init__(self, name, region="us-east-1"):
self.name = name
self.connection = boto.sqs.connect_to_region(region)
self.queue = self.connection.get_queue(name)
if self.queue is None:
raise NonExistentQueue(name)
def __call__(self, *args, **kw):
message = boto.sqs.message.Message()
message.set_body(json.dumps((args, kw)))
if not self.queue.write(message):
raise AssertionError("Failed to send message")
def sequential(args=None):
if args is None:
args = sys.argv[1:]
[ini] = args
parser = ConfigParser.RawConfigParser()
with open(ini) as fp:
parser.readfp(fp)
container = dict(parser.items('container'))
name = container.pop('queue')
region = container.pop('region', 'us-east-1')
worker = container.pop('worker')
ZConfig.configureLoggers(container.pop('loggers'))
if container:
print("Unexpected container options", container)
if parser.has_section('worker'):
worker_options = dict(parser.items('worker'))
else:
worker_options = {}
module, expr = worker.split(':', 1)
module = __import__(module, {}, {}, ['*'])
worker = eval(expr, module.__dict__)(worker_options)
connection = boto.sqs.connect_to_region(region)
queue = connection.get_queue(name)
while 1:
rs = queue.get_messages(wait_time_seconds=20)
if len(rs):
message = rs[0]
data = message.get_body()
try:
args, kw = json.loads(data)
worker(*args, **kw)
except TransientError:
continue
except Exception:
logger.exception("Handling a message")
message_logger.info(data)
queue.delete_message(message) | zc.sqs | /zc.sqs-1.0.0.tar.gz/zc.sqs-1.0.0/src/zc/sqs/__init__.py | __init__.py |
=================================
Creating SSH tunnels in buildouts
=================================
This recipe creates a control script for an SSH tunnel. This is only
expected to work on systems with the OpenSSH "ssh" binary on $PATH,
and may require setting up the SSH configuration to use the expected
usernames for each system.
Let's create a configuration that defines a single tunnel in a part
called "my-tunnel"::
>>> write("buildout.cfg", """\
...
... [buildout]
... parts = my-tunnel
... find-links = http://download.zope.org/distribution/
...
... [my-tunnel]
... recipe = zc.sshtunnel
... python = sample-python
... specification = 8080:server.example.net:6060
... via = somehost.example.net
...
... [sample-python]
... executable = /usr/bin/python
...
... """)
Building this out creates a single script in the bin/ directory::
>>> print system(join("bin", "buildout")),
buildout: Installing my-tunnel
>>> ls("bin")
- buildout
- my-tunnel
The script is a Python script; the tunnel parameters are stored at the
top of the script::
>>> cat(join("bin", "my-tunnel"))
#!/usr/bin/python
...
pid_file = "/sample-buildout/parts/my-tunnel.pid"
specification = "8080:server.example.net:6060"
via = "somehost.example.net"
wait_port = 8080
name = "my-tunnel"
...
The script accepts the "start", "stop", "restart", and "status"
verbs. Let's demonstrate "status", since that doesn't require
actually establishing a tunnel::
>>> print system(join("bin", "my-tunnel") + " status")
Pid file /sample-buildout/parts/my-tunnel.pid doesn't exist
<BLANKLINE>
| zc.sshtunnel | /zc.sshtunnel-1.2.tar.gz/zc.sshtunnel-1.2/src/zc/sshtunnel/README.txt | README.txt |
__docformat__ = "reStructuredText"
import os
class Recipe(object):
def __init__(self, buildout, name, options):
self.name = name
self.options = options
self.via = options["via"]
self.specification = options["specification"]
parts = self.specification.split(":")
wait_port = int(parts[-3])
self.wait_port = str(wait_port)
python = options.get("python", "buildout")
self.executable = buildout[python]["executable"]
self.script = os.path.join(
buildout["buildout"]["bin-directory"], name)
self.pidfile = os.path.join(
buildout["buildout"]["parts-directory"], name + ".pid")
options["executable"] = self.executable
options["pidfile"] = self.pidfile
options["run-script"] = self.script
def install(self):
d = {
"name": self.name,
"pid_file": self.pidfile,
"python": self.executable,
"specification": self.specification,
"via": self.via,
"wait_port": self.wait_port,
}
text = tunnel_script_template % d
f = open(self.script, "w")
f.write(text)
f.close()
os.chmod(self.script, int("0770", 8))
return [self.script]
def update(self):
# No changes, so nothing to do.
pass
tunnel_script_template = r"""#!%(python)s
import os, sys, signal, socket, time, errno
pid_file = "%(pid_file)s"
specification = "%(specification)s"
via = "%(via)s"
wait_port = %(wait_port)s
name = "%(name)s"
def wait(port):
addr = 'localhost', port
for i in range(120):
time.sleep(0.25)
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(addr)
s.close()
break
except socket.error, e:
if e[0] not in (errno.ECONNREFUSED, errno.ECONNRESET):
raise
s.close()
else:
raise
def main(args=None):
if args is None:
args = sys.argv[1:]
[verb] = args
if verb == 'start':
if os.path.exists(pid_file):
print "Pid file %%s already exists" %% pid_file
return
pid = os.fork()
if pid == 0:
# redirect output to /dev/null. This will
# cause nohup to be unannoying
os.dup2(os.open('/dev/null', os.O_WRONLY), 1)
os.dup2(os.open('/dev/null', os.O_WRONLY), 2)
pid = os.spawnlp(os.P_NOWAIT, 'nohup', 'nohup',
'ssh', '-TnaxqNL'+specification, via)
open(pid_file, 'w').write("%%s\n" %% pid)
else:
wait(wait_port)
print name, 'started'
elif verb == 'status':
if os.path.exists(pid_file):
pid = int(open(pid_file).read().strip())
try:
os.kill(pid, 0)
except OSError, v:
if v.errno == errno.ESRCH:
print name, 'not running'
# Unlink the pid_file if we can, to avoid having
# process numbers cycle around and accidentally
# recognizing some other process mistakenly.
try:
os.unlink(pid_file)
except OSError:
pass
else:
print v
else:
print name, 'running'
else:
print "Pid file %%s doesn't exist" %% pid_file
elif verb == 'stop':
if os.path.exists(pid_file):
pid = int(open(pid_file).read().strip())
try:
os.kill(pid, signal.SIGINT)
except OSError, v:
print v
os.remove(pid_file)
print name, 'stopped'
else:
print "Pid file %%s doesn't exist" %% pid_file
elif verb == 'restart':
main(['stop'])
main(['start'])
return
else:
raise ValueError("Unknown verb", verb)
if __name__ == '__main__':
main()
""" | zc.sshtunnel | /zc.sshtunnel-1.2.tar.gz/zc.sshtunnel-1.2/src/zc/sshtunnel/recipe.py | recipe.py |
CHANGES
=======
1.0 (2023-02-17)
----------------
- Drop support for Python 2.7, 3.5, 3.6.
- Add support for Python 3.5, 3.7, 3.8, 3.9, 3.10, 3.11.
0.10.0 (2020-02-06)
-------------------
- Make Python 3 compatible
0.9.0 (2012-11-21)
------------------
- Using Python's ``doctest`` module instead of deprecated
``zope.testing.doctest``.
- Removed dependency on ``zope.app.testing`` and ``zope.app.form``.
- Add test extra, move ``zope.testing`` to it.
0.8.1 (2010-05-25)
------------------
- Replaced html entities with unicode entities since they are xthml valid.
0.8.0 (2009-07-23)
------------------
- Updated tests to latest packages.
0.7.0 (2008-05-20)
------------------
- Fixed HTML-encoding of cell contents for ``GetterColumn``.
- Add ``href`` attributes (for MSIE) and fix up JavaScript on Next/Prev links
for batching.
- Update packaging.
0.6 (2006-09-22)
----------------
Initial release on Cheeseshop.
| zc.table | /zc.table-1.0.tar.gz/zc.table-1.0/CHANGES.rst | CHANGES.rst |
======
Tables
======
Tables are general purpose UI constructs designed to simplify presenting
tabular information. A table has a column set which collects columns and
manages configuration data.
We must register a faux resource directory in preparation::
>>> import zope.interface
>>> import zope.component
>>> import zope.publisher.interfaces
>>> @zope.component.adapter(zope.publisher.interfaces.IRequest)
... @zope.interface.implementer(zope.interface.Interface)
... def dummyResource(request):
... return lambda:'/@@/zc.table'
...
>>> zope.component.provideAdapter(dummyResource, name='zc.table')
Columns
=======
``Columns`` have methods to render a header and the contents of a cell based on
the item that occupies that cell. Here's a very simple example::
>>> from zope import interface
>>> from zc.table import interfaces
>>> @interface.implementer(interfaces.IColumn)
... class GetItemColumn:
... def __init__(self, title, name, attr):
... self.title = title
... self.name = name
... self.attr = attr # This isn't part of IColumn
... def renderHeader(self, formatter):
... return self.title
... def renderCell(self, item, formatter):
... return str(getattr(item, self.attr))
Note that the methods do not provide the <th> and <td> tags.
The title is for display, while the name is for identifying the column within
a collection of columns: a column name must be unique within a collection of
columns used for a table formatter.
`renderHeader` takes a formatter--the table formatter introduced in the section
immediately below this one. It has the responsibility of rendering the
contents of the header for the column. `renderCell` takes the item to be
rendered and the formatter, and is responsible for returning the cell contents
for the given item.
The formatter is passed because it contains references to a number of useful
values. The context and request are particularly important.
Columns may also support sorting by implementing the ISortableColumn interface.
This interface is comprised of two methods, `sort` and `reversesort`. Both
take the same rather large set of arguments: items, formatter, start, stop,
and sorters. At least two values should be unsurprising: the `items` are the
items to be sorted, the `formatter` is the table formatter. The `start` and
`stop` values are the values that are needed for the rendering, so some
implementations may be able to optimize to only give precise results for the
given range. The `sorters` are optional sub-sorters--callables with signatures
identical to `sort` and `reversesort` that are a further sort refinement that
an implementation may optionally ignore. If a column has two or
more values that will sort identically, the column might take advantage of any
sub-sorters to further sort the data.
The columns.py file has a number of useful base column classes. The
columns.txt file discusses some of them. For our examples here, we will use
the relatively simple and versatile zc.table.column.GetterColumn. It is
instantiated with two required values and two optional values::
title - (required) the title of the column.
getter - (required) a callable that is passed the item and the table
formatter; returns the value used in the cell.
cell_formatter - (optional) a callable that is passed the result of getter,
the item, and the table formatter; returns the formatted
HTML. defaults to a function that returns the result of
trying to convert the result to unicode.
name - (optional) the name of the column. The title is used if a name is
not specified.
It includes a reasonably simple implementation of ISortableColumn but does
not declare the interface itself. It tries to sort on the basis of the getter
value and can be customized simply by overriding the `getSortKey` method.
Let's import the GetterColumn and create some columns that we'll use later,
and then verify that one of the columns fully implements IColumn. We'll also
then declare that all three of them provide ISortableColumn and verify one of
them::
>>> from zc.table.column import GetterColumn
>>> columns = (
... GetterColumn(u'First', lambda i,f: i.a, subsort=True),
... GetterColumn(u'Second', lambda i,f: i.b, subsort=True),
... GetterColumn(u'Third', lambda i,f: i.c, subsort=True),
... )
>>> import zope.interface.verify
>>> zope.interface.verify.verifyObject(interfaces.IColumn, columns[0])
True
>>> for c in columns:
... interface.directlyProvides(c, interfaces.ISortableColumn)
...
>>> zope.interface.verify.verifyObject(
... interfaces.ISortableColumn, columns[0])
True
Formatters
==========
When a sequence of objects are to be turned into an HTML table, a
table.Formatter is used. The table package includes a simple implementation
of IFormatter as well as a few important variations.
The default Formatter is instantiated with three required arguments--
`context`, `request`, and `items`--and a long string of optional arguments
we'll discuss in a moment. The first two required arguments are reminiscent
of browser views--and in fact, a table formatter is a specialized browser
view. The `context` is the object for which the table formatter is being
rendered, and can be important to various columns; and the `request` is the
current request. The `items` are the full set of items on which the table will
give a view.
The first three optional arguments affect the display::
visible_column_names=None, batch_start=0, batch_size=0
visible_column_names are a list of column names that should be displayed; note
that even if a column is not visible, it may still affect other behavior such
as sorting, discussed for a couple of Formatter subclasses below.
batch_start is the item position the table should begin to render. batch_size
is the number of items the table should render; 0 means all.
The next optional argument, `prefix=None`, is particularly important when a
table formatter is used within a form: it sets a prefix for any form fields
and XML identifiers generated for the table or a contained element.
The last optional argument is the full set of columns for the table (not just
the ones curently visible). It is optional because it may be set instead as
a subclass attribute: the value itself is required on instances.
Lets create some data to format and instantiate the default Formatter.
Our formatters won't need the context, so we'll fake it. As an
exercise, we'll hide the second column.
>>> class DataItem:
... def __init__(self, a, b, c):
... self.a = a
... self.b = b
... self.c = c
>>> items = [DataItem('a0', 'b0', 'c0'),
... DataItem('a2', 'b2', 'c2'),
... DataItem('a1', 'b1', 'c1'),
... ]
>>> from zc.table import table
>>> import zope.publisher.browser
>>> request = zope.publisher.browser.TestRequest()
>>> context = None
>>> formatter = table.Formatter(
... context, request, items, visible_column_names=('First', 'Third'),
... columns=columns)
>>> zope.interface.verify.verifyObject(
... interfaces.IFormatter, formatter)
True
The simplest way to use a table formatter is to call it, asking the formatter
to render the entire table::
>>> print(formatter())
<table>
<thead>
<tr>
<th>
First
</th>
<th>
Third
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
a0
</td>
<td>
c0
</td>
</tr>
<tr>
<td>
a2
</td>
<td>
c2
</td>
</tr>
<tr>
<td>
a1
</td>
<td>
c1
</td>
</tr>
</tbody>
</table>
If you want more control over the output then you may want to call methods
on the formatter that generate various parts of the output piecemeal. In
particular, getRows, getHeaders, and getCells exist only for this sort of use.
Here is an example of getRows in use to generate even and odd rows and a
column with cells in a special class:
>>> html = '<table class="my_class">\n'
>>> html += '<tr class="header">\n'+ formatter.renderHeaders() + '</tr>\n'
>>> for index, row in enumerate(formatter.getRows()):
... if index % 2:
... html += '<tr class="even">'
... else:
... html += '<tr class="odd">'
... for index, cell in enumerate(row):
... if index == 0:
... html += '<td class="first_column">'
... else:
... html += '<td>'
... html += cell + '<td>'
... html += '</tr>\n'
>>> html += '</table>'
>>> print(html)
<table class="my_class">
<tr class="header">
<th>
First
</th>
<th>
Third
</th>
</tr>
<tr class="odd"><td class="first_column">a0<td><td>c0<td></tr>
<tr class="even"><td class="first_column">a2<td><td>c2<td></tr>
<tr class="odd"><td class="first_column">a1<td><td>c1<td></tr>
</table>
However, the formatter provides some simple support for style sheets, since it
is the most common form of customization. Each formatter has an attribute
called ``cssClasses``, which is a mapping from HTML elements to CSS
classes. As you saw above, by default there are no CSS classes registered for
the formatter. Let's now register one for the "table" element:
>>> formatter.cssClasses['table'] = 'list'
>>> print(formatter())
<table class="list">
...
</table>
This can be done for every element used in the table. Of course, you can also
unregister the class again:
>>> del formatter.cssClasses['table']
>>> print(formatter())
<table>
...
</table>
If you are going to be doing a lot of this sort of thing (or if this approach
is more your style), a subclass of Formatter might be in order--but that
is jumping the gun a bit. See the section about subclasses below.
Columns are typically defined for a class and reused across requests.
Therefore, they have the request that columns need. They also have an
`annotations` attribute that allows columns to stash away information that
they need across method calls--for instance, an adapter that every single
cell in a column--and maybe even across multiple columns--will need.
>>> formatter.annotations
{}
Batching
========
As discussed above, ``Formatter`` instances can also batch. In order to
batch, `items` must minimally be iterable and ideally support a slice syntax.
batch_size and batch_start, introduced above, are the formatter values to use.
Typically these are passed in on instantiation, but we'll change the attributes
on the existing formatter.
>>> formatter.batch_size = 1
>>> print(formatter())
<table>
<thead>
<tr>
<th>
First
</th>
<th>
Third
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
a0
</td>
<td>
c0
</td>
</tr>
</tbody>
</table>
>>> formatter.batch_start=1
>>> print(formatter())
<table>
<thead>
<tr>
<th>
First
</th>
<th>
Third
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
a2
</td>
<td>
c2
</td>
</tr>
</tbody>
</table>
Fancy Columns
=============
It is easy to make columns be more sophisticated. For example, if we wanted
a column that held content that was especially wide, we could do this::
>>> class WideColumn(GetterColumn):
... def renderHeader(self, formatter):
... return '<div style="width:200px">%s</div>' % (
... super(WideColumn, self).renderHeader(formatter),)
>>> fancy_columns = (
... WideColumn(u'First', lambda i,f: i.a),
... GetterColumn(u'Second', lambda i,f: i.b),
... GetterColumn(u'Third', lambda i,f: i.c),
... )
>>> formatter = table.Formatter(
... context, request, items, visible_column_names=('First', 'Third'),
... columns=fancy_columns)
>>> print(formatter())
<table>
<thead>
<tr>
<th>
<div style="width:200px">First</div>
</th>
<th>
Third
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
a0
</td>
<td>
c0
</td>
</tr>
<tr>
<td>
a2
</td>
<td>
c2
</td>
</tr>
<tr>
<td>
a1
</td>
<td>
c1
</td>
</tr>
</tbody>
</table>
This level of control over the way columns are rendered allows for creating
advanced column types.
Formatter Subclasses
====================
The Formatter is useful, but lacks some features you may need. The
factoring is such that, typically, overriding just a few methods can easily
provide what you need. The table module provides a few examples of these
subclasses. While the names are sometimes a bit unwieldy, the functionality is
useful.
AlternatingRowFormatter
-----------------------
The AlternatingRowFormatter is the simplest subclass, offering an
odd-even row formatter that's very easy to use::
>>> formatter = table.AlternatingRowFormatter(
... context, request, items, ('First', 'Third'), columns=columns)
>>> print(formatter())
<table>
<thead>
<tr>
<th>
First
</th>
<th>
Third
</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>
a0
</td>
<td>
c0
</td>
</tr>
<tr class="even">
<td>
a2
</td>
<td>
c2
</td>
</tr>
<tr class="odd">
<td>
a1
</td>
<td>
c1
</td>
</tr>
</tbody>
</table>
If you want different classes other than "even" and "odd" then simply
define `row_classes` on your instance: the default is a tuple of "even" and
"odd", but "green" and "red" will work as well:
>>> formatter.row_classes = ("red", "green")
>>> print(formatter())
<table>
<thead>
<tr>
<th>
First
</th>
<th>
Third
</th>
</tr>
</thead>
<tbody>
<tr class="green">
<td>
a0
</td>
<td>
c0
</td>
</tr>
<tr class="red">
<td>
a2
</td>
<td>
c2
</td>
</tr>
<tr class="green">
<td>
a1
</td>
<td>
c1
</td>
</tr>
</tbody>
</table>
Note that this formatter also plays nicely with the other CSS classes defined
by the formatter:
>>> formatter.cssClasses['tr'] = 'list'
>>> print(formatter())
<table>
<thead>
<tr class="list">
<th>
First
</th>
<th>
Third
</th>
</tr>
</thead>
<tbody>
<tr class="list green">
<td>
a0
</td>
<td>
c0
</td>
</tr>
<tr class="list red">
<td>
a2
</td>
<td>
c2
</td>
</tr>
<tr class="list green">
<td>
a1
</td>
<td>
c1
</td>
</tr>
</tbody>
</table>
SortingFormatter
----------------
``SortingFormatter`` supports ``ISortableColumn`` instances by asking them to
sort using the ``ISortableColumn`` interface described above. Instantiating
one takes a new final optional argument, ``sort_on``, which is a sequence of
tuple pairs of (column name string, reverse sort boolean) in which the first
pair is the primary sort. Here's an example. Notice that we are sorting on
the hidden column--this is acceptable, and not even all that unlikely to
encounter.
>>> formatter = table.SortingFormatter(
... context, request, items, ('First', 'Third'), columns=columns,
... sort_on=(('Second', True),))
>>> print(formatter())
<table>
<thead>
<tr>
<th>
First
</th>
<th>
Third
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
a2
</td>
<td>
c2
</td>
</tr>
<tr>
<td>
a1
</td>
<td>
c1
</td>
</tr>
<tr>
<td>
a0
</td>
<td>
c0
</td>
</tr>
</tbody>
</table>
Sorting can also be done on multiple columns. This has the effect of
subsorting. It is up to a column to support the subsorting: it is not a
required behavior. The default GetterColumns we have been using it support it
at the expense of possibly doing a lot of wasted work; the behavior will come
in handy for some examples, though.
First, we'll add some data items that have the same value in the "First"
column. Then we'll configure the sort to sort with "First" being the primary
key and "Third" being the secondary key (you can provide more than two if you
wish). Note that, unlike some of the values examined up to this point, the
sort columns will only be honored when passed to the class on instanciation.
>>> big_items = items[:]
>>> big_items.append(DataItem('a1', 'b1', 'c9'))
>>> big_items.append(DataItem('a1', 'b1', 'c7'))
>>> big_items.append(DataItem('a1', 'b1', 'c8'))
>>> formatter = table.SortingFormatter(
... context, request, big_items, ('First', 'Third'), columns=columns,
... sort_on=(('First', True), ('Third', False)))
>>> print(formatter())
<table>
<thead>
<tr>
<th>
First
</th>
<th>
Third
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
a2
</td>
<td>
c2
</td>
</tr>
<tr>
<td>
a1
</td>
<td>
c1
</td>
</tr>
<tr>
<td>
a1
</td>
<td>
c7
</td>
</tr>
<tr>
<td>
a1
</td>
<td>
c8
</td>
</tr>
<tr>
<td>
a1
</td>
<td>
c9
</td>
</tr>
<tr>
<td>
a0
</td>
<td>
c0
</td>
</tr>
</tbody>
</table>
If the direction of the primary sort is changed, it doesn't effect the sub
sort::
>>> formatter = table.SortingFormatter(
... context, request, big_items, ('First', 'Third'), columns=columns,
... sort_on=(('First', False), ('Third', False)))
>>> print(formatter())
<table>
<thead>
<tr>
<th>
First
</th>
<th>
Third
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
a0
</td>
<td>
c0
</td>
</tr>
<tr>
<td>
a1
</td>
<td>
c1
</td>
</tr>
<tr>
<td>
a1
</td>
<td>
c7
</td>
</tr>
<tr>
<td>
a1
</td>
<td>
c8
</td>
</tr>
<tr>
<td>
a1
</td>
<td>
c9
</td>
</tr>
<tr>
<td>
a2
</td>
<td>
c2
</td>
</tr>
</tbody>
</table>
When batching sorted tables, the sorting is applied first, then the batching::
>>> formatter = table.SortingFormatter(
... context, request, items, ('First', 'Third'), columns=columns,
... batch_start=1, sort_on=(('Second', True),))
>>> print(formatter())
<table>
<thead>
<tr>
<th>
First
</th>
<th>
Third
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
a1
</td>
<td>
c1
</td>
</tr>
<tr>
<td>
a0
</td>
<td>
c0
</td>
</tr>
</tbody>
</table>
StandaloneSortFormatter and FormSortFormatter
---------------------------------------------
The sorting table formatter takes care of the sorting back end, but it's
convenient to encapsulate a bit of the front end logic as well, to provide
columns with clickable headers for sorting and so on without having to write
the code every time you need the behavior. Two subclasses of
SortingFormatter provide this capability. The
StandaloneSortFormatter is useful for tables that are not parts of a
form, while the FormSortFormatter is designed to fit within a form.
Both versions look at the request to examine what the user has requested be
sorted, and draw UI on the sortable column headers to enable sorting. The
standalone version uses javascript to put the information in the url, and
the form version puts the information in a hidden field.
Let's take a look at the output of one of these formatters. First there will
be no sorting information.
>>> request = zope.publisher.browser.TestRequest()
>>> formatter = table.FormSortFormatter(
... context, request, items, ('First', 'Third'), columns=columns)
>>> print(formatter())
<table>
<thead>
<tr>
<th>
<span class="zc-table-sortable"
onclick="javascript: onSortClickForm(
'First', 'sort_on')"
onMouseOver="javascript: this.className='sortable zc-table-sortable'"
onMouseOut="javascript: this.className='zc-table-sortable'">
First</span>...
</th>
<th>
<span class="zc-table-sortable"
onclick="javascript: onSortClickForm(
'Third', 'sort_on')"
onMouseOver="javascript: this.className='sortable zc-table-sortable'"
onMouseOut="javascript: this.className='zc-table-sortable'">
Third</span>...
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
a0
</td>
<td>
c0
</td>
</tr>
<tr>
<td>
a2
</td>
<td>
c2
</td>
</tr>
<tr>
<td>
a1
</td>
<td>
c1
</td>
</tr>
</tbody>
</table>
...
Setting a prefix also affects the value used to store the sorting information.
>>> formatter = table.FormSortFormatter(
... context, request, items, ('First', 'Third'),
... prefix='slot.first', columns=columns)
>>> sort_on_name = table.getSortOnName(formatter.prefix)
>>> print(formatter())
<table>
<thead>
<tr>
<th>
<span class="zc-table-sortable"
onclick="javascript: onSortClickForm(
'First', 'slot.first.sort_on')"
onMouseOver="javascript: this.className='sortable zc-table-sortable'"
onMouseOut="javascript: this.className='zc-table-sortable'">
First</span>...
</th>
<th>
<span class="zc-table-sortable"
onclick="javascript: onSortClickForm(
'Third', 'slot.first.sort_on')"
onMouseOver="javascript: this.className='sortable zc-table-sortable'"
onMouseOut="javascript: this.className='zc-table-sortable'">
Third</span>...
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
a0
</td>
<td>
c0
</td>
</tr>
<tr>
<td>
a2
</td>
<td>
c2
</td>
</tr>
<tr>
<td>
a1
</td>
<td>
c1
</td>
</tr>
</tbody>
</table>
...
Now we'll add information in the request about the sort, and use a prefix.
The value given in the request indicates that the form should be sorted by
the second column in reverse order.
>>> request.form[sort_on_name] = ['Second', 'Second']
>>> formatter = table.FormSortFormatter(
... context, request, items, ('First', 'Third'),
... prefix='slot.first', columns=columns)
>>> print(formatter())
<table>
<thead>
<tr>
<th>
<span class="zc-table-sortable"
onclick="javascript: onSortClickForm(
'First', 'slot.first.sort_on')"
onMouseOver="javascript: this.className='sortable zc-table-sortable'"
onMouseOut="javascript: this.className='zc-table-sortable'">
First</span>...
</th>
<th>
<span class="zc-table-sortable"
onclick="javascript: onSortClickForm(
'Third', 'slot.first.sort_on')"
onMouseOver="javascript: this.className='sortable zc-table-sortable'"
onMouseOut="javascript: this.className='zc-table-sortable'">
Third</span>...
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
a2
</td>
<td>
c2
</td>
</tr>
<tr>
<td>
a1
</td>
<td>
c1
</td>
</tr>
<tr>
<td>
a0
</td>
<td>
c0
</td>
</tr>
</tbody>
</table>
...
Note that sort_on value explicitly passed to a FormSortFormatter is only an
initial value: if the request contains sort information, then the sort_on
value is ignored. This is correct behavior because the initial sort_on value
is recorded in the form, and does not need to be repeated.
For instance, if we re-use the big_items collection from above and pass a
sort_on but modify the request to effectively get a sort_on of
(('First', True), ('Third', False)), then the code will look something like
this--notice that we draw arrows indicating the direction of the primary
search.
>>> request = zope.publisher.browser.TestRequest()
>>> request.form[sort_on_name] = ['Third', 'First', 'First'] # LIFO
>>> formatter = table.FormSortFormatter(
... context, request, big_items, ('First', 'Third'), columns=columns,
... prefix='slot.first', sort_on=(('Second', False), ('Third', True)))
>>> interfaces.IColumnSortedItems.providedBy(formatter.items)
True
>>> zope.interface.verify.verifyObject(interfaces.IColumnSortedItems,
... formatter.items)
True
>>> formatter.items.sort_on
[['First', True], ['Third', False]]
>>> print(formatter())
<table>
<thead>
<tr>
<th>
<span class="zc-table-sortable"
onclick="javascript: onSortClickForm(
'First', 'slot.first.sort_on')"
onMouseOver="javascript: this.className='sortable zc-table-sortable'"
onMouseOut="javascript: this.className='zc-table-sortable'">
First</span>...
<img src="/@@/zc.table/sort_arrows_up.gif".../>
</th>
<th>
<span class="zc-table-sortable"
onclick="javascript: onSortClickForm(
'Third', 'slot.first.sort_on')"
onMouseOver="javascript: this.className='sortable zc-table-sortable'"
onMouseOut="javascript: this.className='zc-table-sortable'">
Third</span>...
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
a2
</td>
<td>
c2
</td>
</tr>
<tr>
<td>
a1
</td>
<td>
c1
</td>
</tr>
<tr>
<td>
a1
</td>
<td>
c7
</td>
</tr>
<tr>
<td>
a1
</td>
<td>
c8
</td>
</tr>
<tr>
<td>
a1
</td>
<td>
c9
</td>
</tr>
<tr>
<td>
a0
</td>
<td>
c0
</td>
</tr>
</tbody>
</table>
...
The standalone non-form version uses almost all the same code but doesn't
draw the hidden field and calls a different JavaScript function (which puts the
sorting information in the query string rather than in a form field). Here's a
quick copy of the example above, modified to use the standalone version.
Because of the way the query string is used, more than two instances of a
column name may appear in the form field, so this is emulated in the example.
Because the standalone version doesn't have a form to record the initial
sort_on values, they are honored even if sort_on values exist in the request.
This is in direct contrast to the form-based formatter discussed immediately
above.
>>> request = zope.publisher.browser.TestRequest()
>>> request.form[sort_on_name] = [
... 'Third', 'First', 'Second', 'Third', 'Second', 'Third', 'First']
... # == First True, Third False, Second True
>>> formatter = table.StandaloneSortFormatter(
... context, request, big_items, ('First', 'Third'), columns=columns,
... prefix='slot.first', sort_on=(('Second', False), ('Third', True)))
>>> formatter.items.sort_on
[['First', True], ['Third', False], ['Second', False]]
>>> print(formatter())
<table>
<thead>
<tr>
<th>
<span class="zc-table-sortable"
onclick="javascript: onSortClickStandalone(
'First', 'slot.first.sort_on')"
onMouseOver="javascript: this.className='sortable zc-table-sortable'"
onMouseOut="javascript: this.className='zc-table-sortable'">
First</span> <img src="/@@/zc.table/sort_arrows_up.gif".../>
</th>
<th>
<span class="zc-table-sortable"
onclick="javascript: onSortClickStandalone(
'Third', 'slot.first.sort_on')"
onMouseOver="javascript: this.className='sortable zc-table-sortable'"
onMouseOut="javascript: this.className='zc-table-sortable'">
Third</span>...
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
a2
</td>
<td>
c2
</td>
</tr>
<tr>
<td>
a1
</td>
<td>
c1
</td>
</tr>
<tr>
<td>
a1
</td>
<td>
c7
</td>
</tr>
<tr>
<td>
a1
</td>
<td>
c8
</td>
</tr>
<tr>
<td>
a1
</td>
<td>
c9
</td>
</tr>
<tr>
<td>
a0
</td>
<td>
c0
</td>
</tr>
</tbody>
</table>
The sorting code is to be able to accept iterators as items, and only iterate
through them as much as necessary to accomplish the tasks. This needs to
support multiple simultaneous iterations. Another goal is to use the slice
syntax to let sort implementations be guided as to where precise sorting is
needed, in case n-best or other approaches can be used.
There is some trickiness about this in the implementation, and this part of
the document tries to explore some of the edge cases that have proved
problematic in the field.
In particular, we should examine using an iterator in sorted and unsorted
configurations within a sorting table formatter, with batching.
Unsorted:
>>> formatter = table.SortingFormatter(
... context, request, iter(items), ('First', 'Third'),
... columns=columns, batch_size=2)
>>> formatter.items[0] is not None # artifically provoke error :-(
True
>>> print(formatter())
<table>
<thead>
<tr>
<th>
First
</th>
<th>
Third
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
a0
</td>
<td>
c0
</td>
</tr>
<tr>
<td>
a2
</td>
<td>
c2
</td>
</tr>
</tbody>
</table>
Sorted:
>>> formatter = table.SortingFormatter(
... context, request, iter(items), ('First', 'Third'),
... columns=columns, sort_on=(('Second', True),), batch_size=2)
>>> formatter.items[0] is not None # artifically provoke error :-(
True
>>> print(formatter())
<table>
<thead>
<tr>
<th>
First
</th>
<th>
Third
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
a2
</td>
<td>
c2
</td>
</tr>
<tr>
<td>
a1
</td>
<td>
c1
</td>
</tr>
</tbody>
</table>
| zc.table | /zc.table-1.0.tar.gz/zc.table-1.0/src/zc/table/README.rst | README.rst |
"""Useful predefined columns."""
import warnings
from base64 import b64encode
from xml.sax.saxutils import quoteattr
from zope import component
from zope import i18n
from zope import interface
from zope import schema
from zope.formlib.interfaces import IInputWidget
from zope.formlib.interfaces import WidgetInputError
from zope.formlib.interfaces import WidgetsError
from zc.table import interfaces
@interface.implementer(interfaces.IColumn)
class Column:
title = None
name = None
def __init__(self, title=None, name=None):
if title is not None:
self.title = title
self.name = name or title
def renderHeader(self, formatter):
return i18n.translate(
self.title, context=formatter.request, default=self.title)
def renderCell(self, item, formatter):
raise NotImplementedError('Subclasses must provide their '
'own renderCell method.')
@interface.implementer(interfaces.ISortableColumn)
class SortingColumn(Column):
# sort and reversesort are part of ISortableColumn, not IColumn, but are
# put here to provide a reasonable default implementation.
def __init__(self, title=None, name=None, subsort=False):
self.subsort = subsort
super().__init__(title, name)
def _sort(self, items, formatter, start, stop, sorters, reverse=False):
if self.subsort and sorters:
items = sorters[0](items, formatter, start, stop, sorters[1:])
else:
items = list(items) # don't mutate original
getSortKey = self.getSortKey
items.sort(
key=lambda item: getSortKey(item, formatter),
reverse=reverse)
return items
def sort(self, items, formatter, start, stop, sorters):
return self._sort(items, formatter, start, stop, sorters)
def reversesort(self, items, formatter, start, stop, sorters):
return self._sort(items, formatter, start, stop, sorters, reverse=True)
# this is a convenience to override if you just want to keep the basic
# implementation but change the comparison values.
def getSortKey(self, item, formatter):
raise NotImplementedError
@interface.implementer_only(interfaces.IColumn)
class GetterColumn(SortingColumn):
"""Column for simple use cases.
title - the title of the column
getter - a callable that is passed the item and the table formatter;
returns the value used in the cell
cell_formatter - a callable that is passed the result of getter, the
item, and the table formatter; returns the formatted HTML
"""
def __init__(self, title=None, getter=None, cell_formatter=None,
name=None, subsort=False):
if getter is not None:
self.getter = getter
if cell_formatter is not None:
self.cell_formatter = cell_formatter
super().__init__(title, name, subsort=subsort)
def getter(self, item, formatter):
return item
def cell_formatter(self, value, item, formatter):
return str(value).replace('&', '&') \
.replace('<', '<') \
.replace('>', '>')
def renderCell(self, item, formatter):
value = self.getter(item, formatter)
return self.cell_formatter(value, item, formatter)
# this is a convenience to override if you just want to keep the basic
# implementation but change the comparison values.
def getSortKey(self, item, formatter):
return self.getter(item, formatter)
class MailtoColumn(GetterColumn):
def renderCell(self, item, formatter):
email = super().renderCell(item, formatter)
return '<a href="mailto:{}">{}</a>'.format(email, email)
class FieldEditColumn(Column):
"""Columns that supports field/widget update
Note that fields are only bound if bind == True.
"""
def __init__(self, title=None, prefix=None, field=None,
idgetter=None, getter=None, setter=None, name='', bind=False,
widget_class=None, widget_extra=None):
super().__init__(title, name)
assert prefix is not None # this is required
assert field is not None # this is required
assert idgetter is not None # this is required
self.prefix = prefix
self.field = field
self.idgetter = idgetter
if getter is None:
getter = field.get
self.get = getter
if setter is None:
setter = field.set
self.set = setter
self.bind = bind
self.widget_class = widget_class
self.widget_extra = widget_extra
def makeId(self, item):
return b64encode(self.idgetter(item).encode('utf-8')).decode('ascii')
def input(self, items, request):
if not hasattr(request, 'form'):
warnings.warn(
'input should be called with a request, not a formatter',
DeprecationWarning, 2)
request = request.request
data = {}
errors = []
bind = self.bind
if not bind:
widget = component.getMultiAdapter(
(self.field, request), IInputWidget)
for item in items:
if bind:
widget = component.getMultiAdapter(
(self.field.bind(item), request), IInputWidget)
id = self.makeId(item)
# this is wrong: should use formatter prefix. column should not
# have a prefix. This requires a rewrite; this entire class
# will be deprecated.
widget.setPrefix(self.prefix + '.' + id)
if widget.hasInput():
try:
data[id] = widget.getInputValue()
except WidgetInputError as v:
errors.append(v)
if errors:
raise WidgetsError(errors)
return data
def update(self, items, data):
changed = False
for item in items:
id = self.makeId(item)
v = data.get(id, self)
if v is self:
continue
if self.get(item) != v:
self.set(item, v)
changed = True
return changed
def renderCell(self, item, formatter):
id = self.makeId(item)
request = formatter.request
field = self.field
if self.bind:
field = field.bind(item)
widget = component.getMultiAdapter((field, request), IInputWidget)
widget.setPrefix(self.prefix + '.' + id)
if self.widget_extra is not None:
widget.extra = self.widget_extra
if self.widget_class is not None:
widget.cssClass = self.widget_class
ignoreStickyValues = getattr(formatter, 'ignoreStickyValues', False)
if ignoreStickyValues or not widget.hasInput():
widget.setRenderedValue(self.get(item))
return widget()
class SelectionColumn(FieldEditColumn):
title = ''
def __init__(self, idgetter, field=None, prefix=None, getter=None,
setter=None, title=None, name='', hide_header=False):
if field is None:
field = schema.Bool()
if not prefix:
if field.__name__:
prefix = field.__name__ + '_selection_column'
else:
prefix = 'selection_column'
if getter is None:
getter = lambda item: False # noqa
if setter is None:
setter = lambda item, value: None # noqa
if title is None:
title = field.title or ""
self.hide_header = hide_header
super().__init__(field=field, prefix=prefix, getter=getter,
setter=setter, idgetter=idgetter, title=title,
name=name)
def renderHeader(self, formatter):
if self.hide_header:
return ''
return super().renderHeader(formatter)
def getSelected(self, items, request):
"""Return the items which were selected."""
data = self.input(items, request)
return [item for item in items if data.get(self.makeId(item))]
class SubmitColumn(Column):
def __init__(self, title=None, prefix=None, idgetter=None, action=None,
labelgetter=None, condition=None,
extra=None, cssClass=None, renderer=None, name=''):
super().__init__(title, name)
# hacked together. :-/
assert prefix is not None # this is required
assert idgetter is not None # this is required
assert labelgetter is not None # this is required
assert action is not None # this is required
self.prefix = prefix
self.idgetter = idgetter
self.action = action
self.renderer = renderer
self.condition = condition
self.extra = extra
self.cssClass = cssClass
self.labelgetter = labelgetter
def makeId(self, item):
return ''.join(self.idgetter(item).encode('base64').split())
def input(self, items, request):
for item in items:
id = self.makeId(item)
identifier = '{}.{}'.format(self.prefix, id)
if identifier in request.form:
if self.condition is None or self.condition(item):
return id
break
def update(self, items, data):
if data:
for item in items:
id = self.makeId(item)
if id == data:
self.action(item)
return True
return False
def renderCell(self, item, formatter):
if self.condition is None or self.condition(item):
id = self.makeId(item)
identifier = '{}.{}'.format(self.prefix, id)
if self.renderer is not None:
return self.renderer(
item, identifier, formatter, self.extra, self.cssClass)
label = self.labelgetter(item, formatter)
label = i18n.translate(
label, context=formatter.request, default=label)
val = "<input type='submit' name={} value={} {}".format(
quoteattr(identifier),
quoteattr(label),
self.extra and quoteattr(self.extra) or '')
if self.cssClass:
val = "{} class={} />".format(val, quoteattr(self.cssClass))
else:
val += " />"
return val
return '' | zc.table | /zc.table-1.0.tar.gz/zc.table-1.0/src/zc/table/column.py | column.py |
import re
from zope import interface
from zope import schema
pythonLikeNameConstraint = re.compile(r'^[a-zA-Z_]\w*$').match
class IColumn(interface.Interface):
name = schema.BytesLine(
title='Name',
description=('Name used for column in options of a table '
'configuration. Must be unique within any set of '
'columns passed to a table formatter.'),
constraint=pythonLikeNameConstraint,
)
title = schema.TextLine(
title='Title',
description='The title of the column, used in configuration dialogs.',
)
def renderHeader(formatter):
"""Renders a table header.
'formatter' - The IFormatter that is using the IColumn.
Returns html_fragment, not including any surrounding <th> tags.
"""
def renderCell(item, formatter):
"""Renders a table cell.
'item' - the object on this row.
'formatter' - The IFormatter that is using the IColumn.
Returns html_fragment, not including any surrounding <td> tags.
"""
class ISortableColumn(interface.Interface):
def sort(items, formatter, start, stop, sorters):
"""Return a list of items in sorted order.
Formatter is passed to aid calculation of sort parameters. Start and
stop are passed in order to provide a hint as to the range needed, if
the algorithm can optimize. Sorters are a list of zero or more
sub-sort callables with the same signature which may be used if
desired to sub-sort values with equivalent sort values according
to this column.
The original items sequence should not be mutated."""
def reversesort(items, formatter, start, stop, sorters):
"""Return a list of items in reverse sorted order.
Formatter is passed to aid calculation of sort parameters. Start and
stop are passed in order to provide a hint as to the range needed, if
the algorithm can optimize. Sorters are a list of zero or more
sub-sort callables with the same signature as this method, which may
be used if desired to sub-sort values with equivalent sort values
according to this column.
The original items sequence should not be mutated."""
class IColumnSortedItems(interface.Interface):
"""items that support sorting by column. setFormatter must be called
with the formatter to be used before methods work. This is typically done
in a formatter's __init__"""
sort_on = interface.Attribute(
"""list of (colmun name, reversed boolean) beginning with the primary
sort column.""")
def __getitem__(key):
"""given index or slice, returns requested item(s) based on sort order.
"""
def __iter__():
"""iterates over items in sort order"""
def __len__():
"""returns len of sorted items"""
def setFormatter(formatter):
"tell the items about the formatter before using any of the methods"
class IFormatter(interface.Interface):
annotations = schema.Dict(
title="Annotations",
description='Stores arbitrary application data under '
'package-unique keys. '
'By "package-unique keys", we mean keys that are are unique by '
'virtue of including the dotted name of a package as a prefix. '
'A package name is used to limit the authority for picking names '
'for a package to the people using that package. '
'For example, when implementing annotations for a zc.foo package, '
'the key would be (or at least begin with) the following::'
''
' "zc.foo"')
request = schema.Field(
title='Request',
description='The request object.',
)
context = schema.Field(
title='Context',
description='The (Zope ILocation) context for which the table '
'formatter is rendering')
items = schema.List(
title='Items',
description='The items that will be rendered by __call__. items '
'preferably support a way to get a slice (__getitem__ or the '
'deprecated getslice) or alternatively may merely be iterable. '
'see getItems.')
columns = schema.Tuple(
title='All the columns that make up this table.',
description='All columns that may ever be a visible column. A non-'
'visible column may still have an effect on operations such as '
'sorting. The names of all columns must be unique within the '
'sequence.',
unique=True,
)
visible_columns = schema.Tuple(
title='The visible columns that make up this table.',
description='The columns to display when rendering this table.',
unique=True,
)
batch_size = schema.Int(
title='Number of rows per page',
description='The number of rows to show at a time. '
'Set to 0 for no batching.',
default=20,
min=0,
)
batch_start = schema.Int(
title='Batch Start',
description='The starting index for batching.',
default=0,
)
prefix = schema.BytesLine(
title='Prefix',
description='The prefix for all form names',
constraint=pythonLikeNameConstraint,
)
columns_by_name = schema.Dict(
title='Columns by Name',
description='A mapping of column name to column object')
cssClasses = schema.Dict(
title='CSS Classes',
description='A mapping from an HTML element to a CSS class',
key_type=schema.TextLine(title='The HTML element name'),
value_type=schema.TextLine(title='The CSS class name'))
def __call__():
"""Render a complete HTML table from self.items."""
def renderHeaderRow():
"""Render an HTML table header row from the column headers.
Uses renderHeaders."""
def renderHeaders():
"""Render the individual HTML headers from the columns.
Uses renderHeader."""
def renderHeader(column):
"""Render a header for the given column.
Uses getHeader."""
def getHeader(column):
"""Render header contents for the given column.
Includes appropriate code for enabling ISortableColumn.
Uses column.renderHeader"""
def getHeaders():
"""Retrieve a sequence of rendered column header contents.
Uses getHeader.
Available for more low-level use of a table; not used by the other
table code."""
def renderRows():
"""Render HTML rows for the self.items.
Uses renderRow and getItems."""
def getRows():
"""Retrieve a sequence of sequences of rendered cell contents.
Uses getCells and getItems.
Available for more low-level use of a table; not used by the other
table code."""
def getCells(item):
"""Retrieve a sequence rendered cell contents for the item.
Uses getCell.
Available for more low-level use of a table; not used by the other
table code."""
def getCell(item, column):
"""Render the cell contents for the item and column."""
def renderRow(item):
"""Render a row for the given item.
Uses renderCells."""
def renderCells(item):
"""Render the cells--the contents of a row--for the given item.
Uses renderCell."""
def renderCell(item, column):
"""Render the cell for the item and column.
Uses getCell."""
def getItems():
"""Returns the items to be rendered from the full set of self.items.
Should be based on batch_start and batch_size, if set.
"""
class IFormatterFactory(interface.Interface):
"""When called returns a table formatter.
Takes the same arguments as zc.table.table.Formatter""" | zc.table | /zc.table-1.0.tar.gz/zc.table-1.0/src/zc/table/interfaces.py | interfaces.py |
Useful column types
===================
We provide a number of pre-defined column types to use in table
definitions.
Field Edit Columns
------------------
Field edit columns provide support for tables of input widgets.
To define a field edit column, you need to provide:
- title, the label to be displayed
- a prefix, which is used to distinguish a columns inputs
from those of other columns
- a field that describes the type of data in the column
- an id getter
- an optional data getter, and
- an optional data setter
The id getter has to compute a string that uniquely identified an
item.
Let's look at a simple example. We have a collection of contacts,
with names and email addresses:
>>> import re
>>> from zope import schema, interface
>>> class IContact(interface.Interface):
... name = schema.TextLine()
... email = schema.TextLine(
... constraint=re.compile(r'\w+@\w+([.]\w+)+$').match)
>>> @interface.implementer(IContact)
... class Contact:
... def __init__(self, id, name, email):
... self.id = id
... self.name = name
... self.email = email
>>> contacts = (
... Contact('1', 'Bob Smith', '[email protected]'),
... Contact('2', 'Sally Baker', '[email protected]'),
... Contact('3', 'Jethro Tul', '[email protected]'),
... Contact('4', 'Joe Walsh', '[email protected]'),
... )
We'll define columns that allow us to display and edit name and
email addresses.
>>> from zc.table import column
>>> columns = (
... column.FieldEditColumn(
... "Name", "test", IContact["name"],
... lambda contact: contact.id,
... ),
... column.FieldEditColumn(
... "Email address", "test", IContact["email"],
... lambda contact: contact.id,
... ),
... )
Now, with this, we can create a table with input widgets. The columns don't
need a context other than the items themselves, so we ignore that part of the
table formatter instantiation:
>>> from zc import table
>>> import zope.publisher.browser
>>> request = zope.publisher.browser.TestRequest()
>>> context = None
>>> formatter = table.Formatter(
... context, request, contacts, columns=columns)
>>> print(formatter())
<table>
<thead>
<tr>
<th>
Name
</th>
<th>
Email address
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input class="textType" id="test.MQ==.name" name="test.MQ==.name"
size="20" type="text" value="Bob Smith" />
</td>
<td>
<input class="textType" id="test.MQ==.email" name="test.MQ==.email"
size="20" type="text" value="[email protected]" />
</td>
</tr>
<tr>
<td>
<input class="textType" id="test.Mg==.name" name="test.Mg==.name"
size="20" type="text" value="Sally Baker" />
</td>
<td>
<input class="textType" id="test.Mg==.email" name="test.Mg==.email"
size="20" type="text" value="[email protected]" />
</td>
</tr>
<tr>
<td>
<input class="textType" id="test.Mw==.name" name="test.Mw==.name"
size="20" type="text" value="Jethro Tul" />
</td>
<td>
<input class="textType" id="test.Mw==.email" name="test.Mw==.email"
size="20" type="text" value="[email protected]" />
</td>
</tr>
<tr>
<td>
<input class="textType" id="test.NA==.name" name="test.NA==.name"
size="20" type="text" value="Joe Walsh" />
</td>
<td>
<input class="textType" id="test.NA==.email" name="test.NA==.email"
size="20" type="text" value="[email protected]" />
</td>
</tr>
</tbody>
</table>
Note that the input names include base64 encodings of the item ids.
If the request has input for a value, then this will override item data:
>>> request.form["test.NA==.email"] = '[email protected]'
>>> print(formatter())
<table>
<thead>
<tr>
<th>
Name
</th>
<th>
Email address
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input class="textType" id="test.MQ==.name" name="test.MQ==.name"
size="20" type="text" value="Bob Smith" />
</td>
<td>
<input class="textType" id="test.MQ==.email" name="test.MQ==.email"
size="20" type="text" value="[email protected]" />
</td>
</tr>
<tr>
<td>
<input class="textType" id="test.Mg==.name" name="test.Mg==.name"
size="20" type="text" value="Sally Baker" />
</td>
<td>
<input class="textType" id="test.Mg==.email" name="test.Mg==.email"
size="20" type="text" value="[email protected]" />
</td>
</tr>
<tr>
<td>
<input class="textType" id="test.Mw==.name" name="test.Mw==.name"
size="20" type="text" value="Jethro Tul" />
</td>
<td>
<input class="textType" id="test.Mw==.email" name="test.Mw==.email"
size="20" type="text" value="[email protected]" />
</td>
</tr>
<tr>
<td>
<input class="textType" id="test.NA==.name" name="test.NA==.name"
size="20" type="text" value="Joe Walsh" />
</td>
<td>
<input class="textType" id="test.NA==.email" name="test.NA==.email"
size="20" type="text" value="[email protected]" />
</td>
</tr>
</tbody>
</table>
and the contact data is unchanged:
>>> contacts[3].email
'[email protected]'
Field edit columns provide methods for getting and validating input
data, and fpr updating the undelying data:
>>> data = columns[1].input(contacts, request)
>>> data
{'NA==': '[email protected]'}
The data returned is a mapping from item id to input value. Items
that don't have input are ignored. The data can be used with the
update function to update the underlying data:
>>> columns[1].update(contacts, data)
True
>>> contacts[3].email
'[email protected]'
Note that the update function returns a boolean value indicating
whether any changes were made:
>>> columns[1].update(contacts, data)
False
The input function also validates input. If there are any errors, a
WidgetsError will be raised:
>>> request.form["test.NA==.email"] = 'walsh'
>>> data = columns[1].input(contacts, request)
Traceback (most recent call last):
...
zope.formlib.interfaces.WidgetsError: WidgetInputError:
('email', '', ConstraintNotSatisfied('walsh', 'email'))
Custom getters and setters
--------------------------
Normally, the given fields getter and setter is used, however, custom
getters and setters can be provided. Let's look at an example of
a bit table:
>>> data = [0, 0], [1, 1], [2, 2], [3, 3]
>>> def setbit(data, bit, value):
... value = bool(value) << bit
... mask = 1 << bit
... data[1] = ((data[1] | mask) ^ mask) | value
>>> columns = (
... column.FieldEditColumn(
... "Bit 0", "test", schema.Bool(__name__='0'),
... lambda data: str(data[0]),
... getter = lambda data: 1&(data[1]),
... setter = lambda data, v: setbit(data, 0, v),
... ),
... column.FieldEditColumn(
... "Bit 1", "test", schema.Bool(__name__='1'),
... lambda data: str(data[0]),
... getter = lambda data: 2&(data[1]),
... setter = lambda data, v: setbit(data, 1, v),
... ),
... )
>>> context = None # not needed
>>> request = zope.publisher.browser.TestRequest()
>>> formatter = table.Formatter(
... context, request, data, columns=columns)
>>> print(formatter())
<table>
<thead>
<tr>
<th>
Bit 0
</th>
<th>
Bit 1
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input class="hiddenType" id="test.MA==.0.used"
name="test.MA==.0.used" type="hidden" value="" />
<input class="checkboxType" id="test.MA==.0"
name="test.MA==.0" type="checkbox" value="on" />
</td>
<td>
<input class="hiddenType" id="test.MA==.1.used"
name="test.MA==.1.used" type="hidden" value="" />
<input class="checkboxType" id="test.MA==.1"
name="test.MA==.1" type="checkbox" value="on" />
</td>
</tr>
<tr>
<td>
<input class="hiddenType" id="test.MQ==.0.used"
name="test.MQ==.0.used" type="hidden" value="" />
<input class="checkboxType" checked="checked" id="test.MQ==.0"
name="test.MQ==.0" type="checkbox" value="on" />
</td>
<td>
<input class="hiddenType" id="test.MQ==.1.used"
name="test.MQ==.1.used" type="hidden" value="" />
<input class="checkboxType" id="test.MQ==.1"
name="test.MQ==.1" type="checkbox" value="on" />
</td>
</tr>
<tr>
<td>
<input class="hiddenType" id="test.Mg==.0.used"
name="test.Mg==.0.used" type="hidden" value="" />
<input class="checkboxType" id="test.Mg==.0"
name="test.Mg==.0" type="checkbox" value="on" />
</td>
<td>
<input class="hiddenType" id="test.Mg==.1.used"
name="test.Mg==.1.used" type="hidden" value="" />
<input class="checkboxType" checked="checked" id="test.Mg==.1"
name="test.Mg==.1" type="checkbox" value="on" />
</td>
</tr>
<tr>
<td>
<input class="hiddenType" id="test.Mw==.0.used"
name="test.Mw==.0.used" type="hidden" value="" />
<input class="checkboxType" checked="checked" id="test.Mw==.0"
name="test.Mw==.0" type="checkbox" value="on" />
</td>
<td>
<input class="hiddenType" id="test.Mw==.1.used"
name="test.Mw==.1.used" type="hidden" value="" />
<input class="checkboxType" checked="checked" id="test.Mw==.1"
name="test.Mw==.1" type="checkbox" value="on" />
</td>
</tr>
</tbody>
</table>
>>> request.form["test.Mw==.1.used"] = ""
>>> request.form["test.MA==.1.used"] = ""
>>> request.form["test.MA==.1"] = "on"
>>> input = columns[1].input(data, request)
>>> from pprint import pprint
>>> pprint(input)
{'MA==': True,
'Mw==': False}
>>> columns[1].update(data, input)
True
>>> data
([0, 2], [1, 1], [2, 2], [3, 1])
Column names
============
When defining columns, you can supply separate names and titles. You
would do this, for example, to use a blank title:
>>> columns = (
... column.FieldEditColumn(
... "", "test", schema.Bool(__name__='0'),
... lambda data: str(data[0]),
... getter = lambda data: 1&(data[1]),
... setter = lambda data, v: setbit(data, 0, v),
... name = "0",
... ),
... column.FieldEditColumn(
... "", "test", schema.Bool(__name__='1'),
... lambda data: str(data[0]),
... getter = lambda data: 2&(data[1]),
... setter = lambda data, v: setbit(data, 1, v),
... name = "1",
... ),
... )
>>> formatter = table.Formatter(
... context, request, data[0:1], columns=columns)
>>> print(formatter())
<table>
<thead>
<tr>
<th>
<BLANKLINE>
</th>
<th>
<BLANKLINE>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input class="hiddenType" id="test.MA==.0.used"
name="test.MA==.0.used" type="hidden" value="" />
<input class="checkboxType" id="test.MA==.0"
name="test.MA==.0" type="checkbox" value="on" />
</td>
<td>
<input class="hiddenType" id="test.MA==.1.used"
name="test.MA==.1.used" type="hidden" value="" />
<input class="checkboxType" checked="checked" id="test.MA==.1"
name="test.MA==.1" type="checkbox" value="on" />
</td>
</tr>
</tbody>
</table>
<>& encoding bug
================
There was a bug in column.py, it did not encode the characters <>& to
< > &
>>> bugcontacts = (
... Contact('1', 'Bob <Smith>', '[email protected]'),
... Contact('2', 'Sally & Baker', '[email protected]'),
... )
We'll define columns that displays name and email addresses.
>>> from zc.table import column
>>> bugcolumns = (
... column.GetterColumn(
... title="Name", name="name",
... getter=lambda contact, formatter: contact.name,
... ),
... column.GetterColumn(
... title="E-mail", name="email",
... getter=lambda contact, formatter: contact.email,
... ),
... )
>>> request = zope.publisher.browser.TestRequest()
>>> context = None
>>> formatter = table.Formatter(
... context, request, bugcontacts, columns=bugcolumns)
>>> print(formatter())
<table>
<thead>
<tr>
<th>
Name
</th>
<th>
E-mail
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
Bob <Smith>
</td>
<td>
[email protected]
</td>
</tr>
<tr>
<td>
Sally & Baker
</td>
<td>
[email protected]
</td>
</tr>
</tbody>
</table>
>>> from zc.table import column
>>> bug2columns = (
... column.FieldEditColumn(
... "Name", "test", IContact["name"],
... lambda contact: contact.id,
... ),
... column.FieldEditColumn(
... "Email address", "test", IContact["email"],
... lambda contact: contact.id,
... ),
... )
>>> formatter = table.Formatter(
... context, request, bugcontacts, columns=bug2columns)
>>> print(formatter())
<BLANKLINE>
<table>
<thead>
<tr>
<th>
Name
</th>
<th>
Email address
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input class="textType" id="test.MQ==.name" name="test.MQ==.name"
size="20" type="text" value="Bob <Smith>" />
</td>
<td>
<input class="textType" id="test.MQ==.email" name="test.MQ==.email"
size="20" type="text" value="[email protected]" />
</td>
</tr>
<tr>
<td>
<input class="textType" id="test.Mg==.name" name="test.Mg==.name"
size="20" type="text" value="Sally & Baker" />
</td>
<td>
<input class="textType" id="test.Mg==.email" name="test.Mg==.email"
size="20" type="text" value="[email protected]" />
</td>
</tr>
</tbody>
</table>
<BLANKLINE>
| zc.table | /zc.table-1.0.tar.gz/zc.table-1.0/src/zc/table/column.rst | column.rst |
import re
from xml.sax.saxutils import quoteattr
import zope.formlib.form
import zope.formlib.interfaces
import zope.schema.interfaces
from zope import component
from zope.formlib.interfaces import IDisplayWidget
from zope.formlib.interfaces import IInputWidget
from zope.formlib.interfaces import WidgetInputError
from zope.formlib.interfaces import WidgetsError
from zc.table import column
isSafe = re.compile(r'[\w +/]*$').match
def toSafe(string):
# We don't want to use base64 unless we have to,
# because it makes testing and reading html more difficult. We make this
# safe because all base64 strings will have a trailing '=', and our
# `isSafe` regex does not allow '=' at all. The only downside to the
# approach is that a 'safe' string generated by the `toSafe` base64 code
# will not pass the `isSafe` test, so the function is not idempotent. The
# simpler version (without the `isSafe` check) was not idempotent either,
# so no great loss.
if not isSafe(string):
string = ''.join(string.encode('base64').split())
return string
class BaseColumn(column.Column):
# subclass helper API (not expected to be overridden)
def getPrefix(self, item, formatter):
prefix = self.getId(item, formatter)
if formatter.prefix:
prefix = '{}.{}'.format(formatter.prefix, prefix)
return prefix
@property
def key(self):
return '{}.{}.{}'.format(
self.__class__.__module__,
self.__class__.__name__,
self.name)
def setAnnotation(self, name, value, formatter):
formatter.annotations[self.key + name] = value
def getAnnotation(self, name, formatter, default=None):
return formatter.annotations.get(self.key + name, default)
# subclass customization API
def getId(self, item, formatter):
return toSafe(str(item))
class FieldColumn(BaseColumn):
"""Column that supports field/widget update
"""
__slots__ = ('title', 'name', 'field') # to emphasize that this should not
# have thread-local attributes such as request
def __init__(self, field, title=None, name=''):
if zope.schema.interfaces.IField.providedBy(field):
field = zope.formlib.form.FormField(field)
else:
assert zope.formlib.interfaces.IFormField.providedBy(field)
self.field = field
if title is None:
title = self.field.field.title
if not name and self.field.__name__:
name = self.field.__name__
super().__init__(title, name)
# subclass helper API (not expected to be overridden)
def getInputWidget(self, item, formatter):
form_field = self.field
field = form_field.field
request = formatter.request
prefix = self.getPrefix(item, formatter)
context = self.getFieldContext(item, formatter)
if context is not None:
field = form_field.field.bind(context)
if form_field.custom_widget is None:
if field.readonly or form_field.for_display:
iface = IDisplayWidget
else:
iface = IInputWidget
widget = component.getMultiAdapter((field, request), iface)
else:
widget = form_field.custom_widget(field, request)
if form_field.prefix: # this should not be necessary AFAICT
prefix = '{}.{}'.format(prefix, form_field.prefix)
widget.setPrefix(prefix)
return widget
def getRenderWidget(self, item, formatter, ignore_request=False):
widget = self.getInputWidget(item, formatter)
if (ignore_request or
IDisplayWidget.providedBy(widget) or
not widget.hasInput()):
widget.setRenderedValue(self.get(item, formatter))
return widget
# subclass customization API
def get(self, item, formatter):
return self.field.field.get(item)
def set(self, item, value, formatter):
self.field.field.set(item, value)
def getFieldContext(self, item, formatter):
return None
# main API: input, update, and custom renderCell
def input(self, items, formatter):
data = {}
errors = []
for item in items:
widget = self.getInputWidget(item, formatter)
if widget.hasInput():
try:
data[self.getId(item, formatter)] = widget.getInputValue()
except WidgetInputError as v:
errors.append(v)
if errors:
raise WidgetsError(errors)
return data
def update(self, items, data, formatter):
changed = False
for item in items:
id = self.getId(item, formatter)
v = data.get(id, self)
if v is not self and self.get(item, formatter) != v:
self.set(item, v, formatter)
changed = True
if changed:
self.setAnnotation('changed', changed, formatter)
return changed
def renderCell(self, item, formatter):
ignore_request = self.getAnnotation('changed', formatter)
return self.getRenderWidget(
item, formatter, ignore_request)()
class SubmitColumn(BaseColumn):
# subclass helper API (not expected to be overridden)
def getIdentifier(self, item, formatter):
return '{}.{}'.format(self.getPrefix(item, formatter), self.name)
def renderWidget(self, item, formatter, **kwargs):
res = ['{}={}'.format(k, quoteattr(v)) for k, v in kwargs.items()]
lbl = self.getLabel(item, formatter)
res[0:0] = [
'input',
'type="submit"',
'name=%s' % quoteattr(self.getIdentifier(item, formatter)),
'value=%s' % quoteattr(lbl)]
return '<%s />' % (' '.join(res))
# customization API (expected to be overridden)
def getLabel(self, item, formatter):
return super().renderHeader(formatter) # title
# basic API
def input(self, items, formatter):
for item in items:
if self.getIdentifier(item, formatter) in formatter.request.form:
return item
def update(self, items, item, formatter):
raise NotImplementedError
def renderCell(self, item, formatter):
return self.renderWidget(item, formatter)
def renderHeader(self, formatter):
return '' | zc.table | /zc.table-1.0.tar.gz/zc.table-1.0/src/zc/table/fieldcolumn.py | fieldcolumn.py |
FieldColumn
===========
The FieldColumn is intended to be a replacement for the FieldEditColumn. It
has the following goals.
- Support the standard column pattern of instantiating a single module global
column set, and using formatters to store and access information about a
single given rendering. The formatter has annotations, prefix, context, and
request, all of which are desired or even essential for various derived
columns. Generally, the formatter has state that the columns need.
- Support display widgets, in addition to input widgets.
- Support formlib form fields, to support custom widgets and other formlib
field features.
It also has an important design difference. Rather than relying on functions
passed at initialization for column customization, the field column returns to
a standard subclass design. The column expects that any of the following
methods may be overridden:
- getId(item, formatter): given an item whose value is to be displayed in the
column, return a form-friendly string identifier, unique to the item. We
define 'form-friendly' as containing characters that are alphanumeric or a
space, a plus, a slash, or an equals sign (that is, the standard characters
used in MIME-based base64, excluding new lines).
- get(item, formatter): return the current value for the item.
- set(item, value, formatter): set the given value for the item.
- getFieldContext(item, formatter): return a context to which a field should
be bound, or None.
- renderCell(item, formatter): the standard rendering of a cell
- renderHeader(formatter): the standard rendering of a column header.
Without subclassing, the column uses field.get and field.set to get and set
values, returns None for bound context, and just renders the field's widget for
the cell, and the title for the header. Let's look at the default behavior.
We'll use a modified version of the examples given for the FieldEditColumn in
column.txt.
To create a FieldColumn, you must minimally provide a schema field or form
field. If title is not provided, it is the field's title, or empty if the
field has no title. A explicit title of an empty string is acceptable and will
be honored. If name is not provided, it is the field's __name__.
Let's look at a simple example. We have a collection of contacts,
with names and email addresses:
>>> import re
>>> from zope import schema, interface
>>> class IContact(interface.Interface):
... name = schema.TextLine(title='Name')
... email = schema.TextLine(
... title='Email Address',
... constraint=re.compile(r'\w+@\w+([.]\w+)+$').match)
... salutation = schema.Choice(
... title='Salutation',
... values = ['Mr','Ms'],
... )
>>> @interface.implementer(IContact)
... class Contact:
... def __init__(self, id, name, email, salutation):
... self.id = id
... self.name = name
... self.email = email
... self.salutation = salutation
>>> contacts = (
... Contact('1', 'Bob Smith', '[email protected]', 'Mr'),
... Contact('2', 'Sally Baker', '[email protected]', 'Ms'),
... Contact('3', 'Jethro Tul', '[email protected]', 'Mr'),
... Contact('4', 'Joe Walsh', '[email protected]', 'Mr'),
... )
We'll define columns that allow us to display and edit name and
email addresses.
>>> from zc.table import fieldcolumn
>>> class ContactColumn(fieldcolumn.FieldColumn):
... def getId(self, item, formatter):
... return fieldcolumn.toSafe(item.id)
...
>>> class BindingContactColumn(ContactColumn):
... def getFieldContext(self, item, formatter):
... return item
...
>>> columns = (ContactColumn(IContact["name"]),
... ContactColumn(IContact["email"]),
... BindingContactColumn(IContact["salutation"])
... )
Now, with this, we can create a table with input widgets. The columns don't
need a context other than the items themselves, so we ignore that part of the
table formatter instantiation:
>>> from zc import table
>>> import zope.publisher.browser
>>> request = zope.publisher.browser.TestRequest()
>>> context = None
>>> formatter = table.Formatter(
... context, request, contacts, columns=columns, prefix='test')
>>> print(formatter())
<table>
<thead>
<tr>
<th>
Name
</th>
<th>
Email Address
</th>
<th>
Salutation
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input class="textType" id="test.1.name" name="test.1.name"
size="20" type="text" value="Bob Smith" />
</td>
<td>
<input class="textType" id="test.1.email" name="test.1.email"
size="20" type="text" value="[email protected]" />
</td>
<td>
<div>
<div class="value">
<select id="test.1.salutation" name="test.1.salutation"
size="1" >
<option selected="selected" value="Mr">Mr</option>
<option value="Ms">Ms</option>
</select>
</div>
<input name="test.1.salutation-empty-marker" type="hidden"
value="1" />
</div>
</td>
</tr>
<tr>
<td>
<input class="textType" id="test.2.name" name="test.2.name"
size="20" type="text" value="Sally Baker" />
</td>
<td>
<input class="textType" id="test.2.email" name="test.2.email"
size="20" type="text" value="[email protected]" />
</td>
<td>
<div>
<div class="value">
<select id="test.2.salutation" name="test.2.salutation"
size="1" >
<option value="Mr">Mr</option>
<option selected="selected" value="Ms">Ms</option>
</select>
</div>
<input name="test.2.salutation-empty-marker" type="hidden"
value="1" />
</div>
</td>
</tr>
<tr>
<td>
<input class="textType" id="test.3.name" name="test.3.name"
size="20" type="text" value="Jethro Tul" />
</td>
<td>
<input class="textType" id="test.3.email" name="test.3.email"
size="20" type="text" value="[email protected]" />
</td>
<td>
<div>
<div class="value">
<select id="test.3.salutation" name="test.3.salutation"
size="1" >
<option selected="selected" value="Mr">Mr</option>
<option value="Ms">Ms</option>
</select>
</div>
<input name="test.3.salutation-empty-marker" type="hidden"
value="1" />
</div>
</td>
</tr>
<tr>
<td>
<input class="textType" id="test.4.name" name="test.4.name"
size="20" type="text" value="Joe Walsh" />
</td>
<td>
<input class="textType" id="test.4.email" name="test.4.email"
size="20" type="text" value="[email protected]" />
</td>
<td>
<div>
<div class="value">
<select id="test.4.salutation" name="test.4.salutation"
size="1" >
<option selected="selected" value="Mr">Mr</option>
<option value="Ms">Ms</option>
</select>
</div>
<input name="test.4.salutation-empty-marker" type="hidden"
value="1" />
</div>
</td>
</tr>
</tbody>
</table>
Note that the input names do not include base64 encodings of the item ids
because they already match the necessary constraints.
If the request has input for a value, then this will override item data:
>>> request.form["test.4.email"] = '[email protected]'
>>> print(formatter())
<table>
<thead>
<tr>
<th>
Name
</th>
<th>
Email Address
</th>
<th>
Salutation
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input class="textType" id="test.1.name" name="test.1.name"
size="20" type="text" value="Bob Smith" />
</td>
<td>
<input class="textType" id="test.1.email" name="test.1.email"
size="20" type="text" value="[email protected]" />
</td>
<td>
<div>
<div class="value">
<select id="test.1.salutation" name="test.1.salutation"
size="1" >
<option selected="selected" value="Mr">Mr</option>
<option value="Ms">Ms</option>
</select>
</div>
<input name="test.1.salutation-empty-marker" type="hidden"
value="1" />
</div>
</td>
</tr>
<tr>
<td>
<input class="textType" id="test.2.name" name="test.2.name"
size="20" type="text" value="Sally Baker" />
</td>
<td>
<input class="textType" id="test.2.email" name="test.2.email"
size="20" type="text" value="[email protected]" />
</td>
<td>
<div>
<div class="value">
<select id="test.2.salutation" name="test.2.salutation"
size="1" >
<option value="Mr">Mr</option>
<option selected="selected" value="Ms">Ms</option>
</select>
</div>
<input name="test.2.salutation-empty-marker" type="hidden"
value="1" />
</div>
</td>
</tr>
<tr>
<td>
<input class="textType" id="test.3.name" name="test.3.name"
size="20" type="text" value="Jethro Tul" />
</td>
<td>
<input class="textType" id="test.3.email" name="test.3.email"
size="20" type="text" value="[email protected]" />
</td>
<td>
<div>
<div class="value">
<select id="test.3.salutation" name="test.3.salutation"
size="1" >
<option selected="selected" value="Mr">Mr</option>
<option value="Ms">Ms</option>
</select>
</div>
<input name="test.3.salutation-empty-marker" type="hidden"
value="1" />
</div>
</td>
</tr>
<tr>
<td>
<input class="textType" id="test.4.name" name="test.4.name"
size="20" type="text" value="Joe Walsh" />
</td>
<td>
<input class="textType" id="test.4.email" name="test.4.email"
size="20" type="text" value="[email protected]" />
</td>
<td>
<div>
<div class="value">
<select id="test.4.salutation" name="test.4.salutation"
size="1" >
<option selected="selected" value="Mr">Mr</option>
<option value="Ms">Ms</option>
</select>
</div>
<input name="test.4.salutation-empty-marker" type="hidden"
value="1" />
</div>
</td>
</tr>
</tbody>
</table>
and the contact data is unchanged:
>>> contacts[3].email
'[email protected]'
Field edit columns provide methods for getting and validating input
data, and for updating the undelying data:
>>> data = columns[1].input(contacts, formatter)
>>> data
{'4': '[email protected]'}
The data returned is a mapping from item id to input value. Items
that don't have input are ignored. The data can be used with the
update function to update the underlying data:
>>> columns[1].update(contacts, data, formatter)
True
>>> contacts[3].email
'[email protected]'
Note that the update function returns a boolean value indicating
whether any changes were made:
>>> columns[1].update(contacts, data, formatter)
False
The input function also validates input. If there are any errors, a
WidgetsError will be raised:
>>> request.form["test.4.email"] = 'walsh'
>>> try:
... data = columns[1].input(contacts, formatter)
... except zope.formlib.interfaces.WidgetsError as e:
... e
WidgetInputError: ('email', 'Email Address', ConstraintNotSatisfied('walsh', 'email'))
Custom getters and setters
--------------------------
Normally, the given fields getter and setter is used, however, custom
getters and setters can be provided. Let's look at an example of
a bit table:
>>> data = [0, 0], [1, 1], [2, 2], [3, 3]
>>> class BitColumn(fieldcolumn.FieldColumn):
... def __init__(self, field, bit, title=None, name=''):
... super(BitColumn, self).__init__(field, title, name)
... self.bit = bit
... def getId(self, item, formatter):
... return str(item[0])
... def get(self, item, formatter):
... return (1 << self.bit)&(item[1])
... def set(self, item, value, formatter):
... value = bool(value) << self.bit
... mask = 1 << self.bit
... item[1] = ((item[1] | mask) ^ mask) | value
>>> columns = (
... BitColumn(schema.Bool(__name__='0', title='Bit 0'), 0),
... BitColumn(schema.Bool(__name__='1', title='Bit 1'), 1))
>>> context = None # not needed
>>> request = zope.publisher.browser.TestRequest()
>>> formatter = table.Formatter(
... context, request, data, columns=columns, prefix='test')
>>> print(formatter())
<table>
<thead>
<tr>
<th>
Bit 0
</th>
<th>
Bit 1
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input class="hiddenType" id="test.0.0.used"
name="test.0.0.used" type="hidden" value="" />
<input class="checkboxType" id="test.0.0"
name="test.0.0" type="checkbox" value="on" />
</td>
<td>
<input class="hiddenType" id="test.0.1.used"
name="test.0.1.used" type="hidden" value="" />
<input class="checkboxType" id="test.0.1"
name="test.0.1" type="checkbox" value="on" />
</td>
</tr>
<tr>
<td>
<input class="hiddenType" id="test.1.0.used"
name="test.1.0.used" type="hidden" value="" />
<input class="checkboxType" checked="checked" id="test.1.0"
name="test.1.0" type="checkbox" value="on" />
</td>
<td>
<input class="hiddenType" id="test.1.1.used"
name="test.1.1.used" type="hidden" value="" />
<input class="checkboxType" id="test.1.1"
name="test.1.1" type="checkbox" value="on" />
</td>
</tr>
<tr>
<td>
<input class="hiddenType" id="test.2.0.used"
name="test.2.0.used" type="hidden" value="" />
<input class="checkboxType" id="test.2.0"
name="test.2.0" type="checkbox" value="on" />
</td>
<td>
<input class="hiddenType" id="test.2.1.used"
name="test.2.1.used" type="hidden" value="" />
<input class="checkboxType" checked="checked" id="test.2.1"
name="test.2.1" type="checkbox" value="on" />
</td>
</tr>
<tr>
<td>
<input class="hiddenType" id="test.3.0.used"
name="test.3.0.used" type="hidden" value="" />
<input class="checkboxType" checked="checked" id="test.3.0"
name="test.3.0" type="checkbox" value="on" />
</td>
<td>
<input class="hiddenType" id="test.3.1.used"
name="test.3.1.used" type="hidden" value="" />
<input class="checkboxType" checked="checked" id="test.3.1"
name="test.3.1" type="checkbox" value="on" />
</td>
</tr>
</tbody>
</table>
>>> request.form["test.3.1.used"] = ""
>>> request.form["test.0.1.used"] = ""
>>> request.form["test.0.1"] = "on"
>>> input = columns[1].input(data, formatter)
>>> from pprint import pprint
>>> pprint(input)
{'0': True,
'3': False}
>>> columns[1].update(data, input, formatter)
True
>>> data
([0, 2], [1, 1], [2, 2], [3, 1])
| zc.table | /zc.table-1.0.tar.gz/zc.table-1.0/src/zc/table/fieldcolumn.rst | fieldcolumn.rst |
"""Table formatting and configuration
"""
from zope import interface
from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile
import zc.table.interfaces
import zc.table.table
unspecified = object()
class Formatter(zc.table.table.FormSortFormatterMixin,
zc.table.table.AlternatingRowFormatterMixin,
zc.table.table.Formatter):
interface.classProvides(zc.table.interfaces.IFormatterFactory)
def __init__(self, context, request, items, visible_column_names=None,
batch_start=None, batch_size=unspecified, prefix=None,
columns=None, sort_on=None):
if batch_size is unspecified:
batch_size = 20
if prefix is None:
prefix = 'zc.table'
super().__init__(
context, request, items, visible_column_names,
batch_start, batch_size, prefix, columns,
sort_on=sort_on,
)
@property
def batch_change_name(self):
return self.prefix + '.batch_change'
@property
def batch_start_name(self):
return self.prefix + '.batch_start'
_batch_start = None
_batch_start_computed = False
def setPrefix(self, prefix):
super().setPrefix(prefix)
self._batch_start_computed = False
@property
def batch_start(self):
if not self._batch_start_computed:
self.updateBatching()
return self._batch_start
@batch_start.setter
def batch_start(self, value):
self._batch_start = value
self._batch_start_computed = False
@batch_start.deleter
def batch_start(self):
self._batch_start = None
def updateBatching(self):
request = self.request
if self._batch_start is None:
try:
self.batch_start = int(request.get(self.batch_start_name, '0'))
except ValueError:
self._batch_start = 0
# Handle requests to change batches:
change = request.get(self.batch_change_name)
if change == "next":
self._batch_start += self.batch_size
try:
length = len(self.items)
except TypeError:
for length, ob in enumerate(self.items):
if length > self._batch_start:
break
else:
self._batch_start = length
else:
if self._batch_start > length:
self._batch_start = length
elif change == "back":
self._batch_start -= self.batch_size
if self._batch_start < 0:
self._batch_start = 0
self.next_batch_start = self._batch_start + self.batch_size
try:
self.items[self.next_batch_start]
except IndexError:
self.next_batch_start = None
self.previous_batch_start = self._batch_start - self.batch_size
if self.previous_batch_start < 0:
self.previous_batch_start = None
self._batch_start_computed = True
batching_template = ViewPageTemplateFile('batching.pt')
def renderExtra(self):
if not self._batch_start_computed:
self.updateBatching()
return self.batching_template() + super().renderExtra()
def __call__(self):
return ('\n'
'<div style="width: 100%"> '
'<!-- this div is a workaround for an IE bug -->\n'
'<table class="listingdescription" style="width:100%" '
+ ('name="%s">\n' % self.prefix)
+ self.renderContents() +
'</table>\n'
+ self.renderExtra() +
'</div> <!-- end IE bug workaround -->\n'
) | zc.table | /zc.table-1.0.tar.gz/zc.table-1.0/src/zc/table/batching.py | batching.py |
from xml.sax.saxutils import quoteattr
import zc.resourcelibrary
import zope.cachedescriptors.property
from zope import component
from zope import interface
from zc.table import interfaces
@interface.implementer(interfaces.IFormatter)
class Formatter:
items = None
def __init__(self, context, request, items, visible_column_names=None,
batch_start=None, batch_size=None, prefix=None, columns=None):
self.context = context
self.request = request
self.annotations = {}
self.setItems(items)
if columns is None:
assert self.columns is not None
else:
self.columns = columns
if not visible_column_names:
self.visible_columns = self.columns
else:
self.visible_columns = [
self.columns_by_name[nm] for nm in visible_column_names]
self.batch_start = batch_start
self.batch_size = batch_size
self.prefix = prefix
self.cssClasses = {}
def setItems(self, items):
self.items = items
@zope.cachedescriptors.property.Lazy
def columns_by_name(self):
res = {}
for col in self.columns:
assert col.name not in res
res[col.name] = col
return res
def _getCSSClass(self, element):
klass = self.cssClasses.get(element)
return klass and ' class=%s' % quoteattr(klass) or ''
def __call__(self):
return '\n<table{}>\n{}</table>\n{}'.format(
self._getCSSClass('table'), self.renderContents(),
self.renderExtra())
def renderExtra(self):
zc.resourcelibrary.need('zc.table')
return ''
def renderContents(self):
return ' <thead{}>\n{} </thead>\n <tbody>\n{} </tbody>\n'.format(
self._getCSSClass('thead'), self.renderHeaderRow(),
self.renderRows())
def renderHeaderRow(self):
return ' <tr{}>\n{} </tr>\n'.format(
self._getCSSClass('tr'), self.renderHeaders())
def renderHeaders(self):
return ''.join(
[self.renderHeader(col) for col in self.visible_columns])
def renderHeader(self, column):
return ' <th{}>\n {}\n </th>\n'.format(
self._getCSSClass('th'), self.getHeader(column))
def getHeaders(self):
return [self.getHeader(column) for column in self.visible_columns]
def getHeader(self, column):
return column.renderHeader(self)
def renderRows(self):
return ''.join([self.renderRow(item) for item in self.getItems()])
def getRows(self):
for item in self.getItems():
yield [column.renderCell(item, self)
for column in self.visible_columns]
def renderRow(self, item):
return ' <tr{}>\n{} </tr>\n'.format(
self._getCSSClass('tr'), self.renderCells(item))
def renderCells(self, item):
return ''.join(
[self.renderCell(item, col) for col in self.visible_columns])
def renderCell(self, item, column):
return ' <td{}>\n {}\n </td>\n'.format(
self._getCSSClass('td'), self.getCell(item, column))
def getCells(self, item):
return [self.getCell(item, column) for column in self.visible_columns]
def getCell(self, item, column):
return column.renderCell(item, self)
def getItems(self):
batch_start = self.batch_start or 0
batch_size = self.batch_size or 0
if not self.batch_size:
if not batch_start: # ok, no work to be done.
for i in self.items:
yield i
return
batch_end = None
else:
batch_end = batch_start + batch_size
try:
for i in self.items[batch_start:batch_end]:
yield i
except (AttributeError, TypeError, NotImplementedError):
for i, item in enumerate(self.items):
if batch_end is not None and i >= batch_end:
return
if i >= batch_start:
yield item
# sorting helpers
@interface.implementer(interfaces.IColumnSortedItems)
class ColumnSortedItems:
# not intended to be persistent!
"""a wrapper for items that sorts lazily based on ISortableColumns.
Given items, a list of (column name, reversed boolean) pairs beginning
with the primary sort column, and the formatter, supports iteration, len,
and __getitem__ access including slices.
"""
formatter = None
def __init__(self, items, sort_on):
self._items = items
self.sort_on = sort_on # tuple of (column name, reversed) pairs
self._cache = []
self._iterable = None
@property
def items(self):
if getattr(self._items, '__getitem__', None) is not None:
return self._items
else:
return self._iter()
def _iter(self):
# this design is intended to handle multiple simultaneous iterations
ix = 0
cache = self._cache
iterable = self._iterable
if iterable is None:
iterable = self._iterable = iter(self._items)
while True:
try:
yield cache[ix]
except IndexError:
try:
nxt = next(iterable)
except StopIteration:
return
cache.append(nxt)
yield nxt
ix += 1
def setFormatter(self, formatter):
self.formatter = formatter
@property
def sorters(self):
res = []
for nm, reversed in self.sort_on:
column = self.formatter.columns_by_name[nm]
if reversed:
res.append(column.reversesort)
else:
res.append(column.sort)
return res
def __getitem__(self, key):
if isinstance(key, slice):
start = slice.start
stop = slice.stop
stride = slice.step
else:
start = stop = key
stride = 1
items = self.items
if not self.sort_on:
try:
return items.__getitem__(key)
except (AttributeError, TypeError):
if stride != 1:
raise NotImplementedError()
res = []
for ix, val in enumerate(items):
if ix >= start:
res.append(val)
if ix >= stop:
break
if isinstance(key, slice):
return res
elif res:
return res[0]
else:
raise IndexError('list index out of range')
items = self.sorters[0](
items, self.formatter, start, stop, self.sorters[1:])
if isinstance(key, slice):
return items[start:stop:stride]
else:
return items[key]
def __bool__(self):
try:
next(iter(self.items))
except StopIteration:
return False
return True
__nonzero__ = __bool__
def __iter__(self):
if not self.sort_on:
return iter(self.items)
else:
sorters = self.sorters
return iter(sorters[0](
self.items, self.formatter, 0, None, sorters[1:]))
def __len__(self):
return len(self.items)
def getRequestSortOn(request, sort_on_name):
"""get the sorting values from the request.
Returns a list of (name, reversed) pairs.
"""
# useful for code that wants to get the sort on values themselves
sort_on = None
sorting = request.form.get(sort_on_name)
if sorting:
offset = 0
res = {}
for ix, name in enumerate(sorting):
val = res.get(name)
if val is None:
res[name] = [ix + offset, name, False]
else:
val[0] = ix + offset
val[2] = not val[2]
if res:
res = sorted(res.values(), reverse=True)
sort_on = [[nm, reverse] for ix, nm, reverse in res]
return sort_on
def getMungedSortOn(request, sort_on_name, sort_on):
"""get the sorting values from the request.
optionally begins with sort_on values. Returns a list of (name, reversed)
pairs.
"""
res = getRequestSortOn(request, sort_on_name)
if res is None:
res = sort_on
elif sort_on:
for nm, reverse in sort_on:
for ix, (res_nm, res_reverse) in enumerate(res):
if nm == res_nm:
res[ix][1] = not (res_reverse ^ reverse)
break
else:
res.append([nm, reverse])
return res
def getSortOnName(prefix=None):
"""convert the table prefix to the 'sort on' name used in forms"""
# useful for code that wants to get the sort on values themselves
sort_on_name = 'sort_on'
if prefix is not None:
if not prefix.endswith('.'):
prefix += '.'
sort_on_name = prefix + sort_on_name
return sort_on_name
class SortingFormatterMixin:
"""automatically munges sort_on values with sort settings in the request.
"""
def __init__(self, context, request, items, visible_column_names=None,
batch_start=None, batch_size=None, prefix=None, columns=None,
sort_on=None, ignore_request=False):
if not ignore_request:
sort_on = getMungedSortOn(request, getSortOnName(prefix), sort_on)
else:
sort_on = sort_on
if sort_on or getattr(items, '__getitem__', None) is None:
items = ColumnSortedItems(items, sort_on)
super().__init__(
context, request, items, visible_column_names,
batch_start, batch_size, prefix, columns)
if sort_on:
items.setFormatter(self)
def setItems(self, items):
if (interfaces.IColumnSortedItems.providedBy(self.items) and
not interfaces.IColumnSortedItems.providedBy(items)):
items = ColumnSortedItems(items, self.items.sort_on)
if interfaces.IColumnSortedItems.providedBy(items):
items.setFormatter(self)
self.items = items
class AbstractSortFormatterMixin:
"""provides sorting UI: concrete classes must declare script_name."""
script_name = None # Must be defined in subclass
def getHeader(self, column):
contents = column.renderHeader(self)
if (interfaces.ISortableColumn.providedBy(column)):
contents = self._addSortUi(contents, column)
return contents
def _addSortUi(self, header, column):
columnName = column.name
resource_path = component.getAdapter(self.request, name='zc.table')()
if (interfaces.IColumnSortedItems.providedBy(self.items) and
self.items.sort_on):
sortColumnName, sortReversed = self.items.sort_on[0]
else:
sortColumnName = sortReversed = None
if columnName == sortColumnName:
if sortReversed:
dirIndicator = ('<img src="%s/sort_arrows_up.gif" '
'class="sort-indicator" '
'alt="(ascending)"/>' % resource_path)
else:
dirIndicator = ('<img src="%s/sort_arrows_down.gif" '
'class="sort-indicator" '
'alt="(descending)"/>' % resource_path)
else:
dirIndicator = ('<img src="%s/sort_arrows.gif" '
'class="sort-indicator" '
'alt="(sortable)"/>' % resource_path)
sort_on_name = getSortOnName(self.prefix)
script_name = self.script_name
return self._header_template(locals())
def _header_template(self, options):
# The <img> below is intentionally not in the <span> because IE
# doesn't underline it correctly when the CSS class is changed.
# XXX can we avoid changing the className and get a similar effect?
template = """
<span class="zc-table-sortable"
onclick="javascript: %(script_name)s(
'%(columnName)s', '%(sort_on_name)s')"
onMouseOver="javascript:
this.className='sortable zc-table-sortable'"
onMouseOut="javascript: this.className='zc-table-sortable'">
%(header)s</span> %(dirIndicator)s
"""
return template % options
class StandaloneSortFormatterMixin(AbstractSortFormatterMixin):
"A version of the sort formatter mixin for standalone tables, not forms"
script_name = 'onSortClickStandalone'
class FormSortFormatterMixin(AbstractSortFormatterMixin):
"""A version of the sort formatter mixin that plays well within forms.
Does *not* draw a form tag itself, and requires something else to do so.
"""
def __init__(self, context, request, items, visible_column_names=None,
batch_start=None, batch_size=None, prefix=None, columns=None,
sort_on=None, ignore_request=False):
if not ignore_request:
sort_on = (
getRequestSortOn(request, getSortOnName(prefix)) or sort_on)
else:
sort_on = sort_on
if sort_on or getattr(items, '__getitem__', None) is None:
items = ColumnSortedItems(items, sort_on)
super().__init__(
context, request, items, visible_column_names,
batch_start, batch_size, prefix, columns)
if sort_on:
items.setFormatter(self)
script_name = 'onSortClickForm'
def renderExtra(self):
"""Render the hidden input field used to keep up with sorting"""
if (interfaces.IColumnSortedItems.providedBy(self.items) and
self.items.sort_on):
value = []
for name, reverse in reversed(self.items.sort_on):
value.append(name)
if reverse:
value.append(name)
value = ' '.join(value)
else:
value = ''
sort_on_name = getSortOnName(self.prefix)
return '<input type="hidden" name={} id={} value={} />\n'.format(
quoteattr(sort_on_name+":tokens"),
quoteattr(sort_on_name),
quoteattr(value)
) + super().renderExtra()
def setItems(self, items):
if (interfaces.IColumnSortedItems.providedBy(self.items) and
not interfaces.IColumnSortedItems.providedBy(items)):
items = ColumnSortedItems(items, self.items.sort_on)
if interfaces.IColumnSortedItems.providedBy(items):
items.setFormatter(self)
self.items = items
class AlternatingRowFormatterMixin:
row_classes = ('even', 'odd')
def renderRows(self):
self.row = 0
return super().renderRows()
def renderRow(self, item):
self.row += 1
klass = self.cssClasses.get('tr', '')
if klass:
klass += ' '
return ' <tr class={}>\n{} </tr>\n'.format(
quoteattr(klass + self.row_classes[self.row % 2]),
self.renderCells(item))
# TODO Remove all these concrete classes
class SortingFormatter(SortingFormatterMixin, Formatter):
pass
class AlternatingRowFormatter(AlternatingRowFormatterMixin, Formatter):
pass
class StandaloneSortFormatter(
SortingFormatterMixin, StandaloneSortFormatterMixin, Formatter):
pass
class FormSortFormatter(FormSortFormatterMixin, Formatter):
pass
class StandaloneFullFormatter(
SortingFormatterMixin, StandaloneSortFormatterMixin,
AlternatingRowFormatterMixin, Formatter):
pass
class FormFullFormatter(
FormSortFormatterMixin, AlternatingRowFormatterMixin, Formatter):
pass | zc.table | /zc.table-1.0.tar.gz/zc.table-1.0/src/zc/table/table.py | table.py |
Overview
========
The zc.testbrowser package provides web user agents (browsers) with
programmatic interfaces designed to be used for testing web applications,
especially in conjunction with doctests.
There are currently two type of testbrowser provided. One for accessing web
sites via HTTP (zc.testbrowser.browser) and one that controls a Firefox web
browser (zc.testbrowser.real). All flavors of testbrowser have the same API.
This project originates in the Zope 3 community, but is not Zope-specific (the
zc namespace package stands for "Zope Corporation").
Changes
=======
1.0a1 (2007-09-28)
------------------
First release under new name (non Zope-specific code extracted from
zope.testbrowser)
| zc.testbrowser | /zc.testbrowser-1.0a1.tar.gz/zc.testbrowser-1.0a1/README.txt | README.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.