Ejemplo n.º 1
0
def fixupErrorLogging(reg_container, reg):
    # Fix up Error Reporting Service --> Utility 
    # We do this by simply removing old Error Reporting Services and their
    # registrations and then add a new error reporting utility.

    errors = reg.component
    # Set the registration to unregistered and then delete it
    reg.status = InactiveStatus
    del zapi.getParent(reg)[zapi.name(reg)]
    # Get the properties from the old error reporting service and
    # delete it
    props = errors.getProperties()
    folder = zapi.getParent(errors)
    del folder._SampleContainer__data[zapi.name(errors)]
    
    # Only add a new error reporting utility, if there is none.
    if 'ErrorReporting' not in folder:
        # Create the error reporting utility and set its properties
        utility = ErrorReportingUtility()
        utility.setProperties(**props)
        folder['ErrorReporting'] = utility
        # Register the utility and set the registration active
        reg = UtilityRegistration('', IErrorReportingUtility, utility)
        reg_manager = folder.registrationManager
        key = reg_manager.addRegistration(reg)
        reg_manager[key].status = ActiveStatus
    else:
        # If there is one, then at least move the data
        folder['ErrorReporting'].__dict__.update(props)
Ejemplo n.º 2
0
def fixupPrincipalAnnotation(reg_container, reg):
    # Fix up Principal Annotation Service --> Utility 
    ann = reg.component
    # Set the registration to inactive and then delete it
    reg.status = InactiveStatus
    del zapi.getParent(reg)[zapi.name(reg)]
    # Get the instance dictionary from the old principal
    # annotation service and then delete the service
    props = ann.__dict__
    name = zapi.name(ann)
    folder = zapi.getParent(ann)
    del folder._SampleContainer__data[name]
    
    # Only add a new principal annotation utility, if there is none.
    utils = [obj for obj in folder.values()
             if IPrincipalAnnotationUtility.providedBy(obj)]
    if len(utils) == 0:
        # Create the principal annotation utility and set its
        # properties
        utility = PrincipalAnnotationUtility()
        utility.__dict__.update(props)
        folder[name] = utility
        # Register the utility and set the registration active
        reg = UtilityRegistration('', IPrincipalAnnotationUtility,
                                  utility)
        reg_manager = folder.getRegistrationManager() 
        key = reg_manager.addRegistration(reg)
        reg_manager[key].status = ActiveStatus
    else:
        # If there is one, then at least move the data
        utils[0].__dict__.update(props)
Ejemplo n.º 3
0
 def traverse4nagiosGeneratorPre(self, fileDict, level=0, comments=True):
     """graphviz configuration preamble
     """
     tmp_interface = zapi.getParent(self.context)
     tmp_host = zapi.getParent(tmp_interface)
     if comments:
         print >> fileDict['ServiceCfg'], \
               "%s## Pre (%s,%d) - ServiceGenNagios" % \
               ("\t" * level, self.context.ikName, level)
     fileDict['ServiceCfg'].write( "define service {\n")
     fileDict['ServiceCfg'].write( "    use generic-ping\n")
     #fileDict['ServiceCfg'].write( "    host_name %s\n" % \
     #realHost.hostname)
     fileDict['ServiceCfg'].write( "    host_name %s\n" % tmp_host.objectID)
     #fileDict['ServiceCfg'].write( "    hostgroup_name ict_ok\n")
     #fileDict['ServiceCfg'].write( "    service_description %s-%s\n" % \
     #(realHost.ip, realService.description))
     ##if len(self.context.ikDesc) > 0:
         ##fileDict['ServiceCfg'].write( "    service_description %s\n" % \
                                       ##(self.context.ikDesc))
     ##else:
         ##fileDict['ServiceCfg'].write( "    service_description %s\n" % \
                                       ##(self.context.ikName))
     fileDict['ServiceCfg'].write( "    service_description %s\n" % \
                                   (self.context.getDcTitle()))
     fileDict['ServiceCfg'].write( "    contact_groups    admins\n")
     fileDict['ServiceCfg'].write( "    check_period    24x7\n")
     fileDict['ServiceCfg'].write( "    notification_interval    0\n")
     fileDict['ServiceCfg'].write( "    notification_options    w,u,c,r\n")
     fileDict['ServiceCfg'].write( "    notification_period    24x7\n")
     fileDict['ServiceCfg'].write( "    check_command    check_ssh!1!22\n")
     fileDict['ServiceCfg'].write( "    max_check_attempts    3\n")
     fileDict['ServiceCfg'].write( "    normal_check_interval    5\n")
     fileDict['ServiceCfg'].write( "    retry_check_interval    1\n")
     fileDict['ServiceCfg'].write( "}\n\n")
Ejemplo n.º 4
0
 def importAllXlsData(self, request, f_name, codepage):
     """set data from XLS file on new or modified folder objects"""
     sitemanger = zapi.getParent(self)
     locSitemanager = zapi.getParent(sitemanger)
     root_folder = zapi.getParent(locSitemanager)
     parseRet = xl.parse_xls(f_name, codepage)
     for sheet_name, values in parseRet:
         # dbg # print "sheet_name: ", sheet_name
         if sheet_name in root_folder:
             folder = root_folder[sheet_name]
             self._xlsSheet2folder_(request, values, folder)
Ejemplo n.º 5
0
 def create_indices(self):
     """
     will create all non existent indices in database
     """
     sitem = zapi.getSiteManager(self)
     site = zapi.getParent(sitem)
     tmpEvent = TmpEvent()
     if IZopeSite.providedBy(site) or \
         IIctSite.providedBy(site) or \
         zapi.getParent(site) is None:
         tmpEvent.object = site
         createLocalUtils(tmpEvent)
Ejemplo n.º 6
0
 def getMenuLink(self, node):
     """Return the HTML link of the node that is displayed in the menu."""
     obj = node.context
     if zapi.isinstance(obj, Directive):
         ns = zapi.getParent(obj)
         return './'+zapi.name(ns) + '/' + zapi.name(obj) + '/index.html'
     return None
Ejemplo n.º 7
0
    def getContextObjList(self, preList=None, postList=None):
        """
        get an Object list of all interesting objects in the context
        """
        retList = []
        if preList is not None:
            retList.extend(preList)
        retList.append((None, None, zapi.getParent(self.context)))
        if self.context.user != None:
            retList.append(('user', _(u'User'), self.context))
        if self.context.room != None:
            retList.append(('room', _(u'Room'), self.context))
        if len(self.context.links) > 0:
            retList.append(('links', _(u'Connected to'), self.context))
        if self.context.contracts != None and len(self.context.contracts) > 0:
            retList.append(('contracts', _(u'Contracts'), self.context))
        if self.context.requirements != None and len(
                self.context.requirements) > 0:
            retList.append(('requirements', _(u'Requirements'), self.context))
        if self.context.patchpanel != None:
            retList.append(('patchpanel', _(u'Patchpanel'), self.context))
        if postList is not None:
            retList.extend(postList)

        return retList
Ejemplo n.º 8
0
 def getContextObjList(self, preList=None, postList=None):
     """
     get an Object list of all interesting objects in the context
     """
     retList = []
     if preList is not None:
         retList.extend(preList)
     retList.append((None, None, zapi.getParent(self.context)))
     #retList.append(self.context.device)
     #retList.append(('__parent__', _(u'All IP Addresses'), self.context))
     if self.context.user is not None:
         retList.append(('user', _(u'User'), self.context))
     if self.context.room is not None:
         retList.append(('room', _(u'Room'), self.context))
     if self.context.device is not None:
         retList.append(('device', _(u'From Device'), self.context))
     if self.context.ipAddresses and len(self.context.ipAddresses) > 0:
         retList.append(('ipAddresses', _(u'IP Addresses'), self.context))
     if len(self.context.links) > 0:
         retList.append(('links', _(u'Connected to'), self.context))
     if self.context.contracts != None and len(self.context.contracts) > 0:
         retList.append(('contracts', _(u'Contracts'), self.context))
     if self.context.requirements != None and len(
             self.context.requirements) > 0:
         retList.append(('requirements', _(u'Requirements'), self.context))
     #print "===== %s" % retList
     #print "ddd3: ", self.context.device
     #retList.append(self.context.ipAddresses)
     if postList is not None:
         retList.extend(postList)
     return retList
