Exemplo n.º 1
0
 def _movelist_done(self, data):
     move = generic.loads(data)
     if move.__len__() > 0:
         self.origin.move_list(move)
         reactor.callLater(20, self._get_list)
     else:
         self.origin.move_list(move) #empty request just for send all done stuff
         self.all_done = True
Exemplo n.º 2
0
 def _sched_init(self, data):
     #we are hired for a specific work
     activity = generic.loads(data)
     try:
         self.route = activity["route"]
         self.get_origin(activity["origin"])
         self.get_dest(activity["dest"])
         self.force_end = activity["endtime"]
         self._log.write("BASE SETTINGS", "GOT A WORK, %s, %s, %s"%(self.route, activity["origin"], activity["dest"]), "INFO")
         self.send_notify("BASE: Start synching route(%s)"%(self.route), "INFO"); 
     except Exception, e:
         self._log.write("BASE SETTINGS", type(e), "INFO")
         self._final_done_done("no activity in schedule")
Exemplo n.º 3
0
# built-in tests
from xml.marshal import generic, wddx

generic.runtests()
wddx.runtests()

# additional tests
try:
    from test.test_support import verify
except ImportError:
    from test.test_support import TestFailed
    def verify(condition, reason="test failed"):
        if not condition:
            raise TestFailed(reason)

# test for correct processing of ignorable whitespace
data = """<?xml version="1.0"?>
<marshal>
  <list id="i2">
    <int>1</int>
    <int>2</int>
  </list>
</marshal>"""

