예제 #1
0
def registerIcon(klass, iconspec, _prefix=None):
    modname = klass.__module__
    pid = modname[1]
    name = path.split(iconspec)[1]
    klass.icon = 'misc_/%s/%s' % (pid, name)
    icon = Globals.ImageFile(iconspec, _prefix)
    icon.__roles__ = None
    if not hasattr(OFS.misc_.misc_, pid):
        setattr(OFS.misc_.misc_, pid, OFS.misc_.Misc_(pid, {}))
    getattr(OFS.misc_.misc_, pid)[name] = icon
예제 #2
0
파일: register.py 프로젝트: bendavis78/zope
    if constructors:
        pr = PermissionRole(permission)
        for c in constructors:
            name = c.__name__
            setattr(PortalFolder, name, c)
            setattr(PortalFolder, '%s__roles__' % name, pr)

    PortalFolder.content_meta_types = PortalFolder.content_meta_types + (
        {
            'name': meta_type,
            'action': action,
            'permission': permission
        }, )

    if icon:
        path = 'misc_/CMF/%s' % urllib.quote(meta_type)
        instance_class.icon = path
        if not hasattr(OFS.misc_.misc_, 'CMF'):
            OFS.misc_.misc_.CMF = OFS.misc_.Misc_('CMF', {})
        if type(icon) == type(''):
            try:
                if productGlobals is None:
                    productGlobals = globals()
                OFS.misc_.misc_.CMF[meta_type] = Globals.ImageFile(
                    icon, productGlobals)
            except IOError:
                pass
        else:
            OFS.misc_.misc_.CMF[meta_type] = icon