Ejemplo n.º 9
0
    def getContextObjList(self, preList=None, postList=None):
        """
        get an Object list of all interesting objects in the context
        """
        retList = []
        if preList is not None:
            retList.extend(preList)
        retList.append((None, None, zapi.getParent(self.context)))
        if self.context.room is not None:
            retList.append(('room', _(u'Room'), self.context))
        if len(self.context.interfaces) > 0:
            retList.append(('interfaces', _(u'Interfaces'), self.context))
        if len(self.context.osoftwares) > 0:
            retList.append(
                ('osoftwares', _(u'Operating Software'), self.context))
        if len(self.context.appsoftwares) > 0:
            retList.append(
                ('appsoftwares', _(u'Application Software'), self.context))
        if len(self.context.logicalDevices) > 0:
            retList.append(
                ('logicalDevices', _(u'Logical Devices'), self.context))
        if len(self.context.physicalMedia) > 0:
            retList.append(
                ('physicalMedia', _(u'Physical Media'), self.context))
        if self.context.contracts != None and len(self.context.contracts) > 0:
            retList.append(('contracts', _(u'Contracts'), self.context))
        if self.context.requirements != None and len(
                self.context.requirements) > 0:
            retList.append(('requirements', _(u'Requirements'), self.context))
        if postList is not None:
            retList.extend(postList)

        return retList
Ejemplo n.º 10
0
 def nagiosConfigFileRemove(self):
     """remove old nagios configuration file for this object
     """
     host = zapi.getParent(self.context)
     nagiosAdapter = IGenNagios(host)
     if nagiosAdapter is not None:
         nagiosAdapter.nagiosConfigFileOut(True, None)
Ejemplo n.º 11
0
    def getContextObjList(self, preList=None, postList=None):
        """
        get an Object list of all interesting objects in the context
        """
        retList = []
        if preList is not None:
            retList.extend(preList)
        retList.append((None, None, zapi.getParent(self.context)))
        if self.context.mainWorkOrder != None:
            retList.append(
                ('mainWorkOrder', _(u'Main work order'), self.context))
        if len(self.context.contactItems) > 0:
            retList.append(('contactItems', _(u'Contact Items'), self.context))
        if len(self.context.products) > 0:
            retList.append(('products', _(u'Products'), self.context))
        if self.context.contracts != None and len(self.context.contracts) > 0:
            retList.append(('contracts', _(u'Contracts'), self.context))
        if self.context.requirements != None and len(
                self.context.requirements) > 0:
            retList.append(('requirements', _(u'Requirements'), self.context))
        if len(self.context.contactItems) > 0:
            retList.append(
                ('subWorkOrders', _(u'Sub work orders'), self.context))
        if postList is not None:
            retList.extend(postList)

        return retList
Ejemplo n.º 12
0
    def getMethods(self):
        # remove the security proxy, so that `attr` is not proxied. We could
        # unproxy `attr` for each turn, but that would be less efficient.
        #
        # `getPermissionIds()` also expects the class's security checker not
        # to be proxied.
        klass = zope.security.proxy.removeSecurityProxy(self.klassView.context)
        obj = zope.security.proxy.removeSecurityProxy(self.context)

        for name in apidoc.utilities.getPublicAttributes(obj):
            val = getattr(obj, name)
            if not (inspect.ismethod(val) or inspect.ismethoddescriptor(val)):
                continue
            if inspect.ismethod(val):
                signature = apidoc.utilities.getFunctionSignature(val)
            else:
                signature = '(...)'

            entry = {
                'name': name,
                'signature': signature,
                'doc': apidoc.utilities.renderText(
                     val.__doc__ or '',
                     zapi.getParent(self.klassView.context).getPath()),
                'interface': apidoc.utilities.getInterfaceForAttribute(
                     name, klass._Class__all_ifaces)}

            entry.update(apidoc.utilities.getPermissionIds(
                name, klass.getSecurityChecker()))

            yield entry
Ejemplo n.º 13
0
    def getContextObjList(self, preList=None, postList=None):
        """
        get an Object list of all interesting objects in the context
        """
        retList = []
        if preList is not None:
            retList.extend(preList)
        retList.append((None, None, zapi.getParent(self.context)))
        if self.context.contracts != None and len(self.context.contracts) > 0:
            retList.append(('contracts', _(u'Contracts'), self.context))
        if self.context.requirements != None and len(
                self.context.requirements) > 0:
            retList.append(('requirements', _(u'Requirements'), self.context))
        if self.context.contact is not None:
            retList.append(('contact', _(u'Contact'), self.context))
        if self.context.workOrder is not None:
            retList.append(('workOrder', _(u'Work Order'), self.context))
        if len(self.context.adresses) > 0:
            retList.append(('adresses', _(u'Adresses'), self.context))
        if len(self.context.groups) > 0:
            retList.append(('groups', _(u'Groups'), self.context))
        if len(self.context.roles) > 0:
            retList.append(('roles', _(u'Roles'), self.context))
        if len(self.context.closedContracts) > 0:
            retList.append(
                ('closedContracts', _(u'Closed Contracts'), self.context))
        if len(self.context.responsible4Contracts) > 0:
            retList.append(('responsible4Contracts',
                            _(u'Responsible for contracts'), self.context))
        if postList is not None:
            retList.extend(postList)

        return retList
Ejemplo n.º 14
0
 def __str__(self):
     if IContainmentRoot.providedBy(self.context):
         return ""
     name = self.context.__name__
     url = zapi.absoluteURL(zapi.getParent(self.context), self.request)
     url += "/" + name
     return url
Ejemplo n.º 15
0
    def getCollectionAttributes(self, obj_arg):
        additionalAttributes = ''
        if type(obj_arg) is tuple:
            (attributeName, displayTitle, obj) = obj_arg
            appendUrl = '?getAttr&attrName=%s' % attributeName
        else:
            appendUrl = ''
            obj = obj_arg

        parentItem = zapi.getParent(obj)
        parent_url = urlparse(zapi.absoluteURL(parentItem, self.request))
        obj_url = urlparse(zapi.absoluteURL(obj, self.request))
        if type(obj_arg) is tuple:
            xml_title = displayTitle
            additionalAttributes += ' expable="" '
            attrList = getattr(obj, attributeName, None)
            iklen = len(attrList)
        else:
            try:
                xml_title = obj.getDcTitle()
            except ForbiddenAttribute:
                xml_title = _('[top]')
            iklen = len(obj)
        name = obj_url.path.split('/')[-1] + appendUrl
        stateIconUrl = self.getStateIconUrl(obj)
        stateValue = self.getStateValue(obj)
        stateOverview = self.getStateOverview(obj)
        item_ppath = parent_url.path + u'/'
        item_ppath = item_ppath.replace('//', '/')
        if item_ppath[0] == "/":
            item_ppath = item_ppath[1:]
        return (xml_title, name, item_ppath, iklen, stateIconUrl, stateValue,
                stateOverview, additionalAttributes)
Ejemplo n.º 16
0
 def isInIctSite(self):
     """ this supervisor is under a ict site
     """
     sitem = zapi.getSiteManager(self)
     site = zapi.getParent(sitem)
     if IIctSite.providedBy(site):
         return True
     return False