verify(generic.loads(data) == [1, 2])
Exemplo n.º 4
0
    def renderIncludes(self,
                       here,
                       text,
                       extra_context,
                       request,
                       sub_document=None):
        attached_files_dict = {}
        arguments_re = re.compile('''(\S+?)\s*=\s*('|")(.*?)\\2\s*''',
                                  re.DOTALL)

        def getLengthInfos(opts_dict, opts_names):
            ret = []
            for opt_name in opts_names:
                try:
                    val = opts_dict.pop(opt_name)
                    if val.endswith('cm'):
                        val = val[:-2]
                    val = float(val)
                except (ValueError, KeyError):
                    val = None
                ret.append(val)
            return ret

        def replaceIncludes(path):
            # Find the page template based on the path and remove path from dict
            document = self._resolvePath(path)
            document_text = ZopePageTemplate.pt_render(
                document, extra_context=extra_context)

            # Find the type of the embedded document
            document_type = document.content_type

            # Prepare a subdirectory to store embedded objects
            actual_idx = next(self.document_counter)
            dir_name = '%s%d' % (self._OLE_directory_prefix, actual_idx)

            if sub_document:  # sub-document means sub-directory
                dir_name = sub_document + '/' + dir_name

            # Get the stylesheet of the embedded openoffice document
            ooo_stylesheet = document.ooo_stylesheet
            if ooo_stylesheet:
                ooo_stylesheet = getattr(here, ooo_stylesheet)
                # If ooo_stylesheet is dynamic, call it
                try:
                    ooo_stylesheet = ooo_stylesheet()
                except AttributeError:
                    pass
                temp_builder = OOoBuilder(ooo_stylesheet)
                stylesheet = temp_builder.extract('styles.xml')
            else:
                stylesheet = None

            # Start recursion if necessary
            sub_attached_files_dict = {}
            if 'office:include' in document_text:  # small optimisation to avoid recursion if possible
                (document_text, sub_attached_files_dict) = self.renderIncludes(
                    document_text, dir_name, extra_context, request)

            # Attach content, style and settings if any
            attached_files_dict[dir_name] = dict(document=document_text,
                                                 doc_type=document_type,
                                                 stylesheet=stylesheet)

            attached_files_dict.update(sub_attached_files_dict)

            # Build the new tag
            new_path = './%s' % dir_name.split('/')[-1]
            return new_path

        def replaceIncludesImg(match):
            options_dict = {'text:anchor-type': 'paragraph'}
            options_dict.update(
                (x[0], x[2]) for x in arguments_re.findall(match.group(1)))
            for old_name, name, default in (('x', 'svg:x',
                                             '0cm'), ('y', 'svg:y', '0cm'),
                                            ('style', 'draw:style-name',
                                             'fr1')):
                options_dict.setdefault(name,
                                        options_dict.pop(old_name, default))

            picture = self._resolvePath(options_dict.pop('path').encode())

            # If this is not a File, build a new file with this content
            if not isinstance(picture, File):
                tmp_picture = self.newContent(temp_object=True,
                                              portal_type='Image',
                                              id='tmp')
                tmp_picture.setData(picture())
                picture = tmp_picture

            picture_type = options_dict.pop('type', None)

            picture_data = getattr(aq_base(picture), 'data', None)
            if picture_data is None:
                picture_data = picture.Base_download()
                if picture_type is None:
                    picture_type = picture.content_type()
            else:
                # "standard" filetype case (Image or File)
                picture_data = str(picture_data)
                if picture_type is None:
                    picture_type = picture.getContentType()

            w, h, maxwidth, maxheight = getLengthInfos(
                options_dict, ('width', 'height', 'maxwidth', 'maxheight'))

            aspect_ratio = 1
            try:  # try image properties
                aspect_ratio = float(picture.width) / float(picture.height)
            except (TypeError, ZeroDivisionError):
                try:  # try Image Document API
                    height = float(picture.getHeight())
                    if height:
                        aspect_ratio = float(picture.getWidth()) / height
                except AttributeError:  # fallback to Photo API
                    height = float(picture.height())
                    if height:
                        aspect_ratio = float(picture.width()) / height
            # fix a default value and correct the aspect
            if h is None:
                if w is None:
                    w = 10.0
                h = w / aspect_ratio
            elif w is None:
                w = h * aspect_ratio
            # picture is too large
            if maxwidth and maxwidth < w:
                w = maxwidth
                h = w / aspect_ratio
            if maxheight and maxheight < h:
                h = maxheight
                w = h * aspect_ratio

            actual_idx = next(self.document_counter)
            pic_name = 'Pictures/picture%d%s' \
                       % (actual_idx, guess_extension(picture_type) or '')

            # XXX: Pictures directory not managed (seems facultative)
            #  <manifest:file-entry manifest:media-type="" manifest:full-path="ObjBFE4F50D/Pictures/"/>
            is_legacy = 'oasis.opendocument' not in self.content_type
            replacement = (
                '<draw:frame %s>\n<draw:image %s/></draw:frame>',
                '<draw:image %s %s/>'
            )[is_legacy] % (
                '''draw:name="ERP5Image%d" svg:width="%.3fcm" svg:height="%.3fcm"%s'''
                % (actual_idx, w, h, ''.join(
                    ' %s="%s"' % opt for opt in six.iteritems(options_dict))),
                '''xlink:href="%s%s" xlink:type="simple"
           xlink:show="embed" xlink:actuate="onLoad"''' %
                (is_legacy and '#' or '', pic_name))

            if sub_document:  # sub-document means sub-directory
                pic_name = sub_document + '/' + pic_name

            attached_files_dict[pic_name] = dict(
                document=picture_data,
                doc_type=picture_type,
            )

            return replacement

        xml_doc = etree.XML(text)
        for office_include in xml_doc.xpath('//office:include',
                                            namespaces=xml_doc.nsmap):
            marshal_list = office_include.xpath('./marshal')
            if marshal_list:
                from xml.marshal.generic import loads
                arg_dict = loads(
                    etree.tostring(marshal_list[0],
                                   encoding='utf-8',
                                   xml_declaration=True,
                                   pretty_print=False))
                extra_context.update(arg_dict)
                request.other.update(arg_dict)
            path = office_include.attrib['path']
            del (office_include.attrib['path'])
            new_path = replaceIncludes(path)
            draw_object = Element('{%s}object' % xml_doc.nsmap.get('draw'))
            draw_object.attrib.update(
                {'{%s}href' % xml_doc.nsmap.get('xlink'): new_path})
            draw_object.attrib.update(dict(office_include.attrib))
            office_include.getparent().replace(office_include, draw_object)
        text = etree.tostring(xml_doc,
                              encoding='utf-8',
                              xml_declaration=True,
                              pretty_print=False)
        text = re.sub('<\s*office:include_img\s+(.*?)\s*/\s*>(?s)',
                      replaceIncludesImg, text)

        return (text, attached_files_dict)
