~ubuntu-branches/ubuntu/lucid/twisted-web2/lucid

« back to all changes in this revision

Viewing changes to twisted/web2/dav/util.py

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Klose
  • Date: 2008-03-30 22:08:20 UTC
  • mfrom: (0.1.5 upstream)
  • Revision ID: james.westby@ubuntu.com-20080330220820-m2cd4jon35wz2efx
Tags: 8.0.1-1
New upstream version.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# -*- test-case-name: twisted.web2.test.test_util -*-
2
 
##
3
 
# Copyright (c) 2005 Apple Computer, Inc. All rights reserved.
4
 
#
5
 
# Permission is hereby granted, free of charge, to any person obtaining a copy
6
 
# of this software and associated documentation files (the "Software"), to deal
7
 
# in the Software without restriction, including without limitation the rights
8
 
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
 
# copies of the Software, and to permit persons to whom the Software is
10
 
# furnished to do so, subject to the following conditions:
11
 
12
 
# The above copyright notice and this permission notice shall be included in all
13
 
# copies or substantial portions of the Software.
14
 
15
 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
 
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
 
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
 
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
 
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
 
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
 
# SOFTWARE.
22
 
#
23
 
# DRI: Wilfredo Sanchez, wsanchez@apple.com
24
 
##
25
 
 
26
 
"""
27
 
Utilities
28
 
 
29
 
This API is considered private to static.py and is therefore subject to
30
 
change.
31
 
"""
32
 
 
33
 
__all__ = [
34
 
    "allDataFromStream",
35
 
    "davXMLFromStream",
36
 
    "noDataFromStream",
37
 
    "normalizeURL",
38
 
    "joinURL",
39
 
    "parentForURL",
40
 
    "bindMethods",
41
 
]
42
 
 
43
 
import urllib
44
 
from urlparse import urlsplit, urlunsplit
45
 
import posixpath # Careful; this module is not documented as public API
46
 
 
47
 
from twisted.python import log
48
 
from twisted.python.failure import Failure
49
 
from twisted.internet.defer import succeed
50
 
from twisted.web2.stream import readStream
51
 
 
52
 
from twisted.web2.dav import davxml
53
 
 
54
 
##
55
 
# Reading request body
56
 
##
57
 
 
58
 
def allDataFromStream(stream, filter=None):
59
 
    data = []
60
 
    def gotAllData(_):
61
 
        if not data: return None
62
 
        result = "".join([str(x) for x in data])
63
 
        if filter is None:
64
 
            return result
65
 
        else:
66
 
            return filter(result)
67
 
    return readStream(stream, data.append).addCallback(gotAllData)
68
 
 
69
 
def davXMLFromStream(stream):
70
 
    # FIXME:
71
 
    #   This reads the request body into a string and then parses it.
72
 
    #   A better solution would parse directly and incrementally from the
73
 
    #   request stream.
74
 
    if stream is None:
75
 
        return succeed(None)
76
 
 
77
 
    def parse(xml):
78
 
        try:
79
 
            return davxml.WebDAVDocument.fromString(xml)
80
 
        except ValueError:
81
 
            log.err("Bad XML:\n%s" % (xml,))
82
 
            raise
83
 
    return allDataFromStream(stream, parse)
84
 
 
85
 
def noDataFromStream(stream):
86
 
    def gotData(data):
87
 
        if data: raise ValueError("Stream contains unexpected data.")
88
 
    return readStream(stream, gotData)
89
 
 
90
 
##
91
 
# URLs
92
 
##
93
 
 
94
 
def normalizeURL(url):
95
 
    """
96
 
    Normalized a URL.
97
 
    @param url: a URL.
98
 
    @return: the normalized representation of C{url}.  The returned URL will
99
 
        never contain a trailing C{"/"}; it is up to the caller to determine
100
 
        whether the resource referred to by the URL is a collection and add a
101
 
        trailing C{"/"} if so.
102
 
    """
103
 
    def cleanup(path):