Ejemplo n.º 17
0
 def exportAllXlsData(self, request):
     """get XLS file for all folder objects"""
     sitemanger = zapi.getParent(self)
     locSitemanager = zapi.getParent(sitemanger)
     root_folder = zapi.getParent(locSitemanager)
     filename = datetime.now().strftime('ict_all_%Y%m%d%H%M%S.xls')
     f_handle, f_name = tempfile.mkstemp(filename)
     wbook = Workbook()
     for folder in root_folder.values():
         print "folder: ", folder
         folder.exportXlsData(request, folder.ikName, wbook)
     wbook.save(f_name)
     datafile = open(f_name, "r")
     dataMem = datafile.read()
     datafile.close()
     os.remove(f_name)
     return (filename, dataMem)
Ejemplo n.º 18
0
 def getMenuLink(self, node):
     """Return the HTML link of the node that is displayed in the menu."""
     obj = node.context
     if zapi.isinstance(obj, Utility):
         iface = zapi.getParent(obj)
         return "./" + zapi.name(iface) + "/" + zapi.name(obj) + "/index.html"
     if zapi.isinstance(obj, UtilityInterface):
         return "../Interface/" + zapi.name(obj) + "/index.html"
     return None
Ejemplo n.º 19
0
 def delete(self):
     tool = self.activeTool
     regManager = self.context[tool.folder].registrationManager
     names = self.request.form['selected']
     for reg in regManager.values():
         if reg.provided.isOrExtends(tool.interface) and reg.name in names:
             component = reg.component
             reg.status = interfaces.registration.InactiveStatus
             del regManager[zapi.name(reg)]
             del zapi.getParent(component)[zapi.name(component)]
Ejemplo n.º 20
0
    def matches(self, obj):
        """Decide whether the object is shown in the tree."""
        if interfaces.IPreferenceCategory.providedBy(obj):
            return True

        if interfaces.IPreferenceGroup.providedBy(obj):
            parent = zapi.getParent(obj)
            if interfaces.IPreferenceCategory.providedBy(parent):
                return True

        return False
Ejemplo n.º 21
0
 def getContextObjList(self, preList=None, postList=None):
     """
     get an Object list of all interesting objects in the context
     """
     retList = []
     if preList is not None:
         retList.extend(preList)
     retList.append((None, None, zapi.getParent(self.context)))
     if postList is not None:
         retList.extend(postList)
     return retList
Ejemplo n.º 22
0
    def getContextHelpTopic(self):
        """Retrieve a help topic based on the context of the
        help namespace.

        If the context is a view, try to find
        a matching help topic for the view and its context.
        If no help topic is found, try to get a help topic for
        the context only.

        If the context is not a view, try to retrieve a help topic
        based on the context.

        If nothing is found, return the onlinehelp root topic
        """
        if self.topic is not None:
            return self.topic

        onlinehelp = self.context
        help_context = onlinehelp.context
        self.topic = None
        if IBrowserView.providedBy(help_context):
            # called from a view
            self.topic = getTopicFor(
                zapi.getParent(help_context),
                zapi.getName(help_context)
                )
            if self.topic is None:
                # nothing found for view try context only
                self.topic = getTopicFor(
                    zapi.getParent(help_context)
                    )
        else:
            # called without view
            self.topic = getTopicFor(help_context)

        if self.topic is None:
            self.topic = onlinehelp

        return self.topic
Ejemplo n.º 23
0
 def exportAllData(self):
     """get data file for all objects"""
     #dataStructure = {
         #'objects': ['a', 'b', 'c'],
         #'conns': [1, 2, 3],
         #}
     dataStructure = {
         'objects': [],
         'conns': [],
         }
     sitemanger = zapi.getParent(self)
     locSitemanager = zapi.getParent(sitemanger)
     root_folder = zapi.getParent(locSitemanager)
     for folder in root_folder.values():
         for obj in folder.values():
             obj.getAllExportData(dataStructure)
     print "*" * 80
     from pprint import pprint
     pprint(dataStructure)
     print "*" * 80
     python_pickle = pickle.dumps(dataStructure)
     return toxml(python_pickle)
Ejemplo n.º 24
0
 def traverse4nagiosGeneratorPre(self, level=0, comments=True):
     """graphviz configuration preamble
     """
     tmp_interface = zapi.getParent(self.context)
     tmp_host = zapi.getParent(tmp_interface)
     if comments:
         self.write(u"%s## Pre (%s,%d) - ServiceGenNagios" % \
                    ("\t" * level, self.context.ikName, level))
     self.write(u"define service {\n")
     self.write(u"    use generic-service\n")
     self.write(u"    host_name %s\n" % tmp_host.objectID)
     self.write(u"    service_description %s\n" % (self.context.objectID))
     self.write(u"    display_name %s\n" % (self.context.ikName))
     self.write(u"    contact_groups    admins\n")
     self.write(u"    check_period    24x7\n")
     self.write(u"    notification_interval    0\n")
     self.write(u"    notification_options    w,u,c,r\n")
     self.write(u"    notification_period    24x7\n")
     self.write(u"    check_command    check_dns_ict!5!denic.de\n")
     self.write(u"    max_check_attempts    3\n")
     self.write(u"    normal_check_interval    5\n")
     self.write(u"    retry_check_interval    1\n")
     self.write(u"}\n\n")
Ejemplo n.º 25
0
def _findNextSiteManager(site):
    while True:
        if IContainmentRoot.providedBy(site):
            # we're the root site, return None
            return None

        try:
            site = zapi.getParent(site)
        except TypeError:
            # there was not enough context; probably run from a test
            return None

        if interfaces.ISite.providedBy(site):
            return site.getSiteManager()
Ejemplo n.º 26
0
 def nagiosConfigFileOut(self, forceOutput=False, event=None):
     """Nagios-Filegenerator
     
     will produce the nagios configuration files
     
     forceOutput: False will check for a relevant attribute change
     True will alway generate a new config file
      
     event: None or the zope event from lifecycle
     """
     host = zapi.getParent(self.context)
     nagiosAdapter = IGenNagios(host)
     if nagiosAdapter is not None:
         nagiosAdapter.nagiosConfigFileOut(True, event)
Ejemplo n.º 27
0
 def traverse4smokepingGeneratorPre(self, level=0, comments=True):
     """graphviz configuration preamble
     """
     valueChanged = False
     try:
         iface = zapi.getParent(self.context)
         host = zapi.getParent(iface)
         ipList = host.getIpList()
     except TypeError:
         return
     if comments:
         self.write(u"%s## Pre (%s,%d) - HostGenSmokePing" % \
                    ("\t" * level, self.context.ikName, level))
     if self.wantsCheck():
         valueChanged = True
         self.write(u"++++ %s\n" % (self.context.objectID))
         self.write(u"menu = %s\n" % (self.context.ikName))
         self.write(u"title = %s\n" % (self.context.ikName))
         if ipList is not None and \
            len(ipList) > 0:
             self.write(u"host = %s\n" % (ipList[0]))
     else:
         self.write(u"# disabled by user\n")
     return valueChanged
Ejemplo n.º 28
0
    def getContextObjList(self, preList=None, postList=None):
        """
        get an Object list of all interesting objects in the context
        """
        retList = []
        if preList is not None:
            retList.extend(preList)
        retList.append((None, None, zapi.getParent(self.context)))
        if self.context.contracts != None and len(self.context.contracts) > 0:
            retList.append(('contracts', _(u'Contracts'), self.context))
        if self.context.requirements != None and len(
                self.context.requirements) > 0:
            retList.append(('requirements', _(u'Requirements'), self.context))
        if postList is not None:
            retList.extend(postList)

        return retList
