Commit fb33a42d authored by Tres Seaver's avatar Tres Seaver

- Merge tseaver-strexp_delenda-branch to the head.

parent 2054a3e5
......@@ -34,6 +34,10 @@ Zope Changes
Bugs fixed
- Removed pervasive use of string exceptions (some may still be
hiding in the woodwork, but all raise's with string literals are
gone).
- AccessControl.User used a misleading string exeception,
'NotImplemented', which shadowed the Python builtin.
......
......@@ -62,7 +62,7 @@ class RoleManager:
p=class_permissions[i]
if p and (p not in perms):
__traceback_info__=perms, p, i
raise 'Permission mapping error', (
raise ValueError, (
"""Attempted to map a permission to a permission, %s,
that is not valid. This should never happen. (Waaa).
""" % escape(p))
......
......@@ -12,7 +12,7 @@
##############################################################################
"""Access control support"""
__version__='$Revision: 1.57 $'[11:-2]
__version__='$Revision: 1.58 $'[11:-2]
from Globals import DTMLFile, MessageDialog, Dictionary
......@@ -171,7 +171,7 @@ class RoleManager(ExtensionClass.Base, PermissionMapping.RoleManager):
if REQUEST is not None: return self.manage_access(REQUEST)
return
raise 'Invalid Permission', (
raise ValueError, (
"The permission <em>%s</em> is invalid." %
escape(permission_to_manage))
......@@ -245,7 +245,7 @@ class RoleManager(ExtensionClass.Base, PermissionMapping.RoleManager):
},
valid_roles)
raise 'Invalid Permission', (
raise ValueError, (
"The permission <em>%s</em> is invalid." % escape(permission))
def acquiredRolesAreUsedBy(self, permission):
......@@ -257,7 +257,7 @@ class RoleManager(ExtensionClass.Base, PermissionMapping.RoleManager):
roles=p.getRoles()
return type(roles) is ListType and 'CHECKED' or ''
raise 'Invalid Permission', (
raise ValueError, (
"The permission <em>%s</em> is invalid." % escape(permission))
......
......@@ -12,7 +12,7 @@
##############################################################################
"""Access control package"""
__version__='$Revision: 1.180 $'[11:-2]
__version__='$Revision: 1.181 $'[11:-2]
import Globals, socket, SpecialUsers,re
import os
......@@ -26,7 +26,7 @@ from Role import RoleManager, DEFAULTMAXLISTUSERS
from PermissionRole import _what_not_even_god_should_do, rolesForPermissionOn
import AuthEncoding
from AccessControl import getSecurityManager
from zExceptions import Unauthorized
from zExceptions import Unauthorized, BadRequest
from AccessControl.SecurityManagement import newSecurityManager
from AccessControl.SecurityManagement import noSecurityManager
from AccessControl.ZopeSecurityPolicy import _noroles
......@@ -568,7 +568,7 @@ class BasicUserFolder(Implicit, Persistent, Navigation, Tabs, RoleManager,
try: name, password=tuple(decodestring(
auth.split(' ')[-1]).split(':', 1))
except:
raise 'Bad Request', 'Invalid authentication token'
raise BadRequest, 'Invalid authentication token'
return name, password
else:
return None, None
......
......@@ -12,7 +12,7 @@
##############################################################################
__doc__="""System management components"""
__version__='$Revision: 1.89 $'[11:-2]
__version__='$Revision: 1.90 $'[11:-2]
import sys,os,time,Globals, Acquisition, os, Undo
from Globals import DTMLFile
......@@ -28,6 +28,7 @@ from Product import ProductFolder
from version_txt import version_txt
from cStringIO import StringIO
from AccessControl import getSecurityManager
from zExceptions import Redirect
from Products.PageTemplates.PageTemplateFile import PageTemplateFile
import zLOG
import Lifetime
......@@ -352,7 +353,7 @@ class ApplicationManager(Folder,CacheManager):
def manage_app(self, URL2):
"""Return to the main management screen"""
raise 'Redirect', URL2+'/manage'
raise Redirect, URL2+'/manage'
def process_time(self):
s=int(time.time())-self.process_start
......@@ -463,7 +464,7 @@ class ApplicationManager(Folder,CacheManager):
def version_info(self):
r=[]
try: db=self._p_jar.db()
except: raise 'Zope database version error', """
except: raise ValueError, """
Sorry, <em>Version management</em> is only supported if you use ZODB 3.
"""
for v in db.versions():
......
......@@ -14,11 +14,12 @@ __doc__='''Standard routines for handling extensions.
Extensions currently include external methods and pluggable brains.
$Id: Extensions.py,v 1.22 2003/07/09 18:44:24 fdrake Exp $'''
__version__='$Revision: 1.22 $'[11:-2]
$Id: Extensions.py,v 1.23 2003/11/18 13:16:58 tseaver Exp $'''
__version__='$Revision: 1.23 $'[11:-2]
import os, zlib, imp
import Products
from zExceptions import NotFound
path_split=os.path.split
path_join=os.path.join
exists=os.path.exists
......@@ -116,7 +117,7 @@ def getObject(module, name, reload=0,
p = module
p=getPath('Extensions', p, suffixes=('','py','pyp','pyc'))
if p is None:
raise "Module Error", (
raise NotFound, (
"The specified module, <em>%s</em>, couldn't be found." % module)
__traceback_info__=p, module
......@@ -140,7 +141,7 @@ def getObject(module, name, reload=0,
else:
try: execsrc=open(p)
except: raise "Module Error", (
except: raise NotFound, (
"The specified module, <em>%s</em>, couldn't be opened."
% module)
m={}
......@@ -154,7 +155,7 @@ def getObject(module, name, reload=0,
try:
return m[name]
except KeyError:
raise 'Invalid Object Name', (
raise NotFound, (
"The specified object, <em>%s</em>, was not found in module, "
"<em>%s</em>." % (name, module))
......
......@@ -13,13 +13,13 @@
"""Standard management interface support
$Id: Management.py,v 1.63 2003/10/17 16:21:14 andreasjung Exp $"""
__version__='$Revision: 1.63 $'[11:-2]
$Id: Management.py,v 1.64 2003/11/18 13:16:58 tseaver Exp $
"""
import sys, Globals, ExtensionClass, urllib
from Dialogs import MessageDialog
from Globals import DTMLFile, HTMLFile
from zExceptions import Redirect
from AccessControl import getSecurityManager, Unauthorized
class Tabs(ExtensionClass.Base):
......@@ -38,8 +38,10 @@ class Tabs(ExtensionClass.Base):
result=[]
try: options=tuple(self.manage_options)
except: options=tuple(self.manage_options())
try:
options=tuple(self.manage_options)
except:
options=tuple(self.manage_options())
for d in options:
......@@ -48,10 +50,12 @@ class Tabs(ExtensionClass.Base):
continue
path=d.get('path', None)
if path is None: path=d['action']
if path is None:
path=d['action']
o=self.unrestrictedTraverse(path, None)
if o is None: continue
if o is None:
continue
try:
if validate(None, self, None, o):
......@@ -70,13 +74,14 @@ class Tabs(ExtensionClass.Base):
options=self.filtered_manage_options(REQUEST)
try:
m=options[0]['action']
if m=='manage_workspace': raise TypeError
if m=='manage_workspace':
raise TypeError
except:
raise Unauthorized, (
'You are not authorized to view this object.')
if m.find('/'):
raise 'Redirect', (
raise Redirect, (
"%s/%s" % (REQUEST['URL1'], m))
return getattr(self, m)(self, REQUEST)
......@@ -106,13 +111,19 @@ class Tabs(ExtensionClass.Base):
quote=urllib.quote,
):
out=[]
while path[:1]=='/': path=path[1:]
while path[-1:]=='/': path=path[:-1]
while script[:1]=='/': script=script[1:]
while script[-1:]=='/': script=script[:-1]
while path[:1]=='/':
path = path[1:]
while path[-1:]=='/':
path = path[:-1]
while script[:1]=='/':
script = script[1:]
while script[-1:]=='/':
script = script[:-1]
path=path.split('/')[:-1]
if script: path=[script]+path
if not path: return ''
if script:
path = [script] + path
if not path:
return ''
script=''
last=path[-1]
del path[-1]
......@@ -124,7 +135,8 @@ class Tabs(ExtensionClass.Base):
class_manage_path__roles__=None
def class_manage_path(self):
if self.__class__.__module__[:1] != '*': return
if self.__class__.__module__[:1] != '*':
return
path = getattr(self.__class__, '_v_manage_path_roles', None)
if path is None:
meta_type = self.meta_type
......
......@@ -260,14 +260,15 @@ class Product(Folder, PermissionManager):
"Product Distributions"
def __bobo_traverse__(self, REQUEST, name):
if name[-7:] != '.tar.gz': raise 'Invalid Name', escape(name)
if name[-7:] != '.tar.gz':
raise ValueError, 'Invalid Name: %s' % escape(name)
l=name.find('-')
id, version = name[:l], name[l+1:-7]
product=self.aq_parent
if product.id==id and product.version==version:
return Distribution(product)
raise 'Invalid version or product id', escape(name)
raise ValueError, 'Invalid version or product id: %s' % escape(name)
Distributions=Distributions()
......
......@@ -56,7 +56,7 @@ class ProductRegistryMixin:
if mt['name']==meta_type:
if not mt.has_key('product'): mt['product']=pid
if mt['product'] != pid:
raise 'Type Exists', (
raise ValueError, (
'The type <em>%s</em> is already defined.' % meta_type)
mt['action']='%s%s' % (
self._constructor_prefix_string(pid), id)
......@@ -97,7 +97,7 @@ class ProductRegistryMixin:
for d in permissions:
if d['name']==permission:
raise 'Type Exists', (
raise ValueError, (
'The permission <em>%s</em> is already defined.'
% permission)
......
......@@ -177,7 +177,8 @@ class DTMLFile(Bindings, Explicit, ClassicHTMLFile):
except AttributeError:
if type(sys.exc_value)==InstanceType and sys.exc_value.args[0]=="_v_blocks":
LOG("ZPublisher",WARNING,"DTML file '%s' could not be read" % self.raw)
raise "DTML file error","Check logfile for details"
raise ValueError, ("DTML file error: "
"Check logfile for details")
else:
raise
......
......@@ -12,8 +12,8 @@
##############################################################################
__doc__='''Simple module for writing tar files
$Id: tar.py,v 1.6 2002/08/14 21:31:41 mj Exp $'''
__version__='$Revision: 1.6 $'[11:-2]
$Id: tar.py,v 1.7 2003/11/18 13:16:58 tseaver Exp $'''
__version__='$Revision: 1.7 $'[11:-2]
import sys, time, zlib
try:
......@@ -62,7 +62,8 @@ class TarEntry:
pad(prefix, 155),
'\0'*12,
])
if len(header) != 512: raise 'Bad Header Length', len(header)
if len(header) != 512:
raise ValueError, 'Bad Header Length: %d' % len(header)
header=(header[:148]+
oct8(reduce(lambda a,b: a+b, map(ord,header)))+
header[156:])
......
......@@ -12,16 +12,30 @@
##############################################################################
"""Encapsulation of date/time values"""
__version__='$Revision: 1.90 $'[11:-2]
__version__='$Revision: 1.91 $'[11:-2]
import os, re, math, DateTimeZone
from time import time, gmtime, localtime, asctime
from time import daylight, timezone, altzone, strftime
from types import InstanceType,IntType,FloatType,StringType,UnicodeType
try: from time import tzname
except: tzname=('UNKNOWN','UNKNOWN')
from types import InstanceType, IntType, FloatType, StringType, UnicodeType
try:
from time import tzname
except:
tzname=('UNKNOWN','UNKNOWN')
class DateTimeError( Exception ):
pass
class SyntaxError( DateTimeError ):
pass
class DateError( DateTimeError ):
pass
class TimeError( DateTimeError ):
pass
_default_datefmt = os.environ.get('DATETIME_FORMAT', "us").lower()
if not _default_datefmt in ('us', 'international'):
......@@ -241,7 +255,7 @@ class _cache:
try: n=self._zmap[k.lower()]
except KeyError:
if numericTimeZoneMatch(k) == None:
raise 'DateTimeError','Unrecognized timezone: %s' % k
raise DateTimeError,'Unrecognized timezone: %s' % k
return k
try: return self._d[n]
except KeyError:
......@@ -397,7 +411,7 @@ def safegmtime(t):
raise OverflowError # Python 2.3 fix: int can return a long!
return gmtime(t_int)
except (IOError, OverflowError):
raise 'TimeError', 'The time %f is beyond the range ' \
raise TimeError, 'The time %f is beyond the range ' \
'of this Python implementation.' % float(t)
def safelocaltime(t):
......@@ -407,7 +421,7 @@ def safelocaltime(t):
if isinstance(t_int, long):
raise OverflowError # Python 2.3 fix: int can return a long!
except OverflowError:
raise 'TimeError', 'The time %f is beyond the range ' \
raise TimeError, 'The time %f is beyond the range ' \
'of this Python implementation.' % float(t)
rval = localtime(t_int)
return rval
......@@ -657,7 +671,7 @@ class DateTime:
arg=args[0]
if arg=='':
raise self.SyntaxError, arg
raise SyntaxError, arg
if type(arg) in [StringType,UnicodeType] and arg.lower() in self._tzinfo._zidx:
# Current time, to be displayed in specified timezone
......@@ -678,9 +692,9 @@ class DateTime:
if not self._validDate(yr,mo,dy):
raise self.DateTimeError, 'Invalid date: %s' % arg
raise DateError, 'Invalid date: %s' % arg
if not self._validTime(hr,mn,int(sc)):
raise self.DateTimeError, 'Invalid time: %s' % arg
raise TimeError, 'Invalid time: %s' % arg
ms = sc - math.floor(sc)
x = _calcDependentSecond2(yr,mo,dy,hr,mn,sc)
......@@ -688,7 +702,7 @@ class DateTime:
try: tz=self._tzinfo._zmap[tz.lower()]
except KeyError:
if numericTimeZoneMatch(tz) is None:
raise self.DateTimeError, \
raise DateTimeError, \
'Unknown time zone in date: %s' % arg
else:
tz = self._calcTimezoneName(x, ms)
......@@ -734,7 +748,7 @@ class DateTime:
hr,mn,sc,tz=0,0,0,0
yr = _correctYear(yr)
if not self._validDate(yr,mo,dy):
raise self.DateTimeError, 'Invalid date: %s' % (args,)
raise DateError, 'Invalid date: %s' % (args,)
args=args[3:]
if args:
hr,args=args[0],args[1:]
......@@ -745,9 +759,9 @@ class DateTime:
if args:
tz,args=args[0],args[1:]
if args:
raise self.DateTimeError,'Too many arguments'
raise DateTimeError,'Too many arguments'
if not self._validTime(hr,mn,sc):
raise self.DateTimeError, 'Invalid time: %s' % `args`
raise TimeError, 'Invalid time: %s' % `args`
leap = (yr % 4 == 0) and (yr % 100 != 0 or yr % 400 == 0)
x = _calcDependentSecond2(yr,mo,dy,hr,mn,sc)
......@@ -756,7 +770,7 @@ class DateTime:
try: tz=self._tzinfo._zmap[tz.lower()]
except KeyError:
if numericTimeZoneMatch(tz) is None:
raise self.DateTimeError, \
raise DateTimeError, \
'Unknown time zone: %s' % tz
else:
# Get local time zone name
......@@ -793,9 +807,6 @@ class DateTime:
# self._millis is the time since the epoch
# in long integer milliseconds.
DateTimeError='DateTimeError'
SyntaxError ='Invalid Date-Time String'
DateError ='Invalid Date Components'
int_pattern =re.compile(r'([0-9]+)') #AJ
flt_pattern =re.compile(r':([0-9]+\.[0-9]+)') #AJ
name_pattern =re.compile(r'([a-zA-Z]+)', re.I) #AJ
......@@ -949,18 +960,18 @@ class DateTime:
if MonthNumbers.has_key(s):
v=MonthNumbers[s]
if month is None: month=v
else: raise self.SyntaxError, st
else: raise SyntaxError, st
continue
# Check for time modifier:
if s in TimeModifiers:
if tm is None: tm=s
else: raise self.SyntaxError, st
else: raise SyntaxError, st
continue
# Check for and skip day of week:
if DayOfWeekNames.has_key(s):
continue
raise self.SyntaxError, st
raise SyntaxError, st
day=None
if ints[-1] > 60 and d not in ['.',':','/'] and len(ints) > 2:
......@@ -1023,34 +1034,34 @@ class DateTime:
year,month,day = localtime(time())[:3]
year = _correctYear(year)
if year < 1000: raise self.SyntaxError, st
if year < 1000: raise SyntaxError, st
leap = year%4==0 and (year%100!=0 or year%400==0)
try:
if not day or day > self._month_len[leap][month]:
raise self.DateError, st
raise DateError, st
except IndexError:
raise self.DateError, st
raise DateError, st
tod=0
if ints:
i=ints[0]
# Modify hour to reflect am/pm
if tm and (tm=='pm') and i<12: i=i+12
if tm and (tm=='am') and i==12: i=0
if i > 24: raise self.DateTimeError, st
if i > 24: raise TimeError, st
tod = tod + int(i) * 3600
del ints[0]
if ints:
i=ints[0]
if i > 60: raise self.DateTimeError, st
if i > 60: raise TimeError, st
tod = tod + int(i) * 60
del ints[0]
if ints:
i=ints[0]
if i > 60: raise self.DateTimeError, st
if i > 60: raise TimeError, st
tod = tod + i
del ints[0]
if ints: raise self.SyntaxError,st
if ints: raise SyntaxError,st
tod_int = int(math.floor(tod))
......@@ -1549,7 +1560,7 @@ class DateTime:
"""A DateTime may be added to a number and a number may be
added to a DateTime; two DateTimes cannot be added."""
if hasattr(other,'_t'):
raise self.DateTimeError,'Cannot add two DateTimes'
raise DateTimeError,'Cannot add two DateTimes'
o=float(other)
tz = self._tz
t = (self._t + (o*86400.0))
......@@ -1636,7 +1647,7 @@ class DateTime:
try:
return self.__parse_iso8601(s)
except IndexError:
raise self.DateError,'Not an ISO 8601 compliant date string: "%s"' % s
raise DateError,'Not an ISO 8601 compliant date string: "%s"' % s
def __parse_iso8601(self,s):
......
......@@ -331,8 +331,8 @@
''' #'
__rcs_id__='$Id: DT_In.py,v 1.60 2002/08/14 22:29:52 mj Exp $'
__version__='$Revision: 1.60 $'[11:-2]
__rcs_id__='$Id: DT_In.py,v 1.61 2003/11/18 13:17:00 tseaver Exp $'
__version__='$Revision: 1.61 $'[11:-2]
import sys
from DT_Util import ParseError, parse_params, name_param, str, join_unicode
......@@ -450,7 +450,7 @@ class InClass:
return ''
if type(sequence) is type(''):
raise 'InError', (
raise ValueError, (
'Strings are not allowed as input to the in tag.')
......@@ -633,7 +633,7 @@ class InClass:
return ''
if type(sequence) is type(''):
raise 'InError', (
raise ValueError, (
'Strings are not allowed as input to the in tag.')
section=self.section
......
......@@ -151,8 +151,8 @@ Evaluating expressions without rendering results
''' # '
__rcs_id__='$Id: DT_Var.py,v 1.59 2003/02/01 09:25:58 andreasjung Exp $'
__version__='$Revision: 1.59 $'[11:-2]
__rcs_id__='$Id: DT_Var.py,v 1.60 2003/11/18 13:17:00 tseaver Exp $'
__version__='$Revision: 1.60 $'[11:-2]
from DT_Util import parse_params, name_param, str, ustr
import os, string, re, sys
......@@ -303,7 +303,7 @@ class Var:
if have_arg('size'):
size=args['size']
try: size=int(size)
except: raise 'Document Error',(
except: raise ValueError,(
'''a <code>size</code> attribute was used in a <code>var</code>
tag with a non-integer value.''')
if len(val) > size:
......
......@@ -66,7 +66,7 @@ class HelpTopicBase:
def SearchableText(self):
"The full text of the Help Topic, for indexing purposes"
raise "Unimplemented"
raise NotImplementedError
def url(self):
"URL for indexing purposes"
......@@ -139,7 +139,7 @@ class HelpTopic(Acquisition.Implicit, HelpTopicBase, Item, PropertyManager, Pers
def index_html(self, REQUEST, RESPONSE):
"View the Help Topic"
raise "Unimplemented"
raise NotImplementedError
class DTMLDocumentTopic(HelpTopicBase, DTMLDocument):
......
......@@ -12,8 +12,8 @@
##############################################################################
__doc__='''Application support
$Id: Application.py,v 1.194 2003/11/05 05:54:12 fdrake Exp $'''
__version__='$Revision: 1.194 $'[11:-2]
$Id: Application.py,v 1.195 2003/11/18 13:17:02 tseaver Exp $'''
__version__='$Revision: 1.195 $'[11:-2]
import Globals,Folder,os,sys,App.Product, App.ProductRegistry, misc_
import time, traceback, os, Products
......@@ -29,6 +29,7 @@ from App.ProductContext import ProductContext
from misc_ import Misc_
import ZDOM
from zLOG import LOG, ERROR, WARNING, INFO
from zExceptions import Redirect as RedirectException, Forbidden
from HelpSys.HelpSys import HelpSys
from Acquisition import aq_base
from App.Product import doInstall
......@@ -87,8 +88,9 @@ class Application(Globals.ApplicationDefaultPermissions,
def PrincipiaRedirect(self,destination,URL1):
"""Utility function to allow user-controlled redirects"""
if destination.find('//') >= 0: raise 'Redirect', destination
raise 'Redirect', ("%s/%s" % (URL1, destination))
if destination.find('//') >= 0:
raise RedirectException, destination
raise RedirectException, ("%s/%s" % (URL1, destination))
Redirect=ZopeRedirect=PrincipiaRedirect
def __bobo_traverse__(self, REQUEST, name=None):
......@@ -124,12 +126,12 @@ class Application(Globals.ApplicationDefaultPermissions,
def DELETE(self, REQUEST, RESPONSE):
"""Delete a resource object."""
self.dav__init(REQUEST, RESPONSE)
raise 'Forbidden', 'This resource cannot be deleted.'
raise Forbidden, 'This resource cannot be deleted.'
def MOVE(self, REQUEST, RESPONSE):
"""Move a resource to a new location."""
self.dav__init(REQUEST, RESPONSE)
raise 'Forbidden', 'This resource cannot be moved.'
raise Forbidden, 'This resource cannot be moved.'
test_url___allow_groups__=None
test_url=ZopeAttributionButton
......
......@@ -12,9 +12,9 @@
##############################################################################
__doc__="""Cacheable object and cache management base classes.
$Id: Cache.py,v 1.10 2002/08/14 21:42:56 mj Exp $"""
$Id: Cache.py,v 1.11 2003/11/18 13:17:02 tseaver Exp $"""
__version__='$Revision: 1.10 $'[11:-2]
__version__='$Revision: 1.11 $'[11:-2]
import time, sys
import Globals
......@@ -404,7 +404,7 @@ class Cache:
'''
def ZCache_invalidate(self, ob):
raise 'Not implemented'
raise NotImplementedError
def ZCache_get(self, ob, view_name, keywords, mtime_func, default):
# view_name: If an object provides different views that would
......@@ -423,11 +423,11 @@ class Cache:
#
# default: If no entry is found, ZCache_get() should return
# default.
raise 'Not implemented'
raise NotImplementedError
def ZCache_set(self, ob, data, view_name, keywords, mtime_func):
# See ZCache_get() for parameter descriptions.
raise 'Not implemented'
raise NotImplementedError
class CacheManager:
......@@ -437,7 +437,7 @@ class CacheManager:
ZCacheManager_getCache__roles__ = ()
def ZCacheManager_getCache(self):
raise 'Not implemented'
raise NotImplementedError
_isCacheManager = 1
......
......@@ -11,7 +11,7 @@
#
##############################################################################
__doc__="""Copy interface"""
__version__='$Revision: 1.87 $'[11:-2]
__version__='$Revision: 1.88 $'[11:-2]
import sys, Globals, Moniker, tempfile, ExtensionClass
from marshal import loads, dumps
......@@ -20,7 +20,7 @@ from zlib import compress, decompress
from App.Dialogs import MessageDialog
from AccessControl import getSecurityManager
from Acquisition import aq_base, aq_inner, aq_parent
from zExceptions import Unauthorized
from zExceptions import Unauthorized, BadRequest
from AccessControl import getSecurityManager
from webdav.Lockable import ResourceLockedError
......@@ -223,7 +223,7 @@ class CopyContainer(ExtensionClass.Base):
def manage_renameObjects(self, ids=[], new_ids=[], REQUEST=None):
"""Rename several sub-objects"""
if len(ids) != len(new_ids):
raise 'Bad Request','Please rename each listed object.'
raise BadRequest,'Please rename each listed object.'
for i in range(len(ids)):
if ids[i] != new_ids[i]:
self.manage_renameObject(ids[i], new_ids[i], REQUEST)
......
......@@ -12,7 +12,7 @@
##############################################################################
"""DTML Method objects."""
__version__='$Revision: 1.82 $'[11:-2]
__version__='$Revision: 1.83 $'[11:-2]
import History
from Globals import HTML, DTMLFile, MessageDialog
......@@ -30,6 +30,7 @@ import Globals, sys, Acquisition
from AccessControl import getSecurityManager
from AccessControl.DTML import RestrictedDTML
from Cache import Cacheable
from zExceptions import Forbidden
from zExceptions.TracebackSupplement import PathTracebackSupplement
_marker = [] # Create a new marker object.
......@@ -294,7 +295,7 @@ class DTMLMethod(RestrictedDTML, HTML, Acquisition.Implicit, RoleManager,
if user is not None: return
raise 'Forbidden', (
raise Forbidden, (
'You are not authorized to change <em>%s</em> because you '
'do not have proxy roles.\n<!--%s, %s-->' % (self.__name__, u, roles))
......
......@@ -15,9 +15,9 @@ http://www.zope.org/Members/michel/Projects/Interfaces/ObserverAndNotification)
This class is intended to be used as a mixin (note that it doesn't derive
from any Zope persistence classes, for instance).
$Id: DefaultObservable.py,v 1.6 2002/08/14 21:42:56 mj Exp $"""
$Id: DefaultObservable.py,v 1.7 2003/11/18 13:17:02 tseaver Exp $"""
__version__='$Revision: 1.6 $'[11:-2]
__version__='$Revision: 1.7 $'[11:-2]
from types import StringType
......@@ -118,6 +118,8 @@ if __name__ == '__main__':
class DontGoHere( Exception ): pass
class Idawanna( Exception ): pass
class TestSubject( DefaultObservable ):
def __init__( self, paths ):
......@@ -155,7 +157,7 @@ if __name__ == '__main__':
def tryVeto( subject, event ):
""" Simulate attempted veto. """
raise 'Idawanna!'
raise Idawanna
observer = TestObserver()
......
......@@ -12,13 +12,14 @@
##############################################################################
"""Object Histories"""
__version__='$Revision: 1.17 $'[11:-2]
__version__='$Revision: 1.18 $'[11:-2]
import Globals, ExtensionClass, difflib
from DateTime import DateTime
from Acquisition import Implicit, aq_base
from struct import pack, unpack
from cgi import escape
from zExceptions import Redirect
class TemporalParadox(Exception): pass
......@@ -69,7 +70,7 @@ class Historian(Implicit):
def manage_workspace(self, REQUEST):
"We aren't real, so we delegate to that that spawned us!"
raise 'Redirect', REQUEST['URL2']+'/manage_change_history_page'
raise Redirect, REQUEST['URL2']+'/manage_change_history_page'
class Historical(ExtensionClass.Base):
"""Mix-in class to provide a veiw that shows hystorical changes
......
......@@ -12,7 +12,7 @@
##############################################################################
"""Image object"""
__version__='$Revision: 1.147 $'[11:-2]
__version__='$Revision: 1.148 $'[11:-2]
import Globals, struct
from OFS.content_types import guess_content_type
......@@ -31,6 +31,7 @@ from Cache import Cacheable
from mimetools import choose_boundary
from ZPublisher import HTTPRangeSupport
from ZPublisher.HTTPRequest import FileUpload
from zExceptions import Redirect
from cgi import escape
StringType=type('')
......@@ -389,7 +390,7 @@ class File(Persistent, Implicit, PropertyManager,
"""
The default view of the contents of the File or Image.
"""
raise 'Redirect', URL1
raise Redirect, URL1
# private
update_data__roles__=()
......
......@@ -12,9 +12,9 @@
##############################################################################
__doc__="""Object Manager
$Id: ObjectManager.py,v 1.164 2003/11/02 18:02:36 efge Exp $"""
$Id: ObjectManager.py,v 1.165 2003/11/18 13:17:03 tseaver Exp $"""
__version__='$Revision: 1.164 $'[11:-2]
__version__='$Revision: 1.165 $'[11:-2]
import App.Management, Acquisition, Globals, CopySupport, Products
import os, App.FactoryDispatcher, re, Products
......@@ -36,6 +36,7 @@ import App.Common
from App.config import getConfiguration
from AccessControl import getSecurityManager
from zLOG import LOG, ERROR
from zExceptions import BadRequest
import sys,fnmatch,copy
from cgi import escape
from types import StringType, UnicodeType
......@@ -450,10 +451,11 @@ class ObjectManager(
v=self._getOb(id, self)
if v.wl_isLocked():
raise ResourceLockedError, 'Object "%s" is locked via WebDAV' % v.getId()
raise ResourceLockedError, (
'Object "%s" is locked via WebDAV' % v.getId())
if v is self:
raise 'BadRequest', '%s does not exist' % escape(ids[-1])
raise BadRequest, '%s does not exist' % escape(ids[-1])
self._delObject(id)
del ids[-1]
if REQUEST is not None:
......
......@@ -12,7 +12,7 @@
##############################################################################
"""Property management"""
__version__='$Revision: 1.54 $'[11:-2]
__version__='$Revision: 1.55 $'[11:-2]
import ExtensionClass, Globals
import ZDOM
......@@ -21,6 +21,7 @@ from ZPublisher.Converters import type_converters
from Globals import DTMLFile, MessageDialog
from Acquisition import Implicit, aq_base
from Globals import Persistent
from zExceptions import BadRequest
from cgi import escape
......@@ -168,11 +169,11 @@ class PropertyManager(ExtensionClass.Base, ZDOM.ElementWithAttributes):
self._wrapperCheck(value)
if not self.valid_property_id(id):
raise 'Bad Request', 'Invalid or duplicate property id'
raise BadRequest, 'Invalid or duplicate property id'
if type in ('selection', 'multiple selection'):
if not hasattr(self, value):
raise 'Bad Request', 'No select variable %s' % value
raise BadRequest, 'No select variable %s' % value
self._properties=self._properties + (
{'id':id, 'type':type, 'select_variable':value},)
if type=='selection':
......@@ -189,7 +190,7 @@ class PropertyManager(ExtensionClass.Base, ZDOM.ElementWithAttributes):
# the value to the type of the existing property.
self._wrapperCheck(value)
if not self.hasProperty(id):
raise 'Bad Request', 'The property %s does not exist' % escape(id)
raise BadRequest, 'The property %s does not exist' % escape(id)
if type(value)==type(''):
proptype=self.getPropertyType(id) or 'string'
if type_converters.has_key(proptype):
......@@ -288,7 +289,7 @@ class PropertyManager(ExtensionClass.Base, ZDOM.ElementWithAttributes):
for name, value in props.items():
if self.hasProperty(name):
if not 'w' in propdict[name].get('mode', 'wd'):
raise 'BadRequest', '%s cannot be changed' % escape(name)
raise BadRequest, '%s cannot be changed' % escape(name)
self._updateProperty(name, value)
if REQUEST:
message="Saved changes."
......@@ -331,7 +332,7 @@ class PropertyManager(ExtensionClass.Base, ZDOM.ElementWithAttributes):
nd=self._reserved_names
for id in ids:
if not hasattr(aq_base(self), id):
raise 'BadRequest', (
raise BadRequest, (
'The property <em>%s</em> does not exist' % escape(id))
if (not 'd' in propdict[id].get('mode', 'wd')) or (id in nd):
return MessageDialog(
......
......@@ -13,7 +13,7 @@
"""Property sheets"""
__version__='$Revision: 1.91 $'[11:-2]
__version__='$Revision: 1.92 $'[11:-2]
import time, App.Management, Globals
from webdav.WriteLockInterface import WriteLockInterface
......@@ -28,6 +28,7 @@ from Traversable import Traversable
from Acquisition import aq_base
from AccessControl import getSecurityManager
from webdav.common import isDavCollection
from zExceptions import BadRequest, Redirect
from cgi import escape
......@@ -190,16 +191,16 @@ class PropertySheet(Traversable, Persistent, Implicit):
# systems.
self._wrapperCheck(value)
if not self.valid_property_id(id):
raise 'Bad Request', 'Invalid property id, %s.' % escape(id)
raise BadRequest, 'Invalid property id, %s.' % escape(id)
if not self.property_extensible_schema__():
raise 'Bad Request', (
raise BadRequest, (
'Properties cannot be added to this property sheet')
pself=self.p_self()
self=self.v_self()
if hasattr(aq_base(self),id):
if not (id=='title' and not self.__dict__.has_key(id)):
raise 'Bad Request', (
raise BadRequest, (
'Invalid property id, <em>%s</em>. It is in use.' %
escape(id))
if meta is None: meta={}
......@@ -207,7 +208,7 @@ class PropertySheet(Traversable, Persistent, Implicit):
pself._properties=pself._properties+(prop,)
if type in ('selection', 'multiple selection'):
if not value:
raise 'Bad Request', (
raise BadRequest, (
'The value given for a new selection property '
'must be a variable name<p>')
prop['select_variable']=value
......@@ -222,10 +223,10 @@ class PropertySheet(Traversable, Persistent, Implicit):
# it will used to _replace_ the properties meta data.
self._wrapperCheck(value)
if not self.hasProperty(id):
raise 'Bad Request', 'The property %s does not exist.' % escape(id)
raise BadRequest, 'The property %s does not exist.' % escape(id)
propinfo=self.propertyInfo(id)
if not 'w' in propinfo.get('mode', 'wd'):
raise 'Bad Request', '%s cannot be changed.' % escape(id)
raise BadRequest, '%s cannot be changed.' % escape(id)
if type(value)==type(''):
proptype=propinfo.get('type', 'string')
if type_converters.has_key(proptype):
......@@ -243,13 +244,13 @@ class PropertySheet(Traversable, Persistent, Implicit):
# Delete the property with the given id. If a property with the
# given id does not exist, a ValueError is raised.
if not self.hasProperty(id):
raise 'Bad Request', 'The property %s does not exist.' % escape(id)
raise BadRequest, 'The property %s does not exist.' % escape(id)
vself=self.v_self()
if hasattr(vself, '_reserved_names'):
nd=vself._reserved_names
else: nd=()
if (not 'd' in self.propertyInfo(id).get('mode', 'wd')) or (id in nd):
raise 'Bad Request', '%s cannot be deleted.' % escape(id)
raise BadRequest, '%s cannot be deleted.' % escape(id)
delattr(vself, id)
pself=self.p_self()
pself._properties=tuple(filter(lambda i, n=id: i['id'] != n,
......@@ -392,7 +393,7 @@ class PropertySheet(Traversable, Persistent, Implicit):
manage=DTMLFile('dtml/properties', globals())
def manage_propertiesForm(self, URL1):
" "
raise 'Redirect', URL1+'/manage'
raise Redirect, URL1+'/manage'
def manage_addProperty(self, id, value, type, REQUEST=None):
"""Add a new property via the web. Sets a new property with
......@@ -429,7 +430,7 @@ class PropertySheet(Traversable, Persistent, Implicit):
for name, value in props.items():
if self.hasProperty(name):
if not 'w' in propdict[name].get('mode', 'wd'):
raise 'BadRequest', '%s cannot be changed' % escape(name)
raise BadRequest, '%s cannot be changed' % escape(name)
self._updateProperty(name, value)
if REQUEST is not None:
return MessageDialog(
......
......@@ -17,8 +17,8 @@ Aqueduct database adapters, etc.
This module can also be used as a simple template for implementing new
item types.
$Id: SimpleItem.py,v 1.106 2003/02/04 16:38:10 matt Exp $'''
__version__='$Revision: 1.106 $'[11:-2]
$Id: SimpleItem.py,v 1.107 2003/11/18 13:17:03 tseaver Exp $'''
__version__='$Revision: 1.107 $'[11:-2]
import re, sys, Globals, App.Management, Acquisition, App.Undo
import AccessControl.Role, AccessControl.Owned, App.Common
......@@ -32,6 +32,7 @@ from Traversable import Traversable
from Acquisition import aq_base, aq_parent, aq_inner, aq_acquire
from DocumentTemplate.ustr import ustr
from zExceptions.ExceptionFormatter import format_exception
from zExceptions import Redirect
import time
from zLOG import LOG, BLATHER
......@@ -222,7 +223,7 @@ class Item(Base, Resource, CopySource, App.Management.Tabs, Traversable,
def manage(self, URL1):
" "
raise 'Redirect', "%s/manage_main" % URL1
raise Redirect, "%s/manage_main" % URL1
# This keeps simple items from acquiring their parents
# objectValues, etc., when used in simple tree tags.
......
......@@ -12,7 +12,7 @@
##############################################################################
"""Restricted unpickler"""
__version__='$Revision: 1.6 $'[11:-2]
__version__='$Revision: 1.7 $'[11:-2]
import pickle
......@@ -25,7 +25,7 @@ class Unpickler(pickle.Unpickler):
except: raise SystemError, 'Class not registered'
def load_string(self):
raise 'BadPickle', 'Non binstring'
raise pickle.UnpicklingError, 'Bad pickle: Non binstring'
# Public interface
......
......@@ -11,8 +11,8 @@
#
##############################################################################
"""SMTP mail objects
$Id: MailHost.py,v 1.80 2003/07/07 16:04:16 andreasjung Exp $"""
__version__ = "$Revision: 1.80 $"[11:-2]
$Id: MailHost.py,v 1.81 2003/11/18 13:17:05 tseaver Exp $"""
__version__ = "$Revision: 1.81 $"[11:-2]
from Globals import Persistent, DTMLFile, InitializeClass
from smtplib import SMTP
......@@ -26,8 +26,8 @@ from AccessControl.Permissions import view_management_screens, \
use_mailhost_services
from DateTime import DateTime
smtpError = "SMTP Error"
MailHostError = "MailHost Error"
class MailHostError( Exception ):
pass
manage_addMailHostForm=DTMLFile('dtml/addMailHost_form', globals())
def manage_addMailHost( self, id, title='', smtp_host='localhost'
......
......@@ -142,7 +142,7 @@ class Draft(Persistent, Implicit, SimpleItem.Item):
def manage_beforeDelete(self, item, container):
if self.nonempty():
raise 'Version Error', (
raise ValueError, (
'Attempt to %sdelete a non-empty version.<p>'
((self is not item) and 'indirectly ' or ''))
......
......@@ -17,7 +17,7 @@ This product provides support for Script objects containing restricted
Python code.
"""
__version__='$Revision: 1.50 $'[11:-2]
__version__='$Revision: 1.51 $'[11:-2]
import sys, os, traceback, re, marshal, new
from Globals import DTMLFile, MessageDialog, package_home
......@@ -34,6 +34,7 @@ from OFS.Cache import Cacheable
from AccessControl import full_write_guard, safe_builtins
from AccessControl.ZopeGuards import guarded_getattr, guarded_getitem
from zLOG import LOG, ERROR, INFO, PROBLEM
from zExceptions import Forbidden
# Track the Python bytecode version
import imp
......@@ -336,7 +337,7 @@ class PythonScript(Script, Historical, Cacheable):
user = getSecurityManager().getUser()
if user is not None and user.allowed(self, roles):
return
raise 'Forbidden', ('You are not authorized to change <em>%s</em> '
raise Forbidden, ('You are not authorized to change <em>%s</em> '
'because you do not have proxy roles.\n<!--%s, %s-->'
% (self.id, user, roles))
......
......@@ -47,7 +47,8 @@ class VirtualHostMonster(Persistent, Item, Implicit):
try:
host, path = [x.strip() for x in line.split('/', 1)]
except:
raise 'LineError', 'Needs a slash between host and path'
raise ValueError, (
'Line needs a slash between host and path: %s' % line )
pp = filter(None, path.split( '/'))
if pp:
obpath = pp[:]
......@@ -63,16 +64,19 @@ class VirtualHostMonster(Persistent, Item, Implicit):
try:
ob = self.unrestrictedTraverse(obpath)
except:
raise 'LineError', 'Path not found'
raise ValueError, (
'Path not found: %s' % obpath )
if not getattr(ob.aq_base, 'isAnObjectManager', 0):
raise 'LineError', ('Path must lead to '
'an Object Manager')
raise ValueError, (
'Path must lead to an Object Manager: %s'
% obpath)
if 'VirtualHostRoot' not in pp:
pp.append('/')
pp.reverse()
try:
int(host.replace('.',''))
raise 'LineError', 'IP addresses are not mappable'
raise ValueError, (
'IP addresses are not mappable: %s' % host)
except ValueError:
pass
if host[:2] == '*.':
......
......@@ -13,7 +13,7 @@
##############################################################################
"""Site error log module.
$Id: SiteErrorLog.py,v 1.16 2003/07/21 04:16:22 chrism Exp $
$Id: SiteErrorLog.py,v 1.17 2003/11/18 13:17:07 tseaver Exp $
"""
import os
......@@ -118,7 +118,7 @@ class SiteErrorLog (SimpleItem):
# Exceptions that happen all the time, so we dont need
# to log them. Eventually this should be configured
# through-the-web.
_ignored_exceptions = ( 'Unauthorized', 'NotFound' )
_ignored_exceptions = ( 'Unauthorized', 'NotFound', 'Redirect' )
security.declarePrivate('raising')
def raising(self, info):
......
......@@ -13,10 +13,10 @@
"""
Transient Object Container Class ('timeslice'-based design).
$Id: Transience.py,v 1.32 2003/01/21 07:55:22 chrism Exp $
$Id: Transience.py,v 1.33 2003/11/18 13:17:08 tseaver Exp $
"""
__version__='$Revision: 1.32 $'[11:-2]
__version__='$Revision: 1.33 $'[11:-2]
import Globals
from Globals import HTMLFile
......@@ -931,7 +931,7 @@ class Ring(Persistent):
purposes (Zope 2.5X). """
def __init__(self, l, index):
if not len(l):
raise "ring must have at least one element"
raise ValueError, "ring must have at least one element"
DEBUG and TLOG('initial _ring buckets: %s' % map(oid, l))
self._data = l
self._index = index
......
......@@ -14,6 +14,7 @@
from Interface.Verify import verifyClass
import Acquisition
from zExceptions import NotFound
from Products.PluginIndexes.common.PluggableIndex import \
PluggableIndexInterface
......@@ -48,7 +49,7 @@ class LexiconHolder(Acquisition.Implicit):
def dummyUnrestrictedTraverse(self, path):
if path == ('', 'lexicon',):
return self.lexicon
raise 'NotFound', path
raise NotFound, path
# The tests classes below create a ZCTextIndex(). Then they create
# instance variables that point to the internal components used by
......
......@@ -42,6 +42,9 @@ except ImportError:
return callable(ob)
class CatalogError(Exception):
pass
class Catalog(Persistent, Acquisition.Implicit, ExtensionClass.Base):
""" An Object Catalog
......@@ -182,10 +185,10 @@ class Catalog(Persistent, Acquisition.Implicit, ExtensionClass.Base):
names = list(self.names)
if schema.has_key(name):
raise 'Column Exists', 'The column exists'
raise CatalogError, 'The column %s already exists' % name
if name[0] == '_':
raise 'Invalid Meta-Data Name', \
raise CatalogError, \
'Cannot cache fields beginning with "_"'
if not schema.has_key(name):
......@@ -255,13 +258,13 @@ class Catalog(Persistent, Acquisition.Implicit, ExtensionClass.Base):
"""
if self.indexes.has_key(name):
raise 'Index Exists', 'The index specified already exists'
raise CatalogError, 'The index %s already exists' % name
if name.startswith('_'):
raise 'Invalid Index Name', 'Cannot index fields beginning with "_"'
raise CatalogError, 'Cannot index fields beginning with "_"'
if not name:
raise 'Invalid Index Name', 'Name of index is empty'
raise CatalogError, 'Name of index is empty'
indexes = self.indexes
......@@ -277,7 +280,7 @@ class Catalog(Persistent, Acquisition.Implicit, ExtensionClass.Base):
""" deletes an index """
if not self.indexes.has_key(name):
raise 'No Index', 'The index specified does not exist'
raise CatalogError, 'The index %s does not exist' % name
indexes = self.indexes
del indexes[name]
......@@ -754,8 +757,6 @@ class Catalog(Persistent, Acquisition.Implicit, ExtensionClass.Base):
__call__ = searchResults
class CatalogError(Exception): pass
class CatalogSearchArgumentsMap:
"""Multimap catalog arguments coming simultaneously from keywords
and request.
......
......@@ -217,7 +217,9 @@ def main():
f = h.getfile()
data = f.read()
print data
raise "Error reading from host %s" % server
class HTTPRequestError(Exception):
pass
raise HTTPRequestError, "Error reading from host %s" % server
f = h.getfile()
out=open(mb,'w')
print "this is going to take a while..."
......
......@@ -76,12 +76,8 @@ class TestAddDelColumn(CatalogBase,unittest.TestCase):
'add column failed')
def testAddBad(self):
try:
self._catalog.addColumn('_id')
except:
pass
else:
raise 'invalid metadata column check failed'
from Products.ZCatalog.Catalog import CatalogError
self.assertRaises(CatalogError, self._catalog.addColumn, '_id')
def testDel(self):
self._catalog.addColumn('id')
......
......@@ -13,12 +13,14 @@
database_type='Gadfly'
__doc__='''%s Database Connection
$Id: DA.py,v 1.15 2002/08/14 22:25:17 mj Exp $''' % database_type
__version__='$Revision: 1.15 $'[11:-2]
$Id: DA.py,v 1.16 2003/11/18 13:17:11 tseaver Exp $''' % database_type
__version__='$Revision: 1.16 $'[11:-2]
from db import DB, manage_DataSources
import sys, DABase, Globals
import Shared.DC.ZRDB.Connection, ThreadLock
from zExceptions import BadRequest
_Connection=Shared.DC.ZRDB.Connection.Connection
_connections={}
......@@ -84,7 +86,7 @@ class Connection(DABase.Connection):
self._v_database_connection=c[s]=DB(s)
except:
t, v, tb = sys.exc_info()
raise 'BadRequest', (
raise BadRequest, (
'<strong>Invalid connection string: </strong>'
'<CODE>%s</CODE><br>\n'
'<!--\n%s\n%s\n-->\n'
......
......@@ -12,14 +12,20 @@
##############################################################################
__doc__='''Generic Database Adapter Package Registration
$Id: __init__.py,v 1.15 2003/02/11 17:17:07 fdrake Exp $'''
__version__='$Revision: 1.15 $'[11:-2]
$Id: __init__.py,v 1.16 2003/11/18 13:17:11 tseaver Exp $'''
__version__='$Revision: 1.16 $'[11:-2]
import Globals, os
classes=('DA.Connection',)
database_type='Gadfly'
class GadflyError(Exception):
pass
class QueryError(GadflyError):
pass
misc_={'conn':
Globals.ImageFile('Shared/DC/ZRDB/www/DBAdapterFolder_icon.gif')}
......
......@@ -11,8 +11,8 @@
#
##############################################################################
'''$Id: db.py,v 1.13 2002/08/14 22:25:17 mj Exp $'''
__version__='$Revision: 1.13 $'[11:-2]
'''$Id: db.py,v 1.14 2003/11/18 13:17:11 tseaver Exp $'''
__version__='$Revision: 1.14 $'[11:-2]
import os
from string import strip, split
......@@ -22,6 +22,8 @@ from DateTime import DateTime
data_dir=os.path.join(Globals.data_dir,'gadfly')
from Products.ZGadflyDA import GadflyError, QueryError
def manage_DataSources():
if not os.path.exists(data_dir):
......@@ -29,14 +31,14 @@ def manage_DataSources():
os.mkdir(data_dir)
os.mkdir(os.path.join(data_dir,'demo'))
except:
raise 'Gadfly Error', (
raise GadflyError, (
"""
The Zope Gadfly Database Adapter requires the
existence of the directory, <code>%s</code>. An error
occurred while trying to create this directory.
""" % data_dir)
if not os.path.isdir(data_dir):
raise 'Gadfly Error', (
raise GadflyError, (
"""
The Zope Gadfly Database Adapter requires the
existence of the directory, <code>%s</code>. This
......@@ -99,7 +101,7 @@ class DB(Shared.DC.ZRDB.THUNK.THUNKED_TM):
self._register()
c=self.db.cursor()
queries=filter(None, map(strip,split(query_string, '\0')))
if not queries: raise 'Query Error', 'empty query'
if not queries: raise QueryError, 'empty query'
desc=None
result=[]
for qs in queries:
......@@ -108,7 +110,7 @@ class DB(Shared.DC.ZRDB.THUNK.THUNKED_TM):
if d is None: continue
if desc is None: desc=d
elif d != desc:
raise 'Query Error', (
raise QueryError, (
'Multiple incompatible selects in '
'multiple sql-statement query'
)
......
......@@ -4,6 +4,8 @@ verbosity = 0
import os
from Products.ZGadflyDA import GadflyError
# use whatever kjbuckets sqlsem is using
#from sqlsem import kjbuckets, maketuple
......@@ -887,7 +889,8 @@ class View(Relation0):
from sqlsem import kjbuckets
target_atts = selection.attributes()
if len(namelist)!=len(target_atts):
raise "select list and namelist don't match in %s"%name
raise GadflyError, (
"select list and namelist don't match in %s" % name)
pairs = map(None, namelist, target_atts)
self.translate = kjbuckets.kjGraph(pairs)
return self
......@@ -1043,7 +1046,9 @@ class shadow_dict:
try:
value = value_transform(value)
except:
raise "transform fails", (sys.exc_type, sys.exc_value, k, value)
raise GadFlyError, (
"transform fails: %s, %s, %s, %s" %
(sys.exc_type, sys.exc_value, k, value))
shadowed[k] = value
self.touched = {}
......@@ -1053,9 +1058,9 @@ class shadow_dict:
def __setitem__(self, key, item):
from types import StringType
if type(key) is not StringType:
raise "nonstring", key
raise GadflyError, "nonstring: %s" % key
if item is None:
raise "none set", (key, item)
raise GadflyError, "none set: %s, %s" % (key, item)
self.touched[key] = 1
self.shadow[key] = item
......@@ -1410,4 +1415,4 @@ class DB_Logger:
self.read_records(file)
self.verbose = verbose
self.restart()
\ No newline at end of file
......@@ -49,6 +49,8 @@ STARTUP = "gfstest"
import sys, socket
from Products.ZGadflyDA import QueryError
def main():
argv = sys.argv
......@@ -106,7 +108,7 @@ def policy_test():
print "exception", sys.exc_type, sys.exc_value
print "as expected"
else:
raise "DAMN!", "illegal query apparently completed!!!"
raise QueryError, "illegal query apparently completed!!!"
print; print "testing policy test1"; print
conn = gfclient("test1", PORT, "test1", machine)
cursor = conn.cursor()
......@@ -122,7 +124,7 @@ def policy_test():
print "exception", sys.exc_type, sys.exc_value
print "as expected"
else:
raise "Damn!(2)", "illegal query apparently completed"
raise QueryError, "illegal query apparently completed"
def startup(admin_policy, connection, Server_instance):
"""example startup script.
......@@ -222,4 +224,4 @@ def dosimple(command, pw):
print action()
if __name__=="__main__":
main()
\ No newline at end of file
main()
......@@ -6,6 +6,8 @@ run in current directory creates a database in files
test.dfs LIKES.grl SERVES.grl FREQUENTS.grl
"""
from Products.ZGadflyDA import GadflyError
def test(directory):
print "testing"
from gadfly import gadfly
......@@ -62,7 +64,7 @@ def test(directory):
except:
print "exception as expected %s(%s)" %(sys.exc_type, sys.exc_value)
else:
raise "stop!", "unique index permits nonunique field"
raise GadflyError, "unique index permits nonunique field"
print; print "testing introspection"
itests = ["select 10*4 from dual",
"select * from __table_names__",
......@@ -721,4 +723,4 @@ if __name__=="__main__":
test(directory)
rollbacktest(directory)
retest(directory)
\ No newline at end of file
......@@ -335,7 +335,7 @@ class lexdictionary:
self.laststring= self.lastindex= self.lastresult = None
def Dump(self, *k):
raise "sorry", "not implemented"
raise NotImplementedError
__getitem__ = Dump
def keyword(self, str):
......
......@@ -965,6 +965,9 @@ def kjUndump(t1, t2):
return result
class TestFailure(Exception):
pass
def test():
global S, D, G
G = kjGraph()
......@@ -996,37 +999,37 @@ def test():
del X[2]
print X, "Clean after", X.Clean()
if not X.subset(X):
raise "trivial subset fails", X
raise TestFaliure, "trivial subset fails: %s" % X
if not X==X:
raise "trivial cmp fails", X
raise TestFailure, "trivial cmp fails: %s" % X
if not X:
raise "nonzero fails", X
raise TestFailure, "nonzero fails: %s" % X
if X is S:
if not S.member(0):
raise "huh 1?"
raise TestFailure, "huh 1?"
if S.member(123):
raise "huh 2?", S
raise TestFailure, "huh 2?: %s" % S
S.add(999)
del S[1]
if not S.has_key(999):
raise "huh 3?", S
raise TestFailure, "huh 3?: %s" % S
else:
print "values", X.values()
print "keys", X.keys()
print X, "inverted", ~X
if not X.member(0,1):
raise "member test fails (0,1)", X
raise TestFailure, "member test fails (0,1): %s" % X
print "adding to", X
X.add(999,888)
print "added", X
X.delete_arc(999,888)
print "deleted", X
if X.member(999,888):
raise "member test fails (999,888)", X
raise TestFailure, "member test fails (999,888): %s" % X
if X.has_key(999):
raise "has_key fails 999", X
raise TestFailure, "has_key fails 999: %s" % X
if not X.has_key(0):
raise "has_key fails 0", X
raise TestFailure, "has_key fails 0: %s" % X
for Y in ALL:
print "Y", Y
if (X!=S and Y!=S):
......@@ -1040,11 +1043,11 @@ def test():
print "%s&%s=%s" % (X,Y,X&Y)
print "%s*%s=%s" % (X,Y,X*Y)
x,y = cmp(X,Y), cmp(Y,X)
if x!=-y: raise "bad cmp!", (X, Y)
if x!=-y: raise TestFailure, "bad cmp!: %s, %s" % (X, Y)
print "cmp(X,Y), -cmp(Y,X)", x,-y
print "X.subset(Y)", X.subset(Y)
\ No newline at end of file
......@@ -453,7 +453,7 @@ def default_reduction(list, context):
if type(x)==ListType:
if result == []:
if len(x)>0 and type(x[0])==ListType:
raise "oops", x
raise ValueError, "oops: %s" % x
result = x
else:
for y in x:
......
......@@ -1842,7 +1842,7 @@ class BTand_pred(BTPredicate):
for m in ms:
result = result & m # preserves or/and precedence
if result.__class__!=BTor_pred:
raise "what the?"
raise Exception, "what the?"
result = result.detrivialize()
#print "or detected, returning"
#print result
......
......@@ -18,6 +18,8 @@ import DocumentTemplate
import StructuredText
import re
from zExceptions import BadRequest
pre_pat=re.compile(r'<PRE>(.+?)</PRE>', re.IGNORECASE|re.DOTALL)
tutorialExamplesFile='ZopeTutorialExamples.zexp'
......@@ -160,7 +162,7 @@ def addTutorial(self, id, REQUEST=None, RESPONSE=None):
from Products.ZGadflyDA.DA import data_sources
data_sources()
except:
raise 'Bad Request', 'The ZGadflyDA product must be installed!'
raise BadRequest, 'The ZGadflyDA product must be installed!'
# work around old Zope bug in importing
try:
......
......@@ -25,6 +25,7 @@ from urllib import quote
from BindingsUI import BindingsUI
from Bindings import defaultBindings
from DocumentTemplate.DT_Util import TemplateDict
from zExceptions import Redirect
# Temporary:
from Signature import FuncCode
......@@ -51,6 +52,6 @@ class Script(SimpleItem, BindingsUI):
for argvar in argvars:
if argvar.value:
vv.append("%s=%s" % (quote(argvar.name), quote(argvar.value)))
raise "Redirect", "%s?%s" % (REQUEST['URL1'], join(vv, '&'))
raise Redirect, "%s?%s" % (REQUEST['URL1'], join(vv, '&'))
from Signature import _setFuncSignature
......@@ -12,8 +12,8 @@
##############################################################################
__doc__='''Shared classes and functions
$Id: Aqueduct.py,v 1.56 2002/08/14 21:50:59 mj Exp $'''
__version__='$Revision: 1.56 $'[11:-2]
$Id: Aqueduct.py,v 1.57 2003/11/18 13:17:14 tseaver Exp $'''
__version__='$Revision: 1.57 $'[11:-2]
import Globals, os
from Globals import Persistent
......@@ -24,6 +24,7 @@ from cStringIO import StringIO
from OFS import SimpleItem
from AccessControl.Role import RoleManager
from DocumentTemplate import HTML
from zExceptions import Redirect
from string import strip, replace
......@@ -121,7 +122,7 @@ class Searchable(BaseQuery):
def index_html(self, URL1):
" "
raise 'Redirect', ("%s/manage_testForm" % URL1)
raise Redirect, ("%s/manage_testForm" % URL1)
class Composite:
......
......@@ -12,8 +12,8 @@
##############################################################################
__doc__='''Generic Database Connection Support
$Id: Connection.py,v 1.37 2003/10/22 20:33:56 chrisw Exp $'''
__version__='$Revision: 1.37 $'[11:-2]
$Id: Connection.py,v 1.38 2003/11/18 13:17:14 tseaver Exp $'''
__version__='$Revision: 1.38 $'[11:-2]
import Globals, OFS.SimpleItem, AccessControl.Role, Acquisition, sys
from DateTime import DateTime
......@@ -26,6 +26,7 @@ from Results import Results
from sys import exc_info
from zLOG import LOG, ERROR
import DocumentTemplate, RDB
from zExceptions import BadRequest
class Connection(
Globals.Persistent,
......@@ -168,7 +169,7 @@ class Connection(
if s:
self.connect(s)
return self._v_database_connection
raise 'Database Not Connected',(
raise BadRequest,(
'''The database connection is not connected''')
def connect(self,s):
......@@ -179,7 +180,7 @@ class Connection(
self._v_database_connection=DB(s)
except:
t, v, tb = sys.exc_info()
raise 'BadRequest', (
raise BadRequest, (
'<strong>Invalid connection string: </strong><CODE>%s</CODE><br>\n'
'<!--\n%s\n%s\n-->\n'
% (s,t,v)), tb
......
......@@ -13,7 +13,7 @@
__doc__='''Generic Database adapter'''
__version__='$Revision: 1.111 $'[11:-2]
__version__='$Revision: 1.112 $'[11:-2]
import OFS.SimpleItem, Aqueduct, RDB, re
import DocumentTemplate, marshal, md5, base64, Acquisition, os
......@@ -37,6 +37,7 @@ from AccessControl import getSecurityManager
from AccessControl.DTML import RestrictedDTML
from webdav.Resource import Resource
from webdav.Lockable import ResourceLockedError
from zExceptions import BadRequest
try: from IOBTree import Bucket
except: Bucket=lambda:{}
......@@ -411,7 +412,7 @@ class DA(
c))
try: DB__=dbc()
except: raise 'Database Error', (
except: raise BadRequest, (
'%s is not connected to a database' % self.id)
if hasattr(self, 'aq_parent'):
......
......@@ -12,8 +12,8 @@
##############################################################################
__doc__='''Search Interface Wizard
$Id: Search.py,v 1.20 2002/08/14 21:50:59 mj Exp $'''
__version__='$Revision: 1.20 $'[11:-2]
$Id: Search.py,v 1.21 2003/11/18 13:17:14 tseaver Exp $'''
__version__='$Revision: 1.21 $'[11:-2]
from Globals import DTMLFile
from Aqueduct import custom_default_report, custom_default_zpt_report, nicify, Args
......@@ -50,7 +50,7 @@ def manage_addZSearch(self, report_id, report_title, report_style,
arguments[key]=arg
keys.append(key)
if q._searchable_result_columns() is None:
raise 'Unusable Searchable Error',(
raise ValueError,(
"""The input searchable object, <em>%s</em>,
has not been tested. Until it has been tested,
it\'s output schema is unknown, and a report
......
......@@ -13,14 +13,14 @@
__doc__='''short description
$Id: dbi_db.py,v 1.10 2002/08/14 21:50:59 mj Exp $'''
$Id: dbi_db.py,v 1.11 2003/11/18 13:17:14 tseaver Exp $'''
# Copyright
#
# Copyright 1997 Digital Creations, Inc, 910 Princess Anne
# Street, Suite 300, Fredericksburg, Virginia 22401 U.S.A. All
# rights reserved.
#
__version__='$Revision: 1.10 $'[11:-2]
__version__='$Revision: 1.11 $'[11:-2]
import string, sys
from string import strip, split, find, join
......@@ -34,6 +34,9 @@ nonselect_desc=[
('Calls', 'STRING', 12, 12, 0, 0, 1),
]
class QueryError(Exception):
pass
class DB:
_p_oid=_p_changed=_registered=None
......@@ -42,7 +45,7 @@ class DB:
def Database_Connection(self, string):
# Create a dbi-compatible database connection
raise 'ImplementedBySubclass', (
raise NotImplemetedError, (
'attempt to create a database connection for an abstract dbi')
Database_Error='Should be overriden by subclass'
......@@ -79,12 +82,12 @@ class DB:
c=self.cursor
self.register()
queries=filter(None, map(strip,split(query_string, '\0')))
if not queries: raise 'Query Error', 'empty query'
if not queries: raise QueryError, 'empty query'
if len(queries) > 1:
result=[]
for qs in queries:
r=c.execute(qs)
if r is None: raise 'Query Error', (
if r is None: raise QueryError, (
'select in multiple sql-statement query'
)
result.append((qs, str(`r`), calls))
......
......@@ -69,8 +69,8 @@
# rights reserved.
#
############################################################################
__rcs_id__='$Id: sqlgroup.py,v 1.9 2002/08/14 21:50:59 mj Exp $'
__version__='$Revision: 1.9 $'[11:-2]
__rcs_id__='$Id: sqlgroup.py,v 1.10 2003/11/18 13:17:14 tseaver Exp $'
__version__='$Revision: 1.10 $'[11:-2]
from DocumentTemplate.DT_Util import parse_params
str=__builtins__['str']
......@@ -110,7 +110,7 @@ class SQLGroup:
return r
if self.required:
raise 'Input Error', 'Not enough input was provided!<p>'
raise ValueError, 'Not enough input was provided!<p>'
return ''
......
......@@ -55,7 +55,7 @@
'and' or 'or' tag, otherwise, no text is inserted.
'''
__rcs_id__='$Id: sqltest.py,v 1.18 2002/08/14 21:50:59 mj Exp $'
__rcs_id__='$Id: sqltest.py,v 1.19 2003/11/18 13:17:14 tseaver Exp $'
############################################################################
# Copyright
......@@ -65,7 +65,7 @@ __rcs_id__='$Id: sqltest.py,v 1.18 2002/08/14 21:50:59 mj Exp $'
# rights reserved.
#
############################################################################
__version__='$Revision: 1.18 $'[11:-2]
__version__='$Revision: 1.19 $'[11:-2]
import sys
from DocumentTemplate.DT_Util import ParseError, parse_params, name_param
......@@ -129,11 +129,11 @@ class SQLTest:
except KeyError:
if args.has_key('optional') and args['optional']:
return ''
raise 'Missing Input', 'Missing input variable, <em>%s</em>' % name
raise ValueError, 'Missing input variable, <em>%s</em>' % name
if type(v) in (ListType, TupleType):
if len(v) > 1 and not self.multiple:
raise 'Multiple Values', (
raise ValueError, (
'multiple values are not allowed for <em>%s</em>'
% name)
else: v=[v]
......@@ -175,7 +175,7 @@ class SQLTest:
if not vs:
if self.optional: return ''
raise 'Missing Input', (
raise ValueError, (
'No input was provided for <em>%s</em>' % name)
if len(vs) > 1:
......
......@@ -47,7 +47,7 @@
however, if x is ommitted or an empty string, then the value
inserted is 'null'.
'''
__rcs_id__='$Id: sqlvar.py,v 1.14 2003/03/19 20:21:23 zagy Exp $'
__rcs_id__='$Id: sqlvar.py,v 1.15 2003/11/18 13:17:14 tseaver Exp $'
############################################################################
# Copyright
......@@ -57,7 +57,7 @@ __rcs_id__='$Id: sqlvar.py,v 1.14 2003/03/19 20:21:23 zagy Exp $'
# rights reserved.
#
############################################################################
__version__='$Revision: 1.14 $'[11:-2]
__version__='$Revision: 1.15 $'[11:-2]
from DocumentTemplate.DT_Util import ParseError, parse_params, name_param
from string import find, split, join, atoi, atof
......@@ -96,7 +96,7 @@ class SQLVar:
return 'null'
if type(expr) is not type(''):
raise
raise 'Missing Input', 'Missing input variable, <em>%s</em>' % name
raise ValueError, 'Missing input variable, <em>%s</em>' % name
if t=='int':
try:
......
......@@ -12,8 +12,8 @@
##############################################################################
"""Rendering object hierarchies as Trees
"""
__rcs_id__='$Id: TreeTag.py,v 1.54 2003/11/04 21:17:22 evan Exp $'
__version__='$Revision: 1.54 $'[11:-2]
__rcs_id__='$Id: TreeTag.py,v 1.55 2003/11/18 13:17:14 tseaver Exp $'
__version__='$Revision: 1.55 $'[11:-2]
from DocumentTemplate.DT_Util import *
from DocumentTemplate.DT_String import String
......@@ -574,7 +574,7 @@ def decode_seq(state):
state=a2b_base64(state)
state=decompress(state)
if state.find('*') >= 0: raise 'Illegal State', state
if state.find('*') >= 0: raise ValueError, 'Illegal State: %s' % state
try: return list(eval(state,{'__builtins__':{}}))
except: return []
......
......@@ -15,6 +15,7 @@
import Globals, OFS.PropertySheets, OFS.Image, ExtensionClass
import Acquisition, Products
from zExceptions import BadRequest
class ZClassBasicSheet(OFS.PropertySheets.PropertySheet,
OFS.PropertySheets.View):
......@@ -84,7 +85,7 @@ class ZClassViewsSheet(OFS.PropertySheets.PropertySheet,
options=self.data()
changed=0
if len(actions)!=len(options):
raise 'Bad Request', 'wrong number of actions'
raise BadRequest, 'wrong number of actions'
for i in range(len(actions)):
if options[i]['action'] != actions[i]:
......@@ -140,7 +141,7 @@ class ZClassViewsSheet(OFS.PropertySheets.PropertySheet,
options=self.data()
for option in options:
if option['label']==label:
raise 'Bad Request', (
raise BadRequest, (
'Please provide a <strong>new</strong> label.'
)
if help:
......
......@@ -22,6 +22,7 @@ from AccessControl.PermissionMapping import aqwrap, PermissionMapper
import OFS.content_types
from OFS.DTMLMethod import DTMLMethod
from Products.PythonScripts.PythonScript import PythonScript
from zExceptions import BadRequest
import marshal
......@@ -106,10 +107,10 @@ class ZClassMethodsSheet(
def _checkId(self, id, allow_dup=0,
_reserved=('propertysheets','manage_workspace')):
if id in _reserved:
raise 'Bad Request', 'The id, %s, is reseverd' % id
raise BadRequest, 'The id, %s, is reseverd' % id
if not allow_dup and self.getClassAttr(id, self) is not self:
raise 'Bad Request', (
raise BadRequest, (
'The id %s is invalid - it is already in use.' % id)
ZClassMethodsSheet.inheritedAttribute('_checkId')(
......
......@@ -225,7 +225,7 @@ class ZCommonSheet(OFS.PropertySheets.PropertySheet, OFS.SimpleItem.Item):
p=class_permissions[i]
if p and (p not in perms):
__traceback_info__=perms, p, i
raise 'Invalid class permission'
raise ValueError, 'Invalid class permission'
if name not in property_sheet_permissions: continue
......
......@@ -20,6 +20,7 @@ from ExtensionClass import Base
from App.FactoryDispatcher import FactoryDispatcher
from ComputedAttribute import ComputedAttribute
from Products.PythonScripts.PythonScript import PythonScript
from zExceptions import BadRequest, Redirect
import webdav.Collection
import marshal
......@@ -127,7 +128,7 @@ def manage_addZClass(self, id, title='', baseclasses=[],
"""Add a Z Class
"""
if bad_id(id) is not None:
raise 'Bad Request', (
raise BadRequest, (
'The id %s is invalid as a class name.' % id)
if not meta_type: meta_type=id
......@@ -142,7 +143,7 @@ def manage_addZClass(self, id, title='', baseclasses=[],
elif r.has_key(b):
bases.append(r[b])
else:
raise 'Invalid class', b
raise ValueError, 'Invalid class: %s' % b
Z=ZClass(id, title, bases, zope_object=zope_object)
Z._zclass_.meta_type=meta_type
......@@ -372,7 +373,7 @@ class ZClass( Base
jar=self._waaa_getJar()
globals=jar.root()['ZGlobals']
if globals.has_key(class_id):
raise 'Duplicate Class Ids'
raise ValueError, 'Duplicate Class Ids'
globals[class_id]=z
......@@ -620,7 +621,7 @@ class ZClassSheets(OFS.PropertySheets.PropertySheets):
#def tpURL(self): return 'propertysheets'
def manage_workspace(self, URL2):
"Emulate standard interface for use with navigation"
raise 'Redirect', URL2+'/manage_workspace'
raise Redirect, URL2+'/manage_workspace'
views = Basic.ZClassViewsSheet('views')
basic = Basic.ZClassBasicSheet('basic')
......
......@@ -12,11 +12,12 @@
##############################################################################
""" Basic ZPublisher request management.
$Id: BaseRequest.py,v 1.52 2003/10/14 09:08:44 yuppie Exp $
$Id: BaseRequest.py,v 1.53 2003/11/18 13:17:17 tseaver Exp $
"""
from urllib import quote
import xmlrpc
from zExceptions import Forbidden
UNSPECIFIED_ROLES=''
......@@ -499,7 +500,7 @@ def old_validation(groups, request, auth,
if keys is None:
# Not a named group, so don't go further
raise 'Forbidden', (
raise Forbidden, (
"""<strong>You are not authorized to access this resource""")
return None
......
......@@ -12,12 +12,13 @@
##############################################################################
'''CGI Response Output formatter
$Id: BaseResponse.py,v 1.17 2002/08/21 03:09:31 chrism Exp $'''
__version__ = '$Revision: 1.17 $'[11:-2]
$Id: BaseResponse.py,v 1.18 2003/11/18 13:17:17 tseaver Exp $'''
__version__ = '$Revision: 1.18 $'[11:-2]
import types, sys
from types import StringType, InstanceType
from zExceptions import Unauthorized
from zExceptions import Unauthorized, Forbidden
from zExceptions import NotFound, BadRequest
class BaseResponse:
"""Base Response Class
......@@ -139,19 +140,19 @@ class BaseResponse:
def notFoundError(self, v=''):
"""Generate an error indicating that an object was not found.
"""
raise 'Not Found', v
raise NotFound, v
def debugError(self, v=''):
"""Raise an error with debigging info and in debugging mode"""
raise 'Debug Error', v
raise NotFound, "Debugging notice: %s" % v
def badRequestError(self, v=''):
"""Raise an error indicating something wrong with the request"""
raise 'Bad Request', v
raise BadRequest, v
def forbiddenError(self, v=''):
"""Raise an error indicating that the request cannot be done"""
raise 'Forbidden', v
raise Forbidden, v
def unauthorized(self):
"""Raise an eror indicating that the user was not authizated
......
......@@ -31,7 +31,7 @@ that allows one to simply make a single web request.
The module also provides a command-line interface for calling objects.
"""
__version__='$Revision: 1.45 $'[11:-2]
__version__='$Revision: 1.46 $'[11:-2]
import sys, re, socket, mimetools
from httplib import HTTP
......@@ -44,6 +44,9 @@ from types import FileType, ListType, DictType, TupleType
from string import translate, maketrans
from urlparse import urlparse
class BadReply(Exception):
pass
class Function:
username=None
password=None
......@@ -213,9 +216,9 @@ class Function:
try:
[ver, ec, em] = line.split(None, 2)
except ValueError:
raise 'BadReply','Bad reply from server: '+line
raise BadReply,'Bad reply from server: '+line
if ver[:5] != 'HTTP/':
raise 'BadReply','Bad reply from server: '+line
raise BadReply,'Bad reply from server: '+line
ec=int(ec)
em=em.strip()
......
......@@ -11,7 +11,7 @@
#
##############################################################################
__version__='$Revision: 1.92 $'[11:-2]
__version__='$Revision: 1.93 $'[11:-2]
import re, sys, os, urllib, time, random, cgi, codecs
from types import StringType, UnicodeType
......@@ -56,6 +56,10 @@ tainting_env = str(os.environ.get('ZOPE_DTML_REQUEST_AUTOQUOTE', '')).lower()
TAINTING_ENABLED = tainting_env not in ('disabled', '0', 'no')
_marker=[]
class NestedLoopExit( Exception ):
pass
class HTTPRequest(BaseRequest):
"""\
Model HTTP request data.
......@@ -886,8 +890,8 @@ class HTTPRequest(BaseRequest):
for origitem in l:
if not hasattr(origitem, k):
missesdefault = 1
raise "Break"
except "Break":
raise NestedLoopExit
except NestedLoopExit:
break
else:
if not defitem in l:
......
......@@ -12,22 +12,19 @@
##############################################################################
'''CGI Response Output formatter
$Id: HTTPResponse.py,v 1.76 2003/07/08 05:54:11 ctheune Exp $'''
__version__ = '$Revision: 1.76 $'[11:-2]
$Id: HTTPResponse.py,v 1.77 2003/11/18 13:17:17 tseaver Exp $'''
__version__ = '$Revision: 1.77 $'[11:-2]
import types, os, sys, re
import zlib, struct
from string import translate, maketrans
from BaseResponse import BaseResponse
from zExceptions import Unauthorized
from zExceptions import Unauthorized, Redirect
from zExceptions.ExceptionFormatter import format_exception
from ZPublisher import BadRequest, InternalError, NotFound
nl2sp = maketrans('\n',' ')
BadRequest = 'BadRequest'
InternalError = 'InternalError'
NotFound = 'NotFound'
# Enable APPEND_TRACEBACKS to make Zope append tracebacks like it used to,
# but a better solution is to make standard_error_message display error_tb.
......@@ -215,13 +212,20 @@ class HTTPResponse(BaseResponse):
# It has already been determined.
return
if (isinstance(status, types.ClassType)
and issubclass(status, Exception)):
status = status.__name__
if isinstance(status, str):
status = status.lower()
if status_codes.has_key(status):
status = status_codes[status]
else:
status = 500
self.status = status
if reason is None:
if status_reasons.has_key(status):
reason = status_reasons[status]
......@@ -726,6 +730,13 @@ class HTTPResponse(BaseResponse):
self.setHeader('location', v)
tb = None # just one path covered
return self
elif isinstance(v, Redirect): # death to string exceptions!
if self.status == 300:
self.setStatus(302)
self.setHeader('location', v.args[0])
self.setBody('')
tb = None
return self
else:
try:
l, b = v
......
......@@ -12,14 +12,15 @@
##############################################################################
__doc__="""Python Object Publisher -- Publish Python objects on web servers
$Id: Publish.py,v 1.165 2003/10/21 14:10:16 chrism Exp $"""
__version__='$Revision: 1.165 $'[11:-2]
$Id: Publish.py,v 1.166 2003/11/18 13:17:17 tseaver Exp $"""
__version__='$Revision: 1.166 $'[11:-2]
import sys, os
from Response import Response
from Request import Request
from maybe_lock import allocate_lock
from mapply import mapply
from zExceptions import Redirect
class Retry(Exception):
"""Raise this to retry a request
......@@ -69,7 +70,8 @@ def publish(request, module_name, after_list, debug=0,
# First check for "cancel" redirect:
if request_get('SUBMIT','').strip().lower()=='cancel':
cancel=request_get('CANCEL_ACTION','')
if cancel: raise 'Redirect', cancel
if cancel:
raise Redirect, cancel
after_list[0]=bobo_after
if debug_mode: response.debug_mode=debug_mode
......
......@@ -90,9 +90,9 @@ Examples
s
$Id: Test.py,v 1.40 2002/08/14 22:09:40 mj Exp $
$Id: Test.py,v 1.41 2003/11/18 13:17:17 tseaver Exp $
'''
__version__='$Revision: 1.40 $'[11:-2]
__version__='$Revision: 1.41 $'[11:-2]
import sys, traceback, profile, os, getopt
from time import clock
......@@ -130,11 +130,12 @@ def main():
repeat_count=int(val)
elif opt=='-e':
opt=val.find('=')
if opt <= 0: raise 'Invalid argument to -e', val
if opt <= 0: raise ValueError, 'Invalid argument to -e: %s' % val
env[val[:opt]]=val[opt+1:]
if (debug or 0)+(timeit or 0)+(profile and 1 or 0) > 1:
raise 'Invalid options', 'only one of -p, -t, and -d are allowed'
raise ValueError, (
'Invalid options: only one of -p, -t, and -d are allowed')
module=args[0]
......
......@@ -10,7 +10,7 @@
# FOR A PARTICULAR PURPOSE
#
##############################################################################
__version__='$Revision: 1.12 $'[11:-2]
__version__='$Revision: 1.13 $'[11:-2]
# This allows ZPublisher to work with embedded interpreters
......@@ -19,6 +19,7 @@ import sys
if not hasattr(sys, 'argv'):
sys.argv=[]
from zExceptions import NotFound, BadRequest, InternalError, Forbidden
from Publish import publish_module, Retry
......
......@@ -136,9 +136,10 @@ class TestBaseRequest(TestCase):
def test_traverse_withBDEmpty(self):
# Collector 1079 (infinite loop 2)
from ZPublisher import NotFound
r = self.makeBaseRequest()
self.f1.objWithBD._default_path = ['']
self.failUnlessRaises('NotFound', r.traverse, 'folder/objWithBD')
self.failUnlessRaises(NotFound, r.traverse, 'folder/objWithBD')
def test_traverse_slash(self):
r = self.makeBaseRequest()
......
import unittest
class HTTPResponseTests(unittest.TestCase):
def _getTargetClass(self):
from ZPublisher.HTTPResponse import HTTPResponse
return HTTPResponse
def _makeOne(self, *args, **kw):
return self._getTargetClass()(*args, **kw)
def test_setStatus_with_exceptions(self):
from zExceptions import Unauthorized
from zExceptions import Forbidden
from zExceptions import NotFound
from zExceptions import BadRequest
from zExceptions import InternalError
for exc_type, code in ((Unauthorized, 401),
(Forbidden, 403),
(NotFound, 404),
(BadRequest, 400),
(InternalError, 500)):
response = self._makeOne()
response.setStatus(exc_type)
self.assertEqual(response.status, code)
def test_suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(HTTPResponseTests, 'test'))
return suite
if __name__ == '__main__':
unittest.main(defaultTest='test_suite')
......@@ -51,6 +51,9 @@ from types import StringType, TupleType
tz_for_log=compute_timezone_for_log()
class ParseError(Exception):
pass
class PCGIChannel(asynchat.async_chat):
"""Processes a PCGI request by collecting the env and stdin and
then passing them to ZPublisher. The result is wrapped in a
......@@ -300,7 +303,7 @@ class PCGIServer(asyncore.dispatcher):
k,v=string.split(line,'=',1)
directives[string.strip(k)]=string.strip(v)
except:
raise 'ParseError', 'Error parsing PCGI info file'
raise ParseError, 'Error parsing PCGI info file'
self.pid_file=directives.get('PCGI_PID_FILE',None)
self.socket_file=directives.get('PCGI_SOCKET_FILE',None)
......
# -*- Mode: Python; tab-width: 4 -*-
VERSION_STRING = "$Id: select_trigger.py,v 1.6 2003/03/18 21:17:03 fdrake Exp $"
VERSION_STRING = "$Id: select_trigger.py,v 1.7 2003/11/18 13:17:19 tseaver Exp $"
import asyncore
import asynchat
......@@ -92,6 +92,9 @@ else:
# win32-safe version
class BindError(Exception):
pass
class trigger (asyncore.dispatcher):
address = ('127.9.9.9', 19999)
......@@ -113,7 +116,7 @@ else:
break
except:
if port <= 19950:
raise 'Bind Error', 'Cannot bind trigger!'
raise BindError, 'Cannot bind trigger!'
port=port - 1
a.listen (1)
......
......@@ -13,7 +13,7 @@
##############################################################################
"""Zope user bootstrap system"""
__version__='$Revision: 1.4 $ '[11:-2]
__version__='$Revision: 1.5 $ '[11:-2]
import sys, sha, binascii, random, getopt, getpass, os
......@@ -88,6 +88,9 @@ def write_inituser(home, user='', group=''):
import do; do.ch(ac_path, user, group)
class CommandLineError(Exception):
pass
def main(argv):
short_options = ':u:p:e:d:'
long_options = ['username=',
......@@ -120,12 +123,12 @@ Copyright (C) 1999, 2000 Digital Creations, Inc.
try:
if len(argv) < 2:
raise "CommandLineError"
raise CommandLineError, "Not enough arguments!"
optlist, args = getopt.getopt(sys.argv[1:], short_options, long_options)
if len(args) != 1:
raise "CommandLineError"
raise CommandLineError, "Only one filename allowed!"
access_file = open(args[0], 'w')
......@@ -147,7 +150,7 @@ Copyright (C) 1999, 2000 Digital Creations, Inc.
# Verify that we got what we need
if not username or not password:
raise "CommandLineError"
raise CommandLineError, "Must specify username and password."
access_file.write(username + ':' +
generate_passwd(password, encoding) +
......@@ -191,10 +194,12 @@ CLEARTEXT - no protection
generate_passwd(password, encoding) +
domains)
except "CommandLineError":
except CommandLineError, v:
sys.stderr.write(usage)
sys.stderr.write("\n\n%s" % v)
sys.exit(1)
# If called from the command line
if __name__=='__main__': main(sys.argv)
if __name__=='__main__':
main(sys.argv)
......@@ -13,7 +13,7 @@
"""WebDAV support - collection objects."""
__version__='$Revision: 1.25 $'[11:-2]
__version__='$Revision: 1.26 $'[11:-2]
import sys, os, Globals, davcmds, Lockable,re
from common import urlfix, rfc1123_date
......@@ -21,7 +21,8 @@ from Resource import Resource
from AccessControl import getSecurityManager
from urllib import unquote
from WriteLockInterface import WriteLockInterface
from zExceptions import MethodNotAllowed, NotFound
from webdav.common import Locked, PreconditionFailed
class Collection(Resource):
"""The Collection class provides basic WebDAV support for
......@@ -54,10 +55,10 @@ class Collection(Resource):
if hasattr(self, 'index_html'):
if hasattr(self.index_html, 'HEAD'):
return self.index_html.HEAD(REQUEST, RESPONSE)
raise 'Method Not Allowed', (
raise MethodNotAllowed, (
'Method not supported for this resource.'
)
raise 'Not Found', 'The requested resource does not exist.'
raise NotFound, 'The requested resource does not exist.'
def PUT(self, REQUEST, RESPONSE):
"""The PUT method has no inherent meaning for collection
......@@ -65,7 +66,7 @@ class Collection(Resource):
to handle PUT requests. The default response to a PUT request
for collections is 405 (Method Not Allowed)."""
self.dav__init(REQUEST, RESPONSE)
raise 'Method Not Allowed', 'Method not supported for collections.'
raise MethodNotAllowed, 'Method not supported for collections.'
def DELETE(self, REQUEST, RESPONSE):
"""Delete a collection resource. For collection resources, DELETE
......@@ -92,12 +93,12 @@ class Collection(Resource):
if ifhdr:
self.dav__simpleifhandler(REQUEST, RESPONSE, 'DELETE', col=1)
else:
raise 'Locked'
raise Locked
elif Lockable.wl_isLocked(parent):
if ifhdr:
parent.dav__simpleifhandler(REQUEST, RESPONSE, 'DELETE', col=1)
else:
raise 'Precondition Failed'
raise PreconditionFailed
# Second level of lock\conflict checking (are any descendants locked,
# or is the user not permitted to delete?). This results in a
# multistatus response
......
......@@ -11,10 +11,11 @@
#
##############################################################################
__version__ = "$Revision: 1.9 $"[11:-2]
__version__ = "$Revision: 1.10 $"[11:-2]
import time, Interface, re
from webdav.common import PreconditionFailed
class EtagBaseInterface(Interface.Base):
"""\
......@@ -116,7 +117,7 @@ class EtagSupport:
# The resource etag is not in the list of etags required
# to match, as specified in the 'if-match' header. The
# condition fails and the HTTP Method may *not* execute.
raise "Precondition Failed"
raise PreconditionFailed
elif self.http__etag() in matchlist:
return 1
......@@ -129,10 +130,10 @@ class EtagSupport:
# be performed if the specified resource exists
# (webdav.NullResource will want to do special behavior
# here)
raise "Precondition Failed"
raise PreconditionFailed
elif self.http__etag() in nonelist:
# The opposite of if-match, the condition fails
# IF the resources Etag is in the if-none-match list
raise "Precondition Failed"
raise PreconditionFailed
elif self.http__etag() not in nonelist:
return 1
......@@ -13,7 +13,7 @@
"""WebDAV support - null resource objects."""
__version__='$Revision: 1.39 $'[11:-2]
__version__='$Revision: 1.40 $'[11:-2]
import sys, os, mimetypes, Globals, davcmds
import Acquisition, OFS.content_types
......@@ -24,8 +24,10 @@ from Resource import Resource
from Globals import Persistent, DTMLFile
from WriteLockInterface import WriteLockInterface
import OFS.SimpleItem
from zExceptions import Unauthorized
from zExceptions import Unauthorized, NotFound, Forbidden, BadRequest
from zExceptions import MethodNotAllowed
from common import isDavCollection
from common import Locked, Conflict, PreconditionFailed, UnsupportedMediaType
class NullResource(Persistent, Acquisition.Implicit, Resource):
"""Null resources are used to handle HTTP method calls on
......@@ -52,13 +54,13 @@ class NullResource(Persistent, Acquisition.Implicit, Resource):
except: pass
method=REQUEST.get('REQUEST_METHOD', 'GET')
if method in ('PUT', 'MKCOL', 'LOCK'):
raise 'Conflict', 'Collection ancestors must already exist.'
raise 'Not Found', 'The requested resource was not found.'
raise Conflict, 'Collection ancestors must already exist.'
raise NotFound, 'The requested resource was not found.'
def HEAD(self, REQUEST, RESPONSE):
"""Retrieve resource information without a response message body."""
self.dav__init(REQUEST, RESPONSE)
raise 'Not Found', 'The requested resource does not exist.'
raise NotFound, 'The requested resource does not exist.'
# Most methods return 404 (Not Found) for null resources.
DELETE=TRACE=PROPFIND=PROPPATCH=COPY=MOVE=HEAD
......@@ -94,10 +96,10 @@ class NullResource(Persistent, Acquisition.Implicit, Resource):
else:
# There was no If header at all, and our parent is locked,
# so we fail here
raise 'Locked'
raise Locked
elif ifhdr:
# There was an If header, but the parent is not locked
raise 'Precondition Failed'
raise PreconditionFailed
body=REQUEST.get('BODY', '')
typ=REQUEST.get_header('content-type', None)
......@@ -116,7 +118,7 @@ class NullResource(Persistent, Acquisition.Implicit, Resource):
except Unauthorized:
raise
except:
raise 'Forbidden', sys.exc_info()[1]
raise Forbidden, sys.exc_info()[1]
# Delegate actual PUT handling to the new object.
ob.PUT(REQUEST, RESPONSE)
......@@ -130,25 +132,25 @@ class NullResource(Persistent, Acquisition.Implicit, Resource):
"""Create a new collection resource."""
self.dav__init(REQUEST, RESPONSE)
if REQUEST.get('BODY', ''):
raise 'Unsupported Media Type', 'Unknown request body.'
raise UnsupportedMediaType, 'Unknown request body.'
name=self.__name__
parent = self.__parent__
if hasattr(aq_base(parent), name):
raise 'Method Not Allowed', 'The name %s is in use.' % name
raise MethodNotAllowed, 'The name %s is in use.' % name
if not isDavCollection(parent):
raise 'Forbidden', 'Cannot create collection at this location.'
raise Forbidden, 'Cannot create collection at this location.'
ifhdr = REQUEST.get_header('If', '')
if WriteLockInterface.isImplementedBy(parent) and parent.wl_isLocked():
if ifhdr:
parent.dav__simpleifhandler(REQUEST, RESPONSE, col=1)
else:
raise 'Locked'
raise Locked
elif ifhdr:
# There was an If header, but the parent is not locked
raise 'Precondition Failed'
raise PreconditionFailed
# Add hook for webdav/FTP MKCOL (Collector #2254) (needed for CMF)
# parent.manage_addFolder(name)
......@@ -175,16 +177,16 @@ class NullResource(Persistent, Acquisition.Implicit, Resource):
if ifhdr:
parent.dav__simpleifhandler(REQUEST, RESPONSE, col=1)
else:
raise 'Locked'
raise Locked
elif ifhdr:
# There was an If header, but the parent is not locked.
raise 'Precondition Failed'
raise PreconditionFailed
# The logic involved in locking a null resource is simpler than
# a regular resource, since we know we're not already locked,
# and the lock isn't being refreshed.
if not body:
raise 'Bad Request', 'No body was in the request'
raise BadRequest, 'No body was in the request'
locknull = LockNullResource(name)
parent._setObject(name, locknull)
......@@ -268,7 +270,8 @@ class LockNullResource(NullResource, OFS.SimpleItem.Item_w__name__):
RESPONSE.setStatus(423)
else:
# There's no body, so this is likely to be a refresh request
if not ifhdr: raise 'Precondition Failed'
if not ifhdr:
raise PreconditionFailed
taglist = IfParser(ifhdr)
found = 0
for tag in taglist:
......@@ -298,8 +301,10 @@ class LockNullResource(NullResource, OFS.SimpleItem.Item_w__name__):
user = security.getUser()
token = REQUEST.get_header('Lock-Token', '')
url = REQUEST['URL']
if token: token = tokenFinder(token)
else: raise 'Bad Request', 'No lock token was submitted in the request'
if token:
token = tokenFinder(token)
else:
raise BadRequest, 'No lock token was submitted in the request'
cmd = davcmds.Unlock()
result = cmd.apply(self, token, url)
......@@ -329,7 +334,8 @@ class LockNullResource(NullResource, OFS.SimpleItem.Item_w__name__):
# Since a Lock null resource is always locked by definition, all
# operations done by an owner of the lock that affect the resource
# MUST have the If header in the request
if not ifhdr: raise 'Precondition Failed', 'No If-header'
if not ifhdr:
raise PreconditionFailed, 'No If-header'
# First we need to see if the parent of the locknull is locked, and
# if the user owns that lock (checked by handling the information in
......@@ -338,12 +344,14 @@ class LockNullResource(NullResource, OFS.SimpleItem.Item_w__name__):
itrue = parent.dav__simpleifhandler(REQUEST, RESPONSE, 'PUT',
col=1, url=parenturl,
refresh=1)
if not itrue: raise 'Precondition Failed', (
if not itrue:
raise PreconditionFailed, (
'Condition failed against resources parent')
# Now we need to check the If header against our own lock state
itrue = self.dav__simpleifhandler(REQUEST, RESPONSE, 'PUT', refresh=1)
if not itrue: raise 'Precondition Failed', (
if not itrue:
raise PreconditionFailed, (
'Condition failed against locknull resource')
# All of the If header tests succeeded, now we need to remove ourselves
......@@ -367,11 +375,11 @@ class LockNullResource(NullResource, OFS.SimpleItem.Item_w__name__):
except Unauthorized:
raise
except:
raise 'Forbidden', sys.exc_info()[1]
raise Forbidden, sys.exc_info()[1]
# Put the locks on the new object
if not WriteLockInterface.isImplementedBy(ob):
raise 'Method Not Allowed', (
raise MethodNotAllowed, (
'The target object type cannot be locked')
for token, lock in locks:
ob.wl_setLock(token, lock)
......@@ -390,14 +398,15 @@ class LockNullResource(NullResource, OFS.SimpleItem.Item_w__name__):
object and transferring its locks to the newly created Folder """
self.dav__init(REQUEST, RESPONSE)
if REQUEST.get('BODY', ''):
raise 'Unsupported Media Type', 'Unknown request body.'
raise UnsupportedMediaType, 'Unknown request body.'
name = self.__name__
parent = self.aq_parent
parenturl = parent.absolute_url()
ifhdr = REQUEST.get_header('If', '')
if not ifhdr: raise 'Precondition Failed', 'No If-header'
if not ifhdr:
raise PreconditionFailed, 'No If-header'
# If the parent object is locked, that information should be in the
# if-header if the user owns a lock on the parent
......@@ -405,11 +414,13 @@ class LockNullResource(NullResource, OFS.SimpleItem.Item_w__name__):
itrue = parent.dav__simpleifhandler(REQUEST, RESPONSE, 'MKCOL',
col=1, url=parenturl,
refresh=1)
if not itrue: raise 'Precondition Failed', (
if not itrue:
raise PreconditionFailed, (
'Condition failed against resources parent')
# Now we need to check the If header against our own lock state
itrue = self.dav__simpleifhandler(REQUEST,RESPONSE,'MKCOL',refresh=1)
if not itrue: raise 'Precondition Failed', (
if not itrue:
raise PreconditionFailed, (
'Condition failed against locknull resource')
# All of the If header tests succeeded, now we need to remove ourselves
......
......@@ -11,20 +11,32 @@
#
##############################################################################
"""WebDAV support - resource objects."""
"""WebDAV support - resource objects.
__version__='$Revision: 1.57 $'[11:-2]
$Id: Resource.py,v 1.58 2003/11/18 13:17:20 tseaver Exp $
"""
import sys, os, mimetypes, davcmds, ExtensionClass, Lockable
from common import absattr, aq_base, urlfix, rfc1123_date, tokenFinder, urlbase
from common import IfParser
import os
import sys
import mimetypes
import time
from urllib import quote, unquote
import Globals
import ExtensionClass
from Acquisition import aq_base
from AccessControl import getSecurityManager
from WriteLockInterface import WriteLockInterface
import Globals, time
from ZPublisher.HTTPRangeSupport import HTTPRangeInterface
from zExceptions import Unauthorized
from zExceptions import Unauthorized, Forbidden
from zExceptions import BadRequest, MethodNotAllowed
from WriteLockInterface import WriteLockInterface
import Lockable
from common import absattr, urlfix, rfc1123_date, tokenFinder, urlbase
from common import IfParser
from common import isDavCollection
from common import Locked, Conflict, PreconditionFailed
import davcmds
class Resource(ExtensionClass.Base, Lockable.LockableItem):
"""The Resource mixin class provides basic WebDAV support for
......@@ -92,7 +104,7 @@ class Resource(ExtensionClass.Base, Lockable.LockableItem):
col=0, url=None, refresh=0):
ifhdr = request.get_header('If', None)
if Lockable.wl_isLocked(self) and (not ifhdr):
raise "Locked", "Resource is locked."
raise Locked, "Resource is locked."
if not ifhdr: return None
if not Lockable.wl_isLocked(self): return None
......@@ -136,7 +148,7 @@ class Resource(ExtensionClass.Base, Lockable.LockableItem):
found = 1; break
if resourcetagged and (not found):
raise 'Precondition Failed', 'Condition failed.'
raise PreconditionFailed, 'Condition failed.'
elif resourcetagged and found:
return 1
else:
......@@ -181,7 +193,7 @@ class Resource(ExtensionClass.Base, Lockable.LockableItem):
object-specific implementation. By default, PUT requests
fail with a 405 (Method Not Allowed)."""
self.dav__init(REQUEST, RESPONSE)
raise 'Method Not Allowed', 'Method not supported for this resource.'
raise MethodNotAllowed, 'Method not supported for this resource.'
OPTIONS__roles__=None
def OPTIONS(self, REQUEST, RESPONSE):
......@@ -202,7 +214,7 @@ class Resource(ExtensionClass.Base, Lockable.LockableItem):
is not often possible to reproduce the HTTP request verbatim
from within the Zope environment."""
self.dav__init(REQUEST, RESPONSE)
raise 'Method Not Allowed', 'Method not supported for this resource.'
raise MethodNotAllowed, 'Method not supported for this resource.'
def DELETE(self, REQUEST, RESPONSE):
"""Delete a resource. For non-collection resources, DELETE may
......@@ -219,7 +231,7 @@ class Resource(ExtensionClass.Base, Lockable.LockableItem):
else:
# We're locked, and no if header was passed in, so
# the client doesn't own a lock.
raise 'Locked', 'Resource is locked.'
raise Locked, 'Resource is locked.'
elif WriteLockInterface.isImplementedBy(parent) and \
parent.wl_isLocked():
if ifhdr:
......@@ -227,7 +239,7 @@ class Resource(ExtensionClass.Base, Lockable.LockableItem):
else:
# Our parent is locked, and no If header was passed in.
# When a parent is locked, members cannot be removed
raise 'Precondition Failed', 'Resource is locked, and no '\
raise PreconditionFailed, 'Resource is locked, and no '\
'condition was passed in.'
# Either we're not locked, or a succesful lock token was submitted
# so we can delete the lock now.
......@@ -255,7 +267,7 @@ class Resource(ExtensionClass.Base, Lockable.LockableItem):
"""Set and/or remove properties defined on the resource."""
self.dav__init(REQUEST, RESPONSE)
if not hasattr(aq_base(self), 'propertysheets'):
raise 'Method Not Allowed', (
raise MethodNotAllowed, (
'Method not supported for this resource.')
# Lock checking
ifhdr = REQUEST.get_header('If', '')
......@@ -263,7 +275,7 @@ class Resource(ExtensionClass.Base, Lockable.LockableItem):
if ifhdr:
self.dav__simpleifhandler(REQUEST, RESPONSE, 'PROPPATCH')
else:
raise 'Locked', 'Resource is locked.'
raise Locked, 'Resource is locked.'
cmd=davcmds.PropPatch(REQUEST)
result=cmd.apply(self)
......@@ -276,7 +288,7 @@ class Resource(ExtensionClass.Base, Lockable.LockableItem):
"""Create a new collection resource. If called on an existing
resource, MKCOL must fail with 405 (Method Not Allowed)."""
self.dav__init(REQUEST, RESPONSE)
raise 'Method Not Allowed', 'The resource already exists.'
raise MethodNotAllowed, 'The resource already exists.'
COPY__roles__=('Anonymous',)
def COPY(self, REQUEST, RESPONSE):
......@@ -288,48 +300,52 @@ class Resource(ExtensionClass.Base, Lockable.LockableItem):
self.dav__init(REQUEST, RESPONSE)
if not hasattr(aq_base(self), 'cb_isCopyable') or \
not self.cb_isCopyable():
raise 'Method Not Allowed', 'This object may not be copied.'
raise MethodNotAllowed, 'This object may not be copied.'
depth=REQUEST.get_header('Depth', 'infinity')
if not depth in ('0', 'infinity'):
raise 'Bad Request', 'Invalid Depth header.'
raise BadRequest, 'Invalid Depth header.'
dest=REQUEST.get_header('Destination', '')
while dest and dest[-1]=='/':
dest=dest[:-1]
if not dest:
raise 'Bad Request', 'Invalid Destination header.'
raise BadRequest, 'Invalid Destination header.'
try: path = REQUEST.physicalPathFromURL(dest)
except ValueError:
raise 'Bad Request', 'Invalid Destination header'
raise BadRequest, 'Invalid Destination header'
name = path.pop()
parent_path = '/'.join(path)
oflag=REQUEST.get_header('Overwrite', 'F').upper()
if not oflag in ('T', 'F'):
raise 'Bad Request', 'Invalid Overwrite header.'
raise BadRequest, 'Invalid Overwrite header.'
try: parent=self.restrictedTraverse(path)
except ValueError:
raise 'Conflict', 'Attempt to copy to an unknown namespace.'
except 'Not Found':
raise 'Conflict', 'Object ancestors must already exist.'
raise Conflict, 'Attempt to copy to an unknown namespace.'
except NotFound:
raise Conflict, 'Object ancestors must already exist.'
except:
t, v, tb=sys.exc_info()
raise t, v
if hasattr(parent, '__null_resource__'):
raise 'Conflict', 'Object ancestors must already exist.'
raise Conflict, 'Object ancestors must already exist.'
existing=hasattr(aq_base(parent), name)
if existing and oflag=='F':
raise 'Precondition Failed', 'Destination resource exists.'
try: parent._checkId(name, allow_dup=1)
except: raise 'Forbidden', sys.exc_info()[1]
try: parent._verifyObjectPaste(self)
raise PreconditionFailed, 'Destination resource exists.'
try:
parent._checkId(name, allow_dup=1)
except:
raise Forbidden, sys.exc_info()[1]
try:
parent._verifyObjectPaste(self)
except Unauthorized:
raise
except: raise 'Forbidden', sys.exc_info()[1]
except:
raise Forbidden, sys.exc_info()[1]
# Now check locks. The If header on a copy only cares about the
# lock on the destination, so we need to check out the destinations
......@@ -343,16 +359,17 @@ class Resource(ExtensionClass.Base, Lockable.LockableItem):
if ifhdr:
itrue = destob.dav__simpleifhandler(
REQUEST, RESPONSE, 'COPY', refresh=1)
if not itrue: raise 'Preconditon Failed'
if not itrue:
raise PreconditonFailed
else:
raise 'Locked', 'Destination is locked.'
raise Locked, 'Destination is locked.'
elif WriteLockInterface.isImplementedBy(parent) and \
parent.wl_isLocked():
if ifhdr:
parent.dav__simpleifhandler(REQUEST, RESPONSE, 'COPY',
refresh=1)
else:
raise 'Locked', 'Destination is locked.'
raise Locked, 'Destination is locked.'
ob=self._getCopy(parent)
ob.manage_afterClone(ob)
......@@ -385,13 +402,13 @@ class Resource(ExtensionClass.Base, Lockable.LockableItem):
self.dav__validate(self, 'DELETE', REQUEST)
if not hasattr(aq_base(self), 'cb_isMoveable') or \
not self.cb_isMoveable():
raise 'Method Not Allowed', 'This object may not be moved.'
raise MethodNotAllowed, 'This object may not be moved.'
dest=REQUEST.get_header('Destination', '')
try: path = REQUEST.physicalPathFromURL(dest)
except ValueError:
raise 'Bad Request', 'No destination given'
raise BadRequest, 'No destination given'
flag=REQUEST.get_header('Overwrite', 'F')
flag=flag.upper()
......@@ -401,23 +418,27 @@ class Resource(ExtensionClass.Base, Lockable.LockableItem):
try: parent = self.restrictedTraverse(path)
except ValueError:
raise 'Conflict', 'Attempt to move to an unknown namespace.'
raise Conflict, 'Attempt to move to an unknown namespace.'
except 'Not Found':
raise 'Conflict', 'The resource %s must exist.' % parent_path
raise Conflict, 'The resource %s must exist.' % parent_path
except:
t, v, tb=sys.exc_info()
raise t, v
if hasattr(parent, '__null_resource__'):
raise 'Conflict', 'The resource %s must exist.' % parent_path
raise Conflict, 'The resource %s must exist.' % parent_path
existing=hasattr(aq_base(parent), name)
if existing and flag=='F':
raise 'Precondition Failed', 'Resource %s exists.' % dest
try: parent._checkId(name, allow_dup=1)
raise PreconditionFailed, 'Resource %s exists.' % dest
try:
parent._checkId(name, allow_dup=1)
except:
raise Forbidden, sys.exc_info()[1]
try:
parent._verifyObjectPaste(self)
except Unauthorized:
raise
except:
raise 'Forbidden', sys.exc_info()[1]
try: parent._verifyObjectPaste(self)
except Unauthorized: raise
except: raise 'Forbidden', sys.exc_info()[1]
raise Forbidden, sys.exc_info()[1]
# Now check locks. Since we're affecting the resource that we're
# moving as well as the destination, we have to check both.
......@@ -430,9 +451,10 @@ class Resource(ExtensionClass.Base, Lockable.LockableItem):
if ifhdr:
itrue = destob.dav__simpleifhandler(
REQUEST, RESPONSE, 'MOVE', url=dest, refresh=1)
if not itrue: raise 'Precondition Failed'
if not itrue:
raise PreconditionFailed
else:
raise 'Locked', 'Destination is locked.'
raise Locked, 'Destination is locked.'
elif WriteLockInterface.isImplementedBy(parent) and \
parent.wl_isLocked():
# There's no existing object in the destination folder, so
......@@ -441,17 +463,19 @@ class Resource(ExtensionClass.Base, Lockable.LockableItem):
if ifhdr:
itrue = parent.dav__simpleifhandler(REQUEST, RESPONSE, 'MOVE',
col=1, url=dest, refresh=1)
if not itrue: raise 'Precondition Failed', 'Condition failed.'
if not itrue:
raise PreconditionFailed, 'Condition failed.'
else:
raise 'Locked', 'Destination is locked.'
raise Locked, 'Destination is locked.'
if Lockable.wl_isLocked(self):
# Lastly, we check ourselves
if ifhdr:
itrue = self.dav__simpleifhandler(REQUEST, RESPONSE, 'MOVE',
refresh=1)
if not itrue: raise 'Precondition Failed', 'Condition failed.'
if not itrue:
raise PreconditionFailed, 'Condition failed.'
else:
raise 'Precondition Failed', 'Source is locked and no '\
raise PreconditionFailed, 'Source is locked and no '\
'condition was passed in.'
ob=aq_base(self._getCopy(parent))
......@@ -507,7 +531,7 @@ class Resource(ExtensionClass.Base, Lockable.LockableItem):
else:
# There's no body, so this likely to be a refresh request
if not ifhdr:
raise 'Precondition Failed', 'If Header Missing'
raise PreconditionFailed, 'If Header Missing'
taglist = IfParser(ifhdr)
found = 0
for tag in taglist:
......
"""HTTP 1.1 / WebDAV client library."""
__version__='$Revision: 1.20 $'[11:-2]
__version__='$Revision: 1.21 $'[11:-2]
import sys, os, time, types,re
import socket, httplib, mimetools
......@@ -13,7 +13,8 @@ from random import random
from urllib import quote
class NotAvailable(Exception):
pass
class HTTP(httplib.HTTP):
# A revised version of the HTTP class that can do basic
......@@ -124,7 +125,7 @@ class Resource:
data=h.getfile().read()
h.close()
except:
raise 'NotAvailable', sys.exc_value
raise NotAvailable, sys.exc_value
return http_response(ver, code, msg, hdrs, data)
# HTTP methods
......
......@@ -13,7 +13,7 @@
"""Commonly used functions for WebDAV support modules."""
__version__='$Revision: 1.17 $'[11:-2]
__version__='$Revision: 1.18 $'[11:-2]
import time, urllib, re
from App.Common import iso8601_date, rfc850_date, rfc1123_date
......@@ -22,6 +22,21 @@ import random
_randGen = random.Random(time.time())
class WebDAVException(Exception):
pass
class Locked(WebDAVException):
pass
class PreconditionFailed(WebDAVException):
pass
class Conflict(WebDAVException):
pass
class UnsupportedMediaType(WebDAVException):
pass
def absattr(attr):
if callable(attr):
return attr()
......
......@@ -11,9 +11,10 @@
#
##############################################################################
"""WebDAV xml request objects."""
"""WebDAV xml request objects.
__version__='$Revision: 1.21 $'[11:-2]
$Id: davcmds.py,v 1.22 2003/11/18 13:17:20 tseaver Exp $
"""
import sys, os
from common import absattr, aq_base, urlfix, urlbase
......@@ -25,7 +26,9 @@ from xmltools import XmlParser
from cStringIO import StringIO
from urllib import quote
from AccessControl import getSecurityManager
from zExceptions import BadRequest, Forbidden
from common import isDavCollection
from common import PreconditionFailed
def safe_quote(url, mark=r'%'):
if url.find(mark) > -1:
......@@ -58,14 +61,18 @@ class PropFind:
def parse(self, request, dav='DAV:'):
self.depth=request.get_header('Depth', 'infinity')
if not (self.depth in ('0','1','infinity')):
raise 'Bad Request', 'Invalid Depth header.'
raise BadRequest, 'Invalid Depth header.'
body=request.get('BODY', '')
self.allprop=(not len(body))
if not body: return
try: root=XmlParser().parse(body)
except: raise 'Bad Request', sys.exc_info()[1]
if not body:
return
try:
root=XmlParser().parse(body)
except:
raise BadRequest, sys.exc_info()[1]
e=root.elements('propfind', ns=dav)
if not e: raise 'Bad Request', 'Invalid xml request.'
if not e:
raise BadRequest, 'Invalid xml request.'
e=e[0]
if e.elements('allprop', ns=dav):
self.allprop=1
......@@ -74,13 +81,14 @@ class PropFind:
self.propname=1
return
prop=e.elements('prop', ns=dav)
if not prop: raise 'Bad Request', 'Invalid xml request.'
if not prop:
raise BadRequest, 'Invalid xml request.'
prop=prop[0]
for val in prop.elements():
self.propnames.append((val.name(), val.namespace()))
if (not self.allprop) and (not self.propname) and \
(not self.propnames):
raise 'Bad Request', 'Invalid xml request.'
raise BadRequest, 'Invalid xml request.'
return
def apply(self, obj, url=None, depth=0, result=None, top=1):
......@@ -126,7 +134,8 @@ class PropFind:
code='404 Not Found'
if not rdict.has_key(code):
rdict[code]=[prop]
else: rdict[code].append(prop)
else:
rdict[code].append(prop)
keys=rdict.keys()
keys.sort()
for key in keys:
......@@ -138,22 +147,27 @@ class PropFind:
' <d:status>HTTP/1.1 %s</d:status>\n' \
'</d:propstat>\n' % key
)
else: raise 'Bad Request', 'Invalid request'
else:
raise BadRequest, 'Invalid request'
result.write('</d:response>\n')
if depth in ('1', 'infinity') and iscol:
for ob in obj.listDAVObjects():
if hasattr(ob,"meta_type"):
if ob.meta_type=="Broken Because Product is Gone": continue
if ob.meta_type=="Broken Because Product is Gone":
continue
dflag=hasattr(ob, '_p_changed') and (ob._p_changed == None)
if hasattr(ob, '__locknull_resource__'):
# Do nothing, a null resource shouldn't show up to DAV
if dflag: ob._p_deactivate()
if dflag:
ob._p_deactivate()
elif hasattr(ob, '__dav_resource__'):
uri=os.path.join(url, absattr(ob.id))
depth=depth=='infinity' and depth or 0
self.apply(ob, uri, depth, result, top=0)
if dflag: ob._p_deactivate()
if not top: return result
if dflag:
ob._p_deactivate()
if not top:
return result
result.write('</d:multistatus>')
return result.getvalue()
......@@ -169,16 +183,20 @@ class PropPatch:
def parse(self, request, dav='DAV:'):
body=request.get('BODY', '')
try: root=XmlParser().parse(body)
except: raise 'Bad Request', sys.exc_info()[1]
try:
root=XmlParser().parse(body)
except:
raise BadRequest, sys.exc_info()[1]
vals=self.values
e=root.elements('propertyupdate', ns=dav)
if not e: raise 'Bad Request', 'Invalid xml request.'
if not e:
raise BadRequest, 'Invalid xml request.'
e=e[0]
for ob in e.elements():
if ob.name()=='set' and ob.namespace()==dav:
proptag=ob.elements('prop', ns=dav)
if not proptag: raise 'Bad Request', 'Invalid xml request.'
if not proptag:
raise BadRequest, 'Invalid xml request.'
proptag=proptag[0]
for prop in proptag.elements():
# We have to ensure that all tag attrs (including
......@@ -202,7 +220,8 @@ class PropPatch:
vals.append(item)
if ob.name()=='remove' and ob.namespace()==dav:
proptag=ob.elements('prop', ns=dav)
if not proptag: raise 'Bad Request', 'Invalid xml request.'
if not proptag:
raise BadRequest, 'Invalid xml request.'
proptag=proptag[0]
for prop in proptag.elements():
item=(prop.name(), prop.namespace())
......@@ -229,12 +248,14 @@ class PropPatch:
propset=propsets.get(ns)
propdict=propset._propdict()
if propset.hasProperty(name):
try: propset._updateProperty(name, val, meta=md)
try:
propset._updateProperty(name, val, meta=md)
except:
errors.append(str(sys.exc_info()[1]))
status='409 Conflict'
else:
try: propset._setProperty(name, val, meta=md)
try:
propset._setProperty(name, val, meta=md)
except:
errors.append(str(sys.exc_info()[1]))
status='409 Conflict'
......@@ -246,11 +267,13 @@ class PropPatch:
# according to RFC 2518
status='200 OK'
else:
try: propset._delProperty(name)
try:
propset._delProperty(name)
except:
errors.append('%s cannot be deleted.' % name)
status='409 Conflict'
if result != '200 OK': abort=1
if result != '200 OK':
abort = 1
result.write('<d:propstat xmlns:n="%s">\n' \
' <d:prop>\n' \
' <n:%s/>\n' \
......@@ -264,7 +287,8 @@ class PropPatch:
'</d:response>\n' \
'</d:multistatus>' % errmsg)
result=result.getvalue()
if not errors: return result
if not errors:
return result
# This is lame, but I cant find a way to keep ZPublisher
# from sticking a traceback into my xml response :(
get_transaction().abort()
......@@ -325,14 +349,16 @@ class Lock:
url = urlfix(self.request['URL'], 'LOCK')
url = urlbase(url)
iscol = isDavCollection(obj)
if iscol and url[-1] != '/': url = url + '/'
if iscol and url[-1] != '/':
url = url + '/'
errmsg = None
lock = None
try:
lock = LockItem(creator, self.owner, depth, self.timeout,
self.type, self.scope, token)
if token is None: token = lock.getLockToken()
if token is None:
token = lock.getLockToken()
except ValueError, valerrors:
errmsg = "412 Precondition Failed"
......@@ -381,7 +407,8 @@ class Lock:
uri = os.path.join(url, absattr(ob.id))
self.apply(ob, creator, depth, token, result,
uri, top=0)
if not top: return token, result
if not top:
return token, result
if result.getvalue():
# One or more subitems probably failed, so close the multistatus
# element and clear out all succesful locks
......@@ -399,7 +426,8 @@ class Unlock:
url = urlfix(url, 'UNLOCK')
url = urlbase(url)
iscol = isDavCollection(obj)
if iscol and url[-1] != '/': url = url + '/'
if iscol and url[-1] != '/':
url = url + '/'
errmsg = None
islockable = WriteLockInterface.isImplementedBy(obj)
......@@ -407,7 +435,8 @@ class Unlock:
if islockable and obj.wl_hasLock(token):
method = getattr(obj, 'wl_delLock')
vld = getSecurityManager().validate(None,obj,'wl_delLock',method)
if vld: obj.wl_delLock(token)
if vld:
obj.wl_delLock(token)
else:
errmsg = "403 Forbidden"
elif not islockable:
......@@ -415,13 +444,16 @@ class Unlock:
# to a top level object. Otherwise, we're descending a tree
# which may contain many objects that don't implement locking,
# so we just want to avoid them
if top: errmsg = "405 Method Not Allowed"
if top:
errmsg = "405 Method Not Allowed"
if errmsg:
if top and (not iscol):
# We don't need to raise multistatus errors
if errmsg[:3] == '403': raise "Forbidden"
else: raise "Precondition Failed"
if errmsg[:3] == '403':
raise Forbidden
else:
raise PreconditionFailed
elif not result.getvalue():
# We haven't had any errors yet, so our result is empty
# and we need to set up the XML header
......@@ -437,7 +469,8 @@ class Unlock:
WriteLockInterface.isImplementedBy(ob):
uri = os.path.join(url, absattr(ob.id))
self.apply(ob, token, uri, result, top=0)
if not top: return result
if not top:
return result
if result.getvalue():
# One or more subitems probably failed, so close the multistatus
# element and clear out all succesful unlocks
......@@ -490,8 +523,10 @@ class DeleteCollection:
if hasattr(ob, '__dav_resource__'):
uri = os.path.join(url, absattr(ob.id))
self.apply(ob, token, user, uri, result, top=0)
if dflag: ob._p_deactivate()
if not top: return result
if dflag:
ob._p_deactivate()
if not top:
return result
if result.getvalue():
# One or more subitems can't be delted, so close the multistatus
# element
......
......@@ -15,7 +15,25 @@
These exceptions are so general purpose that they don't belong in Zope
application-specific packages.
$Id: __init__.py,v 1.4 2002/08/14 22:12:06 mj Exp $
$Id: __init__.py,v 1.5 2003/11/18 13:17:21 tseaver Exp $
"""
from unauthorized import Unauthorized
class BadRequest(Exception):
pass
class InternalError(Exception):
pass
class NotFound(Exception):
pass
class Forbidden(Exception):
pass
class MethodNotAllowed(Exception):
pass
class Redirect(Exception):
pass
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment