Package ZenRelations :: Module ZItem
[hide private]
[frames] | no frames]

Source Code for Module ZenRelations.ZItem

  1  ########################################################################### 
  2  # 
  3  # This program is part of Zenoss Core, an open source monitoring platform. 
  4  # Copyright (C) 2007, Zenoss Inc. 
  5  # 
  6  # This program is free software; you can redistribute it and/or modify it 
  7  # under the terms of the GNU General Public License version 2 as published by 
  8  # the Free Software Foundation. 
  9  # 
 10  # For complete information please visit: http://www.zenoss.com/oss/ 
 11  # 
 12  ########################################################################### 
 13  import marshal, re, sys, time 
 14   
 15  import Globals, Acquisition 
 16  import App 
 17  import App.Management 
 18  import AccessControl 
 19  import AccessControl.Role, AccessControl.Owned, App.Common 
 20  from ExtensionClass import Base 
 21  from ComputedAttribute import ComputedAttribute 
 22  from AccessControl import getSecurityManager, Unauthorized 
 23  from AccessControl.ZopeSecurityPolicy import getRoles 
 24  from Acquisition import aq_base, aq_parent, aq_inner 
 25  from DocumentTemplate.html_quote import html_quote 
 26  from DocumentTemplate.ustr import ustr 
 27  from zExceptions.ExceptionFormatter import format_exception 
 28  from zExceptions import Redirect 
 29   
 30  from OFS.CopySupport import CopySource 
 31  from OFS.Traversable import Traversable 
 32   
 33  from Products.ZenUtils.Utils import unused 
 34   
 35   
 36  HTML=Globals.HTML 
 37   
 38  import logging 
 39  logger = logging.getLogger() 
 40   