Ejemplo n.º 29
0
 def removeObject(self, msgHeader, msgOldparent,
                  msgNewparent, msgObjectOid):
     """
     an object should be removed
     """
     print "removeObject"
     print "msgHeader: %s" % msgHeader
     print "msgOldparent: %s" % msgOldparent
     print "msgNewparent: %s" % msgNewparent
     print "msgObjectOid: %s" % msgObjectOid
     my_catalog = zapi.getUtility(ICatalog)
     for result in my_catalog.searchResults(oid_index=msgObjectOid):
         print "result: %s = %s" % (result.ikName, result)
         #del result
         objParent = zapi.getParent(result)
         print "objParent: %s" % objParent
         if objParent.has_key(msgObjectOid):
             objParent.__delitem__(msgObjectOid)
Ejemplo n.º 30
0
 def getContextObjList(self, preList=None, postList=None):
     """
     get an Object list of all interesting objects in the context
     """
     retList = []
     if preList is not None:
         retList.extend(preList)
     try:
         parentObj = zapi.getParent(self.context)
         if parentObj is not None and canAccess(parentObj, '__len__'):
             retList.append((None, None, parentObj))
     except Exception:
         print "111e"
         import traceback
         print traceback.format_exc()
     if postList is not None:
         retList.extend(postList)
     return retList
Ejemplo n.º 31
0
 def url(self):
     directive = removeSecurityProxy(self.context)
     subDirective = None
     # Sub-directives are not directly documented, so use parent
     parent = zapi.getParent(directive)
     if not (IRootDirective.providedBy(parent) or
             IRootDirective.providedBy(directive)):
         subDirective = directive
         directive = parent
     ns, name = directive.name
     # Sometimes ns is `None`, especially in the slug files, where no
     # namespaces are used.
     ns = quoteNS(ns or 'ALL')
     zcml = zapi.getUtility(IDocumentationModule, 'ZCML')
     if name not in zcml[ns]:
         ns = 'ALL'
     link = '%s/../ZCML/%s/%s/index.html' %(
         zapi.absoluteURL(findDocModule(self), self.request), ns, name)
     if subDirective:
         link += '#' + subDirective.name[1]
     return link
Ejemplo n.º 32
0
 def getContextObjList(self, preList=None, postList=None):
     """
     get an Object list of all interesting objects in the context
     """
     retList = []
     if preList is not None:
         retList.extend(preList)
     retList.append((None, None, zapi.getParent(self.context)))
     #retList.append(('__parent__', _(u'All IP Addresses'), self.context))
     #if len(self.context.user) > 0:
     ## (navView, viewTitle, contextObj)
     #retList.append(('user', _(u'User'), self.context))
     if len(self.context.logicalDevices) > 0:
         retList.append(
             ('logicalDevices', _(u'Logical Devices'), self.context))
     if len(self.context.physicalMedia) > 0:
         retList.append(
             ('physicalMedia', _(u'Physical Media'), self.context))
     if self.context.rack is not None:
         retList.append(('rack', _(u'Rack'), self.context))
     if self.context.room is not None:
         retList.append(('room', _(u'Room'), self.context))
     if len(self.context.interfaces) > 0:
         retList.append(('interfaces', _(u'Interfaces'), self.context))
     if len(self.context.osoftwares) > 0:
         # (navView, viewTitle, contextObj)
         retList.append(
             ('osoftwares', _(u'Operating software'), self.context))
     if len(self.context.appsoftwares) > 0:
         # (navView, viewTitle, contextObj)
         retList.append(
             ('appsoftwares', _(u'Application software'), self.context))
     if self.context.contracts != None and len(self.context.contracts) > 0:
         retList.append(('contracts', _(u'Contracts'), self.context))
     if self.context.requirements != None and len(
             self.context.requirements) > 0:
         retList.append(('requirements', _(u'Requirements'), self.context))
     if postList is not None:
         retList.extend(postList)
     return retList
Ejemplo n.º 33
0
    def getBreadCrumbs(self):
        """Create breadcrumbs for the module path.

        We cannot reuse the the system's bread crumbs, since they go all the
        way up to the root, but we just want to go to the root module."""
        names = self.context.getPath().split('.')
        crumbs = []
        module = self.context
        # I really need the class here, so remove the proxy.
        while removeSecurityProxy(module).__class__ is Module:
            crumbs.append(
                {'name': zapi.name(module),
                 'url': zapi.absoluteURL(module, self.request)}
                )
            module = zapi.getParent(module)

        crumbs.append(
            {'name': _('[top]'),
             'url': zapi.getMultiAdapter(
                      (module, self.request), name='absolute_url')()} )

        crumbs.reverse()
        return crumbs
Ejemplo n.º 34
0
def findAPIDocumentationRoot(obj, request):
    if zapi.isinstance(obj, APIDocumentation):
        return zapi.absoluteURL(obj, request)
    return findAPIDocumentationRoot(zapi.getParent(obj), request)
Ejemplo n.º 35
0
 def getParent(self):
     """
     returns parent object
     """
     return zapi.getParent(self)