104
 
        # For some silly reason, posixpath.normpath doesn't clean up '//' at the
105
 
        # start of a filename, so let's clean it up here.
106
 
        if path[0] == "/":
107
 
            count = 0
108
 
            for char in path:
109
 
                if char != "/": break
110
 
                count += 1
111
 
            path = path[count-1:]
112
 
 
113
 
        return path
114
 
 
115
 
    (scheme, host, path, query, fragment) = urlsplit(cleanup(url))
116
 
 
117
 
    path = cleanup(posixpath.normpath(urllib.unquote(path)))
118
 
 
119
 
    return urlunsplit((scheme, host, urllib.quote(path), query, fragment))
120
 
 
121
 
def joinURL(*urls):
122
 
    """
123
 
    Appends URLs in series.
124
 
    @param urls: URLs to join.
125
 
    @return: the normalized URL formed by combining each URL in C{urls}.  The
126
 
        returned URL will contain a trailing C{"/"} if and only if the last
127
 
        given URL contains a trailing C{"/"}.
128
 
    """
129
 
    if len(urls) > 0 and len(urls[-1]) > 0 and urls[-1][-1] == "/":
130
 
        trailing = "/"
131
 
    else:
132
 
        trailing = ""
133
 
 
134
 
    url = normalizeURL("/".join([url for url in urls]))
135
 
    if url == "/":
136
 
        return "/"
137
 
    else:
138
 
        return url + trailing
139
 
 
140
 
def parentForURL(url):
141
 
    """
142
 
    Extracts the URL of the containing collection resource for the resource
143
 
    corresponding to a given URL.
144
 
    @param url: an absolute (server-relative is OK) URL.
145
 
    @return: the normalized URL of the collection resource containing the
146
 
        resource corresponding to C{url}.  The returned URL will always contain
147
 
        a trailing C{"/"}.
148
 
    """
149
 
    (scheme, host, path, query, fragment) = urlsplit(normalizeURL(url))
150
 
 
151
 
    index = path.rfind("/")
152
 
    if index is 0:
153
 
        if path == "/":
154
 
            return None
155
 
        else:
156
 
            path = "/"
157
 
    else:
158
 
        if index is -1:
159
 
            raise ValueError("Invalid URL: %s" % (url,))
160
 
        else:
161
 
            path = path[:index] + "/"
162
 
 
163
 
    return urlunsplit((scheme, host, path, query, fragment))
164
 
 
165
 
##
166
 
# Python magic
167
 
##
168
 
 
169
 
def unimplemented(obj):
170
 
    """
171
 
    Throw an exception signifying that the current method is unimplemented
172
 
    and should not have been invoked.
173
 
    """
174
 
    import inspect
175
 
    caller = inspect.getouterframes(inspect.currentframe())[1][3]
176
 
    raise NotImplementedError("Method %s is unimplemented in subclass %s" % (caller, obj.__class__))
177
 
 
178
 
def bindMethods(module, clazz, prefixes=("preconditions_", "http_", "report_")):
179
 
    """
180
 
    Binds all functions in the given module (as defined by that module's
181
 
    C{__all__} attribute) which start with any of the given prefixes as methods
182
 
    of the given class.
183
 
    @param module: the module in which to search for functions.
184
 
    @param clazz: the class to bind found functions to as methods.
185
 
    @param prefixes: a sequence of prefixes to match found functions against.
186
 
    """
187
 
    for submodule_name in module.__all__:
188
 
        try:
189
 
            __import__(module.__name__ + "." + submodule_name)
190
 
        except ImportError:
191
 
            log.err("Unable to import module %s" % (module.__name__ + "." + submodule_name,))
192
 
            Failure().raiseException()
193
 
        submodule = getattr(module, submodule_name)
194
 
        for method_name in submodule.__all__:
195
 
            for prefix in prefixes:
196
 
                if method_name.startswith(prefix):
197
 
                    method = getattr(submodule, method_name)
198
 
                    setattr(clazz, method_name, method)
199
 
                    break