source: products/quintagroup.canonicalpath/trunk/quintagroup/canonicalpath/upgrades.py @ 2370

Last change on this file since 2370 was 2370, checked in by mylan, 14 years ago

Fixed bugs, in converter, fix tests after renamed some convertor's methods

  • Property svn:eol-style set to native
File size: 4.4 KB
Line 
1import sys
2from types import StringTypes
3from logging import NOTSET, DEBUG, INFO, ERROR
4from logging import Logger, StreamHandler, Formatter
5from StringIO import StringIO
6from zope.component import getAdapter
7from Acquisition import aq_base, aq_inner
8
9from quintagroup.canonicalpath.interfaces  import ICanonicalPath
10from quintagroup.canonicalpath.interfaces  import ICanonicalLink
11from quintagroup.canonicalpath.adapters import PROPERTY_LINK
12from quintagroup.canonicalpath.adapters import PROPERTY_PATH
13from quintagroup.canonicalpath.adapters import DefaultPropertyAdapter
14
15class CanonicalConvertor(object):
16    """Convert canonical link to canonical path and vice versa."""
17
18    def __init__(self, portal_url):
19        """Create instanse of convertor.
20           - *portal_url* (string), add in the front of canonical path property
21             value for get canonical link.
22           - *logger_name* - name of the logger
23        """
24        self._initLogger()
25        self.portal_url = portal_url
26
27    def getLogs(self):
28        self._inout.flush()
29        return self._inout.getvalue()
30
31    def cleanupLogs(self):
32        self._inout = StringIO()
33
34    def convertILinkToPath(self, obj):
35        """Convert canonical link to canonical path"""
36        return self._convert(obj, ICanonicalLink, ICanonicalPath,
37                             self._convertL2P)
38
39    def convertIPathToLink(self, obj):
40        """Convert canonical path to canonical link"""
41        return self._convert(obj, ICanonicalPath, ICanonicalLink,
42                             self._convertP2L)
43
44    def convertPLinkToPath(self, obj, prop=PROPERTY_LINK):
45        """Convert canonical link, got from the *prop* parameter
46           to canonical path.
47        """
48        return self._convert(obj, prop, ICanonicalPath,
49                             self._convertL2P)
50
51    def convertPPathToLink(self, obj, prop=PROPERTY_PATH):
52        """Convert canonical path, got from the *prop* parameter
53           to canonical link.
54        """
55        return self._convert(obj, prop, ICanonicalLink,
56                             self._convertP2L)
57
58    def _convert(self, obj, src_iface, dst_iface, converter):
59        """Convert canonical from source canonical interface
60           to destination canonical interface.
61
62           Return True is successfull, False otherwise.
63           Log results in logger.
64        """
65        src_msg = type(src_iface) in StringTypes and src_iface or src_iface.__name__
66        msg = "Migrate %s into %s for %s object: " \
67               % (src_msg, dst_iface.__name__, obj.absolute_url())
68        try:
69            src = self._getOrMakeAdapter(obj, src_iface)
70            dst = getAdapter(obj, dst_iface)
71            # XXX: Check is this correct work XXX
72            obj = aq_base(aq_inner(obj))
73            # XXX
74            converter(src, dst)
75        except Exception:
76            import sys
77            et, em, etr = map(str, sys.exc_info())
78            lev = ERROR
79            msg += "ERROR: %s: %s" % (et, em)
80        else:
81            lev = INFO
82            msg += "SUCCESS"
83        self._logger.log(lev, msg)
84           
85        return lev == INFO and True or False
86   
87    def _getOrMakeAdapter(self, obj, arg):
88        """Function return adapter for process of the property.
89           Adapter get by interface (if arg is not a string - interface assumed)
90           OR if arg is string - adapter created from DefaultCanonicalAdapter.
91        """
92        if type(arg) in StringTypes:
93            adapter = DefaultPropertyAdapter(obj)
94            adapater.prop = arg
95            return adapter
96        else:
97            return getAdapter(obj, arg)
98
99    def _convertP2L(self, src, dst):
100        """Convert canonical path to canonical link."""
101        cpath = src.getProp()
102        cpath = cpath.startswith('/') and cpath or '/' + cpath
103        dst.canonical_link = self.portal_url + cpath
104        src.delProp()
105
106    def _convertL2P(self, src, dst):
107        """Convert canonical link to canonical path."""
108        raise NotImplementedError(
109            "Convertion from canonical link to canonical path not implemented")
110
111    def _initLogger(self):
112        self._inout = StringIO()
113        handler = StreamHandler(self._inout)
114        handler.setLevel(DEBUG)
115        formatter = Formatter(fmt="[%(asctime)s]: %(message)s",
116                                      datefmt="%H:%M:%S")
117        handler.setFormatter(formatter)
118        self._logger = Logger("quintagroup.canonicalpath", NOTSET)
119        self._logger.addHandler(handler)
120
Note: See TracBrowser for help on using the repository browser.