Exemplo n.º 5
0
  def renderIncludes(self, here, text, extra_context, request, sub_document=None):
    attached_files_dict = {}
    arguments_re = re.compile('''(\S+?)\s*=\s*('|")(.*?)\\2\s*''',re.DOTALL)
    def getLengthInfos( opts_dict, opts_names ):
      ret = []
      for opt_name in opts_names:
        try:
          val = opts_dict.pop(opt_name)
          if val.endswith('cm'):
            val = val[:-2]
          val = float( val )
        except (ValueError, KeyError):
          val = None
        ret.append(val)
      return ret

    def replaceIncludes(path):
      # Find the page template based on the path and remove path from dict
      document = self._resolvePath(path)
      document_text = ZopePageTemplate.pt_render(document,
                                                 extra_context=extra_context)

      # Find the type of the embedded document
      document_type = document.content_type

      # Prepare a subdirectory to store embedded objects
      actual_idx = self.document_counter.next()
      dir_name = '%s%d'%(self._OLE_directory_prefix, actual_idx)

      if sub_document: # sub-document means sub-directory
        dir_name = sub_document + '/' + dir_name

      # Get the stylesheet of the embedded openoffice document
      ooo_stylesheet = document.ooo_stylesheet
      if ooo_stylesheet:
        ooo_stylesheet = getattr(here, ooo_stylesheet)
        # If ooo_stylesheet is dynamic, call it
        try:
          ooo_stylesheet = ooo_stylesheet()
        except AttributeError:
          pass
        temp_builder = OOoBuilder(ooo_stylesheet)
        stylesheet = temp_builder.extract('styles.xml')
      else:
        stylesheet = None

      # Start recursion if necessary
      sub_attached_files_dict = {}
      if 'office:include' in document_text: # small optimisation to avoid recursion if possible
        (document_text, sub_attached_files_dict ) = self.renderIncludes(document_text, dir_name, extra_context, request)

      # Attach content, style and settings if any
      attached_files_dict[dir_name] = dict(document=document_text,
                                           doc_type=document_type,
                                           stylesheet=stylesheet)

      attached_files_dict.update(sub_attached_files_dict)

      # Build the new tag
      new_path = './%s' % dir_name.split('/')[-1]
      return new_path

    def replaceIncludesImg(match):
      options_dict = { 'text:anchor-type': 'paragraph' }
      options_dict.update((x[0], x[2]) for x in arguments_re.findall(match.group(1)))
      for old_name, name, default in (('x', 'svg:x', '0cm'),
                                      ('y', 'svg:y', '0cm'),
                                      ('style', 'draw:style-name', 'fr1')):
        options_dict.setdefault(name, options_dict.pop(old_name, default))

      picture = self._resolvePath(options_dict.pop('path').encode())

      # If this is not a File, build a new file with this content
      if not isinstance(picture, File):
        tmp_picture = Products.ERP5Type.Document.newTempImage(self, 'tmp')
        tmp_picture.setData(picture())
        picture = tmp_picture

      picture_type = options_dict.pop('type', None)

      picture_data = getattr(aq_base(picture), 'data', None)
      if picture_data is None:
        picture_data = picture.Base_download()
        if picture_type is None:
          picture_type = picture.content_type()
      else:
        # "standard" filetype case (Image or File)
        picture_data = str(picture_data)
        if picture_type is None:
          picture_type = picture.getContentType()

      w, h, maxwidth, maxheight = getLengthInfos(options_dict,
                                  ('width', 'height', 'maxwidth', 'maxheight'))

      aspect_ratio = 1
      try: # try image properties
        aspect_ratio = float(picture.width) / float(picture.height)
      except (TypeError, ZeroDivisionError):
        try: # try ERP5.Document.Image API
          height = float(picture.getHeight())
          if height:
            aspect_ratio = float(picture.getWidth()) / height
        except AttributeError: # fallback to Photo API
          height = float(picture.height())
          if height:
            aspect_ratio = float(picture.width()) / height
      # fix a default value and correct the aspect
      if h is None:
        if w is None:
          w = 10.0
        h = w / aspect_ratio
      elif w is None:
        w = h * aspect_ratio
      # picture is too large
      if maxwidth and maxwidth < w:
        w = maxwidth
        h = w / aspect_ratio
      if maxheight and maxheight < h:
        h = maxheight
        w = h * aspect_ratio

      actual_idx = self.document_counter.next()
      pic_name = 'Pictures/picture%d%s' \
                 % (actual_idx, guess_extension(picture_type) or '')

      # XXX: Pictures directory not managed (seems facultative)
      #  <manifest:file-entry manifest:media-type="" manifest:full-path="ObjBFE4F50D/Pictures/"/>
      is_legacy = 'oasis.opendocument' not in self.content_type
      replacement = ('<draw:frame %s>\n<draw:image %s/></draw:frame>',
                     '<draw:image %s %s/>')[is_legacy] % (
        '''draw:name="ERP5Image%d" svg:width="%.3fcm" svg:height="%.3fcm"%s'''
        % (actual_idx, w, h,
           ''.join(' %s="%s"' % opt for opt in options_dict.iteritems())),
        '''xlink:href="%s%s" xlink:type="simple"
           xlink:show="embed" xlink:actuate="onLoad"'''
        % (is_legacy and '#' or '', pic_name))

      if sub_document: # sub-document means sub-directory
        pic_name = sub_document + '/' + pic_name

      attached_files_dict[pic_name] = dict(
        document=picture_data,
        doc_type=picture_type,
      )

      return replacement

    xml_doc = etree.XML(text)
    for office_include in xml_doc.xpath('//*[name() = "office:include"]'):
      marshal_list = office_include.xpath('./marshal')
      if marshal_list:
        from xml.marshal.generic import loads
        arg_dict = loads(etree.tostring(marshal_list[0], encoding='utf-8',
                                        xml_declaration=True, pretty_print=False))
        extra_context.update(arg_dict)
        request.other.update(arg_dict)
      path = office_include.attrib['path']
      del(office_include.attrib['path'])
      new_path = replaceIncludes(path)
      draw_object = Element('{%s}object' % xml_doc.nsmap.get('draw'))
      draw_object.attrib.update({'{%s}href' % xml_doc.nsmap.get('xlink'): new_path})
      draw_object.attrib.update(dict(office_include.attrib))
      office_include.getparent().replace(office_include, draw_object)
    text = etree.tostring(xml_doc, encoding='utf-8', xml_declaration=True,
                          pretty_print=False)
    text = re.sub('<\s*office:include_img\s+(.*?)\s*/\s*>(?s)', replaceIncludesImg, text)

    return (text, attached_files_dict)
Exemplo n.º 6
0
# built-in tests
from xml.marshal import generic, wddx

generic.runtests()
wddx.runtests()

# additional tests
try:
    from test.test_support import verify
except ImportError:
    from test.test_support import TestFailed

    def verify(condition, reason="test failed"):
        if not condition:
            raise TestFailed(reason)


# test for correct processing of ignorable whitespace
data = """<?xml version="1.0"?>
<marshal>
  <list id="i2">
    <int>1</int>
    <int>2</int>
  </list>
</marshal>"""

verify(generic.loads(data) == [1, 2])
Exemplo n.º 7
0
 def _dest_init(self, data):
     self.dest = destFactory().allocateDest(generic.loads(data))
Exemplo n.º 8
0
 def _origin_init(self, data):
     self.origin = originFactory().allocateOrigin(generic.loads(data))
     self._log.write("LAST SEEN", self.origin.last_seen, "INFO")
Exemplo n.º 9
0
 def _base_init(self, data):
     self.base_conf = generic.loads(data)
     if self.base_conf.has_key("LOG"):
         self._log = rboxLog(self.base_conf["LOG"])
         self.get_sched()