예제 #3
0
    def registerClass(self,
                      instance_class=None,
                      meta_type='',
                      permission=None,
                      constructors=(),
                      icon=None,
                      permissions=None,
                      legacy=(),
                      visibility="Global",
                      interfaces=_marker,
                      container_filter=None):
        """Register a constructor

        Keyword arguments are used to provide meta data:

        instance_class -- The class of the object that will be created.

          This is not currently used, but may be used in the future to
          increase object mobility.

        meta_type -- The kind of object being created
           This appears in add lists.  If not specified, then the class
           meta_type will be used.

        permission -- The permission name for the constructors.
           If not specified, then a permission name based on the
           meta type will be used.

        constructors -- A list of constructor methods
          A method can me a callable object with a __name__
          attribute giving the name the method should have in the
          product, or the method may be a tuple consisting of a
          name and a callable object.  The method must be picklable.

          The first method will be used as the initial method called
          when creating an object.

        icon -- The name of an image file in the package to
                be used for instances. Note that the class icon
                attribute will be set automagically if an icon is
                provided.

        permissions -- Additional permissions to be registered
           If not provided, then permissions defined in the
           class will be registered.

        legacy -- A list of legacy methods to be added to ObjectManager
                  for backward compatibility

        visibility -- "Global" if the object is globally visible, None else

        interfaces -- a list of the interfaces the object supports

        container_filter -- function that is called with an ObjectManager
           object as the only parameter, which should return a true object
           if the object is happy to be created in that container. The
           filter is called before showing ObjectManager's Add list,
           and before pasting (after object copy or cut), but not
           before calling an object's constructor.

        """
        pack = self.__pack
        initial = constructors[0]
        productObject = self.__prod
        pid = productObject.id

        if icon and instance_class is not None:
            setattr(instance_class, 'icon',
                    'misc_/%s/%s' % (pid, os.path.split(icon)[1]))

        if permissions:
            if isinstance(permissions, basestring):  # You goofed it!
                raise TypeError, ('Product context permissions should be a '
                                  'list of permissions not a string',
                                  permissions)
            for p in permissions:
                if isinstance(p, tuple):
                    p, default = p
                    AccessControl.Permission.registerPermissions(
                        ((p, (), default), ))
                else:
                    AccessControl.Permission.registerPermissions(((p, ()), ))

        ############################################################
        # Constructor permission setup
        if permission is None:
            permission = "Add %ss" % (meta_type or instance_class.meta_type)

        if isinstance(permission, tuple):
            permission, default = permission
        else:
            default = ('Manager', )

        pr = PermissionRole(permission, default)
        AccessControl.Permission.registerPermissions(
            ((permission, (), default), ))
        ############################################################

        OM = OFS.ObjectManager.ObjectManager

        for method in legacy:
            if isinstance(method, tuple):
                name, method = method
                aliased = 1
            else:
                name = method.__name__
                aliased = 0
            if not OM.__dict__.has_key(name):
                setattr(OM, name, method)
                setattr(OM, name + '__roles__', pr)
                if aliased:
                    # Set the unaliased method name and its roles
                    # to avoid security holes.  XXX: All "legacy"
                    # methods need to be eliminated.
                    setattr(OM, method.__name__, method)
                    setattr(OM, method.__name__ + '__roles__', pr)

        if isinstance(initial, tuple):
            name, initial = initial
        else:
            name = initial.__name__

        fd = getattr(pack, '__FactoryDispatcher__', None)
        if fd is None:

            class __FactoryDispatcher__(FactoryDispatcher):
                "Factory Dispatcher for a Specific Product"

            fd = pack.__FactoryDispatcher__ = __FactoryDispatcher__

        if not hasattr(pack, '_m'):
            pack._m = AttrDict(fd)

        m = pack._m

        if interfaces is _marker:
            if instance_class is None:
                interfaces = ()
            else:
                interfaces = tuple(implementedBy(instance_class))
                # BBB: Will be removed in Zope 2.11.
                interfaces += tuple(
                    instancesOfObjectImplements(instance_class))

        Products.meta_types = Products.meta_types + (
            {
                'name': meta_type or instance_class.meta_type,
                # 'action': The action in the add drop down in the ZMI. This is
                #           currently also required by the _verifyObjectPaste
                #           method of CopyContainers like Folders.
                'action': ('manage_addProduct/%s/%s' % (pid, name)),
                # 'product': Used by ProductRegistry for TTW products and by
                #            OFS.Application for refreshing products.
                #            This key might not be available.
                'product': pid,
                # 'permission': Guards the add action.
                'permission': permission,
                # 'visibility': A silly name. Doesn't have much to do with
                #               visibility. Allowed values: 'Global', None
                'visibility': visibility,
                # 'interfaces': A tuple of oldstyle and/or newstyle interfaces.
                'interfaces': interfaces,
                'instance': instance_class,
                'container_filter': container_filter
            }, )

        m[name] = initial
        m[name + '__roles__'] = pr

        for method in constructors[1:]:
            if isinstance(method, tuple):
                name, method = method
            else:
                name = os.path.split(method.__name__)[-1]
            if not productObject.__dict__.has_key(name):
                m[name] = method
                m[name + '__roles__'] = pr

        if icon:
            name = os.path.split(icon)[1]
            icon = Globals.ImageFile(icon, self.__pack.__dict__)
            icon.__roles__ = None
            if not hasattr(OFS.misc_.misc_, pid):
                setattr(OFS.misc_.misc_, pid, OFS.misc_.Misc_(pid, {}))
            getattr(OFS.misc_.misc_, pid)[name] = icon