41 -class ZItem(Base, CopySource, App.Management.Tabs, Traversable, 42 AccessControl.Owned.Owned, 43 ):
44 45 46 """A common base class for simple, non-container objects.""" 47 48 isPrincipiaFolderish=0 49 isTopLevelPrincipiaApplicationObject=0 50
51 - def manage_afterAdd(self, item, container):
52 pass
53
54 - def manage_beforeDelete(self, item, container):
55 pass
56
57 - def manage_afterClone(self, item):
58 pass
59 60 # Direct use of the 'id' attribute is deprecated - use getId() 61 id='' 62 63 getId__roles__=None
64 - def getId(self):
65 """Return the id of the object as a string. 66 67 This method should be used in preference to accessing an id attribute 68 of an object directly. The getId method is public. 69 """ 70 name=getattr(self, 'id', None) 71 if callable(name): 72 return name() 73 if name is not None: 74 return name 75 if hasattr(self, '__name__'): 76 return self.__name__ 77 raise AttributeError, 'This object has no id'
78 79 # Alias id to __name__, which will make tracebacks a good bit nicer: 80 __name__=ComputedAttribute(lambda self: self.getId()) 81 82 # Name, relative to SOFTWARE_URL of icon used to display item 83 # in folder listings. 84 icon='' 85 86 # Meta type used for selecting all objects of a given type. 87 meta_type='simple item' 88 89 # Default title. 90 title='' 91 92 # Default propertysheet info: 93 __propsets__=() 94 95 manage_options=( 96 AccessControl.Owned.Owned.manage_options 97 ) 98 99 # Attributes that must be acquired 100 REQUEST=Acquisition.Acquired 101 102 # Allow (reluctantly) access to unprotected attributes 103 __allow_access_to_unprotected_subobjects__=1 104
105 - def title_or_id(self):
106 """Return the title if it is not blank and the id otherwise. 107 """ 108 title=self.title 109 if callable(title): 110 title=title() 111 if title: return title 112 return self.getId()
113
114 - def title_and_id(self):
115 """Return the title if it is not blank and the id otherwise. 116 117 If the title is not blank, then the id is included in parens. 118 """ 119 title=self.title 120 if callable(title): 121 title=title() 122 id = self.getId() 123 return title and ("%s (%s)" % (title,id)) or id
124
125 - def this(self):
126 # Handy way to talk to ourselves in document templates. 127 return self
128
129 - def tpURL(self):
130 # My URL as used by tree tag 131 return self.getId()
132
133 - def tpValues(self):
134 # My sub-objects as used by the tree tag 135 return ()
136 137 _manage_editedDialog=Globals.DTMLFile('dtml/editedDialog', globals())
138 - def manage_editedDialog(self, REQUEST, **args):
139 return apply(self._manage_editedDialog,(self, REQUEST), args)
140
141 - def raise_standardErrorMessage( 142 self, client=None, REQUEST={}, 143 error_type=None, error_value=None, tb=None, 144 error_tb=None, error_message='', 145 tagSearch=re.compile(r'[a-zA-Z]>').search, 146 error_log_url=''):
147 148 try: 149 if error_type is None: error_type =sys.exc_info()[0] 150 if error_value is None: error_value=sys.exc_info()[1] 151 152 # allow for a few different traceback options 153 if tb is None and error_tb is None: 154 tb=sys.exc_info()[2] 155 if type(tb) is not type('') and (error_tb is None): 156 error_tb = pretty_tb(error_type, error_value, tb) 157 elif type(tb) is type('') and not error_tb: 158 error_tb = tb 159 160 # turn error_type into a string 161 if hasattr(error_type, '__name__'): 162 error_type=error_type.__name__ 163 164 if hasattr(self, '_v_eek'): 165 # Stop if there is recursion. 166 raise error_type, error_value, tb 167 self._v_eek=1 168 169 if str(error_type).lower() in ('redirect',): 170 raise error_type, error_value, tb 171 172 if not error_message: 173 try: 174 s = ustr(error_value) 175 except: 176 s = error_value 177 try: 178 match = tagSearch(s) 179 except TypeError: 180 match = None 181 if match is not None: 182 error_message=error_value 183 184 if client is None: client=self 185 if not REQUEST: REQUEST=self.aq_acquire('REQUEST') 186 187 try: 188 if hasattr(client, 'standard_error_message'): 189 s=client.standard_error_message 190 else: 191 client = client.aq_parent 192 s=client.standard_error_message 193 kwargs = {'error_type': error_type, 194 'error_value': error_value, 195 'error_tb': error_tb, 196 'error_traceback': error_tb, 197 'error_message': error_message, 198 'error_log_url': error_log_url} 199 200 if getattr(aq_base(s),'isDocTemp',0): 201 v = s(client, REQUEST, **kwargs) 202 elif callable(s): 203 v = s(**kwargs) 204 else: 205 __pychecker__='self="s"' 206 v = HTML.__call__(s, client, REQUEST, **kwargs) 207 except: 208 logger.error( 209 'Exception while rendering an error message', 210 exc_info=True 211 ) 212 try: 213 strv = str(error_value) 214 except: 215 strv = ('<unprintable %s object>' % 216 str(type(error_value).__name__)) 217 v = strv + ( 218 (" (Also, the following error occurred while attempting " 219 "to render the standard error message, please see the " 220 "event log for full details: %s)")%( 221 html_quote(sys.exc_info()[1]), 222 )) 223 raise error_type, v, tb 224 finally: 225 if hasattr(self, '_v_eek'): del self._v_eek 226 tb=None
227
228 - def manage(self, URL1):
229 """ 230 """ 231 raise Redirect, "%s/manage_main" % URL1
232 233 # This keeps simple items from acquiring their parents 234 # objectValues, etc., when used in simple tree tags.
235 - def objectValues(self, spec=None):
236 unused(spec) 237 return ()
238 objectIds=objectItems=objectValues 239 240 # FTP support methods 241
242 - def manage_FTPstat(self,REQUEST):
243 """Psuedo stat, used by FTP for directory listings. 244 """ 245 from AccessControl.User import nobody 246 mode=0100000 247 248 if (hasattr(aq_base(self),'manage_FTPget')): 249 try: 250 if getSecurityManager().validate( 251 None, self, 'manage_FTPget', self.manage_FTPget): 252 mode=mode | 0440 253 except Unauthorized: 254 pass 255 256 if nobody.allowed( 257 self.manage_FTPget, 258 getRoles(self, 'manage_FTPget', self.manage_FTPget, ()), 259 ): 260 mode=mode | 0004 261 262 # check write permissions 263 if hasattr(aq_base(self),'PUT'): 264 try: 265 if getSecurityManager().validate(None, self, 'PUT', self.PUT): 266 mode=mode | 0220 267 except Unauthorized: 268 pass 269 270 if nobody.allowed( 271 self.PUT, 272 getRoles(self, 'PUT', self.PUT, ()), 273 ): 274 mode=mode | 0002 275 276 # get size 277 if hasattr(aq_base(self), 'get_size'): 278 size=self.get_size() 279 elif hasattr(aq_base(self),'manage_FTPget'): 280 size=len(self.manage_FTPget()) 281 else: 282 size=0 283 # get modification time 284 if hasattr(aq_base(self), 'bobobase_modification_time'): 285 mtime=self.bobobase_modification_time().timeTime() 286 else: 287 mtime=time.time() 288 # get owner and group 289 owner=group='Zope' 290 if hasattr(aq_base(self), 'get_local_roles'): 291 for user, roles in self.get_local_roles(): 292 if 'Owner' in roles: 293 owner=user 294 break 295 return marshal.dumps((mode,0,0,1,owner,group,size,mtime,mtime,mtime))
296
297 - def manage_FTPlist(self,REQUEST):
298 """Directory listing for FTP. 299 300 In the case of non-Foldoid objects, the listing should contain one 301 object, the object itself. 302 """ 303 # check to see if we are being acquiring or not 304 ob=self 305 while 1: 306 if App.Common.is_acquired(ob): 307 raise ValueError('FTP List not supported on acquired objects') 308 if not hasattr(ob,'aq_parent'): 309 break 310 ob=ob.aq_parent 311 312 stat=marshal.loads(self.manage_FTPstat(REQUEST)) 313 id = self.getId() 314 return marshal.dumps((id,stat))
315
316 - def __len__(self):
317 return 1
318
319 - def __repr__(self):
320 """Show the physical path of the object and its context if available. 321 """ 322 try: 323 path = '/'.join(self.getPhysicalPath()) 324 except: 325 return Base.__repr__(self) 326 context_path = None 327 context = aq_parent(self) 328 container = aq_parent(aq_inner(self)) 329 if aq_base(context) is not aq_base(container): 330 try: 331 context_path = '/'.join(context.getPhysicalPath()) 332 except: 333 context_path = None 334 res = '<%s' % self.__class__.__name__ 335 res += ' at %s' % path 336 if context_path: 337 res += ' used for %s' % context_path 338 res += '>' 339 return res
340
341 -def pretty_tb(t, v, tb, as_html=1):
342 tb = format_exception(t, v, tb, as_html=as_html) 343 tb = '\n'.join(tb) 344 return tb
345