Ejemplo n.º 36
0
    def generatePdf(self, absFilename, authorStr, versionStr, request=None):
        """
        will generate a object pdf report
        steps to do:
        - toReportSet = set([])
        - 1. select of objects (e.g. locations), append  toReportSet
        - 2. select of objects (e.g. buildings), append  toReportSet
        - 3. select of objects (e.g. rooms), append  toReportSet
        - generate Report (1st run, content)
        - generate Report (2nd run, references)
        """
        ##
        ##
        ## TODO:
        ##
        ## evil, very alpha, evaluation code for some kind of "Query Language"
        ## ... to be removed ...
        ##
        ##

        #-> from ZODB.interfaces import IConnection
        #-> connection = IConnection(self)
        #(Pdb)
        #> /Users/markus/Projekte/ict_ok.org/inst/lib/python/org/ict_ok/components/superclass/superclass.py(447)generatePdf()
        #-> from gocept.objectquery.collection import ObjectCollection
        #(Pdb) connection
        #<Connection at 01f19910>
        #(Pdb) dir(connection)
        #['_Connection__onCloseCallbacks', '__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__getitem__', '__hash__', '__implemented__', '__init__', '__module__', '__new__', '__providedBy__', '__provides__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', '_abort', '_abort_savepoint', '_added', '_added_during_commit', '_cache', '_cache_items', '_code_timestamp', '_commit', '_commit_savepoint', '_conflicts', '_creating', '_db', '_debug_info', '_flush_invalidations', '_handle_independent', '_handle_one_serial', '_handle_serial', '_implicitlyAdding', '_import', '_importDuringCommit', '_inv_lock', '_invalidate_creating', '_invalidated', '_invalidatedCache', '_load_before_or_conflict', '_load_count', '_log', '_modified', '_needs_to_join', '_normal_storage', '_opened', '_pre_cache', '_reader', '_register', '_registered_objects', '_resetCache', '_reset_counter', '_rollback', '_savepoint_storage', '_setstate', '_setstate_noncurrent', '_storage', '_storage_sync', '_store_count', '_store_objects', '_tpc_cleanup', '_txn_time', '_version', 'abort', 'add', 'afterCompletion', 'beforeCompletion', 'cacheGC', 'cacheMinimize', 'close', 'commit', 'connections', 'db', 'exchange', 'exportFile', 'get', 'getDebugInfo', 'getTransferCounts', 'getVersion', 'get_connection', 'importFile', 'invalidate', 'invalidateCache', 'isReadOnly', 'modifiedInVersion', 'newTransaction', 'new_oid', 'oldstate', 'onCloseCallback', 'open', 'register', 'root', 'savepoint', 'setDebugInfo', 'setstate', 'sortKey', 'sync', 'tpc_abort', 'tpc_begin', 'tpc_finish', 'tpc_vote', 'transaction_manager']
        #(Pdb) connection.transaction_manager
        #<transaction._manager.ThreadTransactionManager object at 0x1239bf0>
        #(Pdb) pp dir(connection.transaction_manager)
        #['__class__',
        # '__delattr__',
        # '__dict__',
        # '__doc__',
        # '__getattribute__',
        # '__hash__',
        # '__init__',
        # '__module__',
        # '__new__',
        # '__reduce__',
        # '__reduce_ex__',
        # '__repr__',
        # '__setattr__',
        # '__str__',
        # '__weakref__',
        # '_synchs',
        # '_txns',
        # 'abort',
        # 'begin',
        # 'commit',
        # 'doom',
        # 'free',
        # 'get',
        # 'isDoomed',
        # 'registerSynch',
        # 'savepoint',
        # 'unregisterSynch']
        #(Pdb) connection.transaction_manager.registerSynch(index_synch)
        #(Pdb) connection.root()['_oq_collection'] = oc
        #*** NameError: name 'oc' is not defined
        #(Pdb) l
        #442                  publ = request.publication
        #443                  import pdb
        #444                  pdb.set_trace()
        #445                  from ZODB.interfaces import IConnection
        #446                  connection = IConnection(self)
        #447  ->                from gocept.objectquery.collection import ObjectCollection
        #448                  from gocept.objectquery.pathexpressions import RPEQueryParser
        #449                  from gocept.objectquery.processor import QueryProcessor
        #450                  from zope.app import zapi
        #451                  parser = RPEQueryParser()
        #452                  oc = ObjectCollection(connection)
        #(Pdb) n
        #> /Users/markus/Projekte/ict_ok.org/inst/lib/python/org/ict_ok/components/superclass/superclass.py(448)generatePdf()
        #-> from gocept.objectquery.pathexpressions import RPEQueryParser
        #(Pdb)
        #> /Users/markus/Projekte/ict_ok.org/inst/lib/python/org/ict_ok/components/superclass/superclass.py(449)generatePdf()
        #-> from gocept.objectquery.processor import QueryProcessor
        #(Pdb)
        #> /Users/markus/Projekte/ict_ok.org/inst/lib/python/org/ict_ok/components/superclass/superclass.py(450)generatePdf()
        #-> from zope.app import zapi
        #(Pdb)
        #> /Users/markus/Projekte/ict_ok.org/inst/lib/python/org/ict_ok/components/superclass/superclass.py(451)generatePdf()
        #-> parser = RPEQueryParser()
        #(Pdb)
        #> /Users/markus/Projekte/ict_ok.org/inst/lib/python/org/ict_ok/components/superclass/superclass.py(452)generatePdf()
        #-> oc = ObjectCollection(connection)
        #(Pdb)
        #> /Users/markus/Projekte/ict_ok.org/inst/lib/python/org/ict_ok/components/superclass/superclass.py(453)generatePdf()
        #-> d1 = zapi.getParent(self)
        #(Pdb) connection.root()['_oq_collection'] = oc
        #(Pdb) connection.transaction_manager.commit()
        #(Pdb)

        from org.ict_ok.components.happliance.interfaces import IHardwareAppliance
        if IHardwareAppliance.providedBy(self):
            publ = request.publication
            from ZODB.interfaces import IConnection
            connection = IConnection(self)
            from gocept.objectquery.collection import ObjectCollection
            from gocept.objectquery.pathexpressions import RPEQueryParser
            from gocept.objectquery.processor import QueryProcessor
            from zope.app import zapi
            parser = RPEQueryParser()
            oc = ObjectCollection(connection)
            d1 = zapi.getParent(self)
            d2 = zapi.getParent(d1)
            d3 = zapi.getParent(d2)
            from pprint import pprint
            print "-" * 80
            print "class_index:"
            pprint(list(oc.class_index._index))
            #        print "attribute_index:"
            #        pprint(list(oc.attribute_index._index))
            #        print "structure_index:"
            #        pprint(list(oc.structure_index.paths))
            oc.index(connection.root())
            print "-" * 80
            print "class_index:"
            pprint(list(oc.class_index._index))
            print "attribute_index:"
            pprint(list(oc.attribute_index._index))
            print "structure_index:"
            pprint(list(oc.structure_index.paths))
            oc.index(d2)
            print "-" * 80
            print "class_index:"
            pprint(list(oc.class_index._index))
            print "attribute_index:"
            pprint(list(oc.attribute_index._index))
            print "structure_index:"
            pprint(list(oc.structure_index.paths))
            oc.index(d1)
            print "-" * 80
            print "class_index:"
            pprint(list(oc.class_index._index))
            print "attribute_index:"
            pprint(list(oc.attribute_index._index))
            print "structure_index:"
            pprint(list(oc.structure_index.paths))
            oc.index(self)
            print "-" * 80
            print "class_index:"
            pprint(list(oc.class_index._index))
            print "attribute_index:"
            pprint(list(oc.attribute_index._index))
            print "structure_index:"
            pprint(list(oc.structure_index.paths))
            print "-" * 80
            if0 = self.interfaces[0]
            oc.index(if0)
            oc3 = connection.root()['_oq_collection']
            query = QueryProcessor(parser, oc3)
            tt2 = oc3.is_child(self._p_oid, d1._p_oid)
            tt1 = oc3.is_child(d1._p_oid, d2._p_oid)
            tt3 = oc3.is_child(self._p_oid, if0._p_oid)
            tt4 = oc3.is_child(if0._p_oid, self._p_oid)
            ee = query('/Folder')
            ff = query('/Folder/HardwareApplianceFolder/HardwareAppliance')
            print "ff: ", ff
        files2delete = []
        document = RptDocument(absFilename)
        #document.setVolumeNo("1")
        document.setAuthorName(authorStr)
        document.setVersionStr(versionStr)
        adapterRptPdf = IRptPdf(self)
        if adapterRptPdf:
            adapterRptPdf.document = document
            adapterRptPdf.traverse4Rpt(1, True)
            files2delete.extend(adapterRptPdf.files2delete)
            del adapterRptPdf
        document.buildPdf()
        document.outConsoleTree(0)
        for i_filename in files2delete:
            try:
                os.remove(i_filename)
            except OSError:
                pass