예제 #4
0
class CacheManager:
    """Cache management mix-in
    """
    _cache_age = 60
    _vcache_age = 60
    _history_length = 3600  # Seconds

    manage_cacheParameters = Globals.DTMLFile('dtml/cacheParameters',
                                              globals())
    manage_cacheGC = Globals.DTMLFile('dtml/cacheGC', globals())

    transparent_bar = Globals.ImageFile('www/transparent_bar.gif', globals())
    store_bar = Globals.ImageFile('www/store_bar.gif', globals())
    load_bar = Globals.ImageFile('www/load_bar.gif', globals())

    def _getDB(self):
        return self._p_jar.db()

    def _inVersion(self):
        return self._p_jar.getVersion() and True or False

    def cache_length(self):
        return self._getDB().cacheSize()

    def cache_detail_length(self):
        return self._getDB().cacheDetailSize()

    def database_size(self):
        return self._getDB().objectCount()

    def cache_age(self):
        if self._inVersion():
            return self._vcache_age
        else:
            return self._cache_age

    def manage_cache_age(self,value,REQUEST):
        "set cache age"
        db = self._getDB()
        if self._inVersion():
            self._vcache_age = value
            db.setVersionCacheDeactivateAfter(value)
        else:
            self._cache_age = value
            db.setCacheDeactivateAfter(value)

        if REQUEST is not None:
            response=REQUEST['RESPONSE']
            response.redirect(REQUEST['URL1']+'/manage_cacheParameters')

    def cache_size(self):
        db = self._getDB()
        if self._inVersion():
            return db.getVersionCacheSize()
        else:
            return db.getCacheSize()

    def manage_cache_size(self,value,REQUEST):
        "set cache size"
        db = self._getDB()
        if self._inVersion():
            db.setVersionCacheSize(value)
        else:
            db.setCacheSize(value)

        if REQUEST is not None:
            response=REQUEST['RESPONSE']
            response.redirect(REQUEST['URL1']+'/manage_cacheParameters')


    # BoboPOS 2
    def cache_mean_age(self):
        return Globals.Bobobase._jar.cache.cache_mean_age/60.0

    # BoboPOS 2
    def cache_mean_deal(self):
        return Globals.Bobobase._jar.cache.cache_mean_deal*60

    # BoboPOS 2
    def cache_mean_deac(self):
        return Globals.Bobobase._jar.cache.cache_mean_deac*60

    # BoboPOS 2
    def cache_last_gc_time(self):
        t=Globals.Bobobase._jar.cache.cache_last_gc_time
        return time.asctime(time.localtime(t))

    def manage_full_sweep(self,value,REQUEST):
        "Perform a full sweep through the cache"
        db = self._getDB()
        db.cacheFullSweep(value)

        if REQUEST is not None:
            response=REQUEST['RESPONSE']
            response.redirect(REQUEST['URL1']+'/manage_cacheGC')

    def manage_minimize(self,value=1,REQUEST=None):
        "Perform a full sweep through the cache"
        # XXX Add a deprecation warning about value?
        self._getDB().cacheMinimize()

        if REQUEST is not None:
            response=REQUEST['RESPONSE']
            response.redirect(REQUEST['URL1']+'/manage_cacheGC')

    def cache_detail(self, REQUEST=None):
        """
        Returns the name of the classes of the objects in the cache
        and the number of objects in the cache for each class.
        """
        detail = self._getDB().cacheDetail()
        if REQUEST is not None:
            # format as text
            REQUEST.RESPONSE.setHeader('Content-Type', 'text/plain')
            return '\n'.join(map(lambda (name, count): '%6d %s' %
                                   (count, name), detail))
        else:
            # raw
            return detail

    def cache_extreme_detail(self, REQUEST=None):
        """
        Returns information about each object in the cache.
        """
        detail = self._getDB().cacheExtremeDetail()
        if REQUEST is not None:
            # sort the list.
            lst = map(lambda dict: ((dict['conn_no'], dict['oid']), dict),
                      detail)
            # format as text.
            res = [
                '# Table shows connection number, oid, refcount, state, '
                'and class.',
                '# States: L = loaded, G = ghost, C = changed']
            for sortkey, dict in lst:
                id = dict.get('id', None)
                if id:
                    idinfo = ' (%s)' % id
                else:
                    idinfo = ''
                s = dict['state']
                if s == 0:
                    state = 'L'  # loaded
                elif s == 1:
                    state = 'C'  # changed
                else:
                    state = 'G'  # ghost
                res.append('%d %-34s %6d %s %s%s' % (
                    dict['conn_no'], `dict['oid']`, dict['rc'],
                    state, dict['klass'], idinfo))
            REQUEST.RESPONSE.setHeader('Content-Type', 'text/plain')
            return '\n'.join(res)
        else:
            # raw
            return detail

    def _getActivityMonitor(self):
        db = self._getDB()
        if not hasattr(db, 'getActivityMonitor'):
            return None
        am = db.getActivityMonitor()
        if am is None:
            return None
        return am

    def getHistoryLength(self):
        am = self._getActivityMonitor()
        if am is None:
            return 0
        return am.getHistoryLength()

    def manage_setHistoryLength(self, length, REQUEST=None):
        """Change the length of the activity monitor history.
        """
        am = self._getActivityMonitor()
        length = int(length)
        if length < 0:
            raise ValueError, 'length can not be negative'
        if am is not None:
            am.setHistoryLength(length)
        self._history_length = length  # Restore on startup

        if REQUEST is not None:
            response = REQUEST['RESPONSE']
            response.redirect(REQUEST['URL1'] + '/manage_activity')

    def getActivityChartData(self, segment_height, REQUEST=None):
        """Returns information for generating an activity chart.
        """
        am = self._getActivityMonitor()
        if am is None:
            return None

        if REQUEST is not None:
            start = float(REQUEST.get('chart_start', 0))
            end = float(REQUEST.get('chart_end', 0))
            divisions = int(REQUEST.get('chart_divisions', 10))
            analysis = am.getActivityAnalysis(start, end, divisions)
        else:
            analysis = am.getActivityAnalysis()

        total_load_count = 0
        total_store_count = 0
        total_connections = 0
        limit = 0
        divs = []
        for div in analysis:
            total_store_count = total_store_count + div['stores']
            total_load_count = total_load_count + div['loads']
            total_connections = total_connections + div['connections']
            sum = div['stores'] + div['loads']
            if sum > limit:
                limit = sum

        if analysis:
            segment_time = analysis[0]['end'] - analysis[0]['start']
        else:
            segment_time = 0

        for div in analysis:
            stores = div['stores']
            if stores > 0:
                store_len = max(int(segment_height * stores / limit), 1)
            else:
                store_len = 0
            loads = div['loads']
            if loads > 0:
                load_len = max(int(segment_height * loads / limit), 1)
            else:
                load_len = 0

            t = div['end'] - analysis[-1]['end']  # Show negative numbers.
            if segment_time >= 3600:
                # Show hours.
                time_offset = '%dh' % (t / 3600)
            elif segment_time >= 60:
                # Show minutes.
                time_offset = '%dm' % (t / 60)
            elif segment_time >= 1:
                # Show seconds.
                time_offset = '%ds' % t
            else:
                # Show fractions.
                time_offset = '%.2fs' % t
            divs.append({
                'store_len': store_len,
                'load_len': load_len,
                'trans_len': max(segment_height - store_len - load_len, 0),
                'store_count': div['stores'],
                'load_count': div['loads'],
                'connections': div['connections'],
                'start': div['start'],
                'end': div['end'],
                'time_offset': time_offset,
                })

        if analysis:
            start_time = DateTime(divs[0]['start']).aCommonZ()
            end_time = DateTime(divs[-1]['end']).aCommonZ()
        else:
            start_time = ''
            end_time = ''

        res = {'start_time': start_time,
               'end_time': end_time,
               'divs': divs,
               'total_store_count': total_store_count,
               'total_load_count': total_load_count,
               'total_connections': total_connections,
               }
        return res
