Package Products :: Package ZenModel :: Module DeviceReport |
[hide private]
[frames] | no frames]

# Source Code for Module Products.ZenModel.DeviceReport

      1  ##############################################################################
      2  #
      3  # Copyright (C) Zenoss, Inc. 2007, all rights reserved.
      4  #
      5  # This content is made available according to terms specified in
      6  # License.zenoss under the directory where your Zenoss product is installed.
      7  #
      8  ##############################################################################
      9
     10
     11  import cgi
     12  from Globals import InitializeClass
     13  from AccessControl import ClassSecurityInfo
     14  from Products.ZenMessaging.audit import audit
     15  from Products.ZenUtils.ZenTales import talesEval
     16  from Products.ZenUtils.Utils import convToUnits, zdecode, getDisplayType
     17  from Products.ZenWidgets import messaging
     18  from Products.ZenUtils.deprecated import deprecated
     19  from Products.ZenModel.BaseReport import BaseReport
     20
     21  @deprecated
     22 -def manage_addDeviceReport(context, id, title = None, REQUEST = None):
     23      """Add a DeviceReport
     24      """
     25      dc = DeviceReport(id, title)
     26      context._setObject(id, dc)
     27      if REQUEST is not None:
     28          audit('UI.Report.Add', dc.id, title=title, reportType=getDisplayType(dc), organizer=context)
     29          messaging.IMessageSender(context).sendToBrowser(
     30              'Report Created',
     31              'Device report %s was created.' % id
     32          )
     33          return REQUEST['RESPONSE'].redirect(context.absolute_url() + '/manage_main')
     34
     35
     36
     37 -class DeviceReport(BaseReport):
     38
     39      meta_type = "DeviceReport"
     40
     41      path = "/"
     42      deviceQuery = ""
     43      sortedHeader = ""
     44      sortedSence = "asc"
     45      groupby = ""
     46      columns = []
     47      colnames = []
     48
     49      _properties = BaseReport._properties + (
     50          {'id':'path', 'type':'string', 'mode':'w'},
     51          {'id':'deviceQuery', 'type':'string', 'mode':'w'},
     52          {'id':'sortedHeader', 'type':'string', 'mode':'w'},
     53          {'id':'sortedSence', 'type':'string', 'mode':'w'},
     54          {'id':'groupby', 'type':'string', 'mode':'w'},
     55          {'id':'columns', 'type':'lines', 'mode':'w'},
     56          {'id':'colnames', 'type':'lines', 'mode':'w'},
     57      )
     58
     59
     60      # Screen action bindings (and tab definitions)
     61      factory_type_information = (
     62          {
     63              'immediate_view' : '',
     64              'actions'        :
     65              (
     66                  {'name'          : 'View Report',
     67                  'action'        : '',
     68                  'permissions'   : ("View",),
     69                  },
     70                  {'name'          : 'Edit Report',
     71                  'action'        : 'editDeviceReport',
     72                  'permissions'   : ("Manage DMD",),
     73                  },
     74              )
     75           },
     76          )
     77
     78      security = ClassSecurityInfo()
     79
     80 -    def getBreadCrumbUrlPath(self):
     81          '''
     82          Return the url to be used in breadcrumbs for this object.
     83          '''
     84          return self.getPrimaryUrlPath() + '/editDeviceReport'
     85
     86
     87 -    def getDevices(self):
     88          """Return the device list for this report.
     89          """
     90          devs = self.getDmdRoot("Devices")
     91          if self.path != "/": devs = devs.getOrganizer(self.path)
     92          devlist = devs.getSubDevices()
     93          if self.deviceQuery:
     94              try:
     95                  return [ dev for dev in devlist \
     96                              if talesEval("python:"+self.deviceQuery, dev) ]
     97              except Exception, e:
     98                  return e
     99          return devlist
    100
    101
    102 -    def testQueryStyle(self):
    103          """Return red text style if query is bad.
    104          """
    105          try:
    106              self.getDevices()
    107          except:
    108              return "color:#FF0000"
    109
    110
    111 -    def testColNamesStyle(self):
    112          """Return red text style if columns and colnames not the same length.
    113          """
    114          if len(self.columns) != len(self.colnames): return "color:#FF0000"
    115
    116
    117 -    def reportHeader(self):
    118          h = []
    119          tname = self.getPrimaryId()
    120          for i, field in enumerate(self.columns):
    121              try:name = self.colnames[i]
    122              except IndexError: name = field
    123              h.append(self.ZenTableManager.getTableHeader(tname , field, name))
    124          return "\n".join(h)
    125
    126
    127 -    def reportHeaders(self):
    128          h = []
    129          for i, field in enumerate(self.columns):
    130              try:name = self.colnames[i]
    131              except IndexError: name = field
    132              h.append((field, name))
    133          return h
    134
    135
    136 -    def reportBody(self, batch):
    137          """body of this report create from a filtered and sorted batch.
    138          """
    139          body = []
    140          for dev in batch:
    141              # If the query is invalid, dev will be an exception string
    142              if isinstance(dev, basestring):
    143                  body.extend([
    144                      '<tr class="tablevalues">',
    145                      '  <td colspan="%d" align="center">' % len(self.columns),
    146                      '    Query error: %s' % dev,
    147                      '  </td>',
    148                      '</tr>',
    149                      ])
    150              else:
    151                  body.append("<tr class='tablevalues'>")
    152                  for field in self.columns:
    153                      body.append("<td>")
    154                      if field == "getId": field += "Link"
    155
    156                      # Allow the ability to parse Python
    157                      if dev.zenPropIsPassword(field):
    158                          attr = '*****'
    159                      else:
    160                          attr = getattr(dev, field, 'Unknown column')
    161                      variables_and_funcs = {
    162                         'device':dev, 'dev':dev, 'attr':attr,
    163                         'convToUnits':convToUnits, 'zdecode':zdecode,
    164                      }
    165                      if field.startswith('python:'):
    166                          expression = field.replace('python:', 'attr=')
    167                          try:
    168                              exec(expression, variables_and_funcs)
    169                              attr = variables_and_funcs['attr']
    170                          except Exception, ex:
    171                              attr = str(ex)
    172
    173                      if callable(attr):
    174                          try: value = attr()
    175                          except Exception, ex:
    176                               value = str(ex)
    177                      else: value = attr
    178
    179                      if isinstance(value, (list, tuple, set)):
    180                          # Some calls don't return strings
    181                          try: value = ", ".join(value)
    182                          except Exception, ex:
    183                               value = str(ex)
    184                      if (not field.endswith("Link")
    185                              and isinstance(value, basestring)):
    186                          value = cgi.escape(value)
    187                      elif isinstance(value, basestring):
    188                          value = str(value)
    189                      body.append(value)
    190                      body.append("</td>")
    191                  body.append("</tr>")
    192
    193          return "\n".join(body)
    194
    195
    196  InitializeClass(DeviceReport)
    197