Ejemplo n.º 37
0
    def singleBranchTree(self, root=''):
        """Return an XML document with the siblings and parents of an object.

        There is only one branch expanded, in other words, the tree is
        filled with the object, its siblings and its parents with
        their respective siblings.

        """
        result = ''
        oldItem = self.context
        try:
            oldItemOid = self.context.getObjectId()
        except:
            oldItemOid = "+++"

        vh = self.request.getVirtualHostRoot()
        if vh:
            print "vh: ", vh
            vhrootView = zapi.getMultiAdapter(
                    (vh, self.request), name='absolute_url')
            baseURL = vhrootView() + '/'
            try:
                rootName = '[' + vh.__name__ + ']'
            except:
                # we got the containment root itself as the virtual host
                # and there is no name.
                rootName = _('[top]')
            parents = getParentsFromContextToObject(self.context, vh)
        else:
            rootName = _('[top]')
            baseURL = self.request.getApplicationURL() + '/'
            parents = getParents(self.context)
        rootName = translate(rootName, context=self.request,
                             default=rootName)
        for item in parents:
            # skip skin if present
            if item == oldItem:
                continue
            if item is None:
                continue
            subItems = []
            if IReadContainer.providedBy(item):
                keys = list(item.keys())
            else:
                keys = []
            # include the site manager
            keys.append(u'++etc++site')
            for name in keys:
                # Only include items we can traverse to
                subItem = traverse(item, name, None)
                if subItem is None:
                    continue
                if name == u'++etc++site' and \
                   not checkPermission(\
                       'org.ict_ok.ikadmin_utils.usermanagement.Edit',
                       subItem):
                    continue
                iconUrl = self.getIconUrl(subItem)
                subitem_len = self.getLengthOf(subItem)
                dcAdapter = IGeneralDublinCore(subItem)
                xml_title = name
                if dcAdapter:
                    if dcAdapter.title:
                        xml_title = dcAdapter.title
                stateIconUrl = self.getStateIconUrl(subItem)
                if zapi.getParent(subItem):
                    item_ppath = zapi.canonicalPath(zapi.getParent(subItem)) \
                               + u'/'
                    item_ppath = item_ppath.replace('//', '/')
                else:
                    item_ppath = "/"
                try:
                    subItemOid = subItem.getObjectId()
                except:
                    subItemOid = "---"
                stateOverview = self.getStateOverview(item)
                if subitem_len > 0:
                    # the test below seems to be broken
                    # with the ++etc++site case
                    if subItem == oldItem:
                        if oldItemOid == subItemOid: # focussed
                            subItems.append(xmlEscapeWithCData(
                                u'<collection isfocus="" title=%s name=%s '
                                u'iklen=%s '
                                u'icon_url=%s expable="" state_url=%s '
                                u'path=%s state_val=%s>%s</collection>', 
                                xml_title, name, subitem_len, iconUrl,
                                stateIconUrl, item_ppath, stateOverview,
                                result))
                        else:
                            subItems.append(xmlEscapeWithCData(
                                u'<collection title=%s name=%s iklen=%s '
                                u'icon_url=%s state_url=%s path=%s '
                                u'state_val=%s>%s</collection>', 
                                xml_title, name, subitem_len, iconUrl,
                                stateIconUrl, item_ppath, stateOverview,
                                result))
                    else:
                        subItems.append(xmlEscape(
                            u'<collection title=%s name=%s iklen=%s '
                            u'icon_url=%s expable="" state_url=%s path=%s/>',
                            xml_title, name, subitem_len, iconUrl,
                            stateIconUrl, item_ppath))
                else:
                    if subItem == oldItem:
                        if oldItemOid == subItemOid: # focussed
                            subItems.append(xmlEscapeWithCData(
                                u'<collection isfocus="" title=%s '
                                u'name=%s iklen=%s '
                                u'icon_url=%s state_url=%s path=%s '
                                u'state_val=%s>%s</collection>', 
                                xml_title, name, subitem_len, iconUrl,
                                stateIconUrl, item_ppath, stateOverview,
                                result))
                        else:
                            subItems.append(xmlEscapeWithCData(
                                u'<collection title=%s name=%s iklen=%s '
                                u'icon_url=%s state_url=%s path=%s '
                                u'state_val=%s>%s</collection>', 
                                xml_title, name, subitem_len, iconUrl,
                                stateIconUrl, item_ppath, stateOverview,
                                result))
                    else:
                        subItems.append(xmlEscape(
                            u'<collection title=%s name=%s iklen=%s '
                            u'icon_url=%s state_url=%s path=%s/>',
                            xml_title, name, subitem_len, iconUrl,
                            stateIconUrl, item_ppath))

            result = u' '.join(subItems)
            oldItem = item

        # do not forget root folder
        iconUrl = self.getIconUrl(oldItem)
        xml_title = "ICT_Ok"
        rootName =  "."
        
        if len(result) > 0: # collection has content
            result = xmlEscapeWithCData(
                      u'<collection title=%s name=%s baseURL=%s iklen=%s '
                      u'icon_url=%s path=%s isroot="">%s</collection>',
                      xml_title, rootName, baseURL, len(oldItem), iconUrl,
                      "/", result)
        else:
            result = xmlEscapeWithCData(
                      u'<collection title=%s name=%s baseURL=%s iklen=%s '
                      u'icon_url=%s path=%s expable="" '
                      u'isroot="">%s</collection>',
                      xml_title, rootName, baseURL, len(oldItem), iconUrl,
                      "/", result)

        self.request.response.setHeader('Content-Type', 'text/xml')
        setNoCacheHeaders(self.request.response)
        title = translate(titleTemplate,
                          context=self.request, default=titleTemplate)
        loading = translate(loadingMsg,
                          context=self.request, default=loadingMsg)
        return xmlEscapeWithCData(
                u'<?xml version="1.0" encoding="ISO-8859-1"?>'
                u'<children title_tpl=%s title=%s '
                u'loading_msg=%s>%s</children>',
                title, title, loading, result)
Ejemplo n.º 38
0
    def children_utility(self, container):
        """Return an XML document that contains the children of an object."""
        result = []

        try:
            keys = [obj.objectID for \
                    obj in IContentList(container).getContentList()]
        except TypeError:
            keys = list(container.keys())

        # include the site manager
        keys.append(u'++etc++site')

        for name in keys:

            # Only include items we can traverse to
            item = traverse(container, name, None)
            if item is None:
                my_catalog = zapi.getUtility(ICatalog)
                res = my_catalog.searchResults(oid_index=name)
                if len(res) > 0:
                    item = iter(res).next()
                if item is None:
                    continue
            if name == u'++etc++site' and \
               not checkPermission(\
                   'org.ict_ok.ikadmin_utils.usermanagement.Edit', item):
                continue
            dcAdapter = IGeneralDublinCore(item)
            xml_title = name
            if dcAdapter:
                if dcAdapter.title:
                    xml_title = dcAdapter.title
            iconUrl = self.getIconUrl(item)
            stateIconUrl = self.getStateIconUrl(item)
            #stateValue = self.getStateValue(item)
            stateOverview = self.getStateOverview(item)
            item_len = self.getLengthOf(item)
            item_ppath = zapi.canonicalPath(zapi.getParent(item)) + u'/'
            item_ppath = item_ppath.replace('//', '/')
            if item_len > 0:
                if stateOverview:
                    result.append(xmlEscape(
                        u'<collection title=%s name=%s iklen=%s icon_url=%s ' +
                        u'state_url=%s path=%s expable="" state_val=%s/>',
                        xml_title, name, item_len, iconUrl, stateIconUrl,
                        item_ppath, stateOverview))
                else:
                    result.append(xmlEscape(
                        u'<collection title=%s name=%s iklen=%s icon_url=%s ' +
                        u'state_url=%s expable="" path=%s/>',
                        xml_title, name, item_len, iconUrl, stateIconUrl,
                        item_ppath))
            else:
                if stateOverview:
                    result.append(xmlEscape(
                        u'<collection title=%s name=%s iklen=%s icon_url=%s ' +
                        u'state_url=%s path=%s state_val=%s/>',
                        xml_title, name, item_len, iconUrl, stateIconUrl,
                        item_ppath, stateOverview))
                else:
                    result.append(xmlEscape(
                        u'<collection title=%s name=%s iklen=%s icon_url=%s ' +
                        u'state_url=%s path=%s/>',
                        xml_title, name, item_len, iconUrl, stateIconUrl,
                        item_ppath))

        return u' '.join(result)
Ejemplo n.º 39
0
 def getNamespaceName(self):
     """Return the name of the namespace."""
     name = zapi.getParent(self.context).getFullName()
     if name == 'ALL':
         return '<i>all namespaces</i>'
     return name
Ejemplo n.º 40
0
 def getDocString(self):
     """Get the doc string of the function in a rendered format."""
     return renderText(self.context.getDocString() or '',
                       zapi.getParent(self.context).getPath())