예제 #5
0
파일: ZClass.py 프로젝트: bendavis78/zope
    if base_module[:9] == 'Products.':
        base_module = base_module.split('.')[1]
    else:
        base_module = base_module.split('.')[0]

    info = "%s: %s" % (base_module, base_name)

    Products.meta_class_info[key] = info  # meta_type
    Products.meta_classes[key] = Z

    return Z


from OFS.misc_ import p_

p_.ZClass_Icon = Globals.ImageFile('class.gif', globals())


class PersistentClass(Base, webdav.Collection.Collection):

    __metaclass__ = ZClasses._pmc.ZClassPersistentMetaClass

    # We need this class to be treated as a normal global class, even
    # though it is an instance of ZClassPersistentMetaClass.
    # Subclasses should be stored in the database.  See
    # _pmc._p_DataDescr.__get__.

    __global_persistent_class_not_stored_in_DB__ = True

    def __class_init__(self):
        pass
예제 #6
0
파일: __init__.py 프로젝트: bendavis78/zope
                  DeprecationWarning,
                  stacklevel=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')}

for icon in ('table', 'view', 'stable', 'what',
             'field', 'text','bin','int','float',
             'date','time','datetime'):
    misc_[icon]=Globals.ImageFile('icons/%s.gif' % icon, globals())

DA=None
def getDA():
    global DA
    if DA is None:
        home=Globals.package_home(globals())
        from gadfly import sqlwhere
        sqlwhere.filename="%s/gadfly/sql.mar" % home
        import DA
    return DA