Ejemplo n.º 41
0
def createUtils(root_folder, connection=None, dummy_db=None):
    sitem = zapi.getSiteManager(root_folder)
    site = zapi.getParent(sitem)
    isInSite = IIctSite.providedBy(site)
    madeLdapAdapter = ensureUtility(\
        root_folder,
        IManageableLDAPAdapter,
        'ManageableLDAPAdapter',
        ManageableLDAPAdapter,
        name='ManageableLDAPAdapter',
        copy_to_zlog=False)

    madeLdapPas = ensureUtility(\
        root_folder,
        IMyLDAPAuthentication,
        'MyLDAPAuthentication',
        MyLDAPAuthentication,
        name='MyLDAPAuthentication',
        copy_to_zlog=False)

    if isinstance(madeLdapPas, MyLDAPAuthentication):
        madeLdapPas.adapterName = 'ManageableLDAPAdapter'
        madeLdapPas.principalIdPrefix = u'ldap.'

    madePluggableAuthentication = ensureUtility(\
        root_folder,
        IAdmUtilUserManagement,
        'AdmUtilUserManagement',
        AdmUtilUserManagement,
        name='',
        copy_to_zlog=False)

    if isinstance(madePluggableAuthentication, PluggableAuthentication):
        logger.info(u"bootstrap: Ensure named AdmUtilUserManagement")
        dcore = IWriteZopeDublinCore(madePluggableAuthentication)
        dcore.title = u"User Authentication"
        dcore.created = datetime.utcnow()
        madePluggableAuthentication.ikName = dcore.title
        # madePluggableAuthentication.__post_init__()
        sitem = root_folder.getSiteManager()
        utils = [
            util for util in sitem.registeredUtilities()
            if util.provided.isOrExtends(IAdmUtilSupervisor)
        ]
        instAdmUtilSupervisor = utils[0].component
        instAdmUtilSupervisor.appendEventHistory(\
            u" bootstrap: made AdmUtilUserManagement-Utility")
        if not isInSite:
            # only produce in real zope root folder not sites
            groups = GroupFolder(u'group.')
            madePluggableAuthentication[u'groups'] = groups
            principals = PrincipalFolder(u'principal.')
            madePluggableAuthentication[u'principals'] = principals
            madePluggableAuthentication.credentialsPlugins = \
                                       (u'Session Credentials',
                                        u'No Challenge if Authenticated',)
            p_user = InternalPrincipal(u'User',
                                       u'User',
                                       u'Initial User',
                                       passwordManagerName="SHA1")
            p_manager = InternalPrincipal(u'Manager',
                                          u'Manager',
                                          u'Initial Manager',
                                          passwordManagerName="SHA1")
            p_admin = InternalPrincipal(u'Administrator',
                                        u'Administrator',
                                        u'Initial Administrator',
                                        passwordManagerName="SHA1")
            p_developer = InternalPrincipal(u'Developer',
                                            u'Developer',
                                            u'Initial Developer',
                                            passwordManagerName="SHA1")
            principals[u'User'] = p_user
            principals[u'Manager'] = p_manager
            principals[u'Administrator'] = p_admin
            principals[u'Developer'] = p_developer
            grp_usr = GroupInformation(
                u'User', u'view & analyse data, generate reports '
                u'& leave notes at any object')
            grp_mgr = GroupInformation(
                u'Manager', u'search, connect, configure '
                u'& delete devices')
            grp_adm = GroupInformation(
                u'Administrator', u'install, configure '
                u'& administrate System')
            grp_dvl = GroupInformation(
                u'Developer', u'individual adaption '
                u'& development on System')
            grp_usr.principals = [u'principal.User']
            grp_mgr.principals = [u'principal.Manager']
            grp_adm.principals = [u'principal.Administrator']
            grp_dvl.principals = [u'principal.Developer']
            groups[u'User'] = grp_usr
            groups[u'Manager'] = grp_mgr
            groups[u'Administrator'] = grp_adm
            groups[u'Developer'] = grp_dvl
            madePluggableAuthentication[u'LDAPAuthentication'] = madeLdapPas
            madePluggableAuthentication.authenticatorPlugins = \
                (u'groups', u'principals', u'LDAPAuthentication', )
            prm = IPrincipalRoleManager(root_folder)
            prm.assignRoleToPrincipal(u'org.ict_ok.usr', u'group.User')
            prm.assignRoleToPrincipal(u'org.ict_ok.mgr', u'group.Manager')
            prm.assignRoleToPrincipal(u'org.ict_ok.adm',
                                      u'group.Administrator')
            prm.assignRoleToPrincipal(u'org.ict_ok.dvl', u'group.Developer')
        else:  # is in site
            madePluggableAuthentication.credentialsPlugins = \
                                       (u'Session Credentials',
                                        u'No Challenge if Authenticated',)
            madePluggableAuthentication[u'LDAPAuthentication'] = madeLdapPas
            madePluggableAuthentication.authenticatorPlugins = \
                (u'LDAPAuthentication', )

    transaction.get().commit()
    if connection is not None:
        connection.close()
Ejemplo n.º 42
0
def evolve(context):
    """Evolve the ZODB from a Zope X3.0 to a X3.1 compatible format.

    - The Principal Annotation Service was replaced by the Principal
      Annotation Utility. Thus all service registrations have to be changed to
      utility registrations. 

    - The Error Reporting Service was replaced by the Error Reporting
      Utility. Thus, all service registrations have to be changed to utility
      registrations. 

    - Component-based registrations used to keep track of their components via
      the component's path. Now it stores the component directly. All
      registrations are updated to this new format.

    - Converts all service registrations to utility registrations providing
      IService, which is the method used to simulate the old service API.

    - Remove 'RegistrationManager' object from all site management folders.

    - Remove all local adapter and utility service instances. 
    """
    root = getRootFolder(context)

    for site in findObjectsProviding(root, ISite):
        sm = site.getSiteManager()

        # Remove old registration manager instances
        for rm in findObjectsProviding(sm, IRegistrationManager):
            # Make sure that we called the new registration manager
            # which will retrieve the old one, if necessary
            zapi.getParent(rm).registrationManager = rm

            # Do a hard core delete, because I want no whining and complaining
            container = zapi.getParent(rm)
            del container._SampleContainer__data[zapi.getName(rm)]

            # Make sure the new registration manager has the correct name:
            rm.__name__ = '++registrations++'
            rm.__parent__ = container

        for reg_container in findObjectsProviding(sm, IRegisterableContainer):
            manager = reg_container.registrationManager

            # Iterate through each registration and fix it up.
            for reg in tuple(manager.values()):

                # Regardless of registration type, we want to convert the
                # component path to component  
                if ('_BBB_componentPath' in reg.__dict__ and
                    reg._BBB_componentPath is not None):

                    reg.component = reg.getComponent()
                    del reg.__dict__['_BBB_componentPath']

                # Fixup and convert service registrations
                if IServiceRegistration.providedBy(reg):
                    if reg.name == 'ErrorLogging':
                        fixupErrorLogging(reg_container, reg)

                    elif reg.name == 'PrincipalAnnotation':
                        fixupPrincipalAnnotation(reg_container, reg)

                    elif reg.name in ('Utilities', 'Adapters'):
                        # Delete the registration
                        reg.status = InactiveStatus
                        del manager[zapi.name(reg)]
                        # Delete the component
                        c = reg.component
                        del zapi.getParent(c)[zapi.name(c)]

                    else:
                        # Handle all outstanding service registrations
                        # Create a new utility registration
                        new_reg = UtilityRegistration(reg.name, IService,
                                                      reg.component)
                        manager.addRegistration(new_reg)
                        new_reg.status = ActiveStatus
                        # Delete the old registration
                        reg.status = InactiveStatus
                        del manager[zapi.getName(reg)]

                # Fixup utility registrations
                else:
                    # Getting the provided interface converts the utility
                    # registration automatically from 'interface' -> 'provided'
                    reg.provided
                    # Now let's reactivate the utility, so it will be
                    # available within the new framework
                    orig = reg.status
                    reg.status = InactiveStatus
                    reg.status = orig
Ejemplo n.º 43
0
    def children_utility(self, container):
        """Return an XML document that contains the children of an object."""
        result = []
        try:
            keys = [obj.objectID for \
                    obj in IContentList(container).getContentList()]
        except TypeError:
            keys = list(container.keys())

        # include the site manager
        keys.append(u'++etc++site')

        for name in keys:

            # Only include items we can traverse to
            item = traverse(container, name, None)
            if item is None:
                my_catalog = zapi.getUtility(ICatalog)
                res = my_catalog.searchResults(oid_index=name)
                if len(res) > 0:
                    item = iter(res).next()
                if item is None:
                    continue
            if name == u'++etc++site' and \
               not checkPermission(\
                   'org.ict_ok.ikadmin_utils.usermanagement.Edit', item):
                continue
            dcAdapter = IGeneralDublinCore(item)
            xml_title = name
            if dcAdapter:
                if dcAdapter.title:
                    xml_title = dcAdapter.title
            userManagement = queryUtility(IAdmUtilUserManagement)
            if userManagement is not None and\
                hasattr(item, 'shortName') and\
                userManagement.navExplanation is True:
                shortName = item.shortName
                item_cnt = len(item)
                if item_cnt > 0:
                    xml_title = u'%d ' % item_cnt \
                        + translate(xml_title,
                                    domain='org.ict_ok',
                                    context=self.request) \
                        + u' (%s)' % (shortName)
                else:
                    xml_title = translate(xml_title,
                                          domain='org.ict_ok',
                                          context=self.request) \
                        + u' (%s)' % (shortName)
            iconUrl = self.getIconUrl(item)
            stateIconUrl = self.getStateIconUrl(item)
            #stateValue = self.getStateValue(item)
            stateOverview = self.getStateOverview(item)
            try:
                item_len = len(IContentList(item).getContentList())
            except TypeError:
                item_len = self.getLengthOf(item)
#            item_ppath = zapi.canonicalPath(zapi.getParent(item)) + u'/'
            url = urlparse(zapi.absoluteURL(zapi.getParent(item),
                                            self.request))
            item_ppath = url.path + u'/'
            item_ppath = item_ppath.replace('//', '/')
            if item_len > 0:
                if stateOverview:
                    result.append(
                        xmlEscape(
                            u'<collection title=%s name=%s iklen=%s icon_url=%s rem="1.1.1" '
                            +
                            u'state_url=%s path=%s navparam="children1.xml" expable="" state_val=%s/>',
                            xml_title, name, item_len, iconUrl, stateIconUrl,
                            item_ppath, stateOverview))
                else:
                    result.append(
                        xmlEscape(
                            u'<collection title=%s name=%s iklen=%s icon_url=%s rem="1.1.2" '
                            +
                            u'state_url=%s navparam="children2.xml" expable="" path=%s/>',
                            xml_title, name, item_len, iconUrl, stateIconUrl,
                            item_ppath))
            else:
                if stateOverview:
                    result.append(
                        xmlEscape(
                            u'<collection title=%s name=%s iklen=%s icon_url=%s rem="1.2.1" '
                            +
                            u'state_url=%s navparam="children3.xml" path=%s state_val=%s/>',
                            xml_title, name, item_len, iconUrl, stateIconUrl,
                            item_ppath, stateOverview))
                else:
                    result.append(
                        xmlEscape(
                            u'<collection title=%s name=%s iklen=%s icon_url=%s rem="1.2.2" '
                            +
                            u'state_url=%s navparam="children4.xml" path=%s/>',
                            xml_title, name, item_len, iconUrl, stateIconUrl,
                            item_ppath))

        return u' '.join(result)
Ejemplo n.º 44
0
    def singleBranchTree3(self, root=''):
        result = ''
        oldItem = self.context
        xml_title = '11111'
        name = '22222'
        subitem_len = 0
        #oldItem = []
        iconUrl = ''
        stateIconUrl = ''
        item_ppath = ''
        stateOverview = ''
        rootName = '8888'
        baseURL = ''
        subItems = []
        #        subItems.append(xmlEscapeWithCData(
        #            u'<collection isfocused="" title=%s '
        #            u'name=%s iklen=%s rem="2.2.1.1" '
        #            u'icon_url=%s state_url=%s path=%s '
        #            u'state_val=%s>%s</collection>',
        #            xml_title, name, subitem_len, iconUrl,
        #            stateIconUrl, item_ppath, stateOverview,
        #            result))
        result = u' '.join(subItems)

        #        dcAdapter = IGeneralDublinCore(oldItem)
        xml_title = oldItem.getDcTitle()
        #        if dcAdapter:
        #            if dcAdapter.title:
        #                xml_title = dcAdapter.title
        iconUrl = self.getIconUrl(oldItem)
        url2 = urlparse(zapi.absoluteURL(oldItem, self.request))
        name = url2[2].split('/')[-1]
        parentItem = zapi.getParent(oldItem)
        #parentItem.keys()[parentItem.values().index(oldItem)]
        stateIconUrl = self.getStateIconUrl(oldItem)
        #stateValue = self.getStateValue(oldItem)
        stateOverview = self.getStateOverview(oldItem)
        try:
            item_len = len(IContentList(oldItem).getContentList())
        except TypeError:
            item_len = self.getLengthOf(oldItem)
#            item_ppath = zapi.canonicalPath(zapi.getParent(item)) + u'/'
        url = urlparse(zapi.absoluteURL(zapi.getParent(oldItem), self.request))
        item_ppath = url.path + u'/'
        item_ppath = item_ppath.replace('//', '/')

        if len(result) > 0:  # collection has content
            result = xmlEscapeWithCData(
                u'<collection title=%s name=%s iklen=%s rem="3.1" '
                u'icon_url=%s path=%s isopen="" isroot="">%s</collection>',
                xml_title, name, len(oldItem), iconUrl, item_ppath, result)
        else:
            result = xmlEscapeWithCData(
                u'<collection title=%s name=%s iklen=%s rem="3.2" '
                u'icon_url=%s path=%s expable="" '
                u'isroot="">%s</collection>', xml_title, name, len(oldItem),
                iconUrl, item_ppath, result)
        self.request.response.setHeader('Content-Type', 'text/xml')
        setNoCacheHeaders(self.request.response)
        title = translate(titleTemplate,
                          context=self.request,
                          default=titleTemplate)
        loading = translate(loadingMsg,
                            context=self.request,
                            default=loadingMsg)
        return xmlEscapeWithCData(
            u'<?xml version="1.0" encoding="ISO-8859-1"?>'
            u'<children title_tpl=%s title=%s '
            u'loading_msg=%s>%s</children>', title, title, loading, result)
Ejemplo n.º 45
0
 def parent(self):
     return zapi.getParent(self.context)
Ejemplo n.º 46
0
 def getDoc(self):
     """Get the doc string of the class STX formatted."""
     return renderText(self.context.getDocString() or '',
                       zapi.getParent(self.context).getPath())
Ejemplo n.º 47
0
 def getBaseURL(self):
     """Return the URL for the API Documentation Tool."""
     m = zapi.getUtility(IDocumentationModule, "Code")
     return zapi.absoluteURL(zapi.getParent(m), self.request)
Ejemplo n.º 48
0
def findDocModule(obj):
    if IDocumentationModule.providedBy(obj):
        return obj
    return findDocModule(zapi.getParent(obj))
Ejemplo n.º 49
0
 def registrations(self):
     rm = zapi.getParent(self.registerable).registrationManager
     return [reg for reg in rm.values()
             if (interfaces.IComponentRegistration.providedBy(reg) and
                 reg.component is self.registerable)]